summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework
diff options
context:
space:
mode:
Diffstat (limited to 'src/SMAPI.Web/Framework')
-rw-r--r--src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs74
-rw-r--r--src/SMAPI.Web/Framework/InternalControllerFeatureProvider.cs27
-rw-r--r--src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs51
-rw-r--r--src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs92
-rw-r--r--src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs97
-rw-r--r--src/SMAPI.Web/Framework/ModRepositories/IModRepository.cs24
-rw-r--r--src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs89
-rw-r--r--src/SMAPI.Web/Framework/RewriteSubdomainRule.cs30
-rw-r--r--src/SMAPI.Web/Framework/VersionConstraint.cs15
9 files changed, 499 insertions, 0 deletions
diff --git a/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs b/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs
new file mode 100644
index 00000000..03de639e
--- /dev/null
+++ b/src/SMAPI.Web/Framework/ConfigModels/ModUpdateCheckConfig.cs
@@ -0,0 +1,74 @@
+namespace StardewModdingAPI.Web.Framework.ConfigModels
+{
+ /// <summary>The config settings for mod update checks.</summary>
+ public class ModUpdateCheckConfig
+ {
+ /*********
+ ** Accessors
+ *********/
+ /****
+ ** General
+ ****/
+ /// <summary>The number of minutes update checks should be cached before refetching them.</summary>
+ public int CacheMinutes { get; set; }
+
+ /// <summary>A regex which matches SMAPI-style semantic version.</summary>
+ /// <remarks>Derived from SMAPI's SemanticVersion implementation.</remarks>
+ public string SemanticVersionRegex { get; set; }
+
+ /****
+ ** Chucklefish mod site
+ ****/
+ /// <summary>The repository key for the Chucklefish mod site.</summary>
+ public string ChucklefishKey { get; set; }
+
+ /// <summary>The user agent for the Chucklefish API client, where {0} is the SMAPI version.</summary>
+ public string ChucklefishUserAgent { get; set; }
+
+ /// <summary>The base URL for the Chucklefish mod site.</summary>
+ public string ChucklefishBaseUrl { get; set; }
+
+ /// <summary>The URL for a mod page on the Chucklefish mod site excluding the <see cref="GitHubBaseUrl"/>, where {0} is the mod ID.</summary>
+ public string ChucklefishModPageUrlFormat { get; set; }
+
+
+ /****
+ ** GitHub
+ ****/
+ /// <summary>The repository key for Nexus Mods.</summary>
+ public string GitHubKey { get; set; }
+
+ /// <summary>The user agent for the GitHub API client, where {0} is the SMAPI version.</summary>
+ public string GitHubUserAgent { get; set; }
+
+ /// <summary>The base URL for the GitHub API.</summary>
+ public string GitHubBaseUrl { get; set; }
+
+ /// <summary>The URL for a GitHub API latest-release query excluding the <see cref="GitHubBaseUrl"/>, where {0} is the organisation and project name.</summary>
+ public string GitHubReleaseUrlFormat { get; set; }
+
+ /// <summary>The Accept header value expected by the GitHub API.</summary>
+ public string GitHubAcceptHeader { get; set; }
+
+ /// <summary>The username with which to authenticate to the GitHub API (if any).</summary>
+ public string GitHubUsername { get; set; }
+
+ /// <summary>The password with which to authenticate to the GitHub API (if any).</summary>
+ public string GitHubPassword { get; set; }
+
+ /****
+ ** Nexus Mods
+ ****/
+ /// <summary>The repository key for Nexus Mods.</summary>
+ public string NexusKey { get; set; }
+
+ /// <summary>The user agent for the Nexus Mods API client.</summary>
+ public string NexusUserAgent { get; set; }
+
+ /// <summary>The base URL for the Nexus Mods API.</summary>
+ public string NexusBaseUrl { get; set; }
+
+ /// <summary>The URL for a Nexus Mods API query excluding the <see cref="NexusBaseUrl"/>, where {0} is the mod ID.</summary>
+ public string NexusModUrlFormat { get; set; }
+ }
+}
diff --git a/src/SMAPI.Web/Framework/InternalControllerFeatureProvider.cs b/src/SMAPI.Web/Framework/InternalControllerFeatureProvider.cs
new file mode 100644
index 00000000..2c24c610
--- /dev/null
+++ b/src/SMAPI.Web/Framework/InternalControllerFeatureProvider.cs
@@ -0,0 +1,27 @@
+using System;
+using System.Reflection;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Controllers;
+
+namespace StardewModdingAPI.Web.Framework
+{
+ /// <summary>Discovers controllers with support for non-public controllers.</summary>
+ internal class InternalControllerFeatureProvider : ControllerFeatureProvider
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Determines if a given type is a controller.</summary>
+ /// <param name="type">The <see cref="T:System.Reflection.TypeInfo" /> candidate.</param>
+ /// <returns><code>true</code> if the type is a controller; otherwise <code>false</code>.</returns>
+ protected override bool IsController(TypeInfo type)
+ {
+ return
+ type.IsClass
+ && !type.IsAbstract
+ && (/*type.IsPublic &&*/ !type.ContainsGenericParameters)
+ && (!type.IsDefined(typeof(NonControllerAttribute))
+ && (type.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) || type.IsDefined(typeof(ControllerAttribute))));
+ }
+ }
+}
diff --git a/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs
new file mode 100644
index 00000000..d98acd89
--- /dev/null
+++ b/src/SMAPI.Web/Framework/ModRepositories/BaseRepository.cs
@@ -0,0 +1,51 @@
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using StardewModdingAPI.Models;
+
+namespace StardewModdingAPI.Web.Framework.ModRepositories
+{
+ internal abstract class RepositoryBase : IModRepository
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The unique key for this vendor.</summary>
+ public string VendorKey { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
+ public abstract void Dispose();
+
+ /// <summary>Get metadata about a mod in the repository.</summary>
+ /// <param name="id">The mod ID in this repository.</param>
+ public abstract Task<ModInfoModel> GetModInfoAsync(string id);
+
+
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="vendorKey">The unique key for this vendor.</param>
+ protected RepositoryBase(string vendorKey)
+ {
+ this.VendorKey = vendorKey;
+ }
+
+ /// <summary>Normalise a version string.</summary>
+ /// <param name="version">The version to normalise.</param>
+ protected string NormaliseVersion(string version)
+ {
+ if (string.IsNullOrWhiteSpace(version))
+ return null;
+
+ version = version.Trim();
+ if (Regex.IsMatch(version, @"^v\d", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)) // common version prefix
+ version = version.Substring(1);
+
+ return version;
+ }
+ }
+}
diff --git a/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs
new file mode 100644
index 00000000..ed7bd60b
--- /dev/null
+++ b/src/SMAPI.Web/Framework/ModRepositories/ChucklefishRepository.cs
@@ -0,0 +1,92 @@
+using System;
+using System.Net;
+using System.Threading.Tasks;
+using HtmlAgilityPack;
+using Pathoschild.Http.Client;
+using StardewModdingAPI.Models;
+
+namespace StardewModdingAPI.Web.Framework.ModRepositories
+{
+ /// <summary>An HTTP client for fetching mod metadata from the Chucklefish mod site.</summary>
+ internal class ChucklefishRepository : RepositoryBase
+ {
+ /*********
+ ** 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="vendorKey">The unique key for this vendor.</param>
+ /// <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 ChucklefishRepository(string vendorKey, string userAgent, string baseUrl, string modPageUrlFormat)
+ : base(vendorKey)
+ {
+ this.BaseUrl = baseUrl;
+ this.ModPageUrlFormat = modPageUrlFormat;
+ this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
+ }
+
+ /// <summary>Get metadata about a mod in the repository.</summary>
+ /// <param name="id">The mod ID in this repository.</param>
+ public override async Task<ModInfoModel> GetModInfoAsync(string id)
+ {
+ // validate ID format
+ if (!uint.TryParse(id, out uint _))
+ return new ModInfoModel($"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID.");
+
+ // fetch info
+ try
+ {
+ // 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 new ModInfoModel("Found no mod with this ID.");
+ }
+
+ // 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 ModInfoModel(name, this.NormaliseVersion(version), url);
+ }
+ catch (Exception ex)
+ {
+ return new ModInfoModel(ex.ToString());
+ }
+ }
+
+ /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
+ public override void Dispose()
+ {
+ this.Client.Dispose();
+ }
+ }
+}
diff --git a/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs
new file mode 100644
index 00000000..174fb79a
--- /dev/null
+++ b/src/SMAPI.Web/Framework/ModRepositories/GitHubRepository.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Net;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+using Pathoschild.Http.Client;
+using StardewModdingAPI.Models;
+
+namespace StardewModdingAPI.Web.Framework.ModRepositories
+{
+ /// <summary>An HTTP client for fetching mod metadata from GitHub project releases.</summary>
+ internal class GitHubRepository : RepositoryBase
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The URL for a Nexus Mods API query excluding the base URL, where {0} is the mod ID.</summary>
+ private readonly string ReleaseUrlFormat;
+
+ /// <summary>The underlying HTTP client.</summary>
+ private readonly IClient Client;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="vendorKey">The unique key for this vendor.</param>
+ /// <param name="baseUrl">The base URL for the Nexus Mods API.</param>
+ /// <param name="releaseUrlFormat">The URL for a Nexus Mods API query excluding the <paramref name="baseUrl"/>, where {0} is the mod ID.</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 GitHubRepository(string vendorKey, string baseUrl, string releaseUrlFormat, string userAgent, string acceptHeader, string username, string password)
+ : base(vendorKey)
+ {
+ 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 metadata about a mod in the repository.</summary>
+ /// <param name="id">The mod ID in this repository.</param>
+ public override async Task<ModInfoModel> GetModInfoAsync(string id)
+ {
+ // validate ID format
+ if (!id.Contains("/") || id.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) != id.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase))
+ return new ModInfoModel($"The value '{id}' isn't a valid GitHub mod ID, must be a username and project name like 'Pathoschild/LookupAnything'.");
+
+ // fetch info
+ try
+ {
+ GitRelease release = await this.Client
+ .GetAsync(string.Format(this.ReleaseUrlFormat, id))
+ .As<GitRelease>();
+ return new ModInfoModel(id, this.NormaliseVersion(release.Tag), $"https://github.com/{id}/releases");
+ }
+ catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ {
+ return new ModInfoModel("Found no mod with this ID.");
+ }
+ catch (Exception ex)
+ {
+ return new ModInfoModel(ex.ToString());
+ }
+ }
+
+ /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
+ public override void Dispose()
+ {
+ this.Client.Dispose();
+ }
+
+
+ /*********
+ ** Private models
+ *********/
+ /// <summary>Metadata about a GitHub release tag.</summary>
+ private 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; }
+ }
+ }
+}
diff --git a/src/SMAPI.Web/Framework/ModRepositories/IModRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/IModRepository.cs
new file mode 100644
index 00000000..98e4c957
--- /dev/null
+++ b/src/SMAPI.Web/Framework/ModRepositories/IModRepository.cs
@@ -0,0 +1,24 @@
+using System;
+using System.Threading.Tasks;
+using StardewModdingAPI.Models;
+
+namespace StardewModdingAPI.Web.Framework.ModRepositories
+{
+ /// <summary>A repository which provides mod metadata.</summary>
+ internal interface IModRepository : IDisposable
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The unique key for this vendor.</summary>
+ string VendorKey { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get metadata about a mod in the repository.</summary>
+ /// <param name="id">The mod ID in this repository.</param>
+ Task<ModInfoModel> GetModInfoAsync(string id);
+ }
+}
diff --git a/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs
new file mode 100644
index 00000000..71970bec
--- /dev/null
+++ b/src/SMAPI.Web/Framework/ModRepositories/NexusRepository.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+using Pathoschild.Http.Client;
+using StardewModdingAPI.Models;
+
+namespace StardewModdingAPI.Web.Framework.ModRepositories
+{
+ /// <summary>An HTTP client for fetching mod metadata from Nexus Mods.</summary>
+ internal class NexusRepository : RepositoryBase
+ {
+ /*********
+ ** 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="vendorKey">The unique key for this vendor.</param>
+ /// <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 NexusRepository(string vendorKey, string userAgent, string baseUrl, string modUrlFormat)
+ : base(vendorKey)
+ {
+ this.ModUrlFormat = modUrlFormat;
+ this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
+ }
+
+ /// <summary>Get metadata about a mod in the repository.</summary>
+ /// <param name="id">The mod ID in this repository.</param>
+ public override async Task<ModInfoModel> GetModInfoAsync(string id)
+ {
+ // validate ID format
+ if (!uint.TryParse(id, out uint _))
+ return new ModInfoModel($"The value '{id}' isn't a valid Nexus mod ID, must be an integer ID.");
+
+ // fetch info
+ try
+ {
+ NexusResponseModel response = await this.Client
+ .GetAsync(string.Format(this.ModUrlFormat, id))
+ .As<NexusResponseModel>();
+
+ return response != null
+ ? new ModInfoModel(response.Name, this.NormaliseVersion(response.Version), response.Url)
+ : new ModInfoModel("Found no mod with this ID.");
+ }
+ catch (Exception ex)
+ {
+ return new ModInfoModel(ex.ToString());
+ }
+ }
+
+ /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
+ public override void Dispose()
+ {
+ this.Client.Dispose();
+ }
+
+
+ /*********
+ ** Private models
+ *********/
+ /// <summary>A mod metadata response from Nexus Mods.</summary>
+ private class NexusResponseModel
+ {
+ /*********
+ ** 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/RewriteSubdomainRule.cs b/src/SMAPI.Web/Framework/RewriteSubdomainRule.cs
new file mode 100644
index 00000000..5a56844f
--- /dev/null
+++ b/src/SMAPI.Web/Framework/RewriteSubdomainRule.cs
@@ -0,0 +1,30 @@
+using System;
+using Microsoft.AspNetCore.Rewrite;
+
+namespace StardewModdingAPI.Web.Framework
+{
+ /// <summary>Rewrite requests to prepend the subdomain portion (if any) to the path.</summary>
+ /// <remarks>Derived from <a href="https://stackoverflow.com/a/44526747/262123" />.</remarks>
+ internal class RewriteSubdomainRule : IRule
+ {
+ /// <summary>Applies the rule. Implementations of ApplyRule should set the value for <see cref="RewriteContext.Result" /> (defaults to RuleResult.ContinueRules).</summary>
+ /// <param name="context">The rewrite context.</param>
+ public void ApplyRule(RewriteContext context)
+ {
+ context.Result = RuleResult.ContinueRules;
+
+ // get host parts
+ string host = context.HttpContext.Request.Host.Host;
+ string[] parts = host.Split('.');
+
+ // validate
+ if (parts.Length < 2)
+ return;
+ if (parts.Length < 3 && !"localhost".Equals(parts[1], StringComparison.InvariantCultureIgnoreCase))
+ return;
+
+ // prepend to path
+ context.HttpContext.Request.Path = $"/{parts[0]}{context.HttpContext.Request.Path}";
+ }
+ }
+}
diff --git a/src/SMAPI.Web/Framework/VersionConstraint.cs b/src/SMAPI.Web/Framework/VersionConstraint.cs
new file mode 100644
index 00000000..be9c0918
--- /dev/null
+++ b/src/SMAPI.Web/Framework/VersionConstraint.cs
@@ -0,0 +1,15 @@
+using Microsoft.AspNetCore.Routing.Constraints;
+
+namespace StardewModdingAPI.Web.Framework
+{
+ /// <summary>Constrains a route value to a valid semantic version.</summary>
+ internal class VersionConstraint : RegexRouteConstraint
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public VersionConstraint()
+ : base(@"^v(?>(?<major>0|[1-9]\d*))\.(?>(?<minor>0|[1-9]\d*))(?>(?:\.(?<patch>0|[1-9]\d*))?)(?:-(?<prerelease>(?>[a-z0-9]+[\-\.]?)+))?$") { }
+ }
+}