-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathFirestackStorage.m
More file actions
385 lines (339 loc) · 15.4 KB
/
FirestackStorage.m
File metadata and controls
385 lines (339 loc) · 15.4 KB
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
//
// FirestackStorage.m
// Firestack
//
// Created by Ari Lerner on 8/24/16.
// Copyright © 2016 Facebook. All rights reserved.
//
#import "FirestackStorage.h"
#import "FirestackEvents.h"
#import <Photos/Photos.h>
@implementation FirestackStorage
RCT_EXPORT_MODULE(FirestackStorage);
// Run on a different thread
- (dispatch_queue_t)methodQueue
{
return dispatch_queue_create("io.fullstack.firestack.storage", DISPATCH_QUEUE_SERIAL);
}
RCT_EXPORT_METHOD(delete: (NSString *) path
callback:(RCTResponseSenderBlock) callback)
{
FIRStorageReference *fileRef = [self getReference:path];
[fileRef deleteWithCompletion:^(NSError * _Nullable error) {
if (error == nil) {
NSDictionary *resp = @{
@"status": @"success",
@"path": path
};
callback(@[[NSNull null], resp]);
} else {
NSDictionary *evt = @{
@"status": @"error",
@"path": path,
@"message": [error debugDescription]
};
callback(@[evt]);
}
}];
}
RCT_EXPORT_METHOD(getDownloadURL: (NSString *) path
callback:(RCTResponseSenderBlock) callback)
{
FIRStorageReference *fileRef = [self getReference:path];
[fileRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
if (error != nil) {
NSDictionary *evt = @{
@"status": @"error",
@"path": path,
@"message": [error debugDescription]
};
callback(@[evt]);
} else {
callback(@[[NSNull null], [URL absoluteString]]);
}
}];
}
RCT_EXPORT_METHOD(getMetadata: (NSString *) path
callback:(RCTResponseSenderBlock) callback)
{
FIRStorageReference *fileRef = [self getReference:path];
[fileRef metadataWithCompletion:^(FIRStorageMetadata * _Nullable metadata, NSError * _Nullable error) {
if (error != nil) {
NSDictionary *evt = @{
@"status": @"error",
@"path": path,
@"message": [error debugDescription]
};
callback(@[evt]);
} else {
NSDictionary *resp = [metadata dictionaryRepresentation];
callback(@[[NSNull null], resp]);
}
}];
}
RCT_EXPORT_METHOD(updateMetadata: (NSString *) path
metadata:(NSDictionary *) metadata
callback:(RCTResponseSenderBlock) callback)
{
FIRStorageReference *fileRef = [self getReference:path];
FIRStorageMetadata *firmetadata = [[FIRStorageMetadata alloc] initWithDictionary:metadata];
[fileRef updateMetadata:firmetadata completion:^(FIRStorageMetadata * _Nullable metadata, NSError * _Nullable error) {
if (error != nil) {
NSDictionary *evt = @{
@"status": @"error",
@"path": path,
@"message": [error debugDescription]
};
callback(@[evt]);
} else {
NSDictionary *resp = [metadata dictionaryRepresentation];
callback(@[[NSNull null], resp]);
}
}];
}
RCT_EXPORT_METHOD(downloadFile: (NSString *) path
localPath:(NSString *) localPath
callback:(RCTResponseSenderBlock) callback)
{
FIRStorageReference *fileRef = [self getReference:path];
NSURL *localFile = [NSURL fileURLWithPath:localPath];
FIRStorageDownloadTask *downloadTask = [fileRef writeToFile:localFile];
// Listen for state changes, errors, and completion of the download.
[downloadTask observeStatus:FIRStorageTaskStatusResume handler:^(FIRStorageTaskSnapshot *snapshot) {
// Download resumed, also fires when the upload starts
NSDictionary *event = [self getDownloadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_STATE_CHANGED props:event];
}];
[downloadTask observeStatus:FIRStorageTaskStatusPause handler:^(FIRStorageTaskSnapshot *snapshot) {
// Download paused
NSDictionary *event = [self getDownloadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_STATE_CHANGED props:event];
}];
[downloadTask observeStatus:FIRStorageTaskStatusProgress handler:^(FIRStorageTaskSnapshot *snapshot) {
// Download reported progress
NSDictionary *event = [self getDownloadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_STATE_CHANGED props:event];
}];
[downloadTask observeStatus:FIRStorageTaskStatusSuccess handler:^(FIRStorageTaskSnapshot *snapshot) {
// Download completed successfully
NSDictionary *resp = [self getDownloadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_DOWNLOAD_SUCCESS props:resp];
callback(@[[NSNull null], resp]);
}];
[downloadTask observeStatus:FIRStorageTaskStatusFailure handler:^(FIRStorageTaskSnapshot *snapshot) {
if (snapshot.error != nil) {
NSDictionary *errProps = [[NSMutableDictionary alloc] init];
NSLog(@"Error in download: %@", snapshot.error);
switch (snapshot.error.code) {
case FIRStorageErrorCodeObjectNotFound:
// File doesn't exist
[errProps setValue:@"File does not exist" forKey:@"message"];
break;
case FIRStorageErrorCodeUnauthorized:
// User doesn't have permission to access file
[errProps setValue:@"You do not have permissions" forKey:@"message"];
break;
case FIRStorageErrorCodeCancelled:
// User canceled the upload
[errProps setValue:@"Download canceled" forKey:@"message"];
break;
case FIRStorageErrorCodeUnknown:
// Unknown error occurred, inspect the server response
[errProps setValue:@"Unknown error" forKey:@"message"];
break;
}
//TODO: Error event
callback(@[errProps]);
}}];
}
RCT_EXPORT_METHOD(putFile:(NSString *) path
localPath:(NSString *)localPath
metadata:(NSDictionary *)metadata
callback:(RCTResponseSenderBlock) callback)
{
FIRStorageReference *fileRef = [self getReference:path];
FIRStorageMetadata *firmetadata = [[FIRStorageMetadata alloc] initWithDictionary:metadata];
if ([localPath hasPrefix:@"assets-library://"]) {
NSURL *localFile = [[NSURL alloc] initWithString:localPath];
PHFetchResult* assets = [PHAsset fetchAssetsWithALAssetURLs:@[localFile] options:nil];
PHAsset *asset = [assets firstObject];
[[PHImageManager defaultManager] requestImageDataForAsset:asset
options:nil
resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
FIRStorageUploadTask *uploadTask = [fileRef putData:imageData
metadata:firmetadata];
[self addUploadObservers:uploadTask
path:path
callback:callback];
}];
} else {
NSURL *imageFile = [NSURL fileURLWithPath:localPath];
FIRStorageUploadTask *uploadTask = [fileRef putFile:imageFile
metadata:firmetadata];
[self addUploadObservers:uploadTask
path:path
callback:callback];
}
}
- (void) addUploadObservers:(FIRStorageUploadTask *) uploadTask
path:(NSString *) path
callback:(RCTResponseSenderBlock) callback
{
// Listen for state changes, errors, and completion of the upload.
[uploadTask observeStatus:FIRStorageTaskStatusResume handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload resumed, also fires when the upload starts
NSDictionary *event = [self getUploadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_STATE_CHANGED props:event];
}];
[uploadTask observeStatus:FIRStorageTaskStatusPause handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload paused
NSDictionary *event = [self getUploadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_STATE_CHANGED props:event];
}];
[uploadTask observeStatus:FIRStorageTaskStatusProgress handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload reported progress
NSDictionary *event = [self getUploadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_STATE_CHANGED props:event];
}];
[uploadTask observeStatus:FIRStorageTaskStatusSuccess handler:^(FIRStorageTaskSnapshot *snapshot) {
// Upload completed successfully
NSDictionary *resp = [self getUploadTaskAsDictionary:snapshot];
[self sendJSEvent:STORAGE_EVENT path:path title:STORAGE_UPLOAD_SUCCESS props:resp];
callback(@[[NSNull null], resp]);
}];
[uploadTask observeStatus:FIRStorageTaskStatusFailure handler:^(FIRStorageTaskSnapshot *snapshot) {
if (snapshot.error != nil) {
NSDictionary *errProps = [[NSMutableDictionary alloc] init];
switch (snapshot.error.code) {
case FIRStorageErrorCodeObjectNotFound:
// File doesn't exist
[errProps setValue:@"File does not exist" forKey:@"message"];
break;
case FIRStorageErrorCodeUnauthorized:
// User doesn't have permission to access file
[errProps setValue:@"You do not have permissions" forKey:@"message"];
break;
case FIRStorageErrorCodeCancelled:
// User canceled the upload
[errProps setValue:@"Upload cancelled" forKey:@"message"];
break;
case FIRStorageErrorCodeUnknown:
// Unknown error occurred, inspect the server response
[errProps setValue:@"Unknown error" forKey:@"message"];
break;
}
//TODO: Error event
callback(@[errProps]);
}}];
}
//Firebase.Storage methods
RCT_EXPORT_METHOD(setMaxDownloadRetryTime:(NSNumber *) milliseconds)
{
[[FIRStorage storage] setMaxDownloadRetryTime:[milliseconds doubleValue]];
}
RCT_EXPORT_METHOD(setMaxOperationRetryTime:(NSNumber *) milliseconds)
{
[[FIRStorage storage] setMaxOperationRetryTime:[milliseconds doubleValue]];
}
RCT_EXPORT_METHOD(setMaxUploadRetryTime:(NSNumber *) milliseconds)
{
[[FIRStorage storage] setMaxUploadRetryTime:[milliseconds doubleValue]];
}
- (FIRStorageReference *)getReference:(NSString *)path
{
if ([path hasPrefix:@"url::"]) {
NSString *url = [path substringFromIndex:5];
return [[FIRStorage storage] referenceForURL:url];
} else {
return [[FIRStorage storage] referenceWithPath:path];
}
}
- (NSDictionary *)getDownloadTaskAsDictionary:(FIRStorageTaskSnapshot *)task {
return @{
@"bytesTransferred": @(task.progress.completedUnitCount),
@"ref": task.reference.fullPath,
@"status": [self getTaskStatus:task.status],
@"totalBytes": @(task.progress.totalUnitCount)
};
}
- (NSDictionary *)getUploadTaskAsDictionary:(FIRStorageTaskSnapshot *)task
{
NSString *downloadUrl = [task.metadata.downloadURL absoluteString];
FIRStorageMetadata *metadata = [task.metadata dictionaryRepresentation];
return @{
@"bytesTransferred": @(task.progress.completedUnitCount),
@"downloadUrl": downloadUrl != nil ? downloadUrl : [NSNull null],
@"metadata": metadata != nil ? metadata : [NSNull null],
@"ref": task.reference.fullPath,
@"state": [self getTaskStatus:task.status],
@"totalBytes": @(task.progress.totalUnitCount)
};
}
- (NSString *)getTaskStatus:(FIRStorageTaskStatus)status
{
if (status == FIRStorageTaskStatusResume || status == FIRStorageTaskStatusProgress) {
return @"RUNNING";
} else if (status == FIRStorageTaskStatusPause) {
return @"PAUSED";
} else if (status == FIRStorageTaskStatusSuccess) {
return @"SUCCESS";
} else if (status == FIRStorageTaskStatusFailure) {
return @"ERROR";
} else {
return @"UNKNOWN";
}
}
// This is just too good not to use, but I don't want to take credit for
// this work from RNFS
// https://github.com/johanneslumpe/react-native-fs/blob/master/RNFSManager.m
- (NSString *)getPathForDirectory:(int)directory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
return [paths firstObject];
}
- (NSDictionary *)constantsToExport
{
return @{
@"MAIN_BUNDLE_PATH": [[NSBundle mainBundle] bundlePath],
@"CACHES_DIRECTORY_PATH": [self getPathForDirectory:NSCachesDirectory],
@"DOCUMENT_DIRECTORY_PATH": [self getPathForDirectory:NSDocumentDirectory],
@"EXTERNAL_DIRECTORY_PATH": [NSNull null],
@"EXTERNAL_STORAGE_DIRECTORY_PATH": [NSNull null],
@"TEMP_DIRECTORY_PATH": NSTemporaryDirectory(),
@"LIBRARY_DIRECTORY_PATH": [self getPathForDirectory:NSLibraryDirectory],
@"FILETYPE_REGULAR": NSFileTypeRegular,
@"FILETYPE_DIRECTORY": NSFileTypeDirectory
};
}
// Not sure how to get away from this... yet
- (NSArray<NSString *> *)supportedEvents {
return @[STORAGE_EVENT, STORAGE_ERROR];
}
- (void) sendJSError:(NSError *) error
withPath:(NSString *) path
{
NSDictionary *evt = @{
@"path": path,
@"message": [error debugDescription]
};
[self sendJSEvent:STORAGE_ERROR path:path title:STORAGE_ERROR props: evt];
}
- (void) sendJSEvent:(NSString *)type
path:(NSString *)path
title:(NSString *)title
props:(NSDictionary *)props
{
@try {
[self sendEventWithName:type
body:@{
@"eventName": title,
@"path": path,
@"body": props
}];
}
@catch (NSException *err) {
NSLog(@"An error occurred in sendJSEvent: %@", [err debugDescription]);
NSLog(@"Tried to send: %@ with %@", title, props);
}
}
@end