using System; using System.Net; using System.Threading.Tasks; using HtmlAgilityPack; using Pathoschild.Http.Client; using StardewModdingAPI.Toolkit.Framework.UpdateData; namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish { /// An HTTP client for fetching mod metadata from the Chucklefish mod site. internal class ChucklefishClient : IChucklefishClient { /********* ** Fields *********/ /// 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; /********* ** Accessors *********/ /// The unique key for the mod site. public ModSiteKey SiteKey => ModSiteKey.Chucklefish; /********* ** 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.ModPageUrlFormat = modPageUrlFormat; this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent); } /// Get update check info about a mod. /// The mod ID. public async Task GetModData(string id) { IModPage page = new GenericModPage(this.SiteKey, id); // get mod ID if (!uint.TryParse(id, out uint parsedId)) return page.SetError(RemoteModStatus.DoesNotExist, $"The value '{id}' isn't a valid Chucklefish mod ID, must be an integer ID."); // fetch HTML string html; try { html = await this.Client .GetAsync(string.Format(this.ModPageUrlFormat, parsedId)) .AsString(); } catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound || ex.Status == HttpStatusCode.Forbidden) { return page.SetError(RemoteModStatus.DoesNotExist, "Found no Chucklefish mod with this ID."); } var doc = new HtmlDocument(); doc.LoadHtml(html); // extract mod info string url = this.GetModUrl(parsedId); string version = doc.DocumentNode.SelectSingleNode("//h1/span")?.InnerText; string name = doc.DocumentNode.SelectSingleNode("//h1").ChildNodes[0].InnerText.Trim(); if (name.StartsWith("[SMAPI]")) name = name.Substring("[SMAPI]".Length).TrimStart(); // return info return page.SetInfo(name: name, version: version, url: url, downloads: Array.Empty()); } /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. public void Dispose() { this.Client?.Dispose(); } /********* ** Private methods *********/ /// Get the full mod page URL for a given ID. /// The mod ID. private string GetModUrl(uint id) { UriBuilder builder = new UriBuilder(this.Client.BaseClient.BaseAddress); builder.Path += string.Format(this.ModPageUrlFormat, id); return builder.Uri.ToString(); } } }