-
Notifications
You must be signed in to change notification settings - Fork 163
/
BoxFilesManager.cs
1414 lines (1195 loc) · 69.1 KB
/
BoxFilesManager.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Box.V2.Auth;
using Box.V2.Config;
using Box.V2.Converter;
using Box.V2.Exceptions;
using Box.V2.Extensions;
using Box.V2.Models;
using Box.V2.Models.Request;
using Box.V2.Request;
using Box.V2.Services;
using Box.V2.Utility;
using Newtonsoft.Json.Linq;
namespace Box.V2.Managers
{
/// <summary>
/// File objects represent that metadata about individual files in Box, with attributes describing who created the file,
/// when it was last modified, and other information.
/// </summary>
public class BoxFilesManager : BoxResourceManager, IBoxFilesManager
{
public BoxFilesManager(IBoxConfig config, IBoxService service, IBoxConverter converter, IAuthRepository auth, string asUser = null, bool? suppressNotifications = null)
: base(config, service, converter, auth, asUser, suppressNotifications) { }
/// <summary>
/// Retrieves information about a file.
/// </summary>
/// <param name="id">Id of the file.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="sharedLink">The shared link for this file</param>
/// <param name="sharedLinkPassword">The password for the shared link (if required)</param>
/// <returns>A full file object is returned if the ID is valid and if the user has access to the file.</returns>
public async Task<BoxFile> GetInformationAsync(string id, IEnumerable<string> fields = null, string sharedLink = null, string sharedLinkPassword = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, id)
.Param(ParamFields, fields);
if (!string.IsNullOrEmpty(sharedLink))
{
var sharedLinkHeader = SharedLinkUtils.GetSharedLinkHeader(sharedLink, sharedLinkPassword);
request.Header(sharedLinkHeader.Item1, sharedLinkHeader.Item2);
}
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Returns the stream of the requested file.
/// </summary>
/// <param name="id">Id of the file to download.</param>
/// <param name="versionId">The ID specific version of this file to download.</param>
/// <param name="timeout">Optional timeout for response.</param>
/// <param name="startOffsetInBytes">Starting byte of the chunk to download.</param>
/// <param name="endOffsetInBytes">Ending byte of the chunk to download.</param>
/// <param name="sharedLink">The shared link for this file</param>
/// <param name="sharedLinkPassword">The password for the shared link (if required)</param>
/// <returns>Stream of the requested file.</returns>
public async Task<Stream> DownloadAsync(string id, string versionId = null, TimeSpan? timeout = null, long? startOffsetInBytes = null, long? endOffsetInBytes = null, string sharedLink = null, string sharedLinkPassword = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ContentPathString, id)) { Timeout = timeout }
.Param("version", versionId);
if (startOffsetInBytes.HasValue && endOffsetInBytes.HasValue)
{
request = request.Header("Range", $"bytes={startOffsetInBytes}-{endOffsetInBytes}");
}
if (!string.IsNullOrEmpty(sharedLink))
{
var sharedLinkHeader = SharedLinkUtils.GetSharedLinkHeader(sharedLink, sharedLinkPassword);
request.Header(sharedLinkHeader.Item1, sharedLinkHeader.Item2);
}
IBoxResponse<Stream> response = await ToResponseAsync<Stream>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Retrieves the temporary direct Uri to a file (valid for 15 minutes). This is typically used to send as a redirect to a browser to make the browser download the file directly from Box.
/// </summary>
/// <param name="id">Id of the file.</param>
/// <param name="versionId">Version of the file.</param>
/// <returns></returns>
public async Task<Uri> GetDownloadUriAsync(string id, string versionId = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ContentPathString, id)) { FollowRedirect = false }
.Param("version", versionId);
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
var locationUri = response.Headers.Location;
return locationUri;
}
/// <summary>
/// Verify that a file will be accepted by Box before you send all the bytes over the wire.
/// </summary>
/// <remarks>
/// Preflight checks verify all permissions as if the file was actually uploaded including:
/// Folder upload permission
/// File name collisions
/// file size caps
/// folder and file name restrictions*
/// folder and account storage quota
/// </remarks>
/// <param name="preflightCheckRequest">BoxPreflightCheckRequest object.</param>
/// <returns>Returns a BoxPreflightCheck object if successful, otherwise an error is thrown when any of the preflight conditions are not met.</returns>
public async Task<BoxPreflightCheck> PreflightCheck(BoxPreflightCheckRequest preflightCheckRequest)
{
preflightCheckRequest.ThrowIfNull("preflightCheckRequest")
.Name.ThrowIfNullOrWhiteSpace("preflightCheckRequest.Name");
preflightCheckRequest.Parent.ThrowIfNull("preflightCheckRequest.Parent")
.Id.ThrowIfNullOrWhiteSpace("preflightCheckRequest.Parent.Id");
BoxRequest request = new BoxRequest(_config.FilesPreflightCheckUri)
.Method(RequestMethod.Options);
request.Payload = _converter.Serialize(preflightCheckRequest);
request.ContentType = Constants.RequestParameters.ContentTypeJson;
IBoxResponse<BoxPreflightCheck> response = await ToResponseAsync<BoxPreflightCheck>(request).ConfigureAwait(false);
response.ResponseObject.Success = response.Status == ResponseStatus.Success;
return response.ResponseObject;
}
/// <summary>
/// Verify that a new version of a file will be accepted by Box before you send all the bytes over the wire.
/// </summary>
/// <param name="fileId"></param>
/// <param name="preflightCheckRequest"></param>
/// <returns></returns>
public async Task<BoxPreflightCheck> PreflightCheckNewVersion(string fileId, BoxPreflightCheckRequest preflightCheckRequest)
{
if (preflightCheckRequest.Size <= 0)
throw new ArgumentException("Size in bytes must be greater than zero (otherwise preflight check for new version would always succeed)", "sizeinBytes");
BoxRequest request = new BoxRequest(new Uri(string.Format(Constants.FilesPreflightCheckNewVersionString, fileId)))
.Method(RequestMethod.Options);
request.Payload = _converter.Serialize(preflightCheckRequest);
request.ContentType = Constants.RequestParameters.ContentTypeJson;
IBoxResponse<BoxPreflightCheck> response = await ToResponseAsync<BoxPreflightCheck>(request).ConfigureAwait(false);
response.ResponseObject.Success = response.Status == ResponseStatus.Success;
return response.ResponseObject;
}
/// <summary>
/// Uploads a provided file to the target parent folder.
/// If the file already exists, an error will be thrown.
/// A proper timeout should be provided for large uploads.
/// </summary>
/// <param name="fileRequest">BoxFileRequest object.</param>
/// <param name="stream">Stream of uploading file.</param>
/// <param name="fields">Fields which shall be returned in result.</param>
/// <param name="timeout">Timeout for response.</param>
/// <param name="contentMD5">The SHA1 hash of the file.</param>
/// <param name="setStreamPositionToZero">Set position for input stream to 0.</param>
/// <param name="uploadUri">Uri to use for upload. Default upload endpoint URI is used if not specified.</param>
/// <returns>A full file object is returned inside of a collection if the ID is valid and if the update is successful.</returns>
public async Task<BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, IEnumerable<string> fields = null,
TimeSpan? timeout = null, byte[] contentMD5 = null,
bool setStreamPositionToZero = true,
Uri uploadUri = null)
{
stream.ThrowIfNull("stream");
fileRequest.ThrowIfNull("fileRequest")
.Name.ThrowIfNullOrWhiteSpace("filedRequest.Name");
fileRequest.Parent.ThrowIfNull("fileRequest.Parent")
.Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id");
if (setStreamPositionToZero)
stream.Position = 0;
uploadUri = uploadUri ?? _config.FilesUploadEndpointUri;
BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout }
.Param(ParamFields, fields)
.FormPart(new BoxStringFormPart()
{
Name = "attributes",
Value = _converter.Serialize(fileRequest)
})
.FormPart(new BoxFileFormPart()
{
Name = "file",
Value = stream,
FileName = fileRequest.Name
});
if (contentMD5 != null)
request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5));
IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false);
// We can only upload one file at a time, so return the first entry
return response.ResponseObject.Entries.FirstOrDefault();
}
/// <summary>
/// Create an upload session for uploading a new file.
/// </summary>
/// <param name="uploadSessionRequest">The upload session request.</param>
/// <returns>The upload session.</returns>
public async Task<BoxFileUploadSession> CreateUploadSessionAsync(BoxFileUploadSessionRequest uploadSessionRequest)
{
var uploadUri = _config.FilesUploadSessionEndpointUri;
var request = new BoxRequest(uploadUri)
.Method(RequestMethod.Post);
request.Payload = _converter.Serialize(uploadSessionRequest);
request.ContentType = Constants.RequestParameters.ContentTypeJson;
IBoxResponse<BoxFileUploadSession> response = await ToResponseAsync<BoxFileUploadSession>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Create an upload session for uploading a new file version.
/// </summary>
/// <param name="fileId">The file id.</param>
/// <param name="uploadNewVersionSessionRequest">The upload session request for new file version.</param>
/// <returns>The upload session for uploading new Box file version using session.</returns>
public async Task<BoxFileUploadSession> CreateNewVersionUploadSessionAsync(string fileId,
BoxFileUploadSessionRequest uploadNewVersionSessionRequest)
{
var uploadUri = new Uri(string.Format(Constants.FilesNewVersionUploadSessionEndpointString, fileId));
var request = new BoxRequest(uploadUri)
.Method(RequestMethod.Post);
request.Payload = _converter.Serialize(uploadNewVersionSessionRequest);
request.ContentType = Constants.RequestParameters.ContentTypeJson;
IBoxResponse<BoxFileUploadSession> response = await ToResponseAsync<BoxFileUploadSession>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads,
/// these are performed as multipart form uploads. An optional If-Match header can be included to ensure that client only
/// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version.
/// To update the file’s name, you can specify a new name for the file using the fileName parameter.
/// A proper timeout should be provided for large uploads.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="fileId">Id of the file to upload a new version to.</param>
/// <param name="stream">Stream of the uploading file.</param>
/// <param name="etag">This ‘etag’ field of the file, which will be set in the If-Match header.</param>
/// <param name="fields">Fields which shall be returned in result.</param>
/// <param name="timeout">Optional timeout for response.</param>
/// <param name="contentMD5">The SHA1 hash of the file.</param>
/// <param name="setStreamPositionToZero">Set position for input stream to 0.</param>
/// <param name="uploadUri">Optional url for uploading file.</param>
/// <returns>A full file object is returned.</returns>
public async Task<BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream,
string etag = null, IEnumerable<string> fields = null,
TimeSpan? timeout = null, byte[] contentMD5 = null,
bool setStreamPositionToZero = true,
Uri uploadUri = null, DateTimeOffset? contentModifiedTime = null)
{
fileId.ThrowIfNullOrWhiteSpace("fileId");
stream.ThrowIfNull("stream");
if (setStreamPositionToZero)
stream.Position = 0;
uploadUri = uploadUri ?? new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId));
dynamic attributes = new JObject();
if (fileName != null)
{
attributes.name = fileName;
}
if (contentModifiedTime.HasValue)
{
attributes.content_modified_at = contentModifiedTime.Value.ToUniversalTime().ToString(Constants.RFC3339DateFormat_UTC);
}
BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout }
.Header(Constants.RequestParameters.IfMatch, etag)
.Param(ParamFields, fields)
.FormPart(new BoxStringFormPart()
{
Name = "attributes",
Value = _converter.Serialize(attributes)
})
.FormPart(new BoxFileFormPart()
{
Name = "filename",
Value = stream,
FileName = fileName
});
if (contentMD5 != null)
request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5));
IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false);
// We can only upload one file at a time, so return the first entry
return response.ResponseObject.Entries.FirstOrDefault();
}
/// <summary>
/// Upload a part of the file to the session.
/// </summary>
/// <param name="uploadPartUri">Upload Uri from Create Session which include SessionId</param>
/// <param name="sha">The message digest of the part body, formatted as specified by RFC 3230.</param>
/// <param name="partStartOffsetInBytes">Part begin offset in bytes.</param>
/// <param name="sizeOfOriginalFileInBytes">Size of original file in bytes.</param>
/// <param name="stream">The file part stream.</param>
/// <param name="timeout">Timeout of the request.</param>
/// <returns>The complete BoxUploadPartResponse object if success.</returns>
public async Task<BoxUploadPartResponse> UploadPartAsync(Uri uploadPartUri, string sha, long partStartOffsetInBytes, long sizeOfOriginalFileInBytes, Stream stream, TimeSpan? timeout = null)
{
var request = new BoxBinaryRequest(uploadPartUri) { Timeout = timeout }
.Method(RequestMethod.Put)
.Header(Constants.RequestParameters.Digest, "sha=" + sha)
.Header(Constants.RequestParameters.ContentRange, "bytes " + partStartOffsetInBytes + "-" + (partStartOffsetInBytes + stream.Length - 1) + "/" + sizeOfOriginalFileInBytes)
.Part(new BoxFilePart()
{
Value = stream
});
var response = await ToResponseAsync<BoxUploadPartResponse>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Commits a session after all individual file part uploads are complete.
/// </summary>
/// <param name="commitSessionUrl">Commit URL returned in the Create Session response.</param>
/// <param name="sha">The message digest of the complete file, formatted as specified by RFC 3230.</param>
/// <param name="sessionPartsInfo">Parts info for the uploaded parts.</param>
/// <returns> The complete BoxFile object. </returns>
public async Task<BoxFile> CommitSessionAsync(Uri commitSessionUrl, string sha, BoxSessionParts sessionPartsInfo)
{
return await CommitSessionInternalAsync(commitSessionUrl, sha, sessionPartsInfo).ConfigureAwait(false);
}
/// <summary>
/// Commits a session after all individual new file version part uploads are complete.
/// </summary>
/// <param name="commitSessionUrl">Commit URL returned in the Create Session response.</param>
/// <param name="sha">The message digest of the complete file, formatted as specified by RFC 3230.</param>
/// <param name="sessionPartsInfo">Parts info for the uploaded parts.</param>
/// <returns> The complete BoxFile object. </returns>
public async Task<BoxFile> CommitFileVersionSessionAsync(Uri commitSessionUrl, string sha, BoxSessionParts sessionPartsInfo)
{
return await CommitSessionInternalAsync(commitSessionUrl, sha, sessionPartsInfo).ConfigureAwait(false);
}
private async Task<BoxFile> CommitSessionInternalAsync(Uri commitSessionUrl, string sha, BoxSessionParts sessionPartsInfo)
{
BoxRequest request = new BoxRequest(commitSessionUrl)
.Method(RequestMethod.Post)
.Header(Constants.RequestParameters.Digest, "sha=" + sha)
.Payload(_converter.Serialize(sessionPartsInfo));
request.ContentType = Constants.RequestParameters.ContentTypeJson;
var response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false);
// We can only commit one file at a time, so return the first entry
return response.ResponseObject.Entries.FirstOrDefault();
}
/// <summary>
/// Get a list of parts that were uploaded in a session.
/// </summary>
/// <param name="sessionPartsUri">The Url returned in the Create Session response.</param>
/// <param name="offset">Zero-based index of first OffsetID of part to return.</param>
/// <param name="limit">How many parts to return.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all; defaults to false.</param>
/// <returns>Returns a list of file part information uploaded so far in the session.</returns>
public async Task<BoxCollection<BoxSessionPartInfo>> GetSessionUploadedPartsAsync(Uri sessionPartsUri, int? offset = null, int? limit = null, bool autoPaginate = false)
{
BoxRequest request = new BoxRequest(sessionPartsUri)
.Method(RequestMethod.Get);
if (offset.HasValue)
{
request.Param("offset", offset.Value.ToString());
// sessionPartsUri = sessionPartsUri.AppendQueryString("offset", offset.Value.ToString());
}
if (limit.HasValue)
{
request.Param("limit", limit.Value.ToString());
// sessionPartsUri = sessionPartsUri.AppendQueryString("limit", limit.Value.ToString());
}
if (autoPaginate)
{
if (!limit.HasValue)
{
limit = 100;
request.Param("limit", limit.ToString());
}
if (!offset.HasValue)
{
request.Param("offset", "0");
}
return await AutoPaginateLimitOffset<BoxSessionPartInfo>(request, limit.Value).ConfigureAwait(false);
}
else
{
var response = await ToResponseAsync<BoxCollection<BoxSessionPartInfo>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Gets the status of the upload session.
/// </summary>
/// <param name="sessionUploadStatusUri">The Url returned in the Create Session response.</param>
/// <returns>Returns an object representing the status of the upload session.</returns>
public async Task<BoxSessionUploadStatus> GetSessionUploadStatusAsync(Uri sessionUploadStatusUri)
{
BoxRequest request = new BoxRequest(sessionUploadStatusUri)
.Method(RequestMethod.Get);
IBoxResponse<BoxSessionUploadStatus> response = await ToResponseAsync<BoxSessionUploadStatus>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Upload a new large file version by splitting them up and uploads in a session.
/// </summary>
/// <param name="stream">The file stream.</param>
/// <param name="fileId">Id of the remote file.</param>
/// <param name="timeout">Timeout for subsequent UploadPart requests.</param>
/// <param name="progress">Will report progress from 1 - 100.</param>
/// <returns>The BoxFile object.</returns>
public async Task<BoxFile> UploadNewVersionUsingSessionAsync(Stream stream, string fileId, string fileName = null, TimeSpan? timeout = null,
IProgress<BoxProgress> progress = null)
{
// Create Upload Session
var fileSize = stream.Length;
var uploadNewVersionSessionRequest = new BoxFileUploadSessionRequest
{
FileSize = fileSize,
FileName = fileName
};
var boxFileVersionUploadSession = await CreateNewVersionUploadSessionAsync(fileId, uploadNewVersionSessionRequest).ConfigureAwait(false);
var response = await UploadSessionAsync(stream, boxFileVersionUploadSession, timeout, progress).ConfigureAwait(false);
return response;
}
/// <summary>
/// Upload a large file by splitting them up and uploads in a session.
/// </summary>
/// <param name="stream">The file stream.</param>
/// <param name="fileName">Name of the remote file name.</param>
/// <param name="folderId">Parent folder id.</param>
/// <param name="timeout">Timeout for subsequent UploadPart requests.</param>
/// <param name="progress">Will report progress from 1 - 100.</param>
/// <returns>The complete BoxFile object.</returns>
public async Task<BoxFile> UploadUsingSessionAsync(Stream stream, string fileName,
string folderId, TimeSpan? timeout = null, IProgress<BoxProgress> progress = null)
{
// Create Upload Session
var fileSize = stream.Length;
var uploadSessionRequest = new BoxFileUploadSessionRequest
{
FileName = fileName,
FileSize = fileSize,
FolderId = folderId
};
var boxFileUploadSession = await CreateUploadSessionAsync(uploadSessionRequest).ConfigureAwait(false);
var response = await UploadSessionAsync(stream, boxFileUploadSession, timeout, progress).ConfigureAwait(false);
return response;
}
/// <summary>
/// Using the upload session for new file upload and new file version upload,
/// upload by parts file/file version
/// </summary>
/// <param name="stream">The file stream.</param>
/// <param name="uploadSession">BoxFileUpload session retrieved for uploading new file or uploading new file version</param>
/// <param name="progress">Will report progress from 1 - 100.</param>
/// <param name="callingMethod"> The calling function name used to determine which commit function to call.</param>
/// <returns>The complete BoxFile object.</returns>
private async Task<BoxFile> UploadSessionAsync(Stream stream, BoxFileUploadSession uploadFileSession,
TimeSpan? timeout = null, IProgress<BoxProgress> progress = null, [CallerMemberName] string callingMethod = null)
{
var fileSize = stream.Length;
// Parse upload session response
var boxSessionEndpoint = uploadFileSession.SessionEndpoints;
var uploadPartUri = new Uri(boxSessionEndpoint.UploadPart);
var commitUri = new Uri(boxSessionEndpoint.Commit);
var partSize = uploadFileSession.PartSize;
if (long.TryParse(partSize, out var partSizeLong) == false)
{
throw new BoxCodingException("File part size is wrong!");
}
var numberOfParts = UploadUsingSessionInternal.GetNumberOfParts(fileSize,
partSizeLong);
// Full file sha1 for final commit
var fullFileSha1 = await Task.Run(() =>
{
return Helper.GetSha1Hash(stream);
});
// Upload parts in session
var allSessionParts = await UploadPartsInSessionAsync(uploadPartUri,
numberOfParts, partSizeLong, stream,
fileSize, timeout, progress).ConfigureAwait(false);
var allSessionPartsList = allSessionParts.ToList();
var sessionPartsForCommit = new BoxSessionParts
{
Parts = allSessionPartsList
};
// Commit, Retry 5 times with interval related to the total part number
// Having debugged this -- retries do consistenly happen so we up the retries
const int RetryCount = 5;
var retryInterval = allSessionPartsList.Count * 100;
// Depending on the calling function a different commit function will be used
// to commit file upload parts
if (callingMethod == "UploadUsingSessionAsync")
{
var fileResponse =
await Retry.ExecuteAsync(
async () =>
await CommitSessionAsync(commitUri, fullFileSha1,
sessionPartsForCommit).ConfigureAwait(false),
TimeSpan.FromMilliseconds(retryInterval), RetryCount);
return fileResponse;
}
else // This is to call the commit function for file version uploads
{
var versionResponse =
await Retry.ExecuteAsync(
async () =>
await CommitFileVersionSessionAsync(commitUri, fullFileSha1,
sessionPartsForCommit).ConfigureAwait(false),
TimeSpan.FromMilliseconds(retryInterval), RetryCount);
return versionResponse;
}
}
private async Task<IEnumerable<BoxSessionPartInfo>> UploadPartsInSessionAsync(
Uri uploadPartsUri, int numberOfParts, long partSize, Stream stream,
long fileSize, TimeSpan? timeout = null, IProgress<BoxProgress> progress = null)
{
var maxTaskNum = Environment.ProcessorCount + 1;
// Retry 5 times for 10 seconds
const int RetryMaxCount = 5;
const int RetryMaxInterval = 10;
var ret = new List<BoxSessionPartInfo>();
using (var concurrencySemaphore = new SemaphoreSlim(maxTaskNum))
{
var postTaskTasks = new List<Task>();
var taskCompleted = 0;
var tasks = new List<Task<BoxUploadPartResponse>>();
for (var i = 0; i < numberOfParts; i++)
{
await concurrencySemaphore.WaitAsync().ConfigureAwait(false);
// Split file as per part size
var partOffset = partSize * i;
// Retry
var uploadPartWithRetryTask = Retry.ExecuteAsync(async () =>
{
// Release the memory when done
using (var partFileStream = UploadUsingSessionInternal.GetFilePart(stream, partSize,
partOffset))
{
var sha = Helper.GetSha1Hash(partFileStream);
partFileStream.Position = 0;
var uploadPartResponse = await UploadPartAsync(
uploadPartsUri, sha, partOffset, fileSize, partFileStream,
timeout).ConfigureAwait(false);
return uploadPartResponse;
}
}, TimeSpan.FromSeconds(RetryMaxInterval), RetryMaxCount);
// Have each task notify the Semaphore when it completes so that it decrements the number of tasks currently running.
postTaskTasks.Add(uploadPartWithRetryTask.ContinueWith(tsk =>
{
concurrencySemaphore.Release();
++taskCompleted;
if (progress != null)
{
var boxProgress = new BoxProgress()
{
progress = taskCompleted * 100 / numberOfParts
};
progress.Report(boxProgress);
}
}
));
tasks.Add(uploadPartWithRetryTask);
}
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
ret.AddRange(results.Select(elem => elem.Part));
}
return ret;
}
private string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (var b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
/// <summary>
/// If there are previous versions of this file, this method can be used to retrieve metadata about the older versions.
/// <remarks>Versions are only tracked for Box users with premium accounts.</remarks>
/// </summary>
/// <param name="id">The file id.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="offset">Zero-based index of first OffsetID of part to return.</param>
/// <param name="limit">How many parts to return.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all; defaults to false.</param>
/// <returns>A collection of versions other than the main version of the file. If a file has no other versions, an empty collection will be returned.
/// Note that if a file has a total of three versions, only the first two version will be returned.</returns>
public async Task<BoxCollection<BoxFileVersion>> ViewVersionsAsync(string id, IEnumerable<string> fields = null, int? offset = null, int? limit = null, bool autoPaginate = false)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.VersionsPathString, id))
.Param(ParamFields, fields);
if (offset.HasValue)
{
request.Param("offset", offset.Value.ToString());
}
if (limit.HasValue)
{
request.Param("limit", limit.Value.ToString());
}
if (autoPaginate)
{
if (!limit.HasValue)
{
limit = 100;
request.Param("limit", limit.ToString());
}
if (!offset.HasValue)
{
request.Param("offset", "0");
}
return await AutoPaginateLimitOffset<BoxFileVersion>(request, limit.Value).ConfigureAwait(false);
}
else
{
IBoxResponse<BoxCollection<BoxFileVersion>> response = await ToResponseAsync<BoxCollection<BoxFileVersion>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Used to update individual or multiple fields in the file object, including renaming the file, changing it’s description,
/// and creating a shared link for the file. To move a file, change the ID of its parent folder. An optional etag
/// can be included to ensure that client only updates the file if it knows about the latest version.
/// </summary>
/// <param name="fileRequest">BoxFileRequest object.</param>
/// <param name="etag">This ‘etag’ field of the file, which will be set in the If-Match header.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>The complete BoxFile object.</returns>
public async Task<BoxFile> UpdateInformationAsync(BoxFileRequest fileRequest, string etag = null, IEnumerable<string> fields = null)
{
fileRequest.ThrowIfNull("fileRequest")
.Id.ThrowIfNullOrWhiteSpace("fileRequest.Id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, fileRequest.Id)
.Method(RequestMethod.Put)
.Header(Constants.RequestParameters.IfMatch, etag)
.Param(ParamFields, fields);
request.Payload = _converter.Serialize(fileRequest);
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Discards a file to the trash. The etag of the file can be included as an ‘If-Match’ header to prevent race conditions.
/// <remarks>Depending on the enterprise settings for this user, the item will either be immediately and permanently deleted from Box or moved to the trash.</remarks>
/// </summary>
/// <param name="id">Id of the file.</param>
/// <param name="etag">This ‘etag’ field of the file, which will be set in the If-Match header.</param>
/// <returns>True if file is deleted, false otherwise.</returns>
public async Task<bool> DeleteAsync(string id, string etag = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, id)
.Method(RequestMethod.Delete)
.Header(Constants.RequestParameters.IfMatch, etag);
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.Status == ResponseStatus.Success;
}
/// <summary>
/// Abort the upload session and discard all data uploaded. This cannot be reversed.
/// </summary>
/// <param name="abortUri">The upload session abort url that aborts the session.</param>
/// <returns>True if deletion success.</returns>
public async Task<bool> DeleteUploadSessionAsync(Uri abortUri)
{
var request = new BoxRequest(abortUri)
.Method(RequestMethod.Delete);
IBoxResponse<BoxFileUploadSession> response = await ToResponseAsync<BoxFileUploadSession>(request).ConfigureAwait(false);
return response.Status == ResponseStatus.Success;
}
/// <summary>
/// Used to create a copy of a file in another folder. The original version of the file will not be altered.
/// </summary>
/// <param name="fileRequest">BoxFileRequest object.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>
/// A full file object is returned if the ID is valid and if the update is successful.
/// Errors can be thrown if the destination folder is invalid or if a file-name collision occurs.
/// </returns>
public async Task<BoxFile> CopyAsync(BoxFileRequest fileRequest, IEnumerable<string> fields = null)
{
fileRequest.ThrowIfNull("fileRequest");
fileRequest.Id.ThrowIfNullOrWhiteSpace("fileRequest.Id");
fileRequest.Parent.ThrowIfNull("fileRequest.Parent")
.Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.CopyPathString, fileRequest.Id))
.Method(RequestMethod.Post)
.Param(ParamFields, fields);
fileRequest.Id = null; //file Id was used as a query parameter in this case
request.Payload(_converter.Serialize(fileRequest));
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Used to create a shared link for a file.
/// </summary>
/// <param name="id">Id of the file.</param>
/// <param name="sharedLinkRequest">BoxSharedLinkRequest object.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>A full file object containing the updated shared link is returned
/// if the ID is valid and if the update is successful.</returns>
public async Task<BoxFile> CreateSharedLinkAsync(string id, BoxSharedLinkRequest sharedLinkRequest, IEnumerable<string> fields = null)
{
id.ThrowIfNullOrWhiteSpace("id");
sharedLinkRequest.ThrowIfNull("sharedLinkRequest");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, id)
.Method(RequestMethod.Put)
.Param(ParamFields, fields)
.Payload(_converter.Serialize(new BoxItemRequest() { SharedLink = sharedLinkRequest }));
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Used to delete the shared link for a file.
/// </summary>
/// <param name="id">The Id of the file to remove the shared link from.</param>
/// <returns>A full file object with the shared link removed is returned
/// if the ID is valid and if the update is successful.</returns>
public async Task<BoxFile> DeleteSharedLinkAsync(string id, IEnumerable<string> fields = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, id)
.Method(RequestMethod.Put)
.Param(ParamFields, fields)
.Payload(_converter.Serialize(new BoxDeleteSharedLinkRequest()));
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Use this to get a list of all the collaborations on a file
/// </summary>
/// <param name="id">Id of the file</param>
/// <param name="marker">Paging marker; use null to retrieve the first page of results</param>
/// <param name="limit">Number of records to return per page</param>
/// <param name="fields">Attribute(s) to include in the response</param>
/// <param name="autoPaginate">Whether to automatically gather the entire result set</param>
/// <returns>Collection of the collaborations on a file</returns>
public async Task<BoxCollectionMarkerBasedV2<BoxCollaboration>> GetCollaborationsCollectionAsync(string id, string marker = null, int? limit = null, IEnumerable<string> fields = null, bool autoPaginate = false)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.CollaborationsPathString, id))
.Param(ParamFields, fields)
.Param("limit", limit?.ToString())
.Param("marker", marker);
if (autoPaginate)
{
if (!limit.HasValue)
{
limit = 100;
request.Param("limit", limit.ToString());
}
return await AutoPaginateMarkerV2<BoxCollaboration>(request, limit.Value).ConfigureAwait(false);
}
else
{
IBoxResponse<BoxCollectionMarkerBasedV2<BoxCollaboration>> response = await ToResponseAsync<BoxCollectionMarkerBasedV2<BoxCollaboration>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Retrieves the comments on a particular file, if any exist.
/// </summary>
/// <param name="id">The Id of the item that the comments should be retrieved for.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>A Collection of comment objects are returned. If there are no comments on the file, an empty comments array is returned.</returns>
public async Task<BoxCollection<BoxComment>> GetCommentsAsync(string id, IEnumerable<string> fields = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.CommentsPathString, id))
.Param(ParamFields, fields);
IBoxResponse<BoxCollection<BoxComment>> response = await ToResponseAsync<BoxCollection<BoxComment>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Retrieves a thumbnail, or smaller image representation, of this file. Sizes of 32x32,
/// 64x64, 128x128, and 256x256 can be returned in the .png format
/// and sizes of 32x32, 94x94, 160x160, and 320x320 can be returned in the .jpg format.
/// Thumbnails can be generated for the image and video file formats listed here.
/// see <a href="http://community.box.com/t5/Managing-Your-Content/What-file-types-are-supported-by-Box-s-Content-Preview/ta-p/327"/>
/// </summary>
/// <param name="id">Id of the file.</param>
/// <param name="minHeight">The minimum height of the thumbnail.</param>
/// <param name="minWidth">The minimum width of the thumbnail.</param>
/// <param name="maxHeight">The maximum height of the thumbnail.</param>
/// <param name="maxWidth">The maximum width of the thumbnail.</param>
/// <param name="handleRetry">Specifies whether the method handles retries. If true, then the method would retry the call if the HTTP response is 'Accepted'. The delay for the retry is determined
/// by the RetryAfter header, or if that header is not set, by the constant DefaultRetryDelay.</param>
/// <param name="throttle">Whether the requests will be throttled. Recommended to be left true to prevent spamming the server.</param>
/// <param name="extension">png or jpg with no "."</param>
/// <returns>Contents of thumbnail as Stream.</returns>
public async Task<Stream> GetThumbnailAsync(string id, int? minHeight = null, int? minWidth = null, int? maxHeight = null, int? maxWidth = null, bool throttle = true, bool handleRetry = true, string extension = "png")
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ThumbnailPathExtensionString, id, extension))
.Param("min_height", minHeight.ToString())
.Param("min_width", minWidth.ToString())
.Param("max_height", maxHeight.ToString())
.Param("max_width", maxWidth.ToString());
IBoxResponse<Stream> response = await ToResponseAsync<Stream>(request, throttle).ConfigureAwait(false);
while (response.StatusCode == HttpStatusCode.Accepted && handleRetry)
{
await Task.Delay(GetTimeDelay(response.Headers));
response = await ToResponseAsync<Stream>(request, throttle).ConfigureAwait(false);
}
return response.ResponseObject;
}
/// <summary>
/// Gets a preview link (URI) for a file that is valid for 60 seconds.
/// </summary>
/// <param name="id">Id of the file.</param>
/// <returns>Preview link (URI) for a file that is valid for 60 seconds.</returns>
public async Task<Uri> GetPreviewLinkAsync(string id)
{
var fields = new List<string>() { "expiring_embed_link" };
var file = await GetInformationAsync(id, fields).ConfigureAwait(false);
return file.ExpiringEmbedLink.Url;
}
/// <summary>
/// Return the time to wait until retrying the call. If no RetryAfter value is specified in the header, use default value;
/// </summary>
private int GetTimeDelay(HttpResponseHeaders headers)
{
return headers != null && headers.RetryAfter != null && int.TryParse(headers.RetryAfter.ToString(), out var timeToWait)
? timeToWait * 1000
: Constants.DefaultRetryDelay;
}
/// <summary>
/// Retrieves an item that has been moved to the trash.
/// </summary>
/// <param name="id">Id of the file.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>The full item will be returned, including information about when the it was moved to the trash.</returns>
public async Task<BoxFile> GetTrashedAsync(string id, IEnumerable<string> fields = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.TrashPathString, id))
.Param(ParamFields, fields);
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Restores an item that has been moved to the trash. Default behavior is to restore the item to the folder it was in before
/// it was moved to the trash. If that parent folder no longer exists or if there is now an item with the same name in that
/// parent folder, the new parent folder and/or new name will need to be included in the request.
/// </summary>
/// <param name="fileRequest">BoxFileRequest object.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>The full item will be returned with a 201 Created status. By default it is restored to the parent folder it was in before it was trashed.</returns>
public async Task<BoxFile> RestoreTrashedAsync(BoxFileRequest fileRequest, IEnumerable<string> fields = null)
{
fileRequest.ThrowIfNull("fileRequest")
.Id.ThrowIfNullOrWhiteSpace("fileRequest.Id");
BoxRequest request = new BoxRequest(_config.FilesEndpointUri, fileRequest.Id)
.Method(RequestMethod.Post)
.Param(ParamFields, fields)
.Payload(_converter.Serialize(fileRequest));
IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Permanently deletes an item that is in the trash. The item will no longer exist in Box. This action cannot be undone.
/// </summary>
/// <param name="id">Id of the file.</param>