forked from dpa99c/cordova-plugin-firebasex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FirebasePlugin.java
executable file
·4224 lines (3790 loc) · 193 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
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
package org.apache.cordova.firebase;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.NotificationChannel;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.media.AudioAttributes;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.util.Base64;
import android.util.Log;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.firebase.auth.ActionCodeSettings;
import com.google.firebase.auth.EmailAuthCredential;
import com.google.firebase.auth.EmailAuthProvider;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuthMultiFactorException;
import com.google.firebase.auth.FirebaseUserMetadata;
import com.google.firebase.auth.MultiFactorAssertion;
import com.google.firebase.auth.MultiFactorInfo;
import com.google.firebase.auth.MultiFactorResolver;
import com.google.firebase.auth.MultiFactorSession;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneMultiFactorGenerator;
import com.google.firebase.auth.PhoneMultiFactorInfo;
import com.google.firebase.auth.UserInfo;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
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.Timestamp;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.analytics.FirebaseAnalytics.ConsentType;
import com.google.firebase.analytics.FirebaseAnalytics.ConsentStatus;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.OAuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.auth.OAuthProvider;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.crashlytics.internal.metadata.UserMetadata;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.MetadataChanges;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.Query.Direction;
import com.google.firebase.functions.FirebaseFunctions;
import com.google.firebase.functions.FirebaseFunctionsException;
import com.google.firebase.functions.HttpsCallableResult;
import com.google.firebase.installations.FirebaseInstallations;
import com.google.firebase.installations.InstallationTokenResult;
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 org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.List;
import java.util.Date;
import java.util.EnumMap;
// Firebase PhoneAuth
import java.util.concurrent.TimeUnit;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import static android.content.Context.MODE_PRIVATE;
public class FirebasePlugin extends CordovaPlugin {
protected static FirebasePlugin instance = null;
private FirebaseAnalytics mFirebaseAnalytics;
private FirebaseCrashlytics firebaseCrashlytics;
private FirebaseFirestore firestore;
private FirebaseFunctions functions;
private Gson gson;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseAuth.IdTokenListener idTokenListener;
private boolean authStateChangeListenerInitialized = false;
private String currentIdToken;
private static CordovaInterface cordovaInterface = null;
protected static Context applicationContext = null;
private static Activity cordovaActivity = null;
protected static final String TAG = "FirebasePlugin";
protected static final String JS_GLOBAL_NAMESPACE = "FirebasePlugin.";
protected static final String KEY = "badge";
protected static final int GOOGLE_SIGN_IN = 0x1;
protected static final String SETTINGS_NAME = "settings";
private static final String CRASHLYTICS_COLLECTION_ENABLED = "firebase_crashlytics_collection_enabled";
private static final String ANALYTICS_COLLECTION_ENABLED = "firebase_analytics_collection_enabled";
private static final String PERFORMANCE_COLLECTION_ENABLED = "firebase_performance_collection_enabled";
private static final String GOOGLE_ANALYTICS_ADID_COLLECTION_ENABLED = "google_analytics_adid_collection_enabled";
private static final String GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE = "google_analytics_default_allow_analytics_storage";
private static final String GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE = "firebase_performance_collectigoogle_analytics_default_allow_ad_storageon_enabled";
private static final String GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA = "google_analytics_default_allow_ad_user_data";
private static final String GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS = "google_analytics_default_allow_ad_personalization_signals";
protected static final String POST_NOTIFICATIONS = "POST_NOTIFICATIONS";
protected static final int POST_NOTIFICATIONS_PERMISSION_REQUEST_ID = 1;
private static boolean inBackground = true;
private static ArrayList<Bundle> notificationStack = null;
private static CallbackContext notificationCallbackContext;
private static CallbackContext tokenRefreshCallbackContext;
private static CallbackContext activityResultCallbackContext;
private static CallbackContext authResultCallbackContext;
private static CallbackContext postNotificationPermissionRequestCallbackContext;
private static NotificationChannel defaultNotificationChannel = null;
public static String defaultChannelId = null;
public static String defaultChannelName = null;
private Map<String, AuthCredential> authCredentials = new HashMap<String, AuthCredential>();
private Map<String, OAuthProvider> authProviders = new HashMap<String, OAuthProvider>();
private Map<String, ListenerRegistration> firestoreListeners = new HashMap<String, ListenerRegistration>();
private MultiFactorResolver multiFactorResolver = null;
@Override
protected void pluginInitialize() {
instance = this;
cordovaActivity = this.cordova.getActivity();
applicationContext = cordovaActivity.getApplicationContext();
final Bundle extras = cordovaActivity.getIntent().getExtras();
FirebasePlugin.cordovaInterface = this.cordova;
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
Log.d(TAG, "Starting Firebase plugin");
if (getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)) {
setPreference(CRASHLYTICS_COLLECTION_ENABLED, true);
}
if (getMetaDataFromManifest(ANALYTICS_COLLECTION_ENABLED)) {
setPreference(ANALYTICS_COLLECTION_ENABLED, true);
}
if (getMetaDataFromManifest(PERFORMANCE_COLLECTION_ENABLED)) {
setPreference(PERFORMANCE_COLLECTION_ENABLED, true);
}
if (getMetaDataFromManifest(GOOGLE_ANALYTICS_ADID_COLLECTION_ENABLED)) {
setPreference(GOOGLE_ANALYTICS_ADID_COLLECTION_ENABLED, true);
}
if (getMetaDataFromManifest(GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE)) {
setPreference(GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE, true);
}
if (getMetaDataFromManifest(GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE)) {
setPreference(GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE, true);
}
if (getMetaDataFromManifest(GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA)) {
setPreference(GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA, true);
}
if (getMetaDataFromManifest(GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS)) {
setPreference(GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS, true);
}
FirebaseApp.initializeApp(applicationContext);
firebaseCrashlytics = FirebaseCrashlytics.getInstance();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(applicationContext);
authStateListener = new AuthStateListener();
FirebaseAuth.getInstance().addAuthStateListener(authStateListener);
idTokenListener = new IdTokenListener();
FirebaseAuth.getInstance().addIdTokenListener(idTokenListener);
firestore = FirebaseFirestore.getInstance();
functions = FirebaseFunctions.getInstance();
gson = new GsonBuilder()
.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
if (src.isNaN() || src.isInfinite())
return new JsonPrimitive(src.toString());
return new JsonPrimitive(src);
}
})
.create();
if (extras != null && extras.size() > 1) {
if (FirebasePlugin.notificationStack == null) {
FirebasePlugin.notificationStack = new ArrayList<Bundle>();
}
if (extras.containsKey("google.message_id")) {
extras.putString("messageType", "notification");
extras.putString("tap", "background");
notificationStack.add(extras);
Log.d(TAG, "Notification message found on init: " + extras.toString());
}
}
defaultChannelId = getStringResource("default_notification_channel_id");
defaultChannelName = getStringResource("default_notification_channel_name");
createDefaultChannel();
} catch (Exception e) {
handleExceptionWithoutContext(e);
}
}
});
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
switch (action) {
case "getId":
this.getInstallationId(args, callbackContext);
break;
case "getToken":
this.getToken(args, callbackContext);
break;
case "hasPermission":
this.hasPermission(callbackContext);
break;
case "grantPermission":
this.grantPermission(callbackContext);
break;
case "subscribe":
this.subscribe(callbackContext, args.getString(0));
break;
case "unsubscribe":
this.unsubscribe(callbackContext, args.getString(0));
break;
case "isAutoInitEnabled":
this.isAutoInitEnabled(callbackContext);
break;
case "setAutoInitEnabled":
this.setAutoInitEnabled(callbackContext, args.getBoolean(0));
break;
case "unregister":
this.unregister(callbackContext);
break;
case "onMessageReceived":
this.onMessageReceived(callbackContext);
break;
case "onTokenRefresh":
this.onTokenRefresh(callbackContext);
break;
case "logEvent":
this.logEvent(callbackContext, args.getString(0), args.getJSONObject(1));
break;
case "logError":
this.logError(callbackContext, args);
break;
case "setCrashlyticsUserId":
this.setCrashlyticsUserId(callbackContext, args.getString(0));
break;
case "setScreenName":
this.setScreenName(callbackContext, args.getString(0));
break;
case "setUserId":
this.setUserId(callbackContext, args.getString(0));
break;
case "setUserProperty":
this.setUserProperty(callbackContext, args.getString(0), args.getString(1));
break;
case "activateFetched":
this.activateFetched(callbackContext);
break;
case "fetchAndActivate":
this.fetchAndActivate(callbackContext);
break;
case "fetch":
if (args.length() > 0) {
this.fetch(callbackContext, args.getLong(0));
} else {
this.fetch(callbackContext);
}
break;
case "resetRemoteConfig":
this.resetRemoteConfig(callbackContext);
break;
case "getValue":
this.getValue(callbackContext, args.getString(0));
break;
case "getInfo":
this.getInfo(callbackContext);
break;
case "getAll":
this.getAll(callbackContext);
break;
case "didCrashOnPreviousExecution":
this.didCrashOnPreviousExecution(callbackContext);
break;
case "setConfigSettings":
this.setConfigSettings(callbackContext, args);
break;
case "setDefaults":
this.setDefaults(callbackContext, args.getJSONObject(0));
break;
case "verifyPhoneNumber":
this.verifyPhoneNumber(callbackContext, args);
break;
case "enrollSecondAuthFactor":
this.enrollSecondAuthFactor(callbackContext, args);
break;
case "verifySecondAuthFactor":
this.verifySecondAuthFactor(callbackContext, args);
break;
case "listEnrolledSecondAuthFactors":
this.listEnrolledSecondAuthFactors(callbackContext, args);
break;
case "unenrollSecondAuthFactor":
this.unenrollSecondAuthFactor(callbackContext, args);
break;
case "setLanguageCode":
this.setLanguageCode(callbackContext, args);
break;
case "authenticateUserWithGoogle":
this.authenticateUserWithGoogle(callbackContext, args);
break;
case "authenticateUserWithApple":
this.authenticateUserWithApple(callbackContext, args);
break;
case "authenticateUserWithMicrosoft":
this.authenticateUserWithMicrosoft(callbackContext, args);
break;
case "authenticateUserWithFacebook":
this.authenticateUserWithFacebook(callbackContext, args);
break;
case "authenticateUserWithOAuth":
this.authenticateUserWithOAuth(callbackContext, args);
break;
case "createUserWithEmailAndPassword":
this.createUserWithEmailAndPassword(callbackContext, args);
break;
case "signInUserWithEmailAndPassword":
this.signInUserWithEmailAndPassword(callbackContext, args);
break;
case "authenticateUserWithEmailAndPassword":
this.authenticateUserWithEmailAndPassword(callbackContext, args);
break;
case "signInUserWithCustomToken":
this.signInUserWithCustomToken(callbackContext, args);
break;
case "signInUserAnonymously":
this.signInUserAnonymously(callbackContext);
break;
case "signInWithCredential":
this.signInWithCredential(callbackContext, args);
break;
case "linkUserWithCredential":
this.linkUserWithCredential(callbackContext, args);
break;
case "unlinkUserWithProvider":
this.unlinkUserWithProvider(callbackContext, args);
break;
case "reauthenticateWithCredential":
this.reauthenticateWithCredential(callbackContext, args);
break;
case "isUserSignedIn":
this.isUserSignedIn(callbackContext, args);
break;
case "signOutUser":
this.signOutUser(callbackContext, args);
break;
case "getCurrentUser":
this.getCurrentUser(callbackContext, args);
break;
case "reloadCurrentUser":
this.reloadCurrentUser(callbackContext, args);
break;
case "updateUserProfile":
this.updateUserProfile(callbackContext, args);
break;
case "updateUserEmail":
this.updateUserEmail(callbackContext, args);
break;
case "sendUserEmailVerification":
this.sendUserEmailVerification(callbackContext, args);
break;
case "verifyBeforeUpdateEmail":
this.verifyBeforeUpdateEmail(callbackContext, args);
break;
case "updateUserPassword":
this.updateUserPassword(callbackContext, args);
break;
case "sendUserPasswordResetEmail":
this.sendUserPasswordResetEmail(callbackContext, args);
break;
case "deleteUser":
this.deleteUser(callbackContext, args);
break;
case "useAuthEmulator":
this.useAuthEmulator(callbackContext, args);
break;
case "getClaims":
this.getClaims(callbackContext, args);
break;
case "startTrace":
this.startTrace(callbackContext, args.getString(0));
break;
case "incrementCounter":
this.incrementCounter(callbackContext, args.getString(0), args.getString(1));
break;
case "stopTrace":
this.stopTrace(callbackContext, args.getString(0));
break;
case "setAnalyticsCollectionEnabled":
this.setAnalyticsCollectionEnabled(callbackContext, args.getBoolean(0));
break;
case "isAnalyticsCollectionEnabled":
this.isAnalyticsCollectionEnabled(callbackContext);
break;
case "setPerformanceCollectionEnabled":
this.setPerformanceCollectionEnabled(callbackContext, args.getBoolean(0));
break;
case "isPerformanceCollectionEnabled":
this.isPerformanceCollectionEnabled(callbackContext);
break;
case "setCrashlyticsCollectionEnabled":
this.setCrashlyticsCollectionEnabled(callbackContext, args.getBoolean(0));
break;
case "isCrashlyticsCollectionEnabled":
this.isCrashlyticsCollectionEnabled(callbackContext);
break;
case "setAnalyticsConsentMode":
this.setAnalyticsConsentMode(callbackContext, args.getJSONObject(0));
break;
case "clearAllNotifications":
this.clearAllNotifications(callbackContext);
break;
case "setCrashlyticsCustomKey":
this.setCrashlyticsCustomKey(callbackContext, args);
break;
case "logMessage":
logMessage(args, callbackContext);
break;
case "sendCrash":
sendCrash(args, callbackContext);
break;
case "createChannel":
this.createChannel(callbackContext, args.getJSONObject(0));
break;
case "deleteChannel":
this.deleteChannel(callbackContext, args.getString(0));
break;
case "listChannels":
this.listChannels(callbackContext);
break;
case "setDefaultChannel":
this.setDefaultChannel(callbackContext, args.getJSONObject(0));
break;
case "addDocumentToFirestoreCollection":
this.addDocumentToFirestoreCollection(args, callbackContext);
break;
case "setDocumentInFirestoreCollection":
this.setDocumentInFirestoreCollection(args, callbackContext);
break;
case "updateDocumentInFirestoreCollection":
this.updateDocumentInFirestoreCollection(args, callbackContext);
break;
case "deleteDocumentFromFirestoreCollection":
this.deleteDocumentFromFirestoreCollection(args, callbackContext);
break;
case "documentExistsInFirestoreCollection":
this.documentExistsInFirestoreCollection(args, callbackContext);
break;
case "fetchDocumentInFirestoreCollection":
this.fetchDocumentInFirestoreCollection(args, callbackContext);
break;
case "fetchFirestoreCollection":
this.fetchFirestoreCollection(args, callbackContext);
break;
case "listenToDocumentInFirestoreCollection":
this.listenToDocumentInFirestoreCollection(args, callbackContext);
break;
case "listenToFirestoreCollection":
this.listenToFirestoreCollection(args, callbackContext);
break;
case "removeFirestoreListener":
this.removeFirestoreListener(args, callbackContext);
break;
case "functionsHttpsCallable":
this.functionsHttpsCallable(args, callbackContext);
break;
case "grantCriticalPermission":
case "hasCriticalPermission":
case "setBadgeNumber":
case "getBadgeNumber":
// Stubs for other platform methods
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true));
break;
case "deleteInstallationId":
this.deleteInstallationId(args, callbackContext);
break;
case "getInstallationId":
this.getInstallationId(args, callbackContext);
break;
case "getInstallationToken":
this.getInstallationToken(args, callbackContext);
break;
default:
callbackContext.error("Invalid action: " + action);
return false;
}
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
return false;
}
return true;
}
@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;
FirebasePlugin.activityResultCallbackContext = null;
FirebasePlugin.authResultCallbackContext = null;
}
@Override
public void onDestroy() {
FirebaseAuth.getInstance().removeAuthStateListener(authStateListener);
instance = null;
cordovaActivity = null;
cordovaInterface = null;
applicationContext = null;
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case GOOGLE_SIGN_IN:
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
GoogleSignInAccount acct;
try {
acct = task.getResult(ApiException.class);
} catch (ApiException ae) {
if (ae.getStatusCode() == 10) {
throw new Exception("Unknown server client ID");
} else {
throw new Exception(CommonStatusCodes.getStatusCodeString(ae.getStatusCode()));
}
}
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
String id = FirebasePlugin.instance.saveAuthCredential(credential);
String idToken = acct.getIdToken();
JSONObject returnResults = new JSONObject();
returnResults.put("instantVerification", true);
returnResults.put("id", id);
returnResults.put("idToken", idToken);
FirebasePlugin.activityResultCallbackContext.success(returnResults);
break;
}
} catch (Exception e) {
handleExceptionWithContext(e, FirebasePlugin.activityResultCallbackContext);
}
}
/**
* Get a string from resources without importing the .R package
*
* @param name Resource Name
* @return Resource
*/
private String getStringResource(String name) {
return applicationContext.getString(
applicationContext.getResources().getIdentifier(
name, "string", applicationContext.getPackageName()
)
);
}
private void onMessageReceived(final CallbackContext callbackContext) {
FirebasePlugin.notificationCallbackContext = callbackContext;
if (FirebasePlugin.notificationStack != null) {
for (Bundle bundle : FirebasePlugin.notificationStack) {
FirebasePlugin.sendMessage(bundle, applicationContext);
}
FirebasePlugin.notificationStack.clear();
}
}
private void onTokenRefresh(final CallbackContext callbackContext) {
FirebasePlugin.tokenRefreshCallbackContext = callbackContext;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
try {
if (task.isSuccessful() || task.getException() == null) {
String currentToken = task.getResult();
if (currentToken != null) {
FirebasePlugin.sendToken(currentToken);
}
} else if (task.getException() != null) {
callbackContext.error(task.getException().getMessage());
} else {
callbackContext.error("Task failed for unknown reason");
}
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
;
});
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
public static void sendMessage(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 (bundle != null) {
// Pass the message bundle to the receiver manager so any registered receivers can decide to handle it
boolean wasHandled = FirebasePluginMessageReceiverManager.sendMessage(bundle);
if (wasHandled) {
Log.d(TAG, "Message bundle was handled by a registered receiver");
} else if (callbackContext != null) {
JSONObject json = new JSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
try {
json.put(key, bundle.get(key));
} catch (JSONException e) {
handleExceptionWithContext(e, callbackContext);
return;
}
}
FirebasePlugin.instance.sendPluginResultAndKeepCallback(json, callbackContext);
}
}
}
public static void sendToken(String token) {
if (FirebasePlugin.tokenRefreshCallbackContext == null) {
return;
}
final CallbackContext callbackContext = FirebasePlugin.tokenRefreshCallbackContext;
if (callbackContext != null && token != null) {
FirebasePlugin.instance.sendPluginResultAndKeepCallback(token, callbackContext);
}
}
public static boolean inBackground() {
return FirebasePlugin.inBackground;
}
public static boolean hasNotificationsCallback() {
return FirebasePlugin.notificationCallbackContext != null;
}
@Override
public void onNewIntent(Intent intent) {
try {
super.onNewIntent(intent);
final Bundle data = intent.getExtras();
if (data != null && data.containsKey("google.message_id")) {
data.putString("messageType", "notification");
data.putString("tap", "background");
Log.d(TAG, "Notification message on new intent: " + data.toString());
FirebasePlugin.sendMessage(data, applicationContext);
}
} catch (Exception e) {
handleExceptionWithoutContext(e);
}
}
private void getToken(JSONArray args, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
try {
if (task.isSuccessful() || task.getException() == null) {
String currentToken = task.getResult();
callbackContext.success(currentToken);
} else if (task.getException() != null) {
callbackContext.error(task.getException().getMessage());
} else {
callbackContext.error("Task failed for unknown reason");
}
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
;
});
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void hasPermission(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(cordovaActivity);
boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
boolean hasRuntimePermission = true;
if (Build.VERSION.SDK_INT >= 33) { // Android 13+
hasRuntimePermission = hasRuntimePermission(POST_NOTIFICATIONS);
}
callbackContext.success(conformBooleanForPluginResult(areNotificationsEnabled && hasRuntimePermission));
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void grantPermission(final CallbackContext callbackContext) {
CordovaPlugin plugin = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
if (Build.VERSION.SDK_INT >= 33) { // Android 13+
boolean hasRuntimePermission = hasRuntimePermission(POST_NOTIFICATIONS);
if (!hasRuntimePermission) {
String[] permissions = new String[]{qualifyPermission(POST_NOTIFICATIONS)};
postNotificationPermissionRequestCallbackContext = callbackContext;
requestPermissions(plugin, POST_NOTIFICATIONS_PERMISSION_REQUEST_ID, permissions);
sendEmptyPluginResultAndKeepCallback(callbackContext);
}
} else {
// No runtime permission required on Android 12 and below
callbackContext.success(1);
}
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void subscribe(final CallbackContext callbackContext, final String topic) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
handleTaskOutcome(FirebaseMessaging.getInstance().subscribeToTopic(topic), callbackContext);
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void unsubscribe(final CallbackContext callbackContext, final String topic) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
handleTaskOutcome(FirebaseMessaging.getInstance().unsubscribeFromTopic(topic), callbackContext);
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void unregister(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
handleTaskOutcome(FirebaseMessaging.getInstance().deleteToken(), callbackContext);
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void isAutoInitEnabled(final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
boolean isEnabled = FirebaseMessaging.getInstance().isAutoInitEnabled();
callbackContext.success(conformBooleanForPluginResult(isEnabled));
} catch (Exception e) {
logExceptionToCrashlytics(e);
callbackContext.error(e.getMessage());
}
}
});
}
private void setAutoInitEnabled(final CallbackContext callbackContext, final boolean enabled) {
final FirebasePlugin self = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
FirebaseMessaging.getInstance().setAutoInitEnabled(enabled);
callbackContext.success();
} catch (Exception e) {
logExceptionToCrashlytics(e);
e.printStackTrace();
callbackContext.error(e.getMessage());
}
}
});
}
private Bundle createBundleFromJSONObject(final JSONObject params) throws JSONException {
final Bundle bundle = new Bundle();
Iterator<String> iter = params.keys();
while (iter.hasNext()) {
String key = iter.next();
Object obj = params.get(key);
if (obj instanceof Integer) {
bundle.putInt(key, (Integer) obj);
} else if (obj instanceof Double) {
bundle.putDouble(key, (Double) obj);
} else if (obj instanceof Float) {
bundle.putFloat(key, (Float) obj);
} else if (obj instanceof JSONObject) {
Bundle item = this.createBundleFromJSONObject((JSONObject) obj);
bundle.putBundle(key, item);
} else if (obj instanceof JSONArray) {
JSONArray objArr = (JSONArray) obj;
ArrayList<Bundle> bundleArray = new ArrayList<Bundle>(objArr.length());
for (int idx = 0; idx < objArr.length(); idx++) {
Object tmp = objArr.get(idx);
if (tmp instanceof JSONObject) {
Bundle item = createBundleFromJSONObject(objArr.getJSONObject(idx));
bundleArray.add(item);
}
}
bundle.putParcelableArrayList(key, bundleArray);
} else {
bundle.putString(key, obj.toString());
}
}
return bundle;
}
private void logEvent(final CallbackContext callbackContext, final String name, final JSONObject params)
throws JSONException {
final Bundle bundle = this.createBundleFromJSONObject(params);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
mFirebaseAnalytics.logEvent(name, bundle);
callbackContext.success();
} catch (Exception e) {
handleExceptionWithContext(e, callbackContext);
}
}
});
}
private void logError(final CallbackContext callbackContext, final JSONArray args) throws JSONException {
final String message = args.getString(0);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
if (isCrashlyticsEnabled()) {
// We can optionally be passed a stack trace generated by stacktrace.js.
if (args.length() == 2) {
JSONArray stackTrace = args.getJSONArray(1);
StackTraceElement[] trace = new StackTraceElement[stackTrace.length()];
for (int i = 0; i < stackTrace.length(); i++) {
JSONObject elem = stackTrace.getJSONObject(i);
trace[i] = new StackTraceElement(
"",
elem.optString("functionName", "(anonymous function)"),
elem.optString("fileName", "(unknown file)"),
elem.optInt("lineNumber", -1)
);
}
Exception e = new JavaScriptException(message);
e.setStackTrace(trace);
logExceptionToCrashlytics(e);
} else {
logExceptionToCrashlytics(new JavaScriptException(message));
}
Log.e(TAG, message);
callbackContext.success(1);
} else {
callbackContext.error("Cannot log error - Crashlytics collection is disabled");
}
} catch (Exception e) {
logExceptionToCrashlytics(e);
callbackContext.error(e.getMessage());
}