summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework/Clients/UpdateManifest/UpdateManifestClient.cs
blob: 88a5c2f674f386da37a1c4aea288ada200163408 (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
// Copyright 2022 Jamie Taylor
using System.Net;
using System.Threading.Tasks;
using Pathoschild.Http.Client;
using StardewModdingAPI.Toolkit.Framework.UpdateData;

namespace StardewModdingAPI.Web.Framework.Clients.UpdateManifest
{
    /// <summary>An API client for fetching update metadata from an arbitrary JSON URL.</summary>
    internal class UpdateManifestClient : IUpdateManifestClient
    {
        /*********
        ** Fields
        *********/
        /// <summary>The underlying HTTP client.</summary>
        private readonly IClient Client;


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


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="userAgent">The user agent for the API client.</param>
        public UpdateManifestClient(string userAgent)
        {
            this.Client = new FluentClient()
                .SetUserAgent(userAgent);
            this.Client.Formatters.Add(new TextAsJsonMediaTypeFormatter());
        }

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

        /// <inheritdoc/>
        public async Task<IModPage?> GetModData(string id)
        {
            UpdateManifestModel? manifest;
            try
            {
                manifest = await this.Client.GetAsync(id).As<UpdateManifestModel?>();
            }
            catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound)
            {
                return new GenericModPage(this.SiteKey, id).SetError(RemoteModStatus.DoesNotExist, $"No update manifest found at {id}");
            }

            return manifest is not null
                ? new UpdateManifestModPage(id, manifest)
                : new GenericModPage(this.SiteKey, id).SetError(RemoteModStatus.DoesNotExist, $"The update manifest at {id} has an invalid format");
        }
    }
}