-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathStorageFileApi.cs
534 lines (444 loc) · 23.5 KB
/
StorageFileApi.cs
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Supabase.Storage.Exceptions;
using Supabase.Storage.Extensions;
using Supabase.Storage.Interfaces;
using Supabase.Storage.Responses;
namespace Supabase.Storage
{
public class StorageFileApi : IStorageFileApi<FileObject>
{
public ClientOptions Options { get; protected set; }
protected string Url { get; set; }
protected Dictionary<string, string> Headers { get; set; }
protected string? BucketId { get; set; }
public StorageFileApi(string url, string bucketId, ClientOptions? options,
Dictionary<string, string>? headers = null) : this(url, headers, bucketId)
{
Options = options ?? new ClientOptions();
}
public StorageFileApi(string url, Dictionary<string, string>? headers = null, string? bucketId = null)
{
Url = url;
BucketId = bucketId;
Options ??= new ClientOptions();
Headers = headers ?? new Dictionary<string, string>();
}
/// <summary>
/// A simple convenience function to get the URL for an asset in a public bucket.If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
/// This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
/// </summary>
/// <param name="path"></param>
/// <param name="transformOptions"></param>
/// <param name="downloadOptions"></param>
/// <returns></returns>
public string GetPublicUrl(string path, TransformOptions? transformOptions, DownloadOptions? downloadOptions = null)
{
var queryParams = HttpUtility.ParseQueryString(string.Empty);
if (downloadOptions != null)
queryParams.Add(downloadOptions.ToQueryCollection());
if (transformOptions == null)
{
var queryParamsString = queryParams.ToString();
return $"{Url}/object/public/{GetFinalPath(path)}?{queryParamsString}";
}
queryParams.Add(transformOptions.ToQueryCollection());
var builder = new UriBuilder($"{Url}/render/image/public/{GetFinalPath(path)}")
{
Query = queryParams.ToString()
};
return builder.ToString();
}
/// <summary>
/// Create signed url to download file without requiring permissions. This URL can be valid for a set number of seconds.
/// </summary>
/// <param name="path">The file path to be downloaded, including the current file name. For example `folder/image.png`.</param>
/// <param name="expiresIn">The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.</param>
/// <param name="transformOptions"></param>
/// <param name="downloadOptions"></param>
/// <returns></returns>
public async Task<string> CreateSignedUrl(string path, int expiresIn, TransformOptions? transformOptions = null, DownloadOptions? downloadOptions = null)
{
var body = new Dictionary<string, object?> { { "expiresIn", expiresIn } };
var url = $"{Url}/object/sign/{GetFinalPath(path)}";
if (transformOptions != null)
{
var transformOptionsJson = JsonConvert.SerializeObject(transformOptions, new StringEnumConverter());
var transformOptionsObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(transformOptionsJson);
body.Add("transform", transformOptionsObj);
}
var response = await Helpers.MakeRequest<CreateSignedUrlResponse>(HttpMethod.Post, url, body, Headers);
if (response == null || string.IsNullOrEmpty(response.SignedUrl))
throw new SupabaseStorageException(
$"Signed Url for {path} returned empty, do you have permission?");
var downloadQueryParams = downloadOptions?.ToQueryCollection().ToString();
return $"{Url}{response.SignedUrl}?{downloadQueryParams}";
}
/// <summary>
/// Create signed URLs to download files without requiring permissions. These URLs can be valid for a set number of seconds.
/// </summary>
/// <param name="paths">paths The file paths to be downloaded, including the current file names. For example [`folder/image.png`, 'folder2/image2.png'].</param>
/// <param name="expiresIn">The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.</param>
/// <param name="downloadOptions"></param>
/// <returns></returns>
public async Task<List<CreateSignedUrlsResponse>?> CreateSignedUrls(List<string> paths, int expiresIn, DownloadOptions? downloadOptions = null)
{
var body = new Dictionary<string, object> { { "expiresIn", expiresIn }, { "paths", paths } };
var response = await Helpers.MakeRequest<List<CreateSignedUrlsResponse>>(HttpMethod.Post,
$"{Url}/object/sign/{BucketId}", body, Headers);
var downloadQueryParams = downloadOptions?.ToQueryCollection().ToString();
if (response != null)
{
foreach (var item in response)
{
if (string.IsNullOrEmpty(item.SignedUrl))
throw new SupabaseStorageException(
$"Signed Url for {item.Path} returned empty, do you have permission?");
item.SignedUrl = $"{Url}{item.SignedUrl}?{downloadQueryParams}";
}
}
return response;
}
/// <summary>
/// Lists all the files within a bucket.
/// </summary>
/// <param name="path"></param>
/// <param name="options"></param>
/// <returns></returns>
public async Task<List<FileObject>?> List(string path = "", SearchOptions? options = null)
{
options ??= new SearchOptions();
var json = JsonConvert.SerializeObject(options);
var body = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
if (body != null)
body.Add("prefix", string.IsNullOrEmpty(path) ? "" : path);
var response =
await Helpers.MakeRequest<List<FileObject>>(HttpMethod.Post, $"{Url}/object/list/{BucketId}", body,
Headers);
return response;
}
/// <summary>
/// Uploads a file to an existing bucket.
/// </summary>
/// <param name="localFilePath">File Source Path</param>
/// <param name="supabasePath">The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.</param>
/// <param name="options"></param>
/// <param name="onProgress"></param>
/// <param name="inferContentType"></param>
/// <returns></returns>
public async Task<string> Upload(string localFilePath, string supabasePath, FileOptions? options = null,
EventHandler<float>? onProgress = null, bool inferContentType = true)
{
options ??= new FileOptions();
if (inferContentType)
options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(localFilePath);
var result = await UploadOrUpdate(localFilePath, supabasePath, options, onProgress);
return result;
}
/// <summary>
/// Uploads a byte array to an existing bucket.
/// </summary>
/// <param name="data"></param>
/// <param name="supabasePath">The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.</param>
/// <param name="options"></param>
/// <param name="onProgress"></param>
/// <param name="inferContentType"></param>
/// <returns></returns>
public async Task<string> Upload(byte[] data, string supabasePath, FileOptions? options = null,
EventHandler<float>? onProgress = null, bool inferContentType = true)
{
options ??= new FileOptions();
if (inferContentType)
options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(supabasePath);
var result = await UploadOrUpdate(data, supabasePath, options, onProgress);
return result;
}
/// <summary>
/// Uploads a file to using a pre-generated Signed Upload Url
/// </summary>
/// <param name="localFilePath">File Source Path</param>
/// <param name="signedUrl"></param>
/// <param name="options"></param>
/// <param name="onProgress"></param>
/// <param name="inferContentType"></param>
/// <returns></returns>
public async Task<string> UploadToSignedUrl(string localFilePath, UploadSignedUrl signedUrl,
FileOptions? options = null, EventHandler<float>? onProgress = null, bool inferContentType = true)
{
options ??= new FileOptions();
if (inferContentType)
options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(localFilePath);
var headers = new Dictionary<string, string>(Headers)
{
["Authorization"] = $"Bearer {signedUrl.Token}",
["cache-control"] = $"max-age={options.CacheControl}",
["content-type"] = options.ContentType
};
if (options.Upsert)
headers.Add("x-upsert", options.Upsert.ToString().ToLower());
var progress = new Progress<float>();
if (onProgress != null)
progress.ProgressChanged += onProgress;
await Helpers.HttpUploadClient!.UploadFileAsync(signedUrl.SignedUrl, localFilePath, headers, progress);
return GetFinalPath(signedUrl.Key);
}
/// <summary>
/// Uploads a byte array using a pre-generated Signed Upload Url
/// </summary>
/// <param name="data"></param>
/// <param name="signedUrl"></param>
/// <param name="options"></param>
/// <param name="onProgress"></param>
/// <param name="inferContentType"></param>
/// <returns></returns>
public async Task<string> UploadToSignedUrl(byte[] data, UploadSignedUrl signedUrl, FileOptions? options = null,
EventHandler<float>? onProgress = null, bool inferContentType = true)
{
options ??= new FileOptions();
if (inferContentType)
options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(signedUrl.Key);
var headers = new Dictionary<string, string>(Headers)
{
["Authorization"] = $"Bearer {signedUrl.Token}",
["cache-control"] = $"max-age={options.CacheControl}",
["content-type"] = options.ContentType
};
if (options.Upsert)
headers.Add("x-upsert", options.Upsert.ToString().ToLower());
var progress = new Progress<float>();
if (onProgress != null)
progress.ProgressChanged += onProgress;
await Helpers.HttpUploadClient!.UploadBytesAsync(signedUrl.SignedUrl, data, headers, progress);
return GetFinalPath(signedUrl.Key);
}
/// <summary>
/// Replaces an existing file at the specified path with a new one.
/// </summary>
/// <param name="localFilePath">File source path.</param>
/// <param name="supabasePath">The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.</param>
/// <param name="options">HTTP headers.</param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<string> Update(string localFilePath, string supabasePath, FileOptions? options = null,
EventHandler<float>? onProgress = null)
{
options ??= new FileOptions();
return UploadOrUpdate(localFilePath, supabasePath, options, onProgress);
}
/// <summary>
/// Replaces an existing file at the specified path with a new one.
/// </summary>
/// <param name="data"></param>
/// <param name="supabasePath">The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.</param>
/// <param name="options">HTTP headers.</param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<string> Update(byte[] data, string supabasePath, FileOptions? options = null,
EventHandler<float>? onProgress = null)
{
options ??= new FileOptions();
return UploadOrUpdate(data, supabasePath, options, onProgress);
}
/// <summary>
/// Moves an existing file, optionally renaming it at the same time.
/// </summary>
/// <param name="fromPath">The original file path, including the current file name. For example `folder/image.png`.</param>
/// <param name="toPath">The new file path, including the new file name. For example `folder/image-copy.png`.</param>
/// <returns></returns>
public async Task<bool> Move(string fromPath, string toPath)
{
var body = new Dictionary<string, string?>
{
{ "bucketId", BucketId },
{ "sourceKey", fromPath },
{ "destinationKey", toPath }
};
await Helpers.MakeRequest<GenericResponse>(HttpMethod.Post, $"{Url}/object/move", body, Headers);
return true;
}
/// <summary>
/// Downloads a file from a private bucket. For public buckets, use <see cref="DownloadPublicFile(string, string, TransformOptions?, EventHandler{float}?)"/>
/// </summary>
/// <param name="supabasePath"></param>
/// <param name="localPath"></param>
/// <param name="transformOptions"></param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<string> Download(string supabasePath, string localPath, TransformOptions? transformOptions = null,
EventHandler<float>? onProgress = null)
{
var url = transformOptions != null
? $"{Url}/render/image/authenticated/{GetFinalPath(supabasePath)}"
: $"{Url}/object/{GetFinalPath(supabasePath)}";
return DownloadFile(url, localPath, transformOptions, onProgress);
}
/// <summary>
/// Downloads a file from a private bucket. For public buckets, use <see cref="DownloadPublicFile(string, string, TransformOptions?, EventHandler{float}?)"/>
/// </summary>
/// <param name="supabasePath"></param>
/// <param name="localPath"></param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<string> Download(string supabasePath, string localPath, EventHandler<float>? onProgress = null) =>
Download(supabasePath, localPath, null, onProgress: onProgress);
/// <summary>
/// Downloads a byte array from a private bucket to be used programmatically. For public buckets <see cref="DownloadPublicFile(string, TransformOptions?, EventHandler{float}?)"/>
/// </summary>
/// <param name="supabasePath"></param>
/// <param name="transformOptions"></param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<byte[]> Download(string supabasePath, TransformOptions? transformOptions = null,
EventHandler<float>? onProgress = null)
{
var url = $"{Url}/object/{GetFinalPath(supabasePath)}";
return DownloadBytes(url, transformOptions, onProgress);
}
/// <summary>
/// Downloads a byte array from a private bucket to be used programmatically. For public buckets <see cref="DownloadPublicFile(string, TransformOptions?, EventHandler{float}?)"/>
/// </summary>
/// <param name="supabasePath"></param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<byte[]> Download(string supabasePath, EventHandler<float>? onProgress = null) =>
Download(supabasePath, transformOptions: null, onProgress: onProgress);
/// <summary>
/// Downloads a public file to the filesystem. This method DOES NOT VERIFY that the file is actually public.
/// </summary>
/// <param name="supabasePath"></param>
/// <param name="localPath"></param>
/// <param name="transformOptions"></param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<string> DownloadPublicFile(string supabasePath, string localPath,
TransformOptions? transformOptions = null, EventHandler<float>? onProgress = null)
{
var url = GetPublicUrl(supabasePath, transformOptions);
return DownloadFile(url, localPath, transformOptions, onProgress);
}
/// <summary>
/// Downloads a byte array from a private bucket to be used programmatically. This method DOES NOT VERIFY that the file is actually public.
/// </summary>
/// <param name="supabasePath"></param>
/// <param name="transformOptions"></param>
/// <param name="onProgress"></param>
/// <returns></returns>
public Task<byte[]> DownloadPublicFile(string supabasePath, TransformOptions? transformOptions = null,
EventHandler<float>? onProgress = null)
{
var url = GetPublicUrl(supabasePath, transformOptions);
return DownloadBytes(url, transformOptions, onProgress);
}
/// <summary>
/// Deletes file within the same bucket
/// </summary>
/// <param name="path">A path to delete, for example `folder/image.png`.</param>
/// <returns></returns>
public async Task<FileObject?> Remove(string path)
{
var result = await Remove(new List<string> { path });
return result?.FirstOrDefault();
}
/// <summary>
/// Deletes files within the same bucket
/// </summary>
/// <param name="paths">An array of files to be deletes, including the path and file name. For example [`folder/image.png`].</param>
/// <returns></returns>
public async Task<List<FileObject>?> Remove(List<string> paths)
{
var data = new Dictionary<string, object> { { "prefixes", paths } };
var response =
await Helpers.MakeRequest<List<FileObject>>(HttpMethod.Delete, $"{Url}/object/{BucketId}", data,
Headers);
return response;
}
/// <summary>
/// Creates an upload signed URL. Use it to upload a file straight to the bucket without credentials
/// </summary>
/// <param name="supabasePath">The file path, including the current file name. For example `folder/image.png`.</param>
/// <returns></returns>
public async Task<UploadSignedUrl> CreateUploadSignedUrl(string supabasePath)
{
var path = GetFinalPath(supabasePath);
var url = $"{Url}/object/upload/sign/{path}";
var response =
await Helpers.MakeRequest<CreatedUploadSignedUrlResponse>(HttpMethod.Post, url, null, Headers);
if (response == null || string.IsNullOrEmpty(response.Url) || !response.Url!.Contains("token"))
throw new SupabaseStorageException(
"Response did not return with expected data. Does this token have proper permission to generate a url?");
var generatedUri = new Uri($"{Url}{response.Url}");
var query = HttpUtility.ParseQueryString(generatedUri.Query);
var token = query["token"];
return new UploadSignedUrl(generatedUri, token, supabasePath);
}
private async Task<string> UploadOrUpdate(string localPath, string supabasePath, FileOptions options,
EventHandler<float>? onProgress = null)
{
Uri uri = new Uri($"{Url}/object/{GetFinalPath(supabasePath)}");
var headers = new Dictionary<string, string>(Headers)
{
{ "cache-control", $"max-age={options.CacheControl}" },
{ "content-type", options.ContentType }
};
if (options.Upsert)
headers.Add("x-upsert", options.Upsert.ToString().ToLower());
var progress = new Progress<float>();
if (onProgress != null)
progress.ProgressChanged += onProgress;
await Helpers.HttpUploadClient!.UploadFileAsync(uri, localPath, headers, progress);
return GetFinalPath(supabasePath);
}
private async Task<string> UploadOrUpdate(byte[] data, string supabasePath, FileOptions options,
EventHandler<float>? onProgress = null)
{
Uri uri = new Uri($"{Url}/object/{GetFinalPath(supabasePath)}");
var headers = new Dictionary<string, string>(Headers)
{
{ "cache-control", $"max-age={options.CacheControl}" },
{ "content-type", options.ContentType }
};
if (options.Upsert)
headers.Add("x-upsert", options.Upsert.ToString().ToLower());
var progress = new Progress<float>();
if (onProgress != null)
progress.ProgressChanged += onProgress;
await Helpers.HttpUploadClient!.UploadBytesAsync(uri, data, headers, progress);
return GetFinalPath(supabasePath);
}
private async Task<string> DownloadFile(string url, string localPath, TransformOptions? transformOptions = null,
EventHandler<float>? onProgress = null)
{
var builder = new UriBuilder(url);
var progress = new Progress<float>();
if (transformOptions != null)
builder.Query = transformOptions.ToQueryCollection().ToString();
if (onProgress != null)
progress.ProgressChanged += onProgress;
var stream = await Helpers.HttpDownloadClient!.DownloadDataAsync(builder.Uri, Headers, progress);
using var fileStream = new FileStream(localPath, FileMode.OpenOrCreate, FileAccess.Write);
stream.WriteTo(fileStream);
return localPath;
}
private async Task<byte[]> DownloadBytes(string url, TransformOptions? transformOptions = null,
EventHandler<float>? onProgress = null)
{
var builder = new UriBuilder(url);
var progress = new Progress<float>();
if (transformOptions != null)
builder.Query = transformOptions.ToQueryCollection().ToString();
if (onProgress != null)
progress.ProgressChanged += onProgress;
var stream = await Helpers.HttpDownloadClient!.DownloadDataAsync(builder.Uri, Headers, progress);
return stream.ToArray();
}
private string GetFinalPath(string path) => $"{BucketId}/{path}";
}
}