forked from arnesson/cordova-plugin-firebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FirebasePlugin.java
executable file
·972 lines (883 loc) · 39.6 KB
/
FirebasePlugin.java
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
package org.apache.cordova.firebase;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Base64;
import android.util.Log;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
import java.lang.reflect.Field;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigValue;
import com.google.firebase.perf.FirebasePerformance;
import com.google.firebase.perf.metrics.Trace;
import me.leolin.shortcutbadger.ShortcutBadger;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
// Firebase PhoneAuth
import java.util.concurrent.TimeUnit;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
public class FirebasePlugin extends CordovaPlugin {
private FirebaseAnalytics mFirebaseAnalytics;
private static CordovaWebView appView;
private final String TAG = "FirebasePlugin";
protected static final String KEY = "badge";
private static boolean inBackground = true;
private static ArrayList<Bundle> notificationStack = null;
private static CallbackContext notificationCallbackContext;
private static CallbackContext tokenRefreshCallbackContext;
@Override
protected void pluginInitialize() {
final Context context = this.cordova.getActivity().getApplicationContext();
final Bundle extras = this.cordova.getActivity().getIntent().getExtras();
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
Log.d(TAG, "Starting Firebase plugin");
FirebaseApp.initializeApp(context);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(context);
mFirebaseAnalytics.setAnalyticsCollectionEnabled(true);
if (extras != null && extras.size() > 1) {
if (FirebasePlugin.notificationStack == null) {
FirebasePlugin.notificationStack = new ArrayList<Bundle>();
}
if (extras.containsKey("google.message_id")) {
extras.putBoolean("tap", true);
notificationStack.add(extras);
}
}
}
});
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("getInstanceId")) {
this.getInstanceId(callbackContext);
return true;
} else if (action.equals("getId")) {
this.getId(callbackContext);
return true;
} else if (action.equals("getToken")) {
this.getToken(callbackContext);
return true;
} else if (action.equals("hasPermission")) {
this.hasPermission(callbackContext);
return true;
} else if (action.equals("setBadgeNumber")) {
this.setBadgeNumber(callbackContext, args.getInt(0));
return true;
} else if (action.equals("getBadgeNumber")) {
this.getBadgeNumber(callbackContext);
return true;
} else if (action.equals("subscribe")) {
this.subscribe(callbackContext, args.getString(0));
return true;
} else if (action.equals("unsubscribe")) {
this.unsubscribe(callbackContext, args.getString(0));
return true;
} else if (action.equals("unregister")) {
this.unregister(callbackContext);
return true;
} else if (action.equals("onNotificationOpen")) {
this.onNotificationOpen(callbackContext);
return true;
} else if (action.equals("onTokenRefresh")) {
this.onTokenRefresh(callbackContext);
return true;
} else if (action.equals("logEvent")) {
this.logEvent(callbackContext, args.getString(0), args.getJSONObject(1));
return true;
} else if (action.equals("logError")) {
this.logError(callbackContext, args.getString(0));
return true;
}else if(action.equals("setCrashlyticsUserId")){
this.setCrashlyticsUserId(callbackContext, args.getString(0));
return true;
} else if (action.equals("setScreenName")) {
this.setScreenName(callbackContext, args.getString(0));
return true;
} else if (action.equals("setUserId")) {
this.setUserId(callbackContext, args.getString(0));
return true;
} else if (action.equals("setUserProperty")) {
this.setUserProperty(callbackContext, args.getString(0), args.getString(1));
return true;
} else if (action.equals("activateFetched")) {
this.activateFetched(callbackContext);
return true;
} else if (action.equals("fetch")) {
if (args.length() > 0) {
this.fetch(callbackContext, args.getLong(0));
} else {
this.fetch(callbackContext);
}
return true;
} else if (action.equals("getByteArray")) {
if (args.length() > 1) {
this.getByteArray(callbackContext, args.getString(0), args.getString(1));
} else {
this.getByteArray(callbackContext, args.getString(0), null);
}
return true;
} else if (action.equals("getValue")) {
if (args.length() > 1) {
this.getValue(callbackContext, args.getString(0), args.getString(1));
} else {
this.getValue(callbackContext, args.getString(0), null);
}
return true;
} else if (action.equals("getInfo")) {
this.getInfo(callbackContext);
return true;
} else if (action.equals("setConfigSettings")) {
this.setConfigSettings(callbackContext, args.getJSONObject(0));
return true;
} else if (action.equals("setDefaults")) {
if (args.length() > 1) {
this.setDefaults(callbackContext, args.getJSONObject(0), args.getString(1));
} else {
this.setDefaults(callbackContext, args.getJSONObject(0), null);
}
return true;
} else if (action.equals("verifyPhoneNumber")) {
this.verifyPhoneNumber(callbackContext, args.getString(0), args.getInt(1));
return true;
} else if (action.equals("startTrace")) {
this.startTrace(callbackContext, args.getString(0));
return true;
} else if (action.equals("incrementCounter")) {
this.incrementCounter(callbackContext, args.getString(0), args.getString(1));
return true;
} else if (action.equals("stopTrace")) {
this.stopTrace(callbackContext, args.getString(0));
return true;
} else if (action.equals("setAnalyticsCollectionEnabled")) {
this.setAnalyticsCollectionEnabled(callbackContext, args.getBoolean(0));
return true;
} else if (action.equals("setPerformanceCollectionEnabled")) {
this.setPerformanceCollectionEnabled(callbackContext, args.getBoolean(0));
return true;
} else if (action.equals("clearAllNotifications")) {
this.clearAllNotifications(callbackContext);
return true;
}
return false;
}
@Override
public void onPause(boolean multitasking) {
FirebasePlugin.inBackground = true;
}
@Override
public void onResume(boolean multitasking) {
FirebasePlugin.inBackground = false;
}
@Override
public void onReset() {
FirebasePlugin.notificationCallbackContext = null;
FirebasePlugin.tokenRefreshCallbackContext = null;
}
@Override
public void onDestroy() {
super.onDestroy();
if (this.appView != null) {
appView.handleDestroy();
}
}
private void onNotificationOpen(final CallbackContext callbackContext) {
FirebasePlugin.notificationCallbackContext = callbackContext;
if (FirebasePlugin.notificationStack != null) {
for (Bundle bundle : FirebasePlugin.notificationStack) {
FirebasePlugin.sendNotification(bundle, this.cordova.getActivity().getApplicationContext());
}
FirebasePlugin.notificationStack.clear();
}
}
private void onTokenRefresh(final CallbackContext callbackContext) {
FirebasePlugin.tokenRefreshCallbackContext = callbackContext;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String currentToken = FirebaseInstanceId.getInstance().getToken();
if (currentToken != null) {
FirebasePlugin.sendToken(currentToken);
}
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
public static void sendNotification(Bundle bundle, Context context) {
if (!FirebasePlugin.hasNotificationsCallback()) {
String packageName = context.getPackageName();
if (FirebasePlugin.notificationStack == null) {
FirebasePlugin.notificationStack = new ArrayList<Bundle>();
}
notificationStack.add(bundle);
return;
}
final CallbackContext callbackContext = FirebasePlugin.notificationCallbackContext;
if (callbackContext != null && bundle != null) {
JSONObject json = new JSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
try {
json.put(key, bundle.get(key));
} catch (JSONException e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
return;
}
}
PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, json);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
}
}
public static void sendToken(String token) {
if (FirebasePlugin.tokenRefreshCallbackContext == null) {
return;
}
final CallbackContext callbackContext = FirebasePlugin.tokenRefreshCallbackContext;
if (callbackContext != null && token != null) {
PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, token);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
}
}
public static boolean inBackground() {
return FirebasePlugin.inBackground;
}
public static boolean hasNotificationsCallback() {
return FirebasePlugin.notificationCallbackContext != null;
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
final Bundle data = intent.getExtras();
if (data != null && data.containsKey("google.message_id")) {
data.putBoolean("tap", true);
FirebasePlugin.sendNotification(data, this.cordova.getActivity().getApplicationContext());
}
}
// DEPRECTED - alias of getToken
private void getInstanceId(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String token = FirebaseInstanceId.getInstance().getToken();
callbackContext.success(token);
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
}
});
}
private void getId(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String id = FirebaseInstanceId.getInstance().getId();
callbackContext.success(id);
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void getToken(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
String token = FirebaseInstanceId.getInstance().getToken();
callbackContext.success(token);
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void hasPermission(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Context context = cordova.getActivity();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
JSONObject object = new JSONObject();
object.put("isEnabled", areNotificationsEnabled);
callbackContext.success(object);
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setBadgeNumber(final CallbackContext callbackContext, final int number) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Context context = cordova.getActivity();
SharedPreferences.Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putInt(KEY, number);
editor.apply();
ShortcutBadger.applyCount(context, number);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void getBadgeNumber(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Context context = cordova.getActivity();
SharedPreferences settings = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
int number = settings.getInt(KEY, 0);
callbackContext.success(number);
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void subscribe(final CallbackContext callbackContext, final String topic) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseMessaging.getInstance().subscribeToTopic(topic);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void unsubscribe(final CallbackContext callbackContext, final String topic) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseMessaging.getInstance().unsubscribeFromTopic(topic);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void unregister(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseInstanceId.getInstance().deleteInstanceId();
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void logEvent(final CallbackContext callbackContext, final String name, final JSONObject params)
throws JSONException {
final Bundle bundle = new Bundle();
Iterator iter = params.keys();
while (iter.hasNext()) {
String key = (String) iter.next();
Object value = params.get(key);
if (value instanceof Integer || value instanceof Double) {
bundle.putFloat(key, ((Number) value).floatValue());
} else {
bundle.putString(key, value.toString());
}
}
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
mFirebaseAnalytics.logEvent(name, bundle);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void logError(final CallbackContext callbackContext, final String message) throws JSONException {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Crashlytics.logException(new Exception(message));
callbackContext.success(1);
} catch (Exception e) {
Crashlytics.log(e.getMessage());
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
private void setCrashlyticsUserId(final CallbackContext callbackContext, final String userId) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
Crashlytics.setUserIdentifier(userId);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setScreenName(final CallbackContext callbackContext, final String name) {
// This must be called on the main thread
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
mFirebaseAnalytics.setCurrentScreen(cordova.getActivity(), name, null);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setUserId(final CallbackContext callbackContext, final String id) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
mFirebaseAnalytics.setUserId(id);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setUserProperty(final CallbackContext callbackContext, final String name, final String value) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
mFirebaseAnalytics.setUserProperty(name, value);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void activateFetched(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
final boolean activated = FirebaseRemoteConfig.getInstance().activateFetched();
callbackContext.success(String.valueOf(activated));
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void fetch(CallbackContext callbackContext) {
fetch(callbackContext, FirebaseRemoteConfig.getInstance().fetch());
}
private void fetch(CallbackContext callbackContext, long cacheExpirationSeconds) {
fetch(callbackContext, FirebaseRemoteConfig.getInstance().fetch(cacheExpirationSeconds));
}
private void fetch(final CallbackContext callbackContext, final Task<Void> task) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void data) {
callbackContext.success();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
});
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void getByteArray(final CallbackContext callbackContext, final String key, final String namespace) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
byte[] bytes = namespace == null ? FirebaseRemoteConfig.getInstance().getByteArray(key)
: FirebaseRemoteConfig.getInstance().getByteArray(key, namespace);
JSONObject object = new JSONObject();
object.put("base64", Base64.encodeToString(bytes, Base64.DEFAULT));
object.put("array", new JSONArray(bytes));
callbackContext.success(object);
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void getValue(final CallbackContext callbackContext, final String key, final String namespace) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseRemoteConfigValue value = namespace == null
? FirebaseRemoteConfig.getInstance().getValue(key)
: FirebaseRemoteConfig.getInstance().getValue(key, namespace);
callbackContext.success(value.asString());
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void getInfo(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseRemoteConfigInfo remoteConfigInfo = FirebaseRemoteConfig.getInstance().getInfo();
JSONObject info = new JSONObject();
JSONObject settings = new JSONObject();
settings.put("developerModeEnabled", remoteConfigInfo.getConfigSettings().isDeveloperModeEnabled());
info.put("configSettings", settings);
info.put("fetchTimeMillis", remoteConfigInfo.getFetchTimeMillis());
info.put("lastFetchStatus", remoteConfigInfo.getLastFetchStatus());
callbackContext.success(info);
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setConfigSettings(final CallbackContext callbackContext, final JSONObject config) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
boolean devMode = config.getBoolean("developerModeEnabled");
FirebaseRemoteConfigSettings.Builder settings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(devMode);
FirebaseRemoteConfig.getInstance().setConfigSettings(settings.build());
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setDefaults(final CallbackContext callbackContext, final JSONObject defaults, final String namespace) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
if (namespace == null)
FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults));
else
FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults), namespace);
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private static Map<String, Object> defaultsToMap(JSONObject object) throws JSONException {
final Map<String, Object> map = new HashMap<String, Object>();
for (Iterator<String> keys = object.keys(); keys.hasNext(); ) {
String key = keys.next();
Object value = object.get(key);
if (value instanceof Integer) {
//setDefaults() should take Longs
value = new Long((Integer) value);
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
if (array.length() == 1 && array.get(0) instanceof String) {
//parse byte[] as Base64 String
value = Base64.decode(array.getString(0), Base64.DEFAULT);
} else {
//parse byte[] as numeric array
byte[] bytes = new byte[array.length()];
for (int i = 0; i < array.length(); i++)
bytes[i] = (byte) array.getInt(i);
value = bytes;
}
}
map.put(key, value);
}
return map;
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
public void verifyPhoneNumber(
final CallbackContext callbackContext,
final String number,
final int timeOutDuration
) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// This callback will be invoked in two situations:
// 1 - Instant verification. In some cases the phone number can be instantly
// verified without needing to send or enter a verification code.
// 2 - Auto-retrieval. On some devices Google Play services can automatically
// detect the incoming verification SMS and perform verificaiton without
// user action.
Log.d(TAG, "success: verifyPhoneNumber.onVerificationCompleted");
JSONObject returnResults = new JSONObject();
try {
String verificationId = null;
String code = null;
Field[] fields = credential.getClass().getDeclaredFields();
for (Field field : fields) {
Class type = field.getType();
if(type == String.class){
String value = getPrivateField(credential, field);
if(value == null) continue;
if(value.length() > 100) verificationId = value;
else if(value.length() >= 4 && value.length() <= 6) code = value;
}
}
returnResults.put("verified", verificationId != null && code != null);
returnResults.put("verificationId", verificationId);
returnResults.put("code", code);
returnResults.put("instantVerification", true);
} catch(JSONException e){
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
return;
}
PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, returnResults);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
}
@Override
public void onVerificationFailed(FirebaseException e) {
// This callback is invoked in an invalid request for verification is made,
// for instance if the the phone number format is not valid.
Log.w(TAG, "failed: verifyPhoneNumber.onVerificationFailed ", e);
String errorMsg = "unknown error verifying number";
errorMsg += " Error instance: " + e.getClass().getName();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
errorMsg = "Invalid phone number";
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
errorMsg = "The SMS quota for the project has been exceeded";
}
Crashlytics.logException(e);
callbackContext.error(errorMsg);
}
@Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID [(in app)].
Log.d(TAG, "success: verifyPhoneNumber.onCodeSent");
JSONObject returnResults = new JSONObject();
try {
returnResults.put("verificationId", verificationId);
returnResults.put("instantVerification", false);
} catch (JSONException e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
return;
}
PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, returnResults);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
}
};
PhoneAuthProvider.getInstance().verifyPhoneNumber(number, // Phone number to verify
timeOutDuration, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
cordova.getActivity(), // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
} catch (Exception e) {
Crashlytics.logException(e);
callbackContext.error(e.getMessage());
}
}
});
}
private static String getPrivateField(PhoneAuthCredential credential, Field field) {
try {
field.setAccessible(true);
return (String) field.get(credential);
} catch (IllegalAccessException e) {
return null;
}
}
//
// Firebase Performace
//
private HashMap<String, Trace> traces = new HashMap<String, Trace>();
private void startTrace(final CallbackContext callbackContext, final String name) {
final FirebasePlugin self = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Trace myTrace = null;
if (self.traces.containsKey(name)) {
myTrace = self.traces.get(name);
}
if (myTrace == null) {
myTrace = FirebasePerformance.getInstance().newTrace(name);
myTrace.start();
self.traces.put(name, myTrace);
}
callbackContext.success();
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
private void incrementCounter(final CallbackContext callbackContext, final String name, final String counterNamed) {
final FirebasePlugin self = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Trace myTrace = null;
if (self.traces.containsKey(name)) {
myTrace = self.traces.get(name);
}
if (myTrace != null && myTrace instanceof Trace) {
myTrace.incrementCounter(counterNamed);
callbackContext.success();
} else {
callbackContext.error("Trace not found");
}
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
private void stopTrace(final CallbackContext callbackContext, final String name) {
final FirebasePlugin self = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Trace myTrace = null;
if (self.traces.containsKey(name)) {
myTrace = self.traces.get(name);
}
if (myTrace != null && myTrace instanceof Trace) { //
myTrace.stop();
self.traces.remove(name);
callbackContext.success();
} else {
callbackContext.error("Trace not found");
}
} catch (Exception e) {
Crashlytics.logException(e);
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
private void setAnalyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) {
final FirebasePlugin self = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
mFirebaseAnalytics.setAnalyticsCollectionEnabled(enabled);
callbackContext.success();
} catch (Exception e) {
Crashlytics.log(e.getMessage());
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
private void setPerformanceCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) {
final FirebasePlugin self = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebasePerformance.getInstance().setPerformanceCollectionEnabled(enabled);
callbackContext.success();
} catch (Exception e) {
Crashlytics.log(e.getMessage());
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
public void clearAllNotifications(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Context context = cordova.getActivity();
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancelAll();
callbackContext.success();
} catch (Exception e) {
Crashlytics.log(e.getMessage());
}
}
});
}
}