summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework/Storage/StorageProvider.cs
blob: 0177e602a0af57e3735ada7d2159729f26f677e8 (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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#nullable disable

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Options;
using StardewModdingAPI.Web.Framework.Clients.Pastebin;
using StardewModdingAPI.Web.Framework.Compression;
using StardewModdingAPI.Web.Framework.ConfigModels;

namespace StardewModdingAPI.Web.Framework.Storage
{
    /// <summary>Provides access to raw data storage.</summary>
    internal class StorageProvider : IStorageProvider
    {
        /*********
        ** Fields
        *********/
        /// <summary>The API client settings.</summary>
        private readonly ApiClientsConfig ClientsConfig;

        /// <summary>The underlying Pastebin client.</summary>
        private readonly IPastebinClient Pastebin;

        /// <summary>The underlying text compression helper.</summary>
        private readonly IGzipHelper GzipHelper;

        /// <summary>Whether Azure blob storage is configured.</summary>
        private bool HasAzure => !string.IsNullOrWhiteSpace(this.ClientsConfig.AzureBlobConnectionString);

        /// <summary>The number of days since the blob's last-modified date when it will be deleted.</summary>
        private int ExpiryDays => this.ClientsConfig.AzureBlobTempExpiryDays;


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="clientsConfig">The API client settings.</param>
        /// <param name="pastebin">The underlying Pastebin client.</param>
        /// <param name="gzipHelper">The underlying text compression helper.</param>
        public StorageProvider(IOptions<ApiClientsConfig> clientsConfig, IPastebinClient pastebin, IGzipHelper gzipHelper)
        {
            this.ClientsConfig = clientsConfig.Value;
            this.Pastebin = pastebin;
            this.GzipHelper = gzipHelper;
        }

        /// <inheritdoc />
        public async Task<UploadResult> SaveAsync(string content, bool compress = true)
        {
            string id = Guid.NewGuid().ToString("N");

            // save to Azure
            if (this.HasAzure)
            {
                try
                {
                    using Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(content));
                    BlobClient blob = this.GetAzureBlobClient(id);
                    await blob.UploadAsync(stream);

                    return new UploadResult(true, id, null);
                }
                catch (Exception ex)
                {
                    return new UploadResult(false, null, ex.Message);
                }
            }

            // save to local filesystem for testing
            else
            {
                string path = this.GetDevFilePath(id);
                Directory.CreateDirectory(Path.GetDirectoryName(path));

                File.WriteAllText(path, content);
                return new UploadResult(true, id, null);
            }
        }

        /// <inheritdoc />
        public async Task<StoredFileInfo> GetAsync(string id, bool renew)
        {
            // fetch from blob storage
            if (Guid.TryParseExact(id, "N", out Guid _))
            {
                // Azure Blob storage
                if (this.HasAzure)
                {
                    try
                    {
                        // get client
                        BlobClient blob = this.GetAzureBlobClient(id);

                        // extend expiry
                        if (renew)
                            await blob.SetMetadataAsync(new Dictionary<string, string> { ["expiryRenewed"] = DateTime.UtcNow.ToString("O") }); // change the blob's last-modified date (the specific property set doesn't matter)

                        // fetch file
                        Response<BlobDownloadInfo> response = await blob.DownloadAsync();
                        using BlobDownloadInfo result = response.Value;
                        using StreamReader reader = new(result.Content);
                        DateTimeOffset expiry = result.Details.LastModified + TimeSpan.FromDays(this.ExpiryDays);
                        string content = this.GzipHelper.DecompressString(reader.ReadToEnd());

                        // build model
                        return new StoredFileInfo
                        {
                            Success = true,
                            Content = content,
                            Expiry = expiry.UtcDateTime
                        };
                    }
                    catch (RequestFailedException ex)
                    {
                        return new StoredFileInfo
                        {
                            Error = ex.ErrorCode == "BlobNotFound"
                                ? "There's no file with that ID."
                                : $"Could not fetch that file from storage ({ex.ErrorCode}: {ex.Message})."
                        };
                    }
                }

                // local filesystem for testing
                else
                {
                    // get file
                    FileInfo file = new(this.GetDevFilePath(id));
                    if (file.Exists && file.LastWriteTimeUtc.AddDays(this.ExpiryDays) < DateTime.UtcNow) // expired
                        file.Delete();
                    if (!file.Exists)
                    {
                        return new StoredFileInfo
                        {
                            Error = "There's no file with that ID."
                        };
                    }

                    // renew
                    if (renew)
                    {
                        File.SetLastWriteTimeUtc(file.FullName, DateTime.UtcNow);
                        file.Refresh();
                    }

                    // build model
                    return new StoredFileInfo
                    {
                        Success = true,
                        Content = File.ReadAllText(file.FullName),
                        Expiry = DateTime.UtcNow.AddDays(this.ExpiryDays),
                        Warning = "This file was saved temporarily to the local computer. This should only happen in a local development environment."
                    };
                }
            }

            // get from Pastebin
            else
            {
                PasteInfo response = await this.Pastebin.GetAsync(id);
                response.Content = this.GzipHelper.DecompressString(response.Content);
                return new StoredFileInfo
                {
                    Success = response.Success,
                    Content = response.Content,
                    Error = response.Error
                };
            }
        }

        /// <summary>Get a client for reading and writing to Azure Blob storage.</summary>
        /// <param name="id">The file ID.</param>
        private BlobClient GetAzureBlobClient(string id)
        {
            var azure = new BlobServiceClient(this.ClientsConfig.AzureBlobConnectionString);
            var container = azure.GetBlobContainerClient(this.ClientsConfig.AzureBlobTempContainer);
            return container.GetBlobClient($"uploads/{id}");
        }

        /// <summary>Get the absolute file path for an upload when running in a local test environment with no Azure account configured.</summary>
        /// <param name="id">The file ID.</param>
        private string GetDevFilePath(string id)
        {
            return Path.Combine(Path.GetTempPath(), "smapi-web-temp", $"{id}.txt");
        }
    }
}