From 05541c11a72735d79d98cf3ae14d592e70bd8f54 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 24 Dec 2017 23:28:07 -0500 Subject: decouple API clients from mods API (#411) --- .../Clients/Chucklefish/ChucklefishClient.cs | 83 ++++++++++++++++++++++ .../Clients/Chucklefish/ChucklefishMod.cs | 18 +++++ .../Clients/Chucklefish/IChucklefishClient.cs | 17 +++++ .../Framework/Clients/GitHub/GitHubClient.cs | 70 ++++++++++++++++++ .../Framework/Clients/GitHub/GitRelease.cs | 19 +++++ .../Framework/Clients/GitHub/IGitHubClient.cs | 17 +++++ .../Framework/Clients/Nexus/INexusClient.cs | 17 +++++ .../Framework/Clients/Nexus/NexusClient.cs | 48 +++++++++++++ src/SMAPI.Web/Framework/Clients/Nexus/NexusMod.cs | 21 ++++++ 9 files changed, 310 insertions(+) create mode 100644 src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishMod.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Chucklefish/IChucklefishClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/GitHub/GitHubClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs create mode 100644 src/SMAPI.Web/Framework/Clients/GitHub/IGitHubClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Nexus/INexusClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Nexus/NexusMod.cs (limited to 'src/SMAPI.Web/Framework/Clients') 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 +{ + /// An HTTP client for fetching mod metadata from the Chucklefish mod site. + internal class ChucklefishClient : IChucklefishClient + { + /********* + ** Properties + *********/ + /// The base URL for the Chucklefish mod site. + private readonly string BaseUrl; + + /// The URL for a mod page excluding the base URL, where {0} is the mod ID. + private readonly string ModPageUrlFormat; + + /// The underlying HTTP client. + private readonly IClient Client; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The user agent for the API client. + /// The base URL for the Chucklefish mod site. + /// The URL for a mod page excluding the , where {0} is the mod ID. + public ChucklefishClient(string userAgent, string baseUrl, string modPageUrlFormat) + { + this.BaseUrl = baseUrl; + this.ModPageUrlFormat = modPageUrlFormat; + this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + } + + /// Get metadata about a mod. + /// The Chucklefish mod ID. + /// Returns the mod info if found, else null. + public async Task 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 + }; + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + 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 +{ + /// Mod metadata from the Chucklefish mod site. + internal class ChucklefishMod + { + /********* + ** Accessors + *********/ + /// The mod name. + public string Name { get; set; } + + /// The mod's semantic version number. + public string Version { get; set; } + + /// The mod's web URL. + 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 +{ + /// An HTTP client for fetching mod metadata from the Chucklefish mod site. + internal interface IChucklefishClient : IDisposable + { + /********* + ** Methods + *********/ + /// Get metadata about a mod. + /// The Chucklefish mod ID. + /// Returns the mod info if found, else null. + Task GetModAsync(uint id); + } +} 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 +{ + /// An HTTP client for fetching metadata from GitHub. + internal class GitHubClient : IGitHubClient + { + /********* + ** Properties + *********/ + /// The URL for a GitHub releases API query excluding the base URL, where {0} is the repository owner and name. + private readonly string ReleaseUrlFormat; + + /// The underlying HTTP client. + private readonly IClient Client; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The base URL for the GitHub API. + /// The URL for a GitHub releases API query excluding the , where {0} is the repository owner and name. + /// The user agent for the API client. + /// The Accept header value expected by the GitHub API. + /// The username with which to authenticate to the GitHub API. + /// The password with which to authenticate to the GitHub API. + 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); + } + + /// Get the latest release for a GitHub repository. + /// The repository key (like Pathoschild/SMAPI). + /// Returns the latest release if found, else null. + public async Task 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(); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + return null; + } + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + 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..0a47f3b4 --- /dev/null +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs @@ -0,0 +1,19 @@ +using Newtonsoft.Json; + +namespace StardewModdingAPI.Web.Framework.Clients.GitHub +{ + /// A GitHub project release. + internal class GitRelease + { + /********* + ** Accessors + *********/ + /// The display name. + [JsonProperty("name")] + public string Name { get; set; } + + /// The semantic version string. + [JsonProperty("tag_name")] + public string Tag { 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 +{ + /// An HTTP client for fetching metadata from GitHub. + internal interface IGitHubClient : IDisposable + { + /********* + ** Methods + *********/ + /// Get the latest release for a GitHub repository. + /// The repository key (like Pathoschild/SMAPI). + /// Returns the latest release if found, else null. + Task 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 +{ + /// An HTTP client for fetching mod metadata from Nexus Mods. + internal interface INexusClient : IDisposable + { + /********* + ** Methods + *********/ + /// Get metadata about a mod. + /// The Nexus mod ID. + /// Returns the mod info if found, else null. + Task 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 +{ + /// An HTTP client for fetching mod metadata from Nexus Mods. + internal class NexusClient : INexusClient + { + /********* + ** Properties + *********/ + /// The URL for a Nexus Mods API query excluding the base URL, where {0} is the mod ID. + private readonly string ModUrlFormat; + + /// The underlying HTTP client. + private readonly IClient Client; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The user agent for the Nexus Mods API client. + /// The base URL for the Nexus Mods API. + /// The URL for a Nexus Mods API query excluding the , where {0} is the mod ID. + public NexusClient(string userAgent, string baseUrl, string modUrlFormat) + { + this.ModUrlFormat = modUrlFormat; + this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + } + + /// Get metadata about a mod. + /// The Nexus mod ID. + /// Returns the mod info if found, else null. + public async Task GetModAsync(uint id) + { + return await this.Client + .GetAsync(string.Format(this.ModUrlFormat, id)) + .As(); + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + 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 +{ + /// Mod metadata from Nexus Mods. + internal class NexusMod + { + /********* + ** Accessors + *********/ + /// The mod name. + public string Name { get; set; } + + /// The mod's semantic version number. + public string Version { get; set; } + + /// The mod's web URL. + [JsonProperty("mod_page_uri")] + public string Url { get; set; } + } +} -- cgit From bbd021f8736d1496f34a58b12bb0ee6c341d1c5e Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 24 Dec 2017 23:40:23 -0500 Subject: decouple Pastebin client from log parser (#411) --- src/SMAPI.Web/Controllers/LogParserController.cs | 20 ++- .../Framework/Clients/Pastebin/IPastebinClient.cs | 17 +++ .../Framework/Clients/Pastebin/PasteInfo.cs | 15 +++ .../Framework/Clients/Pastebin/PastebinClient.cs | 134 +++++++++++++++++++++ .../Framework/Clients/Pastebin/SavePasteResult.cs | 15 +++ .../Framework/ConfigModels/ApiClientsConfig.cs | 16 +++ .../Framework/ConfigModels/LogParserConfig.cs | 12 -- .../Framework/LogParser/GetPasteResponse.cs | 15 --- .../Framework/LogParser/PastebinClient.cs | 134 --------------------- .../Framework/LogParser/SavePasteResponse.cs | 15 --- src/SMAPI.Web/Startup.cs | 10 ++ src/SMAPI.Web/appsettings.Development.json | 9 +- src/SMAPI.Web/appsettings.json | 12 +- 13 files changed, 227 insertions(+), 197 deletions(-) create mode 100644 src/SMAPI.Web/Framework/Clients/Pastebin/IPastebinClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Pastebin/PasteInfo.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs create mode 100644 src/SMAPI.Web/Framework/Clients/Pastebin/SavePasteResult.cs delete mode 100644 src/SMAPI.Web/Framework/LogParser/GetPasteResponse.cs delete mode 100644 src/SMAPI.Web/Framework/LogParser/PastebinClient.cs delete mode 100644 src/SMAPI.Web/Framework/LogParser/SavePasteResponse.cs (limited to 'src/SMAPI.Web/Framework/Clients') diff --git a/src/SMAPI.Web/Controllers/LogParserController.cs b/src/SMAPI.Web/Controllers/LogParserController.cs index 454440bb..b9227a2f 100644 --- a/src/SMAPI.Web/Controllers/LogParserController.cs +++ b/src/SMAPI.Web/Controllers/LogParserController.cs @@ -6,8 +6,8 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using StardewModdingAPI.Web.Framework; +using StardewModdingAPI.Web.Framework.Clients.Pastebin; using StardewModdingAPI.Web.Framework.ConfigModels; -using StardewModdingAPI.Web.Framework.LogParser; using StardewModdingAPI.Web.ViewModels; namespace StardewModdingAPI.Web.Controllers @@ -22,7 +22,7 @@ namespace StardewModdingAPI.Web.Controllers private readonly LogParserConfig Config; /// The underlying Pastebin client. - private readonly PastebinClient PastebinClient; + private readonly IPastebinClient Pastebin; /// The first bytes in a valid zip file. /// See . @@ -37,13 +37,11 @@ namespace StardewModdingAPI.Web.Controllers ***/ /// Construct an instance. /// The log parser config settings. - public LogParserController(IOptions configProvider) + /// The Pastebin API client. + public LogParserController(IOptions configProvider, IPastebinClient pastebin) { - // init Pastebin client this.Config = configProvider.Value; - string version = this.GetType().Assembly.GetName().Version.ToString(3); - string userAgent = string.Format(this.Config.PastebinUserAgent, version); - this.PastebinClient = new PastebinClient(this.Config.PastebinBaseUrl, userAgent, this.Config.PastebinUserKey, this.Config.PastebinDevKey); + this.Pastebin = pastebin; } /*** @@ -67,9 +65,9 @@ namespace StardewModdingAPI.Web.Controllers /// The Pastebin paste ID. [HttpGet, Produces("application/json")] [Route("log/fetch/{id}")] - public async Task GetAsync(string id) + public async Task GetAsync(string id) { - GetPasteResponse response = await this.PastebinClient.GetAsync(id); + PasteInfo response = await this.Pastebin.GetAsync(id); response.Content = this.DecompressString(response.Content); return response; } @@ -78,10 +76,10 @@ namespace StardewModdingAPI.Web.Controllers /// The log content to save. [HttpPost, Produces("application/json"), AllowLargePosts] [Route("log/save")] - public async Task PostAsync([FromBody] string content) + public async Task PostAsync([FromBody] string content) { content = this.CompressString(content); - return await this.PastebinClient.PostAsync(content); + return await this.Pastebin.PostAsync(content); } 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 +{ + /// An API client for Pastebin. + internal interface IPastebinClient : IDisposable + { + /// Fetch a saved paste. + /// The paste ID. + Task GetAsync(string id); + + /// Save a paste to Pastebin. + /// The paste content. + Task 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 +{ + /// The response for a get-paste request. + internal class PasteInfo + { + /// Whether the log was successfully fetched. + public bool Success { get; set; } + + /// The fetched paste content (if is true). + public string Content { get; set; } + + /// The error message (if saving failed). + 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 +{ + /// An API client for Pastebin. + internal class PastebinClient : IPastebinClient + { + /********* + ** Properties + *********/ + /// The underlying HTTP client. + private readonly IClient Client; + + /// The user key used to authenticate with the Pastebin API. + private readonly string UserKey; + + /// The developer key used to authenticate with the Pastebin API. + private readonly string DevKey; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The base URL for the Pastebin API. + /// The user agent for the API client. + /// The user key used to authenticate with the Pastebin API. + /// The developer key used to authenticate with the Pastebin API. + public PastebinClient(string baseUrl, string userAgent, string userKey, string devKey) + { + this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); + this.UserKey = userKey; + this.DevKey = devKey; + } + + /// Fetch a saved paste. + /// The paste ID. + public async Task 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("Save a paste to Pastebin. + /// The paste content. + public async Task 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 + { + ["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() }; + } + } + + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + public void Dispose() + { + this.Client.Dispose(); + } + + + /********* + ** Private methods + *********/ + /// Build an HTTP content body with form-url-encoded content. + /// The content to encode. + /// This bypasses an issue where restricts the body length to the maximum size of a URL, which isn't applicable here. + private HttpContent GetFormUrlEncodedContent(IDictionary 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 +{ + /// The response for a save-log request. + internal class SavePasteResult + { + /// Whether the log was successfully saved. + public bool Success { get; set; } + + /// The saved paste ID (if is true). + public string ID { get; set; } + + /// The error message (if saving failed). + public string Error { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs index 19794920..61219414 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/ApiClientsConfig.cs @@ -52,5 +52,21 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels /// The URL for a Nexus Mods API query excluding the , where {0} is the mod ID. public string NexusModUrlFormat { get; set; } + + /**** + ** Pastebin + ****/ + /// The base URL for the Pastebin API. + public string PastebinBaseUrl { get; set; } + + /// The user agent for the Pastebin API client, where {0} is the SMAPI version. + public string PastebinUserAgent { get; set; } + + /// The user key used to authenticate with the Pastebin API. + public string PastebinUserKey { get; set; } + + /// The developer key used to authenticate with the Pastebin API. + public string PastebinDevKey { get; set; } + } } diff --git a/src/SMAPI.Web/Framework/ConfigModels/LogParserConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/LogParserConfig.cs index df5d605d..198274b2 100644 --- a/src/SMAPI.Web/Framework/ConfigModels/LogParserConfig.cs +++ b/src/SMAPI.Web/Framework/ConfigModels/LogParserConfig.cs @@ -8,17 +8,5 @@ namespace StardewModdingAPI.Web.Framework.ConfigModels *********/ /// The root URL for the log parser controller. public string SectionUrl { get; set; } - - /// The base URL for the Pastebin API. - public string PastebinBaseUrl { get; set; } - - /// The user agent for the Pastebin API client, where {0} is the SMAPI version. - public string PastebinUserAgent { get; set; } - - /// The user key used to authenticate with the Pastebin API. - public string PastebinUserKey { get; set; } - - /// The developer key used to authenticate with the Pastebin API. - public string PastebinDevKey { get; set; } } } diff --git a/src/SMAPI.Web/Framework/LogParser/GetPasteResponse.cs b/src/SMAPI.Web/Framework/LogParser/GetPasteResponse.cs deleted file mode 100644 index 4f8794db..00000000 --- a/src/SMAPI.Web/Framework/LogParser/GetPasteResponse.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace StardewModdingAPI.Web.Framework.LogParser -{ - /// The response for a get-paste request. - internal class GetPasteResponse - { - /// Whether the log was successfully fetched. - public bool Success { get; set; } - - /// The fetched paste content (if is true). - public string Content { get; set; } - - /// The error message (if saving failed). - public string Error { get; set; } - } -} diff --git a/src/SMAPI.Web/Framework/LogParser/PastebinClient.cs b/src/SMAPI.Web/Framework/LogParser/PastebinClient.cs deleted file mode 100644 index 1cfaed17..00000000 --- a/src/SMAPI.Web/Framework/LogParser/PastebinClient.cs +++ /dev/null @@ -1,134 +0,0 @@ -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.LogParser -{ - /// An API client for Pastebin. - internal class PastebinClient : IDisposable - { - /********* - ** Properties - *********/ - /// The underlying HTTP client. - private readonly IClient Client; - - /// The user key used to authenticate with the Pastebin API. - private readonly string UserKey; - - /// The developer key used to authenticate with the Pastebin API. - private readonly string DevKey; - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The base URL for the Pastebin API. - /// The user agent for the API client. - /// The user key used to authenticate with the Pastebin API. - /// The developer key used to authenticate with the Pastebin API. - public PastebinClient(string baseUrl, string userAgent, string userKey, string devKey) - { - this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); - this.UserKey = userKey; - this.DevKey = devKey; - } - - /// Fetch a saved paste. - /// The paste ID. - public async Task 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 GetPasteResponse { Error = "Received an empty response from Pastebin." }; - if (content.StartsWith("Save a paste to Pastebin. - /// The paste content. - public async Task PostAsync(string content) - { - try - { - // validate - if (string.IsNullOrWhiteSpace(content)) - return new SavePasteResponse { 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 - { - ["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 SavePasteResponse { Error = "Received an empty response from Pastebin." }; - if (response.StartsWith("Bad API request")) - return new SavePasteResponse { Error = response }; - if (!response.Contains("/")) - return new SavePasteResponse { Error = $"Received an unknown response: {response}" }; - - // return paste ID - string pastebinID = response.Split("/").Last(); - return new SavePasteResponse { Success = true, ID = pastebinID }; - } - catch (Exception ex) - { - return new SavePasteResponse { Success = false, Error = ex.ToString() }; - } - } - - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - public void Dispose() - { - this.Client.Dispose(); - } - - - /********* - ** Private methods - *********/ - /// Build an HTTP content body with form-url-encoded content. - /// The content to encode. - /// This bypasses an issue where restricts the body length to the maximum size of a URL, which isn't applicable here. - private HttpContent GetFormUrlEncodedContent(IDictionary 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/LogParser/SavePasteResponse.cs b/src/SMAPI.Web/Framework/LogParser/SavePasteResponse.cs deleted file mode 100644 index 1c0960a4..00000000 --- a/src/SMAPI.Web/Framework/LogParser/SavePasteResponse.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace StardewModdingAPI.Web.Framework.LogParser -{ - /// The response for a save-log request. - internal class SavePasteResponse - { - /// Whether the log was successfully saved. - public bool Success { get; set; } - - /// The saved paste ID (if is true). - public string ID { get; set; } - - /// The error message (if saving failed). - public string Error { get; set; } - } -} diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index 7938520a..307c4ae9 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -10,6 +10,7 @@ using StardewModdingAPI.Web.Framework; using StardewModdingAPI.Web.Framework.Clients.Chucklefish; using StardewModdingAPI.Web.Framework.Clients.GitHub; using StardewModdingAPI.Web.Framework.Clients.Nexus; +using StardewModdingAPI.Web.Framework.Clients.Pastebin; using StardewModdingAPI.Web.Framework.ConfigModels; using StardewModdingAPI.Web.Framework.RewriteRules; @@ -69,6 +70,7 @@ namespace StardewModdingAPI.Web baseUrl: api.ChucklefishBaseUrl, modPageUrlFormat: api.ChucklefishModPageUrlFormat )); + services.AddSingleton(new GitHubClient( baseUrl: api.GitHubBaseUrl, releaseUrlFormat: api.GitHubReleaseUrlFormat, @@ -77,11 +79,19 @@ namespace StardewModdingAPI.Web username: api.GitHubUsername, password: api.GitHubPassword )); + services.AddSingleton(new NexusClient( userAgent: api.NexusUserAgent, baseUrl: api.NexusBaseUrl, modUrlFormat: api.NexusModUrlFormat )); + + services.AddSingleton(new PastebinClient( + baseUrl: api.PastebinBaseUrl, + userAgent: userAgent, + userKey: api.PastebinUserKey, + devKey: api.PastebinDevKey + )); } } diff --git a/src/SMAPI.Web/appsettings.Development.json b/src/SMAPI.Web/appsettings.Development.json index 4602d1ed..45fc30f3 100644 --- a/src/SMAPI.Web/appsettings.Development.json +++ b/src/SMAPI.Web/appsettings.Development.json @@ -18,11 +18,12 @@ }, "ApiClients": { "GitHubUsername": null, - "GitHubPassword": null - }, - "LogParser": { - "SectionUrl": "http://localhost:59482/log/", + "GitHubPassword": null, + "PastebinUserKey": null, "PastebinDevKey": null + }, + "LogParser": { + "SectionUrl": "http://localhost:59482/log/" } } diff --git a/src/SMAPI.Web/appsettings.json b/src/SMAPI.Web/appsettings.json index 4f70b41b..69b3b4f8 100644 --- a/src/SMAPI.Web/appsettings.json +++ b/src/SMAPI.Web/appsettings.json @@ -27,7 +27,11 @@ "NexusUserAgent": "Nexus Client v0.63.15", "NexusBaseUrl": "http://www.nexusmods.com/stardewvalley", - "NexusModUrlFormat": "mods/{0}" + "NexusModUrlFormat": "mods/{0}", + + "PastebinBaseUrl": "https://pastebin.com/", + "PastebinUserKey": null, // see top note + "PastebinDevKey": null // see top note }, "ModUpdateCheck": { @@ -39,10 +43,6 @@ "NexusKey": "Nexus" }, "LogParser": { - "SectionUrl": null, // see top note - "PastebinBaseUrl": "https://pastebin.com/", - "PastebinUserAgent": "SMAPI/{0} (+https://github.com/Pathoschild/SMAPI)", - "PastebinUserKey": null, // see top note - "PastebinDevKey": null // see top note + "SectionUrl": null // see top note } } -- cgit From adee66b3b4ea111b0082a31108e55726fab10643 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 25 Dec 2017 01:47:10 -0500 Subject: add basic download page (#411) --- src/SMAPI.Web/Controllers/IndexController.cs | 79 ++++++++++++++++++++++ src/SMAPI.Web/Controllers/LogParserController.cs | 1 - src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs | 20 ++++++ .../Framework/Clients/GitHub/GitRelease.cs | 6 ++ src/SMAPI.Web/Properties/launchSettings.json | 2 +- src/SMAPI.Web/StardewModdingAPI.Web.csproj | 1 + src/SMAPI.Web/Startup.cs | 1 - src/SMAPI.Web/ViewModels/IndexModel.cs | 41 +++++++++++ src/SMAPI.Web/Views/Index/Index.cshtml | 73 ++++++++++++++++++++ 9 files changed, 221 insertions(+), 3 deletions(-) create mode 100644 src/SMAPI.Web/Controllers/IndexController.cs create mode 100644 src/SMAPI.Web/Framework/Clients/GitHub/GitAsset.cs create mode 100644 src/SMAPI.Web/ViewModels/IndexModel.cs create mode 100644 src/SMAPI.Web/Views/Index/Index.cshtml (limited to 'src/SMAPI.Web/Framework/Clients') diff --git a/src/SMAPI.Web/Controllers/IndexController.cs b/src/SMAPI.Web/Controllers/IndexController.cs new file mode 100644 index 00000000..c2c5f2fe --- /dev/null +++ b/src/SMAPI.Web/Controllers/IndexController.cs @@ -0,0 +1,79 @@ +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using StardewModdingAPI.Web.Framework.Clients.GitHub; +using StardewModdingAPI.Web.ViewModels; + +namespace StardewModdingAPI.Web.Controllers +{ + /// Provides an info/download page about SMAPI. + [Route("")] + [Route("install")] + internal class IndexController : Controller + { + /********* + ** Properties + *********/ + /// The GitHub API client. + private readonly IGitHubClient GitHub; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The GitHub API client. + public IndexController(IGitHubClient github) + { + this.GitHub = github; + } + + /// Display the index page. + [HttpGet] + public async Task Index() + { + // fetch latest SMAPI release + GitRelease release = await this.GitHub.GetLatestReleaseAsync("Pathoschild/SMAPI"); + string downloadUrl = this.GetMainDownloadUrl(release); + string devDownloadUrl = this.GetDevDownloadUrl(release); + + // render view + var model = new IndexModel(release.Name, release.Body, downloadUrl, devDownloadUrl); + return this.View(model); + } + + + /********* + ** Private methods + *********/ + /// Get the main download URL for a SMAPI release. + /// The SMAPI release. + private string GetMainDownloadUrl(GitRelease release) + { + // get main download URL + foreach (GitAsset asset in release.Assets ?? new GitAsset[0]) + { + if (Regex.IsMatch(asset.FileName, @"SMAPI-[\d\.]+-installer.zip")) + return asset.DownloadUrl; + } + + // fallback just in case + return "https://github.com/pathoschild/SMAPI/releases"; + } + + /// Get the for-developers download URL for a SMAPI release. + /// The SMAPI release. + private string GetDevDownloadUrl(GitRelease release) + { + // get dev download URL + foreach (GitAsset asset in release.Assets ?? new GitAsset[0]) + { + if (Regex.IsMatch(asset.FileName, @"SMAPI-[\d\.]+-installer-for-developers.zip")) + return asset.DownloadUrl; + } + + // fallback just in case + return "https://github.com/pathoschild/SMAPI/releases"; + } + } +} diff --git a/src/SMAPI.Web/Controllers/LogParserController.cs b/src/SMAPI.Web/Controllers/LogParserController.cs index b9227a2f..ad979397 100644 --- a/src/SMAPI.Web/Controllers/LogParserController.cs +++ b/src/SMAPI.Web/Controllers/LogParserController.cs @@ -50,7 +50,6 @@ namespace StardewModdingAPI.Web.Controllers /// Render the log parser UI. /// The paste ID. [HttpGet] - [Route("")] [Route("log")] [Route("log/{id}")] public ViewResult Index(string id = null) 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 +{ + /// A GitHub download attached to a release. + internal class GitAsset + { + /// The file name. + [JsonProperty("name")] + public string FileName { get; set; } + + /// The file content type. + [JsonProperty("content_type")] + public string ContentType { get; set; } + + /// The download URL. + [JsonProperty("browser_download_url")] + public string DownloadUrl { get; set; } + } +} diff --git a/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs index 0a47f3b4..b944088d 100644 --- a/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs +++ b/src/SMAPI.Web/Framework/Clients/GitHub/GitRelease.cs @@ -15,5 +15,11 @@ namespace StardewModdingAPI.Web.Framework.Clients.GitHub /// The semantic version string. [JsonProperty("tag_name")] public string Tag { get; set; } + + /// The Markdown description for the release. + public string Body { get; set; } + + /// The attached files. + public GitAsset[] Assets { get; set; } } } diff --git a/src/SMAPI.Web/Properties/launchSettings.json b/src/SMAPI.Web/Properties/launchSettings.json index e485e4e3..88179044 100644 --- a/src/SMAPI.Web/Properties/launchSettings.json +++ b/src/SMAPI.Web/Properties/launchSettings.json @@ -11,7 +11,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "log", + "launchUrl": "", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } diff --git a/src/SMAPI.Web/StardewModdingAPI.Web.csproj b/src/SMAPI.Web/StardewModdingAPI.Web.csproj index b5b0ff07..19198503 100644 --- a/src/SMAPI.Web/StardewModdingAPI.Web.csproj +++ b/src/SMAPI.Web/StardewModdingAPI.Web.csproj @@ -11,6 +11,7 @@ + diff --git a/src/SMAPI.Web/Startup.cs b/src/SMAPI.Web/Startup.cs index 307c4ae9..c6e3f85d 100644 --- a/src/SMAPI.Web/Startup.cs +++ b/src/SMAPI.Web/Startup.cs @@ -134,7 +134,6 @@ namespace StardewModdingAPI.Web // shortcut redirects .Add(new RedirectToUrlRule("^/docs$", "https://stardewvalleywiki.com/Modding:Index")) - .Add(new RedirectToUrlRule("^/install$", "https://stardewvalleywiki.com/Modding:Installing_SMAPI")) ) .UseStaticFiles() // wwwroot folder .UseMvc(); diff --git a/src/SMAPI.Web/ViewModels/IndexModel.cs b/src/SMAPI.Web/ViewModels/IndexModel.cs new file mode 100644 index 00000000..6d3da91e --- /dev/null +++ b/src/SMAPI.Web/ViewModels/IndexModel.cs @@ -0,0 +1,41 @@ +namespace StardewModdingAPI.Web.ViewModels +{ + /// The view model for the index page. + public class IndexModel + { + /********* + ** Accessors + *********/ + /// The latest SMAPI version. + public string LatestVersion { get; set; } + + /// The Markdown description for the release. + public string Description { get; set; } + + /// The main download URL. + public string DownloadUrl { get; set; } + + /// The for-developers download URL. + public string DevDownloadUrl { get; set; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public IndexModel() { } + + /// Construct an instance. + /// The latest SMAPI version. + /// The Markdown description for the release. + /// The main download URL. + /// The for-developers download URL. + internal IndexModel(string latestVersion, string description, string downloadUrl, string devDownloadUrl) + { + this.LatestVersion = latestVersion; + this.Description = description; + this.DownloadUrl = downloadUrl; + this.DevDownloadUrl = devDownloadUrl; + } + } +} diff --git a/src/SMAPI.Web/Views/Index/Index.cshtml b/src/SMAPI.Web/Views/Index/Index.cshtml new file mode 100644 index 00000000..b2b8c0dd --- /dev/null +++ b/src/SMAPI.Web/Views/Index/Index.cshtml @@ -0,0 +1,73 @@ +@{ + ViewData["Title"] = "SMAPI"; +} +@model StardewModdingAPI.Web.ViewModels.IndexModel + + + +

+ SMAPI is the modding API for Stardew Valley. It works fine with Steam achievements and the + overlay, you can uninstall it anytime, and there's a friendly community if you need help. It's + a cool boy. +

+ +

Download and links

+
+ +

What's new in SMAPI @Model.LatestVersion?

+
+ @Html.Raw(Markdig.Markdown.ToHtml(Model.Description)) +
+ +

Support SMAPI ♥

+ + +

+ Special thanks to + acerbicon, + ChefRude, + jwdred, + Karmylla, + OfficialPiAddict, + Robby LaFarge, + and a few anonymous users for supporting SMAPI; you're awesome! +

+ +

For mod creators

+ -- cgit