summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs
blob: 9689807c4512a3c47439c395e786618cae27a2db (plain)
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
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
{
    /// <summary>An HTTP client for fetching mod metadata from the Chucklefish mod site.</summary>
    internal class ChucklefishClient : IChucklefishClient
    {
        /*********
        ** Fields
        *********/
        /// <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;


        /*********
        ** Accessors
        *********/
        /// <summary>The unique key for the mod site.</summary>
        public ModSiteKey SiteKey => ModSiteKey.Chucklefish;


        /*********
        ** 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.ModPageUrlFormat = modPageUrlFormat;
            this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
        }

        /// <summary>Get update check info about a mod.</summary>
        /// <param name="id">The mod ID.</param>
        public async Task<IModPage> 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<IModDownload>());
        }

        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public void Dispose()
        {
            this.Client?.Dispose();
        }


        /*********
        ** Private methods
        *********/
        /// <summary>Get the full mod page URL for a given ID.</summary>
        /// <param name="id">The mod ID.</param>
        private string GetModUrl(uint id)
        {
            UriBuilder builder = new(this.Client.BaseClient.BaseAddress);
            builder.Path += string.Format(this.ModPageUrlFormat, id);
            return builder.Uri.ToString();
        }
    }
}