/
FLTFirebaseStoragePlugin.m
901 lines (795 loc) 路 38.3 KB
/
FLTFirebaseStoragePlugin.m
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
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <TargetConditionals.h>
#import <Firebase/Firebase.h>
#import <FirebaseStorage/FIRStorageTypedefs.h>
#import <firebase_core/FLTFirebasePluginRegistry.h>
#import "FLTFirebaseStoragePlugin.h"
static NSString *const kFLTFirebaseStorageChannelName = @"plugins.flutter.io/firebase_storage";
static NSString *const kFLTFirebaseStorageKeyCacheControl = @"cacheControl";
static NSString *const kFLTFirebaseStorageKeyContentDisposition = @"contentDisposition";
static NSString *const kFLTFirebaseStorageKeyContentEncoding = @"contentEncoding";
static NSString *const kFLTFirebaseStorageKeyContentLanguage = @"contentLanguage";
static NSString *const kFLTFirebaseStorageKeyContentType = @"contentType";
static NSString *const kFLTFirebaseStorageKeyCustomMetadata = @"customMetadata";
static NSString *const kFLTFirebaseStorageKeyName = @"name";
static NSString *const kFLTFirebaseStorageKeyBucket = @"bucket";
static NSString *const kFLTFirebaseStorageKeyGeneration = @"generation";
static NSString *const kFLTFirebaseStorageKeyMetadataGeneration = @"metadataGeneration";
static NSString *const kFLTFirebaseStorageKeyFullPath = @"fullPath";
static NSString *const kFLTFirebaseStorageKeySize = @"size";
static NSString *const kFLTFirebaseStorageKeyCreationTime = @"creationTimeMillis";
static NSString *const kFLTFirebaseStorageKeyUpdatedTime = @"updatedTimeMillis";
static NSString *const kFLTFirebaseStorageKeyMD5Hash = @"md5Hash";
static NSString *const kFLTFirebaseStorageKeyAppName = @"appName";
static NSString *const kFLTFirebaseStorageKeyMaxOperationRetryTime = @"maxOperationRetryTime";
static NSString *const kFLTFirebaseStorageKeyMaxDownloadRetryTime = @"maxDownloadRetryTime";
static NSString *const kFLTFirebaseStorageKeyMaxUploadRetryTime = @"maxUploadRetryTime";
static NSString *const kFLTFirebaseStorageKeyPath = @"path";
static NSString *const kFLTFirebaseStorageKeySnapshot = @"snapshot";
static NSString *const kFLTFirebaseStorageKeyHandle = @"handle";
static NSString *const kFLTFirebaseStorageKeyMetadata = @"metadata";
static NSString *const kFLTFirebaseStorageKeyPageToken = @"pageToken";
static NSString *const kFLTFirebaseStorageKeyOptions = @"options";
static NSString *const kFLTFirebaseStorageKeyMaxResults = @"maxResults";
static NSString *const kFLTFirebaseStorageKeyItems = @"items";
static NSString *const kFLTFirebaseStorageKeyPrefixes = @"prefixes";
static NSString *const kFLTFirebaseStorageKeyNextPageToken = @"nextPageToken";
static NSString *const kFLTFirebaseStorageKeyMaxSize = @"maxSize";
typedef NS_ENUM(NSUInteger, FLTFirebaseStorageTaskState) {
FLTFirebaseStorageTaskStateCancel = 0,
FLTFirebaseStorageTaskStatePause = 1,
FLTFirebaseStorageTaskStateResume = 2,
};
typedef NS_ENUM(NSUInteger, FLTFirebaseStorageTaskType) {
FLTFirebaseStorageTaskTypeFile = 0,
FLTFirebaseStorageTaskTypeBytes = 1,
FLTFirebaseStorageTaskTypeDownload = 2,
FLTFirebaseStorageTaskTypeString = 3,
};
typedef NS_ENUM(NSUInteger, FLTFirebaseStorageStringType) {
// FLTFirebaseStorageStringTypeRaw = 0, // unused
FLTFirebaseStorageStringTypeBase64 = 1,
FLTFirebaseStorageStringTypeBase64URL = 2,
// FLTFirebaseStorageStringTypeDataUrl = 3, // unused
};
@interface FLTFirebaseStoragePlugin ()
@property(nonatomic, retain) FlutterMethodChannel *channel;
@end
@implementation FLTFirebaseStoragePlugin {
NSMutableDictionary<NSNumber *, FIRStorageObservableTask<FIRStorageTaskManagement> *> *_tasks;
dispatch_queue_t _callbackQueue;
}
#pragma mark - FlutterPlugin
// Returns a singleton instance of the Firebase Storage plugin.
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
static FLTFirebaseStoragePlugin *instance;
dispatch_once(&onceToken, ^{
instance = [[FLTFirebaseStoragePlugin alloc] init];
// Register with the Flutter Firebase plugin registry.
[[FLTFirebasePluginRegistry sharedInstance] registerFirebasePlugin:instance];
});
return instance;
}
- (instancetype)init {
self = [super init];
if (self) {
_tasks = [NSMutableDictionary<NSNumber *, FIRStorageObservableTask<FIRStorageTaskManagement> *>
dictionary];
_callbackQueue =
dispatch_queue_create("io.flutter.plugins.firebase.storage", DISPATCH_QUEUE_SERIAL);
}
return self;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:kFLTFirebaseStorageChannelName
binaryMessenger:[registrar messenger]];
FLTFirebaseStoragePlugin *instance = [FLTFirebaseStoragePlugin sharedInstance];
instance.channel = channel;
#if TARGET_OS_OSX
// TODO(Salakar): Publish does not exist on MacOS version of FlutterPluginRegistrar.
#else
[registrar publish:instance];
#endif
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)cleanupWithCompletion:(void (^)(void))completion {
@synchronized(self->_tasks) {
for (NSNumber *key in [self->_tasks allKeys]) {
FIRStorageObservableTask<FIRStorageTaskManagement> *task = self->_tasks[key];
if (task != nil) {
[task removeAllObservers];
[task cancel];
}
}
[self->_tasks removeAllObjects];
if (completion != nil) completion();
}
}
- (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
[self cleanupWithCompletion:^() {
self.channel = nil;
}];
}
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)flutterResult {
FLTFirebaseMethodCallErrorBlock errorBlock = ^(
NSString *_Nullable code, NSString *_Nullable message, NSDictionary *_Nullable details,
NSError *_Nullable error) {
if (code == nil) {
NSDictionary *errorDetails = [self NSDictionaryFromNSError:error];
code = errorDetails[@"code"];
message = errorDetails[@"message"];
details = errorDetails;
}
if ([@"unknown" isEqualToString:code]) {
NSLog(@"FLTFirebaseStorage: An unknown error occurred while calling method %@", call.method);
}
flutterResult([FLTFirebasePlugin createFlutterErrorFromCode:code
message:message
optionalDetails:details
andOptionalNSError:error]);
};
FLTFirebaseMethodCallResult *methodCallResult =
[FLTFirebaseMethodCallResult createWithSuccess:flutterResult andErrorBlock:errorBlock];
if ([@"Storage#useEmulator" isEqualToString:call.method]) {
[self useEmulator:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#delete" isEqualToString:call.method]) {
[self referenceDelete:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#getDownloadURL" isEqualToString:call.method]) {
[self referenceGetDownloadUrl:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#getMetadata" isEqualToString:call.method]) {
[self referenceGetMetadata:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#getData" isEqualToString:call.method]) {
[self referenceGetData:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#list" isEqualToString:call.method]) {
[self referenceList:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#listAll" isEqualToString:call.method]) {
[self referenceListAll:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Reference#updateMetadata" isEqualToString:call.method]) {
[self referenceUpdateMetadata:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#startPutData" isEqualToString:call.method]) {
[self taskStartPutData:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#startPutString" isEqualToString:call.method]) {
[self taskStartPutString:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#startPutFile" isEqualToString:call.method]) {
[self taskStartPutFile:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#pause" isEqualToString:call.method]) {
[self taskPause:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#resume" isEqualToString:call.method]) {
[self taskResume:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#cancel" isEqualToString:call.method]) {
[self taskCancel:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Task#writeToFile" isEqualToString:call.method]) {
[self taskWriteToFile:call.arguments withMethodCallResult:methodCallResult];
} else {
flutterResult(FlutterMethodNotImplemented);
}
}
#pragma mark - Firebase Storage API
- (void)useEmulator:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
[self FIRStorageForArguments:arguments];
result.success(nil);
}
- (void)referenceDelete:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
[reference deleteWithCompletion:^(NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)referenceGetDownloadUrl:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
[reference downloadURLWithCompletion:^(NSURL *URL, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
NSString *url = URL.absoluteString;
if ([url rangeOfString:@":443"].location != NSNotFound) {
NSRange replaceRange = [url rangeOfString:@":443"];
url = [url stringByReplacingCharactersInRange:replaceRange withString:@""];
}
result.success(@{
@"downloadURL" : url,
});
}
}];
}
- (void)referenceGetMetadata:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
[reference metadataWithCompletion:^(FIRStorageMetadata *metadata, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success([self NSDictionaryFromFIRStorageMetadata:metadata]);
}
}];
}
- (void)referenceGetData:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
NSNumber *maxSize = arguments[kFLTFirebaseStorageKeyMaxSize];
[reference dataWithMaxSize:[maxSize longLongValue]
completion:^(NSData *_Nullable data, NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
return;
}
FlutterStandardTypedData *typedData;
if (data == nil) {
typedData =
[FlutterStandardTypedData typedDataWithBytes:[[NSData alloc] init]];
} else {
typedData = [FlutterStandardTypedData typedDataWithBytes:data];
}
result.success(typedData);
}];
}
- (void)referenceList:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
NSDictionary *options = arguments[kFLTFirebaseStorageKeyOptions];
long maxResults = [options[kFLTFirebaseStorageKeyMaxResults] longValue];
id completion = ^(FIRStorageListResult *listResult, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success([self NSDictionaryFromFIRStorageListResult:listResult]);
}
};
NSString *pageToken = options[kFLTFirebaseStorageKeyPageToken];
if ([pageToken isEqual:[NSNull null]]) {
[reference listWithMaxResults:(int64_t)maxResults completion:completion];
} else {
[reference listWithMaxResults:(int64_t)maxResults pageToken:pageToken completion:completion];
}
}
- (void)referenceListAll:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
[reference listAllWithCompletion:^(FIRStorageListResult *listResult, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success([self NSDictionaryFromFIRStorageListResult:listResult]);
}
}];
}
- (void)referenceUpdateMetadata:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
FIRStorageMetadata *metadata =
[self FIRStorageMetadataFromNSDictionary:arguments[kFLTFirebaseStorageKeyMetadata]];
[reference updateMetadata:metadata
completion:^(FIRStorageMetadata *updatedMetadata, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success([self NSDictionaryFromFIRStorageMetadata:updatedMetadata]);
}
}];
}
- (void)taskStartPutData:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
[self startFIRStorageObservableTaskForArguments:arguments
andFLTFirebaseStorageTaskType:FLTFirebaseStorageTaskTypeBytes];
result.success(nil);
}
- (void)taskStartPutString:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
[self startFIRStorageObservableTaskForArguments:arguments
andFLTFirebaseStorageTaskType:FLTFirebaseStorageTaskTypeString];
result.success(nil);
}
- (void)taskStartPutFile:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
[self startFIRStorageObservableTaskForArguments:arguments
andFLTFirebaseStorageTaskType:FLTFirebaseStorageTaskTypeFile];
result.success(nil);
}
- (void)taskWriteToFile:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
[self startFIRStorageObservableTaskForArguments:arguments
andFLTFirebaseStorageTaskType:FLTFirebaseStorageTaskTypeDownload];
result.success(nil);
}
- (void)taskPause:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
dispatch_async(self->_callbackQueue, ^() {
NSNumber *handle = arguments[kFLTFirebaseStorageKeyHandle];
FIRStorageObservableTask<FIRStorageTaskManagement> *task;
@synchronized(self->_tasks) {
task = self->_tasks[handle];
}
if (task != nil) {
[self setState:FLTFirebaseStorageTaskStatePause
forFIRStorageObservableTask:task
withCompletion:^(BOOL success, NSDictionary *snapshotDict) {
result.success(@{
@"status" : @(success),
@"snapshot" : (id)snapshotDict ?: [NSNull null],
});
}];
} else {
result.success(@{
@"status" : @(NO),
});
}
});
}
- (void)taskResume:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
dispatch_async(self->_callbackQueue, ^() {
NSNumber *handle = arguments[kFLTFirebaseStorageKeyHandle];
FIRStorageObservableTask<FIRStorageTaskManagement> *task;
@synchronized(self->_tasks) {
task = self->_tasks[handle];
}
if (task != nil) {
[self setState:FLTFirebaseStorageTaskStateResume
forFIRStorageObservableTask:task
withCompletion:^(BOOL success, NSDictionary *snapshotDict) {
result.success(@{
@"status" : @(success),
@"snapshot" : (id)snapshotDict ?: [NSNull null],
});
}];
} else {
result.success(@{
@"status" : @(NO),
});
}
});
}
- (void)taskCancel:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
dispatch_async(self->_callbackQueue, ^() {
NSNumber *handle = arguments[kFLTFirebaseStorageKeyHandle];
FIRStorageObservableTask<FIRStorageTaskManagement> *task;
@synchronized(self->_tasks) {
task = self->_tasks[handle];
}
if (task != nil) {
[self setState:FLTFirebaseStorageTaskStateCancel
forFIRStorageObservableTask:task
withCompletion:^(BOOL success, NSDictionary *snapshotDict) {
result.success(@{
@"status" : @(success),
@"snapshot" : (id)snapshotDict ?: [NSNull null],
});
}];
} else {
result.success(@{
@"status" : @(NO),
});
}
});
}
#pragma mark - Utilities
// To match Web & Android SDKs we need to return a bool of whether a task state change was
// successful.
- (void)setState:(FLTFirebaseStorageTaskState)state
forFIRStorageObservableTask:(FIRStorageObservableTask<FIRStorageTaskManagement> *)task
withCompletion:(void (^)(BOOL, NSDictionary *))completion {
// Pause
if (state == FLTFirebaseStorageTaskStatePause) {
if (task.snapshot.status == FIRStorageTaskStatusResume ||
task.snapshot.status == FIRStorageTaskStatusProgress ||
task.snapshot.status == FIRStorageTaskStatusUnknown) {
__block FIRStorageHandle pauseHandle;
__block FIRStorageHandle successHandle;
__block FIRStorageHandle failureHandle;
pauseHandle =
[task observeStatus:FIRStorageTaskStatusPause
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:pauseHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(YES, [self NSDictionaryFromFIRStorageTaskSnapshot:snapshot]);
}];
successHandle = [task observeStatus:FIRStorageTaskStatusSuccess
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:pauseHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(NO, nil);
}];
failureHandle = [task observeStatus:FIRStorageTaskStatusFailure
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:pauseHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(NO, nil);
}];
[task pause];
} else {
completion(NO, nil);
}
return;
}
// Resume
if (state == FLTFirebaseStorageTaskStateResume) {
if (task.snapshot.status == FIRStorageTaskStatusPause) {
__block FIRStorageHandle resumeHandle;
__block FIRStorageHandle progressHandle;
__block FIRStorageHandle successHandle;
__block FIRStorageHandle failureHandle;
resumeHandle =
[task observeStatus:FIRStorageTaskStatusResume
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:resumeHandle];
[task removeObserverWithHandle:progressHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(YES, [self NSDictionaryFromFIRStorageTaskSnapshot:snapshot]);
}];
progressHandle =
[task observeStatus:FIRStorageTaskStatusProgress
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:resumeHandle];
[task removeObserverWithHandle:progressHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(YES, [self NSDictionaryFromFIRStorageTaskSnapshot:snapshot]);
}];
successHandle = [task observeStatus:FIRStorageTaskStatusSuccess
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:resumeHandle];
[task removeObserverWithHandle:progressHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(NO, nil);
}];
failureHandle = [task observeStatus:FIRStorageTaskStatusFailure
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:resumeHandle];
[task removeObserverWithHandle:progressHandle];
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(NO, nil);
}];
[task resume];
} else {
completion(NO, nil);
}
return;
}
// Cancel
if (state == FLTFirebaseStorageTaskStateCancel) {
if (task.snapshot.status == FIRStorageTaskStatusPause ||
task.snapshot.status == FIRStorageTaskStatusResume ||
task.snapshot.status == FIRStorageTaskStatusProgress ||
task.snapshot.status == FIRStorageTaskStatusUnknown) {
__block FIRStorageHandle successHandle;
__block FIRStorageHandle failureHandle;
successHandle = [task observeStatus:FIRStorageTaskStatusSuccess
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
completion(NO, nil);
}];
failureHandle =
[task observeStatus:FIRStorageTaskStatusFailure
handler:^(FIRStorageTaskSnapshot *snapshot) {
[task removeObserverWithHandle:successHandle];
[task removeObserverWithHandle:failureHandle];
if (snapshot.error && snapshot.error.code == FIRStorageErrorCodeCancelled) {
completion(YES, [self NSDictionaryFromFIRStorageTaskSnapshot:snapshot]);
} else {
completion(NO, nil);
}
}];
[task cancel];
} else {
completion(NO, nil);
}
return;
}
completion(NO, nil);
}
- (void)startFIRStorageObservableTaskForArguments:(id)arguments
andFLTFirebaseStorageTaskType:(FLTFirebaseStorageTaskType)type {
dispatch_async(self->_callbackQueue, ^() {
FIRStorageObservableTask<FIRStorageTaskManagement> *task;
FIRStorageReference *reference = [self FIRStorageReferenceForArguments:arguments];
FIRStorageMetadata *metadata =
[self FIRStorageMetadataFromNSDictionary:arguments[kFLTFirebaseStorageKeyMetadata]];
if (type == FLTFirebaseStorageTaskTypeFile) {
NSURL *fileUrl = [NSURL fileURLWithPath:arguments[@"filePath"]];
task = [reference putFile:fileUrl metadata:metadata];
} else if (type == FLTFirebaseStorageTaskTypeBytes) {
NSData *data = [(FlutterStandardTypedData *)arguments[@"data"] data];
task = [reference putData:data metadata:metadata];
} else if (type == FLTFirebaseStorageTaskTypeDownload) {
NSURL *fileUrl = [NSURL fileURLWithPath:arguments[@"filePath"]];
task = [reference writeToFile:fileUrl];
} else if (type == FLTFirebaseStorageTaskTypeString) {
NSData *data = [self
NSDataFromUploadString:arguments[@"data"]
format:(FLTFirebaseStorageStringType)[arguments[@"format"] intValue]];
task = [reference putData:data metadata:metadata];
}
NSNumber *handle = arguments[kFLTFirebaseStorageKeyHandle];
__weak FLTFirebaseStoragePlugin *weakSelf = self;
@synchronized(self->_tasks) {
self->_tasks[handle] = task;
}
// upload paused
[task observeStatus:FIRStorageTaskStatusPause
handler:^(FIRStorageTaskSnapshot *snapshot) {
dispatch_async(self->_callbackQueue, ^() {
[weakSelf.channel invokeMethod:@"Task#onPaused"
arguments:[weakSelf NSDictionaryFromHandle:handle
andFIRStorageTaskSnapshot:snapshot]];
});
}];
// upload reported progress
[task observeStatus:FIRStorageTaskStatusProgress
handler:^(FIRStorageTaskSnapshot *snapshot) {
dispatch_async(self->_callbackQueue, ^() {
[weakSelf.channel invokeMethod:@"Task#onProgress"
arguments:[weakSelf NSDictionaryFromHandle:handle
andFIRStorageTaskSnapshot:snapshot]];
});
}];
// upload completed successfully
[task observeStatus:FIRStorageTaskStatusSuccess
handler:^(FIRStorageTaskSnapshot *snapshot) {
dispatch_async(self->_callbackQueue, ^() {
@synchronized(self->_tasks) {
[self->_tasks removeObjectForKey:handle];
}
[weakSelf.channel invokeMethod:@"Task#onSuccess"
arguments:[weakSelf NSDictionaryFromHandle:handle
andFIRStorageTaskSnapshot:snapshot]];
});
}];
[task observeStatus:FIRStorageTaskStatusFailure
handler:^(FIRStorageTaskSnapshot *snapshot) {
dispatch_async(self->_callbackQueue, ^() {
@synchronized(self->_tasks) {
[self->_tasks removeObjectForKey:handle];
}
if (snapshot.error.code == FIRStorageErrorCodeCancelled) {
[weakSelf.channel invokeMethod:@"Task#onCanceled"
arguments:[weakSelf NSDictionaryFromHandle:handle
andFIRStorageTaskSnapshot:snapshot]];
} else {
[weakSelf.channel invokeMethod:@"Task#onFailure"
arguments:[weakSelf NSDictionaryFromHandle:handle
andFIRStorageTaskSnapshot:snapshot]];
}
});
}];
});
}
- (NSDictionary *)NSDictionaryFromNSError:(NSError *)error {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSString *code = @"unknown";
NSString *message = [error localizedDescription];
if (error.code == FIRStorageErrorCodeUnknown) {
code = @"unknown";
} else if (error.code == FIRStorageErrorCodeObjectNotFound) {
code = @"object-not-found";
message = @"No object exists at the desired reference.";
} else if (error.code == FIRStorageErrorCodeBucketNotFound) {
code = @"bucket-not-found";
message = @"No bucket is configured for Firebase Storage.";
} else if (error.code == FIRStorageErrorCodeProjectNotFound) {
code = @"project-not-found";
message = @"No project is configured for Firebase Storage.";
} else if (error.code == FIRStorageErrorCodeQuotaExceeded) {
code = @"quota-exceeded";
message = @"Quota on your Firebase Storage bucket has been exceeded.";
} else if (error.code == FIRStorageErrorCodeUnauthenticated) {
code = @"unauthenticated";
message = @"User is unauthenticated. Authenticate and try again.";
} else if (error.code == FIRStorageErrorCodeUnauthorized) {
code = @"unauthorized";
message = @"User is not authorized to perform the desired action.";
} else if (error.code == FIRStorageErrorCodeRetryLimitExceeded) {
code = @"retry-limit-exceeded";
message = @"The maximum time limit on an operation (upload, download, delete, etc.) has been "
@"exceeded.";
} else if (error.code == FIRStorageErrorCodeNonMatchingChecksum) {
code = @"invalid-checksum";
message = @"File on the client does not match the checksum of the file received by the server.";
} else if (error.code == FIRStorageErrorCodeDownloadSizeExceeded) {
code = @"download-size-exceeded";
message =
@"Size of the downloaded file exceeds the amount of memory allocated for the download.";
} else if (error.code == FIRStorageErrorCodeCancelled) {
code = @"canceled";
message = @"User cancelled the operation.";
} else if (error.code == FIRStorageErrorCodeInvalidArgument) {
code = @"invalid-argument";
}
dictionary[@"code"] = code;
dictionary[@"message"] = message;
return dictionary;
}
- (NSDictionary *)NSDictionaryFromHandle:(NSNumber *)handle
andFIRStorageTaskSnapshot:(FIRStorageTaskSnapshot *)snapshot {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
dictionary[kFLTFirebaseStorageKeyHandle] = handle;
dictionary[kFLTFirebaseStorageKeyAppName] =
[FLTFirebasePlugin firebaseAppNameFromIosName:snapshot.reference.storage.app.name];
dictionary[kFLTFirebaseStorageKeyBucket] = snapshot.reference.bucket;
if (snapshot.error != nil) {
dictionary[@"error"] = [self NSDictionaryFromNSError:snapshot.error];
} else {
dictionary[kFLTFirebaseStorageKeySnapshot] =
[self NSDictionaryFromFIRStorageTaskSnapshot:snapshot];
}
return dictionary;
}
- (NSDictionary *)NSDictionaryFromFIRStorageTaskSnapshot:(FIRStorageTaskSnapshot *)snapshot {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
dictionary[kFLTFirebaseStorageKeyPath] = snapshot.reference.fullPath;
if (snapshot.metadata != nil) {
dictionary[@"metadata"] = [self NSDictionaryFromFIRStorageMetadata:snapshot.metadata];
}
if (snapshot.progress != nil) {
dictionary[@"bytesTransferred"] = @(snapshot.progress.completedUnitCount);
dictionary[@"totalBytes"] = @(snapshot.progress.totalUnitCount);
} else {
dictionary[@"bytesTransferred"] = @(0);
dictionary[@"totalBytes"] = @(0);
}
return dictionary;
}
- (NSData *)NSDataFromUploadString:(NSString *)string format:(FLTFirebaseStorageStringType)format {
// Dart: PutStringFormat.base64
if (format == FLTFirebaseStorageStringTypeBase64) {
return [[NSData alloc] initWithBase64EncodedString:string options:0];
}
// Dart: PutStringFormat.base64Url
if (format == FLTFirebaseStorageStringTypeBase64URL) {
// Convert to base64 from base64url.
NSString *base64Encoded = string;
base64Encoded = [base64Encoded stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
base64Encoded = [base64Encoded stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
// Add mandatory base64 encoding padding.
while (base64Encoded.length % 4 != 0) {
base64Encoded = [base64Encoded stringByAppendingString:@"="];
}
return [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];
}
return nil;
}
- (NSDictionary *)NSDictionaryFromFIRStorageListResult:(FIRStorageListResult *)listResult {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableArray<NSString *> *items = [[NSMutableArray alloc] init];
for (FIRStorageReference *reference in listResult.items) {
[items addObject:reference.fullPath];
}
dictionary[kFLTFirebaseStorageKeyItems] = items;
NSMutableArray<NSString *> *prefixes = [[NSMutableArray alloc] init];
for (FIRStorageReference *reference in listResult.prefixes) {
[prefixes addObject:reference.fullPath];
}
dictionary[kFLTFirebaseStorageKeyPrefixes] = prefixes;
if (listResult.pageToken != nil) {
dictionary[kFLTFirebaseStorageKeyNextPageToken] = listResult.pageToken;
}
return dictionary;
}
- (FIRStorageMetadata *)FIRStorageMetadataFromNSDictionary:(NSDictionary *)dictionary {
if (dictionary == nil || [dictionary isEqual:[NSNull null]]) return nil;
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
if (dictionary[kFLTFirebaseStorageKeyCacheControl] != [NSNull null]) {
metadata.cacheControl = dictionary[kFLTFirebaseStorageKeyCacheControl];
}
if (dictionary[kFLTFirebaseStorageKeyContentDisposition] != [NSNull null]) {
metadata.contentDisposition = dictionary[kFLTFirebaseStorageKeyContentDisposition];
}
if (dictionary[kFLTFirebaseStorageKeyContentEncoding] != [NSNull null]) {
metadata.contentEncoding = dictionary[kFLTFirebaseStorageKeyContentEncoding];
}
if (dictionary[kFLTFirebaseStorageKeyContentLanguage] != [NSNull null]) {
metadata.contentLanguage = dictionary[kFLTFirebaseStorageKeyContentLanguage];
}
if (dictionary[kFLTFirebaseStorageKeyContentType] != [NSNull null]) {
metadata.contentType = dictionary[kFLTFirebaseStorageKeyContentType];
}
if (dictionary[kFLTFirebaseStorageKeyCustomMetadata] != [NSNull null]) {
metadata.customMetadata = dictionary[kFLTFirebaseStorageKeyCustomMetadata];
}
return metadata;
}
- (NSDictionary *)NSDictionaryFromFIRStorageMetadata:(FIRStorageMetadata *)metadata {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:[metadata name] forKey:kFLTFirebaseStorageKeyName];
[dictionary setValue:[metadata bucket] forKey:kFLTFirebaseStorageKeyBucket];
[dictionary setValue:[NSString stringWithFormat:@"%lld", [metadata generation]]
forKey:kFLTFirebaseStorageKeyGeneration];
[dictionary setValue:[NSString stringWithFormat:@"%lld", [metadata metageneration]]
forKey:kFLTFirebaseStorageKeyMetadataGeneration];
[dictionary setValue:[metadata path] forKey:kFLTFirebaseStorageKeyFullPath];
[dictionary setValue:@([metadata size]) forKey:kFLTFirebaseStorageKeySize];
[dictionary setValue:@((long)([[metadata timeCreated] timeIntervalSince1970] * 1000.0))
forKey:kFLTFirebaseStorageKeyCreationTime];
[dictionary setValue:@((long)([[metadata updated] timeIntervalSince1970] * 1000.0))
forKey:kFLTFirebaseStorageKeyUpdatedTime];
if ([metadata md5Hash] != nil) {
[dictionary setValue:[metadata md5Hash] forKey:kFLTFirebaseStorageKeyMD5Hash];
}
if ([metadata cacheControl] != nil) {
[dictionary setValue:[metadata cacheControl] forKey:kFLTFirebaseStorageKeyCacheControl];
}
if ([metadata contentDisposition] != nil) {
[dictionary setValue:[metadata contentDisposition]
forKey:kFLTFirebaseStorageKeyContentDisposition];
}
if ([metadata contentEncoding] != nil) {
[dictionary setValue:[metadata contentEncoding] forKey:kFLTFirebaseStorageKeyContentEncoding];
}
if ([metadata contentLanguage] != nil) {
[dictionary setValue:[metadata contentLanguage] forKey:kFLTFirebaseStorageKeyContentLanguage];
}
if ([metadata contentType] != nil) {
[dictionary setValue:[metadata contentType] forKey:kFLTFirebaseStorageKeyContentType];
}
if ([metadata customMetadata] != nil) {
[dictionary setValue:[metadata customMetadata] forKey:kFLTFirebaseStorageKeyCustomMetadata];
} else {
[dictionary setValue:@{} forKey:kFLTFirebaseStorageKeyCustomMetadata];
}
return dictionary;
}
- (FIRStorage *)FIRStorageForArguments:(id)arguments {
FIRStorage *storage;
NSString *appName = arguments[kFLTFirebaseStorageKeyAppName];
NSString *bucket = arguments[kFLTFirebaseStorageKeyBucket];
FIRApp *firebaseApp = [FLTFirebasePlugin firebaseAppNamed:appName];
if (![bucket isEqual:[NSNull null]] && bucket != nil) {
NSString *url = [@"gs://" stringByAppendingString:bucket];
storage = [FIRStorage storageForApp:firebaseApp URL:url];
} else {
storage = [FIRStorage storageForApp:firebaseApp];
}
NSNumber *maxOperationRetryTime = arguments[kFLTFirebaseStorageKeyMaxOperationRetryTime];
if (![maxOperationRetryTime isEqual:[NSNull null]]) {
storage.maxOperationRetryTime = [maxOperationRetryTime longLongValue] / 1000.0;
}
NSNumber *maxDownloadRetryTime = arguments[kFLTFirebaseStorageKeyMaxDownloadRetryTime];
if (![maxDownloadRetryTime isEqual:[NSNull null]]) {
storage.maxDownloadRetryTime = [maxDownloadRetryTime longLongValue] / 1000.0;
}
NSNumber *maxUploadRetryTime = arguments[kFLTFirebaseStorageKeyMaxUploadRetryTime];
if (![maxUploadRetryTime isEqual:[NSNull null]]) {
storage.maxUploadRetryTime = [maxUploadRetryTime longLongValue] / 1000.0;
}
NSString *emulatorHost = arguments[@"host"];
if (![emulatorHost isEqual:[NSNull null]] && emulatorHost != nil) {
@try {
[storage useEmulatorWithHost:emulatorHost port:[arguments[@"port"] integerValue]];
} @catch (NSException *e) {
NSLog(@"WARNING: Unable to set the Firebase Storage emulator settings. These must be set "
@"before any usages of Firebase Storage. If you see this log after a hot "
@"reload/restart you can safely ignore it.");
}
}
storage.callbackQueue = _callbackQueue;
return storage;
}
- (FIRStorageReference *)FIRStorageReferenceForArguments:(id)arguments {
NSString *path = arguments[kFLTFirebaseStorageKeyPath];
FIRStorage *storage = [self FIRStorageForArguments:arguments];
return [storage referenceWithPath:path];
}
#pragma mark - FLTFirebasePlugin
- (void)didReinitializeFirebaseCore:(void (^)(void))completion {
[self cleanupWithCompletion:completion];
}
- (NSDictionary *_Nonnull)pluginConstantsForFIRApp:(FIRApp *)firebase_app {
return @{};
}
- (NSString *_Nonnull)firebaseLibraryName {
return LIBRARY_NAME;
}
- (NSString *_Nonnull)firebaseLibraryVersion {
return LIBRARY_VERSION;
}
- (NSString *_Nonnull)flutterChannelName {
return kFLTFirebaseStorageChannelName;
}
@end