diff options
author | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-12-26 00:31:36 -0500 |
---|---|---|
committer | Jesse Plamondon-Willard <github@jplamondonw.com> | 2017-12-26 00:31:36 -0500 |
commit | 15d4b6310e3dd15c62f3faedbf1290b2db26fb59 (patch) | |
tree | 47d49a9c69628f0df1e688361f46bc5b46b3c0fd /src/SMAPI.Web/Framework/Clients | |
parent | 5cc5f089b9645a60385ff293b5a7202f260bfc0f (diff) | |
parent | f19cc3aac1a781bf2f2d20bc9577c2fe929b1e96 (diff) | |
download | SMAPI-15d4b6310e3dd15c62f3faedbf1290b2db26fb59.tar.gz SMAPI-15d4b6310e3dd15c62f3faedbf1290b2db26fb59.tar.bz2 SMAPI-15d4b6310e3dd15c62f3faedbf1290b2db26fb59.zip |
Merge branch 'develop' into stable
Diffstat (limited to 'src/SMAPI.Web/Framework/Clients')
14 files changed, 517 insertions, 0 deletions
diff --git a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs new file mode 100644 index 00000000..6772672c --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs @@ -0,0 +1,83 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using HtmlAgilityPack; +using Pathoschild.Http.Client; + +namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish +{ + /// <summary>An HTTP client for fetching mod metadata from the Chucklefish mod site.</summary> + internal class ChucklefishClient : IChucklefishClient + { + /********* + ** Properties + *********/ + /// <summary>The base URL for the Chucklefish mod site.</summary> + private readonly string BaseUrl; + + /// <summary>The URL for a mod page excluding the base URL, where {0} is the mod ID.</summary> + private readonly string ModPageUrlFormat; + + /// <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 API client.</param> + /// <param name="baseUrl">The base URL for the Chucklefish mod site.</param> + /// <param name="modPageUrlFormat">The URL for a mod page excluding the <paramref name="baseUrl"/>, where {0} is the mod ID.</param> + public ChucklefishClient(string userAgent, string baseUrl, string modPageUrlFormat) + { + this.BaseUrl = baseUrl; + this.ModPageUrlFormat = modPageUrlFormat; + this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + } + + /// <summary>Get metadata about a mod.</summary> + /// <param name="id">The Chucklefish mod ID.</param> + /// <returns>Returns the mod info if found, else <c>null</c>.</returns> + public async Task<ChucklefishMod> GetModAsync(uint id) + { + // fetch HTML + string html; + try + { + html = await this.Client + .GetAsync(string.Format(this.ModPageUrlFormat, id)) + .AsString(); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + return null; + } + + // parse HTML + var doc = new HtmlDocument(); + doc.LoadHtml(html); + + // extract mod info + string url = new UriBuilder(new Uri(this.BaseUrl)) { Path = string.Format(this.ModPageUrlFormat, id) }.Uri.ToString(); + string name = doc.DocumentNode.SelectSingleNode("//meta[@name='twitter:title']").Attributes["content"].Value; + if (name.StartsWith("[SMAPI] ")) + name = name.Substring("[SMAPI] ".Length); + string version = doc.DocumentNode.SelectSingleNode("//h1/span").InnerText; + + // create model + return new ChucklefishMod + { + Name = name, + Version = version, + Url = url + }; + } + + /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> + public void Dispose() + { + this.Client?.Dispose(); + } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishMod.cs b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishMod.cs new file mode 100644 index 00000000..fd0101d4 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishMod.cs @@ -0,0 +1,18 @@ +namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish +{ + /// <summary>Mod metadata from the Chucklefish mod site.</summary> + internal class ChucklefishMod + { + /********* + ** Accessors + *********/ + /// <summary>The mod name.</summary> + public string Name { get; set; } + + /// <summary>The mod's semantic version number.</summary> + public string Version { get; set; } + + /// <summary>The mod's web URL.</summary> + public string Url { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Chucklefish/IChucklefishClient.cs b/src/SMAPI.Web/Framework/Clients/Chucklefish/IChucklefishClient.cs new file mode 100644 index 00000000..1d8b256e --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Chucklefish/IChucklefishClient.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading.Tasks; + +namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish +{ + /// <summary>An HTTP client for fetching mod metadata from the Chucklefish mod site.</summary> + internal interface IChucklefishClient : IDisposable + { + /********* + ** Methods + *********/ + /// <summary>Get metadata about a mod.</summary> + /// <param name="id">The Chucklefish mod ID.</param> + /// <returns>Returns the mod info if found, else <c>null</c>.</returns> + Task<ChucklefishMod> GetModAsync(uint id); + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs new file mode 100644 index 00000000..73ce4025 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs @@ -0,0 +1,20 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// <summary>A GitHub download attached to a release.</summary> + internal class GitAsset + { + /// <summary>The file name.</summary> + [JsonProperty("name")] + public string FileName { get; set; } + + /// <summary>The file content type.</summary> + [JsonProperty("content_type")] + public string ContentType { get; set; } + + /// <summary>The download URL.</summary> + [JsonProperty("browser_download_url")] + public string DownloadUrl { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs new file mode 100644 index 00000000..0b205660 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs @@ -0,0 +1,70 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Pathoschild.Http.Client; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// <summary>An HTTP client for fetching metadata from GitHub.</summary> + internal class GitHubClient : IGitHubClient + { + /********* + ** Properties + *********/ + /// <summary>The URL for a GitHub releases API query excluding the base URL, where {0} is the repository owner and name.</summary> + private readonly string ReleaseUrlFormat; + + /// <summary>The underlying HTTP client.</summary> + private readonly IClient Client; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="baseUrl">The base URL for the GitHub API.</param> + /// <param name="releaseUrlFormat">The URL for a GitHub releases API query excluding the <paramref name="baseUrl"/>, where {0} is the repository owner and name.</param> + /// <param name="userAgent">The user agent for the API client.</param> + /// <param name="acceptHeader">The Accept header value expected by the GitHub API.</param> + /// <param name="username">The username with which to authenticate to the GitHub API.</param> + /// <param name="password">The password with which to authenticate to the GitHub API.</param> + public GitHubClient(string baseUrl, string releaseUrlFormat, string userAgent, string acceptHeader, string username, string password) + { + this.ReleaseUrlFormat = releaseUrlFormat; + + this.Client = new FluentClient(baseUrl) + .SetUserAgent(userAgent) + .AddDefault(req => req.WithHeader("Accept", acceptHeader)); + if (!string.IsNullOrWhiteSpace(username)) + this.Client = this.Client.SetBasicAuthentication(username, password); + } + + /// <summary>Get the latest release for a GitHub repository.</summary> + /// <param name="repo">The repository key (like <c>Pathoschild/SMAPI</c>).</param> + /// <returns>Returns the latest release if found, else <c>null</c>.</returns> + public async Task<GitRelease> GetLatestReleaseAsync(string repo) + { + // validate key format + if (!repo.Contains("/") || repo.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) != repo.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase)) + throw new ArgumentException($"The value '{repo}' isn't a valid GitHub repository key, must be a username and project name like 'Pathoschild/SMAPI'.", nameof(repo)); + + // fetch info + try + { + return await this.Client + .GetAsync(string.Format(this.ReleaseUrlFormat, repo)) + .As<GitRelease>(); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + return null; + } + } + + /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> + public void Dispose() + { + this.Client?.Dispose(); + } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs new file mode 100644 index 00000000..b944088d --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs @@ -0,0 +1,25 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// <summary>A GitHub project release.</summary> + internal class GitRelease + { + /********* + ** Accessors + *********/ + /// <summary>The display name.</summary> + [JsonProperty("name")] + public string Name { get; set; } + + /// <summary>The semantic version string.</summary> + [JsonProperty("tag_name")] + public string Tag { get; set; } + + /// <summary>The Markdown description for the release.</summary> + public string Body { get; set; } + + /// <summary>The attached files.</summary> + public GitAsset[] Assets { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs b/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs new file mode 100644 index 00000000..6e8eadff --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading.Tasks; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// <summary>An HTTP client for fetching metadata from GitHub.</summary> + internal interface IGitHubClient : IDisposable + { + /********* + ** Methods + *********/ + /// <summary>Get the latest release for a GitHub repository.</summary> + /// <param name="repo">The repository key (like <c>Pathoschild/SMAPI</c>).</param> + /// <returns>Returns the latest release if found, else <c>null</c>.</returns> + Task<GitRelease> GetLatestReleaseAsync(string repo); + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/INexusClient.cs b/src/SMAPI.Web/Framework/Clients/Nexus/INexusClient.cs new file mode 100644 index 00000000..e56e7af4 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Nexus/INexusClient.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading.Tasks; + +namespace StardewModdingAPI.Web.Framework.Clients.Nexus +{ + /// <summary>An HTTP client for fetching mod metadata from Nexus Mods.</summary> + internal interface INexusClient : IDisposable + { + /********* + ** Methods + *********/ + /// <summary>Get metadata about a mod.</summary> + /// <param name="id">The Nexus mod ID.</param> + /// <returns>Returns the mod info if found, else <c>null</c>.</returns> + Task<NexusMod> GetModAsync(uint id); + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs new file mode 100644 index 00000000..1a7011e2 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs @@ -0,0 +1,48 @@ +using System.Threading.Tasks; +using Pathoschild.Http.Client; + +namespace StardewModdingAPI.Web.Framework.Clients.Nexus +{ + /// <summary>An HTTP client for fetching mod metadata from Nexus Mods.</summary> + internal class NexusClient : INexusClient + { + /********* + ** Properties + *********/ + /// <summary>The URL for a Nexus Mods API query excluding the base URL, where {0} is the mod ID.</summary> + private readonly string ModUrlFormat; + + /// <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 Nexus Mods API client.</param> + /// <param name="baseUrl">The base URL for the Nexus Mods API.</param> + /// <param name="modUrlFormat">The URL for a Nexus Mods API query excluding the <paramref name="baseUrl"/>, where {0} is the mod ID.</param> + public NexusClient(string userAgent, string baseUrl, string modUrlFormat) + { + this.ModUrlFormat = modUrlFormat; + this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + } + + /// <summary>Get metadata about a mod.</summary> + /// <param name="id">The Nexus mod ID.</param> + /// <returns>Returns the mod info if found, else <c>null</c>.</returns> + public async Task<NexusMod> GetModAsync(uint id) + { + return await this.Client + .GetAsync(string.Format(this.ModUrlFormat, id)) + .As<NexusMod>(); + } + + /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> + public void Dispose() + { + this.Client?.Dispose(); + } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/NexusMod.cs b/src/SMAPI.Web/Framework/Clients/Nexus/NexusMod.cs new file mode 100644 index 00000000..2b04104f --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Nexus/NexusMod.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.Nexus +{ + /// <summary>Mod metadata from Nexus Mods.</summary> + internal class NexusMod + { + /********* + ** Accessors + *********/ + /// <summary>The mod name.</summary> + public string Name { get; set; } + + /// <summary>The mod's semantic version number.</summary> + public string Version { get; set; } + + /// <summary>The mod's web URL.</summary> + [JsonProperty("mod_page_uri")] + public string Url { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Pastebin/IPastebinClient.cs b/src/SMAPI.Web/Framework/Clients/Pastebin/IPastebinClient.cs new file mode 100644 index 00000000..630dfb76 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Pastebin/IPastebinClient.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading.Tasks; + +namespace StardewModdingAPI.Web.Framework.Clients.Pastebin +{ + /// <summary>An API client for Pastebin.</summary> + internal interface IPastebinClient : IDisposable + { + /// <summary>Fetch a saved paste.</summary> + /// <param name="id">The paste ID.</param> + Task<PasteInfo> GetAsync(string id); + + /// <summary>Save a paste to Pastebin.</summary> + /// <param name="content">The paste content.</param> + Task<SavePasteResult> PostAsync(string content); + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs b/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs new file mode 100644 index 00000000..955156eb --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs @@ -0,0 +1,15 @@ +namespace StardewModdingAPI.Web.Framework.Clients.Pastebin +{ + /// <summary>The response for a get-paste request.</summary> + internal class PasteInfo + { + /// <summary>Whether the log was successfully fetched.</summary> + public bool Success { get; set; } + + /// <summary>The fetched paste content (if <see cref="Success"/> is <c>true</c>).</summary> + public string Content { get; set; } + + /// <summary>The error message (if saving failed).</summary> + public string Error { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs b/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs new file mode 100644 index 00000000..ef83a91e --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using System.Web; +using Pathoschild.Http.Client; + +namespace StardewModdingAPI.Web.Framework.Clients.Pastebin +{ + /// <summary>An API client for Pastebin.</summary> + internal class PastebinClient : IPastebinClient + { + /********* + ** Properties + *********/ + /// <summary>The underlying HTTP client.</summary> + private readonly IClient Client; + + /// <summary>The user key used to authenticate with the Pastebin API.</summary> + private readonly string UserKey; + + /// <summary>The developer key used to authenticate with the Pastebin API.</summary> + private readonly string DevKey; + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="baseUrl">The base URL for the Pastebin API.</param> + /// <param name="userAgent">The user agent for the API client.</param> + /// <param name="userKey">The user key used to authenticate with the Pastebin API.</param> + /// <param name="devKey">The developer key used to authenticate with the Pastebin API.</param> + public PastebinClient(string baseUrl, string userAgent, string userKey, string devKey) + { + this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + this.UserKey = userKey; + this.DevKey = devKey; + } + + /// <summary>Fetch a saved paste.</summary> + /// <param name="id">The paste ID.</param> + public async Task<PasteInfo> GetAsync(string id) + { + try + { + // get from API + string content = await this.Client + .GetAsync($"raw/{id}") + .AsString(); + + // handle Pastebin errors + if (string.IsNullOrWhiteSpace(content)) + return new PasteInfo { Error = "Received an empty response from Pastebin." }; + if (content.StartsWith("<!DOCTYPE")) + return new PasteInfo { Error = $"Received a captcha challenge from Pastebin. Please visit https://pastebin.com/{id} in a new window to solve it." }; + return new PasteInfo { Success = true, Content = content }; + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + return new PasteInfo { Error = "There's no log with that ID." }; + } + catch (Exception ex) + { + return new PasteInfo { Error = ex.ToString() }; + } + } + + /// <summary>Save a paste to Pastebin.</summary> + /// <param name="content">The paste content.</param> + public async Task<SavePasteResult> PostAsync(string content) + { + try + { + // validate + if (string.IsNullOrWhiteSpace(content)) + return new SavePasteResult { Error = "The log content can't be empty." }; + + // post to API + string response = await this.Client + .PostAsync("api/api_post.php") + .WithBodyContent(this.GetFormUrlEncodedContent(new Dictionary<string, string> + { + ["api_option"] = "paste", + ["api_user_key"] = this.UserKey, + ["api_dev_key"] = this.DevKey, + ["api_paste_private"] = "1", // unlisted + ["api_paste_name"] = $"SMAPI log {DateTime.UtcNow:s}", + ["api_paste_expire_date"] = "N", // never expire + ["api_paste_code"] = content + })) + .AsString(); + + // handle Pastebin errors + if (string.IsNullOrWhiteSpace(response)) + return new SavePasteResult { Error = "Received an empty response from Pastebin." }; + if (response.StartsWith("Bad API request")) + return new SavePasteResult { Error = response }; + if (!response.Contains("/")) + return new SavePasteResult { Error = $"Received an unknown response: {response}" }; + + // return paste ID + string pastebinID = response.Split("/").Last(); + return new SavePasteResult { Success = true, ID = pastebinID }; + } + catch (Exception ex) + { + return new SavePasteResult { Success = false, Error = ex.ToString() }; + } + } + + /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> + public void Dispose() + { + this.Client.Dispose(); + } + + + /********* + ** Private methods + *********/ + /// <summary>Build an HTTP content body with form-url-encoded content.</summary> + /// <param name="data">The content to encode.</param> + /// <remarks>This bypasses an issue where <see cref="FormUrlEncodedContent"/> restricts the body length to the maximum size of a URL, which isn't applicable here.</remarks> + private HttpContent GetFormUrlEncodedContent(IDictionary<string, string> data) + { + string body = string.Join("&", from arg in data select $"{HttpUtility.UrlEncode(arg.Key)}={HttpUtility.UrlEncode(arg.Value)}"); + return new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"); + } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/Pastebin/SavePasteResult.cs b/src/SMAPI.Web/Framework/Clients/Pastebin/SavePasteResult.cs new file mode 100644 index 00000000..89dab697 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/Pastebin/SavePasteResult.cs @@ -0,0 +1,15 @@ +namespace StardewModdingAPI.Web.Framework.Clients.Pastebin +{ + /// <summary>The response for a save-log request.</summary> + internal class SavePasteResult + { + /// <summary>Whether the log was successfully saved.</summary> + public bool Success { get; set; } + + /// <summary>The saved paste ID (if <see cref="Success"/> is <c>true</c>).</summary> + public string ID { get; set; } + + /// <summary>The error message (if saving failed).</summary> + public string Error { get; set; } + } +} |