summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework/Clients/Pastebin/PastebinClient.cs
blob: 1be00be76178c8b1d3648a589dc9d68f9e331b87 (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
using System;
using System.Net;
using System.Threading.Tasks;
using Pathoschild.Http.Client;

namespace StardewModdingAPI.Web.Framework.Clients.Pastebin
{
    /// <summary>An API client for Pastebin.</summary>
    internal class PastebinClient : IPastebinClient
    {
        /*********
        ** Fields
        *********/
        /// <summary>The underlying HTTP client.</summary>
        private readonly IClient Client;


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="baseUrl">The base URL for the Pastebin API.</param>
        /// <param name="userAgent">The user agent for the API client.</param>
        public PastebinClient(string baseUrl, string userAgent)
        {
            this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
        }

        /// <summary>Fetch a saved paste.</summary>
        /// <param name="id">The paste ID.</param>
        public async Task<PasteInfo> 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("<!DOCTYPE"))
                    return new PasteInfo { Error = $"Received a captcha challenge from Pastebin. Please visit https://pastebin.com/{id} in a new window to solve it." };
                return new PasteInfo { Success = true, Content = content };
            }
            catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound)
            {
                return new PasteInfo { Error = "There's no log with that ID." };
            }
            catch (Exception ex)
            {
                return new PasteInfo { Error = $"Pastebin error: {ex}" };
            }
        }

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