This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathfirebase.android.js
executable file
·2120 lines (1830 loc) · 72.2 KB
/
firebase.android.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var appModule = require("application");
var utils = require("utils/utils");
var frame = require("ui/frame");
var fs = require("file-system");
var firebase = require("./firebase-common");
// this may fail if tns-core-modules doesn't include it (can be removed in about a year), see https://github.com/EddyVerbruggen/nativescript-plugin-firebase/pull/449
var profile;
try {
profile = require("profiling").profile;
} catch (ignore) {}
firebase._launchNotification = null;
// we need to cache and restore the context, otherwise the next invocation is broken
firebase._rememberedContext = null;
firebase._googleSignInIdToken = null;
firebase._facebookAccessToken = null;
var fbCallbackManager = null;
var GOOGLE_SIGNIN_INTENT_ID = 123;
var REQUEST_INVITE_INTENT_ID = 48;
function lazy(action) {
var _value;
var that = this;
return function () {
return that._value || (that._value = action());
}
}
var gson = new lazy(function () {
return typeof(com.google.gson) === "undefined" ? null : new com.google.gson.Gson()
});
var messagingEnabled = new lazy(function () {
return typeof(com.google.firebase.messaging) !== "undefined"
});
(function () {
appModule.on("launch", function (args) {
if (!messagingEnabled()) {
return;
}
var intent = args.android;
var extras = intent.getExtras();
if (extras !== null) {
var result = {
foreground: false,
data: {}
};
var iterator = extras.keySet().iterator();
while (iterator.hasNext()) {
var key = iterator.next();
if (key !== "from" && key !== "collapse_key") {
result[key] = extras.get(key);
result.data[key] = extras.get(key);
}
}
// in case this was a cold start we don't have the _receivedNotificationCallback yet
if (firebase._receivedNotificationCallback === null) {
firebase._launchNotification = result;
} else {
// add a little delay just to make sure clients alerting this message will see it as the UI needs to settle
setTimeout(function () {
firebase._receivedNotificationCallback(result);
});
}
}
});
})();
firebase.toHashMap = function (obj) {
var node = new java.util.HashMap();
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (obj[property] === null) {
node.put(property, null);
} else {
switch (typeof obj[property]) {
case 'object':
node.put(property, firebase.toHashMap(obj[property], node));
break;
case 'boolean':
node.put(property, java.lang.Boolean.valueOf(String(obj[property])));
break;
case 'number':
if (Number(obj[property]) === obj[property] && obj[property] % 1 === 0)
node.put(property, java.lang.Long.valueOf(String(obj[property])));
else
node.put(property, java.lang.Double.valueOf(String(obj[property])));
break;
case 'string':
node.put(property, String(obj[property]));
break;
}
}
}
}
return node;
};
firebase.toValue = function (val) {
var returnVal = null;
if (val !== null) {
switch (typeof val) {
case 'object':
returnVal = firebase.toHashMap(val);
break;
case 'boolean':
returnVal = java.lang.Boolean.valueOf(String(val));
break;
case 'number':
if (Number(val) === val && val % 1 === 0)
returnVal = java.lang.Long.valueOf(String(val));
else
returnVal = java.lang.Double.valueOf(String(val));
break;
case 'string':
returnVal = String(val);
break;
}
}
return returnVal;
};
firebase.toJsObject = function (javaObj) {
if (gson() !== null) {
return JSON.parse(gson().toJson(javaObj));
} else {
// temp fallback for folks not having fetched gson yet in their build for some reason
return firebase.toJsObjectLegacy(javaObj);
}
};
firebase.toJsObjectLegacy = function (javaObj) {
if (javaObj === null || typeof javaObj != "object") {
return javaObj;
}
var node;
switch (javaObj.getClass().getName()) {
case 'java.lang.Boolean':
var str = String(javaObj);
return Boolean(!!(str == "True" || str == "true"));
case 'java.lang.String':
return String(javaObj);
case 'java.lang.Long':
case 'java.lang.Double':
return Number(String(javaObj));
case 'java.util.ArrayList':
node = [];
for (var i = 0; i < javaObj.size(); i++) {
node[i] = firebase.toJsObjectLegacy(javaObj.get(i));
}
break;
default:
node = {};
var iterator = javaObj.entrySet().iterator();
while (iterator.hasNext()) {
var item = iterator.next();
node[item.getKey()] = firebase.toJsObjectLegacy(item.getValue());
}
}
return node;
};
firebase.getCallbackData = function (type, snapshot) {
return {
type: type,
key: snapshot.getKey(),
value: firebase.toJsObject(snapshot.getValue())
};
};
firebase.authStateListener = null;
firebase.init = function (arg) {
return new Promise(function (resolve, reject) {
function runInit() {
if (firebase.instance !== null) {
reject("You already ran init");
return;
}
arg = arg || {};
firebase.ServerValue = {
TIMESTAMP: firebase.toJsObject(com.google.firebase.database.ServerValue.TIMESTAMP)
};
var fDatabase = com.google.firebase.database.FirebaseDatabase;
if (arg.persist) {
fDatabase.getInstance().setPersistenceEnabled(true);
}
// the URL is picked up from google-services.json, so you can use it like this:
firebase.instance = fDatabase.getInstance().getReference();
// it is however still possible to pass the URL programmatically (which we'll do for now):
// firebase.instance = fDatabase.getInstance().getReferenceFromUrl(arg.url);
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
if (arg.onAuthStateChanged) {
firebase.authStateListener = new com.google.firebase.auth.FirebaseAuth.AuthStateListener({
onAuthStateChanged: function (fbAuth) {
var user = fbAuth.getCurrentUser();
arg.onAuthStateChanged({
loggedIn: user !== null,
user: toLoginResult(user)
});
}
});
firebaseAuth.addAuthStateListener(firebase.authStateListener);
}
// Listen to auth state changes
if (!firebase.authStateListener) {
firebase.authStateListener = new com.google.firebase.auth.FirebaseAuth.AuthStateListener({
onAuthStateChanged: function (fbAuth) {
var user = fbAuth.getCurrentUser();
firebase.notifyAuthStateListeners({
loggedIn: user !== null,
user: toLoginResult(user)
});
}
});
firebaseAuth.addAuthStateListener(firebase.authStateListener);
}
// Firebase notifications (FCM)
if (messagingEnabled()) {
if (arg.onMessageReceivedCallback !== undefined) {
firebase.addOnMessageReceivedCallback(arg.onMessageReceivedCallback);
}
if (arg.onPushTokenReceivedCallback !== undefined) {
firebase.addOnPushTokenReceivedCallback(arg.onPushTokenReceivedCallback);
}
}
// Firebase storage
if (arg.storageBucket) {
if (typeof(com.google.firebase.storage) === "undefined") {
reject("Uncomment firebase-storage in the plugin's include.gradle first");
return;
}
firebase.storage = com.google.firebase.storage.FirebaseStorage.getInstance().getReferenceFromUrl(arg.storageBucket);
}
// Facebook
if (typeof(com.facebook) !== "undefined" && typeof(com.facebook.FacebookSdk) !== "undefined") {
com.facebook.FacebookSdk.sdkInitialize(com.tns.NativeScriptApplication.getInstance());
fbCallbackManager = com.facebook.CallbackManager.Factory.create();
appModule.android.on(appModule.AndroidApplication.activityResultEvent, function (eventData) {
if (eventData.requestCode !== GOOGLE_SIGNIN_INTENT_ID) {
fbCallbackManager.onActivityResult(eventData.requestCode, eventData.resultCode, eventData.intent);
}
});
}
resolve(firebase.instance);
}
var _resolve = profile === undefined ? runInit : profile("firebase.init resolve", runInit);
try {
if (appModule.android.foregroundActivity) {
_resolve();
} else {
// if this is called before application.start() wait for the event to fire
appModule.on(appModule.launchEvent, _resolve);
}
} catch (ex) {
console.log("Error in firebase.init: " + ex);
reject(ex);
}
});
};
firebase.fetchProvidersForEmail = function (email) {
return new Promise(function (resolve, reject) {
try {
if (typeof(email) !== "string") {
reject("A parameter representing an email address is required.");
return;
}
var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task /* <ProviderQueryResult> */) {
if (!task.isSuccessful()) {
reject((task.getException() && task.getException().getReason ? task.getException().getReason() : task.getException()));
} else {
var providerList = task.getResult().getProviders();
resolve(firebase.toJsObject(providerList));
}
}
});
com.google.firebase.auth.FirebaseAuth.getInstance().fetchProvidersForEmail(email).addOnCompleteListener(onCompleteListener);
} catch (ex) {
console.log("Error in firebase.fetchProvidersForEmail: " + ex);
reject(ex);
}
});
};
firebase.getCurrentPushToken = function () {
return new Promise(function (resolve, reject) {
try {
if (typeof(com.google.firebase.messaging || com.google.firebase.iid) === "undefined") {
reject("Uncomment firebase-messaging in the plugin's include.gradle first");
return;
}
resolve(com.google.firebase.iid.FirebaseInstanceId.getInstance().getToken());
} catch (ex) {
console.log("Error in firebase.getCurrentPushToken: " + ex);
reject(ex);
}
});
};
firebase.addOnMessageReceivedCallback = function (callback) {
return new Promise(function (resolve, reject) {
try {
if (typeof(com.google.firebase.messaging) === "undefined") {
reject("Uncomment firebase-messaging in the plugin's include.gradle first");
return;
}
firebase._receivedNotificationCallback = callback;
org.nativescript.plugins.firebase.FirebasePlugin.setOnNotificationReceivedCallback(
new org.nativescript.plugins.firebase.FirebasePluginListener({
success: function (notification) {
callback(JSON.parse(notification));
}
})
);
// if the app was launched from a notification, process it now
if (firebase._launchNotification !== null) {
callback(firebase._launchNotification);
firebase._launchNotification = null;
}
resolve();
} catch (ex) {
console.log("Error in firebase.addOnMessageReceivedCallback: " + ex);
reject(ex);
}
});
};
firebase.addOnPushTokenReceivedCallback = function (callback) {
return new Promise(function (resolve, reject) {
try {
if (typeof(com.google.firebase.messaging) === "undefined") {
reject("Uncomment firebase-messaging in the plugin's include.gradle first");
return;
}
org.nativescript.plugins.firebase.FirebasePlugin.setOnPushTokenReceivedCallback(
new org.nativescript.plugins.firebase.FirebasePluginListener({
success: function (token) {
callback(token);
}
})
);
resolve();
} catch (ex) {
console.log("Error in firebase.addOnPushTokenReceivedCallback: " + ex);
reject(ex);
}
});
};
firebase.getRemoteConfigDefaults = function (properties) {
var defaults = {};
for (var p in properties) {
var prop = properties[p];
if (prop.default !== undefined) {
defaults[prop.key] = prop.default;
}
}
return defaults;
};
firebase._isGooglePlayServicesAvailable = function () {
var context = com.tns.NativeScriptApplication.getInstance();
var playServiceStatusSuccess = com.google.android.gms.common.ConnectionResult.SUCCESS; // 0
var playServicesStatus = com.google.android.gms.common.GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
return playServicesStatus === playServiceStatusSuccess;
};
firebase.analytics.logEvent = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (arg.key === undefined) {
reject("Argument 'key' is missing");
return;
}
var bundle = new android.os.Bundle();
if (arg.parameters !== undefined) {
for (var p in arg.parameters) {
var param = arg.parameters[p];
if (param.value !== undefined) {
bundle.putString(param.key, param.value);
}
}
}
com.google.firebase.analytics.FirebaseAnalytics.getInstance(appModule.android.currentContext || com.tns.NativeScriptApplication.getInstance()).logEvent(arg.key, bundle);
resolve();
} catch (ex) {
console.log("Error in firebase.analytics.logEvent: " + ex);
reject(ex);
}
});
};
firebase.analytics.setUserProperty = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (arg.key === undefined) {
reject("Argument 'key' is missing");
return;
}
if (arg.value === undefined) {
reject("Argument 'value' is missing");
return;
}
com.google.firebase.analytics.FirebaseAnalytics.getInstance(appModule.android.currentContext || com.tns.NativeScriptApplication.getInstance()).setUserProperty(arg.key, arg.value);
resolve();
} catch (ex) {
console.log("Error in firebase.analytics.setUserProperty: " + ex);
reject(ex);
}
});
};
firebase.analytics.setScreenName = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (arg.screenName === undefined) {
reject("Argument 'screenName' is missing");
return;
}
com.google.firebase.analytics.FirebaseAnalytics.getInstance(appModule.android.currentContext || com.tns.NativeScriptApplication.getInstance()).setCurrentScreen(appModule.android.foregroundActivity, arg.screenName, null);
resolve();
} catch (ex) {
console.log("Error in firebase.analytics.setScreenName: " + ex);
reject(ex);
}
});
};
//see https://firebase.google.com/docs/admob/android/quick-start
firebase.admob.showBanner = function (arg) {
return new Promise(function (resolve, reject) {
try {
var settings = firebase.merge(arg, firebase.admob.defaults);
// this should also be possible in init
com.google.android.gms.ads.MobileAds.initialize(
appModule.android.context,
settings.androidBannerId); // TODO not sure its bound to packagename.. this is from the admob-demo
// always close a previously opened banner
if (firebase.admob.adView !== null && firebase.admob.adView !== undefined) {
var parent = firebase.admob.adView.getParent();
if (parent !== null) {
parent.removeView(firebase.admob.adView);
}
}
firebase.admob.adView = new com.google.android.gms.ads.AdView(appModule.android.foregroundActivity);
firebase.admob.adView.setAdUnitId(settings.androidBannerId);
var bannerType = firebase.admob._getBannerType(settings.size);
firebase.admob.adView.setAdSize(bannerType);
console.log("----- bannerType: " + bannerType);
// TODO consider implementing events
//firebase.admob.adView.setAdListener(new com.google.android.gms.ads.BannerListener());
var ad = firebase.admob._buildAdRequest(settings);
firebase.admob.adView.loadAd(ad);
var density = utils.layout.getDisplayDensity(),
top = settings.margins.top * density,
bottom = settings.margins.bottom * density;
var relativeLayoutParams = new android.widget.RelativeLayout.LayoutParams(
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
if (bottom > -1) {
relativeLayoutParams.bottomMargin = bottom;
relativeLayoutParams.addRule(android.widget.RelativeLayout.ALIGN_PARENT_BOTTOM);
} else {
if (top > -1) {
relativeLayoutParams.topMargin = top;
}
relativeLayoutParams.addRule(android.widget.RelativeLayout.ALIGN_PARENT_TOP);
}
var adViewLayout = new android.widget.RelativeLayout(appModule.android.foregroundActivity);
adViewLayout.addView(firebase.admob.adView, relativeLayoutParams);
var relativeLayoutParamsOuter = new android.widget.RelativeLayout.LayoutParams(
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT);
// wrapping it in a timeout makes sure that when this function is loaded from
// a Page.loaded event 'frame.topmost()' doesn't resolve to 'undefined'
setTimeout(function () {
frame.topmost().currentPage.android.getParent().addView(adViewLayout, relativeLayoutParamsOuter);
}, 0);
resolve();
} catch (ex) {
console.log("Error in firebase.admob.showBanner: " + ex);
reject(ex);
}
});
};
firebase.admob.showInterstitial = function (arg) {
return new Promise(function (resolve, reject) {
try {
var settings = firebase.merge(arg, firebase.admob.defaults);
firebase.admob.interstitialView = new com.google.android.gms.ads.InterstitialAd(appModule.android.foregroundActivity);
firebase.admob.interstitialView.setAdUnitId(settings.androidInterstitialId);
// Interstitial ads must be loaded before they can be shown, so adding a listener
var InterstitialAdListener = com.google.android.gms.ads.AdListener.extend({
onAdLoaded: function () {
firebase.admob.interstitialView.show();
resolve();
},
onAdFailedToLoad: function (errorCode) {
reject(errorCode);
},
onAdClosed: function () {
firebase.admob.interstitialView.setAdListener(null);
firebase.admob.interstitialView = null;
}
});
firebase.admob.interstitialView.setAdListener(new InterstitialAdListener());
var ad = firebase.admob._buildAdRequest(settings);
firebase.admob.interstitialView.loadAd(ad);
} catch (ex) {
console.log("Error in firebase.admob.showInterstitial: " + ex);
reject(ex);
}
});
};
firebase.admob.hideBanner = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (firebase.admob.adView !== null) {
var parent = firebase.admob.adView.getParent();
if (parent !== null) {
parent.removeView(firebase.admob.adView);
}
firebase.admob.adView = null;
}
resolve();
} catch (ex) {
console.log("Error in firebase.admob.hideBanner: " + ex);
reject(ex);
}
});
};
firebase.admob._getBannerType = function (size) {
if (size == firebase.admob.AD_SIZE.BANNER) {
return com.google.android.gms.ads.AdSize.BANNER;
} else if (size == firebase.admob.AD_SIZE.LARGE_BANNER) {
return com.google.android.gms.ads.AdSize.LARGE_BANNER;
} else if (size == firebase.admob.AD_SIZE.MEDIUM_RECTANGLE) {
return com.google.android.gms.ads.AdSize.MEDIUM_RECTANGLE;
} else if (size == firebase.admob.AD_SIZE.FULL_BANNER) {
return com.google.android.gms.ads.AdSize.FULL_BANNER;
} else if (size == firebase.admob.AD_SIZE.LEADERBOARD) {
return com.google.android.gms.ads.AdSize.LEADERBOARD;
} else if (size == firebase.admob.AD_SIZE.SMART_BANNER) {
return com.google.android.gms.ads.AdSize.SMART_BANNER;
} else {
return null;
}
};
firebase.admob._buildAdRequest = function (settings) {
var builder = new com.google.android.gms.ads.AdRequest.Builder();
if (settings.testing) {
builder.addTestDevice(com.google.android.gms.ads.AdRequest.DEVICE_ID_EMULATOR);
// This will request test ads on the emulator and device by passing this hashed device ID.
var ANDROID_ID = android.provider.Settings.Secure.getString(appModule.android.foregroundActivity.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
var deviceId = firebase.admob._md5(ANDROID_ID);
if (deviceId !== null) {
deviceId = deviceId.toUpperCase();
console.log("Treating this deviceId as testdevice: " + deviceId);
builder.addTestDevice(deviceId);
}
}
var bundle = new android.os.Bundle();
bundle.putInt("nativescript", 1);
var adextras = new com.google.android.gms.ads.mediation.admob.AdMobExtras(bundle);
//builder = builder.addNetworkExtras(adextras);
return builder.build();
};
firebase.admob._md5 = function (input) {
try {
var digest = java.security.MessageDigest.getInstance("MD5");
var bytes = [];
for (var j = 0; j < input.length; ++j) {
bytes.push(input.charCodeAt(j));
}
var s = new java.lang.String(input);
digest.update(s.getBytes());
var messageDigest = digest.digest();
var hexString = "";
for (var i = 0; i < messageDigest.length; i++) {
var h = java.lang.Integer.toHexString(0xFF & messageDigest[i]);
while (h.length < 2)
h = "0" + h;
hexString += h;
}
return hexString;
} catch (noSuchAlgorithmException) {
console.log("error generating md5: " + noSuchAlgorithmException);
return null;
}
};
firebase.getRemoteConfig = function (arg) {
return new Promise(function (resolve, reject) {
if (typeof(com.google.firebase.remoteconfig) === "undefined") {
reject("Uncomment firebase-config in the plugin's include.gradle first");
return;
}
if (arg.properties === undefined) {
reject("Argument 'properties' is missing");
return;
}
function runGetRemoteConfig() {
if (!firebase._isGooglePlayServicesAvailable()) {
reject("Google Play services is required for this feature, but not available on this device");
return;
}
// Get a Remote Config object instance
firebaseRemoteConfig = com.google.firebase.remoteconfig.FirebaseRemoteConfig.getInstance();
// Enable developer mode to allow for frequent refreshes of the cache
var remoteConfigSettings = new com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(arg.developerMode || false)
.build();
firebaseRemoteConfig.setConfigSettings(remoteConfigSettings);
var defaults = firebase.getRemoteConfigDefaults(arg.properties);
firebaseRemoteConfig.setDefaults(firebase.toHashMap(defaults));
var returnMethod = function (throttled) {
firebaseRemoteConfig.activateFetched();
var lastFetchTime = firebaseRemoteConfig.getInfo().getFetchTimeMillis();
var lastFetch = new Date(lastFetchTime);
var result = {
lastFetch: lastFetch,
throttled: throttled,
properties: {}
};
for (var p in arg.properties) {
var prop = arg.properties[p];
var key = prop.key;
var value = firebaseRemoteConfig.getString(key);
// we could have the user pass in the type but this seems easier to use
result.properties[key] = firebase.strongTypeify(value);
}
resolve(result);
};
var onSuccessListener = new com.google.android.gms.tasks.OnSuccessListener({
onSuccess: function () {
returnMethod(false);
}
});
var onFailureListener = new com.google.android.gms.tasks.OnFailureListener({
onFailure: function (exception) {
if (exception == "com.google.firebase.remoteconfig.FirebaseRemoteConfigFetchThrottledException") {
returnMethod(true);
} else {
reject("Retrieving remote config data failed. " + exception);
}
}
});
// default 12 hours, just like the SDK does
var expirationDuration = arg.cacheExpirationSeconds || 43200;
firebaseRemoteConfig.fetch(expirationDuration)
.addOnSuccessListener(onSuccessListener)
.addOnFailureListener(onFailureListener);
}
var _resolve = profile === undefined ? runGetRemoteConfig : profile("firebase.getRemoteConfig resolve", runGetRemoteConfig);
try {
if (appModule.android.foregroundActivity) {
_resolve();
} else {
// if this is called before application.start() wait for the event to fire
appModule.on(appModule.launchEvent, _resolve);
}
} catch (ex) {
console.log("Error in firebase.getRemoteConfig: " + ex);
reject(ex);
}
});
};
firebase.getCurrentUser = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (firebase.instance === null) {
reject("Run init() first!");
return;
}
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
var user = firebaseAuth.getCurrentUser();
if (user !== null) {
resolve(toLoginResult(user));
} else {
reject();
}
} catch (ex) {
console.log("Error in firebase.getCurrentUser: " + ex);
reject(ex);
}
});
};
firebase.sendEmailVerification = function () {
return new Promise(function (resolve, reject) {
try {
if (firebase.instance === null) {
reject("Run init() first!");
return;
}
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
var user = firebaseAuth.getCurrentUser();
if (user !== null) {
var addOnCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task) {
if (!task.isSuccessful()) {
reject((task.getException() && task.getException().getReason ? task.getException().getReason() : task.getException()));
} else {
resolve();
}
}
});
user.sendEmailVerification().addOnCompleteListener(addOnCompleteListener);
} else {
reject("Log in first");
}
} catch (ex) {
console.log("Error in firebase.sendEmailVerification: " + ex);
reject(ex);
}
});
};
firebase.logout = function (arg) {
return new Promise(function (resolve, reject) {
try {
com.google.firebase.auth.FirebaseAuth.getInstance().signOut();
// also disconnect from Google otherwise ppl can't connect with a different account
if (firebase._mGoogleApiClient) {
com.google.android.gms.auth.api.Auth.GoogleSignInApi.revokeAccess(firebase._mGoogleApiClient);
}
if (typeof(com.facebook) !== "undefined" && typeof(com.facebook.login) !== "undefined") {
com.facebook.login.LoginManager.getInstance().logOut();
}
resolve();
} catch (ex) {
console.log("Error in firebase.logout: " + ex);
reject(ex);
}
});
};
firebase.getAuthToken = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (firebase.instance === null) {
reject("Run init() first!");
return;
}
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
var user = firebaseAuth.getCurrentUser();
if (user !== null) {
var onSuccessListener = new com.google.android.gms.tasks.OnSuccessListener({
onSuccess: function (getTokenResult) {
resolve(getTokenResult.getToken());
}
});
var onFailureListener = new com.google.android.gms.tasks.OnFailureListener({
onFailure: function (exception) {
reject(exception);
}
});
user.getIdToken(arg.forceRefresh)
.addOnSuccessListener(onSuccessListener)
.addOnFailureListener(onFailureListener);
} else {
reject("Log in first");
}
} catch (ex) {
console.log("Error in firebase.getAuthToken: " + ex);
reject(ex);
}
});
};
function toLoginResult(user) {
if (user === null) {
return false;
}
// for convenience return the result in multiple formats
var providers = [];
var providerData = user.getProviderData();
for (var i = 0; i < providerData.size(); i++) {
var pid = providerData.get(i).getProviderId();
if (pid === 'facebook.com') {
providers.push({id: pid, token: firebase._facebookAccessToken});
}
else {
providers.push({id: pid});
}
}
return {
uid: user.getUid(),
name: user.getDisplayName(),
email: user.getEmail(),
emailVerified: user.isEmailVerified(),
// provider: user.getProviderId(), // always 'firebase'
providers: providers,
anonymous: user.isAnonymous(),
phoneNumber: user.getPhoneNumber(),
profileImageURL: user.getPhotoUrl() ? user.getPhotoUrl().toString() : null
};
}
firebase.login = function (arg) {
return new Promise(function (resolve, reject) {
try {
if (!firebase._isGooglePlayServicesAvailable()) {
reject("Google Play services is required for this feature, but not available on this device");
return;
}
firebase.moveLoginOptionsToObjects(arg);
var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({
onComplete: function (task) {
if (firebase._rememberedContext !== null) {
appModule.android.currentContext = firebase._rememberedContext;
firebase._rememberedContext = null;
}
if (!task.isSuccessful()) {
console.log("Logging in the user failed. " + (task.getException() && task.getException().getReason ? task.getException().getReason() : task.getException()));
// also disconnect from Google otherwise ppl can't connect with a different account
if (firebase._mGoogleApiClient) {
com.google.android.gms.auth.api.Auth.GoogleSignInApi.revokeAccess(firebase._mGoogleApiClient);
}
reject("Logging in the user failed. " + (task.getException() && task.getException().getReason ? task.getException().getReason() : task.getException()));
} else {
var user = task.getResult().getUser();
resolve(toLoginResult(user));
}
}
});
if (arg.type === firebase.LoginType.ANONYMOUS) {
firebaseAuth.signInAnonymously().addOnCompleteListener(onCompleteListener);
} else if (arg.type === firebase.LoginType.PASSWORD) {
if (!arg.passwordOptions || !arg.passwordOptions.email || !arg.passwordOptions.password) {
reject("Auth type PASSWORD requires an 'passwordOptions.email' and 'passwordOptions.password' argument");
return;
}
var user = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser();
if (user) {
if (firebase._alreadyLinkedToAuthProvider(user, "password")) {
firebaseAuth.signInWithEmailAndPassword(arg.passwordOptions.email, arg.passwordOptions.password).addOnCompleteListener(onCompleteListener);
} else {
var authCredential = com.google.firebase.auth.EmailAuthProvider.getCredential(arg.passwordOptions.email, arg.passwordOptions.password);
user.linkWithCredential(authCredential).addOnCompleteListener(onCompleteListener);
}
} else {
firebaseAuth.signInWithEmailAndPassword(arg.passwordOptions.email, arg.passwordOptions.password).addOnCompleteListener(onCompleteListener);
}
} else if (arg.type === firebase.LoginType.PHONE) {
// https://firebase.google.com/docs/auth/android/phone-auth
if (!arg.phoneOptions || !arg.phoneOptions.phoneNumber) {
reject("Auth type PHONE requires a 'phoneOptions.phoneNumber' argument");
return;
}
var user = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser();
// TODO, no hurry
if (false && user) {
if (firebase._alreadyLinkedToAuthProvider(user, "phone")) {
// TODO .. you don't want to sign in again I guess...
// firebaseAuth.signInWithEmailAndPassword(arg.email, arg.password).addOnCompleteListener(onCompleteListener);
} else {
// TODO get auth credential.. prolly need to move this
user.linkWithCredential(authCredential).addOnCompleteListener(onCompleteListener);
}
} else {
var OnVerificationStateChangedCallbacks = com.google.firebase.auth.PhoneAuthProvider.OnVerificationStateChangedCallbacks.extend({
onVerificationCompleted: function (phoneAuthCredential) {
console.log("phone number verification completed");
firebase._verifyPhoneNumberInProgress = false;
// the user previously authenticated with phone (or no prompt was required), so sign in and complete
firebaseAuth.signInWithCredential(phoneAuthCredential).addOnCompleteListener(onCompleteListener);
},
onVerificationFailed: function (firebaseException) {
console.log("onVerificationStateChangedCallbacks.onVerificationFailed: " + firebaseException);
firebase._verifyPhoneNumberInProgress = false;
var errorMessage = firebaseException.getMessage();
if (errorMessage.indexOf("INVALID_APP_CREDENTIAL") > -1) {
reject("Please upload the SHA1 fingerprint of your debug and release keystores to the Firebase console, see https://github.com/EddyVerbruggen/nativescript-plugin-firebase/blob/master/docs/AUTHENTICATION.md#phone-verification");
} else {
reject(errorMessage);
}
},
onCodeSent: function (verificationId, forceResendingToken) {
// If the device has a SIM card auto-verification may occur in the background (eventually calling onVerificationCompleted)
// .. so the prompt would be redundant, but it's recommended by Google not to wait to long before showing the prompt
setTimeout(function () {
if (firebase._verifyPhoneNumberInProgress) {
firebase._verifyPhoneNumberInProgress = false;
firebase.requestPhoneAuthVerificationCode(function (userResponse) {
var authCredential = com.google.firebase.auth.PhoneAuthProvider.getCredential(verificationId, userResponse);
var user = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser();
if (user) {
if (firebase._alreadyLinkedToAuthProvider(user, "phone")) {
firebaseAuth.signInWithCredential(authCredential).addOnCompleteListener(onCompleteListener);
} else {
user.linkWithCredential(authCredential).addOnCompleteListener(onCompleteListener);
}
} else {
firebaseAuth.signInWithCredential(authCredential).addOnCompleteListener(onCompleteListener);
}
}, arg.phoneOptions.verificationPrompt);
}