-
Notifications
You must be signed in to change notification settings - Fork 32
/
Files.cs
462 lines (402 loc) · 21 KB
/
Files.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
using System;
using B2Net.Http;
using B2Net.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace B2Net {
public class Files : IFiles {
private B2Options _options;
private HttpClient _client;
private string _api = "Files";
public Files(B2Options options) {
_options = options;
_client = HttpClientFactory.CreateHttpClient(options.RequestTimeout);
}
/// <summary>
/// Lists the names of all non-hidden files in a bucket, starting at a given name.
/// </summary>
/// <param name="bucketId"></param>
/// <param name="startFileName"></param>
/// <param name="maxFileCount"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2FileList> GetList(string startFileName = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)) {
return await GetListWithPrefixOrDemiliter(startFileName, "", "", maxFileCount, bucketId, cancelToken);
}
/// <summary>
/// BETA: Lists the names of all non-hidden files in a bucket, starting at a given name. With an optional file prefix or delimiter.
/// See here for more details: https://www.backblaze.com/b2/docs/b2_list_file_names.html
/// </summary>
/// <param name="startFileName"></param>
/// <param name="prefix"></param>
/// <param name="delimiter"></param>
/// <param name="maxFileCount"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2FileList> GetListWithPrefixOrDemiliter(string startFileName = "", string prefix = "", string delimiter = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)) {
var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId);
var requestMessage = FileMetaDataRequestGenerators.GetList(_options, operationalBucketId, startFileName, maxFileCount, prefix, delimiter);
var response = await _client.SendAsync(requestMessage, cancelToken);
return await ResponseParser.ParseResponse<B2FileList>(response, _api);
}
/// <summary>
/// Lists all of the versions of all of the files contained in one bucket,
/// in alphabetical order by file name, and by reverse of date/time uploaded
/// for versions of files with the same name.
/// </summary>
/// <param name="startFileName"></param>
/// <param name="startFileId"></param>
/// <param name="maxFileCount"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2FileList> GetVersions(string startFileName = "", string startFileId = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)) {
return await GetVersionsWithPrefixOrDelimiter(startFileName, startFileId, "", "", maxFileCount, bucketId, cancelToken);
}
/// <summary>
/// BETA: Lists all of the versions of all of the files contained in one bucket,
/// in alphabetical order by file name, and by reverse of date/time uploaded
/// for versions of files with the same name. With an optional file prefix or delimiter.
/// See here for more details: https://www.backblaze.com/b2/docs/b2_list_file_versions.html
/// </summary>
/// <param name="startFileName"></param>
/// <param name="startFileId"></param>
/// <param name="prefix"></param>
/// <param name="delimiter"></param>
/// <param name="maxFileCount"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2FileList> GetVersionsWithPrefixOrDelimiter(string startFileName = "", string startFileId = "", string prefix = "", string delimiter = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)) {
var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId);
var requestMessage = FileMetaDataRequestGenerators.ListVersions(_options, operationalBucketId, startFileName, startFileId, maxFileCount, prefix, delimiter);
var response = await _client.SendAsync(requestMessage, cancelToken);
return await ResponseParser.ParseResponse<B2FileList>(response, _api);
}
/// <summary>
/// Gets information about one file stored in B2.
/// </summary>
/// <param name="fileId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> GetInfo(string fileId, CancellationToken cancelToken = default(CancellationToken)) {
var requestMessage = FileMetaDataRequestGenerators.GetInfo(_options, fileId);
var response = await _client.SendAsync(requestMessage, cancelToken);
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// get an upload url for use with one Thread.
/// </summary>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2UploadUrl> GetUploadUrl(string bucketId = "", CancellationToken cancelToken = default(CancellationToken)) {
var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId);
// send the request.
var uploadUrlRequest = FileUploadRequestGenerators.GetUploadUrl(_options, operationalBucketId);
var uploadUrlResponse = await _client.SendAsync(uploadUrlRequest, cancelToken);
// parse response and return it.
var uploadUrl = await ResponseParser.ParseResponse<B2UploadUrl>(uploadUrlResponse);
// Set the upload auth token
_options.UploadAuthorizationToken = uploadUrl.AuthorizationToken;
return uploadUrl;
}
/// <summary>
/// DEPRECATED: This method has been deprecated in favor of the Upload that takes an UploadUrl parameter.
/// The other Upload method is the preferred, and more efficient way, of uploading to B2.
/// </summary>
/// <param name="fileData"></param>
/// <param name="fileName"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Upload(byte[] fileData, string fileName, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)) {
var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId);
// Get the upload url for this file
var uploadUrlRequest = FileUploadRequestGenerators.GetUploadUrl(_options, operationalBucketId);
var uploadUrlResponse = await _client.SendAsync(uploadUrlRequest, cancelToken);
var uploadUrlData = await uploadUrlResponse.Content.ReadAsStringAsync();
var uploadUrlObject = JsonConvert.DeserializeObject<B2UploadUrl>(uploadUrlData);
// Set the upload auth token
_options.UploadAuthorizationToken = uploadUrlObject.AuthorizationToken;
// Now we can upload the file
var requestMessage = FileUploadRequestGenerators.Upload(_options, uploadUrlObject.UploadUrl, fileData, fileName, fileInfo);
var response = await _client.SendAsync(requestMessage, cancelToken);
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// Uploads one file to B2, returning its unique file ID. Filename will be URL Encoded.
/// </summary>
/// <param name="fileData"></param>
/// <param name="fileName"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)) {
return await Upload(fileData, fileName, uploadUrl, "", false, bucketId, fileInfo, cancelToken);
}
/// <summary>
/// Uploads one file to B2, returning its unique file ID. Filename will be URL Encoded. If auto retry
/// is set true it will retry a failed upload once after 1 second.
/// </summary>
/// <param name="fileData"></param>
/// <param name="fileName"></param>
/// <param name="uploadUrl"></param>
/// <param name="bucketId"></param>
/// <param name="autoRetry">Retry a failed upload one time after waiting for 1 second.</param>
/// <param name="fileInfo"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, bool autoRetry, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)) {
return await Upload(fileData, fileName, uploadUrl, "", autoRetry, bucketId, fileInfo, cancelToken);
}
/// <summary>
/// Uploads one file to B2, returning its unique file ID. Filename will be URL Encoded. If auto retry
/// is set true it will retry a failed upload once after 1 second.
/// </summary>
/// <param name="fileData"></param>
/// <param name="fileName"></param>
/// <param name="uploadUrl"></param>
/// <param name="bucketId"></param>
/// <param name="contentType"></param>
/// <param name="autoRetry">Retry a failed upload one time after waiting for 1 second.</param>
/// <param name="fileInfo"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, string contentType, bool autoRetry, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)) {
// Now we can upload the file
var requestMessage = FileUploadRequestGenerators.Upload(_options, uploadUrl.UploadUrl, fileData, fileName, fileInfo, contentType);
var response = await _client.SendAsync(requestMessage, cancelToken);
// Auto retry
if (autoRetry && (
response.StatusCode == (HttpStatusCode)429 ||
response.StatusCode == HttpStatusCode.RequestTimeout ||
response.StatusCode == HttpStatusCode.ServiceUnavailable)) {
Task.Delay(1000, cancelToken).Wait(cancelToken);
var retryMessage = FileUploadRequestGenerators.Upload(_options, uploadUrl.UploadUrl, fileData, fileName, fileInfo, contentType);
response = await _client.SendAsync(retryMessage, cancelToken);
}
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// Uploads one file to B2 using a stream, returning its unique file ID. Filename will be URL Encoded. If auto retry
/// is set true it will retry a failed upload once after 1 second. If you don't want to use a SHA1 for the stream set dontSHA.
/// </summary>
/// <param name="fileDataWithSHA"></param>
/// <param name="fileName"></param>
/// <param name="uploadUrl"></param>
/// <param name="contentType"></param>
/// <param name="autoRetry"></param>
/// <param name="bucketId"></param>
/// <param name="fileInfo"></param>
/// <param name="dontSHA"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Upload(Stream fileDataWithSHA, string fileName, B2UploadUrl uploadUrl, string contentType, bool autoRetry, string bucketId = "", Dictionary<string, string> fileInfo = null, bool dontSHA = false, CancellationToken cancelToken = default(CancellationToken)) {
// Now we can upload the file
var requestMessage = FileUploadRequestGenerators.Upload(_options, uploadUrl.UploadUrl, fileDataWithSHA, fileName, fileInfo, contentType, dontSHA);
var response = await _client.SendAsync(requestMessage, cancelToken);
// Auto retry
if (autoRetry && (
response.StatusCode == (HttpStatusCode)429 ||
response.StatusCode == HttpStatusCode.RequestTimeout ||
response.StatusCode == HttpStatusCode.ServiceUnavailable)) {
Task.Delay(1000, cancelToken).Wait(cancelToken);
var retryMessage = FileUploadRequestGenerators.Upload(_options, uploadUrl.UploadUrl, fileDataWithSHA, fileName, fileInfo, contentType, dontSHA);
response = await _client.SendAsync(retryMessage, cancelToken);
}
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// Downloads a file part by providing the name of the bucket and the name and byte range of the file.
/// For use with the Larg File API.
/// </summary>
/// <param name="fileName"></param>
/// <param name="bucketName"></param>
/// <param name="startBytes"></param>
/// <param name="endBytes"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> DownloadByName(string fileName, string bucketName, int startByte, int endByte,
CancellationToken cancelToken = default(CancellationToken)) {
// Are we searching by name or id?
HttpRequestMessage request;
request = FileDownloadRequestGenerators.DownloadByName(_options, bucketName, fileName, $"{startByte}-{endByte}");
// Send the download request
var response = await _client.SendAsync(request, cancelToken);
// Create B2File from response
return await ParseDownloadResponse(response);
}
/// <summary>
/// Downloads one file by providing the name of the bucket and the name of the file.
/// </summary>
/// <param name="fileId"></param>
/// <param name="fileName"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> DownloadByName(string fileName, string bucketName, CancellationToken cancelToken = default(CancellationToken)) {
// Are we searching by name or id?
HttpRequestMessage request;
request = FileDownloadRequestGenerators.DownloadByName(_options, bucketName, fileName);
// Send the download request
var response = await _client.SendAsync(request, cancelToken);
// Create B2File from response
return await ParseDownloadResponse(response);
}
/// <summary>
/// Downloads a file from B2 using the byte range specified. For use with the Large File API.
/// </summary>
/// <param name="fileId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> DownloadById(string fileId, int startByte, int endByte, CancellationToken cancelToken = default(CancellationToken)) {
// Are we searching by name or id?
HttpRequestMessage request;
request = FileDownloadRequestGenerators.DownloadById(_options, fileId, $"{startByte}-{endByte}");
// Send the download request
var response = await _client.SendAsync(request, cancelToken);
// Create B2File from response
return await ParseDownloadResponse(response);
}
/// <summary>
/// Downloads one file from B2.
/// </summary>
/// <param name="fileId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> DownloadById(string fileId, CancellationToken cancelToken = default(CancellationToken)) {
// Are we searching by name or id?
HttpRequestMessage request;
request = FileDownloadRequestGenerators.DownloadById(_options, fileId);
// Send the download request
var response = await _client.SendAsync(request, cancelToken);
// Create B2File from response
return await ParseDownloadResponse(response);
}
/// <summary>
/// Deletes the specified file version
/// </summary>
/// <param name="fileId"></param>
/// <param name="fileName"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Delete(string fileId, string fileName, CancellationToken cancelToken = default(CancellationToken)) {
var requestMessage = FileDeleteRequestGenerator.Delete(_options, fileId, fileName);
var response = await _client.SendAsync(requestMessage, cancelToken);
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// EXPERIMENTAL: This functionality is not officially part of the Backblaze B2 API and may change or break at any time.
/// This will return a friendly URL that can be shared to download the file. This depends on the Bucket that the file resides
/// in to be allPublic.
/// </summary>
/// <param name="fileName"></param>
/// <param name="bucketName"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public string GetFriendlyDownloadUrl(string fileName, string bucketName, CancellationToken cancelToken = default(CancellationToken)) {
var downloadUrl = _options.DownloadUrl;
var friendlyUrl = "";
if (!string.IsNullOrEmpty(downloadUrl)) {
friendlyUrl = $"{downloadUrl}/file/{bucketName}/{fileName}";
}
return friendlyUrl;
}
/// <summary>
/// Hides or Unhides a file so that downloading by name will not find the file,
/// but previous versions of the file are still stored. See File
/// Versions about what it means to hide a file.
/// </summary>
/// <param name="fileName"></param>
/// <param name="bucketId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Hide(string fileName, string bucketId = "", string fileId = "", CancellationToken cancelToken = default(CancellationToken)) {
var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId);
var requestMessage = FileMetaDataRequestGenerators.HideFile(_options, operationalBucketId, fileName, fileId);
var response = await _client.SendAsync(requestMessage, cancelToken);
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// Copy or Replace a file stored in B2. This will copy the file on B2's servers, resulting in no download or upload charges.
/// </summary>
/// <param name="sourceFileId"></param>
/// <param name="newFileName"></param>
/// <param name="metadataDirective">COPY or REPLACE. COPY will not allow any changes to File Info or Content Type. REPLACE will.</param>
/// <param name="contentType"></param>
/// <param name="fileInfo"></param>
/// <param name="range">byte range to copy.</param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2File> Copy(string sourceFileId, string newFileName,
B2MetadataDirective metadataDirective = B2MetadataDirective.COPY, string contentType = "",
Dictionary<string, string> fileInfo = null, string range = "", string destinationBucketId = "",
CancellationToken cancelToken = default(CancellationToken)) {
if (metadataDirective == B2MetadataDirective.COPY && (!string.IsNullOrWhiteSpace(contentType) || fileInfo != null)) {
throw new CopyReplaceSetupException("Copy operations cannot specify fileInfo or contentType.");
}
if (metadataDirective == B2MetadataDirective.REPLACE &&
(string.IsNullOrWhiteSpace(contentType) || fileInfo == null)) {
throw new CopyReplaceSetupException("Replace operations must specify fileInfo and contentType.");
}
var request = FileCopyRequestGenerators.Copy(_options, sourceFileId, newFileName, metadataDirective, contentType, fileInfo, range, destinationBucketId);
// Send the download request
var response = await _client.SendAsync(request, cancelToken);
// Create B2File from response
return await ResponseParser.ParseResponse<B2File>(response, _api);
}
/// <summary>
/// Downloads one file from B2.
/// </summary>
/// <param name="fileId"></param>
/// <param name="cancelToken"></param>
/// <returns></returns>
public async Task<B2DownloadAuthorization> GetDownloadAuthorization(string fileNamePrefix, int validDurationInSeconds, string bucketId = "", string b2ContentDisposition = "", CancellationToken cancelToken = default(CancellationToken)) {
var operationalBucketId = Utilities.DetermineBucketId(_options, bucketId);
var request = FileDownloadRequestGenerators.GetDownloadAuthorization(_options, fileNamePrefix, validDurationInSeconds, operationalBucketId, b2ContentDisposition);
// Send the download request
var response = await _client.SendAsync(request, cancelToken);
// Create B2File from response
return await ResponseParser.ParseResponse<B2DownloadAuthorization>(response, _api);
}
private async Task<B2File> ParseDownloadResponse(HttpResponseMessage response) {
await Utilities.CheckForErrors(response, _api);
var file = new B2File();
IEnumerable<string> values;
if (response.Headers.TryGetValues("X-Bz-Content-Sha1", out values)) {
file.ContentSHA1 = values.First();
}
if (response.Headers.TryGetValues("X-Bz-File-Name", out values)) {
file.FileName = values.First();
// Decode file name
file.FileName = file.FileName.b2UrlDecode();
}
if (response.Headers.TryGetValues("X-Bz-File-Id", out values)) {
file.FileId = values.First();
}
// File Info Headers
var fileInfoHeaders = response.Headers.Where(h => h.Key.ToLower().Contains("x-bz-info"));
var infoData = new Dictionary<string, string>();
if (fileInfoHeaders.Count() > 0) {
foreach (var fileInfo in fileInfoHeaders) {
// Substring to parse out the file info prefix.
infoData.Add(fileInfo.Key.Substring(10), fileInfo.Value.First());
}
}
file.FileInfo = infoData;
if (response.Content.Headers.ContentLength.HasValue) {
file.Size = response.Content.Headers.ContentLength.Value;
}
file.FileData = await response.Content.ReadAsByteArrayAsync();
return await Task.FromResult(file);
}
}
}