- Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathFirebaseStorage.cs
500 lines (469 loc) · 19.6 KB
/
FirebaseStorage.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
/*
* 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.Collections.Generic;
usingSystem.Reflection;
usingFirebase.Storage.Internal;
namespaceFirebase.Storage{
/// <summary>
/// FirebaseStorage is a service that supports uploading and downloading large objects to Google
/// Cloud Storage.
/// </summary>
/// <remarks>
/// FirebaseStorage is a service that supports uploading and downloading large objects to Google
/// Cloud Storage. Pass a custom instance of
/// <see cref="Firebase.FirebaseApp" />
/// to
/// <see cref="GetInstance" />
/// which will initialize it with a storage
/// location (bucket) specified via
/// <see cref="AppOptions.StorageBucket" />
/// .
/// <p />
/// Otherwise, if you call
/// <see cref="DefaultInstance" />
/// without a FirebaseApp, the
/// FirebaseStorage instance will initialize with the default
/// <see cref="Firebase.FirebaseApp" />
/// obtainable from
/// <see cref="FirebaseApp.DefaultInstance" />.
/// The storage location in this case will come the JSON
/// configuration file downloaded from the web.
/// </remarks>
publicsealedclassFirebaseStorage{
// Dictionary of FirebaseStorage instances indexed by a key FirebaseStorageInternal.InstanceKey.
privatestaticreadonlyDictionary<string,FirebaseStorage>storageByInstanceKey=
newDictionary<string,FirebaseStorage>();
// Proxy for the C++ firebase::storage::Storage object.
privateFirebaseStorageInternalstorageInternal;
// Proxy for the C++ firebase::app:App object.
privatereadonlyFirebaseAppfirebaseApp;
// Key of this instance within storageByInstanceKey.
privatestringinstanceKey;
// Logger for this module.
privatestaticreadonlyModuleLoggerlogger=newModuleLogger{Tag="Cloud Storage"};
/// <summary>
/// Construct an instance associated with the specified app and bucket.
/// </summary>
/// <param name="storage">C# proxy for firebase::storage::Storage.</param>
/// <param name="app">App the C# proxy storageInternal was created from.</param>
privateFirebaseStorage(FirebaseStorageInternalstorage,FirebaseAppapp){
firebaseApp=app;
firebaseApp.AppDisposed+=OnAppDisposed;
storageInternal=storage;
Logger=newModuleLogger(parentLogger:logger){
Tag=String.Format("{0} {1}:",logger.Tag,storageInternal.Url),
// TODO(smiles): Remove when FirebaseApp logger is changed to ModuleLogger.
Level=FirebaseApp.LogLevel
};
// As we know there is only one reference to the C++ firebase::storage::Storage object here
// we'll let the proxy object take ownership so the C++ object can be deleted when the
// proxy's Dispose() method is executed.
storageInternal.SetSwigCMemOwn(true);
instanceKey=storageInternal.InstanceKey;
Logger.LogMessage(LogLevel.Debug,String.Format("Created {0}",instanceKey));
}
// Dispose of this object.
privatestaticvoidDisposeObject(objectobjectToDispose){
((FirebaseStorage)objectToDispose).Dispose();
}
/// <summary>
/// Remove the reference to this object from the storageByInstanceKey dictionary.
/// </summary>
~FirebaseStorage(){
Dispose();
Logger.LogMessage(LogLevel.Debug,String.Format("Finalized {0}",instanceKey));
}
// Remove the reference to this instance from storageByInstanceKey and dispose the proxy.
privatevoidDispose(){
System.GC.SuppressFinalize(this);
lock(storageByInstanceKey){
if(storageInternal!=null&&
FirebaseStorageInternal.getCPtr(storageInternal).Handle!=IntPtr.Zero){
firebaseApp.AppDisposed-=OnAppDisposed;
storageByInstanceKey.Remove(instanceKey);
storageInternal.Dispose();
storageInternal=null;
}
}
}
voidOnAppDisposed(objectsender,System.EventArgseventArgs){
Firebase.Platform.FirebaseLogger.LogMessage(Firebase.Platform.PlatformLogLevel.Warning,"FirebaseStorage.OnAppDisposed()");
Dispose();
}
// Throw a NullReferenceException if this proxy references a deleted object.
privatevoidThrowIfNull(){
if(storageInternal==null||
FirebaseStorageInternal.getCPtr(storageInternal).Handle==System.IntPtr.Zero){
thrownewSystem.NullReferenceException();
}
}
// Logger for this instance.
internalModuleLoggerLogger{get;privateset;}
privatestaticFieldInfopathFieldInfo;
privatestaticFieldInfocachedToString;
// HACK: This hack is specific to firebase storage, and fixes an issue where
// System.Uri decodes "%2F" into slashes, (against the RFC spec) and ignores
// the "dontFormat" flag. (Because it has been deprecated.)
// This hack relies on the fact that paths in Firebase Storage do not have
// slashes after the object indicator "/o/<path to object>", so it's safe to
// convert all slashes past the "/o/" back into "%2F"s.
// The input should be a completely escaped/formatted URL, because it will
// still be returned via Uri.ToString() and Uri.OriginalString().
internalstaticUriConstructFormattedUri(stringformattedUrl){
Uriuri=newUri(formattedUrl);
stringpaq=uri.PathAndQuery;// ensure that "path" has been calculated.
// Set up reflection fields and cache them for additional calls.
if(pathFieldInfo==null){
pathFieldInfo=typeof(Uri).GetField("path",
BindingFlags.Instance|BindingFlags.NonPublic);
if(pathFieldInfo==null){
FirebaseStorage.DefaultInstance.Logger.LogMessage(LogLevel.Debug,String.Format(
"{0}: Unable to reflect Uri field to fix slashes. Storage operations will only work on"
+" the root path of your storage bucket",uri.ToString()));
returnuri;
}
}
if(cachedToString==null){
// cachedToString is not required, but will fix instances of ToString in addition to the
// regular fix to PathAndQuery. This is important for returning a proper DownloadUrl.
cachedToString=typeof(Uri).GetField("cachedToString",
BindingFlags.Instance|BindingFlags.NonPublic);
if(cachedToString==null){
FirebaseStorage.DefaultInstance.Logger.LogMessage(LogLevel.Debug,String.Format(
"{0}: Unable to reflect Uri field cachedToString. Storage operations may only work on"
+" the root path of your storage bucket",uri.ToString()));
// Continue to try to fix PathAndQuery if we can, since that controls uploads/download operations.
}
}
try{
stringpath=(string)pathFieldInfo.GetValue(uri);
if(path==null){
returnuri;
}
intindex=path.LastIndexOf("/o/");
if(index==-1){
returnuri;
}
if(index+3==path.Length){
returnuri;
}
stringfixedSuffix=path.Substring(index+3).Replace("/","%2F");
path=path.Substring(0,index+3)+fixedSuffix;
pathFieldInfo.SetValue(uri,path);
if(cachedToString!=null){
cachedToString.SetValue(uri,formattedUrl);
}
}catch(FieldAccessException){
FirebaseStorage.DefaultInstance.Logger.LogMessage(LogLevel.Debug,String.Format(
"{0}: FieldAccessException reflecting to fix canonicalization",uri.ToString()));
}catch(TargetException){
FirebaseStorage.DefaultInstance.Logger.LogMessage(LogLevel.Debug,String.Format(
"{0}: TargetException reflecting to fix canonicalization",uri.ToString()));
}catch(ArgumentException){
FirebaseStorage.DefaultInstance.Logger.LogMessage(LogLevel.Debug,String.Format(
"{0}: ArgumentException reflecting to fix canonicalization",uri.ToString()));
}
GC.KeepAlive(paq);// Just in case, don't optimize me away.
returnuri;
}
/// <summary>
/// Returns the
/// <see cref="FirebaseStorage" />
/// , initialized with the default
/// <see cref="Firebase.FirebaseApp" />
/// .
/// </summary>
/// <value>
/// a
/// <see cref="FirebaseStorage" />
/// instance.
/// </value>
publicstaticFirebaseStorageDefaultInstance{
get{returnGetInstance(FirebaseApp.DefaultInstance);}
}
/// <summary>Returns the maximum time to retry a download if a failure occurs.</summary>
/// <value>
/// maximum time which defaults to 10 minutes (600,000 milliseconds).
/// </value>
publicTimeSpanMaxDownloadRetryTime{
get{
ThrowIfNull();
returnTimeSpan.FromSeconds(storageInternal.MaxDownloadRetryTime);
}
set{
ThrowIfNull();
storageInternal.MaxDownloadRetryTime=value.TotalSeconds;
}
}
/// <summary>Returns the maximum time to retry an upload if a failure occurs.</summary>
/// <returns>
/// the maximum time which defaults to 10 minutes (600,000 milliseconds).
/// </returns>
publicTimeSpanMaxUploadRetryTime{
get{
ThrowIfNull();
returnTimeSpan.FromSeconds(storageInternal.MaxUploadRetryTime);
}
set{
ThrowIfNull();
storageInternal.MaxUploadRetryTime=value.TotalSeconds;
}
}
/// <summary>
/// Sets the maximum time to retry operations other than upload and download if a
/// failure occurs.
/// </summary>
publicTimeSpanMaxOperationRetryTime{
get{
ThrowIfNull();
returnTimeSpan.FromSeconds(storageInternal.MaxOperationRetryTime);
}
set{
ThrowIfNull();
storageInternal.MaxOperationRetryTime=value.TotalSeconds;
}
}
/// <summary>
/// Creates a new
/// <see cref="StorageReference" />
/// initialized at the root Cloud Storage location.
/// </summary>
/// <returns>
/// An instance of
/// <see cref="StorageReference" />
/// .
/// </returns>
publicStorageReferenceRootReference{
get{
ThrowIfNull();
returnnewStorageReference(this,storageInternal.GetReference());
}
}
/// <summary>
/// Sets or Gets how verbose Cloud Storage Logging will be.
/// To obtain more debug information, set this to
/// <see>
/// <cref>LogLevel.Verbose</cref>
/// </see>
/// </summary>
publicLogLevelLogLevel{
get{returnlogger.Level;}
set{
logger.Level=value;
if(FirebaseApp.LogLevel>value)FirebaseApp.LogLevel=value;
}
}
/// <summary>
/// The
/// <see cref="Firebase.FirebaseApp" />
/// associated with this
/// <see cref="FirebaseStorage" />
/// instance.
/// </summary>
publicFirebaseAppApp{get{returnfirebaseApp;}}
/// <summary>
/// Returns the
/// <see cref="FirebaseStorage" />
/// , initialized with a custom
/// <see cref="Firebase.FirebaseApp" />
/// </summary>
/// <param name="app">
/// The custom
/// <see cref="Firebase.FirebaseApp" />
/// used for initialization.
/// </param>
/// <param name="url">
/// The gs:// url to your Cloud Storage Bucket.
/// </param>
/// <returns>
/// a
/// <see cref="FirebaseStorage" />
/// instance.
/// </returns>
publicstaticFirebaseStorageGetInstance(FirebaseAppapp,stringurl=null){
returnGetInstanceInternal(app,
!String.IsNullOrEmpty(url)?url:
!String.IsNullOrEmpty(app.Options.StorageBucket)?
String.Format("gs://{0}",app.Options.StorageBucket):null);
}
/// <summary>
/// Returns the
/// <see cref="FirebaseStorage" />
/// , initialized with the default <see cref="Firebase.FirebaseApp" />
/// and a custom Storage Bucket
/// </summary>
/// <param name="url">
/// The gs:// url to your Cloud Storage Bucket.
/// </param>
/// <returns>
/// a
/// <see cref="FirebaseStorage" />
/// instance.
/// </returns>
publicstaticFirebaseStorageGetInstance(stringurl){
returnGetInstance(FirebaseApp.DefaultInstance,url);
}
/// <summary>
/// Find a previously created FirebaseStorage by FirebaseStorageInternal.InstanceKey.
/// </summary>
/// <param name="instanceKey">Key to search for.</param>
/// <returns>Storage instance if successful, null otherwise.</returns>
privatestaticFirebaseStorageFindByKey(stringinstanceKey){
lock(storageByInstanceKey){
FirebaseStoragestorage=null;
if(storageByInstanceKey.TryGetValue(instanceKey,outstorage)){
if(storage!=null)returnstorage;
storageByInstanceKey.Remove(instanceKey);
}
}
returnnull;
}
/// <summary>
/// Get or create an instance from the specified all and bucket URL.
/// </summary>
/// <remarks>
/// Even though the C++ layer will return only one instance for each app / bucket tuple, this
/// method prevents creation of multiple FirebaseStorageInternal proxy objects that each point
/// at the same underlying C++ object such that for each app / bucket tuple we'll always have
/// the unique set of FirebaseStorage --> FirebaseStorageInternal --> firebase::storage::Storage
/// objects.
/// </remarks>
/// <param name="app">App the storage instance is associated with.</param>
/// <param name="bucketUrl">URL of the storage bucket associated with the instance.</param>
/// <returns>FirebaseStorage instance that is unique for the app / bucketUrl tuple.</returns>
privatestaticFirebaseStorageGetInstanceInternal(FirebaseAppapp,stringbucketUrl){
app=app??FirebaseApp.DefaultInstance;
InitResultinitResult;
FirebaseStorageInternalstorageInternal=null;
try{
storageInternal=
FirebaseStorageInternal.GetInstanceInternal(app,bucketUrl,outinitResult);
}catch(ApplicationExceptionexception){
// The original C# implementation threw an ArgumentException when failing to create a
// storage instance so mirror the behavior here.
thrownewArgumentException(exception.Message);
}
if(initResult!=InitResult.Success){
// The original C# implementation threw an ArgumentException when failing to create a
// storage instance so mirror the behavior here.
// TODO(b/77966715): Better way to communicate url parse error to C#
// After introducing InitResult, Storage::GetInstance() in C++ no longer trigger exception
// through assert. However, InitResult may not be success due to various reason, ex.
// invalid url or fail to create Java/Object-C object. Throw ArgumentException
// for all scenario for now but need to have better way to handle different error in the
// future.
thrownewArgumentException(String.Format(
"Unable to initialize FirebaseStorage for bucket URL '{0}'",bucketUrl??""));
}elseif(storageInternal==null){
logger.LogMessage(LogLevel.Error,
String.Format("Unable to create FirebaseStorage for bucket "+
"URL '{0}'",bucketUrl??""));
returnnull;
}
FirebaseStoragestorage=null;
lock(storageByInstanceKey){
varstorageInternalInstanceKey=storageInternal.InstanceKey;
storage=FindByKey(storageInternalInstanceKey);
if(storage!=null)returnstorage;
storage=newFirebaseStorage(storageInternal,app);
storageByInstanceKey[storageInternalInstanceKey]=storage;
}
returnstorage;
}
/// <summary>
/// Throw an ArgumentException if the StorageReference is invalid.
/// </summary>
/// <param name="reference">Reference to validate.</param>
/// <param name="message">Message used to construct the exception if reference is
/// invalid.</param>
/// <returns>reference</returns>
/// <throws>ArgumentException if reference is invalid.</param>
privateStorageReferenceInternalValidateStorageReferenceInternal(
StorageReferenceInternalreference,stringmessage){
if(reference==null||!reference.IsValid)thrownewArgumentException(message);
returnreference;
}
/// <summary>
/// Returns a gs:// url to the Cloud Storage Bucket, or an empty string if this Storage was
/// created with default parameters.
/// </summary>
publicstringUrl(){
ThrowIfNull();
returnstorageInternal.Url;
}
/// <summary>
/// Creates a
/// <see cref="StorageReference" />
/// given a gs:// or https:// URL pointing to a Firebase
/// Storage location.
/// </summary>
/// <param name="fullUrl">
/// A gs:// or http[s]:// URL used to initialize the reference.
/// For example, you can pass in a download URL retrieved from
/// <see cref="StorageReference.GetDownloadUrlAsync" />
/// or the uri retrieved from
/// <see cref="StorageReference.ToString()" />
/// An error is thrown if fullUrl is not associated with the
/// <see cref="Firebase.FirebaseApp" />
/// used to initialize this
/// <see cref="FirebaseStorage" />
/// .
/// </param>
publicStorageReferenceGetReferenceFromUrl(stringfullUrl){
try{
ThrowIfNull();
returnnewStorageReference(
this,ValidateStorageReferenceInternal(
storageInternal.GetReferenceFromUrl(fullUrl),
String.Format("URL {0} does not match the storage URL {1}",fullUrl,
storageInternal.Url)));
}catch(ApplicationExceptionexception){
// The original C# implementation threw an ArgumentException when failing to create a
// storage instance so mirror the behavior here.
thrownewArgumentException(exception.Message);
}
}
/// <summary>
/// Creates a new
/// <see cref="StorageReference" />
/// initialized with a child Cloud Storage location.
/// </summary>
/// <param name="location">
/// A relative path from the root to initialize the reference with, for instance
/// "path/to/object"
/// </param>
/// <returns>
/// An instance of
/// <see cref="StorageReference" />
/// at the given child path.
/// </returns>
publicStorageReferenceGetReference(stringlocation){
try{
ThrowIfNull();
returnnewStorageReference(
this,ValidateStorageReferenceInternal(
storageInternal.GetReference(location),
String.Format("Path {0} is invalid for storage URL {1}",location,
storageInternal.Url)));
}catch(ApplicationExceptionexception){
// The original C# implementation threw an ArgumentException when failing to create a
// storage instance so mirror the behavior here.
thrownewArgumentException(exception.Message);
}
}
}
}