1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Pathoschild.Http.Client;
namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki
{
/// <summary>An HTTP client for fetching mod metadata from the wiki compatibility list.</summary>
public class WikiCompatibilityClient : IDisposable
{
/*********
** Properties
*********/
/// <summary>The underlying HTTP client.</summary>
private readonly IClient Client;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="userAgent">The user agent for the wiki API.</param>
/// <param name="baseUrl">The base URL for the wiki API.</param>
public WikiCompatibilityClient(string userAgent, string baseUrl = "https://stardewvalleywiki.com/mediawiki/api.php")
{
this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
}
/// <summary>Fetch mod compatibility entries.</summary>
public async Task<WikiModEntry[]> FetchAsync()
{
// fetch HTML
ResponseModel response = await this.Client
.GetAsync("")
.WithArguments(new
{
action = "parse",
page = "Modding:SMAPI_compatibility",
format = "json"
})
.As<ResponseModel>();
string html = response.Parse.Text["*"];
// parse HTML
var doc = new HtmlDocument();
doc.LoadHtml(html);
// find mod entries
HtmlNodeCollection modNodes = doc.DocumentNode.SelectNodes("table[@id='mod-list']//tr[@class='mod']");
if (modNodes == null)
throw new InvalidOperationException("Can't parse wiki compatibility list, no mods found.");
// parse
return this.ParseEntries(modNodes).ToArray();
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
this.Client?.Dispose();
}
/*********
** Private methods
*********/
/// <summary>Parse valid mod compatibility entries.</summary>
/// <param name="nodes">The HTML compatibility entries.</param>
private IEnumerable<WikiModEntry> ParseEntries(IEnumerable<HtmlNode> nodes)
{
foreach (HtmlNode node in nodes)
{
// extract fields
string name = this.GetMetadataField(node, "mod-name");
string alternateNames = this.GetMetadataField(node, "mod-name2");
string author = this.GetMetadataField(node, "mod-author");
string alternateAuthors = this.GetMetadataField(node, "mod-author2");
string[] ids = this.GetMetadataField(node, "mod-id")?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray() ?? new string[0];
int? nexusID = this.GetNullableIntField(node, "mod-nexus-id");
int? chucklefishID = this.GetNullableIntField(node, "mod-chucklefish-id");
string githubRepo = this.GetMetadataField(node, "mod-github");
string customSourceUrl = this.GetMetadataField(node, "mod-custom-source");
string customUrl = this.GetMetadataField(node, "mod-url");
string brokeIn = this.GetMetadataField(node, "mod-broke-in");
string anchor = this.GetMetadataField(node, "mod-anchor");
// parse stable compatibility
WikiCompatibilityInfo compatibility = new WikiCompatibilityInfo
{
Status = this.GetStatusField(node, "mod-status") ?? WikiCompatibilityStatus.Ok,
UnofficialVersion = this.GetSemanticVersionField(node, "mod-unofficial-version"),
UnofficialUrl = this.GetMetadataField(node, "mod-unofficial-url"),
Summary = this.GetMetadataField(node, "mod-summary")?.Trim()
};
// parse beta compatibility
WikiCompatibilityInfo betaCompatibility = null;
{
WikiCompatibilityStatus? betaStatus = this.GetStatusField(node, "mod-beta-status");
if (betaStatus.HasValue)
{
betaCompatibility = new WikiCompatibilityInfo
{
Status = betaStatus.Value,
UnofficialVersion = this.GetSemanticVersionField(node, "mod-beta-unofficial-version"),
UnofficialUrl = this.GetMetadataField(node, "mod-beta-unofficial-url"),
Summary = this.GetMetadataField(node, "mod-beta-summary")
};
}
}
// yield model
yield return new WikiModEntry
{
ID = ids,
Name = name,
AlternateNames = alternateNames,
Author = author,
AlternateAuthors = alternateAuthors,
NexusID = nexusID,
ChucklefishID = chucklefishID,
GitHubRepo = githubRepo,
CustomSourceUrl = customSourceUrl,
CustomUrl = customUrl,
BrokeIn = brokeIn,
Compatibility = compatibility,
BetaCompatibility = betaCompatibility,
Anchor = anchor
};
}
}
/// <summary>Get the value of a metadata field.</summary>
/// <param name="container">The metadata container.</param>
/// <param name="name">The field name.</param>
private string GetMetadataField(HtmlNode container, string name)
{
return container.Descendants().FirstOrDefault(p => p.HasClass(name))?.InnerHtml;
}
/// <summary>Get the value of a metadata field as a compatibility status.</summary>
/// <param name="container">The metadata container.</param>
/// <param name="name">The field name.</param>
private WikiCompatibilityStatus? GetStatusField(HtmlNode container, string name)
{
string raw = this.GetMetadataField(container, name);
if (raw == null)
return null;
if (!Enum.TryParse(raw, true, out WikiCompatibilityStatus status))
throw new InvalidOperationException($"Unknown status '{raw}' when parsing compatibility list.");
return status;
}
/// <summary>Get the value of a metadata field as a semantic version.</summary>
/// <param name="container">The metadata container.</param>
/// <param name="name">The field name.</param>
private ISemanticVersion GetSemanticVersionField(HtmlNode container, string name)
{
string raw = this.GetMetadataField(container, name);
return SemanticVersion.TryParse(raw, out ISemanticVersion version)
? version
: null;
}
/// <summary>Get the value of a metadata field as a nullable integer.</summary>
/// <param name="container">The metadata container.</param>
/// <param name="name">The field name.</param>
private int? GetNullableIntField(HtmlNode container, string name)
{
string raw = this.GetMetadataField(container, name);
if (raw != null && int.TryParse(raw, out int value))
return value;
return null;
}
/// <summary>The response model for the MediaWiki parse API.</summary>
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Local")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
private class ResponseModel
{
/// <summary>The parse API results.</summary>
public ResponseParseModel Parse { get; set; }
}
/// <summary>The inner response model for the MediaWiki parse API.</summary>
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Local")]
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
private class ResponseParseModel
{
/// <summary>The parsed text.</summary>
public IDictionary<string, string> Text { get; set; }
}
}
}
|