- Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathStorageReference.cs
896 lines (854 loc) · 38.7 KB
/
StorageReference.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
/*
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
usingSystem;
usingSystem.IO;
usingSystem.Runtime.InteropServices;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingFirebase.Storage.Internal;
namespaceFirebase.Storage{
/// <summary>Represents a reference to a Google Cloud Storage object.</summary>
/// <remarks>
/// Represents a reference to a Google Cloud Storage object. Developers can upload and download
/// objects, get/set object metadata, and delete an object at a specified path.
/// (see <a href="https://cloud.google.com/storage/">Google Cloud Storage</a>)
/// </remarks>
publicsealedclassStorageReference{
/// <summary>
/// Extracts the cancellation status and exception from a task generated by a
/// firebase::Future.
/// </summary>
privateclassTaskCompletionStatus{
/// <summary>
/// true if the task completed successfully.
/// </summary>
publicboolIsSuccessful{get;privateset;}
/// <summary>
/// true if the task was canceled.
/// </summary>
publicboolIsCanceled{get;privateset;}
/// <summary>
/// Non-null if the task failed.
/// </summary>
publicSystem.ExceptionException{get;privateset;}
/// <summary>
/// Extract the completion status from the specified task.
/// </summary>
/// <param name="task">Task to extract completion status from.</param>
/// <param name="operationDescription">Description of the operation performed by the
/// task used to log task status.</param>
/// <param name="logger">Used to log task completion status.</param>
publicTaskCompletionStatus(Tasktask,stringoperationDescription,ModuleLoggerlogger){
if(task.IsCompleted&&!task.IsFaulted&&!task.IsCanceled){
IsSuccessful=true;
logger.LogMessage(LogLevel.Debug,String.Format("{0} completed successfully.",
operationDescription));
return;
}
StorageExceptionstorageException=
task.IsFaulted?StorageException.CreateFromException(task.Exception):null;
// When an operation is canceled a C++ future will complete with a cancellation error code
// so cancel the task when the cancelation error code is detected.
if(task.IsCanceled||(storageException!=null&&
storageException.ErrorCode==StorageException.ErrorCanceled)){
logger.LogMessage(LogLevel.Debug,String.Format("{0} canceled.",operationDescription));
IsCanceled=true;
return;
}
Exception=storageException;
if(Exception!=null){
logger.LogMessage(LogLevel.Debug,String.Format("{0} failed {1}.",operationDescription,
Exception.Message));
return;
}
logger.LogMessage(LogLevel.Debug,String.Format("{0} failed due to an unknown error.",
operationDescription));
Exception=newInvalidOperationException(String.Format("{0} failed.",
operationDescription));
}
/// <summary>
/// Create a task from this object's status.
/// </summary>
/// <returns>A completed Task from this object's status.</returns>
publicTaskToTask(){
vartaskCompletionSource=newTaskCompletionSource<bool>();
if(IsSuccessful){
taskCompletionSource.SetResult(true);
}elseif(IsCanceled){
// Emulates Task.FromCanceled in .NET 4.5.
taskCompletionSource.SetCanceled();
}else{
// Emulates Task.FromException in .NET 4.5.
taskCompletionSource.SetException(this.Exception);
}
returntaskCompletionSource.Task;
}
}
// Storage object this reference was created from.
privatereadonlyFirebaseStoragefirebaseStorage;
/// <summary>
/// Construct a wrapper around the StorageReferenceInternal object.
/// </summary>
internalStorageReference(FirebaseStoragestorage,
StorageReferenceInternalstorageReferenceInternal){
firebaseStorage=storage;
Internal=storageReferenceInternal;
Logger=newModuleLogger(parentLogger:firebaseStorage.Logger){
Tag=String.Format("StorageReference {0}",ToString())
};
}
/// <summary>
/// Logger for this reference.
/// </summary>
// Logger for this reference.
internalModuleLoggerLogger{get;privateset;}
/// <summary>
/// Returns a new instance of
/// <see cref="StorageReference" />
/// pointing to the parent location or null
/// if this instance references the root location.
/// For example:
/// <pre>
/// <c>
/// path = foo/bar/baz parent = foo/bar
/// path = foo parent = (root)
/// path = (root) parent = (null)
/// </c>
/// </pre>
/// </summary>
/// <returns>
/// the parent
/// <see cref="StorageReference" />
/// .
/// </returns>
publicStorageReferenceParent{
get{returnnewStorageReference(firebaseStorage,Internal.GetParent());}
}
/// <summary>
/// Returns a new instance of
/// <see cref="StorageReference" />
/// pointing to the root location.
/// </summary>
/// <returns>
/// the root
/// <see cref="StorageReference" />
/// .
/// </returns>
publicStorageReferenceRoot{get{returnfirebaseStorage.RootReference;}}
/// <summary>Returns the short name of this object.</summary>
/// <returns>the name.</returns>
publicstringName{get{returnInternal.Name;}}
/// <summary>
/// Returns the full path to this object, not including the Google Cloud Storage bucket.
/// </summary>
/// <returns>the path.</returns>
publicstringPath{get{returnInternal.FullPath;}}
/// <summary>Return the Google Cloud Storage bucket that holds this object.</summary>
/// <returns>the bucket.</returns>
publicstringBucket{get{returnInternal.Bucket;}}
/// <summary>
/// Returns the
/// <see cref="FirebaseStorage" />
/// service which created this reference.
/// </summary>
/// <returns>
/// The
/// <see cref="FirebaseStorage" />
/// service.
/// </returns>
publicFirebaseStorageStorage{get{returnfirebaseStorage;}}
/// <summary>
/// Returns a new instance of
/// <see cref="StorageReference" />
/// pointing to a child location of the current
/// reference. All leading and trailing slashes will be removed, and consecutive slashes will
/// be compressed to single slashes. For example:
/// <pre>
/// <c>
/// child = /foo/bar path = foo/bar
/// child = foo/bar/ path = foo/bar
/// child = foo///bar path = foo/bar
/// </c>
/// </pre>
/// </summary>
/// <param name="pathString">The relative path from this reference.</param>
/// <returns>
/// the child
/// <see cref="StorageReference" />
/// .
/// </returns>
publicStorageReferenceChild(stringpathString){
returnnewStorageReference(firebaseStorage,Internal.Child(pathString));
}
/// <summary>
/// Uploads byte data to this
/// <see cref="StorageReference" />
/// .
/// This is not recommended for large files. Instead upload a file via
/// <see>
/// <cref>PutFile</cref>
/// </see>
/// or a Stream via
/// <see>
/// <cref>PutStream</cref>
/// </see>
/// .
/// </summary>
/// <param name="bytes">The byte[] to upload.</param>
/// <param name="customMetadata">
/// <see cref="MetadataChange" />
/// containing additional information (MIME type, etc.)
/// about the object being uploaded.
/// </param>
/// <param name="progressHandler">
/// usually an instance of <see cref="StorageProgress"/> that will
/// receive periodic updates during the operation. This value can
/// be null.</param>
/// <param name="cancelToken">A CancellationToken to control the operation
/// and possibly later cancel it. This value may be CancellationToken.None
/// to indicate no value.</param>
/// <param name="previousSessionUri">A Uri previously obtained by
/// <see cref="UploadState.UploadSessionUri"/> that can be used to resume
/// a previously interrupted upload.</param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the upload.
/// </returns>
publicTask<StorageMetadata>PutBytesAsync(
byte[]bytes,
MetadataChangecustomMetadata=null,
IProgress<UploadState>progressHandler=null,
CancellationTokencancelToken=default(CancellationToken),
UripreviousSessionUri=null){
returnPutBytesUsingCompletionSourceAsync(bytes,customMetadata,progressHandler,cancelToken,
previousSessionUri,
newTaskCompletionSource<StorageMetadata>());
}
/// <summary>
/// Call Internal.PutBytesUsingMonitorControllerAsync while maintaining a reference to
// monitorController and metadata until the operation is complete.
/// </summary>
/// <param name="buffer">Address of pinned buffer to upload.</param>
/// <param name="bufferSize">Size of buffer in bytes.</param>
/// <param name="metadata">Metadata to upload or null to use defaults.</param>
/// <param name="monitorController">Object that can be used to monitor and control the
/// transfer.</param>
/// <param name="cancellationToken">Token which can be used to cancel the upload.</param>
/// <returns>Task that indicates when the upload is complete.
/// NOTE: This task is the object constructed from firebase::Future.</returns>
privateTask<MetadataInternal>PutBytesUsingMonitorControllerAsync(
IntPtrbuffer,uintbufferSize,MetadataInternalmetadata,
MonitorControllerInternalmonitorController,CancellationTokencancellationToken){
vartask=Internal.PutBytesUsingMonitorControllerAsync(buffer,bufferSize,metadata,
monitorController);
monitorController.RegisterCancellationToken(cancellationToken);
returntask.ContinueWith((completedTask)=>{
monitorController.Dispose();
if(metadata!=null)metadata.Dispose();
returncompletedTask;
}).Unwrap();
}
/// <summary>
/// Uploads an array of bytes signally the specified completion source when complete.
/// </summary>
/// <param name="bytes">Array of bytes to upload.</param>
/// <param name="customMetadata">Metadata to upload.</param>
/// <param name="progressHandler">Handler to report progress to.</param>
/// <param name="cancelToken">Token used to signal task cancellation.</param>
/// <param name="previousSessionUri">URL used to resume upload.</param>
/// <param name="completionSource">Completion source that is signalled when the operation is
/// complete.</param>
/// <returns>Task that indicates when the upload is complete.</returns>
privateTask<StorageMetadata>PutBytesUsingCompletionSourceAsync(
byte[]bytes,
MetadataChangecustomMetadata,
IProgress<UploadState>progressHandler,
CancellationTokencancelToken,
UripreviousSessionUri,
TaskCompletionSource<StorageMetadata>completionSource){
varuploadState=newUploadState(this,bytes.Length);
vartransferStateUpdater=newTransferStateUpdater<UploadState>(
this,progressHandler,uploadState,uploadState.State);
// TODO(smiles): Add support for resumable uploads when b/68320317 is resolved.
varbytesHandle=GCHandle.Alloc(bytes,GCHandleType.Pinned);
PutBytesUsingMonitorControllerAsync(
bytesHandle.AddrOfPinnedObject(),(uint)bytes.Length,
StorageMetadata.BuildMetadataInternal(customMetadata),
transferStateUpdater.MonitorController,cancelToken)
.ContinueWith(task =>{
bytesHandle.Free();
CompleteTask(task,completionSource,
()=>{
varmetadata=newStorageMetadata(this,task.Result);
transferStateUpdater.SetMetadata(metadata);
returnmetadata;
},"PutBytes");
});
returncompletionSource.Task;
}
/// <summary>
/// Call Internal.PutFileUsingMonitorControllerAsync while maintaining a reference to
// monitorController and metadata until the operation is complete.
/// </summary>
/// <param name="path">Path (URI string) of the file to upload.</param>
/// <param name="metadata">Metadata to upload or null to use defaults.</param>
/// <param name="monitorController">Object that can be used to monitor and control the
/// transfer.</param>
/// <param name="cancellationToken">Token which can be used to cancel the upload.</param>
/// <returns>Task that indicates when the upload is complete.
/// NOTE: This task is the object constructed from firebase::Future.</returns>
internalTask<MetadataInternal>PutFileUsingMonitorControllerAsync(
stringpath,MetadataInternalmetadata,MonitorControllerInternalmonitorController,
CancellationTokencancellationToken){
vartask=Internal.PutFileUsingMonitorControllerAsync(path,metadata,monitorController);
monitorController.RegisterCancellationToken(cancellationToken);
returntask.ContinueWith(completedTask =>{
monitorController.Dispose();
if(metadata!=null)metadata.Dispose();
returncompletedTask;
}).Unwrap();
}
/// <summary>
/// Uploads from a content URI to this
/// <see cref="StorageReference" />
/// .
/// </summary>
/// <param name="filePath">
/// The source of the upload.
/// This should be a file system URI representing the path the object
/// should be uploaded from.
/// </param>
/// <param name="customMetadata">
/// <see cref="MetadataChange" />
/// containing additional information (MIME
/// type, etc.) about the object being uploaded.
/// </param>
/// <param name="progressHandler">
/// usually an instance of <see cref="StorageProgress"/> that will
/// receive periodic updates during the operation. This value can
/// be null.</param>
/// <param name="cancelToken">A CancellationToken to control the operation
/// and possibly later cancel it. This value may be CancellationToken.None
/// to indicate no value.</param>
/// <param name="previousSessionUri">A Uri previously obtained by
/// <see cref="UploadState.UploadSessionUri"/> that can be used to resume
/// a previously interrupted upload.</param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the upload.
/// </returns>
publicTask<StorageMetadata>PutFileAsync(
stringfilePath,
MetadataChangecustomMetadata=null,
IProgress<UploadState>progressHandler=null,
CancellationTokencancelToken=default(CancellationToken),
UripreviousSessionUri=null){
Preconditions.CheckArgument(filePath!=null,"filePath cannot be null");
varresult=newTaskCompletionSource<StorageMetadata>();
stringfilePathUriOrLocalPath=filePath.StartsWith("file://")?
(newUri(filePath)).LocalPath:filePath;
if(File.Exists(filePathUriOrLocalPath)){
varuploadState=newUploadState(this,(newFileInfo(filePathUriOrLocalPath)).Length);
vartransferStateUpdater=newTransferStateUpdater<UploadState>(
this,progressHandler,uploadState,uploadState.State);
PutFileUsingMonitorControllerAsync(
filePath,StorageMetadata.BuildMetadataInternal(customMetadata),
transferStateUpdater.MonitorController,cancelToken).ContinueWith(task =>{
CompleteTask(task,result,
()=>{
varmetadata=newStorageMetadata(this,task.Result);
transferStateUpdater.SetMetadata(metadata);
returnmetadata;
},"PutFile");
});
}else{
result.SetException(newFileNotFoundException(String.Format("{0} not found",
filePathUriOrLocalPath),
filePath));
}
returnresult.Task;
}
/// <summary>
/// Uploads a stream of data to this
/// <see cref="StorageReference" />
/// .
/// The stream will remain open at the end of the upload.
/// </summary>
/// <param name="stream">
/// The
/// <see cref="Stream" />
/// to upload.
/// </param>
/// <param name="customMetadata">
/// <see cref="MetadataChange" />
/// containing additional information (MIME type, etc.)
/// about the object being uploaded.
/// </param>
/// <param name="progressHandler">
/// usually an instance of <see cref="StorageProgress"/> that will
/// receive periodic updates during the operation. This value can
/// be null.</param>
/// <param name="cancelToken">A CancellationToken to control the operation
/// and possibly later cancel it. This value may be CancellationToken.None
/// to indicate no value.</param>
/// <param name="previousSessionUri">A Uri previously obtained by
/// <see cref="UploadState.UploadSessionUri"/> that can be used to resume
/// a previously interrupted upload.</param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the upload.
/// </returns>
publicTask<StorageMetadata>PutStreamAsync(
Streamstream,
MetadataChangecustomMetadata=null,
IProgress<UploadState>progressHandler=null,
CancellationTokencancelToken=default(CancellationToken),
UripreviousSessionUri=null){
Preconditions.CheckArgument(stream!=null,"stream cannot be null");
varresult=newTaskCompletionSource<StorageMetadata>();
// TODO(smiles): *STOP SHIP* This is awful as it copies the *entire* stream into memory then
// copies it *again* into a byte array that can be passed to PutBytes(). b/68200113
(newThread(()=>{
byte[]buffer=newbyte[512];
using(MemoryStreammemoryStream=newMemoryStream()){
while(true){
intread=stream.Read(buffer,0,buffer.Length);
if(read<=0)break;
memoryStream.Write(buffer,0,read);
}
PutBytesUsingCompletionSourceAsync(memoryStream.ToArray(),customMetadata,
progressHandler,cancelToken,previousSessionUri,
result);
}
})).Start();
returnresult.Task;
}
/// <summary>
/// Retrieves metadata associated with an object at this
/// <see cref="StorageReference" />
/// .
/// </summary>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTask<StorageMetadata>GetMetadataAsync(){
varresult=newTaskCompletionSource<StorageMetadata>();
Internal.GetMetadataAsync().ContinueWith(task =>{
CompleteTask(task,result,()=>{returnnewStorageMetadata(this,task.Result);},
"GetMetadata");
});
returnresult.Task;
}
/// <summary>
/// Retrieves a long lived download URL with a revokable token.
/// </summary>
/// <remarks>
/// Retrieves a long lived download URL with a revokable token.
/// This can be used to share the file with others, but can be revoked by a developer
/// in the Firebase Console if desired.
/// </remarks>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTask<Uri>GetDownloadUrlAsync(){
varresult=newTaskCompletionSource<Uri>();
Internal.GetDownloadUrlAsync().ContinueWith(task =>{
CompleteTask(task,result,
()=>{
varurl=task.Result;
if(String.IsNullOrEmpty(url))returnnull;
returnFirebaseStorage.ConstructFormattedUri(url);
},"GetDownloadUrl.");
});
returnresult.Task;
}
/// <summary>
/// Updates the metadata associated with this
/// <see cref="StorageReference" />
/// .
/// </summary>
/// <param name="metadata">
/// A
/// <see cref="MetadataChange" />
/// object with the metadata to update.
/// </param>
/// <returns>
/// a
/// <see cref="System.Threading.Tasks.Task" />
/// that will return the final
/// <see cref="StorageMetadata" />
/// once the operation
/// is complete.
/// </returns>
publicTask<StorageMetadata>UpdateMetadataAsync(MetadataChangemetadata){
Preconditions.CheckNotNull(metadata);
varresult=newTaskCompletionSource<StorageMetadata>();
varmetadataInternal=metadata.Build().Internal;
Internal.UpdateMetadataAsync(metadataInternal).ContinueWith(
task =>{
metadataInternal.Dispose();
CompleteTask(task,result,()=>{returnnewStorageMetadata(this,task.Result);},
"UpdateMetadata");
});
returnresult.Task;
}
/// <summary>
/// Downloads the object from this
/// <see cref="StorageReference" />
/// A byte array will be allocated large enough to hold the entire file in memory.
/// Therefore, using this method will impact memory usage of your process. If you are
/// downloading many large files,
/// <see>
/// <cref>GetStream(StreamDownloadTask.StreamProcessor)</cref>
/// </see>
/// may be a better option.
/// </summary>
/// <param name="maxDownloadSizeBytes">
/// The maximum allowed size in bytes that will be allocated.
/// Set this parameter to prevent out of memory conditions from
/// occurring. If the download exceeds this limit, the task will
/// fail and an
/// <see cref="System.IndexOutOfRangeException" />
/// will be returned.
/// </param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTask<byte[]>GetBytesAsync(longmaxDownloadSizeBytes){
returnGetBytesAsync(maxDownloadSizeBytes,progressHandler:null,
cancelToken:default(CancellationToken));
}
/// <summary>
/// Call Internal.GetBytesUsingMonitorControllerAsync while maintaining a reference to
/// monitorController until the operation is complete.
/// </summary>
/// <param name="buffer">Address of pinned buffer to read into.</param>
/// <param name="bufferSize">Size of buffer in bytes.</param>
/// <param name="monitorController">Object that can be used to monitor and control the
/// transfer.</param>
/// <param name="cancellationToken">Token which can be used to cancel the transfer.</param>
/// <returns>Task that indicates when the download is complete.
/// NOTE: This task is the object constructed from firebase::Future.</returns>
internalTask<long>GetBytesUsingMonitorControllerAsync(
System.IntPtrbuffer,uintbufferSize,MonitorControllerInternalmonitorController,
CancellationTokencancellationToken){
vartask=Internal.GetBytesUsingMonitorControllerAsync(buffer,bufferSize,
monitorController);
monitorController.RegisterCancellationToken(cancellationToken);
returntask.ContinueWith(completedTask =>{
monitorController.Dispose();
returncompletedTask;
}).Unwrap();
}
/// <summary>
/// Downloads the object from this
/// <see cref="StorageReference" />
/// A byte array will be allocated large enough to hold the entire file in memory.
/// Therefore, using this method will impact memory usage of your process. If you are
/// downloading many large files,
/// <see>
/// <cref>GetStream(StreamDownloadTask.StreamProcessor)</cref>
/// </see>
/// may be a better option.
/// </summary>
/// <param name="maxDownloadSizeBytes">
/// The maximum allowed size in bytes that will be allocated.
/// Set this parameter to prevent out of memory conditions from
/// occurring. If the download exceeds this limit, the task will
/// fail and an
/// <see cref="System.IndexOutOfRangeException" />
/// will be returned.
/// </param>
/// <param name="progressHandler">
/// usually an instance of <see cref="StorageProgress"/> that will
/// receive periodic updates during the operation. This value can
/// be null.</param>
/// <param name="cancelToken">A CancellationToken to control the operation
/// and possibly later cancel it. This value may be CancellationToken.None
/// to indicate no value.</param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTask<byte[]>GetBytesAsync(longmaxDownloadSizeBytes,
IProgress<DownloadState>progressHandler,
CancellationTokencancelToken=default(CancellationToken)){
Logger.LogMessage(LogLevel.Debug,
String.Format("Get up to {0} bytes.",maxDownloadSizeBytes>0?
maxDownloadSizeBytes.ToString():"all"));
varresult=newTaskCompletionSource<byte[]>();
GetMetadataAsync().ContinueWith(metadataTask =>{
varsuccessful=CompleteTask(
metadataTask,result,()=>{
// If the returned metadata describes a zero sized file, abort.
if(metadataTask.Result.SizeBytes<=0){
returnnull;
}
// NOTE: This value is unused, we just return a non-null value here to indicate
// success.
returnnewbyte[1];
},
"Get file size",setCompletionSourceResult:false);
if(successful==null)return;
varmetadata=metadataTask.Result;
varsizeBytes=metadata.SizeBytes;
Logger.LogMessage(LogLevel.Debug,String.Format("Fetched metadata: {0}",
metadata.AsString()));
ExceptionfaultException=null;
if(maxDownloadSizeBytes>0&&sizeBytes>maxDownloadSizeBytes){
faultException=newIndexOutOfRangeException(
String.Format("File size {0} is larger than the maximum download size {1}",
sizeBytes,maxDownloadSizeBytes));
}
// Clamp the download size to sizeBytes if maxDownloadSizeBytes is specified
// (i.e not zero) and greater than the size of the file.
vardownloadSizeBytes=(maxDownloadSizeBytes>0&&maxDownloadSizeBytes<sizeBytes)?
maxDownloadSizeBytes:sizeBytes;
Logger.LogMessage(LogLevel.Debug,String.Format("Downloading {0} bytes",
downloadSizeBytes));
vardownloadState=newDownloadState(this,downloadSizeBytes);
vartransferStateUpdater=newTransferStateUpdater<DownloadState>(
this,progressHandler,downloadState,downloadState.State);
varbytes=newbyte[downloadSizeBytes];
varbytesHandle=GCHandle.Alloc(bytes,GCHandleType.Pinned);
GetBytesUsingMonitorControllerAsync(
bytesHandle.AddrOfPinnedObject(),(uint)bytes.Length,
transferStateUpdater.MonitorController,cancelToken).ContinueWith(downloadTask =>{
bytesHandle.Free();
CompleteTask(downloadTask,result,()=>{
if(faultException!=null){
result.SetException(faultException);
}
returnbytes;
},"GetBytes");
});
});
returnresult.Task;
}
/// <summary>
/// Call Internal.GetFileUsingMonitorControllerAsync while maintaining a reference to
/// monitorController until the operation is complete.
/// </summary>
/// <param name="path">Path (URI string) of the file to read to.</param>
/// <param name="monitorController">Object that can be used to monitor and control the
/// transfer.</param>
/// <param name="cancellationToken">Token which can be used to cancel the transfer.</param>
/// <returns>Task that indicates when the download is complete.
/// NOTE: This task is the object constructed from firebase::Future.</returns>
privateTask<long>GetFileUsingMonitorControllerAsync(
stringpath,MonitorControllerInternalmonitorController,
CancellationTokencancellationToken){
vartask=Internal.GetFileUsingMonitorControllerAsync(path,monitorController);
monitorController.RegisterCancellationToken(cancellationToken);
returntask.ContinueWith(completedTask =>{
monitorController.Dispose();
returncompletedTask;
}).Unwrap();
}
/// <summary>
/// Downloads the object at this
/// <see cref="StorageReference" />
/// to a specified system
/// filepath.
/// </summary>
/// <param name="destinationFilePath">
/// A file system URI representing the path the object should be
/// downloaded to.
/// </param>
/// <param name="progressHandler">
/// usually an instance of <see cref="StorageProgress"/> that will
/// receive periodic updates during the operation. This value can
/// be null.</param>
/// <param name="cancelToken">A CancellationToken to control the operation
/// and possibly later cancel it. This value may be CancellationToken.None
/// to indicate no value.</param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTaskGetFileAsync(stringdestinationFilePath,
IProgress<DownloadState>progressHandler=null,
CancellationTokencancelToken=default(CancellationToken)){
Logger.LogMessage(LogLevel.Debug,String.Format("Downloading to {0}.",
destinationFilePath));
vardownloadState=newDownloadState(this,-1);
vartransferStateUpdater=newTransferStateUpdater<DownloadState>(
this,progressHandler,downloadState,downloadState.State);
returnGetFileUsingMonitorControllerAsync(
destinationFilePath,transferStateUpdater.MonitorController,
cancelToken).ContinueWith((task)=>{
return(newTaskCompletionStatus(task,"GetFile",Logger)).ToTask();
}).Unwrap();
}
/// <summary>
/// Downloads the object at this
/// <see cref="StorageReference" />
/// via a
/// <see cref="Stream" />
/// .
/// The resulting InputStream should be not be accessed on the main thread
/// because calling into it may block the calling thread.
/// </summary>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation.
/// </returns>
publicTask<Stream>GetStreamAsync(){
varresult=newTaskCompletionSource<Stream>();
// TODO(smiles): Fix this interface as it's totally odd. Reading an entire file into a stream
// seems broken rather than simply providing a stream with a small-ish buffer that blocks
// downloading when it's not being read and is complete when it is closed.
// Also, this doesn't support progress reporting or cancellation.
GetBytesAsync(0).ContinueWith(task =>{
CompleteTask(task,result,()=>{
varbytes=task.Result;
returnbytes!=null?newMemoryStream(bytes):null;
},
"GetStreamAsync");
});
returnresult.Task;
}
/// <summary>
/// Downloads the object at this
/// <see cref="StorageReference" />
/// via a
/// <see cref="Stream" />
/// .
/// </summary>
/// <param name="streamProcessor">
/// A delegate
/// that is responsible for
/// reading data from the
/// <see cref="Stream" />
/// .
/// The delegate
/// is called on a background
/// thread and exceptions thrown from this object will be returned as
/// a failure to the Task
/// </param>
/// <param name="progressHandler">
/// usually an instance of <see cref="StorageProgress"/> that will
/// receive periodic updates during the operation. This value can
/// be null.</param>
/// <param name="cancelToken">A CancellationToken to control the operation
/// and possibly later cancel it. This value may be CancellationToken.None
/// to indicate no value.</param>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTaskGetStreamAsync(Action<Stream>streamProcessor,
IProgress<DownloadState>progressHandler=null,
CancellationTokencancelToken=default(CancellationToken)){
// TODO(smiles): *STOP SHIP* Fix streaming support. b/68200113
returnGetBytesAsync(0,progressHandler:progressHandler,
cancelToken:cancelToken).ContinueWith(task =>{
if(!task.IsFaulted&&!task.IsCanceled){
varbytes=task.Result;
if(bytes!=null){
streamProcessor(newMemoryStream(bytes));
}
}
returntask;
}).Unwrap();
}
/// <summary>
/// Deletes the object at this
/// <see cref="StorageReference" />
/// .
/// </summary>
/// <returns>
/// A <see cref="Task"/>
/// which can be used to monitor the operation and obtain the result.
/// </returns>
publicTaskDeleteAsync(){
returnInternal.DeleteAsync().ContinueWith((task)=>{
if(task.IsFaulted&&(task.Exception!=null)){
returnTask.Run(()=>{throwStorageException.CreateFromException(task.Exception);});
}
returntask;
}).Unwrap();
}
/// <returns>
/// This object in URI form, which can then be shared and passed into
/// <see cref="FirebaseStorage.GetReferenceFromUrl" />
/// .
/// </returns>
publicoverridestringToString(){
returnString.Format("gs://{0}{1}",Bucket,Path);
}
/// <summary>
/// Compares two storage reference URIs.
/// </summary>
/// <returns>true if two references point to the same path, false otherwise.</returns>
publicoverrideboolEquals(objectother){
if(!(otherisStorageReference)){
returnfalse;
}
varotherStorage=(StorageReference)other;
returnotherStorage.ToString().Equals(ToString());
}
/// <summary>
/// Create a hash of the URI string used by this reference.
/// </summary>
/// <returns>Hash of this reference's URI.</returns>
publicoverrideintGetHashCode(){
returnToString().GetHashCode();
}
// C# proxy for the firebase::storage::StorageReference object.
internalStorageReferenceInternalInternal{get;privateset;}
/// <summary>
/// Complete the specified task by either setting a result on the completion source or
/// forwarding the failures status from the completion source.
/// </summary>
/// <param name="task">Task to read completion status from.</param>
/// <param name="completionSource">Completion source to set the result on.</param>
/// <param name="getResult">Function that is called if the task successfully completed. This
/// function should return the result if it succeeded or null if it failed.</param>
/// <param name="operationDescription">Description of the operation being completed. This is
/// used to log the completion and to form the exception string when setting an
/// InvalidOperationException on the task, if the task failed but didn't contain an exception.
/// </param>
/// <param name="setCompletionSourceResult">Whether to set the result on the task completion
/// source. This can be disabled if the completion of the completionSource should occur
/// outside of this method.</param>
/// <param name="operationDescription">Description of the operation being completed used when
/// logging is enabled.</param>
/// <returns>Value returned by setResult() if successful, null otherwise.</returns>
privateOCompleteTask<I,O>(Task<I>task,TaskCompletionSource<O>completionSource,
Func<O>getResult,stringoperationDescription,
boolsetCompletionSourceResult=true){
Oresult=default(O);
varstatus=newTaskCompletionStatus(task,operationDescription,Logger);
if(status.IsSuccessful){
result=getResult();
if(result!=null){
if(setCompletionSourceResult)completionSource.SetResult(result);
returnresult;
}
}
if(status.IsCanceled){
completionSource.SetCanceled();
returnresult;
}
completionSource.SetException(status.Exception);
returnresult;
}
}
}