From 5101c1a05c0c0ca1dcf4dea9d3f543cf05fc1f81 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Fri, 13 Mar 2020 17:20:18 +0000 Subject: [PATCH 01/24] Minor version (CLI): 9.0.1-cli --- CHANGELOG.md | 21 ++++----------------- README.md | 39 ++++++++++++++++++--------------------- package.json | 2 +- plugin.xml | 8 +------- 4 files changed, 24 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 079b6b52a..97c86abbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,23 +3,10 @@ * *BREAKING CHANGE* to function signature. * Merged from PR [#367](https://github.com/dpa99c/cordova-plugin-firebasex/pull/367). -# Version 9.0.3 -* (Android & iOS) Add `reloadCurrentUser()` -* (Doc) `createChannel()` suggestion for multiple sounds - * Merged from PR [#225](https://github.com/dpa99c/cordova-plugin-firebasex/pull/225). -* (iOS) Implement `getInfo()` for iOS. - * Merged from PR [#363](https://github.com/dpa99c/cordova-plugin-firebasex/pull/363). -* (Android & iOS) Add `signInUserWithCustomToken()` AND `signInUserAnonymously()` auth methods - * Merged from PR [#359](https://github.com/dpa99c/cordova-plugin-firebasex/pull/359). - -# Version 9.0.2 -* (Android): Don't display app icon for large notification icon on Android. Resolves [#343](https://github.com/dpa99c/cordova-plugin-firebasex/issues/343). -* (Android & iOS) Sign out of Google signing out of Firebase. Resolves [#353](https://github.com/dpa99c/cordova-plugin-firebasex/issues/353). -* (Android & iOS) Add `documentExistsInFirestoreCollection()` and fix resolution of `fetchDocumentInFirestoreCollection()`. - -# Version 9.0.1 -* Re-add Firebase Inapp Messaging SDK component to master branch. -* Document `cli_build` branch. See [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326). +# Version 9.0.1-cli +* Document `cli_build` branch. +* *BREAKING CHANGE*: Remove Firebase Inapp Messaging and Google Tag Manager SDK components due to causing Cordova CLI build issues. + * Resolves [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326). # Version 9.0.0 * *BREAKING CHANGE*: Change method signature of `setCrashlyticsCollectionEnabled()` to `(enabled, success, error)` (from `()`) to allow enabling/disabling of Crashlytics at runtime and align it with `setPerformanceCollectionEnabled()` and `setAnalyticsCollectionEnabled()` diff --git a/README.md b/README.md index 9760ee520..83289fa90 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,20 @@ Brings push notifications, analytics, event tracking, crash reporting and more f Supported platforms: Android and iOS +#cli_build branch +This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. +It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). + +To use it, install an npm release with the `-cli` suffix, e.g.: + + cordova plugin add cordova-plugin-firebasex@9.0.1-cli + +Or install it directly from this branch: + + cordova plugin add https://github.com/dpa99c/cordova-plugin-firebasex#cli_build + +If you wish to use either of these components, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a major plugin release via the NPM registry and build using Xcode. + [![donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZRD3W47HQ3EMJ) @@ -196,7 +210,6 @@ The following plugin variables are used to specify the Firebase SDK versions as - `ANDROID_FIREBASE_CONFIG_VERSION` - `ANDROID_FIREBASE_PERF_VERSION` - `ANDROID_FIREBASE_AUTH_VERSION` -- `$ANDROID_FIREBASE_INAPPMESSAGING_VERSION` - `ANDROID_FIREBASE_FIRESTORE_VERSION` - `ANDROID_CRASHLYTICS_VERSION` - `ANDROID_CRASHLYTICS_NDK_VERSION` @@ -361,7 +374,6 @@ The following plugin variables are used to specify the following Gradle dependen - `ANDROID_FIREBASE_PERF_VERSION` => `com.google.firebase:firebase-perf` - `ANDROID_FIREBASE_AUTH_VERSION` => `com.google.firebase:firebase-auth` - `ANDROID_FIREBASE_FIRESTORE_VERSION` => `com.google.firebase:firebase-firestore` -- `$ANDROID_FIREBASE_INAPPMESSAGING_VERSION` => `com.google.firebase:firebase-inappmessaging-display` - `ANDROID_CRASHLYTICS_VERSION` => `com.crashlytics.sdk.android:crashlytics` - `ANDROID_CRASHLYTICS_NDK_VERSION` => `com.crashlytics.sdk.android:crashlytics-ndk` - `ANDROID_GSON_VERSION` => `com.google.code.gson:gson` @@ -1176,27 +1188,12 @@ The [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) c You can test this by building and running the example project app, and sending the [notification_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/notification_custom_receiver.json) and [data_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/data_custom_receiver.json) test messages using the [built-in FCM client](https://github.com/dpa99c/cordova-plugin-firebasex-test#messaging-client). # InApp Messaging -Engage active app users with contextual messages. -The SDK component is included in the plugin but no explicit plugin API calls are required to use inapp messaging. - -See the [iOS](https://firebase.google.com/docs/in-app-messaging/get-started?platform=ios#send_a_test_message) and [Android](https://firebase.google.com/docs/in-app-messaging/get-started?platform=android#send_a_test_message) guides for how to send a test message. +The Firebase Inapp Messaging SDK component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). +If you wish to use Firebase Inapp Messaging, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. # Google Tag Manager -Download your container-config json file from Tag Manager and add a `` node in your `config.xml`. - -## Android -```xml - - - ... -``` - -## iOS -```xml - - - ... -``` +The Google Tag Manager component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). +If you wish to use Google Tag Manager, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. # API The list of available methods for this plugin is described below. diff --git a/package.json b/package.json index f06f88669..1c78c44ac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-firebasex", - "version": "9.1.0", + "version": "9.0.1-cli", "description": "Cordova plugin for Google Firebase", "types": "./types/index.d.ts", "author": { diff --git a/plugin.xml b/plugin.xml index 9706a43c4..b3ece749b 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,5 +1,5 @@ - Google Firebase Plugin @@ -61,27 +61,23 @@ - - - - @@ -136,12 +132,10 @@ - - From afef95322bacfbcbeabf2763a1da03f71646a64c Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Fri, 13 Mar 2020 17:27:46 +0000 Subject: [PATCH 02/24] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83289fa90..293bac452 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Brings push notifications, analytics, event tracking, crash reporting and more f Supported platforms: Android and iOS -#cli_build branch +# cli_build branch This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). From b780de3ab089b32272a12ae8f1820037b209946c Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Mon, 16 Mar 2020 08:27:11 +0000 Subject: [PATCH 03/24] (Android): Don't display app icon for large notification icon on Android. Resolves #343. --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97c86abbe..50ec6ea97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ * *BREAKING CHANGE* to function signature. * Merged from PR [#367](https://github.com/dpa99c/cordova-plugin-firebasex/pull/367). +* (Android): Don't display app icon for large notification icon on Android. Resolves [#343](https://github.com/dpa99c/cordova-plugin-firebasex/issues/343). + # Version 9.0.1-cli * Document `cli_build` branch. * *BREAKING CHANGE*: Remove Firebase Inapp Messaging and Google Tag Manager SDK components due to causing Cordova CLI build issues. From 0f414eea8de19cef6bb1296733ae54a7efd3e2e5 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Sun, 5 Apr 2020 22:04:46 +0100 Subject: [PATCH 04/24] [iOS] Sign out of Google when signing out of Firebase. Resolves #353. --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50ec6ea97..8c13fbf03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * Merged from PR [#367](https://github.com/dpa99c/cordova-plugin-firebasex/pull/367). * (Android): Don't display app icon for large notification icon on Android. Resolves [#343](https://github.com/dpa99c/cordova-plugin-firebasex/issues/343). +* (Android & iOS) Sign out of Google signing out of Firebase. Resolves [#353](https://github.com/dpa99c/cordova-plugin-firebasex/issues/353). # Version 9.0.1-cli * Document `cli_build` branch. From ab6a89a7a9bfdc304a5035fdde589a8e1a08689c Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Sun, 5 Apr 2020 22:52:43 +0100 Subject: [PATCH 05/24] (Android & iOS) Add documentExistsInFirestoreCollection() and fix resolution of fetchDocumentInFirestoreCollection(). --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c13fbf03..ff715c4ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * (Android): Don't display app icon for large notification icon on Android. Resolves [#343](https://github.com/dpa99c/cordova-plugin-firebasex/issues/343). * (Android & iOS) Sign out of Google signing out of Firebase. Resolves [#353](https://github.com/dpa99c/cordova-plugin-firebasex/issues/353). +* (Android & iOS) Add `documentExistsInFirestoreCollection()` and fix resolution of `fetchDocumentInFirestoreCollection()`. # Version 9.0.1-cli * Document `cli_build` branch. From 3ecbad347da49c0022dc8bba3db846a8239aa307 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Tue, 7 Apr 2020 19:59:36 +0100 Subject: [PATCH 06/24] Patch version: 9.0.2-cli --- CHANGELOG.md | 2 ++ package.json | 2 +- plugin.xml | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff715c4ed..1e8681546 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ * *BREAKING CHANGE* to function signature. * Merged from PR [#367](https://github.com/dpa99c/cordova-plugin-firebasex/pull/367). +# Version 9.0.2-cli + * (Android): Don't display app icon for large notification icon on Android. Resolves [#343](https://github.com/dpa99c/cordova-plugin-firebasex/issues/343). * (Android & iOS) Sign out of Google signing out of Firebase. Resolves [#353](https://github.com/dpa99c/cordova-plugin-firebasex/issues/353). * (Android & iOS) Add `documentExistsInFirestoreCollection()` and fix resolution of `fetchDocumentInFirestoreCollection()`. diff --git a/package.json b/package.json index 1c78c44ac..6f2613449 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-firebasex", - "version": "9.0.1-cli", + "version": "9.0.2-cli", "description": "Cordova plugin for Google Firebase", "types": "./types/index.d.ts", "author": { diff --git a/plugin.xml b/plugin.xml index b3ece749b..a0e5ca1c2 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,5 +1,5 @@ - Google Firebase Plugin From 06624280cc3e6143ce2d2238958c962f83264265 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Mon, 13 Apr 2020 19:51:47 +0100 Subject: [PATCH 07/24] Patch version: 9.0.3-cli --- CHANGELOG.md | 2 +- package.json | 2 +- plugin.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e8681546..05cd534e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# Version 9.1.0 +# Version 9.0.3-cli * (Android & iOS) *BREAKING CHANGE*: Add support for filters to `fetchDocumentInFirestoreCollection()` * *BREAKING CHANGE* to function signature. * Merged from PR [#367](https://github.com/dpa99c/cordova-plugin-firebasex/pull/367). diff --git a/package.json b/package.json index 6f2613449..683d72ed7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-firebasex", - "version": "9.0.2-cli", + "version": "9.0.3-cli", "description": "Cordova plugin for Google Firebase", "types": "./types/index.d.ts", "author": { diff --git a/plugin.xml b/plugin.xml index a0e5ca1c2..b22b702d3 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,5 +1,5 @@ - Google Firebase Plugin From 23f2b11a664a97633b196b4f3188b1b84c9f2971 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Thu, 16 Apr 2020 19:03:24 +0100 Subject: [PATCH 08/24] Minor version: 9.1.0-cli --- CHANGELOG.md | 13 ++++++++++++- package.json | 2 +- plugin.xml | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05cd534e0..6a3b7d2c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,19 @@ -# Version 9.0.3-cli +# Version 9.1.0-cli * (Android & iOS) *BREAKING CHANGE*: Add support for filters to `fetchDocumentInFirestoreCollection()` * *BREAKING CHANGE* to function signature. * Merged from PR [#367](https://github.com/dpa99c/cordova-plugin-firebasex/pull/367). +* (Android) Fix regression bug which causes CLI builds to fail on Android. +Resolves [#369](https://github.com/dpa99c/cordova-plugin-firebasex/issues/369). +# Version 9.0.3-cli +* (Android & iOS) Add `reloadCurrentUser()` +* (Doc) `createChannel()` suggestion for multiple sounds + * Merged from PR [#225](https://github.com/dpa99c/cordova-plugin-firebasex/pull/225). +* (iOS) Implement `getInfo()` for iOS. + * Merged from PR [#363](https://github.com/dpa99c/cordova-plugin-firebasex/pull/363). +* (Android & iOS) Add `signInUserWithCustomToken()` AND `signInUserAnonymously()` auth methods + * Merged from PR [#359](https://github.com/dpa99c/cordova-plugin-firebasex/pull/359). + # Version 9.0.2-cli * (Android): Don't display app icon for large notification icon on Android. Resolves [#343](https://github.com/dpa99c/cordova-plugin-firebasex/issues/343). diff --git a/package.json b/package.json index 683d72ed7..9882a0964 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-firebasex", - "version": "9.0.3-cli", + "version": "9.1.0-cli", "description": "Cordova plugin for Google Firebase", "types": "./types/index.d.ts", "author": { diff --git a/plugin.xml b/plugin.xml index b22b702d3..433dca9b9 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,5 +1,5 @@ - Google Firebase Plugin From 08fc857f5df096618adcf6ec9507899abd3a31cd Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Sun, 26 Apr 2020 07:27:21 +0100 Subject: [PATCH 09/24] (Android) Bump Firebase SDK (and other Gradle dependencies) to latest versions. See https://firebase.google.com/support/release-notes/android#2020-04-23 --- plugin.xml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/plugin.xml b/plugin.xml index 433dca9b9..cc8bb95bc 100644 --- a/plugin.xml +++ b/plugin.xml @@ -61,13 +61,13 @@ - - - - - - - + + + + + + + From f6720f3cec8c2836b6ecaf9811860c68db05d890 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Sun, 26 Apr 2020 07:29:55 +0100 Subject: [PATCH 10/24] (iOS): Bump Firebase SDK components to v6.23.0. Relates to #373. See https://firebase.google.com/support/release-notes/ios#version_6230_-_april_21_2020. --- plugin.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/plugin.xml b/plugin.xml index cc8bb95bc..145057d78 100644 --- a/plugin.xml +++ b/plugin.xml @@ -127,12 +127,12 @@ - - - - - - + + + + + + From 4457439347a82b7e4fd9e5fc243bcc1ad0e07faa Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Sun, 26 Apr 2020 07:31:29 +0100 Subject: [PATCH 11/24] Patch version: 9.1.1-cli --- CHANGELOG.md | 7 +++++++ package.json | 2 +- plugin.xml | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a3b7d2c9..b1b916975 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# Version 9.1.1-cli +* (iOS): Bump Firebase SDK components to v6.23.0. + * Relates to [#373](https://github.com/dpa99c/cordova-plugin-firebasex/issues/373). + * See https://firebase.google.com/support/release-notes/ios#version_6230_-_april_21_2020. +* (Android) Bump Firebase SDK (and other Gradle dependencies) to latest versions. + * See https://firebase.google.com/support/release-notes/android#2020-04-23 + # Version 9.1.0-cli * (Android & iOS) *BREAKING CHANGE*: Add support for filters to `fetchDocumentInFirestoreCollection()` * *BREAKING CHANGE* to function signature. diff --git a/package.json b/package.json index 9882a0964..18730f295 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-firebasex", - "version": "9.1.0-cli", + "version": "9.1.1-cli", "description": "Cordova plugin for Google Firebase", "types": "./types/index.d.ts", "author": { diff --git a/plugin.xml b/plugin.xml index 145057d78..79ebd8fa9 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,5 +1,5 @@ - Google Firebase Plugin From 84f36bfc31fcb5d2e16a47695cb1793a4e04c9ca Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Wed, 29 Apr 2020 13:11:53 +0100 Subject: [PATCH 12/24] (Android) Fix retrieval of auth provider ID. See https://github.com/firebase/FirebaseUI-Android/issues/329#issuecomment-564409912 --- src/android/FirebasePlugin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/android/FirebasePlugin.java b/src/android/FirebasePlugin.java index c96c45f1c..4b7884d64 100755 --- a/src/android/FirebasePlugin.java +++ b/src/android/FirebasePlugin.java @@ -1102,7 +1102,7 @@ private void extractAndReturnUserInfo(final CallbackContext callbackContext) thr returnResults.put("phoneNumber", user.getPhoneNumber()); returnResults.put("photoUrl", user.getPhotoUrl() == null ? null : user.getPhotoUrl().toString()); returnResults.put("uid", user.getUid()); - returnResults.put("providerId", user.getProviderId()); + returnResults.put("providerId", user.getIdToken(false).getResult().getSignInProvider()); returnResults.put("isAnonymous", user.isAnonymous()); user.getIdToken(true).addOnSuccessListener(new OnSuccessListener() { From faf7d0c3a60ba88581f3e047376c58dda6166acc Mon Sep 17 00:00:00 2001 From: Ankur Panchani Date: Mon, 11 May 2020 14:02:14 +0530 Subject: [PATCH 13/24] Fix: correct return type of a method --- types/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/index.d.ts b/types/index.d.ts index e9cf84aca..d2cb96360 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -116,7 +116,7 @@ interface FirebasePlugin { stackTrace?: object, success?: () => void, error?: (err: string) => void - ) + ): void verifyPhoneNumber( success: (value: object) => void, error: (err: string) => void, From 414c274dfa3d604ed81ec0048f6dc5f4d7a3f0e8 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Wed, 13 May 2020 09:36:16 +0100 Subject: [PATCH 14/24] (Documentation) Update guidance and requirements when opening issues # Conflicts: # README.md --- .github/ISSUE_TEMPLATE/bug_report.md | 13 +--- .github/ISSUE_TEMPLATE/documentation-issue.md | 4 +- .github/ISSUE_TEMPLATE/feature_request.md | 4 +- README.md | 62 +++++++++++++++---- 4 files changed, 58 insertions(+), 25 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 834937392..e2396e480 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -14,16 +14,7 @@ WARNING: Failure to follow the issue template guidelines below will result in th Only bug reports should be opened here. -Before opening an issue, please do the following: -- check a similar issue is not already open (or closed) against this plugin. - - Duplicates or near-duplicates will be closed immediately. -- try to reproduce the issue using the example project - - or if that's not possible, using an isolated test project that you are able to share - - this will eliminate bugs in your code or conflicts with other code as possible causes of the issue -- any issue which is suspected of being caused by the Ionic Native wrapper should be [reported against Ionic Native](https://github.com/ionic-team/ionic-native/issues/new) - - Ionic Native Typescript wrappers are maintained by the Ionic Team - - To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper). - - Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately. +Before opening an issue, please read [Reporting issues](https://github.com/dpa99c/cordova-plugin-firebasex#reporting-issues) --> @@ -117,4 +108,4 @@ A POLITE REMINDER - Help/support will not be given by the author, so forums (e.g. Ionic) or Stack Overflow should be used. Any issues requesting help/support will be closed immediately. - If you have urgent need of a bug fix/feature, the author can be engaged for PAID contract work to do so: please contact dave@workingedge.co.uk - Rude or abusive comments/issues will not be tolerated, nor will opening multiple issues if those previously closed are deemed unsuitable. Any of the above will result in you being BANNED from ALL of my Github repositories. ---> \ No newline at end of file +--> diff --git a/.github/ISSUE_TEMPLATE/documentation-issue.md b/.github/ISSUE_TEMPLATE/documentation-issue.md index dcbcee646..f8d8d8196 100644 --- a/.github/ISSUE_TEMPLATE/documentation-issue.md +++ b/.github/ISSUE_TEMPLATE/documentation-issue.md @@ -11,7 +11,7 @@ WARNING: Failure to follow the issue template guidelines below will result in th Only documentation issues should be opened here. -Before opening an issue, please check a similar issue is not already open (or closed). Duplicates or near-duplicates will be closed immediately. +Before opening an issue, please read [Reporting issues](https://github.com/dpa99c/cordova-plugin-firebasex#reporting-issues) --> @@ -33,4 +33,4 @@ A POLITE REMINDER - Help/support will not be given by the author, so forums (e.g. Ionic) or Stack Overflow should be used. Any issues requesting help/support will be closed immediately. - If you have urgent need of a bug fix/feature, the author can be engaged for PAID contract work to do so: please contact dave@workingedge.co.uk - Rude or abusive comments/issues will not be tolerated, nor will opening multiple issues if those previously closed are deemed unsuitable. Any of the above will result in you being BANNED from ALL of my Github repositories. ---> \ No newline at end of file +--> diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 559f6517f..539d77663 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -11,6 +11,8 @@ WARNING: Failure to follow the issue template guidelines below will result in th Only feature requests should be opened here. +Before opening an issue, please read [Reporting issues](https://github.com/dpa99c/cordova-plugin-firebasex#reporting-issues) + --> @@ -38,4 +40,4 @@ A POLITE REMINDER - Help/support will not be given by the author, so forums (e.g. Ionic) or Stack Overflow should be used. Any issues requesting help/support will be closed immediately. - If you have urgent need of a bug fix/feature, the author can be engaged for PAID contract work to do so: please contact dave@workingedge.co.uk - Rude or abusive comments/issues will not be tolerated, nor will opening multiple issues if those previously closed are deemed unsuitable. Any of the above will result in you being BANNED from ALL of my Github repositories. ---> \ No newline at end of file +--> diff --git a/README.md b/README.md index 293bac452..28b9dab1a 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@ Brings push notifications, analytics, event tracking, crash reporting and more f Supported platforms: Android and iOS +**IMPORTANT:** Before opening an issue against this plugin, please read [Reporting issues](#reporting-issues). + # cli_build branch This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). @@ -58,6 +60,8 @@ To help ensure this plugin is kept updated, new features are added and bugfixes - [Disable data collection on startup](#disable-data-collection-on-startup) - [Example project](#example-project) - [Reporting issues](#reporting-issues) + - [Reporting a bug or problem](#reporting-a-bug-or-problem) + - [Requesting a new feature](#requesting-a-new-feature) - [Cloud messaging](#cloud-messaging) - [Background notifications](#background-notifications) - [Foreground notifications](#foreground-notifications) @@ -513,16 +517,54 @@ Please use this as a working reference. Before reporting any issues, please (if possible) test against the example project to rule out causes external to this plugin. # Reporting issues -Before reporting an issue with this plugin, please do the following: -- check a similar issue is not already open (or closed) against this plugin. -- try to reproduce the issue using the example project - - or if that's not possible, using an isolated test project that you are able to share - - this will eliminate bugs in your code or conflicts with other code as possible causes of the issue -- any issue which is suspected of being caused by the Ionic Native wrapper should be [reported against Ionic Native](https://github.com/ionic-team/ionic-native/issues/new) - - Ionic Native Typescript wrappers are maintained by the Ionic Team +**IMPORTANT:** Please read the following carefully. +Failure to follow the issue template guidelines below will result in the issue being immediately closed. + +## Reporting a bug or problem +Before [opening a bug issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=bug_report.md&title=), please do the following: +- *DO NOT* open issues asking for support in using/integrating the plugin into your project + - Only open issues for suspected bugs/issues with the plugin that are generic and will affect other users + - I don't have time to offer free technical support: this is free open-source software + - Ask for help on StackOverflow, Ionic Forums, etc. + - Use the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) as a known working reference + - Any issues requesting support will be closed immediately. +- *DO NOT* open issues related to the [Ionic Typescript wrapper for this plugin](https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/firebase-x/index.ts) + - This is owned/maintained by [Ionic](https://github.com/ionic-team) and is not part of this plugin + - Please raise such issues/PRs against [Ionic Native](https://github.com/ionic-team/ionic-native/) instead. - To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper). -- if you are having build problems, ensure you have thoroughly read the [Build environment notes](#build-environment-notes) section and searched existing open/closed issues for a similar problem. -- if you are migrating from `cordova-plugin-firebase` to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section. + - Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately. +- If you are migrating from [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section. +- Read the above documentation thoroughly + - For example, if you're having a build issue ensure you've read through the [build environment notes](#build-environment-notes) + - If an iOS CLI build is failing, ensure you've read the [Cordova CLI builds](#cordova-cli-builds) section +- Check the [CHANGELOG](https://github.com/dpa99c/cordova-plugin-firebasex/blob/master/CHANGELOG.md) for any breaking changes that may be causing your issue. +- Check a similar issue (open or closed) does not already exist against this plugin. + - Duplicates or near-duplicates will be closed immediately. +- When [creating a new issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new/choose) + - Choose the "Bug report" template + - Fill out the relevant sections of the template and delete irrelevant sections + - *WARNING:* Failure to complete the issue template will result in the issue being closed immediately. +- Reproduce the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) + - This will eliminate bugs in your code or conflicts with other code as possible causes of the issue + - This will also validate your development environment using a known working codebase + - If reproducing the issue using the example project is not possible, create an isolated test project that you are able to share +- Include full verbose console output when reporting build issues + - If the full console output is too large to insert directly into the Github issue, then post it on an external site such as [Pastebin](https://pastebin.com/) and link to it from the issue + - Often the details of an error causing a build failure is hidden away when building with the CLI + - To get the full detailed console output, append the `--verbose` flag to CLI build commands + - e.g. `cordova build ios --verbose` + - Failure to include the full console output will result in the issue being closed immediately +- If the issue relates to the plugin documentation (and not the code), please of a [documentation issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=documentation-issue.md&title=) + +## Requesting a new feature +Before [opening a feature request issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=feature_request.md&title=), please do the following: +- Check the above documentation to ensure the feature you are requesting doesn't already exist +- Check the list if open/closed issues to check if there's a reason that feature hasn't been included already +- Ensure the feature you are requesting is actually possible to implement and generically useful to other users than yourself +- Where possible, post a link to the documentation related to the feature you are requesting +- Include other relevant links, e.g. + - Stack Overflow post illustrating a solution + - Code within another Github repo that illustrates a solution # Cloud messaging @@ -2878,8 +2920,6 @@ FirebasePlugin.fetchFirestoreCollection(collection, filters, function(documents) }); ``` - - # Credits - [@robertarnesson](https://github.com/robertarnesson) for the original [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) from which this plugin is forked. - [@sagrawal31](https://github.com/sagrawal31) and [Wiz Panda](https://github.com/wizpanda) for contributions via [cordova-plugin-firebase-lib](https://github.com/wizpanda/cordova-plugin-firebase-lib). From 55d431b67cabce9ca06fe85fce4efa4ef42473d7 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Tue, 19 May 2020 23:07:30 +0100 Subject: [PATCH 15/24] (iOS): Fix escaping of line endings in multi-line log messages being sent from native iOS implementation to JS console. Resolves #401. --- src/ios/FirebasePlugin.m | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ios/FirebasePlugin.m b/src/ios/FirebasePlugin.m index 4cb35cdf1..1f257756e 100644 --- a/src/ios/FirebasePlugin.m +++ b/src/ios/FirebasePlugin.m @@ -1618,27 +1618,28 @@ - (void)executeGlobalJavascript: (NSString*)jsString - (void)_logError: (NSString*)msg { NSLog(@"%@ ERROR: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logInfo: (NSString*)msg { NSLog(@"%@ INFO: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logMessage: (NSString*)msg { NSLog(@"%@ LOG: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } -- (NSString*)escapeDoubleQuotes: (NSString*)str +- (NSString*)escapeJavascriptString: (NSString*)str { - NSString *result =[str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; + NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; + result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; return result; } From b08c51277dc57918928e83dc66e0b0c24fd4af7e Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Wed, 20 May 2020 22:09:05 +0100 Subject: [PATCH 16/24] Add checklist to bug report issue template --- .github/ISSUE_TEMPLATE/bug_report.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index e2396e480..c16abb508 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -11,16 +11,30 @@ assignees: '' IMPORTANT: PLEASE READ WARNING: Failure to follow the issue template guidelines below will result in the issue being immediately closed. - -Only bug reports should be opened here. - -Before opening an issue, please read [Reporting issues](https://github.com/dpa99c/cordova-plugin-firebasex#reporting-issues) --> # Bug report + +**CHECKLIST** +- [ ] I have read the [issue reporting guidelines](https://github.com/dpa99c/cordova-plugin-firebasex#reporting-issues) + +- [ ] I confirm this is a suspected bug or issue that will affect other users + + +- [ ] I have reproduced the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) or provided the necessary information to reproduce the issue. + + +- [ ] I have read [the documentation](https://github.com/dpa99c/cordova-plugin-firebasex) thoroughly and it does not help solve my issue. + + +- [ ] I have checked that no similar issues (open or closed) already exist. + + + + **Current behavior:** From b3598f931d864f48c142d89cfd064a9fe5892f8d Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Fri, 22 May 2020 20:33:01 +0100 Subject: [PATCH 17/24] (iOS): Set shouldEstablishDirectChannel via a plugin variable which defaults to false. Resolves #406. --- README.md | 11 ++++++++++- scripts/ios/helper.js | 4 ++++ src/ios/AppDelegate+FirebasePlugin.m | 13 ++++++++----- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 28b9dab1a..74a23bcf7 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,16 @@ See [Specifying Android library versions](#specifying-android-library-versions) ### iOS only - `IOS_STRIP_DEBUG` - prevents symbolification of all libraries included via Cocoapods. See [Strip debug symbols](#strip-debug-symbols) for more info. -- `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info. + - e.g. `--variable IOS_STRIP_DEBUG=true` + - Defaults to `false` if not specified. +- `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info. + - e.g. `--variable IOS_STRIP_DEBUG=true` + - Defaults to `false` if not specified. +- `IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL` - If `true` Firebase Messaging will automatically establish a socket-based, direct channel to the FCM server. + - e.g. `--variable IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL=true` + - Defaults to `false` if not specified. + - See [`shouldEstablishDirectChannel`](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/c:objc(cs)FIRMessaging(py)shouldEstablishDirectChannel) + - Note: Firebase Messaging iOS SDK version 7.0 will be a breaking change where the SDK will no longer support iOS Direct Channel API. ## Supported Cordova Versions - cordova: `>= 9` diff --git a/scripts/ios/helper.js b/scripts/ios/helper.js index 5b312b812..e4507cdf6 100755 --- a/scripts/ios/helper.js +++ b/scripts/ios/helper.js @@ -200,6 +200,10 @@ module.exports = { googlePlist["FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } + if(typeof pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] !== 'undefined'){ + appPlist["shouldEstablishDirectChannel"] = (pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] === "true") ; + appPlistModified = true; + } if(pluginVariables['SETUP_RECAPTCHA_VERIFICATION'] === 'true'){ var reversedClientId = googlePlist['REVERSED_CLIENT_ID']; diff --git a/src/ios/AppDelegate+FirebasePlugin.m b/src/ios/AppDelegate+FirebasePlugin.m index 98d52701b..bf3d4d1c9 100644 --- a/src/ios/AppDelegate+FirebasePlugin.m +++ b/src/ios/AppDelegate+FirebasePlugin.m @@ -27,6 +27,7 @@ + (AppDelegate*) instance { static NSDictionary* mutableUserInfo; static FIRAuthStateDidChangeListenerHandle authStateChangeListener; static bool authStateChangeListenerInitialized = false; +static bool shouldEstablishDirectChannel = false; - (void)setDelegate:(id)delegate { objc_setAssociatedObject(self, kDelegateKey, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); @@ -77,10 +78,12 @@ - (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithO [FirebasePlugin.firebasePlugin _logError:@"GoogleService-Info.plist NOT FOUND, setup: [FIRApp defaultApp]"]; [FIRApp configure]; } + + shouldEstablishDirectChannel = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"shouldEstablishDirectChannel"] boolValue]; // Set FCM messaging delegate [FIRMessaging messaging].delegate = self; - [FIRMessaging messaging].shouldEstablishDirectChannel = true; + [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; // Setup Firestore [FirebasePlugin setFirestore:[FIRFirestore firestore]]; @@ -119,15 +122,15 @@ - (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithO } - (void)applicationDidBecomeActive:(UIApplication *)application { - [FIRMessaging messaging].shouldEstablishDirectChannel = true; self.applicationInBackground = @(NO); - [FirebasePlugin.firebasePlugin _logMessage:@"FCM direct channel = true"]; + [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"Enter foreground: FCM direct channel = %@", shouldEstablishDirectChannel ? @"true" : @"false"]]; } - (void)applicationDidEnterBackground:(UIApplication *)application { - [FIRMessaging messaging].shouldEstablishDirectChannel = false; self.applicationInBackground = @(YES); - [FirebasePlugin.firebasePlugin _logMessage:@"FCM direct channel = false"]; + [FIRMessaging messaging].shouldEstablishDirectChannel = false; + [FirebasePlugin.firebasePlugin _logMessage:@"Enter background: FCM direct channel = false"]; } # pragma mark - Google SignIn From d9a6e54b49f34e6f3d51b8d884a04b9f4306205f Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Mon, 25 May 2020 14:15:02 +0100 Subject: [PATCH 18/24] (iOS) Align retrieval of auth provider ID with Android. See https://github.com/firebase/FirebaseUI-Android/issues/329#issuecomment-564409912 --- src/ios/FirebasePlugin.m | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/ios/FirebasePlugin.m b/src/ios/FirebasePlugin.m index 1f257756e..f470b2c86 100644 --- a/src/ios/FirebasePlugin.m +++ b/src/ios/FirebasePlugin.m @@ -751,11 +751,13 @@ - (void) extractAndReturnUserInfo:(CDVInvokedUrlCommand *)command { [userInfo setValue:user.phoneNumber forKey:@"phoneNumber"]; [userInfo setValue:user.photoURL ? user.photoURL.absoluteString : nil forKey:@"photoUrl"]; [userInfo setValue:user.uid forKey:@"uid"]; - [userInfo setValue:user.providerID forKey:@"providerId"]; [userInfo setValue:@(user.isAnonymous ? true : false) forKey:@"isAnonymous"]; [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) { [userInfo setValue:token forKey:@"idToken"]; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo] callbackId:command.callbackId]; + [user getIDTokenResultWithCompletion:^(FIRAuthTokenResult * _Nullable tokenResult, NSError * _Nullable error) { + [userInfo setValue:tokenResult.signInProvider forKey:@"providerId"]; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo] callbackId:command.callbackId]; + }]; }]; } @@ -1618,28 +1620,27 @@ - (void)executeGlobalJavascript: (NSString*)jsString - (void)_logError: (NSString*)msg { NSLog(@"%@ ERROR: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logInfo: (NSString*)msg { NSLog(@"%@ INFO: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logMessage: (NSString*)msg { NSLog(@"%@ LOG: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; [self executeGlobalJavascript:jsString]; } -- (NSString*)escapeJavascriptString: (NSString*)str +- (NSString*)escapeDoubleQuotes: (NSString*)str { - NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; - result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; + NSString *result =[str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; return result; } From 765cc2a4f89105ef2e2f070f36d3bd26fb791666 Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Thu, 28 May 2020 17:13:51 +0100 Subject: [PATCH 19/24] (iOS) Fix merge error which unintentionally reverted 09af8d366a394417e46b504b9a4efb514b047ff0. Fixes #401 again. --- src/ios/FirebasePlugin.m | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ios/FirebasePlugin.m b/src/ios/FirebasePlugin.m index f470b2c86..83a4dd816 100644 --- a/src/ios/FirebasePlugin.m +++ b/src/ios/FirebasePlugin.m @@ -1620,27 +1620,28 @@ - (void)executeGlobalJavascript: (NSString*)jsString - (void)_logError: (NSString*)msg { NSLog(@"%@ ERROR: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logInfo: (NSString*)msg { NSLog(@"%@ INFO: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logMessage: (NSString*)msg { NSLog(@"%@ LOG: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeDoubleQuotes:msg]]; + NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } -- (NSString*)escapeDoubleQuotes: (NSString*)str +- (NSString*)escapeJavascriptString: (NSString*)str { - NSString *result =[str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; + NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; + result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; return result; } From c9a77ef95235c95e1ecb8079887c385f39e3ea6d Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Mon, 1 Jun 2020 09:18:14 +0100 Subject: [PATCH 20/24] Bump androidx plugin version dependencies. Resolves #418. --- plugin.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin.xml b/plugin.xml index 79ebd8fa9..b5a47ec34 100644 --- a/plugin.xml +++ b/plugin.xml @@ -6,8 +6,8 @@ MIT - - + + From 83b0e5b357294bf4f4829c199683f70cd8a359df Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Mon, 1 Jun 2020 09:49:42 +0100 Subject: [PATCH 21/24] Patch version: 9.1.2-cli --- CHANGELOG.md | 13 +++++++++++++ package.json | 2 +- plugin.xml | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1b916975..034a5491f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,16 @@ +# Version 9.1.2-cli +* (Android) Fix retrieval of auth provider ID - [see here for more info](https://github.com/firebase/FirebaseUI-Android/issues/329#issuecomment-564409912) +* (iOS) Align retrieval of auth provider ID with Android. +* (Typing): correct return type of a method + * Merged from PR [#390](https://github.com/dpa99c/cordova-plugin-firebasex/pull/390). +* (Documentation) Update guidance and requirements when opening issues +* (iOS): Fix escaping of line endings in multi-line log messages being sent from native iOS implementation to JS console. + * Resolves [#401](https://github.com/dpa99c/cordova-plugin-firebasex/issues/401). +* (iOS): Set shouldEstablishDirectChannel via a plugin variable which defaults to false. + Resolves [#406](https://github.com/dpa99c/cordova-plugin-firebasex/issues/406). +* Bump androidx plugin version dependencies. + Resolves [#418](https://github.com/dpa99c/cordova-plugin-firebasex/issues/418). + # Version 9.1.1-cli * (iOS): Bump Firebase SDK components to v6.23.0. * Relates to [#373](https://github.com/dpa99c/cordova-plugin-firebasex/issues/373). diff --git a/package.json b/package.json index 18730f295..3a6b391df 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cordova-plugin-firebasex", - "version": "9.1.1-cli", + "version": "9.1.2-cli", "description": "Cordova plugin for Google Firebase", "types": "./types/index.d.ts", "author": { diff --git a/plugin.xml b/plugin.xml index b5a47ec34..ebb5f6aa8 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,5 +1,5 @@ - Google Firebase Plugin From ed71a97daed924480612757fe1150813d35a346d Mon Sep 17 00:00:00 2001 From: Dave Alden Date: Sun, 7 Jun 2020 07:55:05 +0100 Subject: [PATCH 22/24] (iOS) Handle case where LD_RUNPATH_SEARCH_PATHS is an array. Resolves #344. Also bump xcode dependency to latest v3.0.1 --- package.json | 2 +- scripts/ios/helper.js | 33 ++++++++++++++++++++------------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 3a6b391df..37e0f1e16 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ }, "dependencies": { "plist": "^3.0.1", - "xcode": "^2.0.0", + "xcode": "^3.0.1", "xml-js": "^1.6.11" } } diff --git a/scripts/ios/helper.js b/scripts/ios/helper.js index e4507cdf6..0c367f415 100755 --- a/scripts/ios/helper.js +++ b/scripts/ios/helper.js @@ -139,20 +139,27 @@ module.exports = { ensureRunpathSearchPath: function(context, xcodeProjectPath){ function addRunpathSearchBuildProperty(proj, build) { - const LD_RUNPATH_SEARCH_PATHS = proj.getBuildProperty("LD_RUNPATH_SEARCH_PATHS", build); - if (!LD_RUNPATH_SEARCH_PATHS) { - proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build); - } - if (LD_RUNPATH_SEARCH_PATHS.indexOf("@executable_path/Frameworks") == -1) { - var newValue = LD_RUNPATH_SEARCH_PATHS.substr(0, LD_RUNPATH_SEARCH_PATHS.length - 1); - newValue += ' @executable_path/Frameworks\"'; - proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); - } - if (LD_RUNPATH_SEARCH_PATHS.indexOf("$(inherited)") == -1) { - var newValue = LD_RUNPATH_SEARCH_PATHS.substr(0, LD_RUNPATH_SEARCH_PATHS.length - 1); - newValue += ' $(inherited)\"'; - proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); + let LD_RUNPATH_SEARCH_PATHS = proj.getBuildProperty("LD_RUNPATH_SEARCH_PATHS", build); + + if (!Array.isArray(LD_RUNPATH_SEARCH_PATHS)) { + LD_RUNPATH_SEARCH_PATHS = [LD_RUNPATH_SEARCH_PATHS]; } + + LD_RUNPATH_SEARCH_PATHS.forEach(LD_RUNPATH_SEARCH_PATH => { + if (!LD_RUNPATH_SEARCH_PATH) { + proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build); + } + if (LD_RUNPATH_SEARCH_PATH.indexOf("@executable_path/Frameworks") == -1) { + var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); + newValue += ' @executable_path/Frameworks\"'; + proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); + } + if (LD_RUNPATH_SEARCH_PATH.indexOf("$(inherited)") == -1) { + var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); + newValue += ' $(inherited)\"'; + proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); + } + }); } // Read and parse the XCode project (.pxbproj) from disk. From 0dfb5753edcd9fc19a0e7a52fdd4fc79d6d976ea Mon Sep 17 00:00:00 2001 From: vivek Date: Tue, 16 Jun 2020 16:08:48 +0530 Subject: [PATCH 23/24] Upgraded to the Firebase Crahlytics SDK for both Android & IOS --- README.md | 2936 +---------------- plugin.xml | 146 +- scripts/ios/helper.js | 239 +- src/android/FirebasePlugin.java | 2533 +------------- .../FirebasePluginMessagingService.java | 349 +- src/android/build.gradle | 47 +- src/ios/AppDelegate+FirebasePlugin.h | 12 +- src/ios/AppDelegate+FirebasePlugin.m | 568 +--- src/ios/FirebasePlugin.m | 1783 +--------- 9 files changed, 9 insertions(+), 8604 deletions(-) mode change 100755 => 100644 scripts/ios/helper.js mode change 100755 => 100644 src/android/FirebasePlugin.java mode change 100755 => 100644 src/android/FirebasePluginMessagingService.java mode change 100755 => 100644 src/android/build.gradle mode change 100755 => 100644 src/ios/AppDelegate+FirebasePlugin.h diff --git a/README.md b/README.md index 74a23bcf7..920b9b715 100644 --- a/README.md +++ b/README.md @@ -1,2935 +1 @@ -cordova-plugin-firebasex [![Latest Stable Version](https://img.shields.io/npm/v/cordova-plugin-firebasex.svg)](https://www.npmjs.com/package/cordova-plugin-firebasex) [![Total Downloads](https://img.shields.io/npm/dt/cordova-plugin-firebasex.svg)](https://npm-stat.com/charts.html?package=cordova-plugin-firebasex) -======================== - -Brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project. - -Supported platforms: Android and iOS - -**IMPORTANT:** Before opening an issue against this plugin, please read [Reporting issues](#reporting-issues). - -# cli_build branch -This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. -It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). - -To use it, install an npm release with the `-cli` suffix, e.g.: - - cordova plugin add cordova-plugin-firebasex@9.0.1-cli - -Or install it directly from this branch: - - cordova plugin add https://github.com/dpa99c/cordova-plugin-firebasex#cli_build - -If you wish to use either of these components, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a major plugin release via the NPM registry and build using Xcode. - - -[![donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZRD3W47HQ3EMJ) - -I dedicate a considerable amount of my free time to developing and maintaining this Cordova plugin, along with my other Open Source software. -To help ensure this plugin is kept updated, new features are added and bugfixes are implemented quickly, please donate a couple of dollars (or a little more if you can stretch) as this will help me to afford to dedicate time to its maintenance. Please consider donating if you're using this plugin in an app that makes you money, if you're being paid to make the app, if you're asking for new features or priority bug fixes. - - - - - -**Table of Contents** - -- [Installation](#installation) - - [Plugin variables](#plugin-variables) - - [Android & iOS](#android--ios) - - [Android only](#android-only) - - [iOS only](#ios-only) - - [Supported Cordova Versions](#supported-cordova-versions) - - [Supported Mobile Platform Versions](#supported-mobile-platform-versions) - - [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) - - [Breaking API changes](#breaking-api-changes) - - [Ionic 4+](#ionic-4) - - [Ionic 3](#ionic-3) -- [Build environment notes](#build-environment-notes) - - [PhoneGap Build](#phonegap-build) - - [Android-specific](#android-specific) - - [Specifying Android library versions](#specifying-android-library-versions) - - [AndroidX](#androidx) - - [Google Play Services and Firebase libraries](#google-play-services-and-firebase-libraries) - - [iOS-specific](#ios-specific) - - [Specifying iOS library versions](#specifying-ios-library-versions) - - [Cocoapods](#cocoapods) - - [Out-of-date pods](#out-of-date-pods) - - [Strip debug symbols](#strip-debug-symbols) - - [Cordova CLI builds](#cordova-cli-builds) -- [Firebase config setup](#firebase-config-setup) -- [Disable data collection on startup](#disable-data-collection-on-startup) -- [Example project](#example-project) -- [Reporting issues](#reporting-issues) - - [Reporting a bug or problem](#reporting-a-bug-or-problem) - - [Requesting a new feature](#requesting-a-new-feature) -- [Cloud messaging](#cloud-messaging) - - [Background notifications](#background-notifications) - - [Foreground notifications](#foreground-notifications) - - [Android notifications](#android-notifications) - - [Android background notifications](#android-background-notifications) - - [Android foreground notifications](#android-foreground-notifications) - - [Android Notification Channels](#android-notification-channels) - - [Android 7 and below](#android-7-and-below) - - [Android Notification Icons](#android-notification-icons) - - [Android Default Notification Icon](#android-default-notification-icon) - - [Android Large Notification Icon](#android-large-notification-icon) - - [Android Custom Notification Icons](#android-custom-notification-icons) - - [Android Notification Color](#android-notification-color) - - [Android Notification Sound](#android-notification-sound) - - [Android 8.0 and above](#android-80-and-above) - - [On Android 7 and below](#on-android-7-and-below) - - [iOS notifications](#ios-notifications) - - [iOS background notifications](#ios-background-notifications) - - [iOS notification sound](#ios-notification-sound) - - [iOS badge number](#ios-badge-number) - - [Data messages](#data-messages) - - [Data message notifications](#data-message-notifications) - - [Android data message notifications](#android-data-message-notifications) - - [iOS data message notifications](#ios-data-message-notifications) - - [Custom FCM message handling](#custom-fcm-message-handling) - - [Android](#android) - - [iOS](#ios) - - [Example](#example) -- [InApp Messaging](#inapp-messaging) -- [Google Tag Manager](#google-tag-manager) - - [Android](#android-1) - - [iOS](#ios-1) -- [API](#api) - - [Notifications and data messages](#notifications-and-data-messages) - - [getToken](#gettoken) - - [getId](#getid) - - [onTokenRefresh](#ontokenrefresh) - - [getAPNSToken](#getapnstoken) - - [onApnsTokenReceived](#onapnstokenreceived) - - [onMessageReceived](#onmessagereceived) - - [grantPermission](#grantpermission) - - [hasPermission](#haspermission) - - [unregister](#unregister) - - [isAutoInitEnabled](#isautoinitenabled) - - [setAutoInitEnabled](#setautoinitenabled) - - [setBadgeNumber](#setbadgenumber) - - [getBadgeNumber](#getbadgenumber) - - [clearAllNotifications](#clearallnotifications) - - [subscribe](#subscribe) - - [unsubscribe](#unsubscribe) - - [createChannel](#createchannel) - - [setDefaultChannel](#setdefaultchannel) - - [Default Android Channel Properties](#default-android-channel-properties) - - [deleteChannel](#deletechannel) - - [listChannels](#listchannels) - - [Analytics](#analytics) - - [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled) - - [isAnalyticsCollectionEnabled](#isanalyticscollectionenabled) - - [logEvent](#logevent) - - [setScreenName](#setscreenname) - - [setUserId](#setuserid) - - [setUserProperty](#setuserproperty) - - [Crashlytics](#crashlytics) - - [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled) - - [isCrashlyticsCollectionEnabled](#iscrashlyticscollectionenabled) - - [isCrashlyticsCollectionCurrentlyEnabled](#iscrashlyticscollectioncurrentlyenabled) - - [setCrashlyticsUserId](#setcrashlyticsuserid) - - [sendCrash](#sendcrash) - - [logMessage](#logmessage) - - [logError](#logerror) - - [Authentication](#authentication) - - [isUserSignedIn](#isusersignedin) - - [signOutUser](#signoutuser) - - [getCurrentUser](#getcurrentuser) - - [reloadCurrentUser](#reloadcurrentuser) - - [updateUserProfile](#updateuserprofile) - - [updateUserEmail](#updateuseremail) - - [sendUserEmailVerification](#senduseremailverification) - - [updateUserPassword](#updateuserpassword) - - [sendUserPasswordResetEmail](#senduserpasswordresetemail) - - [deleteUser](#deleteuser) - - [createUserWithEmailAndPassword](#createuserwithemailandpassword) - - [signInUserWithEmailAndPassword](#signinuserwithemailandpassword) - - [signInUserWithCustomToken](#signinuserwithcustomtoken) - - [signInUserAnonymously](#signinuseranonymously) - - [verifyPhoneNumber](#verifyphonenumber) - - [Android](#android-2) - - [iOS](#ios-2) - - [authenticateUserWithGoogle](#authenticateuserwithgoogle) - - [Android](#android-3) - - [authenticateUserWithApple](#authenticateuserwithapple) - - [iOS](#ios-3) - - [Android](#android-4) - - [signInWithCredential](#signinwithcredential) - - [linkUserWithCredential](#linkuserwithcredential) - - [reauthenticateWithCredential](#reauthenticatewithcredential) - - [registerAuthStateChangeListener](#registerauthstatechangelistener) - - [Remote Config](#remote-config) - - [fetch](#fetch) - - [activateFetched](#activatefetched) - - [getValue](#getvalue) - - [getByteArray](#getbytearray) - - [getInfo](#getinfo) - - [setConfigSettings](#setconfigsettings) - - [setDefaults](#setdefaults) - - [Performance](#performance) - - [setPerformanceCollectionEnabled](#setperformancecollectionenabled) - - [isPerformanceCollectionEnabled](#isperformancecollectionenabled) - - [startTrace](#starttrace) - - [incrementCounter](#incrementcounter) - - [stopTrace](#stoptrace) - - [Firestore](#firestore) - - [addDocumentToFirestoreCollection](#adddocumenttofirestorecollection) - - [setDocumentInFirestoreCollection](#setdocumentinfirestorecollection) - - [updateDocumentInFirestoreCollection](#updatedocumentinfirestorecollection) - - [deleteDocumentFromFirestoreCollection](#deletedocumentfromfirestorecollection) - - [documentExistsInFirestoreCollection](#documentexistsinfirestorecollection) - - [fetchDocumentInFirestoreCollection](#fetchdocumentinfirestorecollection) - - [fetchFirestoreCollection](#fetchfirestorecollection) -- [Credits](#credits) - - - -# Installation -Install the plugin by adding it to your project's config.xml: -```xml - -``` -or by running: -``` -cordova plugin add cordova-plugin-firebasex -``` - -## Plugin variables -The following Cordova plugin variables are supported by the plugin. -Note that these must be set at plugin installation time. If you wish to change plugin variables, you'll need to uninstall the plugin and reinstall it with the new variable values. - -### Android & iOS -- `FIREBASE_ANALYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Analytics data collection on app startup -- `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` - whether to automatically enable Firebase Performance data collection on app startup -- `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Crashlytics data collection on app startup -See [Disable data collection on startup](#disable-data-collection-on-startup) for more info. - -### Android only -The following plugin variables are used to specify the Firebase SDK versions as Gradle dependencies on Android: -- `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` -- `ANDROID_PLAY_SERVICES_AUTH_VERSION` -- `ANDROID_FIREBASE_ANALYTICS_VERSION` -- `ANDROID_FIREBASE_MESSAGING_VERSION` -- `ANDROID_FIREBASE_CONFIG_VERSION` -- `ANDROID_FIREBASE_PERF_VERSION` -- `ANDROID_FIREBASE_AUTH_VERSION` -- `ANDROID_FIREBASE_FIRESTORE_VERSION` -- `ANDROID_CRASHLYTICS_VERSION` -- `ANDROID_CRASHLYTICS_NDK_VERSION` -- `ANDROID_GSON_VERSION` -See [Specifying Android library versions](#specifying-android-library-versions) for more info. - -- `ANDROID_ICON_ACCENT` - sets the default accent color for system notifications. See [Android Notification Color](#android-notification-color) for more info. - -### iOS only -- `IOS_STRIP_DEBUG` - prevents symbolification of all libraries included via Cocoapods. See [Strip debug symbols](#strip-debug-symbols) for more info. - - e.g. `--variable IOS_STRIP_DEBUG=true` - - Defaults to `false` if not specified. -- `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info. - - e.g. `--variable IOS_STRIP_DEBUG=true` - - Defaults to `false` if not specified. -- `IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL` - If `true` Firebase Messaging will automatically establish a socket-based, direct channel to the FCM server. - - e.g. `--variable IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL=true` - - Defaults to `false` if not specified. - - See [`shouldEstablishDirectChannel`](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/c:objc(cs)FIRMessaging(py)shouldEstablishDirectChannel) - - Note: Firebase Messaging iOS SDK version 7.0 will be a breaking change where the SDK will no longer support iOS Direct Channel API. - -## Supported Cordova Versions -- cordova: `>= 9` -- cordova-android: `>= 8` -- cordova-ios: `>= 5` - -## Supported Mobile Platform Versions -- Android `>= 4.1` -- iOS `>= 10.0` - -## Migrating from cordova-plugin-firebase -This plugin is a fork of [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) which has been reworked to fix issues and add new functionality. -If you already have [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) installed in your Cordova project, you need to completely remove it before installing this plugin otherwise they will conflict and cause build errors in your project. The safest way of doing this is as follows: - - rm -Rf platforms/android - cordova plugin rm cordova-plugin-firebase - rm -Rf plugins/ node_modules/ - npm install - cordova plugin add cordova-plugin-firebasex - cordova platform add android - -### Breaking API changes -**IMPORTANT:** Recent versions of `cordova-plugin-firebasex` have made breaking changes to the plugin API in order to fix bugs or add more functionality. -Therefore you can no longer directly substitute `cordova-plugin-firebasex` in place of `cordova-plugin-firebase` without making code changes. - -You should be aware of the following breaking changes compared with `cordova-plugin-firebase`: -* Minimum supported Cordova versions - * `cordova@9` (CLI) - * `cordova-android@8` (Android platform) - * `cordova-ios@5` (iOS platform) -* Migrated to AndroidX from legacy Android Support Library - * add dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) and [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) -* Migrated to Cocoapods to satisfy Firebase SDK dependencies on iOS -* `onNotificationOpen()` renamed to `onMessageReceived()` - * `tap` parameter is only set when user taps on a notification (not when a message is received from FCM) - * `tap=foreground|background` instead of `tap=true|false` -* `hasPermission()` receives argument as a boolean (rather than an object with `isEnabled` key) - * e.g. `FirebasePlugin.hasPermission(function(hasPermission){ - console.log("Permission is " + (hasPermission ? "granted" : "denied")); - });` -* Adds support for foreground notifications and data notification messages - -### Ionic 4+ -Ionic Native provides a [FirebaseX Typescript wrapper](https://ionicframework.com/docs/native/firebase-x) for using `cordova-plugin-firebasex` with Ionic v4, v5 and above. -Please see their documentation for usage. - -First install the package. - -``` -ionic cordova plugin add cordova-plugin-firebasex -npm install @ionic-native/firebase-x -``` - -If you're using Angular, register it in your component/service's `NgModule` (for example, app.module.ts) as a provider. - -```typescript -import { FirebaseX } from "@ionic-native/firebase-x/ngx"; - -@NgModule({ - //declarations, imports... - providers: [ - FirebaseX, - //other providers... - ] -}) -``` - -Then you're good to go. -```typescript -import { FirebaseX } from "@ionic-native/firebase-x/ngx"; - -//... - -constructor(private firebase: FirebaseX) - -this.firebase.getToken().then(token => console.log(`The token is ${token}`)) -this.firebase.onMessageReceived().subscribe(data => console.log(`FCM message: ${data}`)); -``` - -**NOTE:** -- This plugin provides only the Javascript API as documented below. -- The Typescript wrapper is owned and maintain by Ionic. -- Please [report any issues](https://github.com/ionic-team/ionic-native/issues) against the [Ionic Native repo](https://github.com/ionic-team/ionic-native/), not this one. -- Any issues opened against this repo which relate to the Typescript wrapper **will be closed immediately**. - - -### Ionic 3 -The above PR does not work for Ionic 3 so you (currently) can't use the [Ionic Native Firebase](https://ionicframework.com/docs/native/firebase) Typescript wrapper with Ionic 3. -(i.e. `import { Firebase } from "@ionic-native/firebase"` will not work). - -To use `cordova-plugin-firebasex` with Ionic 3, you'll need to call its Javascript API directly from your Typescript app code, for example: - -```typescript -(window).FirebasePlugin.getToken(token => console.log(`token: ${token}`)) - -(window).FirebasePlugin.onMessageReceived((message) => { - if (message.tap) { console.log(`Notification was tapped in the ${message.tap}`); } -}) -``` - -If you want to make the `onMessageReceived()` JS API behave like the Ionic Native wrapper: - -```javascript -onNotificationOpen() { - return new Observable(observer => { - (window as any).FirebasePlugin.onMessageReceived((response) => { - observer.next(response); - }); - }); -} -... -this.onNotificationOpen().subscribe(data => console.log(`FCM message: ${data}`)); -``` - -See the [cordova-plugin-firebasex-ionic3-test](https://github.com/dpa99c/cordova-plugin-firebasex-ionic3-test) example project for a demonstration of how to use the plugin with Ionic 3. - -# Build environment notes - -## PhoneGap Build -This plugin will not work with Phonegap Build (and other remote cloud build envs) do not support Cordova hook scripts as they are used by this plugin to configure the native platform projects. - -## Android-specific - -### Specifying Android library versions -This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Gradle on Android. -By default this plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned versions as ``'s, for example: - -```xml - -``` - -The Android defaults can be overridden at plugin installation time by specifying plugin variables as command-line arguments, for example: - - cordova plugin add cordova-plugin-firebasex --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 - -Or you can specify them as plugin variables in your `config.xml`, for example: - -```xml - - - -``` - -The following plugin variables are used to specify the following Gradle dependency versions on Android: - -- `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` => `com.google.android.gms:play-services-tagmanager` -- `ANDROID_PLAY_SERVICES_AUTH_VERSION` => `com.google.android.gms:play-services-auth` -- `ANDROID_FIREBASE_ANALYTICS_VERSION` => `com.google.firebase:firebase-analytics` -- `ANDROID_FIREBASE_MESSAGING_VERSION` => `com.google.firebase:firebase-messaging` -- `ANDROID_FIREBASE_CONFIG_VERSION` => `com.google.firebase:firebase-config` -- `ANDROID_FIREBASE_PERF_VERSION` => `com.google.firebase:firebase-perf` -- `ANDROID_FIREBASE_AUTH_VERSION` => `com.google.firebase:firebase-auth` -- `ANDROID_FIREBASE_FIRESTORE_VERSION` => `com.google.firebase:firebase-firestore` -- `ANDROID_CRASHLYTICS_VERSION` => `com.crashlytics.sdk.android:crashlytics` -- `ANDROID_CRASHLYTICS_NDK_VERSION` => `com.crashlytics.sdk.android:crashlytics-ndk` -- `ANDROID_GSON_VERSION` => `com.google.code.gson:gson` - -For example: - - cordova plugin add cordova-plugin-firebasex \ - --variable ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION=17.0.0 \ - --variable ANDROID_PLAY_SERVICES_AUTH_VERSION=17.0.0 \ - --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 \ - --variable ANDROID_FIREBASE_MESSAGING_VERSION=19.0.0 \ - --variable ANDROID_FIREBASE_CONFIG_VERSION=18.0.0 \ - --variable ANDROID_FIREBASE_PERF_VERSION=18.0.0 \ - --variable ANDROID_FIREBASE_AUTH_VERSION=18.0.0 \ - --variable ANDROID_CRASHLYTICS_VERSION=2.10.1 \ - --variable ANDROID_CRASHLYTICS_NDK_VERSION=2.1.0 \ - -### AndroidX -This plugin has been migrated to use [AndroidX (Jetpack)](https://developer.android.com/jetpack/androidx/migrate) which is the successor to the [Android Support Library](https://developer.android.com/topic/libraries/support-library/index). -This is implemented by adding a dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) which enables AndroidX in the Android platform of a Cordova project. - -This is because the [major release of the Firebase and Play Services libraries on 17 June 2019](https://developers.google.com/android/guides/releases#june_17_2019) were migrated to AndroidX. - -Therefore if your project includes any plugins which are dependent on the legacy Android Support Library, you should add [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) to your project. -This plugin will dynamically migrate any plugin code from the Android Support Library to AndroidX equivalents. - -## Google Play Services and Firebase libraries -Your Android build may fail if you are installing multiple plugins that use the Google Play Services library. -This is caused by plugins installing different versions of the Google Play Services library. -This can be resolved by installing [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) which enables you to override the versions specified by other plugins in order to align them. - -Similarly, if your build is failing because multiple plugins are installing different versions of the Firebase library, -you can try installing [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release) to align these. - -## iOS-specific -### Specifying iOS library versions -This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Cocoapods on iOS. -This plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned iOS versions in the ``'s, for example: - - - -**It is currently not possible to override these at plugin installation time** because `cordova@9`/`cordova-ios@5` does not support the use of plugin variables in the ``'s `spec` attribute. -Therefore if you need to change the specified versions, you'll currently need to do this by forking the plugin and editing the `plugin.xml` to change the specified `spec` values. - -### Cocoapods -This plugin relies on `cordova@9`/`cordova-ios@5` support for the [CocoaPods dependency manager]( https://cocoapods.org/) in order to satisfy the iOS Firebase SDK library dependencies. - -Therefore please make sure you have Cocoapods@>=1.8 installed in your iOS build environment - setup instructions can be found [here](https://cocoapods.org/). - -If building your project in Xcode, you need to open `YourProject.xcworkspace` (not `YourProject.xcodeproj`) so both your Cordova app project and the Pods project will be loaded into Xcode. - -You can list the pod dependencies in your Cordova iOS project by installing [cocoapods-dependencies](https://github.com/segiddins/cocoapods-dependencies): - - sudo gem install cocoapods-dependencies - cd platforms/ios/ - pod dependencies - -### Out-of-date pods -If you receive a build error such as this: - - None of your spec sources contain a spec satisfying the dependencies: `Firebase/Analytics (~> 6.1.0), Firebase/Analytics (= 6.1.0, ~> 6.1.0)`. - -Make sure your local Cocoapods repo is up-to-date by running `pod repo update` then run `pod install` in `/your_project/platforms/ios/`. - -### Strip debug symbols -If your iOS app build contains too many debug symbols (i.e. because you include lots of libraries via a Cocoapods), you might get an error (e.g. [issue #28](https://github.com/dpa99c/cordova-plugin-firebase/issues/28)) when you upload your binary to App Store Connect, e.g.: - - ITMS-90381: Too many symbol files - These symbols have no corresponding slice in any binary [16EBC8AC-DAA9-39CF-89EA-6A58EB5A5A2F.symbols, 1B105D69-2039-36A4-A04D-96C1C5BAF235.symbols, 476EACDF-583B-3B29-95B9-253CB41097C8.symbols, 9789B03B-6774-3BC9-A8F0-B9D44B08DCCB.symbols, 983BAE60-D245-3291-9F9C-D25E610846AC.symbols]. - -To prevent this, you can set the `IOS_STRIP_DEBUG` plugin variable which prevents symbolification of all libraries included via Cocoapods ([see here for more information](https://stackoverflow.com/a/48518656/777265)): - - cordova plugin add cordova-plugin-firebasex --variable IOS_STRIP_DEBUG=true - -By default this preference is set to `false`. - -Note: if you enable this setting, any crashes that occur within libraries included via Cocopods will not be recorded in Crashlytics or other crash reporting services. - -### Cordova CLI builds -If you are building (directly or indirectly) via the Cordova CLI and encounter build failures on iOS, this is likely due to [an issue with Cordova CLI builds for iOS](https://github.com/apache/cordova-ios/issues/659) when including certain pods into the build (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). - -Note that building from Xcode works fine, so if you are able then do this. - -Otherwise (e.g. if building via a CI) then you'll need to switch to using the [cli_build branch](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) of this plugin which removes the Firebase Inapp Messaging and Google Tag Manager SDK components that are causing the build issues. - -# Firebase config setup -There's a handy [installation and setup guide on medium.com](https://medium.com/@felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821). -However, if using this, remember this forked plugin is `cordova-plugin-firebasex` (not `cordova-plugin-firebase`). - -Download your Firebase configuration files, `GoogleService-Info.plist` for iOS and `google-services.json` for android, and place them in the root folder of your cordova project. -Check out this [firebase article](https://support.google.com/firebase/answer/7015592) for details on how to download the files. - -``` -- My Project/ - platforms/ - plugins/ - www/ - config.xml - google-services.json <-- - GoogleService-Info.plist <-- - ... -``` -IMPORTANT: The Firebase SDK requires the configuration files to be present and valid, otherwise your app will crash on boot or Firebase features won't work. - -# Disable data collection on startup -By default, analytics, performance and Crashlytics data will begin being collected as soon as the app starts up. -However, for data protection or privacy reasons, you may wish to disable data collection until such time as the user has granted their permission. - -To do this, set the following plugin variables to `false` at plugin install time: - -* `FIREBASE_ANALYTICS_COLLECTION_ENABLED` -* `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` -* `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` - - - cordova plugin add cordova-plugin-firebasex \ - --variable FIREBASE_ANALYTICS_COLLECTION_ENABLED=false \ - --variable FIREBASE_PERFORMANCE_COLLECTION_ENABLED=false \ - --variable FIREBASE_CRASHLYTICS_COLLECTION_ENABLED=false - -This will disable data collection (on both Android & iOS) until you call [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled), [setPerformanceCollectionEnabled](#setperformancecollectionenabled) and [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled): - - FirebasePlugin.setAnalyticsCollectionEnabled(true); - FirebasePlugin.setPerformanceCollectionEnabled(true); - FirebasePlugin.setCrashlyticsCollectionEnabled(true); - -Notes: -- Calling `setXCollectionEnabled()` will have no effect if the corresponding `FIREBASE_X_COLLECTION_ENABLED` variable is set to `true`. -- Calling `setAnalyticsCollectionEnabled(true|false)` or `setPerformanceCollectionEnabled(true|false)` will enable/disable data collection during the current app session and across subsequent app sessions until such time as the same method is called again with a different value. -- Calling `setCrashlyticsCollectionEnabled(true|false)` will enable/disable data collection during subsequent app sessions until such time as the same method is called again with a different value. It **does not** affect the current app session. - -# Example project -An example project repo exists to demonstrate and validate the functionality of this plugin: -https://github.com/dpa99c/cordova-plugin-firebasex-test - -Please use this as a working reference. - -Before reporting any issues, please (if possible) test against the example project to rule out causes external to this plugin. - -# Reporting issues -**IMPORTANT:** Please read the following carefully. -Failure to follow the issue template guidelines below will result in the issue being immediately closed. - -## Reporting a bug or problem -Before [opening a bug issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=bug_report.md&title=), please do the following: -- *DO NOT* open issues asking for support in using/integrating the plugin into your project - - Only open issues for suspected bugs/issues with the plugin that are generic and will affect other users - - I don't have time to offer free technical support: this is free open-source software - - Ask for help on StackOverflow, Ionic Forums, etc. - - Use the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) as a known working reference - - Any issues requesting support will be closed immediately. -- *DO NOT* open issues related to the [Ionic Typescript wrapper for this plugin](https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/firebase-x/index.ts) - - This is owned/maintained by [Ionic](https://github.com/ionic-team) and is not part of this plugin - - Please raise such issues/PRs against [Ionic Native](https://github.com/ionic-team/ionic-native/) instead. - - To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper). - - Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately. -- If you are migrating from [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section. -- Read the above documentation thoroughly - - For example, if you're having a build issue ensure you've read through the [build environment notes](#build-environment-notes) - - If an iOS CLI build is failing, ensure you've read the [Cordova CLI builds](#cordova-cli-builds) section -- Check the [CHANGELOG](https://github.com/dpa99c/cordova-plugin-firebasex/blob/master/CHANGELOG.md) for any breaking changes that may be causing your issue. -- Check a similar issue (open or closed) does not already exist against this plugin. - - Duplicates or near-duplicates will be closed immediately. -- When [creating a new issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new/choose) - - Choose the "Bug report" template - - Fill out the relevant sections of the template and delete irrelevant sections - - *WARNING:* Failure to complete the issue template will result in the issue being closed immediately. -- Reproduce the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) - - This will eliminate bugs in your code or conflicts with other code as possible causes of the issue - - This will also validate your development environment using a known working codebase - - If reproducing the issue using the example project is not possible, create an isolated test project that you are able to share -- Include full verbose console output when reporting build issues - - If the full console output is too large to insert directly into the Github issue, then post it on an external site such as [Pastebin](https://pastebin.com/) and link to it from the issue - - Often the details of an error causing a build failure is hidden away when building with the CLI - - To get the full detailed console output, append the `--verbose` flag to CLI build commands - - e.g. `cordova build ios --verbose` - - Failure to include the full console output will result in the issue being closed immediately -- If the issue relates to the plugin documentation (and not the code), please of a [documentation issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=documentation-issue.md&title=) - -## Requesting a new feature -Before [opening a feature request issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=feature_request.md&title=), please do the following: -- Check the above documentation to ensure the feature you are requesting doesn't already exist -- Check the list if open/closed issues to check if there's a reason that feature hasn't been included already -- Ensure the feature you are requesting is actually possible to implement and generically useful to other users than yourself -- Where possible, post a link to the documentation related to the feature you are requesting -- Include other relevant links, e.g. - - Stack Overflow post illustrating a solution - - Code within another Github repo that illustrates a solution - -# Cloud messaging - -

- -   - -

- -There are 2 distinct types of messages that can be sent by Firebase Cloud Messaging (FCM): - -- [Notification messages](https://firebase.google.com/docs/cloud-messaging/concept-options#notifications) - - automatically displayed to the user by the operating system on behalf of the client app **while your app is not running or is in the background** - - **if your app is in the foreground when the notification message arrives**, it is passed to the client app and it is the responsibility of the client app to display it. - - have a predefined set of user-visible keys and an optional data payload of custom key-value pairs. -- [Data messages](https://firebase.google.com/docs/cloud-messaging/concept-options#data_messages) - - Client app is responsible for processing data messages. - - Data messages have only custom key-value pairs. - -Note: only notification messages can be sent via the Firebase Console - data messages must be sent via the [FCM APIs](https://firebase.google.com/docs/cloud-messaging/server). - -## Background notifications -If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. - -By default, no callback is made to the plugin when the message arrives while the app is not in the foreground, since the display of the notification is entirely handled by the operating system. -However, there are platform-specific circumstances where a callback can be made when the message arrives and the app is in the background that don't require user interaction to receive the message payload - see [Android background notifications](#android-background-notifications) and [iOS background notifications](#ios-background-notifications) for details. - -If the user taps the system notification, this launches/resumes the app and the notification title, body and optional data payload is passed to the [onMessageReceived](#onMessageReceived) callback. - -When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the background/not running, it will be passed the property `tap: "background"`. - - -## Foreground notifications -If the notification message arrives while the app is in running in the foreground, by default **it will NOT be displayed as a system notification**. -Instead the notification message payload will be passed to the [onMessageReceived](#onMessageReceived) callback for the plugin to handle (`tap` will not be set). - -If you include the `notification_foreground` key in the `data` payload, the plugin will also display a system notification upon receiving the notification messages while the app is running in the foreground. -For example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "data": { - "notification_foreground": "true", - } -} -``` - -When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the foreground, it will be passed the property `tap: "foreground"`. - -You can set additional properties of the foreground notification using the same key names as for [Data Message Notifications](#data-message-notification-keys). - -## Android notifications -Notifications on Android can be customised to specify the sound, icon, LED colour, etc. that's displayed when the notification arrives. - -### Android background notifications -If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. - -If a notification message arrives while the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. - -If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. - -In addition to the title and body of the notification message, Android system notifications support specification of the following notification settings: -- [Icon](#android-notification-icons) -- [Sound](#android-notification-sound) -- [Color accent](#android-notification-color) -- [Channel ID](#android-notification-channels) (Android 8.0 (O) and above) - - This channel configuration enables you to specify: - - Sound - - Vibration - - LED light - - Badge - - Importance - - Visibility - - See [createChannel](#createchannel) for details. - -Note: on tapping a background notification, if your app is not running, only the `data` section of the notification message payload will be delivered to [onMessageReceived](#onMessageReceived). -i.e. the notification title, body, etc. will not. Therefore if you need the properties of the notification message itself (e.g. title & body) to be delivered to [onMessageReceived](#onMessageReceived), you must duplicate these in the `data` section, e.g.: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "data": { - "notification_body": "Notification body", - "notification_title": "Notification title" - } -} -``` - -### Android foreground notifications -If the notification message arrives while the app is in the foreground, by default a system notification won't be displayed and the data will be passed to [onMessageReceived](#onMessageReceived). - -However, if you set the `notification_foreground` key in the `data` section of the notification message payload, this will cause the plugin to display system notification when the message is received while your app is in the foreground. You can customise the notification using the same keys as for [Android data message notifications](#android-data-message-notifications). - -### Android Notification Channels -- Android 8 (O) introduced [notification channels](https://developer.android.com/training/notify-user/channels). -- Notification channels are configured by the app and used to determine the **sound/lights/vibration** settings of system notifications. -- By default, this plugin creates a default channel with [default properties](#default-android-channel-properties) - - These can be overridden via the [setDefaultChannel](#setdefaultchannel) function. -- The plugin enables the creation of additional custom channels via the [createChannel](#createchannel) function. - -First you need to create a custom channel with the desired settings, for example: - -```javascript -var channel = { - id: "my_channel_id", - sound: "mysound", - vibration: true, - light: true, - lightColor: parseInt("FF0000FF", 16).toString(), - importance: 4, - badge: true, - visibility: 1 -}; - -FirebasePlugin.createChannel(channel, -function(){ - console.log('Channel created: ' + channel.id); -}, -function(error){ - console.log('Create channel error: ' + error); -}); -``` - -Then reference it from your message payload: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "android": { - "notification": { - "channel_id": "my_channel_id" - } - } -} -``` - -#### Android 7 and below -- the channel referenced in the message payload will be ignored -- the sound setting of system notifications is specified in the notification message itself - see [Android Notification Sound](#android-notification-sound). - - -### Android Notification Icons -By default the plugin will use the default app icon for notification messages. - -#### Android Default Notification Icon -To define a custom default notification icon, you need to create the images and deploy them to the `/platforms/android/app/src/main/res/` folders. -The easiest way to create the images is using the [Image Asset Studio in Android Studio](https://developer.android.com/studio/write/image-asset-studio#create-notification) or using the [Android Asset Studio webapp](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=notification_icon). - -The icons should be monochrome transparent PNGs with the following sizes: - -- mdpi: 24x24 -- hdpi: 36x36 -- xhdpi: 48x48 -- xxhdpi: 72x72 -- xxxhdpi: 96x96 - -Once you've created the images, you need to deploy them from your Cordova project to the native Android project. -To do this, copy the `drawable-DPI` image directories into your Cordova project and add `` entries to the `` section of your `config.xml`, where `src` specifies the relative path to the images files within your Cordova project directory. - -For example, copy the`drawable-DPI` image directories to `/res/android/` and add the following to your `config.xml`: - -```xml - - - - - - - -``` - -The default notification icon images **must** be named `notification_icon.png`. - -You then need to add a `` block to the `config.xml` which will instruct Firebase to use your icon as the default for notifications: - -```xml - - - - - -``` - - -#### Android Large Notification Icon -The default notification icons above are monochrome, however you can additionally define a larger multi-coloured icon. - -**NOTE:** FCM currently does not support large icons in system notifications displayed for notification messages received in the while the app is in the background (or not running). -So the large icon will currently only be used if specified in [data messages](#android-data-messages) or [foreground notifications](#foreground-notifications). - -The large icon image should be a PNG-24 that's 256x256 pixels and must be named `notification_icon_large.png` and should be placed in the `drawable-xxxhdpi` resource directory. -As with the small icons, you'll need to add a `` entry to the `` section of your `config.xml`: - -```xml - - - -``` - - -#### Android Custom Notification Icons -You can define additional sets of notification icons in the same manner as above. -These can be specified in notification or data messages. - -For example: - -```xml - - - - - - -``` - -When sending an FCM notification message, you will then specify the icon name in the `android.notification` section, for example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "android": { - "notification": { - "icon": "my_icon", - } - }, - "data": { - "notification_foreground": "true", - } -} -``` - -You can also reference these icons in [data messages](#android-data-messages), for example: - -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_android_icon": "my_icon", - } -} -``` - - -### Android Notification Color -On Android Lollipop (5.0/API 21) and above you can set the default accent color for the notification by adding a color setting. -This is defined as an [ARGB colour](https://en.wikipedia.org/wiki/RGBA_color_space#ARGB_(word-order)) which the plugin sets by default to `#FF00FFFF` (cyan). -Note: On Android 7 and above, the accent color can only be set for the notification displayed in the system tray area - the icon in the statusbar is always white. - -You can override this default by specifying a value using the `ANDROID_ICON_ACCENT` plugin variable during plugin installation, for example: - - cordova plugin add cordova-plugin-firebasex --variable ANDROID_ICON_ACCENT=#FF123456 - -You can override the default color accent by specifying the `colour` key as an RGB value in a notification message, e.g.: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "android": { - "notification": { - "color": "#00ff00" - } - } -} -``` - -And in a data message: - -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_android_color": "#00ff00" - } -} -``` - -### Android Notification Sound -You can specify custom sounds for notifications or play the device default notification sound. - -Custom sound files must be in `.mp3` format and deployed to the `/res/raw` directory in the Android project. -To do this, you can add `` tags to your `config.xml` to deploy the files, for example: - -```xml - - - -``` - -To ensure your custom sounds works on all versions of Android, be sure to include both the channel name and sound name in your message payload (see below for details), for example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "android": { - "notification": { - "channel_id": "my_channel_id", - "sound": "my_sound" - } - } -} -``` - -#### Android 8.0 and above -On Android 8.0 and above, the notification sound is specified by which [Android notification channel](#android-notification-channels) is referenced in the notification message payload. -First create a channel that references your sound, for example: - -```javascript -var channel = { - id: "my_channel_id", - sound: "my_sound" -}; - -FirebasePlugin.createChannel(channel, -function(){ - console.log('Channel created: ' + channel.id); -}, -function(error){ - console.log('Create channel error: ' + error); -}); -``` - -Then reference that channel in your message payload: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "android": { - "notification": { - "channel_id": "my_channel_id" - } - } -} -``` - -#### On Android 7 and below -On Android 7 and below, you need to specify the sound file name in the `android.notification` section of the message payload. -For example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "android": { - "notification": { - "sound": "my_sound" - } - } -} -``` - -And in a data message by specifying it in the `data` section: - -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_android_sound": "my_sound" - } -} -``` - -- To play the default notification sound, set `"sound": "default"`. -- To display a silent notification (no sound), omit the `sound` key from the message. - -## iOS notifications -Notifications on iOS can be customised to specify the sound and badge number that's displayed when the notification arrives. - -Notification settings are specified in the `apns.payload.aps` key of the notification message payload. -For example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "apns": { - "payload": { - "aps": { - "sound": "default", - "badge": 1, - "content-available": 1 - } - } - } -} -``` - -### iOS background notifications -If the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback can be invoked when the message arrives without requiring user interaction (i.e. tapping the system notification). -To do this you must specify `"content-available": 1` in the `apns.payload.aps` section of the message payload - see the [Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW8) for more information. -When the message arrives, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. -If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. - -### iOS notification sound -You can specify custom sounds for notifications or play the device default notification sound. - -Custom sound files must be in a supported audio format (see [this Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW10) for supported formats). -For example to convert an `.mp3` file to the supported `.caf` format run: - - afconvert my_sound.mp3 my_sound.caf -d ima4 -f caff -v - -Sound files must be deployed with the iOS application bundle. -To do this, you can add `` tags to your `config.xml` to deploy the files, for example: - -```xml - - - -``` - -In a notification message, specify the `sound` key in the `apns.payload.aps` section, for example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "apns": { - "payload": { - "aps": { - "sound": "my_sound.caf" - } - } - } -} -``` - -- To play the default notification sound, set `"sound": "default"`. -- To display a silent notification (no sound), omit the `sound` key from the message. - -In a data message, specify the `notification_ios_sound` key in the `data` section: - -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_ios_sound": "my_sound.caf" - } -} -``` - -### iOS badge number -In a notification message, specify the `badge` key in the `apns.payload.aps` section, for example: - -```json -{ - "name": "my_notification", - "notification": { - "body": "Notification body", - "title": "Notification title" - }, - "apns": { - "payload": { - "aps": { - "badge": 1 - } - } - } -} -``` - -In a data message, specify the `notification_ios_badge` key in the `data` section: - -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_ios_badge": 1 - } -} -``` - -## Data messages -FCM data messages are sent as an arbitrary k/v structure and by default are passed to the app for it to handle them. - -**NOTE:** FCM data messages **cannot** be sent from the Firebase Console - they can only be sent via the FCM APIs. - -### Data message notifications -This plugin enables a data message to be displayed as a system notification. -To have the app display a notification when the data message arrives, you need to set the `notification_foreground` key in the `data` section. -You can then set a `notification_title` and `notification_body`, for example: - -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "foo" : "bar" - } -} -``` - -Additional platform-specific notification options can be set using the additional keys below (which are only relevant if the `notification_foreground` key is set). - -Note: [foreground notification messages](#foreground-notifications) can also make use of these keys. - -#### Android data message notifications -On Android: -- Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. -- Data messages (not containing notification keys) that arrive while your app is **not running** will be passed to the `onMessageReceived()` Javascript handler when the app is next launched. -- Data messages containing notification keys that arrive while your app is running or **not running** will be displayed as a system notification. - -The following Android-specific keys are supported and should be placed inside the `data` section: - -- `notification_android_icon` - name of a [custom notification icon](#android-custom-notification-icons) in the drawable resources - - if not specified, the plugin will use the default `notification_icon` if it exists; otherwise the default app icon will be displayed - - if a [large icon](#android-large-notification-icon) has been defined, it will also be displayed in the system notification. -- `notification_android_color` - the [color accent](#android-notification-color) to use for the small notification icon - - if not specified, the default color accent will be used -- `notification_android_channel_id` - ID of the [notification channel](#android-notification-channels) to use to display the notification - - Only applies to Android 8.0 and above - - If not specified, the [default notification channel](#default-android-channel-properties) will be used. - - You can override the default configuration for the default notification channel using [setDefaultChannel](#setdefaultchannel). - - You can create additional channels using [createChannel](#createchannel). -- `notification_android_priority` - Specifies the notification priority - - Possible values: - - `2` - Highest notification priority for your application's most important items that require the user's prompt attention or input. - - `1` - Higher notification priority for more important notifications or alerts. - - `0` - Default notification priority. - - `-1` - Lower notification priority for items that are less important. - - `-2` - Lowest notification priority. These items might not be shown to the user except under special circumstances, such as detailed notification logs. - - Defaults to `2` if not specified. -- `notification_android_visibility` - Specifies the notification visibility - - Possible values: - - `1` - Show this notification in its entirety on all lockscreens. - - `0` - Show this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. - - `-1` - Do not reveal any part of this notification on a secure lockscreen. - - Defaults to `1` if not specified. - -The following keys only apply to Android 7 and below. -On Android 8 and above they will be ignored - the `notification_android_channel_id` property should be used to specify a [notification channel](#android-notification-channels) with equivalent settings. - -- `notification_android_sound` - name of a sound resource to play as the [notification sound](#android-notification-sound) - - if not specified, no sound is played - - `default` plays the default device notification sound - - otherwise should be the name of an `.mp3` file in the `/res/raw` directory, e.g. `my_sound.mp3` => `"sounds": "my_sound"` -- `notification_android_lights` - color and pattern to use to blink the LED light - - if not defined, LED will not blink - - in the format `ARGB, time_on_ms, time_off_ms` where - - `ARGB` is an ARGB color definition e.g. `#ffff0000` - - `time_on_ms` is the time in milliseconds to turn the LED on for - - `time_off_ms` is the time in milliseconds to turn the LED off for - - e.g. `"lights": "#ffff0000, 250, 250"` -- `notification_android_vibrate` - pattern of vibrations to use when the message arrives - - if not specified, device will not vibrate - - an array of numbers specifying the time in milliseconds to vibrate - - e.g. `"vibrate": "500, 200, 500"` - -Example data message with Android notification keys: - -```json -{ - "name": "my_data_message", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_android_channel_id": "my_channel", - "notification_android_priority": "2", - "notification_android_visibility": "1", - "notification_android_color": "#ff0000", - "notification_android_icon": "coffee", - "notification_android_sound": "my_sound", - "notification_android_vibrate": "500, 200, 500", - "notification_android_lights": "#ffff0000, 250, 250" - } -} -``` - -#### iOS data message notifications -On iOS: -- Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. -- Data messages that arrive while your app is **not running** will **NOT be received by your app!** - -The following iOS-specific keys are supported and should be placed inside the `data` section: - -- `notification_ios_sound` - Sound to play when the notification is displayed - - To play a custom sound, set the name of the sound file bundled with your app, e.g. `"sound": "my_sound.caf"` - see [iOS notification sound](#ios-notification-sound) for more info. - - To play the default notification sound, set `"sound": "default"`. - - To display a silent notification (no sound), omit the `sound` key from the message. -- `notification_ios_badge` - Badge number to display on app icon on home screen. - -For example: -```json -{ - "name": "my_data", - "data" : { - "notification_foreground": "true", - "notification_body" : "Notification body", - "notification_title": "Notification title", - "notification_ios_sound": "my_sound.caf", - "notification_ios_badge": 1 - } -} -``` - -## Custom FCM message handling -In some cases you may want to handle certain incoming FCM messages differently rather than with the default behaviour of this plugin. -Therefore this plugin provides a mechanism by which you can implement your own custom FCM message handling for specific FCM messages which bypasses handling of those messages by this plugin. -To do this requires you to write native handlers for Android & iOS which hook into the native code of this plugin. - -### Android -You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/android/FirebasePluginMessageReceiver.java) and implements the `onMessageReceived()` and `sendMessage()` abstract methods. - -### iOS -You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/ios/FirebasePluginMessageReceiver.h) and implements the `sendNotification()` abstract method. - -### Example -The [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) contains an [example plugin](https://github.com/dpa99c/cordova-plugin-firebasex-test/tree/master/plugins/cordova-plugin-customfcmreceiver) which implements a custom receiver class for both platforms. -You can test this by building and running the example project app, and sending the [notification_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/notification_custom_receiver.json) and [data_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/data_custom_receiver.json) test messages using the [built-in FCM client](https://github.com/dpa99c/cordova-plugin-firebasex-test#messaging-client). - -# InApp Messaging -The Firebase Inapp Messaging SDK component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). -If you wish to use Firebase Inapp Messaging, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. - -# Google Tag Manager -The Google Tag Manager component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). -If you wish to use Google Tag Manager, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. - -# API -The list of available methods for this plugin is described below. - -## Notifications and data messages -The plugin is capable of receiving push notifications and FCM data messages. - -See [Cloud messaging](#cloud-messaging) section for more. - -### getToken -Get the current FCM token. -Null if the token has not been allocated yet by the Firebase SDK. - -**Parameters**: -- {function} success - callback function which will be passed the {string} token as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.getToken(function(fcmToken) { - console.log(fcmToken); -}, function(error) { - console.error(error); -}); -``` -Note that token will be null if it has not been established yet. - -### getId -Get the app instance ID (an constant ID which persists as long as the app is not uninstalled/reinstalled). -Null if the ID has not been allocated yet by the Firebase SDK. - -**Parameters**: -- {function} success - callback function which will be passed the {string} ID as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.getId(function(appInstanceId) { - console.log(appInstanceId); -}, function(error) { - console.error(error); -}); -``` -Note that token will be null if it has not been established yet. - -### onTokenRefresh -Registers a handler to call when the FCM token changes. -This is the best way to get the token as soon as it has been allocated. -This will be called on the first run after app install when a token is first allocated. -It may also be called again under other circumstances, e.g. if `unregister()` is called or Firebase allocates a new token for other reasons. -You can use this callback to return the token to you server to keep the FCM token associated with a given user up-to-date. - -**Parameters**: -- {function} success - callback function which will be passed the {string} token as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.onTokenRefresh(function(fcmToken) { - console.log(fcmToken); -}, function(error) { - console.error(error); -}); -``` - -### getAPNSToken -iOS only. -Get the APNS token allocated for this app install. -Note that token will be null if it has not been allocated yet. - -**Parameters**: -- {function} success - callback function which will be passed the {string} APNS token as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.getAPNSToken(function(apnsToken) { - console.log(apnsToken); -}, function(error) { - console.error(error); -}); -``` - -### onApnsTokenReceived -iOS only. -Registers a handler to call when the APNS token is allocated. -This will be called once when remote notifications permission has been granted by the user at runtime. - -**Parameters**: -- {function} success - callback function which will be passed the {string} token as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.onApnsTokenReceived(function(apnsToken) { - console.log(apnsToken); -}, function(error) { - console.error(error); -}); -``` - -### onMessageReceived -Registers a callback function to invoke when: -- a notification or data message is received by the app -- a system notification is tapped by the user - -**Parameters**: -- {function} success - callback function which will be passed the {object} message as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.onMessageReceived(function(message) { - console.log("Message type: " + message.messageType); - if(message.messageType === "notification"){ - console.log("Notification message received"); - if(message.tap){ - console.log("Tapped in " + message.tap); - } - } - console.dir(message); -}, function(error) { - console.error(error); -}); -``` - -The `message` object passed to the callback function will contain the platform-specific FCM message payload along with the following keys: -- `messageType=notification|data` - indicates if received message is a notification or data message -- `tap=foreground|background` - set if the call to `onMessageReceived()` was initiated by user tapping on a system notification. - - indicates if the system notification was tapped while the app was in the foreground or background. - - not set if no system notification was tapped (i.e. message was received directly from FCM rather than via a user tap on a system notification). - -Notification message flow: - -1. App is in foreground: - a. By default, when a notification message arrives the app receives the notification message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. - b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. -2. App is in background: - a. User receives the notification message as a system notification in the device notification bar - b. User taps the system notification which launches the app - b. User receives the notification message payload in the `onMessageReceived` JavaScript callback - -Data message flow: - -1. App is in foreground: - a. By default, when a data message arrives the app receives the data message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. - b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. -2. App is in background: - a. The app receives the data message in the `onMessageReceived` JavaScript callback while in the background - b. If the data message contains the [data message notification keys](#data-message-notifications), the plugin will display a system notification for the data message while in the background. - -### grantPermission -Grant permission to receive push notifications (will trigger prompt) and return `hasPermission: true`. -iOS only (Android will always return true). - -**Parameters**: -- {function} success - callback function which will be passed the {boolean} permission result as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.grantPermission(function(hasPermission){ - console.log("Permission was " + (hasPermission ? "granted" : "denied")); -}); -``` -### hasPermission -Check permission to receive push notifications and return the result to a callback function as boolean. -On iOS, returns true is runtime permission for remote notifications is granted and enabled in Settings. -On Android, returns true if remote notifications are enabled. - -**Parameters**: -- {function} success - callback function which will be passed the {boolean} permission result as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.hasPermission(function(hasPermission){ - console.log("Permission is " + (hasPermission ? "granted" : "denied")); -}); -``` - -### unregister -Unregisters from Firebase by deleting the current device token. -Use this to stop receiving push notifications associated with the current token. -e.g. call this when you logout user from your app. -By default, a new token will be generated as soon as the old one is removed. -To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). - -**Parameters**: None - -```javascript -FirebasePlugin.unregister(); -``` - -### isAutoInitEnabled -Indicates whether autoinit is currently enabled. -If so, new FCM tokens will be automatically generated. - -**Parameters**: -- {function} success - callback function which will be passed the {boolean} result as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - - -```javascript -FirebasePlugin.isAutoInitEnabled(function(enabled){ - console.log("Auto init is " + (enabled ? "enabled" : "disabled")); -}); - -``` - -### setAutoInitEnabled -Sets whether to autoinit new FCM tokens. -By default, a new token will be generated as soon as the old one is removed. -To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). - -**Parameters**: -- {boolean} enabled - set true to enable, false to disable -- {function} success - callback function to call on successful execution of operation. -- {function} error - callback function which will be passed a {string} error message as an argument - - -```javascript -FirebasePlugin.setAutoInitEnabled(false, function(){ - console.log("Auto init has been disabled "); - FirebasePlugin.unregister(); -}); - -``` - -### setBadgeNumber -iOS only. -Set a number on the icon badge: - -**Parameters**: -- {integer} badgeNumber - number to set for the app badge - -```javascript -FirebasePlugin.setBadgeNumber(3); -``` - -Set 0 to clear the badge -```javascript -FirebasePlugin.setBadgeNumber(0); -``` - -Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) - -### getBadgeNumber -iOS only. -Get icon badge number: - -**Parameters**: -- {function} success - callback function which will be passed the {integer} current badge number as an argument - -```javascript -FirebasePlugin.getBadgeNumber(function(n) { - console.log(n); -}); -``` - -Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) - -### clearAllNotifications -Clear all pending notifications from the drawer: - -**Parameters**: None - -```javascript -FirebasePlugin.clearAllNotifications(); -``` - -### subscribe -Subscribe to a topic. - -Topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. - -**Parameters**: -- {string} topicName - name of topic to subscribe to - -```javascript -FirebasePlugin.subscribe("latest_news"); -``` - -### unsubscribe -Unsubscribe from a topic. - -This will stop you receiving messages for that topic - -**Parameters**: -- {string} topicName - name of topic to unsubscribe from - -```javascript -FirebasePlugin.unsubscribe("latest_news"); -``` - -### createChannel -Android 8+ only. -Creates a custom channel to be used by notification messages which have the channel property set in the message payload to the `id` of the created channel: -- For background (system) notifications: `android.notification.channel_id` -- For foreground/data notifications: `data.notification_android_channel_id` - -For each channel you may set the sound to be played, the color of the phone LED (if supported by the device), whether to vibrate and set vibration pattern (if supported by the device), importance and visibility. -Channels should be created as soon as possible (on program start) so notifications can work as expected. -A default channel is created by the plugin at app startup; the properties of this can be overridden see [setDefaultChannel](#setdefaultchannel) - -Calling on Android 7 or below or another platform will have no effect. - -**Parameters**: -- {object} - channel configuration object (see below for object keys/values) -- {function} success - callback function which will be call on successful channel creation -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -// Define custom channel - all keys are except 'id' are optional. -var channel = { - // channel ID - must be unique per app package - id: "my_channel_id", - - // Channel description. Default: empty string - description: "Channel description", - - // Channel name. Default: empty string - name: "Channel name", - - //The sound to play once a push comes. Default value: 'default' - //Values allowed: - //'default' - plays the default notification sound - //'ringtone' - plays the currently set ringtone - //'false' - silent; don't play any sound - //filename - the filename of the sound file located in '/res/raw' without file extension (mysound.mp3 -> mysound) - sound: "mysound", - - //Vibrate on new notification. Default value: true - //Possible values: - //Boolean - vibrate or not - //Array - vibration pattern - e.g. [500, 200, 500] - milliseconds vibrate, milliseconds pause, vibrate, pause, etc. - vibration: true, - - // Whether to blink the LED - light: true, - - //LED color in ARGB format - this example BLUE color. If set to -1, light color will be default. Default value: -1. - lightColor: parseInt("FF0000FF", 16).toString(), - - //Importance - integer from 0 to 4. Default value: 4 - //0 - none - no sound, does not show in the shade - //1 - min - no sound, only shows in the shade, below the fold - //2 - low - no sound, shows in the shade, and potentially in the status bar - //3 - default - shows everywhere, makes noise, but does not visually intrude - //4 - high - shows everywhere, makes noise and peeks - importance: 4, - - //Show badge over app icon when non handled pushes are present. Default value: true - badge: true, - - //Show message on locked screen. Default value: 1 - //Possible values (default 1): - //-1 - secret - Do not reveal any part of the notification on a secure lockscreen. - //0 - private - Show the notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. - //1 - public - Show the notification in its entirety on all lockscreens. - visibility: 1 -}; - -// Create the channel -FirebasePlugin.createChannel(channel, -function(){ - console.log('Channel created: ' + channel.id); -}, -function(error){ - console.log('Create channel error: ' + error); -}); -``` - -Example FCM v1 API notification message payload for invoking the above example channel: - -```json - -{ - "notification": - { - "title":"Notification title", - "body":"Notification body" - }, - "android": { - "notification": { - "channel_id": "my_channel_id" - } - } -} - -``` - -If your Android app plays multiple sounds or effects, it's a good idea to create a channel for each likely combination. This is because once a channel is created you cannot override sounds/effects. -IE, expanding on the createChannel example: -```javascript -let soundList = ["train","woop","clock","radar","sonar"]; -for (let key of soundList) { - let name = "yourchannelprefix_" + key; - channel.id = name; - channel.sound = key; - channel.name = "Your description " + key; - - // Create the channel - window.FirebasePlugin.createChannel(channel, - function(){ - console.log('Notification Channel created: ' + channel.id + " " + JSON.stringify(channel)); - }, - function(error){ - console.log('Create notification channel error: ' + error); - }); -} -``` - -Note, if you just have one sound / effect combination that the user can customise, just use setDefaultChannel when any changes are made. - - -### setDefaultChannel -Android 8+ only. -Overrides the properties for the default channel. -The default channel is used if no other channel exists or is specified in the notification. -Any options not specified will not be overridden. -Should be called as soon as possible (on app start) so default notifications will work as expected. -Calling on Android 7 or below or another platform will have no effect. - -**Parameters**: -- {object} - channel configuration object -- {function} success - callback function which will be call on successfully setting default channel -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -var channel = { - id: "my_default_channel", - name: "My Default Name", - description: "My Default Description", - sound: "ringtone", - vibration: [500, 200, 500], - light: true, - lightColor: parseInt("FF0000FF", 16).toString(), - importance: 4, - badge: false, - visibility: -1 -}; - -FirebasePlugin.setDefaultChannel(channel, -function(){ - console.log('Default channel set'); -}, -function(error){ - console.log('Set default channel error: ' + error); -}); -``` - -### Default Android Channel Properties -The default channel is initialised at app startup with the following default settings: - -```json -{ - id: "fcm_default_channel", - name: "Default", - description: "", - sound: "default", - vibration: true, - light: true, - lightColor: -1, - importance: 4, - badge: true, - visibility: 1 -} -``` - -### deleteChannel -Android 8+ only. -Removes a previously defined channel. -Calling on Android 7 or below or another platform will have no effect. - -**Parameters**: -- {string} - id of channel to delete -- {function} success - callback function which will be call on successfully deleting channel -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.deleteChannel("my_channel_id", -function(){ - console.log('Channel deleted'); -}, -function(error){ - console.log('Delete channel error: ' + error); -}); - -``` - -### listChannels -Android 8+ only. -Gets a list of all channels. -Calling on Android 7 or below or another platform will have no effect. - -**Parameters**: -- {function} success - callback function which will be passed the {array} of channel objects as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.listChannels( -function(channels){ - if(typeof channels == "undefined") - return; - - for(var i=0;i -Android -
- - -

-iOS -
- - - - -## Authentication - -### isUserSignedIn -Checks if there is a current Firebase user signed into the app. - -**Parameters**: -- {function} success - callback function to pass {boolean} result to as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.isUserSignedIn(function(isSignedIn) { - console.log("User "+(isSignedIn ? "is" : "is not") + " signed in"); - }, function(error) { - console.error("Failed to check if user is signed in: " + error); - }); -``` - -### signOutUser -Signs current Firebase user out of the app. - -**Parameters**: -- {function} success - callback function to pass {boolean} result to as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.signOutUser(function() { - console.log("User signed out"); - }, function(error) { - console.error("Failed to sign out user: " + error); - }); -``` - -### getCurrentUser -Returns details of the currently logged in user from local Firebase SDK. -Note that some user properties will be empty is they are not defined in Firebase for the current user. - -**Parameters**: -- {function} success - callback function to pass user {object} to as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.getCurrentUser(function(user) { - console.log("Name: "+user.name); - console.log("Email: "+user.email); - console.log("Is email verified?: "+user.emailIsVerified); - console.log("Phone number: "+user.phoneNumber); - console.log("Photo URL: "+user.photoUrl); - console.log("UID: "+user.uid); - console.log("Provider ID: "+user.providerId); - console.log("ID token: "+user.idToken); - }, function(error) { - console.error("Failed to get current user data: " + error); - }); -``` - -### reloadCurrentUser -Loads details of the currently logged in user from remote Firebase server. -This differs from `getCurrentUser()` which loads the locally cached details which may be stale. -For example, if you want to check if a user has verified their email address, this method will guarantee the reported verified state is up-to-date. - -**Parameters**: -- {function} success - callback function to pass user {object} to as an argument -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.reloadCurrentUser(function(user) { - console.log("Name: "+user.name); - console.log("Email: "+user.email); - console.log("Is email verified?: "+user.emailIsVerified); - console.log("Phone number: "+user.phoneNumber); - console.log("Photo URL: "+user.photoUrl); - console.log("UID: "+user.uid); - console.log("Provider ID: "+user.providerId); - console.log("ID token: "+user.idToken); - }, function(error) { - console.error("Failed to reload current user data: " + error); - }); -``` - -### updateUserProfile -Updates the display name and/or photo URL of the current Firebase user signed into the app. - -**Parameters**: -- {object} profile - new profile details: - - {string} name - display name of user - - {string} photoUri - URL of user profile photo -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.updateUserProfile({ - name: "Homer Simpson", - photoUri: "http://homer.simpson.com/photo.png" - },function() { - console.log("User profile successfully updated"); - }, function(error) { - console.error("Failed to update user profile: " + error); - }); -``` - -### updateUserEmail -Updates/sets the email address of the current Firebase user signed into the app. - -**Parameters**: -- {string} email - email address of user -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.updateUserEmail("user@somewhere.com",function() { - console.log("User email successfully updated"); - }, function(error) { - console.error("Failed to update user email: " + error); - }); -``` - -### sendUserEmailVerification -Sends a verification email to the currently configured email address of the current Firebase user signed into the app. -When the user opens the contained link, their email address will have been verified. - -**Parameters**: -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.sendUserEmailVerification(function() { - console.log("User verification email successfully sent"); - }, function(error) { - console.error("Failed to send user verification email: " + error); - }); -``` - -### updateUserPassword -Updates/sets the account password for the current Firebase user signed into the app. - -**Parameters**: -- {string} password - user-defined password -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.updateUserPassword("mypassword",function() { - console.log("User password successfully updated"); - }, function(error) { - console.error("Failed to update user password: " + error); - }); -``` - -### sendUserPasswordResetEmail -Sends a password reset email to the specified user email address. -Note: doesn't require the Firebase user to be signed in to the app. - -**Parameters**: -- {string} email - email address of user -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.sendUserPasswordResetEmail("user@somewhere.com",function() { - console.log("User password reset email sent successfully"); - }, function(error) { - console.error("Failed to send user password reset email: " + error); - }); -``` - -### deleteUser -Deletes the account of the current Firebase user signed into the app. - -**Parameters**: -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript - FirebasePlugin.deleteUser(function() { - console.log("User account deleted"); - }, function(error) { - console.error("Failed to delete current user account: " + error); - }); -``` - -### createUserWithEmailAndPassword -Creates a new email/password-based user account. -If account creation is successful, user will be automatically signed in. - -**Parameters**: -- {string} email - user email address. It is the responsibility of the app to ensure this is a valid email address. -- {string} password - user password. It is the responsibility of the app to ensure the password is suitable. -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript - FirebasePlugin.createUserWithEmailAndPassword(email, password, function() { - console.log("Successfully created email/password-based user account"); - // User is now signed in - }, function(error) { - console.error("Failed to create email/password-based user account", error); - }); -``` - -### signInUserWithEmailAndPassword -Signs in to an email/password-based user account. - -**Parameters**: -- {string} email - user email address -- {string} password - user password -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript - FirebasePlugin.signInUserWithEmailAndPassword(email, password, function() { - console.log("Successfully signed in"); - // User is now signed in - }, function(error) { - console.error("Failed to sign in", error); - }); -``` - -### signInUserWithCustomToken -Signs in user with custom token. - -**Parameters**: -- {string} customToken - the custom token -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript - FirebasePlugin.signInUserWithCustomToken(customToken, function() { - console.log("Successfully signed in"); - // User is now signed in - }, function(error) { - console.error("Failed to sign in", error); - }); -``` - -### signInUserAnonymously -Signs in user anonymously. - -**Parameters**: -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript - FirebasePlugin.signInUserAnonymously(function() { - console.log("Successfully signed in"); - // User is now signed in - }, function(error) { - console.error("Failed to sign in", error); - }); -``` - -### verifyPhoneNumber -Requests verification of a phone number. -The resulting credential can be used to create/sign in to a phone number-based user account in your app or to link the phone number to an existing user account - -**NOTE: This will only work on physical devices with a SIM card (not iOS Simulator or Android Emulator)** - -In response to your request, you'll receive a verification ID which you can use in conjunction with the verification code to sign the user in. - -There are 3 verification scenarios: -- Some Android devices support "instant verification" where the phone number can be instantly verified without sending or receiving an SMS. - - In this case, the user doesn't need to do anything in order for you to sign them in and you don't need to provide any additional credentials in order to sign the user in or link the user account to an existing Firebase user account. -- Some Android devices support "auto-retrieval" where Google Play services is able to detect the incoming verification SMS and perform verification with no user action required. - - As above, the user doesn't need to do anything in order for you to sign them in. -- For other Android devices and all iOS devices, the user must manually enter the verification code received in the SMS into your app. - - This code be used, along with the accompanying verification ID, to sign the user in or link phone number to an existing Firebase user account. - -**Parameters**: -- {function} success - callback function to pass {object} credentials to as an argument -- {function} error - callback function which will be passed a {string} error message as an argument -- {string} phoneNumber - phone number to verify -- {integer} timeOutDuration - (optional) time to wait in seconds before timing out -- {string} fakeVerificationCode - (optional) to test instant verification on Android ,specify a fake verification code to return for whitelisted phone numbers. - - See [Firebase SDK Phone Auth Android Integration Testing](https://firebase.google.com/docs/auth/android/phone-auth#integration-testing) for more info. - -The success callback will be passed a credential object with the following possible properties: -- {boolean} instantVerification - `true` if the Android device used instant verification to instantly verify the user without sending an SMS -or used auto-retrieval to automatically read an incoming SMS. -If this is `false`, the device will be sent an SMS containing the verification code. -If the Android device supports auto-retrieval, on the device receiving the SMS, this success callback will be immediately invoked again with `instantVerification: true` and no user action will be required for verification since Google Play services will extract and submit the verification code. -Otherwise the user must manually enter the verification code from the SMS into your app. -Always `false` on iOS. -- {string} id - the identifier of a native credential object which can be used for signing in the user. -Will only be present if `instantVerification` is `true`. -- {string} verificationId - the verification ID to be passed along with the verification code sent via SMS to sign the user in. -Will only be present if `instantVerification` is `false`. - -Example usage: - -```javascript -var number = '+441234567890'; -var timeOutDuration = 60; -var fakeVerificationCode = '123456'; -var awaitingSms = false; - -FirebasePlugin.verifyPhoneNumber(function(credential) { - - if(credential.instantVerification){ - if(awaitingSms){ - awaitingSms = false; - // the Android device used auto-retrieval to extract and submit the verification code in the SMS so dismiss user input UI - dismissUserPromptToInputCode(); - } - signInWithCredential(credential); - }else{ - awaitingSms = true; - promptUserToInputCode() // you need to implement this - .then(function(userEnteredCode){ - awaitingSms = false; - credential.code = userEnteredCode; // set the user-entered verification code on the credential object - signInWithCredential(credential); - }); - } -}, function(error) { - console.error("Failed to verify phone number: " + JSON.stringify(error)); -}, number, timeOutDuration, fakeVerificationCode); - -function signInWithCredential(credential){ - FirebasePlugin.signInWithCredential(credential, function() { - console.log("Successfully signed in"); - }, function(error) { - console.error("Failed to sign in", error); - }); -} -``` - -#### Android -To use phone auth with your Android app, you need to configure your app SHA-1 hash in the android app configuration in the Firebase console. -See [this guide](https://developers.google.com/android/guides/client-auth) to find how to your SHA-1 app hash. -See the [Firebase phone auth integration guide for native Android](https://firebase.google.com/docs/auth/android/phone-auth) for more information. - -#### iOS -When you call this method on iOS, FCM sends a silent push notification to the iOS device to verify it. -So to use phone auth with your iOS app, you need to: -- [setup your iOS app for push notifications](https://firebase.google.com/docs/cloud-messaging/ios/certs) -- Verify that push notifications are arriving on your physical device -- [Upload your APNs auth key to the Firebase console](https://firebase.google.com/docs/cloud-messaging/ios/client#upload_your_apns_authentication_key). - -You can [set up reCAPTCHA verification for iOS](https://firebase.google.com/docs/auth/ios/phone-auth#set-up-recaptcha-verification) automatically by specifying the `SETUP_RECAPTCHA_VERIFICATION` plugin variable at plugin install time: - - cordova plugin add cordova-plugin-firebasex --variable SETUP_RECAPTCHA_VERIFICATION=true - -This adds the `REVERSED_CLIENT_ID` from the `GoogleService-Info.plist` to the list of custom URL schemes in your Xcode project, so you don't need to do this manually. - -### authenticateUserWithGoogle -Authenticates the user with a Google account to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. - -**Parameters**: -- {string} clientId - your OAuth 2.0 client ID - [see here](https://developers.google.com/identity/sign-in/android/start-integrating#get_your_backend_servers_oauth_20_client_id) how to obtain it. -- {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: - - {string} id - the identifier of a native credential object which can be used for signing in the user. -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript -FirebasePlugin.authenticateUserWithGoogle(clientId, function(credential) { - FirebasePlugin.signInWithCredential(credential, function() { - console.log("Successfully signed in"); - }, function(error) { - console.error("Failed to sign in", error); - }); -}, function(error) { - console.error("Failed to authenticate with Google: " + error); -}); -``` - -#### Android -To use Google Sign-in in your Android app you need to do the following: -- Add the SHA-1 fingerprint of your app's signing key to your Firebase project -- Enable Google Sign-in in the Firebase console - -For details how to do the above, see the [Google Sign-In on Android page](https://firebase.google.com/docs/auth/android/google-signin) in the Firebase documentation. - -### authenticateUserWithApple -Authenticates the user with an Apple account using Sign In with Apple to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. - -**Parameters**: -- {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: - - {string} id - the identifier of a native credential object which can be used for signing in the user. -- {function} error - callback function which will be passed a {string} error message as an argument - - {string} locale - (Android only) the language to display Apple's Sign-in screen in. - - Defaults to "en" (English) if not specified. - - See [the Apple documentation](https://developer.apple.com/documentation/signinwithapplejs/incorporating_sign_in_with_apple_into_other_platforms###2112) for a list of supported locales. - - The value is ignored on iOS which uses the locale of the device to determine the display language. - -Example usage: - -```javascript - -FirebasePlugin.authenticateUserWithApple(function(credential) { - FirebasePlugin.signInWithCredential(credential, function() { - console.log("Successfully signed in"); - }, function(error) { - console.error("Failed to sign in", error); - }); -}, function(error) { - console.error("Failed to authenticate with Apple: " + error); -}, 'en_GB'); -``` -#### iOS -To use Sign In with Apple in your iOS app you need to do the following: -- Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/ios/apple#before-you-begin) -- After adding the `cordova-ios` platform, open the project workspace in Xcode (`platforms/ios/YourApp.xcworkspace`) and add the "Sign In with Apple" capability in the "Signing & Capabilities section" - - Note: AFAIK there is currently no way to automate the addition of this capability - -#### Android -To use Sign In with Apple in your Android app you need to do the following: -- Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/android/apple#before-you-begin) - -### signInWithCredential -Signs the user into Firebase with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. -See the [Android-](https://firebase.google.com/docs/auth/android/phone-auth#sign-in-the-user) and [iOS](https://firebase.google.com/docs/auth/ios/phone-auth#sign-in-the-user-with-the-verification-code)-specific Firebase documentation for more info. - -**Parameters**: -- {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - - {string} id - the identifier of a native credential object which can be used for signing in the user. - Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. - If true, you do not need to provide a user-entered verification. - - Only present if the credential was obtained via `verifyPhoneNumber()` - - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. -- {function} success - callback function to call on successful sign-in using credentials -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript -function signInWithCredential(credential){ - FirebasePlugin.signInWithCredential(credential, function() { - console.log("Successfully signed in"); - }, function(error) { - console.error("Failed to sign in", error); - }); -} - -``` - -### linkUserWithCredential -Links an existing Firebase user account with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. -See the [Android-](https://firebase.google.com/docs/auth/android/account-linking) and [iOS](https://firebase.google.com/docs/auth/ios/account-linking)-specific Firebase documentation for more info. - -**Parameters**: -- {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - - {string} id - the identifier of a native credential object which can be used for signing in the user. - Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. - If true, you do not need to provide a user-entered verification. - - Only present if the credential was obtained via `verifyPhoneNumber()` - - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. -- {function} success - callback function to call on successful linking using credentials -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript -function linkUserWithCredential(credential){ - FirebasePlugin.linkUserWithCredential(credential, function() { - console.log("Successfully linked"); - }, function(error) { - console.error("Failed to link", error); - }); -} - -``` - -### reauthenticateWithCredential -Reauthenticates the currently signed in user with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. - -**Parameters**: -- {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - - {string} id - the identifier of a native credential object which can be used for signing in the user. - Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. - If true, you do not need to provide a user-entered verification. - - Only present if the credential was obtained via `verifyPhoneNumber()` - - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. -- {function} success - callback function to call on success -- {function} error - callback function which will be passed a {string} error message as an argument - -Example usage: - -```javascript - FirebasePlugin.reauthenticateWithCredential(credential, function() { - console.log("Successfully reauthenticated"); - }, function(error) { - console.error("Failed to reauthenticate", error); - }); -``` - -### registerAuthStateChangeListener -Registers a Javascript function to invoke when Firebase Authentication state changes between user signed in/signed out. - -**Parameters**: -- {function} fn - callback function to invoke when authentication state changes - - Will be a passed a single boolean argument which is `true` if user just signed in and `false` if user just signed out. - -Example usage: - -```javascript - FirebasePlugin.registerAuthStateChangeListener(function(userSignedIn){ - console.log("Auth state changed: User signed " + (userSignedIn ? "in" : "out")); - }); -``` - -## Remote Config - -### fetch -Fetch Remote Config parameter values for your app: - -**Parameters**: -- {integer} cacheExpirationSeconds (optional) - cache expiration in seconds -- {function} success - callback function on successfully fetching remote config -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.fetch(function () { - // success callback -}, function () { - // error callback -}); -// or, specify the cacheExpirationSeconds -FirebasePlugin.fetch(600, function () { - // success callback -}, function () { - // error callback -}); -``` - -### activateFetched -Activate the Remote Config fetched config: - -**Parameters**: -- {function} success - callback function which will be passed a {boolean} argument indicating whether fetched config was successfully activated -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.activateFetched(function(activated) { - // activated will be true if there was a fetched config activated, - // or false if no fetched config was found, or the fetched config was already activated. - console.log(activated); -}, function(error) { - console.error(error); -}); -``` - -### getValue -Retrieve a Remote Config value: - -**Parameters**: -- {string} key - key for which to fetch associated value -- {function} success - callback function which will be passed a {any} argument containing the value stored against the specified key. -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.getValue("key", function(value) { - console.log(value); -}, function(error) { - console.error(error); -}); -``` - -### getByteArray -Android only. -Retrieve a Remote Config byte array: - -**Parameters**: -- {string} key - key for which to fetch associated value -- {function} success - callback function which will be passed a {string} argument containing the Base64 encoded string that represents the value stored against the specified key. -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.getByteArray("key", function(bytes) { - // a Base64 encoded string that represents the value for "key" - console.log(bytes.base64); - // a numeric array containing the values of the byte array (i.e. [0xFF, 0x00]) - console.log(bytes.array); -}, function(error) { - console.error(error); -}); -``` - -### getInfo -Get the current state of the FirebaseRemoteConfig singleton object: - -**Parameters**: -- {function} success - callback function which will be passed an {object} argument containing the state info -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.getInfo(function(info) { - // the status of the developer mode setting (true/false) - console.log(info.configSettings.developerModeEnabled); - // (iOS only) for how much (secs) fetch cache is valid and data will not be refetched - console.log(info.configSettings.minimumFetchInterval); - // (iOS only) value in seconds to abandon a pending fetch request made to the backend - console.log(info.configSettings.fetchTimeout); - // the timestamp (milliseconds since epoch) of the last successful fetch - console.log(info.fetchTimeMillis); - // the status of the most recent fetch attempt (int) - // 0 = Config has never been fetched. - // 1 = Config fetch succeeded. - // 2 = Config fetch failed. - // 3 = Config fetch was throttled. - console.log(info.lastFetchStatus); -}, function(error) { - console.error(error); -}); -``` - -### setConfigSettings -Android only. -Change the settings for the FirebaseRemoteConfig object's operations: - -**Parameters**: -- {object} configSettings - object specifying the remote config settings -- {function} success - callback function to be call on successfully setting the remote config settings -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -var settings = { - developerModeEnabled: true -} -FirebasePlugin.setConfigSettings(settings); -``` - -### setDefaults -Android only. -Set defaults in the Remote Config: - -**Parameters**: -- {object} defaultSettings - object specifying the default remote config settings -- {function} success - callback function to be call on successfully setting the remote config setting defaults -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -// define defaults -var defaults = { - // map property name to value in Remote Config defaults - mLong: 1000, - mString: 'hello world', - mDouble: 3.14, - mBoolean: true, - // map "mBase64" to a Remote Config byte array represented by a Base64 string - // Note: the Base64 string is in an array in order to differentiate from a string config value - mBase64: ["SGVsbG8gV29ybGQ="], - // map "mBytes" to a Remote Config byte array represented by a numeric array - mBytes: [0xFF, 0x00] -} -// set defaults -FirebasePlugin.setDefaults(defaults); - -``` - -## Performance - -### setPerformanceCollectionEnabled -Manually enable/disable performance data collection, e.g. if [disabled on app startup](#disable-data-collection-on-startup). - -**Parameters**: -- {boolean} setEnabled - whether to enable or disable performance data collection - -```javascript -FirebasePlugin.setPerformanceCollectionEnabled(true); // Enables performance data collection - -FirebasePlugin.setPerformanceCollectionEnabled(false); // Disables performance data collection -``` - -### isPerformanceCollectionEnabled -Indicates whether performance data collection is enabled. - -Notes: -- This value applies both to the current app session and subsequent app sessions until such time as it is changed. -- It returns the value set by [setPerformanceCollectionEnabled()](#setperformancecollectionenabled). -- If automatic data collection was not [disabled on app startup](#disable-data-collection-on-startup), this will always return `true`. - -**Parameters**: -- {function} success - callback function which will be invoked on success. -Will be passed a {boolean} indicating if the setting is enabled. -- {function} error - (optional) callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.isPerformanceCollectionEnabled(function(enabled){ - console.log("Performance data collection is "+(enabled ? "enabled" : "disabled")); -}, function(error){ - console.error("Error getting Performance data collection setting: "+error); -}); -``` - -### startTrace - -Start a trace. - -**Parameters**: -- {string} name - name of trace to start -- {function} success - callback function to call on successfully starting trace -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.startTrace("test trace", success, error); -``` - -### incrementCounter - -To count the performance-related events that occur in your app (such as cache hits or retries), add a line of code similar to the following whenever the event occurs, using a string other than retry to name that event if you are counting a different type of event: - -**Parameters**: -- {string} name - name of trace -- {string} counterName - name of counter to increment -- {function} success - callback function to call on successfully incrementing counter -- {function} error - callback function which will be passed a {string} error message as an argument - - -```javascript -FirebasePlugin.incrementCounter("test trace", "retry", success, error); -``` - -### stopTrace - -Stop the trace - -**Parameters**: -- {string} name - name of trace to stop -- {function} success - callback function to call on successfully stopping trace -- {function} error - callback function which will be passed a {string} error message as an argument - -```javascript -FirebasePlugin.stopTrace("test trace"); -``` - -## Firestore -These plugin API functions provide CRUD operations for working with documents in Firestore collections. - -Notes: -- Only top-level Firestore collections are currently supported - [subcollections](https://firebase.google.com/docs/firestore/manage-data/structure-data#subcollections) (nested collections within documents) are currently not supported due to the complexity of mapping the native objects into the plugin's JS API layer. -- A document object may contain values of primitive Javascript types `string`, `number`, `boolean`, `array` or `object`. -Arrays and objects may contain nested structures of these types. -- If a collection name referenced in a document write operation does not already exist, it will be created by the first write operation referencing it. - -### addDocumentToFirestoreCollection -Adds a new document to a Firestore collection, which will be allocated an auto-generated document ID. - -**Parameters**: -- {object} document - document object to add to collection -- {string} collection - name of top-level collection to add document to. -- {function} success - callback function to call on successfully adding the document. -Will be passed a {string} argument containing the auto-generated document ID that the document was stored against. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var document = { - "a_string": "foo", - "a_list": [1, 2, 3], - "an_object": { - "an_integer": 1, - } -}; -var collection = "my_collection"; -FirebasePlugin.addDocumentToFirestoreCollection(document, collection, function(documentId){ - console.log("Successfully added document with id="+documentId); -}, function(error){ - console.error("Error adding document: "+error); -}); -``` - -### setDocumentInFirestoreCollection -Sets (adds/replaces) a document with the given ID in a Firestore collection. - -**Parameters**: -- {string} documentId - document ID to use when setting document in the collection. -- {object} document - document object to set in collection. -- {string} collection - name of top-level collection to set document in. -- {function} success - callback function to call on successfully setting the document. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var documentId = "my_doc"; -var document = { - "a_string": "foo", - "a_list": [1, 2, 3], - "an_object": { - "an_integer": 1, - } -}; -var collection = "my_collection"; -FirebasePlugin.setDocumentInFirestoreCollection(documentId, document, collection, function(){ - console.log("Successfully set document with id="+documentId); -}, function(error){ - console.error("Error setting document: "+error); -}); -``` - -### updateDocumentInFirestoreCollection -Updates an existing document with the given ID in a Firestore collection. -This is a non-destructive update that will only overwrite existing keys in the existing document or add new ones if they don't already exist. -If the no document with the specified ID exists in the collection, an error will be raised. - -**Parameters**: -- {string} documentId - document ID of the document to update. -- {object} document - entire document or document fragment to update existing document with. -- {string} collection - name of top-level collection to update document in. -- {function} success - callback function to call on successfully updating the document. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var documentId = "my_doc"; -var documentFragment = { - "a_string": "new value", - "a_new_string": "bar" -}; -var collection = "my_collection"; -FirebasePlugin.updateDocumentInFirestoreCollection(documentId, documentFragment, collection, function(){ - console.log("Successfully updated document with id="+documentId); -}, function(error){ - console.error("Error updating document: "+error); -}); -``` - -### deleteDocumentFromFirestoreCollection -Deletes an existing document with the given ID in a Firestore collection. - -Note: If the no document with the specified ID exists in the collection, the Firebase SDK will still return a successful outcome. - -**Parameters**: -- {string} documentId - document ID of the document to delete. -- {string} collection - name of top-level collection to delete document in. -- {function} success - callback function to call on successfully deleting the document. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var documentId = "my_doc"; -var collection = "my_collection"; -FirebasePlugin.deleteDocumentFromFirestoreCollection(documentId, collection, function(){ - console.log("Successfully deleted document with id="+documentId); -}, function(error){ - console.error("Error deleting document: "+error); -}); -``` - -### documentExistsInFirestoreCollection -Indicates if a document with the given ID exists in a Firestore collection. - -**Parameters**: -- {string} documentId - document ID of the document. -- {string} collection - name of top-level collection to check for document. -- {function} success - callback function to call pass result. -Will be passed an {boolean} which is `true` if a document exists. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var documentId = "my_doc"; -var collection = "my_collection"; -FirebasePlugin.documentExistsInFirestoreCollection(documentId, collection, function(exists){ - console.log("Document " + (exists ? "exists" : "doesn't exist")); -}, function(error){ - console.error("Error fetching document: "+error); -}); -``` - -### fetchDocumentInFirestoreCollection -Fetches an existing document with the given ID from a Firestore collection. - -Note: If the no document with the specified ID exists in the collection, the error callback will be invoked. - -**Parameters**: -- {string} documentId - document ID of the document to fetch. -- {string} collection - name of top-level collection to fetch document from. -- {function} success - callback function to call on successfully fetching the document. -Will be passed an {object} contain the document contents. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var documentId = "my_doc"; -var collection = "my_collection"; -FirebasePlugin.fetchDocumentInFirestoreCollection(documentId, collection, function(document){ - console.log("Successfully fetched document: "+JSON.stringify(document)); -}, function(error){ - console.error("Error fetching document: "+error); -}); -``` - -### fetchFirestoreCollection -Fetches all the documents in the specific collection. - -**Parameters**: -- {string} collection - name of top-level collection to fetch. -- {array} filters - a list of filters to sort/filter the documents returned from your collection. - - Supports `where`, `orderBy`, `startAt`, `endAt` and `limit` filters. - - See the [Firestore documentation](https://firebase.google.com/docs/firestore/query-data/queries) for more details. -- {function} success - callback function to call on successfully deleting the document. -Will be passed an {object} containing all the documents in the collection, indexed by document ID. -If a Firebase collection with that name does not exist or it contains no documents, the object will be empty. -- {function} error - callback function which will be passed a {string} error message as an argument. - -```javascript -var collection = "my_collection"; -var filters = [ - ['where', 'field', '==', 'value'], - ['orderBy', 'field', 'desc'] -]; -FirebasePlugin.fetchFirestoreCollection(collection, filters, function(documents){ - console.log("Successfully fetched collection: "+JSON.stringify(documents)); -}, function(error){ - console.error("Error fetching collection: "+error); -}); -``` - -# Credits -- [@robertarnesson](https://github.com/robertarnesson) for the original [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) from which this plugin is forked. -- [@sagrawal31](https://github.com/sagrawal31) and [Wiz Panda](https://github.com/wizpanda) for contributions via [cordova-plugin-firebase-lib](https://github.com/wizpanda/cordova-plugin-firebase-lib). -- [Full list of contributors](https://github.com/dpa99c/cordova-plugin-firebasex/graphs/contributors) +cordova-plugin-firebasex [![Latest Stable Version](https://img.shields.io/npm/v/cordova-plugin-firebasex.svg)](https://www.npmjs.com/package/cordova-plugin-firebasex) [![Total Downloads](https://img.shields.io/npm/dt/cordova-plugin-firebasex.svg)](https://npm-stat.com/charts.html?package=cordova-plugin-firebasex) ======================== Brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project. Upgraded to the Firebase Crahlytics SDK for both [Android](https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=android) [iOS](https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=ios) Supported platforms: Android and iOS **IMPORTANT:** Before opening an issue against this plugin, please read [Reporting issues](#reporting-issues). # cli_build branch This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). To use it, install an npm release with the `-cli` suffix, e.g.: cordova plugin add cordova-plugin-firebasex@9.1.2-cli Or install it directly from this branch: cordova plugin add https://github.com/dpa99c/cordova-plugin-firebasex#cli_build If you wish to use either of these components, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a major plugin release via the NPM registry and build using Xcode. [![donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZRD3W47HQ3EMJ) I dedicate a considerable amount of my free time to developing and maintaining this Cordova plugin, along with my other Open Source software. To help ensure this plugin is kept updated, new features are added and bugfixes are implemented quickly, please donate a couple of dollars (or a little more if you can stretch) as this will help me to afford to dedicate time to its maintenance. Please consider donating if you're using this plugin in an app that makes you money, if you're being paid to make the app, if you're asking for new features or priority bug fixes. **Table of Contents** - [Installation](#installation) - [Plugin variables](#plugin-variables) - [Android & iOS](#android--ios) - [Android only](#android-only) - [iOS only](#ios-only) - [Supported Cordova Versions](#supported-cordova-versions) - [Supported Mobile Platform Versions](#supported-mobile-platform-versions) - [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) - [Breaking API changes](#breaking-api-changes) - [Ionic 4+](#ionic-4) - [Ionic 3](#ionic-3) - [Build environment notes](#build-environment-notes) - [PhoneGap Build](#phonegap-build) - [Android-specific](#android-specific) - [Specifying Android library versions](#specifying-android-library-versions) - [AndroidX](#androidx) - [Google Play Services and Firebase libraries](#google-play-services-and-firebase-libraries) - [iOS-specific](#ios-specific) - [Specifying iOS library versions](#specifying-ios-library-versions) - [Cocoapods](#cocoapods) - [Out-of-date pods](#out-of-date-pods) - [Strip debug symbols](#strip-debug-symbols) - [Cordova CLI builds](#cordova-cli-builds) - [Firebase config setup](#firebase-config-setup) - [Disable data collection on startup](#disable-data-collection-on-startup) - [Example project](#example-project) - [Reporting issues](#reporting-issues) - [Reporting a bug or problem](#reporting-a-bug-or-problem) - [Requesting a new feature](#requesting-a-new-feature) - [Cloud messaging](#cloud-messaging) - [Background notifications](#background-notifications) - [Foreground notifications](#foreground-notifications) - [Android notifications](#android-notifications) - [Android background notifications](#android-background-notifications) - [Android foreground notifications](#android-foreground-notifications) - [Android Notification Channels](#android-notification-channels) - [Android 7 and below](#android-7-and-below) - [Android Notification Icons](#android-notification-icons) - [Android Default Notification Icon](#android-default-notification-icon) - [Android Large Notification Icon](#android-large-notification-icon) - [Android Custom Notification Icons](#android-custom-notification-icons) - [Android Notification Color](#android-notification-color) - [Android Notification Sound](#android-notification-sound) - [Android 8.0 and above](#android-80-and-above) - [On Android 7 and below](#on-android-7-and-below) - [iOS notifications](#ios-notifications) - [iOS background notifications](#ios-background-notifications) - [iOS notification sound](#ios-notification-sound) - [iOS badge number](#ios-badge-number) - [Data messages](#data-messages) - [Data message notifications](#data-message-notifications) - [Android data message notifications](#android-data-message-notifications) - [iOS data message notifications](#ios-data-message-notifications) - [Custom FCM message handling](#custom-fcm-message-handling) - [Android](#android) - [iOS](#ios) - [Example](#example) - [InApp Messaging](#inapp-messaging) - [Google Tag Manager](#google-tag-manager) - [Android](#android-1) - [iOS](#ios-1) - [API](#api) - [Notifications and data messages](#notifications-and-data-messages) - [getToken](#gettoken) - [getId](#getid) - [onTokenRefresh](#ontokenrefresh) - [getAPNSToken](#getapnstoken) - [onApnsTokenReceived](#onapnstokenreceived) - [onMessageReceived](#onmessagereceived) - [grantPermission](#grantpermission) - [hasPermission](#haspermission) - [unregister](#unregister) - [isAutoInitEnabled](#isautoinitenabled) - [setAutoInitEnabled](#setautoinitenabled) - [setBadgeNumber](#setbadgenumber) - [getBadgeNumber](#getbadgenumber) - [clearAllNotifications](#clearallnotifications) - [subscribe](#subscribe) - [unsubscribe](#unsubscribe) - [createChannel](#createchannel) - [setDefaultChannel](#setdefaultchannel) - [Default Android Channel Properties](#default-android-channel-properties) - [deleteChannel](#deletechannel) - [listChannels](#listchannels) - [Analytics](#analytics) - [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled) - [isAnalyticsCollectionEnabled](#isanalyticscollectionenabled) - [logEvent](#logevent) - [setScreenName](#setscreenname) - [setUserId](#setuserid) - [setUserProperty](#setuserproperty) - [Crashlytics](#crashlytics) - [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled) - [isCrashlyticsCollectionEnabled](#iscrashlyticscollectionenabled) - [isCrashlyticsCollectionCurrentlyEnabled](#iscrashlyticscollectioncurrentlyenabled) - [setCrashlyticsUserId](#setcrashlyticsuserid) - [sendCrash](#sendcrash) - [logMessage](#logmessage) - [logError](#logerror) - [Authentication](#authentication) - [isUserSignedIn](#isusersignedin) - [signOutUser](#signoutuser) - [getCurrentUser](#getcurrentuser) - [reloadCurrentUser](#reloadcurrentuser) - [updateUserProfile](#updateuserprofile) - [updateUserEmail](#updateuseremail) - [sendUserEmailVerification](#senduseremailverification) - [updateUserPassword](#updateuserpassword) - [sendUserPasswordResetEmail](#senduserpasswordresetemail) - [deleteUser](#deleteuser) - [createUserWithEmailAndPassword](#createuserwithemailandpassword) - [signInUserWithEmailAndPassword](#signinuserwithemailandpassword) - [signInUserWithCustomToken](#signinuserwithcustomtoken) - [signInUserAnonymously](#signinuseranonymously) - [verifyPhoneNumber](#verifyphonenumber) - [Android](#android-2) - [iOS](#ios-2) - [authenticateUserWithGoogle](#authenticateuserwithgoogle) - [Android](#android-3) - [authenticateUserWithApple](#authenticateuserwithapple) - [iOS](#ios-3) - [Android](#android-4) - [signInWithCredential](#signinwithcredential) - [linkUserWithCredential](#linkuserwithcredential) - [reauthenticateWithCredential](#reauthenticatewithcredential) - [registerAuthStateChangeListener](#registerauthstatechangelistener) - [Remote Config](#remote-config) - [fetch](#fetch) - [activateFetched](#activatefetched) - [getValue](#getvalue) - [getByteArray](#getbytearray) - [getInfo](#getinfo) - [setConfigSettings](#setconfigsettings) - [setDefaults](#setdefaults) - [Performance](#performance) - [setPerformanceCollectionEnabled](#setperformancecollectionenabled) - [isPerformanceCollectionEnabled](#isperformancecollectionenabled) - [startTrace](#starttrace) - [incrementCounter](#incrementcounter) - [stopTrace](#stoptrace) - [Firestore](#firestore) - [addDocumentToFirestoreCollection](#adddocumenttofirestorecollection) - [setDocumentInFirestoreCollection](#setdocumentinfirestorecollection) - [updateDocumentInFirestoreCollection](#updatedocumentinfirestorecollection) - [deleteDocumentFromFirestoreCollection](#deletedocumentfromfirestorecollection) - [documentExistsInFirestoreCollection](#documentexistsinfirestorecollection) - [fetchDocumentInFirestoreCollection](#fetchdocumentinfirestorecollection) - [fetchFirestoreCollection](#fetchfirestorecollection) - [Credits](#credits) # Installation Install the plugin by adding it to your project's config.xml: ```xml ``` or by running: ``` cordova plugin add cordova-plugin-firebasex ``` ## Plugin variables The following Cordova plugin variables are supported by the plugin. Note that these must be set at plugin installation time. If you wish to change plugin variables, you'll need to uninstall the plugin and reinstall it with the new variable values. ### Android & iOS - `FIREBASE_ANALYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Analytics data collection on app startup - `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` - whether to automatically enable Firebase Performance data collection on app startup - `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Crashlytics data collection on app startup See [Disable data collection on startup](#disable-data-collection-on-startup) for more info. ### Android only The following plugin variables are used to specify the Firebase SDK versions as Gradle dependencies on Android: - `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` - `ANDROID_PLAY_SERVICES_AUTH_VERSION` - `ANDROID_FIREBASE_ANALYTICS_VERSION` - `ANDROID_FIREBASE_MESSAGING_VERSION` - `ANDROID_FIREBASE_CONFIG_VERSION` - `ANDROID_FIREBASE_PERF_VERSION` - `ANDROID_FIREBASE_AUTH_VERSION` - `ANDROID_FIREBASE_FIRESTORE_VERSION` - `ANDROID_CRASHLYTICS_VERSION` - `ANDROID_CRASHLYTICS_NDK_VERSION` - `ANDROID_GSON_VERSION` See [Specifying Android library versions](#specifying-android-library-versions) for more info. - `ANDROID_ICON_ACCENT` - sets the default accent color for system notifications. See [Android Notification Color](#android-notification-color) for more info. ### iOS only - `IOS_STRIP_DEBUG` - prevents symbolification of all libraries included via Cocoapods. See [Strip debug symbols](#strip-debug-symbols) for more info. - e.g. `--variable IOS_STRIP_DEBUG=true` - Defaults to `false` if not specified. - `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info. - e.g. `--variable IOS_STRIP_DEBUG=true` - Defaults to `false` if not specified. - `IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL` - If `true` Firebase Messaging will automatically establish a socket-based, direct channel to the FCM server. - e.g. `--variable IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL=true` - Defaults to `false` if not specified. - See [`shouldEstablishDirectChannel`](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/c:objc(cs)FIRMessaging(py)shouldEstablishDirectChannel) - Note: Firebase Messaging iOS SDK version 7.0 will be a breaking change where the SDK will no longer support iOS Direct Channel API. ## Supported Cordova Versions - cordova: `>= 9` - cordova-android: `>= 8` - cordova-ios: `>= 5` ## Supported Mobile Platform Versions - Android `>= 4.1` - iOS `>= 10.0` ## Migrating from cordova-plugin-firebase This plugin is a fork of [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) which has been reworked to fix issues and add new functionality. If you already have [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) installed in your Cordova project, you need to completely remove it before installing this plugin otherwise they will conflict and cause build errors in your project. The safest way of doing this is as follows: rm -Rf platforms/android cordova plugin rm cordova-plugin-firebase rm -Rf plugins/ node_modules/ npm install cordova plugin add cordova-plugin-firebasex cordova platform add android ### Breaking API changes **IMPORTANT:** Recent versions of `cordova-plugin-firebasex` have made breaking changes to the plugin API in order to fix bugs or add more functionality. Therefore you can no longer directly substitute `cordova-plugin-firebasex` in place of `cordova-plugin-firebase` without making code changes. You should be aware of the following breaking changes compared with `cordova-plugin-firebase`: * Minimum supported Cordova versions * `cordova@9` (CLI) * `cordova-android@8` (Android platform) * `cordova-ios@5` (iOS platform) * Migrated to AndroidX from legacy Android Support Library * add dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) and [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) * Migrated to Cocoapods to satisfy Firebase SDK dependencies on iOS * `onNotificationOpen()` renamed to `onMessageReceived()` * `tap` parameter is only set when user taps on a notification (not when a message is received from FCM) * `tap=foreground|background` instead of `tap=true|false` * `hasPermission()` receives argument as a boolean (rather than an object with `isEnabled` key) * e.g. `FirebasePlugin.hasPermission(function(hasPermission){ console.log("Permission is " + (hasPermission ? "granted" : "denied")); });` * Adds support for foreground notifications and data notification messages ### Ionic 4+ Ionic Native provides a [FirebaseX Typescript wrapper](https://ionicframework.com/docs/native/firebase-x) for using `cordova-plugin-firebasex` with Ionic v4, v5 and above. Please see their documentation for usage. First install the package. ``` ionic cordova plugin add cordova-plugin-firebasex npm install @ionic-native/firebase-x ``` If you're using Angular, register it in your component/service's `NgModule` (for example, app.module.ts) as a provider. ```typescript import { FirebaseX } from "@ionic-native/firebase-x/ngx"; @NgModule({ //declarations, imports... providers: [ FirebaseX, //other providers... ] }) ``` Then you're good to go. ```typescript import { FirebaseX } from "@ionic-native/firebase-x/ngx"; //... constructor(private firebase: FirebaseX) this.firebase.getToken().then(token => console.log(`The token is ${token}`)) this.firebase.onMessageReceived().subscribe(data => console.log(`FCM message: ${data}`)); ``` **NOTE:** - This plugin provides only the Javascript API as documented below. - The Typescript wrapper is owned and maintain by Ionic. - Please [report any issues](https://github.com/ionic-team/ionic-native/issues) against the [Ionic Native repo](https://github.com/ionic-team/ionic-native/), not this one. - Any issues opened against this repo which relate to the Typescript wrapper **will be closed immediately**. ### Ionic 3 The above PR does not work for Ionic 3 so you (currently) can't use the [Ionic Native Firebase](https://ionicframework.com/docs/native/firebase) Typescript wrapper with Ionic 3. (i.e. `import { Firebase } from "@ionic-native/firebase"` will not work). To use `cordova-plugin-firebasex` with Ionic 3, you'll need to call its Javascript API directly from your Typescript app code, for example: ```typescript (window).FirebasePlugin.getToken(token => console.log(`token: ${token}`)) (window).FirebasePlugin.onMessageReceived((message) => { if (message.tap) { console.log(`Notification was tapped in the ${message.tap}`); } }) ``` If you want to make the `onMessageReceived()` JS API behave like the Ionic Native wrapper: ```javascript onNotificationOpen() { return new Observable(observer => { (window as any).FirebasePlugin.onMessageReceived((response) => { observer.next(response); }); }); } ... this.onNotificationOpen().subscribe(data => console.log(`FCM message: ${data}`)); ``` See the [cordova-plugin-firebasex-ionic3-test](https://github.com/dpa99c/cordova-plugin-firebasex-ionic3-test) example project for a demonstration of how to use the plugin with Ionic 3. # Build environment notes ## PhoneGap Build This plugin will not work with Phonegap Build (and other remote cloud build envs) do not support Cordova hook scripts as they are used by this plugin to configure the native platform projects. ## Android-specific ### Specifying Android library versions This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Gradle on Android. By default this plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned versions as ``'s, for example: ```xml ``` The Android defaults can be overridden at plugin installation time by specifying plugin variables as command-line arguments, for example: cordova plugin add cordova-plugin-firebasex --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 Or you can specify them as plugin variables in your `config.xml`, for example: ```xml ``` The following plugin variables are used to specify the following Gradle dependency versions on Android: - `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` => `com.google.android.gms:play-services-tagmanager` - `ANDROID_PLAY_SERVICES_AUTH_VERSION` => `com.google.android.gms:play-services-auth` - `ANDROID_FIREBASE_ANALYTICS_VERSION` => `com.google.firebase:firebase-analytics` - `ANDROID_FIREBASE_MESSAGING_VERSION` => `com.google.firebase:firebase-messaging` - `ANDROID_FIREBASE_CONFIG_VERSION` => `com.google.firebase:firebase-config` - `ANDROID_FIREBASE_PERF_VERSION` => `com.google.firebase:firebase-perf` - `ANDROID_FIREBASE_AUTH_VERSION` => `com.google.firebase:firebase-auth` - `ANDROID_FIREBASE_FIRESTORE_VERSION` => `com.google.firebase:firebase-firestore` - `ANDROID_CRASHLYTICS_VERSION` => `com.crashlytics.sdk.android:crashlytics` - `ANDROID_CRASHLYTICS_NDK_VERSION` => `com.crashlytics.sdk.android:crashlytics-ndk` - `ANDROID_GSON_VERSION` => `com.google.code.gson:gson` For example: cordova plugin add cordova-plugin-firebasex \ --variable ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION=17.0.0 \ --variable ANDROID_PLAY_SERVICES_AUTH_VERSION=17.0.0 \ --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 \ --variable ANDROID_FIREBASE_MESSAGING_VERSION=19.0.0 \ --variable ANDROID_FIREBASE_CONFIG_VERSION=18.0.0 \ --variable ANDROID_FIREBASE_PERF_VERSION=18.0.0 \ --variable ANDROID_FIREBASE_AUTH_VERSION=18.0.0 \ --variable ANDROID_CRASHLYTICS_VERSION=2.10.1 \ --variable ANDROID_CRASHLYTICS_NDK_VERSION=2.1.0 \ ### AndroidX This plugin has been migrated to use [AndroidX (Jetpack)](https://developer.android.com/jetpack/androidx/migrate) which is the successor to the [Android Support Library](https://developer.android.com/topic/libraries/support-library/index). This is implemented by adding a dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) which enables AndroidX in the Android platform of a Cordova project. This is because the [major release of the Firebase and Play Services libraries on 17 June 2019](https://developers.google.com/android/guides/releases#june_17_2019) were migrated to AndroidX. Therefore if your project includes any plugins which are dependent on the legacy Android Support Library, you should add [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) to your project. This plugin will dynamically migrate any plugin code from the Android Support Library to AndroidX equivalents. ## Google Play Services and Firebase libraries Your Android build may fail if you are installing multiple plugins that use the Google Play Services library. This is caused by plugins installing different versions of the Google Play Services library. This can be resolved by installing [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) which enables you to override the versions specified by other plugins in order to align them. Similarly, if your build is failing because multiple plugins are installing different versions of the Firebase library, you can try installing [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release) to align these. ## iOS-specific ### Specifying iOS library versions This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Cocoapods on iOS. This plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned iOS versions in the ``'s, for example: **It is currently not possible to override these at plugin installation time** because `cordova@9`/`cordova-ios@5` does not support the use of plugin variables in the ``'s `spec` attribute. Therefore if you need to change the specified versions, you'll currently need to do this by forking the plugin and editing the `plugin.xml` to change the specified `spec` values. ### Cocoapods This plugin relies on `cordova@9`/`cordova-ios@5` support for the [CocoaPods dependency manager]( https://cocoapods.org/) in order to satisfy the iOS Firebase SDK library dependencies. Therefore please make sure you have Cocoapods@>=1.8 installed in your iOS build environment - setup instructions can be found [here](https://cocoapods.org/). If building your project in Xcode, you need to open `YourProject.xcworkspace` (not `YourProject.xcodeproj`) so both your Cordova app project and the Pods project will be loaded into Xcode. You can list the pod dependencies in your Cordova iOS project by installing [cocoapods-dependencies](https://github.com/segiddins/cocoapods-dependencies): sudo gem install cocoapods-dependencies cd platforms/ios/ pod dependencies ### Out-of-date pods If you receive a build error such as this: None of your spec sources contain a spec satisfying the dependencies: `Firebase/Analytics (~> 6.1.0), Firebase/Analytics (= 6.1.0, ~> 6.1.0)`. Make sure your local Cocoapods repo is up-to-date by running `pod repo update` then run `pod install` in `/your_project/platforms/ios/`. ### Strip debug symbols If your iOS app build contains too many debug symbols (i.e. because you include lots of libraries via a Cocoapods), you might get an error (e.g. [issue #28](https://github.com/dpa99c/cordova-plugin-firebase/issues/28)) when you upload your binary to App Store Connect, e.g.: ITMS-90381: Too many symbol files - These symbols have no corresponding slice in any binary [16EBC8AC-DAA9-39CF-89EA-6A58EB5A5A2F.symbols, 1B105D69-2039-36A4-A04D-96C1C5BAF235.symbols, 476EACDF-583B-3B29-95B9-253CB41097C8.symbols, 9789B03B-6774-3BC9-A8F0-B9D44B08DCCB.symbols, 983BAE60-D245-3291-9F9C-D25E610846AC.symbols]. To prevent this, you can set the `IOS_STRIP_DEBUG` plugin variable which prevents symbolification of all libraries included via Cocoapods ([see here for more information](https://stackoverflow.com/a/48518656/777265)): cordova plugin add cordova-plugin-firebasex --variable IOS_STRIP_DEBUG=true By default this preference is set to `false`. Note: if you enable this setting, any crashes that occur within libraries included via Cocopods will not be recorded in Crashlytics or other crash reporting services. ### Cordova CLI builds If you are building (directly or indirectly) via the Cordova CLI and encounter build failures on iOS, this is likely due to [an issue with Cordova CLI builds for iOS](https://github.com/apache/cordova-ios/issues/659) when including certain pods into the build (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). Note that building from Xcode works fine, so if you are able then do this. Otherwise (e.g. if building via a CI) then you'll need to switch to using the [cli_build branch](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) of this plugin which removes the Firebase Inapp Messaging and Google Tag Manager SDK components that are causing the build issues. # Firebase config setup There's a handy [installation and setup guide on medium.com](https://medium.com/@felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821). However, if using this, remember this forked plugin is `cordova-plugin-firebasex` (not `cordova-plugin-firebase`). Download your Firebase configuration files, `GoogleService-Info.plist` for iOS and `google-services.json` for android, and place them in the root folder of your cordova project. Check out this [firebase article](https://support.google.com/firebase/answer/7015592) for details on how to download the files. ``` - My Project/ platforms/ plugins/ www/ config.xml google-services.json <-- GoogleService-Info.plist <-- ... ``` IMPORTANT: The Firebase SDK requires the configuration files to be present and valid, otherwise your app will crash on boot or Firebase features won't work. # Disable data collection on startup By default, analytics, performance and Crashlytics data will begin being collected as soon as the app starts up. However, for data protection or privacy reasons, you may wish to disable data collection until such time as the user has granted their permission. To do this, set the following plugin variables to `false` at plugin install time: * `FIREBASE_ANALYTICS_COLLECTION_ENABLED` * `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` * `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` cordova plugin add cordova-plugin-firebasex \ --variable FIREBASE_ANALYTICS_COLLECTION_ENABLED=false \ --variable FIREBASE_PERFORMANCE_COLLECTION_ENABLED=false \ --variable FIREBASE_CRASHLYTICS_COLLECTION_ENABLED=false This will disable data collection (on both Android & iOS) until you call [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled), [setPerformanceCollectionEnabled](#setperformancecollectionenabled) and [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled): FirebasePlugin.setAnalyticsCollectionEnabled(true); FirebasePlugin.setPerformanceCollectionEnabled(true); FirebasePlugin.setCrashlyticsCollectionEnabled(true); Notes: - Calling `setXCollectionEnabled()` will have no effect if the corresponding `FIREBASE_X_COLLECTION_ENABLED` variable is set to `true`. - Calling `setAnalyticsCollectionEnabled(true|false)` or `setPerformanceCollectionEnabled(true|false)` will enable/disable data collection during the current app session and across subsequent app sessions until such time as the same method is called again with a different value. - Calling `setCrashlyticsCollectionEnabled(true|false)` will enable/disable data collection during subsequent app sessions until such time as the same method is called again with a different value. It **does not** affect the current app session. # Example project An example project repo exists to demonstrate and validate the functionality of this plugin: https://github.com/dpa99c/cordova-plugin-firebasex-test Please use this as a working reference. Before reporting any issues, please (if possible) test against the example project to rule out causes external to this plugin. # Reporting issues **IMPORTANT:** Please read the following carefully. Failure to follow the issue template guidelines below will result in the issue being immediately closed. ## Reporting a bug or problem Before [opening a bug issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=bug_report.md&title=), please do the following: - *DO NOT* open issues asking for support in using/integrating the plugin into your project - Only open issues for suspected bugs/issues with the plugin that are generic and will affect other users - I don't have time to offer free technical support: this is free open-source software - Ask for help on StackOverflow, Ionic Forums, etc. - Use the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) as a known working reference - Any issues requesting support will be closed immediately. - *DO NOT* open issues related to the [Ionic Typescript wrapper for this plugin](https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/firebase-x/index.ts) - This is owned/maintained by [Ionic](https://github.com/ionic-team) and is not part of this plugin - Please raise such issues/PRs against [Ionic Native](https://github.com/ionic-team/ionic-native/) instead. - To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper). - Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately. - If you are migrating from [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section. - Read the above documentation thoroughly - For example, if you're having a build issue ensure you've read through the [build environment notes](#build-environment-notes) - If an iOS CLI build is failing, ensure you've read the [Cordova CLI builds](#cordova-cli-builds) section - Check the [CHANGELOG](https://github.com/dpa99c/cordova-plugin-firebasex/blob/master/CHANGELOG.md) for any breaking changes that may be causing your issue. - Check a similar issue (open or closed) does not already exist against this plugin. - Duplicates or near-duplicates will be closed immediately. - When [creating a new issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new/choose) - Choose the "Bug report" template - Fill out the relevant sections of the template and delete irrelevant sections - *WARNING:* Failure to complete the issue template will result in the issue being closed immediately. - Reproduce the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) - This will eliminate bugs in your code or conflicts with other code as possible causes of the issue - This will also validate your development environment using a known working codebase - If reproducing the issue using the example project is not possible, create an isolated test project that you are able to share - Include full verbose console output when reporting build issues - If the full console output is too large to insert directly into the Github issue, then post it on an external site such as [Pastebin](https://pastebin.com/) and link to it from the issue - Often the details of an error causing a build failure is hidden away when building with the CLI - To get the full detailed console output, append the `--verbose` flag to CLI build commands - e.g. `cordova build ios --verbose` - Failure to include the full console output will result in the issue being closed immediately - If the issue relates to the plugin documentation (and not the code), please of a [documentation issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=documentation-issue.md&title=) ## Requesting a new feature Before [opening a feature request issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=feature_request.md&title=), please do the following: - Check the above documentation to ensure the feature you are requesting doesn't already exist - Check the list if open/closed issues to check if there's a reason that feature hasn't been included already - Ensure the feature you are requesting is actually possible to implement and generically useful to other users than yourself - Where possible, post a link to the documentation related to the feature you are requesting - Include other relevant links, e.g. - Stack Overflow post illustrating a solution - Code within another Github repo that illustrates a solution # Cloud messaging

 

There are 2 distinct types of messages that can be sent by Firebase Cloud Messaging (FCM): - [Notification messages](https://firebase.google.com/docs/cloud-messaging/concept-options#notifications) - automatically displayed to the user by the operating system on behalf of the client app **while your app is not running or is in the background** - **if your app is in the foreground when the notification message arrives**, it is passed to the client app and it is the responsibility of the client app to display it. - have a predefined set of user-visible keys and an optional data payload of custom key-value pairs. - [Data messages](https://firebase.google.com/docs/cloud-messaging/concept-options#data_messages) - Client app is responsible for processing data messages. - Data messages have only custom key-value pairs. Note: only notification messages can be sent via the Firebase Console - data messages must be sent via the [FCM APIs](https://firebase.google.com/docs/cloud-messaging/server). ## Background notifications If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. By default, no callback is made to the plugin when the message arrives while the app is not in the foreground, since the display of the notification is entirely handled by the operating system. However, there are platform-specific circumstances where a callback can be made when the message arrives and the app is in the background that don't require user interaction to receive the message payload - see [Android background notifications](#android-background-notifications) and [iOS background notifications](#ios-background-notifications) for details. If the user taps the system notification, this launches/resumes the app and the notification title, body and optional data payload is passed to the [onMessageReceived](#onMessageReceived) callback. When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the background/not running, it will be passed the property `tap: "background"`. ## Foreground notifications If the notification message arrives while the app is in running in the foreground, by default **it will NOT be displayed as a system notification**. Instead the notification message payload will be passed to the [onMessageReceived](#onMessageReceived) callback for the plugin to handle (`tap` will not be set). If you include the `notification_foreground` key in the `data` payload, the plugin will also display a system notification upon receiving the notification messages while the app is running in the foreground. For example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "data": { "notification_foreground": "true", } } ``` When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the foreground, it will be passed the property `tap: "foreground"`. You can set additional properties of the foreground notification using the same key names as for [Data Message Notifications](#data-message-notification-keys). ## Android notifications Notifications on Android can be customised to specify the sound, icon, LED colour, etc. that's displayed when the notification arrives. ### Android background notifications If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. If a notification message arrives while the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. In addition to the title and body of the notification message, Android system notifications support specification of the following notification settings: - [Icon](#android-notification-icons) - [Sound](#android-notification-sound) - [Color accent](#android-notification-color) - [Channel ID](#android-notification-channels) (Android 8.0 (O) and above) - This channel configuration enables you to specify: - Sound - Vibration - LED light - Badge - Importance - Visibility - See [createChannel](#createchannel) for details. Note: on tapping a background notification, if your app is not running, only the `data` section of the notification message payload will be delivered to [onMessageReceived](#onMessageReceived). i.e. the notification title, body, etc. will not. Therefore if you need the properties of the notification message itself (e.g. title & body) to be delivered to [onMessageReceived](#onMessageReceived), you must duplicate these in the `data` section, e.g.: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "data": { "notification_body": "Notification body", "notification_title": "Notification title" } } ``` ### Android foreground notifications If the notification message arrives while the app is in the foreground, by default a system notification won't be displayed and the data will be passed to [onMessageReceived](#onMessageReceived). However, if you set the `notification_foreground` key in the `data` section of the notification message payload, this will cause the plugin to display system notification when the message is received while your app is in the foreground. You can customise the notification using the same keys as for [Android data message notifications](#android-data-message-notifications). ### Android Notification Channels - Android 8 (O) introduced [notification channels](https://developer.android.com/training/notify-user/channels). - Notification channels are configured by the app and used to determine the **sound/lights/vibration** settings of system notifications. - By default, this plugin creates a default channel with [default properties](#default-android-channel-properties) - These can be overridden via the [setDefaultChannel](#setdefaultchannel) function. - The plugin enables the creation of additional custom channels via the [createChannel](#createchannel) function. First you need to create a custom channel with the desired settings, for example: ```javascript var channel = { id: "my_channel_id", sound: "mysound", vibration: true, light: true, lightColor: parseInt("FF0000FF", 16).toString(), importance: 4, badge: true, visibility: 1 }; FirebasePlugin.createChannel(channel, function(){ console.log('Channel created: ' + channel.id); }, function(error){ console.log('Create channel error: ' + error); }); ``` Then reference it from your message payload: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "channel_id": "my_channel_id" } } } ``` #### Android 7 and below - the channel referenced in the message payload will be ignored - the sound setting of system notifications is specified in the notification message itself - see [Android Notification Sound](#android-notification-sound). ### Android Notification Icons By default the plugin will use the default app icon for notification messages. #### Android Default Notification Icon To define a custom default notification icon, you need to create the images and deploy them to the `/platforms/android/app/src/main/res/` folders. The easiest way to create the images is using the [Image Asset Studio in Android Studio](https://developer.android.com/studio/write/image-asset-studio#create-notification) or using the [Android Asset Studio webapp](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=notification_icon). The icons should be monochrome transparent PNGs with the following sizes: - mdpi: 24x24 - hdpi: 36x36 - xhdpi: 48x48 - xxhdpi: 72x72 - xxxhdpi: 96x96 Once you've created the images, you need to deploy them from your Cordova project to the native Android project. To do this, copy the `drawable-DPI` image directories into your Cordova project and add `` entries to the `` section of your `config.xml`, where `src` specifies the relative path to the images files within your Cordova project directory. For example, copy the`drawable-DPI` image directories to `/res/android/` and add the following to your `config.xml`: ```xml ``` The default notification icon images **must** be named `notification_icon.png`. You then need to add a `` block to the `config.xml` which will instruct Firebase to use your icon as the default for notifications: ```xml ``` #### Android Large Notification Icon The default notification icons above are monochrome, however you can additionally define a larger multi-coloured icon. **NOTE:** FCM currently does not support large icons in system notifications displayed for notification messages received in the while the app is in the background (or not running). So the large icon will currently only be used if specified in [data messages](#android-data-messages) or [foreground notifications](#foreground-notifications). The large icon image should be a PNG-24 that's 256x256 pixels and must be named `notification_icon_large.png` and should be placed in the `drawable-xxxhdpi` resource directory. As with the small icons, you'll need to add a `` entry to the `` section of your `config.xml`: ```xml ``` #### Android Custom Notification Icons You can define additional sets of notification icons in the same manner as above. These can be specified in notification or data messages. For example: ```xml ``` When sending an FCM notification message, you will then specify the icon name in the `android.notification` section, for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "icon": "my_icon", } }, "data": { "notification_foreground": "true", } } ``` You can also reference these icons in [data messages](#android-data-messages), for example: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_icon": "my_icon", } } ``` ### Android Notification Color On Android Lollipop (5.0/API 21) and above you can set the default accent color for the notification by adding a color setting. This is defined as an [ARGB colour](https://en.wikipedia.org/wiki/RGBA_color_space#ARGB_(word-order)) which the plugin sets by default to `#FF00FFFF` (cyan). Note: On Android 7 and above, the accent color can only be set for the notification displayed in the system tray area - the icon in the statusbar is always white. You can override this default by specifying a value using the `ANDROID_ICON_ACCENT` plugin variable during plugin installation, for example: cordova plugin add cordova-plugin-firebasex --variable ANDROID_ICON_ACCENT=#FF123456 You can override the default color accent by specifying the `colour` key as an RGB value in a notification message, e.g.: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "color": "#00ff00" } } } ``` And in a data message: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_color": "#00ff00" } } ``` ### Android Notification Sound You can specify custom sounds for notifications or play the device default notification sound. Custom sound files must be in `.mp3` format and deployed to the `/res/raw` directory in the Android project. To do this, you can add `` tags to your `config.xml` to deploy the files, for example: ```xml ``` To ensure your custom sounds works on all versions of Android, be sure to include both the channel name and sound name in your message payload (see below for details), for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "channel_id": "my_channel_id", "sound": "my_sound" } } } ``` #### Android 8.0 and above On Android 8.0 and above, the notification sound is specified by which [Android notification channel](#android-notification-channels) is referenced in the notification message payload. First create a channel that references your sound, for example: ```javascript var channel = { id: "my_channel_id", sound: "my_sound" }; FirebasePlugin.createChannel(channel, function(){ console.log('Channel created: ' + channel.id); }, function(error){ console.log('Create channel error: ' + error); }); ``` Then reference that channel in your message payload: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "channel_id": "my_channel_id" } } } ``` #### On Android 7 and below On Android 7 and below, you need to specify the sound file name in the `android.notification` section of the message payload. For example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "sound": "my_sound" } } } ``` And in a data message by specifying it in the `data` section: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_sound": "my_sound" } } ``` - To play the default notification sound, set `"sound": "default"`. - To display a silent notification (no sound), omit the `sound` key from the message. ## iOS notifications Notifications on iOS can be customised to specify the sound and badge number that's displayed when the notification arrives. Notification settings are specified in the `apns.payload.aps` key of the notification message payload. For example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "apns": { "payload": { "aps": { "sound": "default", "badge": 1, "content-available": 1 } } } } ``` ### iOS background notifications If the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback can be invoked when the message arrives without requiring user interaction (i.e. tapping the system notification). To do this you must specify `"content-available": 1` in the `apns.payload.aps` section of the message payload - see the [Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW8) for more information. When the message arrives, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. ### iOS notification sound You can specify custom sounds for notifications or play the device default notification sound. Custom sound files must be in a supported audio format (see [this Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW10) for supported formats). For example to convert an `.mp3` file to the supported `.caf` format run: afconvert my_sound.mp3 my_sound.caf -d ima4 -f caff -v Sound files must be deployed with the iOS application bundle. To do this, you can add `` tags to your `config.xml` to deploy the files, for example: ```xml ``` In a notification message, specify the `sound` key in the `apns.payload.aps` section, for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "apns": { "payload": { "aps": { "sound": "my_sound.caf" } } } } ``` - To play the default notification sound, set `"sound": "default"`. - To display a silent notification (no sound), omit the `sound` key from the message. In a data message, specify the `notification_ios_sound` key in the `data` section: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_ios_sound": "my_sound.caf" } } ``` ### iOS badge number In a notification message, specify the `badge` key in the `apns.payload.aps` section, for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "apns": { "payload": { "aps": { "badge": 1 } } } } ``` In a data message, specify the `notification_ios_badge` key in the `data` section: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_ios_badge": 1 } } ``` ## Data messages FCM data messages are sent as an arbitrary k/v structure and by default are passed to the app for it to handle them. **NOTE:** FCM data messages **cannot** be sent from the Firebase Console - they can only be sent via the FCM APIs. ### Data message notifications This plugin enables a data message to be displayed as a system notification. To have the app display a notification when the data message arrives, you need to set the `notification_foreground` key in the `data` section. You can then set a `notification_title` and `notification_body`, for example: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "foo" : "bar" } } ``` Additional platform-specific notification options can be set using the additional keys below (which are only relevant if the `notification_foreground` key is set). Note: [foreground notification messages](#foreground-notifications) can also make use of these keys. #### Android data message notifications On Android: - Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. - Data messages (not containing notification keys) that arrive while your app is **not running** will be passed to the `onMessageReceived()` Javascript handler when the app is next launched. - Data messages containing notification keys that arrive while your app is running or **not running** will be displayed as a system notification. The following Android-specific keys are supported and should be placed inside the `data` section: - `notification_android_icon` - name of a [custom notification icon](#android-custom-notification-icons) in the drawable resources - if not specified, the plugin will use the default `notification_icon` if it exists; otherwise the default app icon will be displayed - if a [large icon](#android-large-notification-icon) has been defined, it will also be displayed in the system notification. - `notification_android_color` - the [color accent](#android-notification-color) to use for the small notification icon - if not specified, the default color accent will be used - `notification_android_channel_id` - ID of the [notification channel](#android-notification-channels) to use to display the notification - Only applies to Android 8.0 and above - If not specified, the [default notification channel](#default-android-channel-properties) will be used. - You can override the default configuration for the default notification channel using [setDefaultChannel](#setdefaultchannel). - You can create additional channels using [createChannel](#createchannel). - `notification_android_priority` - Specifies the notification priority - Possible values: - `2` - Highest notification priority for your application's most important items that require the user's prompt attention or input. - `1` - Higher notification priority for more important notifications or alerts. - `0` - Default notification priority. - `-1` - Lower notification priority for items that are less important. - `-2` - Lowest notification priority. These items might not be shown to the user except under special circumstances, such as detailed notification logs. - Defaults to `2` if not specified. - `notification_android_visibility` - Specifies the notification visibility - Possible values: - `1` - Show this notification in its entirety on all lockscreens. - `0` - Show this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. - `-1` - Do not reveal any part of this notification on a secure lockscreen. - Defaults to `1` if not specified. The following keys only apply to Android 7 and below. On Android 8 and above they will be ignored - the `notification_android_channel_id` property should be used to specify a [notification channel](#android-notification-channels) with equivalent settings. - `notification_android_sound` - name of a sound resource to play as the [notification sound](#android-notification-sound) - if not specified, no sound is played - `default` plays the default device notification sound - otherwise should be the name of an `.mp3` file in the `/res/raw` directory, e.g. `my_sound.mp3` => `"sounds": "my_sound"` - `notification_android_lights` - color and pattern to use to blink the LED light - if not defined, LED will not blink - in the format `ARGB, time_on_ms, time_off_ms` where - `ARGB` is an ARGB color definition e.g. `#ffff0000` - `time_on_ms` is the time in milliseconds to turn the LED on for - `time_off_ms` is the time in milliseconds to turn the LED off for - e.g. `"lights": "#ffff0000, 250, 250"` - `notification_android_vibrate` - pattern of vibrations to use when the message arrives - if not specified, device will not vibrate - an array of numbers specifying the time in milliseconds to vibrate - e.g. `"vibrate": "500, 200, 500"` Example data message with Android notification keys: ```json { "name": "my_data_message", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_channel_id": "my_channel", "notification_android_priority": "2", "notification_android_visibility": "1", "notification_android_color": "#ff0000", "notification_android_icon": "coffee", "notification_android_sound": "my_sound", "notification_android_vibrate": "500, 200, 500", "notification_android_lights": "#ffff0000, 250, 250" } } ``` #### iOS data message notifications On iOS: - Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. - Data messages that arrive while your app is **not running** will **NOT be received by your app!** The following iOS-specific keys are supported and should be placed inside the `data` section: - `notification_ios_sound` - Sound to play when the notification is displayed - To play a custom sound, set the name of the sound file bundled with your app, e.g. `"sound": "my_sound.caf"` - see [iOS notification sound](#ios-notification-sound) for more info. - To play the default notification sound, set `"sound": "default"`. - To display a silent notification (no sound), omit the `sound` key from the message. - `notification_ios_badge` - Badge number to display on app icon on home screen. For example: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_ios_sound": "my_sound.caf", "notification_ios_badge": 1 } } ``` ## Custom FCM message handling In some cases you may want to handle certain incoming FCM messages differently rather than with the default behaviour of this plugin. Therefore this plugin provides a mechanism by which you can implement your own custom FCM message handling for specific FCM messages which bypasses handling of those messages by this plugin. To do this requires you to write native handlers for Android & iOS which hook into the native code of this plugin. ### Android You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/android/FirebasePluginMessageReceiver.java) and implements the `onMessageReceived()` and `sendMessage()` abstract methods. ### iOS You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/ios/FirebasePluginMessageReceiver.h) and implements the `sendNotification()` abstract method. ### Example The [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) contains an [example plugin](https://github.com/dpa99c/cordova-plugin-firebasex-test/tree/master/plugins/cordova-plugin-customfcmreceiver) which implements a custom receiver class for both platforms. You can test this by building and running the example project app, and sending the [notification_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/notification_custom_receiver.json) and [data_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/data_custom_receiver.json) test messages using the [built-in FCM client](https://github.com/dpa99c/cordova-plugin-firebasex-test#messaging-client). # InApp Messaging The Firebase Inapp Messaging SDK component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). If you wish to use Firebase Inapp Messaging, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. # Google Tag Manager The Google Tag Manager component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). If you wish to use Google Tag Manager, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. # API The list of available methods for this plugin is described below. ## Notifications and data messages The plugin is capable of receiving push notifications and FCM data messages. See [Cloud messaging](#cloud-messaging) section for more. ### getToken Get the current FCM token. Null if the token has not been allocated yet by the Firebase SDK. **Parameters**: - {function} success - callback function which will be passed the {string} token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getToken(function(fcmToken) { console.log(fcmToken); }, function(error) { console.error(error); }); ``` Note that token will be null if it has not been established yet. ### getId Get the app instance ID (an constant ID which persists as long as the app is not uninstalled/reinstalled). Null if the ID has not been allocated yet by the Firebase SDK. **Parameters**: - {function} success - callback function which will be passed the {string} ID as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getId(function(appInstanceId) { console.log(appInstanceId); }, function(error) { console.error(error); }); ``` Note that token will be null if it has not been established yet. ### onTokenRefresh Registers a handler to call when the FCM token changes. This is the best way to get the token as soon as it has been allocated. This will be called on the first run after app install when a token is first allocated. It may also be called again under other circumstances, e.g. if `unregister()` is called or Firebase allocates a new token for other reasons. You can use this callback to return the token to you server to keep the FCM token associated with a given user up-to-date. **Parameters**: - {function} success - callback function which will be passed the {string} token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.onTokenRefresh(function(fcmToken) { console.log(fcmToken); }, function(error) { console.error(error); }); ``` ### getAPNSToken iOS only. Get the APNS token allocated for this app install. Note that token will be null if it has not been allocated yet. **Parameters**: - {function} success - callback function which will be passed the {string} APNS token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getAPNSToken(function(apnsToken) { console.log(apnsToken); }, function(error) { console.error(error); }); ``` ### onApnsTokenReceived iOS only. Registers a handler to call when the APNS token is allocated. This will be called once when remote notifications permission has been granted by the user at runtime. **Parameters**: - {function} success - callback function which will be passed the {string} token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.onApnsTokenReceived(function(apnsToken) { console.log(apnsToken); }, function(error) { console.error(error); }); ``` ### onMessageReceived Registers a callback function to invoke when: - a notification or data message is received by the app - a system notification is tapped by the user **Parameters**: - {function} success - callback function which will be passed the {object} message as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.onMessageReceived(function(message) { console.log("Message type: " + message.messageType); if(message.messageType === "notification"){ console.log("Notification message received"); if(message.tap){ console.log("Tapped in " + message.tap); } } console.dir(message); }, function(error) { console.error(error); }); ``` The `message` object passed to the callback function will contain the platform-specific FCM message payload along with the following keys: - `messageType=notification|data` - indicates if received message is a notification or data message - `tap=foreground|background` - set if the call to `onMessageReceived()` was initiated by user tapping on a system notification. - indicates if the system notification was tapped while the app was in the foreground or background. - not set if no system notification was tapped (i.e. message was received directly from FCM rather than via a user tap on a system notification). Notification message flow: 1. App is in foreground: a. By default, when a notification message arrives the app receives the notification message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. 2. App is in background: a. User receives the notification message as a system notification in the device notification bar b. User taps the system notification which launches the app b. User receives the notification message payload in the `onMessageReceived` JavaScript callback Data message flow: 1. App is in foreground: a. By default, when a data message arrives the app receives the data message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. 2. App is in background: a. The app receives the data message in the `onMessageReceived` JavaScript callback while in the background b. If the data message contains the [data message notification keys](#data-message-notifications), the plugin will display a system notification for the data message while in the background. ### grantPermission Grant permission to receive push notifications (will trigger prompt) and return `hasPermission: true`. iOS only (Android will always return true). **Parameters**: - {function} success - callback function which will be passed the {boolean} permission result as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.grantPermission(function(hasPermission){ console.log("Permission was " + (hasPermission ? "granted" : "denied")); }); ``` ### hasPermission Check permission to receive push notifications and return the result to a callback function as boolean. On iOS, returns true is runtime permission for remote notifications is granted and enabled in Settings. On Android, returns true if remote notifications are enabled. **Parameters**: - {function} success - callback function which will be passed the {boolean} permission result as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.hasPermission(function(hasPermission){ console.log("Permission is " + (hasPermission ? "granted" : "denied")); }); ``` ### unregister Unregisters from Firebase by deleting the current device token. Use this to stop receiving push notifications associated with the current token. e.g. call this when you logout user from your app. By default, a new token will be generated as soon as the old one is removed. To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). **Parameters**: None ```javascript FirebasePlugin.unregister(); ``` ### isAutoInitEnabled Indicates whether autoinit is currently enabled. If so, new FCM tokens will be automatically generated. **Parameters**: - {function} success - callback function which will be passed the {boolean} result as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.isAutoInitEnabled(function(enabled){ console.log("Auto init is " + (enabled ? "enabled" : "disabled")); }); ``` ### setAutoInitEnabled Sets whether to autoinit new FCM tokens. By default, a new token will be generated as soon as the old one is removed. To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). **Parameters**: - {boolean} enabled - set true to enable, false to disable - {function} success - callback function to call on successful execution of operation. - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.setAutoInitEnabled(false, function(){ console.log("Auto init has been disabled "); FirebasePlugin.unregister(); }); ``` ### setBadgeNumber iOS only. Set a number on the icon badge: **Parameters**: - {integer} badgeNumber - number to set for the app badge ```javascript FirebasePlugin.setBadgeNumber(3); ``` Set 0 to clear the badge ```javascript FirebasePlugin.setBadgeNumber(0); ``` Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) ### getBadgeNumber iOS only. Get icon badge number: **Parameters**: - {function} success - callback function which will be passed the {integer} current badge number as an argument ```javascript FirebasePlugin.getBadgeNumber(function(n) { console.log(n); }); ``` Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) ### clearAllNotifications Clear all pending notifications from the drawer: **Parameters**: None ```javascript FirebasePlugin.clearAllNotifications(); ``` ### subscribe Subscribe to a topic. Topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. **Parameters**: - {string} topicName - name of topic to subscribe to ```javascript FirebasePlugin.subscribe("latest_news"); ``` ### unsubscribe Unsubscribe from a topic. This will stop you receiving messages for that topic **Parameters**: - {string} topicName - name of topic to unsubscribe from ```javascript FirebasePlugin.unsubscribe("latest_news"); ``` ### createChannel Android 8+ only. Creates a custom channel to be used by notification messages which have the channel property set in the message payload to the `id` of the created channel: - For background (system) notifications: `android.notification.channel_id` - For foreground/data notifications: `data.notification_android_channel_id` For each channel you may set the sound to be played, the color of the phone LED (if supported by the device), whether to vibrate and set vibration pattern (if supported by the device), importance and visibility. Channels should be created as soon as possible (on program start) so notifications can work as expected. A default channel is created by the plugin at app startup; the properties of this can be overridden see [setDefaultChannel](#setdefaultchannel) Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {object} - channel configuration object (see below for object keys/values) - {function} success - callback function which will be call on successful channel creation - {function} error - callback function which will be passed a {string} error message as an argument ```javascript // Define custom channel - all keys are except 'id' are optional. var channel = { // channel ID - must be unique per app package id: "my_channel_id", // Channel description. Default: empty string description: "Channel description", // Channel name. Default: empty string name: "Channel name", //The sound to play once a push comes. Default value: 'default' //Values allowed: //'default' - plays the default notification sound //'ringtone' - plays the currently set ringtone //'false' - silent; don't play any sound //filename - the filename of the sound file located in '/res/raw' without file extension (mysound.mp3 -> mysound) sound: "mysound", //Vibrate on new notification. Default value: true //Possible values: //Boolean - vibrate or not //Array - vibration pattern - e.g. [500, 200, 500] - milliseconds vibrate, milliseconds pause, vibrate, pause, etc. vibration: true, // Whether to blink the LED light: true, //LED color in ARGB format - this example BLUE color. If set to -1, light color will be default. Default value: -1. lightColor: parseInt("FF0000FF", 16).toString(), //Importance - integer from 0 to 4. Default value: 4 //0 - none - no sound, does not show in the shade //1 - min - no sound, only shows in the shade, below the fold //2 - low - no sound, shows in the shade, and potentially in the status bar //3 - default - shows everywhere, makes noise, but does not visually intrude //4 - high - shows everywhere, makes noise and peeks importance: 4, //Show badge over app icon when non handled pushes are present. Default value: true badge: true, //Show message on locked screen. Default value: 1 //Possible values (default 1): //-1 - secret - Do not reveal any part of the notification on a secure lockscreen. //0 - private - Show the notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. //1 - public - Show the notification in its entirety on all lockscreens. visibility: 1 }; // Create the channel FirebasePlugin.createChannel(channel, function(){ console.log('Channel created: ' + channel.id); }, function(error){ console.log('Create channel error: ' + error); }); ``` Example FCM v1 API notification message payload for invoking the above example channel: ```json { "notification": { "title":"Notification title", "body":"Notification body" }, "android": { "notification": { "channel_id": "my_channel_id" } } } ``` If your Android app plays multiple sounds or effects, it's a good idea to create a channel for each likely combination. This is because once a channel is created you cannot override sounds/effects. IE, expanding on the createChannel example: ```javascript let soundList = ["train","woop","clock","radar","sonar"]; for (let key of soundList) { let name = "yourchannelprefix_" + key; channel.id = name; channel.sound = key; channel.name = "Your description " + key; // Create the channel window.FirebasePlugin.createChannel(channel, function(){ console.log('Notification Channel created: ' + channel.id + " " + JSON.stringify(channel)); }, function(error){ console.log('Create notification channel error: ' + error); }); } ``` Note, if you just have one sound / effect combination that the user can customise, just use setDefaultChannel when any changes are made. ### setDefaultChannel Android 8+ only. Overrides the properties for the default channel. The default channel is used if no other channel exists or is specified in the notification. Any options not specified will not be overridden. Should be called as soon as possible (on app start) so default notifications will work as expected. Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {object} - channel configuration object - {function} success - callback function which will be call on successfully setting default channel - {function} error - callback function which will be passed a {string} error message as an argument ```javascript var channel = { id: "my_default_channel", name: "My Default Name", description: "My Default Description", sound: "ringtone", vibration: [500, 200, 500], light: true, lightColor: parseInt("FF0000FF", 16).toString(), importance: 4, badge: false, visibility: -1 }; FirebasePlugin.setDefaultChannel(channel, function(){ console.log('Default channel set'); }, function(error){ console.log('Set default channel error: ' + error); }); ``` ### Default Android Channel Properties The default channel is initialised at app startup with the following default settings: ```json { id: "fcm_default_channel", name: "Default", description: "", sound: "default", vibration: true, light: true, lightColor: -1, importance: 4, badge: true, visibility: 1 } ``` ### deleteChannel Android 8+ only. Removes a previously defined channel. Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {string} - id of channel to delete - {function} success - callback function which will be call on successfully deleting channel - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.deleteChannel("my_channel_id", function(){ console.log('Channel deleted'); }, function(error){ console.log('Delete channel error: ' + error); }); ``` ### listChannels Android 8+ only. Gets a list of all channels. Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {function} success - callback function which will be passed the {array} of channel objects as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.listChannels( function(channels){ if(typeof channels == "undefined") return; for(var i=0;i Android


iOS
## Authentication ### isUserSignedIn Checks if there is a current Firebase user signed into the app. **Parameters**: - {function} success - callback function to pass {boolean} result to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.isUserSignedIn(function(isSignedIn) { console.log("User "+(isSignedIn ? "is" : "is not") + " signed in"); }, function(error) { console.error("Failed to check if user is signed in: " + error); }); ``` ### signOutUser Signs current Firebase user out of the app. **Parameters**: - {function} success - callback function to pass {boolean} result to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.signOutUser(function() { console.log("User signed out"); }, function(error) { console.error("Failed to sign out user: " + error); }); ``` ### getCurrentUser Returns details of the currently logged in user from local Firebase SDK. Note that some user properties will be empty is they are not defined in Firebase for the current user. **Parameters**: - {function} success - callback function to pass user {object} to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getCurrentUser(function(user) { console.log("Name: "+user.name); console.log("Email: "+user.email); console.log("Is email verified?: "+user.emailIsVerified); console.log("Phone number: "+user.phoneNumber); console.log("Photo URL: "+user.photoUrl); console.log("UID: "+user.uid); console.log("Provider ID: "+user.providerId); console.log("ID token: "+user.idToken); }, function(error) { console.error("Failed to get current user data: " + error); }); ``` ### reloadCurrentUser Loads details of the currently logged in user from remote Firebase server. This differs from `getCurrentUser()` which loads the locally cached details which may be stale. For example, if you want to check if a user has verified their email address, this method will guarantee the reported verified state is up-to-date. **Parameters**: - {function} success - callback function to pass user {object} to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.reloadCurrentUser(function(user) { console.log("Name: "+user.name); console.log("Email: "+user.email); console.log("Is email verified?: "+user.emailIsVerified); console.log("Phone number: "+user.phoneNumber); console.log("Photo URL: "+user.photoUrl); console.log("UID: "+user.uid); console.log("Provider ID: "+user.providerId); console.log("ID token: "+user.idToken); }, function(error) { console.error("Failed to reload current user data: " + error); }); ``` ### updateUserProfile Updates the display name and/or photo URL of the current Firebase user signed into the app. **Parameters**: - {object} profile - new profile details: - {string} name - display name of user - {string} photoUri - URL of user profile photo - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.updateUserProfile({ name: "Homer Simpson", photoUri: "http://homer.simpson.com/photo.png" },function() { console.log("User profile successfully updated"); }, function(error) { console.error("Failed to update user profile: " + error); }); ``` ### updateUserEmail Updates/sets the email address of the current Firebase user signed into the app. **Parameters**: - {string} email - email address of user - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.updateUserEmail("user@somewhere.com",function() { console.log("User email successfully updated"); }, function(error) { console.error("Failed to update user email: " + error); }); ``` ### sendUserEmailVerification Sends a verification email to the currently configured email address of the current Firebase user signed into the app. When the user opens the contained link, their email address will have been verified. **Parameters**: - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.sendUserEmailVerification(function() { console.log("User verification email successfully sent"); }, function(error) { console.error("Failed to send user verification email: " + error); }); ``` ### updateUserPassword Updates/sets the account password for the current Firebase user signed into the app. **Parameters**: - {string} password - user-defined password - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.updateUserPassword("mypassword",function() { console.log("User password successfully updated"); }, function(error) { console.error("Failed to update user password: " + error); }); ``` ### sendUserPasswordResetEmail Sends a password reset email to the specified user email address. Note: doesn't require the Firebase user to be signed in to the app. **Parameters**: - {string} email - email address of user - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.sendUserPasswordResetEmail("user@somewhere.com",function() { console.log("User password reset email sent successfully"); }, function(error) { console.error("Failed to send user password reset email: " + error); }); ``` ### deleteUser Deletes the account of the current Firebase user signed into the app. **Parameters**: - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.deleteUser(function() { console.log("User account deleted"); }, function(error) { console.error("Failed to delete current user account: " + error); }); ``` ### createUserWithEmailAndPassword Creates a new email/password-based user account. If account creation is successful, user will be automatically signed in. **Parameters**: - {string} email - user email address. It is the responsibility of the app to ensure this is a valid email address. - {string} password - user password. It is the responsibility of the app to ensure the password is suitable. - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.createUserWithEmailAndPassword(email, password, function() { console.log("Successfully created email/password-based user account"); // User is now signed in }, function(error) { console.error("Failed to create email/password-based user account", error); }); ``` ### signInUserWithEmailAndPassword Signs in to an email/password-based user account. **Parameters**: - {string} email - user email address - {string} password - user password - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.signInUserWithEmailAndPassword(email, password, function() { console.log("Successfully signed in"); // User is now signed in }, function(error) { console.error("Failed to sign in", error); }); ``` ### signInUserWithCustomToken Signs in user with custom token. **Parameters**: - {string} customToken - the custom token - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.signInUserWithCustomToken(customToken, function() { console.log("Successfully signed in"); // User is now signed in }, function(error) { console.error("Failed to sign in", error); }); ``` ### signInUserAnonymously Signs in user anonymously. **Parameters**: - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.signInUserAnonymously(function() { console.log("Successfully signed in"); // User is now signed in }, function(error) { console.error("Failed to sign in", error); }); ``` ### verifyPhoneNumber Requests verification of a phone number. The resulting credential can be used to create/sign in to a phone number-based user account in your app or to link the phone number to an existing user account **NOTE: This will only work on physical devices with a SIM card (not iOS Simulator or Android Emulator)** In response to your request, you'll receive a verification ID which you can use in conjunction with the verification code to sign the user in. There are 3 verification scenarios: - Some Android devices support "instant verification" where the phone number can be instantly verified without sending or receiving an SMS. - In this case, the user doesn't need to do anything in order for you to sign them in and you don't need to provide any additional credentials in order to sign the user in or link the user account to an existing Firebase user account. - Some Android devices support "auto-retrieval" where Google Play services is able to detect the incoming verification SMS and perform verification with no user action required. - As above, the user doesn't need to do anything in order for you to sign them in. - For other Android devices and all iOS devices, the user must manually enter the verification code received in the SMS into your app. - This code be used, along with the accompanying verification ID, to sign the user in or link phone number to an existing Firebase user account. **Parameters**: - {function} success - callback function to pass {object} credentials to as an argument - {function} error - callback function which will be passed a {string} error message as an argument - {string} phoneNumber - phone number to verify - {integer} timeOutDuration - (optional) time to wait in seconds before timing out - {string} fakeVerificationCode - (optional) to test instant verification on Android ,specify a fake verification code to return for whitelisted phone numbers. - See [Firebase SDK Phone Auth Android Integration Testing](https://firebase.google.com/docs/auth/android/phone-auth#integration-testing) for more info. The success callback will be passed a credential object with the following possible properties: - {boolean} instantVerification - `true` if the Android device used instant verification to instantly verify the user without sending an SMS or used auto-retrieval to automatically read an incoming SMS. If this is `false`, the device will be sent an SMS containing the verification code. If the Android device supports auto-retrieval, on the device receiving the SMS, this success callback will be immediately invoked again with `instantVerification: true` and no user action will be required for verification since Google Play services will extract and submit the verification code. Otherwise the user must manually enter the verification code from the SMS into your app. Always `false` on iOS. - {string} id - the identifier of a native credential object which can be used for signing in the user. Will only be present if `instantVerification` is `true`. - {string} verificationId - the verification ID to be passed along with the verification code sent via SMS to sign the user in. Will only be present if `instantVerification` is `false`. Example usage: ```javascript var number = '+441234567890'; var timeOutDuration = 60; var fakeVerificationCode = '123456'; var awaitingSms = false; FirebasePlugin.verifyPhoneNumber(function(credential) { if(credential.instantVerification){ if(awaitingSms){ awaitingSms = false; // the Android device used auto-retrieval to extract and submit the verification code in the SMS so dismiss user input UI dismissUserPromptToInputCode(); } signInWithCredential(credential); }else{ awaitingSms = true; promptUserToInputCode() // you need to implement this .then(function(userEnteredCode){ awaitingSms = false; credential.code = userEnteredCode; // set the user-entered verification code on the credential object signInWithCredential(credential); }); } }, function(error) { console.error("Failed to verify phone number: " + JSON.stringify(error)); }, number, timeOutDuration, fakeVerificationCode); function signInWithCredential(credential){ FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); } ``` #### Android To use phone auth with your Android app, you need to configure your app SHA-1 hash in the android app configuration in the Firebase console. See [this guide](https://developers.google.com/android/guides/client-auth) to find how to your SHA-1 app hash. See the [Firebase phone auth integration guide for native Android](https://firebase.google.com/docs/auth/android/phone-auth) for more information. #### iOS When you call this method on iOS, FCM sends a silent push notification to the iOS device to verify it. So to use phone auth with your iOS app, you need to: - [setup your iOS app for push notifications](https://firebase.google.com/docs/cloud-messaging/ios/certs) - Verify that push notifications are arriving on your physical device - [Upload your APNs auth key to the Firebase console](https://firebase.google.com/docs/cloud-messaging/ios/client#upload_your_apns_authentication_key). You can [set up reCAPTCHA verification for iOS](https://firebase.google.com/docs/auth/ios/phone-auth#set-up-recaptcha-verification) automatically by specifying the `SETUP_RECAPTCHA_VERIFICATION` plugin variable at plugin install time: cordova plugin add cordova-plugin-firebasex --variable SETUP_RECAPTCHA_VERIFICATION=true This adds the `REVERSED_CLIENT_ID` from the `GoogleService-Info.plist` to the list of custom URL schemes in your Xcode project, so you don't need to do this manually. ### authenticateUserWithGoogle Authenticates the user with a Google account to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. **Parameters**: - {string} clientId - your OAuth 2.0 client ID - [see here](https://developers.google.com/identity/sign-in/android/start-integrating#get_your_backend_servers_oauth_20_client_id) how to obtain it. - {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: - {string} id - the identifier of a native credential object which can be used for signing in the user. - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.authenticateUserWithGoogle(clientId, function(credential) { FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); }, function(error) { console.error("Failed to authenticate with Google: " + error); }); ``` #### Android To use Google Sign-in in your Android app you need to do the following: - Add the SHA-1 fingerprint of your app's signing key to your Firebase project - Enable Google Sign-in in the Firebase console For details how to do the above, see the [Google Sign-In on Android page](https://firebase.google.com/docs/auth/android/google-signin) in the Firebase documentation. ### authenticateUserWithApple Authenticates the user with an Apple account using Sign In with Apple to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. **Parameters**: - {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: - {string} id - the identifier of a native credential object which can be used for signing in the user. - {function} error - callback function which will be passed a {string} error message as an argument - {string} locale - (Android only) the language to display Apple's Sign-in screen in. - Defaults to "en" (English) if not specified. - See [the Apple documentation](https://developer.apple.com/documentation/signinwithapplejs/incorporating_sign_in_with_apple_into_other_platforms###2112) for a list of supported locales. - The value is ignored on iOS which uses the locale of the device to determine the display language. Example usage: ```javascript FirebasePlugin.authenticateUserWithApple(function(credential) { FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); }, function(error) { console.error("Failed to authenticate with Apple: " + error); }, 'en_GB'); ``` #### iOS To use Sign In with Apple in your iOS app you need to do the following: - Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/ios/apple#before-you-begin) - After adding the `cordova-ios` platform, open the project workspace in Xcode (`platforms/ios/YourApp.xcworkspace`) and add the "Sign In with Apple" capability in the "Signing & Capabilities section" - Note: AFAIK there is currently no way to automate the addition of this capability #### Android To use Sign In with Apple in your Android app you need to do the following: - Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/android/apple#before-you-begin) ### signInWithCredential Signs the user into Firebase with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. See the [Android-](https://firebase.google.com/docs/auth/android/phone-auth#sign-in-the-user) and [iOS](https://firebase.google.com/docs/auth/ios/phone-auth#sign-in-the-user-with-the-verification-code)-specific Firebase documentation for more info. **Parameters**: - {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - {string} id - the identifier of a native credential object which can be used for signing in the user. Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. If true, you do not need to provide a user-entered verification. - Only present if the credential was obtained via `verifyPhoneNumber()` - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. - {function} success - callback function to call on successful sign-in using credentials - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript function signInWithCredential(credential){ FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); } ``` ### linkUserWithCredential Links an existing Firebase user account with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. See the [Android-](https://firebase.google.com/docs/auth/android/account-linking) and [iOS](https://firebase.google.com/docs/auth/ios/account-linking)-specific Firebase documentation for more info. **Parameters**: - {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - {string} id - the identifier of a native credential object which can be used for signing in the user. Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. If true, you do not need to provide a user-entered verification. - Only present if the credential was obtained via `verifyPhoneNumber()` - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. - {function} success - callback function to call on successful linking using credentials - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript function linkUserWithCredential(credential){ FirebasePlugin.linkUserWithCredential(credential, function() { console.log("Successfully linked"); }, function(error) { console.error("Failed to link", error); }); } ``` ### reauthenticateWithCredential Reauthenticates the currently signed in user with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. **Parameters**: - {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - {string} id - the identifier of a native credential object which can be used for signing in the user. Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. If true, you do not need to provide a user-entered verification. - Only present if the credential was obtained via `verifyPhoneNumber()` - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.reauthenticateWithCredential(credential, function() { console.log("Successfully reauthenticated"); }, function(error) { console.error("Failed to reauthenticate", error); }); ``` ### registerAuthStateChangeListener Registers a Javascript function to invoke when Firebase Authentication state changes between user signed in/signed out. **Parameters**: - {function} fn - callback function to invoke when authentication state changes - Will be a passed a single boolean argument which is `true` if user just signed in and `false` if user just signed out. Example usage: ```javascript FirebasePlugin.registerAuthStateChangeListener(function(userSignedIn){ console.log("Auth state changed: User signed " + (userSignedIn ? "in" : "out")); }); ``` ## Remote Config ### fetch Fetch Remote Config parameter values for your app: **Parameters**: - {integer} cacheExpirationSeconds (optional) - cache expiration in seconds - {function} success - callback function on successfully fetching remote config - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.fetch(function () { // success callback }, function () { // error callback }); // or, specify the cacheExpirationSeconds FirebasePlugin.fetch(600, function () { // success callback }, function () { // error callback }); ``` ### activateFetched Activate the Remote Config fetched config: **Parameters**: - {function} success - callback function which will be passed a {boolean} argument indicating whether fetched config was successfully activated - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.activateFetched(function(activated) { // activated will be true if there was a fetched config activated, // or false if no fetched config was found, or the fetched config was already activated. console.log(activated); }, function(error) { console.error(error); }); ``` ### getValue Retrieve a Remote Config value: **Parameters**: - {string} key - key for which to fetch associated value - {function} success - callback function which will be passed a {any} argument containing the value stored against the specified key. - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getValue("key", function(value) { console.log(value); }, function(error) { console.error(error); }); ``` ### getByteArray Android only. Retrieve a Remote Config byte array: **Parameters**: - {string} key - key for which to fetch associated value - {function} success - callback function which will be passed a {string} argument containing the Base64 encoded string that represents the value stored against the specified key. - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getByteArray("key", function(bytes) { // a Base64 encoded string that represents the value for "key" console.log(bytes.base64); // a numeric array containing the values of the byte array (i.e. [0xFF, 0x00]) console.log(bytes.array); }, function(error) { console.error(error); }); ``` ### getInfo Get the current state of the FirebaseRemoteConfig singleton object: **Parameters**: - {function} success - callback function which will be passed an {object} argument containing the state info - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getInfo(function(info) { // the status of the developer mode setting (true/false) console.log(info.configSettings.developerModeEnabled); // (iOS only) for how much (secs) fetch cache is valid and data will not be refetched console.log(info.configSettings.minimumFetchInterval); // (iOS only) value in seconds to abandon a pending fetch request made to the backend console.log(info.configSettings.fetchTimeout); // the timestamp (milliseconds since epoch) of the last successful fetch console.log(info.fetchTimeMillis); // the status of the most recent fetch attempt (int) // 0 = Config has never been fetched. // 1 = Config fetch succeeded. // 2 = Config fetch failed. // 3 = Config fetch was throttled. console.log(info.lastFetchStatus); }, function(error) { console.error(error); }); ``` ### setConfigSettings Android only. Change the settings for the FirebaseRemoteConfig object's operations: **Parameters**: - {object} configSettings - object specifying the remote config settings - {function} success - callback function to be call on successfully setting the remote config settings - {function} error - callback function which will be passed a {string} error message as an argument ```javascript var settings = { developerModeEnabled: true } FirebasePlugin.setConfigSettings(settings); ``` ### setDefaults Android only. Set defaults in the Remote Config: **Parameters**: - {object} defaultSettings - object specifying the default remote config settings - {function} success - callback function to be call on successfully setting the remote config setting defaults - {function} error - callback function which will be passed a {string} error message as an argument ```javascript // define defaults var defaults = { // map property name to value in Remote Config defaults mLong: 1000, mString: 'hello world', mDouble: 3.14, mBoolean: true, // map "mBase64" to a Remote Config byte array represented by a Base64 string // Note: the Base64 string is in an array in order to differentiate from a string config value mBase64: ["SGVsbG8gV29ybGQ="], // map "mBytes" to a Remote Config byte array represented by a numeric array mBytes: [0xFF, 0x00] } // set defaults FirebasePlugin.setDefaults(defaults); ``` ## Performance ### setPerformanceCollectionEnabled Manually enable/disable performance data collection, e.g. if [disabled on app startup](#disable-data-collection-on-startup). **Parameters**: - {boolean} setEnabled - whether to enable or disable performance data collection ```javascript FirebasePlugin.setPerformanceCollectionEnabled(true); // Enables performance data collection FirebasePlugin.setPerformanceCollectionEnabled(false); // Disables performance data collection ``` ### isPerformanceCollectionEnabled Indicates whether performance data collection is enabled. Notes: - This value applies both to the current app session and subsequent app sessions until such time as it is changed. - It returns the value set by [setPerformanceCollectionEnabled()](#setperformancecollectionenabled). - If automatic data collection was not [disabled on app startup](#disable-data-collection-on-startup), this will always return `true`. **Parameters**: - {function} success - callback function which will be invoked on success. Will be passed a {boolean} indicating if the setting is enabled. - {function} error - (optional) callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.isPerformanceCollectionEnabled(function(enabled){ console.log("Performance data collection is "+(enabled ? "enabled" : "disabled")); }, function(error){ console.error("Error getting Performance data collection setting: "+error); }); ``` ### startTrace Start a trace. **Parameters**: - {string} name - name of trace to start - {function} success - callback function to call on successfully starting trace - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.startTrace("test trace", success, error); ``` ### incrementCounter To count the performance-related events that occur in your app (such as cache hits or retries), add a line of code similar to the following whenever the event occurs, using a string other than retry to name that event if you are counting a different type of event: **Parameters**: - {string} name - name of trace - {string} counterName - name of counter to increment - {function} success - callback function to call on successfully incrementing counter - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.incrementCounter("test trace", "retry", success, error); ``` ### stopTrace Stop the trace **Parameters**: - {string} name - name of trace to stop - {function} success - callback function to call on successfully stopping trace - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.stopTrace("test trace"); ``` ## Firestore These plugin API functions provide CRUD operations for working with documents in Firestore collections. Notes: - Only top-level Firestore collections are currently supported - [subcollections](https://firebase.google.com/docs/firestore/manage-data/structure-data#subcollections) (nested collections within documents) are currently not supported due to the complexity of mapping the native objects into the plugin's JS API layer. - A document object may contain values of primitive Javascript types `string`, `number`, `boolean`, `array` or `object`. Arrays and objects may contain nested structures of these types. - If a collection name referenced in a document write operation does not already exist, it will be created by the first write operation referencing it. ### addDocumentToFirestoreCollection Adds a new document to a Firestore collection, which will be allocated an auto-generated document ID. **Parameters**: - {object} document - document object to add to collection - {string} collection - name of top-level collection to add document to. - {function} success - callback function to call on successfully adding the document. Will be passed a {string} argument containing the auto-generated document ID that the document was stored against. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var document = { "a_string": "foo", "a_list": [1, 2, 3], "an_object": { "an_integer": 1, } }; var collection = "my_collection"; FirebasePlugin.addDocumentToFirestoreCollection(document, collection, function(documentId){ console.log("Successfully added document with id="+documentId); }, function(error){ console.error("Error adding document: "+error); }); ``` ### setDocumentInFirestoreCollection Sets (adds/replaces) a document with the given ID in a Firestore collection. **Parameters**: - {string} documentId - document ID to use when setting document in the collection. - {object} document - document object to set in collection. - {string} collection - name of top-level collection to set document in. - {function} success - callback function to call on successfully setting the document. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var document = { "a_string": "foo", "a_list": [1, 2, 3], "an_object": { "an_integer": 1, } }; var collection = "my_collection"; FirebasePlugin.setDocumentInFirestoreCollection(documentId, document, collection, function(){ console.log("Successfully set document with id="+documentId); }, function(error){ console.error("Error setting document: "+error); }); ``` ### updateDocumentInFirestoreCollection Updates an existing document with the given ID in a Firestore collection. This is a non-destructive update that will only overwrite existing keys in the existing document or add new ones if they don't already exist. If the no document with the specified ID exists in the collection, an error will be raised. **Parameters**: - {string} documentId - document ID of the document to update. - {object} document - entire document or document fragment to update existing document with. - {string} collection - name of top-level collection to update document in. - {function} success - callback function to call on successfully updating the document. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var documentFragment = { "a_string": "new value", "a_new_string": "bar" }; var collection = "my_collection"; FirebasePlugin.updateDocumentInFirestoreCollection(documentId, documentFragment, collection, function(){ console.log("Successfully updated document with id="+documentId); }, function(error){ console.error("Error updating document: "+error); }); ``` ### deleteDocumentFromFirestoreCollection Deletes an existing document with the given ID in a Firestore collection. Note: If the no document with the specified ID exists in the collection, the Firebase SDK will still return a successful outcome. **Parameters**: - {string} documentId - document ID of the document to delete. - {string} collection - name of top-level collection to delete document in. - {function} success - callback function to call on successfully deleting the document. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var collection = "my_collection"; FirebasePlugin.deleteDocumentFromFirestoreCollection(documentId, collection, function(){ console.log("Successfully deleted document with id="+documentId); }, function(error){ console.error("Error deleting document: "+error); }); ``` ### documentExistsInFirestoreCollection Indicates if a document with the given ID exists in a Firestore collection. **Parameters**: - {string} documentId - document ID of the document. - {string} collection - name of top-level collection to check for document. - {function} success - callback function to call pass result. Will be passed an {boolean} which is `true` if a document exists. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var collection = "my_collection"; FirebasePlugin.documentExistsInFirestoreCollection(documentId, collection, function(exists){ console.log("Document " + (exists ? "exists" : "doesn't exist")); }, function(error){ console.error("Error fetching document: "+error); }); ``` ### fetchDocumentInFirestoreCollection Fetches an existing document with the given ID from a Firestore collection. Note: If the no document with the specified ID exists in the collection, the error callback will be invoked. **Parameters**: - {string} documentId - document ID of the document to fetch. - {string} collection - name of top-level collection to fetch document from. - {function} success - callback function to call on successfully fetching the document. Will be passed an {object} contain the document contents. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var collection = "my_collection"; FirebasePlugin.fetchDocumentInFirestoreCollection(documentId, collection, function(document){ console.log("Successfully fetched document: "+JSON.stringify(document)); }, function(error){ console.error("Error fetching document: "+error); }); ``` ### fetchFirestoreCollection Fetches all the documents in the specific collection. **Parameters**: - {string} collection - name of top-level collection to fetch. - {array} filters - a list of filters to sort/filter the documents returned from your collection. - Supports `where`, `orderBy`, `startAt`, `endAt` and `limit` filters. - See the [Firestore documentation](https://firebase.google.com/docs/firestore/query-data/queries) for more details. - {function} success - callback function to call on successfully deleting the document. Will be passed an {object} containing all the documents in the collection, indexed by document ID. If a Firebase collection with that name does not exist or it contains no documents, the object will be empty. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var collection = "my_collection"; var filters = [ ['where', 'field', '==', 'value'], ['orderBy', 'field', 'desc'] ]; FirebasePlugin.fetchFirestoreCollection(collection, filters, function(documents){ console.log("Successfully fetched collection: "+JSON.stringify(documents)); }, function(error){ console.error("Error fetching collection: "+error); }); ``` # Credits - [@robertarnesson](https://github.com/robertarnesson) for the original [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) from which this plugin is forked. - [@sagrawal31](https://github.com/sagrawal31) and [Wiz Panda](https://github.com/wizpanda) for contributions via [cordova-plugin-firebase-lib](https://github.com/wizpanda/cordova-plugin-firebase-lib). - [Full list of contributors](https://github.com/dpa99c/cordova-plugin-firebasex/graphs/contributors) \ No newline at end of file diff --git a/plugin.xml b/plugin.xml index ebb5f6aa8..caba8cafa 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,145 +1 @@ - - - Google Firebase Plugin - - MIT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - development - - - production - - - - remote-notification - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + Google Firebase Plugin MIT development production remote-notification \ No newline at end of file diff --git a/scripts/ios/helper.js b/scripts/ios/helper.js old mode 100755 new mode 100644 index 0c367f415..1159adf47 --- a/scripts/ios/helper.js +++ b/scripts/ios/helper.js @@ -1,238 +1 @@ -var fs = require("fs"); -var path = require("path"); -var utilities = require("../lib/utilities"); -var xcode = require("xcode"); -var plist = require('plist'); - -/** - * This is used as the display text for the build phase block in XCode as well as the - * inline comments inside of the .pbxproj file for the build script phase block. - */ -var comment = "\"Crashlytics\""; - -module.exports = { - - /** - * Used to get the path to the XCode project's .pbxproj file. - */ - getXcodeProjectPath: function () { - var appName = utilities.getAppName(); - return path.join("platforms", "ios", appName + ".xcodeproj", "project.pbxproj"); - }, - - /** - * This helper is used to add a build phase to the XCode project which runs a shell - * script during the build process. The script executes Crashlytics run command line - * tool with the API and Secret keys. This tool is used to upload the debug symbols - * (dSYMs) so that Crashlytics can display stack trace information in it's web console. - */ - addShellScriptBuildPhase: function (context, xcodeProjectPath) { - - // Read and parse the XCode project (.pxbproj) from disk. - // File format information: http://www.monobjc.net/xcode-project-file-format.html - var xcodeProject = xcode.project(xcodeProjectPath); - xcodeProject.parseSync(); - - // Build the body of the script to be executed during the build phase. - var script = '"' + '\\"${PODS_ROOT}/Fabric/run\\"' + '"'; - - // Generate a unique ID for our new build phase. - var id = xcodeProject.generateUuid(); - // Create the build phase. - xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[id] = { - isa: "PBXShellScriptBuildPhase", - buildActionMask: 2147483647, - files: [], - inputPaths: ['"' + '$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)' + '"'], - name: comment, - outputPaths: [], - runOnlyForDeploymentPostprocessing: 0, - shellPath: "/bin/sh", - shellScript: script, - showEnvVarsInLog: 0 - }; - - // Add a comment to the block (viewable in the source of the pbxproj file). - xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[id + "_comment"] = comment; - - // Add this new shell script build phase block to the targets. - for (var nativeTargetId in xcodeProject.hash.project.objects.PBXNativeTarget) { - - // Skip over the comment blocks. - if (nativeTargetId.indexOf("_comment") !== -1) { - continue; - } - - var nativeTarget = xcodeProject.hash.project.objects.PBXNativeTarget[nativeTargetId]; - - nativeTarget.buildPhases.push({ - value: id, - comment: comment - }); - } - - // Finally, write the .pbxproj back out to disk. - fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); - }, - - /** - * This helper is used to remove the build phase from the XCode project that was added - * by the addShellScriptBuildPhase() helper method. - */ - removeShellScriptBuildPhase: function (context, xcodeProjectPath) { - - // Read and parse the XCode project (.pxbproj) from disk. - // File format information: http://www.monobjc.net/xcode-project-file-format.html - var xcodeProject = xcode.project(xcodeProjectPath); - xcodeProject.parseSync(); - - // First, we want to delete the build phase block itself. - - var buildPhases = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase; - - var commentTest = comment.replace(/"/g, ''); - for (var buildPhaseId in buildPhases) { - - var buildPhase = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[buildPhaseId]; - var shouldDelete = false; - - if (buildPhaseId.indexOf("_comment") === -1) { - // Dealing with a build phase block. - - // If the name of this block matches ours, then we want to delete it. - shouldDelete = buildPhase.name && buildPhase.name.indexOf(commentTest) !== -1; - } else { - // Dealing with a comment block. - - // If this is a comment block that matches ours, then we want to delete it. - shouldDelete = buildPhase === commentTest; - } - - if (shouldDelete) { - delete buildPhases[buildPhaseId]; - } - } - - // Second, we want to delete the native target reference to the block. - - var nativeTargets = xcodeProject.hash.project.objects.PBXNativeTarget; - - for (var nativeTargetId in nativeTargets) { - - // Skip over the comment blocks. - if (nativeTargetId.indexOf("_comment") !== -1) { - continue; - } - - var nativeTarget = nativeTargets[nativeTargetId]; - - // We remove the reference to the block by filtering out the the ones that match. - nativeTarget.buildPhases = nativeTarget.buildPhases.filter(function (buildPhase) { - return buildPhase.comment !== commentTest; - }); - } - - // Finally, write the .pbxproj back out to disk. - fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); - }, - - ensureRunpathSearchPath: function(context, xcodeProjectPath){ - - function addRunpathSearchBuildProperty(proj, build) { - let LD_RUNPATH_SEARCH_PATHS = proj.getBuildProperty("LD_RUNPATH_SEARCH_PATHS", build); - - if (!Array.isArray(LD_RUNPATH_SEARCH_PATHS)) { - LD_RUNPATH_SEARCH_PATHS = [LD_RUNPATH_SEARCH_PATHS]; - } - - LD_RUNPATH_SEARCH_PATHS.forEach(LD_RUNPATH_SEARCH_PATH => { - if (!LD_RUNPATH_SEARCH_PATH) { - proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build); - } - if (LD_RUNPATH_SEARCH_PATH.indexOf("@executable_path/Frameworks") == -1) { - var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); - newValue += ' @executable_path/Frameworks\"'; - proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); - } - if (LD_RUNPATH_SEARCH_PATH.indexOf("$(inherited)") == -1) { - var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); - newValue += ' $(inherited)\"'; - proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); - } - }); - } - - // Read and parse the XCode project (.pxbproj) from disk. - // File format information: http://www.monobjc.net/xcode-project-file-format.html - var xcodeProject = xcode.project(xcodeProjectPath); - xcodeProject.parseSync(); - - // Add search paths build property - addRunpathSearchBuildProperty(xcodeProject, "Debug"); - addRunpathSearchBuildProperty(xcodeProject, "Release"); - - // Finally, write the .pbxproj back out to disk. - fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); - }, - stripDebugSymbols: function(){ - var podFilePath = 'platforms/ios/Podfile', - podFile = fs.readFileSync(path.resolve(podFilePath)).toString(); - if(!podFile.match('DEBUG_INFORMATION_FORMAT')){ - podFile += "\npost_install do |installer|\n" + - " installer.pods_project.targets.each do |target|\n" + - " target.build_configurations.each do |config|\n" + - " config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'\n" + - " end\n" + - " end\n" + - "end"; - fs.writeFileSync(path.resolve(podFilePath), podFile); - console.log('cordova-plugin-firebasex: Applied IOS_STRIP_DEBUG to Podfile'); - } - }, - applyPluginVarsToPlists: function(googlePlistPath, appPlistPath, pluginVariables){ - var googlePlist = plist.parse(fs.readFileSync(path.resolve(googlePlistPath), 'utf8')), - appPlist = plist.parse(fs.readFileSync(path.resolve(appPlistPath), 'utf8')), - googlePlistModified = false, - appPlistModified = false; - - if(typeof pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== 'undefined'){ - googlePlist["FIREBASE_ANALYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; - googlePlistModified = true; - } - if(typeof pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== 'undefined'){ - googlePlist["FIREBASE_PERFORMANCE_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; - googlePlistModified = true; - } - if(typeof pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== 'undefined'){ - googlePlist["FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; - googlePlistModified = true; - } - if(typeof pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] !== 'undefined'){ - appPlist["shouldEstablishDirectChannel"] = (pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] === "true") ; - appPlistModified = true; - } - if(pluginVariables['SETUP_RECAPTCHA_VERIFICATION'] === 'true'){ - var reversedClientId = googlePlist['REVERSED_CLIENT_ID']; - - if(!appPlist['CFBundleURLTypes']) appPlist['CFBundleURLTypes'] = []; - var entry, i; - for(i=0; i { if (!LD_RUNPATH_SEARCH_PATH) { proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build); } if (LD_RUNPATH_SEARCH_PATH.indexOf("@executable_path/Frameworks") == -1) { var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); newValue += ' @executable_path/Frameworks\"'; proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); } if (LD_RUNPATH_SEARCH_PATH.indexOf("$(inherited)") == -1) { var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); newValue += ' $(inherited)\"'; proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); } }); } // Read and parse the XCode project (.pxbproj) from disk. // File format information: http://www.monobjc.net/xcode-project-file-format.html var xcodeProject = xcode.project(xcodeProjectPath); xcodeProject.parseSync(); // Add search paths build property addRunpathSearchBuildProperty(xcodeProject, "Debug"); addRunpathSearchBuildProperty(xcodeProject, "Release"); // Finally, write the .pbxproj back out to disk. fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); }, stripDebugSymbols: function(){ var podFilePath = 'platforms/ios/Podfile', podFile = fs.readFileSync(path.resolve(podFilePath)).toString(); if(!podFile.match('DEBUG_INFORMATION_FORMAT')){ podFile += "\npost_install do |installer|\n" + " installer.pods_project.targets.each do |target|\n" + " target.build_configurations.each do |config|\n" + " config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'\n" + " end\n" + " end\n" + "end"; fs.writeFileSync(path.resolve(podFilePath), podFile); console.log('cordova-plugin-firebasex: Applied IOS_STRIP_DEBUG to Podfile'); } }, applyPluginVarsToPlists: function(googlePlistPath, appPlistPath, pluginVariables){ var googlePlist = plist.parse(fs.readFileSync(path.resolve(googlePlistPath), 'utf8')), appPlist = plist.parse(fs.readFileSync(path.resolve(appPlistPath), 'utf8')), googlePlistModified = false, appPlistModified = false; if(typeof pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== 'undefined'){ googlePlist["FIREBASE_ANALYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } if(typeof pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== 'undefined'){ googlePlist["FIREBASE_PERFORMANCE_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } if(typeof pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== 'undefined'){ googlePlist["FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } if(typeof pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] !== 'undefined'){ appPlist["shouldEstablishDirectChannel"] = (pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] === "true") ; appPlistModified = true; } if(pluginVariables['SETUP_RECAPTCHA_VERIFICATION'] === 'true'){ var reversedClientId = googlePlist['REVERSED_CLIENT_ID']; if(!appPlist['CFBundleURLTypes']) appPlist['CFBundleURLTypes'] = []; var entry, i; for(i=0; i notificationStack = null; - private static CallbackContext notificationCallbackContext; - private static CallbackContext tokenRefreshCallbackContext; - private static CallbackContext activityResultCallbackContext; - private static CallbackContext authResultCallbackContext; - - private static NotificationChannel defaultNotificationChannel = null; - public static String defaultChannelId = null; - public static String defaultChannelName = null; - - private Map authCredentials = new HashMap(); - private Map authProviders = new HashMap(); - - @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)){ - isCrashlyticsEnabled = getPreference(CRASHLYTICS_COLLECTION_ENABLED); - if(isCrashlyticsEnabled){ - Fabric.with(applicationContext, new Crashlytics()); - } - }else{ - isCrashlyticsEnabled = true; - 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); - } - - FirebaseApp.initializeApp(applicationContext); - mFirebaseAnalytics = FirebaseAnalytics.getInstance(applicationContext); - - authStateListener = new AuthStateListener(); - FirebaseAuth.getInstance().addAuthStateListener(authStateListener); - - firestore = FirebaseFirestore.getInstance(); - gson = new Gson(); - - if (extras != null && extras.size() > 1) { - if (FirebasePlugin.notificationStack == null) { - FirebasePlugin.notificationStack = new ArrayList(); - } - 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{ - 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("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("isAutoInitEnabled")) { - isAutoInitEnabled(callbackContext); - return true; - } else if (action.equals("setAutoInitEnabled")) { - setAutoInitEnabled(callbackContext, args.getBoolean(0)); - return true; - } else if (action.equals("unregister")) { - this.unregister(callbackContext); - return true; - } else if (action.equals("onMessageReceived")) { - this.onMessageReceived(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); - 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")) { - this.getByteArray(callbackContext, args.getString(0)); - return true; - } else if (action.equals("getValue")) { - this.getValue(callbackContext, args.getString(0)); - 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")) { - this.setDefaults(callbackContext, args.getJSONObject(0)); - return true; - } else if (action.equals("verifyPhoneNumber")) { - this.verifyPhoneNumber(callbackContext, args); - return true; - } else if (action.equals("authenticateUserWithGoogle")) { - this.authenticateUserWithGoogle(callbackContext, args); - return true; - } else if (action.equals("authenticateUserWithApple")) { - this.authenticateUserWithApple(callbackContext, args); - return true; - } else if (action.equals("createUserWithEmailAndPassword")) { - this.createUserWithEmailAndPassword(callbackContext, args); - return true; - } else if (action.equals("signInUserWithEmailAndPassword")) { - this.signInUserWithEmailAndPassword(callbackContext, args); - return true; - } else if (action.equals("signInUserWithCustomToken")) { - this.signInUserWithCustomToken(callbackContext, args); - return true; - } else if (action.equals("signInUserAnonymously")) { - this.signInUserAnonymously(callbackContext); - return true; - } else if (action.equals("signInWithCredential")) { - this.signInWithCredential(callbackContext, args); - return true; - } else if (action.equals("linkUserWithCredential")) { - this.linkUserWithCredential(callbackContext, args); - return true; - } else if (action.equals("reauthenticateWithCredential")) { - this.reauthenticateWithCredential(callbackContext, args); - return true; - } else if (action.equals("isUserSignedIn")) { - this.isUserSignedIn(callbackContext, args); - return true; - } else if (action.equals("signOutUser")) { - this.signOutUser(callbackContext, args); - return true; - } else if (action.equals("getCurrentUser")) { - this.getCurrentUser(callbackContext, args); - return true; - } else if (action.equals("reloadCurrentUser")) { - this.reloadCurrentUser(callbackContext, args); - return true; - } else if (action.equals("updateUserProfile")) { - this.updateUserProfile(callbackContext, args); - return true; - } else if (action.equals("updateUserEmail")) { - this.updateUserEmail(callbackContext, args); - return true; - } else if (action.equals("sendUserEmailVerification")) { - this.sendUserEmailVerification(callbackContext, args); - return true; - } else if (action.equals("updateUserPassword")) { - this.updateUserPassword(callbackContext, args); - return true; - } else if (action.equals("sendUserPasswordResetEmail")) { - this.sendUserPasswordResetEmail(callbackContext, args); - return true; - } else if (action.equals("deleteUser")) { - this.deleteUser(callbackContext, args); - 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("isAnalyticsCollectionEnabled")) { - this.isAnalyticsCollectionEnabled(callbackContext); - return true; - } else if (action.equals("setPerformanceCollectionEnabled")) { - this.setPerformanceCollectionEnabled(callbackContext, args.getBoolean(0)); - return true; - } else if (action.equals("isPerformanceCollectionEnabled")) { - this.isPerformanceCollectionEnabled(callbackContext); - return true; - } else if (action.equals("setCrashlyticsCollectionEnabled")) { - this.setCrashlyticsCollectionEnabled(callbackContext, args.getBoolean(0)); - return true; - } else if (action.equals("isCrashlyticsCollectionEnabled")) { - this.isCrashlyticsCollectionEnabled(callbackContext); - return true; - } else if (action.equals("isCrashlyticsCollectionCurrentlyEnabled")) { - this.isCrashlyticsCollectionCurrentlyEnabled(callbackContext); - return true; - } else if (action.equals("clearAllNotifications")) { - this.clearAllNotifications(callbackContext); - return true; - } else if (action.equals("logMessage")) { - logMessage(args, callbackContext); - return true; - } else if (action.equals("sendCrash")) { - sendCrash(args, callbackContext); - return true; - } else if (action.equals("createChannel")) { - this.createChannel(callbackContext, args.getJSONObject(0)); - return true; - } else if (action.equals("deleteChannel")) { - this.deleteChannel(callbackContext, args.getString(0)); - return true; - } else if (action.equals("listChannels")) { - this.listChannels(callbackContext); - return true; - } else if (action.equals("setDefaultChannel")) { - this.setDefaultChannel(callbackContext, args.getJSONObject(0)); - return true; - } else if (action.equals("addDocumentToFirestoreCollection")) { - this.addDocumentToFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("setDocumentInFirestoreCollection")) { - this.setDocumentInFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("updateDocumentInFirestoreCollection")) { - this.updateDocumentInFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("deleteDocumentFromFirestoreCollection")) { - this.deleteDocumentFromFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("documentExistsInFirestoreCollection")) { - this.documentExistsInFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("fetchDocumentInFirestoreCollection")) { - this.fetchDocumentInFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("fetchFirestoreCollection")) { - this.fetchFirestoreCollection(args, callbackContext); - return true; - } else if (action.equals("grantPermission") - || action.equals("setBadgeNumber") - || action.equals("getBadgeNumber") - ) { - // Stubs for other platform methods - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true)); - return true; - }else{ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Invalid action: " + action)); - return false; - } - }catch(Exception e){ - handleExceptionWithContext(e, callbackContext); - } - 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; - 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 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); - - JSONObject returnResults = new JSONObject(); - returnResults.put("instantVerification", true); - returnResults.put("id", id); - FirebasePlugin.activityResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 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 { - String currentToken = FirebaseInstanceId.getInstance().getToken(); - if (currentToken != null) { - FirebasePlugin.sendToken(currentToken); - } - } 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(); - } - 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 keys = bundle.keySet(); - for (String key : keys) { - try { - json.put(key, bundle.get(key)); - } catch (JSONException e) { - handleExceptionWithContext(e, callbackContext); - 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) { - 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 getId(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String id = FirebaseInstanceId.getInstance().getId(); - callbackContext.success(id); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void hasPermission(final CallbackContext callbackContext) { - if(cordovaActivity == null) return; - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(cordovaActivity); - boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); - callbackContext.success(areNotificationsEnabled ? 1 : 0); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void unregister(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseInstanceId.getInstance().deleteInstanceId(); - callbackContext.success(); - } 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(isEnabled ? 1 : 0); - } 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 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) { - 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()); - } - } - }); - } - - private void logMessage(final JSONArray data, - final CallbackContext callbackContext) { - - if(isCrashlyticsEnabled){ - String message = data.optString(0); - logMessageToCrashlytics(message); - callbackContext.success(); - }else{ - callbackContext.error("Cannot log message - Crashlytics collection is disabled"); - } - } - - private void sendCrash(final JSONArray data, - final CallbackContext callbackContext) { - - cordovaActivity.runOnUiThread(new Runnable() { - @Override - public void run() { - throw new RuntimeException("This is a crash"); - } - }); - } - - - private void setCrashlyticsUserId(final CallbackContext callbackContext, final String userId) { - cordovaActivity.runOnUiThread(new Runnable() { - public void run() { - try { - if(isCrashlyticsEnabled){ - Crashlytics.setUserIdentifier(userId); - callbackContext.success(); - }else{ - callbackContext.error("Cannot set Crashlytics user ID - Crashlytics collection is disabled"); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void setScreenName(final CallbackContext callbackContext, final String name) { - // This must be called on the main thread - cordovaActivity.runOnUiThread(new Runnable() { - public void run() { - try { - mFirebaseAnalytics.setCurrentScreen(cordovaActivity, name, null); - callbackContext.success(); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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 task) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - task.addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(Void data) { - callbackContext.success(); - } - }).addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void getByteArray(final CallbackContext callbackContext, final String key) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - byte[] bytes = FirebaseRemoteConfig.getInstance().getByteArray(key); - JSONObject object = new JSONObject(); - object.put("base64", Base64.encodeToString(bytes, Base64.DEFAULT)); - object.put("array", new JSONArray(bytes)); - callbackContext.success(object); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void getValue(final CallbackContext callbackContext, final String key) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseRemoteConfigValue value = FirebaseRemoteConfig.getInstance().getValue(key); - callbackContext.success(value.asString()); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void setDefaults(final CallbackContext callbackContext, final JSONObject defaults) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults)); - callbackContext.success(); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private static Map defaultsToMap(JSONObject object) throws JSONException { - final Map map = new HashMap(); - - for (Iterator 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; - } - - - public void isUserSignedIn(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - boolean isSignedIn = FirebaseAuth.getInstance().getCurrentUser() != null; - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, isSignedIn)); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void signOutUser(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - // Sign out of Firebase - FirebaseAuth.getInstance().signOut(); - - // Try to sign out of Google - try{ - GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build(); - GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(cordovaActivity, gso); - mGoogleSignInClient.signOut() - .addOnCompleteListener(cordovaActivity, new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - } - }); - }catch(Exception googleSignOutException){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - } - - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void getCurrentUser(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - extractAndReturnUserInfo(callbackContext); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void reloadCurrentUser(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - user.reload() - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(Void aVoid) { - try { - extractAndReturnUserInfo(callbackContext); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void extractAndReturnUserInfo(final CallbackContext callbackContext) throws Exception{ - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - JSONObject returnResults = new JSONObject(); - returnResults.put("name", user.getDisplayName()); - returnResults.put("email", user.getEmail()); - returnResults.put("emailIsVerified", user.isEmailVerified()); - returnResults.put("phoneNumber", user.getPhoneNumber()); - returnResults.put("photoUrl", user.getPhotoUrl() == null ? null : user.getPhotoUrl().toString()); - returnResults.put("uid", user.getUid()); - returnResults.put("providerId", user.getIdToken(false).getResult().getSignInProvider()); - returnResults.put("isAnonymous", user.isAnonymous()); - - user.getIdToken(true).addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(GetTokenResult result) { - try { - String idToken = result.getToken(); - returnResults.put("idToken", idToken); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void updateUserProfile(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - - JSONObject profile = args.getJSONObject(0); - UserProfileChangeRequest profileUpdates; - if(profile.has("name") && profile.has("photoUri")){ - profileUpdates = new UserProfileChangeRequest.Builder() - .setDisplayName(profile.getString("name")) - .setPhotoUri(Uri.parse(profile.getString("photoUri"))) - .build(); - }else if(profile.has("name")){ - profileUpdates = new UserProfileChangeRequest.Builder() - .setDisplayName(profile.getString("name")) - .build(); - }else if(profile.has("photoUri")){ - profileUpdates = new UserProfileChangeRequest.Builder() - .setPhotoUri(Uri.parse(profile.getString("photoUri"))) - .build(); - }else{ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "'name' and/or 'photoUri' keys must be specified in the profile object")); - return; - } - - user.updateProfile(profileUpdates) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void updateUserEmail(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - - String email = args.getString(0); - user.updateEmail(email) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void sendUserEmailVerification(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - - user.sendEmailVerification() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void updateUserPassword(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - - String password = args.getString(0); - user.updatePassword(password) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void sendUserPasswordResetEmail(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseAuth auth = FirebaseAuth.getInstance(); - String email = args.getString(0); - auth.sendPasswordResetEmail(email) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void deleteUser(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - - user.delete() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void reauthenticateWithCredential(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); - if(user == null){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); - return; - } - - JSONObject jsonCredential = args.getJSONObject(0); - if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); - return; - } - - AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); - if(authCredential != null){ - user.reauthenticate(authCredential) - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); - } - }); - return; - } - - OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); - if(authProvider != null){ - FirebasePlugin.instance.authResultCallbackContext = callbackContext; - user.startActivityForReauthenticateWithProvider(FirebasePlugin.cordovaActivity, authProvider) - .addOnSuccessListener(new AuthResultOnSuccessListener()) - .addOnFailureListener(new AuthResultOnFailureListener()); - return; - } - - //ELSE - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); - - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - - - public void signInWithCredential(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - JSONObject jsonCredential = args.getJSONObject(0); - if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); - return; - } - - AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); - if(authCredential != null){ - FirebaseAuth.getInstance().signInWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); - return; - } - - OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); - if(authProvider != null){ - FirebasePlugin.instance.authResultCallbackContext = callbackContext; - FirebaseAuth.getInstance().startActivityForSignInWithProvider(FirebasePlugin.cordovaActivity, authProvider) - .addOnSuccessListener(new AuthResultOnSuccessListener()) - .addOnFailureListener(new AuthResultOnFailureListener()); - return; - } - - //ELSE - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void linkUserWithCredential(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - JSONObject jsonCredential = args.getJSONObject(0); - if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); - return; - } - - AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); - if(authCredential != null){ - FirebaseAuth.getInstance().getCurrentUser().linkWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); - return; - } - - //ELSE - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); - - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private boolean isValidJsonCredential(JSONObject jsonCredential) throws JSONException{ - return jsonCredential.has("id") || (jsonCredential.has("verificationId") && jsonCredential.has("code")); - } - - private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks; - - public void verifyPhoneNumber( - final CallbackContext callbackContext, - final JSONArray args - ) { - 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"); - - String id = FirebasePlugin.instance.saveAuthCredential((AuthCredential) credential); - - JSONObject returnResults = new JSONObject(); - try { - returnResults.put("instantVerification", true); - returnResults.put("id", id); - } catch(JSONException e){ - handleExceptionWithContext(e, callbackContext); - 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; - 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"; - }else{ - errorMsg = e.getMessage(); - } - 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) { - handleExceptionWithContext(e, callbackContext); - return; - } - PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, returnResults); - pluginresult.setKeepCallback(true); - callbackContext.sendPluginResult(pluginresult); - } - }; - - String number = args.getString(0); - int timeOutDuration = args.getInt(1); - String smsCode = args.getString(2); - - if(smsCode != null && smsCode != "null"){ - FirebaseAuth.getInstance().getFirebaseAuthSettings().setAutoRetrievedSmsCodeForPhoneNumber(number, smsCode); - } - - PhoneAuthProvider.getInstance().verifyPhoneNumber(number, // Phone number to verify - timeOutDuration, // Timeout duration - TimeUnit.SECONDS, // Unit of timeout - cordovaActivity, // Activity (for callback binding) - mCallbacks); // OnVerificationStateChangedCallbacks - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void createUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String email = args.getString(0); - String password = args.getString(1); - - if(email == null || email.equals("")){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); - return; - } - - if(password == null || password.equals("")){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); - return; - } - - FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void signInUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String email = args.getString(0); - String password = args.getString(1); - - if(email == null || email.equals("")){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); - return; - } - - if(password == null || password.equals("")){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); - return; - } - - FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - - public void authenticateUserWithGoogle(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String clientId = args.getString(0); - - GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) - .requestIdToken(clientId) - .requestEmail() - .build(); - - GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(FirebasePlugin.instance.cordovaActivity, gso); - Intent signInIntent = mGoogleSignInClient.getSignInIntent(); - FirebasePlugin.activityResultCallbackContext = callbackContext; - FirebasePlugin.instance.cordovaInterface.startActivityForResult(FirebasePlugin.instance, signInIntent, GOOGLE_SIGN_IN); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void authenticateUserWithApple(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String locale = args.getString(0); - OAuthProvider.Builder provider = OAuthProvider.newBuilder("apple.com"); - if(locale != null){ - provider.addCustomParameter("locale", locale); - } - Task pending = FirebaseAuth.getInstance().getPendingAuthResult(); - if (pending != null) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Auth result is already pending")); - pending - .addOnSuccessListener(new AuthResultOnSuccessListener()) - .addOnFailureListener(new AuthResultOnFailureListener()); - } else { - String id = FirebasePlugin.instance.saveAuthProvider(provider.build());; - JSONObject returnResults = new JSONObject(); - returnResults.put("instantVerification", true); - returnResults.put("id", id); - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void signInUserWithCustomToken(final CallbackContext callbackContext, final JSONArray args){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String customToken = args.getString(0); - - if(customToken == null || customToken.equals("")){ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Custom token must be specified")); - return; - } - - FirebaseAuth.getInstance().signInWithCustomToken(customToken).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void signInUserAnonymously(final CallbackContext callbackContext){ - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - // - // Firebase Performace - // - - private HashMap traces = new HashMap(); - - 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) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - 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.incrementMetric(counterNamed, 1); - callbackContext.success(); - } else { - callbackContext.error("Trace not found"); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - 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) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void setAnalyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - if(getMetaDataFromManifest(ANALYTICS_COLLECTION_ENABLED)){ - callbackContext.error("Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); - }else if(enabled && getPreference(ANALYTICS_COLLECTION_ENABLED)){ - callbackContext.error("Analytics data collection is already set to enabled"); - }else if(!enabled && !getPreference(ANALYTICS_COLLECTION_ENABLED)){ - callbackContext.error("Analytics data collection is already set to disabled"); - }else{ - mFirebaseAnalytics.setAnalyticsCollectionEnabled(enabled); - setPreference(ANALYTICS_COLLECTION_ENABLED, enabled); - callbackContext.success(); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void isAnalyticsCollectionEnabled(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - callbackContext.success(getPreference(ANALYTICS_COLLECTION_ENABLED) ? 1 : 0); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void setPerformanceCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - if(getMetaDataFromManifest(PERFORMANCE_COLLECTION_ENABLED)){ - callbackContext.error("Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); - }else if(enabled && getPreference(PERFORMANCE_COLLECTION_ENABLED)){ - callbackContext.error("Performance data collection is already set to enabled"); - }else if(!enabled && !getPreference(PERFORMANCE_COLLECTION_ENABLED)){ - callbackContext.error("Performance data collection is already set to disabled"); - }else{ - FirebasePerformance.getInstance().setPerformanceCollectionEnabled(enabled); - setPreference(PERFORMANCE_COLLECTION_ENABLED, enabled); - callbackContext.success(); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void isPerformanceCollectionEnabled(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - callbackContext.success(getPreference(PERFORMANCE_COLLECTION_ENABLED) ? 1 : 0); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void setCrashlyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - if(getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ - callbackContext.error("Cannot set Crashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); - }else if(enabled && getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ - callbackContext.error("Crashlytics data collection is already set to enabled"); - }else if(!enabled && !getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ - callbackContext.error("Crashlytics data collection is already set to disabled"); - }else{ - setPreference(CRASHLYTICS_COLLECTION_ENABLED, enabled); - callbackContext.success(); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void isCrashlyticsCollectionEnabled(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - callbackContext.success(getPreference(CRASHLYTICS_COLLECTION_ENABLED) ? 1 : 0); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - private void isCrashlyticsCollectionCurrentlyEnabled(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - callbackContext.success(isCrashlyticsEnabled ? 1 : 0); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - e.printStackTrace(); - } - } - }); - } - - public void clearAllNotifications(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); - nm.cancelAll(); - callbackContext.success(); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void createChannel(final CallbackContext callbackContext, final JSONObject options) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - createChannel(options); - callbackContext.success(); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - protected static NotificationChannel createChannel(final JSONObject options) throws JSONException { - NotificationChannel channel = null; - // only call on Android O and above - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - String id = options.getString("id"); - Log.i(TAG, "Creating channel id="+id); - - if(channelExists(id)){ - deleteChannel(id); - } - - NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); - String packageName = cordovaActivity.getPackageName(); - - String name = options.optString("name", ""); - Log.d(TAG, "Channel "+id+" - name="+name); - - int importance = options.optInt("importance", NotificationManager.IMPORTANCE_HIGH); - Log.d(TAG, "Channel "+id+" - importance="+importance); - - channel = new NotificationChannel(id, - name, - importance); - - // Description - String description = options.optString("description", ""); - Log.d(TAG, "Channel "+id+" - description="+description); - channel.setDescription(description); - - // Light - boolean light = options.optBoolean("light", true); - Log.d(TAG, "Channel "+id+" - light="+light); - channel.enableLights(light); - - int lightColor = options.optInt("lightColor", -1); - if (lightColor != -1) { - Log.d(TAG, "Channel "+id+" - lightColor="+lightColor); - channel.setLightColor(lightColor); - } - - // Visibility - int visibility = options.optInt("visibility", NotificationCompat.VISIBILITY_PUBLIC); - Log.d(TAG, "Channel "+id+" - visibility="+visibility); - channel.setLockscreenVisibility(visibility); - - // Badge - boolean badge = options.optBoolean("badge", true); - Log.d(TAG, "Channel "+id+" - badge="+badge); - channel.setShowBadge(badge); - - // Sound - String sound = options.optString("sound", "default"); - AudioAttributes audioAttributes = new AudioAttributes.Builder() - .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) - .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build(); - if ("ringtone".equals(sound)) { - channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), audioAttributes); - Log.d(TAG, "Channel "+id+" - sound=ringtone"); - } else if (sound != null && !sound.contentEquals("default")) { - Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/raw/" + sound); - channel.setSound(soundUri, audioAttributes); - Log.d(TAG, "Channel "+id+" - sound="+sound); - } else if (sound != "false"){ - channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes); - Log.d(TAG, "Channel "+id+" - sound=default"); - }else{ - Log.d(TAG, "Channel "+id+" - sound=none"); - } - - // Vibration: if vibration setting is an array set vibration pattern, else set enable vibration. - JSONArray pattern = options.optJSONArray("vibration"); - if (pattern != null) { - int patternLength = pattern.length(); - long[] patternArray = new long[patternLength]; - for (int i = 0; i < patternLength; i++) { - patternArray[i] = pattern.optLong(i); - } - channel.enableVibration(true); - channel.setVibrationPattern(patternArray); - Log.d(TAG, "Channel "+id+" - vibrate="+pattern); - } else { - boolean vibrate = options.optBoolean("vibration", true); - channel.enableVibration(vibrate); - Log.d(TAG, "Channel "+id+" - vibrate="+vibrate); - } - - // Create channel - nm.createNotificationChannel(channel); - } - return channel; - } - - protected static void createDefaultChannel() throws JSONException { - JSONObject options = new JSONObject(); - options.put("id", defaultChannelId); - options.put("name", defaultChannelName); - createDefaultChannel(options); - } - - protected static void createDefaultChannel(final JSONObject options) throws JSONException { - defaultNotificationChannel = createChannel(options); - } - - public void setDefaultChannel(final CallbackContext callbackContext, final JSONObject options) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - deleteChannel(defaultChannelId); - - String id = options.optString("id", null); - if(id != null){ - defaultChannelId = id; - } - - String name = options.optString("name", null); - if(name != null){ - defaultChannelName = name; - } - createDefaultChannel(options); - callbackContext.success(); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public void deleteChannel(final CallbackContext callbackContext, final String channelID) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - deleteChannel(channelID); - callbackContext.success(); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - protected static void deleteChannel(final String channelID){ - // only call on Android O and above - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); - nm.deleteNotificationChannel(channelID); - } - } - - public void listChannels(final CallbackContext callbackContext) { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - List notificationChannels = listChannels(); - JSONArray channels = new JSONArray(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - for (NotificationChannel notificationChannel : notificationChannels) { - JSONObject channel = new JSONObject(); - channel.put("id", notificationChannel.getId()); - channel.put("name", notificationChannel.getName()); - channels.put(channel); - } - } - callbackContext.success(channels); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - public static List listChannels(){ - List notificationChannels = null; - // only call on Android O and above - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); - notificationChannels = nm.getNotificationChannels(); - } - return notificationChannels; - } - - public static boolean channelExists(String channelId){ - boolean exists = false; - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ - List notificationChannels = FirebasePlugin.listChannels(); - if(notificationChannels != null){ - for (NotificationChannel notificationChannel : notificationChannels) { - if(notificationChannel.getId().equals(channelId)){ - exists = true; - } - } - } - } - return exists; - } - - // - // Firestore - // - private void addDocumentToFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String jsonDoc = args.getString(0); - String collection = args.getString(1); - - firestore.collection(collection) - .add(jsonStringToMap(jsonDoc)) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(DocumentReference documentReference) { - callbackContext.success(documentReference.getId()); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void setDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String documentId = args.getString(0); - String jsonDoc = args.getString(1); - String collection = args.getString(2); - - firestore.collection(collection).document(documentId) - .set(jsonStringToMap(jsonDoc)) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(Void aVoid) { - callbackContext.success(); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void updateDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String documentId = args.getString(0); - String jsonDoc = args.getString(1); - String collection = args.getString(2); - - firestore.collection(collection).document(documentId) - .update(jsonStringToMap(jsonDoc)) - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(Void aVoid) { - callbackContext.success(); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void deleteDocumentFromFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String documentId = args.getString(0); - String collection = args.getString(1); - - firestore.collection(collection).document(documentId) - .delete() - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(Void aVoid) { - callbackContext.success(); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void documentExistsInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String documentId = args.getString(0); - String collection = args.getString(1); - - firestore.collection(collection).document(documentId) - .get() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - try { - if (task.isSuccessful()) { - DocumentSnapshot document = task.getResult(); - callbackContext.success(document != null && document.getData() != null ? 1 : 0); - } else { - Exception e = task.getException(); - if(e != null){ - handleExceptionWithContext(e, callbackContext); - } - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void fetchDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String documentId = args.getString(0); - String collection = args.getString(1); - - firestore.collection(collection).document(documentId) - .get() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - try { - if (task.isSuccessful()) { - DocumentSnapshot document = task.getResult(); - if (document != null && document.getData() != null) { - JSONObject jsonDoc = mapToJsonObject(document.getData()); - callbackContext.success(jsonDoc); - } else { - callbackContext.error("No document found in collection"); - } - } else { - Exception e = task.getException(); - if(e != null){ - handleExceptionWithContext(e, callbackContext); - } - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - handleExceptionWithContext(e, callbackContext); - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - private void fetchFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { - cordova.getThreadPool().execute(new Runnable() { - public void run() { - try { - String collection = args.getString(0); - JSONArray filters = args.getJSONArray(1); - Query query = firestore.collection(collection); - - for(int i = 0; i < filters.length(); i++) { - JSONArray filter = filters.getJSONArray(i); - switch(filter.getString(0)) { - case "where": - if (Objects.equals(filter.getString(2), new String("=="))) { - query = query.whereEqualTo(filter.getString(1), filter.getString(3)); - } - if (Objects.equals(filter.getString(2), new String("<"))) { - query = query.whereLessThan(filter.getString(1), filter.getString(3)); - } - if (Objects.equals(filter.getString(2), new String(">"))) { - query = query.whereGreaterThan(filter.getString(1), filter.getString(3)); - } - if (Objects.equals(filter.getString(2), new String("<="))) { - query = query.whereLessThanOrEqualTo(filter.getString(1), filter.getString(3)); - } - if (Objects.equals(filter.getString(2), new String(">="))) { - query = query.whereGreaterThanOrEqualTo(filter.getString(1), filter.getString(3)); - } - if (Objects.equals(filter.getString(2), new String("array-contains"))) { - query = query.whereArrayContains(filter.getString(1), filter.getString(3)); - } - break; - case "orderBy": - Direction direction = Direction.ASCENDING; - if (Objects.equals(filter.getString(2), new String("desc"))) { - direction = Direction.DESCENDING; - } - query = query.orderBy(filter.getString(1), direction); - break; - case "startAt": - query = query.startAt(filter.getString(1)); - break; - case "endAt": - query = query.endAt(filter.getString(1)); - break; - case "limit": - query = query.limit(filter.getLong(1)); - break; - } - } - - query.get() - .addOnCompleteListener(new OnCompleteListener() { - @Override - public void onComplete(@NonNull Task task) { - try { - if (task.isSuccessful()) { - JSONObject jsonDocs = new JSONObject(); - for (QueryDocumentSnapshot document : task.getResult()) { - jsonDocs.put(document.getId(), mapToJsonObject(document.getData())); - } - callbackContext.success(jsonDocs); - } else { - handleExceptionWithContext(task.getException(), callbackContext); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - }); - } - - - protected static void handleExceptionWithContext(Exception e, CallbackContext context) { - String msg = e.toString(); - Log.e(TAG, msg); - instance.logExceptionToCrashlytics(e); - context.error(msg); - } - - protected static void handleExceptionWithoutContext(Exception e){ - String msg = e.toString(); - Log.e(TAG, msg); - if (instance != null) { - instance.logExceptionToCrashlytics(e); - instance.logErrorToWebview(msg); - } - } - - protected void logErrorToWebview(String msg){ - Log.e(TAG, msg); - executeGlobalJavascript("console.error(\""+TAG+"[native]: "+escapeDoubleQuotes(msg)+"\")"); - } - - private String escapeDoubleQuotes(String string){ - String escapedString = string.replace("\"", "\\\""); - escapedString = escapedString.replace("%22", "\\%22"); - return escapedString; - } - - private void executeGlobalJavascript(final String jsString){ - if(cordovaActivity == null) return; - cordovaActivity.runOnUiThread(new Runnable() { - @Override - public void run() { - webView.loadUrl("javascript:" + jsString); - } - }); - } - - private String saveAuthCredential(AuthCredential authCredential){ - String id = this.generateId(); - this.authCredentials.put(id, authCredential); - return id; - } - - private String saveAuthProvider(OAuthProvider authProvider){ - String id = this.generateId(); - this.authProviders.put(id, authProvider); - return id; - } - - private String generateId(){ - Random r = new Random(); - return Integer.toString(r.nextInt(1000+1)); - } - - private boolean getMetaDataFromManifest(String name) throws Exception{ - return applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean(name); - } - - private void setPreference(String name, boolean value){ - SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); - SharedPreferences.Editor editor = settings.edit(); - editor.putBoolean(name, value); - editor.apply(); - } - - private boolean getPreference(String name){ - SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); - return settings.getBoolean(name, false); - } - - private void handleTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { - try { - if (task.isSuccessful()) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - }else{ - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, task.getException().getMessage())); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - - private void handleAuthTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { - try { - if (task.isSuccessful()) { - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - }else{ - String errMessage = task.getException().getMessage(); - if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { - errMessage = "Invalid verification code"; - } - callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, errMessage)); - } - } catch (Exception e) { - handleExceptionWithContext(e, callbackContext); - } - } - - private AuthCredential obtainAuthCredential(JSONObject jsonCredential) throws JSONException { - AuthCredential authCredential = null; - if(jsonCredential.has("verificationId") && jsonCredential.has("code")){ - Log.d(TAG, "Using specified verificationId and code to authenticate"); - authCredential = (AuthCredential) PhoneAuthProvider.getCredential(jsonCredential.getString("verificationId"), jsonCredential.getString("code")); - }else if(jsonCredential.has("id") && FirebasePlugin.instance.authCredentials.containsKey(jsonCredential.getString("id"))){ - Log.d(TAG, "Using native auth credential to authenticate"); - authCredential = FirebasePlugin.instance.authCredentials.get(jsonCredential.getString("id")); - } - return authCredential; - } - - private OAuthProvider obtainAuthProvider(JSONObject jsonCredential) throws JSONException{ - OAuthProvider authProvider = null; - if(jsonCredential.has("id") && FirebasePlugin.instance.authProviders.containsKey(jsonCredential.getString("id"))){ - Log.d(TAG, "Using native auth provider to authenticate"); - authProvider = FirebasePlugin.instance.authProviders.get(jsonCredential.getString("id")); - } - return authProvider; - } - - - private static class AuthResultOnSuccessListener implements OnSuccessListener { - @Override - public void onSuccess(AuthResult authResult) { - Log.d(TAG, "AuthResult:onSuccess:" + authResult); - if(FirebasePlugin.instance.authResultCallbackContext != null){ - FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); - } - } - } - - private static class AuthResultOnFailureListener implements OnFailureListener { - @Override - public void onFailure(@NonNull Exception e) { - Log.w(TAG, "AuthResult:onFailure", e); - if(FirebasePlugin.instance.authResultCallbackContext != null){ - FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); - } - } - } - - private static class AuthResultOnCompleteListener implements OnCompleteListener { - private final CallbackContext callbackContext; - - public AuthResultOnCompleteListener(CallbackContext callbackContext) { - this.callbackContext = callbackContext; - } - - @Override - public void onComplete(@NonNull Task task) { - FirebasePlugin.instance.handleAuthTaskOutcome(task, callbackContext); - } - } - - private static class AuthStateListener implements FirebaseAuth.AuthStateListener { - @Override - public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { - try { - if(!FirebasePlugin.instance.authStateChangeListenerInitialized){ - FirebasePlugin.instance.authStateChangeListenerInitialized = true; - }else{ - FirebaseUser user = firebaseAuth.getCurrentUser(); - FirebasePlugin.instance.executeGlobalJavascript(JS_GLOBAL_NAMESPACE+"_onAuthStateChange("+(user != null ? "true" : "false")+")"); - } - } catch (Exception e) { - handleExceptionWithoutContext(e); - } - } - } - - private Map jsonStringToMap(String jsonString) throws JSONException { - Type type = new TypeToken>(){}.getType(); - return gson.fromJson(jsonString, type); - } - - - private JSONObject mapToJsonObject(Map map) throws JSONException { - String jsonString = gson.toJson(map); - return new JSONObject(jsonString); - } - - private void logMessageToCrashlytics(String message){ - if(isCrashlyticsEnabled){ - try{ - Crashlytics.log(message); - }catch (Exception e){ - Log.e(TAG, e.getMessage()); - } - }else{ - Log.e(TAG, "Cannot log message - Crashlytics collection is disabled"); - } - } - - private void logExceptionToCrashlytics(Exception exception){ - if(isCrashlyticsEnabled){ - try{ - Crashlytics.logException(exception); - }catch (Exception e){ - Log.e(TAG, e.getMessage()); - } - }else{ - Log.e(TAG, "Cannot log exception - Crashlytics collection is disabled"); - } - } -} +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.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import android.util.Base64; import android.util.Log; 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.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.analytics.FirebaseAnalytics; import com.google.firebase.auth.AuthCredential; 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.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; 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.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 org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; 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; // 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.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 Gson gson; private FirebaseAuth.AuthStateListener authStateListener; private boolean authStateChangeListenerInitialized = false; private static CordovaInterface cordovaInterface = null; protected static Context applicationContext = null; private static Activity cordovaActivity = null; private boolean isCrashlyticsEnabled = false; 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 boolean inBackground = true; private static ArrayList notificationStack = null; private static CallbackContext notificationCallbackContext; private static CallbackContext tokenRefreshCallbackContext; private static CallbackContext activityResultCallbackContext; private static CallbackContext authResultCallbackContext; private static NotificationChannel defaultNotificationChannel = null; public static String defaultChannelId = null; public static String defaultChannelName = null; private Map authCredentials = new HashMap(); private Map authProviders = new HashMap(); @Override protected void pluginInitialize() { instance = this; cordovaActivity = this.cordova.getActivity(); applicationContext = cordovaActivity.getApplicationContext(); final Bundle extras = cordovaActivity.getIntent().getExtras(); FirebasePlugin.cordovaInterface = this.cordova; firebaseCrashlytics = FirebaseCrashlytics.getInstance(); this.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.d(TAG, "Starting Firebase plugin"); if(!getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ isCrashlyticsEnabled = getPreference(CRASHLYTICS_COLLECTION_ENABLED); if(isCrashlyticsEnabled){ firebaseCrashlytics.setCrashlyticsCollectionEnabled(true); } }else{ isCrashlyticsEnabled = true; 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); } FirebaseApp.initializeApp(applicationContext); mFirebaseAnalytics = FirebaseAnalytics.getInstance(applicationContext); authStateListener = new AuthStateListener(); FirebaseAuth.getInstance().addAuthStateListener(authStateListener); firestore = FirebaseFirestore.getInstance(); gson = new Gson(); if (extras != null && extras.size() > 1) { if (FirebasePlugin.notificationStack == null) { FirebasePlugin.notificationStack = new ArrayList(); } 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{ 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("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("isAutoInitEnabled")) { isAutoInitEnabled(callbackContext); return true; } else if (action.equals("setAutoInitEnabled")) { setAutoInitEnabled(callbackContext, args.getBoolean(0)); return true; } else if (action.equals("unregister")) { this.unregister(callbackContext); return true; } else if (action.equals("onMessageReceived")) { this.onMessageReceived(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); 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")) { this.getByteArray(callbackContext, args.getString(0)); return true; } else if (action.equals("getValue")) { this.getValue(callbackContext, args.getString(0)); 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")) { this.setDefaults(callbackContext, args.getJSONObject(0)); return true; } else if (action.equals("verifyPhoneNumber")) { this.verifyPhoneNumber(callbackContext, args); return true; } else if (action.equals("authenticateUserWithGoogle")) { this.authenticateUserWithGoogle(callbackContext, args); return true; } else if (action.equals("authenticateUserWithApple")) { this.authenticateUserWithApple(callbackContext, args); return true; } else if (action.equals("createUserWithEmailAndPassword")) { this.createUserWithEmailAndPassword(callbackContext, args); return true; } else if (action.equals("signInUserWithEmailAndPassword")) { this.signInUserWithEmailAndPassword(callbackContext, args); return true; } else if (action.equals("signInUserWithCustomToken")) { this.signInUserWithCustomToken(callbackContext, args); return true; } else if (action.equals("signInUserAnonymously")) { this.signInUserAnonymously(callbackContext); return true; } else if (action.equals("signInWithCredential")) { this.signInWithCredential(callbackContext, args); return true; } else if (action.equals("linkUserWithCredential")) { this.linkUserWithCredential(callbackContext, args); return true; } else if (action.equals("reauthenticateWithCredential")) { this.reauthenticateWithCredential(callbackContext, args); return true; } else if (action.equals("isUserSignedIn")) { this.isUserSignedIn(callbackContext, args); return true; } else if (action.equals("signOutUser")) { this.signOutUser(callbackContext, args); return true; } else if (action.equals("getCurrentUser")) { this.getCurrentUser(callbackContext, args); return true; } else if (action.equals("reloadCurrentUser")) { this.reloadCurrentUser(callbackContext, args); return true; } else if (action.equals("updateUserProfile")) { this.updateUserProfile(callbackContext, args); return true; } else if (action.equals("updateUserEmail")) { this.updateUserEmail(callbackContext, args); return true; } else if (action.equals("sendUserEmailVerification")) { this.sendUserEmailVerification(callbackContext, args); return true; } else if (action.equals("updateUserPassword")) { this.updateUserPassword(callbackContext, args); return true; } else if (action.equals("sendUserPasswordResetEmail")) { this.sendUserPasswordResetEmail(callbackContext, args); return true; } else if (action.equals("deleteUser")) { this.deleteUser(callbackContext, args); 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("isAnalyticsCollectionEnabled")) { this.isAnalyticsCollectionEnabled(callbackContext); return true; } else if (action.equals("setPerformanceCollectionEnabled")) { this.setPerformanceCollectionEnabled(callbackContext, args.getBoolean(0)); return true; } else if (action.equals("isPerformanceCollectionEnabled")) { this.isPerformanceCollectionEnabled(callbackContext); return true; } else if (action.equals("setCrashlyticsCollectionEnabled")) { this.setCrashlyticsCollectionEnabled(callbackContext, args.getBoolean(0)); return true; } else if (action.equals("isCrashlyticsCollectionEnabled")) { this.isCrashlyticsCollectionEnabled(callbackContext); return true; } else if (action.equals("isCrashlyticsCollectionCurrentlyEnabled")) { this.isCrashlyticsCollectionCurrentlyEnabled(callbackContext); return true; } else if (action.equals("clearAllNotifications")) { this.clearAllNotifications(callbackContext); return true; } else if (action.equals("logMessage")) { logMessage(args, callbackContext); return true; } else if (action.equals("sendCrash")) { sendCrash(args, callbackContext); return true; } else if (action.equals("createChannel")) { this.createChannel(callbackContext, args.getJSONObject(0)); return true; } else if (action.equals("deleteChannel")) { this.deleteChannel(callbackContext, args.getString(0)); return true; } else if (action.equals("listChannels")) { this.listChannels(callbackContext); return true; } else if (action.equals("setDefaultChannel")) { this.setDefaultChannel(callbackContext, args.getJSONObject(0)); return true; } else if (action.equals("addDocumentToFirestoreCollection")) { this.addDocumentToFirestoreCollection(args, callbackContext); return true; } else if (action.equals("setDocumentInFirestoreCollection")) { this.setDocumentInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("updateDocumentInFirestoreCollection")) { this.updateDocumentInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("deleteDocumentFromFirestoreCollection")) { this.deleteDocumentFromFirestoreCollection(args, callbackContext); return true; } else if (action.equals("documentExistsInFirestoreCollection")) { this.documentExistsInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("fetchDocumentInFirestoreCollection")) { this.fetchDocumentInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("fetchFirestoreCollection")) { this.fetchFirestoreCollection(args, callbackContext); return true; } else if (action.equals("grantPermission") || action.equals("setBadgeNumber") || action.equals("getBadgeNumber") ) { // Stubs for other platform methods callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true)); return true; }else{ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Invalid action: " + action)); return false; } }catch(Exception e){ handleExceptionWithContext(e, callbackContext); } 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; 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 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); JSONObject returnResults = new JSONObject(); returnResults.put("instantVerification", true); returnResults.put("id", id); FirebasePlugin.activityResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 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 { String currentToken = FirebaseInstanceId.getInstance().getToken(); if (currentToken != null) { FirebasePlugin.sendToken(currentToken); } } 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(); } 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 keys = bundle.keySet(); for (String key : keys) { try { json.put(key, bundle.get(key)); } catch (JSONException e) { handleExceptionWithContext(e, callbackContext); 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) { 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 getId(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String id = FirebaseInstanceId.getInstance().getId(); callbackContext.success(id); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } private void hasPermission(final CallbackContext callbackContext) { if(cordovaActivity == null) return; cordova.getThreadPool().execute(new Runnable() { public void run() { try { NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(cordovaActivity); boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); callbackContext.success(areNotificationsEnabled ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } private void unregister(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseInstanceId.getInstance().deleteInstanceId(); callbackContext.success(); } 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(isEnabled ? 1 : 0); } 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 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) { 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 - firebaseCrashlytics collection is disabled"); } } catch (Exception e) { logExceptionToCrashlytics(e); callbackContext.error(e.getMessage()); } } }); } private void logMessage(final JSONArray data, final CallbackContext callbackContext) { if(isCrashlyticsEnabled){ String message = data.optString(0); logMessageToCrashlytics(message); callbackContext.success(); }else{ callbackContext.error("Cannot log message - firebaseCrashlytics collection is disabled"); } } private void sendCrash(final JSONArray data, final CallbackContext callbackContext) { cordovaActivity.runOnUiThread(new Runnable() { @Override public void run() { throw new RuntimeException("This is a crash"); } }); } private void setCrashlyticsUserId(final CallbackContext callbackContext, final String userId) { cordovaActivity.runOnUiThread(new Runnable() { public void run() { try { if(isCrashlyticsEnabled){ firebaseCrashlytics.setUserId(userId); callbackContext.success(); }else{ callbackContext.error("Cannot set firebaseCrashlytics user ID - firebaseCrashlytics collection is disabled"); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void setScreenName(final CallbackContext callbackContext, final String name) { // This must be called on the main thread cordovaActivity.runOnUiThread(new Runnable() { public void run() { try { mFirebaseAnalytics.setCurrentScreen(cordovaActivity, name, null); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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 task) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { task.addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void data) { callbackContext.success(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void getByteArray(final CallbackContext callbackContext, final String key) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { byte[] bytes = FirebaseRemoteConfig.getInstance().getByteArray(key); JSONObject object = new JSONObject(); object.put("base64", Base64.encodeToString(bytes, Base64.DEFAULT)); object.put("array", new JSONArray(bytes)); callbackContext.success(object); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void getValue(final CallbackContext callbackContext, final String key) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseRemoteConfigValue value = FirebaseRemoteConfig.getInstance().getValue(key); callbackContext.success(value.asString()); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } private void setDefaults(final CallbackContext callbackContext, final JSONObject defaults) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults)); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private static Map defaultsToMap(JSONObject object) throws JSONException { final Map map = new HashMap(); for (Iterator 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; } public void isUserSignedIn(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { boolean isSignedIn = FirebaseAuth.getInstance().getCurrentUser() != null; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, isSignedIn)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signOutUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } // Sign out of Firebase FirebaseAuth.getInstance().signOut(); // Try to sign out of Google try{ GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build(); GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(cordovaActivity, gso); mGoogleSignInClient.signOut() .addOnCompleteListener(cordovaActivity, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } }); }catch(Exception googleSignOutException){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void getCurrentUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } extractAndReturnUserInfo(callbackContext); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void reloadCurrentUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } user.reload() .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { try { extractAndReturnUserInfo(callbackContext); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void extractAndReturnUserInfo(final CallbackContext callbackContext) throws Exception{ FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); JSONObject returnResults = new JSONObject(); returnResults.put("name", user.getDisplayName()); returnResults.put("email", user.getEmail()); returnResults.put("emailIsVerified", user.isEmailVerified()); returnResults.put("phoneNumber", user.getPhoneNumber()); returnResults.put("photoUrl", user.getPhotoUrl() == null ? null : user.getPhotoUrl().toString()); returnResults.put("uid", user.getUid()); returnResults.put("providerId", user.getIdToken(false).getResult().getSignInProvider()); returnResults.put("isAnonymous", user.isAnonymous()); user.getIdToken(true).addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(GetTokenResult result) { try { String idToken = result.getToken(); returnResults.put("idToken", idToken); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void updateUserProfile(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } JSONObject profile = args.getJSONObject(0); UserProfileChangeRequest profileUpdates; if(profile.has("name") && profile.has("photoUri")){ profileUpdates = new UserProfileChangeRequest.Builder() .setDisplayName(profile.getString("name")) .setPhotoUri(Uri.parse(profile.getString("photoUri"))) .build(); }else if(profile.has("name")){ profileUpdates = new UserProfileChangeRequest.Builder() .setDisplayName(profile.getString("name")) .build(); }else if(profile.has("photoUri")){ profileUpdates = new UserProfileChangeRequest.Builder() .setPhotoUri(Uri.parse(profile.getString("photoUri"))) .build(); }else{ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "'name' and/or 'photoUri' keys must be specified in the profile object")); return; } user.updateProfile(profileUpdates) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void updateUserEmail(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } String email = args.getString(0); user.updateEmail(email) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void sendUserEmailVerification(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void updateUserPassword(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } String password = args.getString(0); user.updatePassword(password) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void sendUserPasswordResetEmail(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseAuth auth = FirebaseAuth.getInstance(); String email = args.getString(0); auth.sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void deleteUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } user.delete() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void reauthenticateWithCredential(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } JSONObject jsonCredential = args.getJSONObject(0); if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); return; } AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); if(authCredential != null){ user.reauthenticate(authCredential) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); return; } OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); if(authProvider != null){ FirebasePlugin.instance.authResultCallbackContext = callbackContext; user.startActivityForReauthenticateWithProvider(FirebasePlugin.cordovaActivity, authProvider) .addOnSuccessListener(new AuthResultOnSuccessListener()) .addOnFailureListener(new AuthResultOnFailureListener()); return; } //ELSE callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInWithCredential(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject jsonCredential = args.getJSONObject(0); if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); return; } AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); if(authCredential != null){ FirebaseAuth.getInstance().signInWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); return; } OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); if(authProvider != null){ FirebasePlugin.instance.authResultCallbackContext = callbackContext; FirebaseAuth.getInstance().startActivityForSignInWithProvider(FirebasePlugin.cordovaActivity, authProvider) .addOnSuccessListener(new AuthResultOnSuccessListener()) .addOnFailureListener(new AuthResultOnFailureListener()); return; } //ELSE callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void linkUserWithCredential(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject jsonCredential = args.getJSONObject(0); if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); return; } AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); if(authCredential != null){ FirebaseAuth.getInstance().getCurrentUser().linkWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); return; } //ELSE callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private boolean isValidJsonCredential(JSONObject jsonCredential) throws JSONException{ return jsonCredential.has("id") || (jsonCredential.has("verificationId") && jsonCredential.has("code")); } private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks; public void verifyPhoneNumber( final CallbackContext callbackContext, final JSONArray args ) { 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"); String id = FirebasePlugin.instance.saveAuthCredential((AuthCredential) credential); JSONObject returnResults = new JSONObject(); try { returnResults.put("instantVerification", true); returnResults.put("id", id); } catch(JSONException e){ handleExceptionWithContext(e, callbackContext); 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; 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"; }else{ errorMsg = e.getMessage(); } 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) { handleExceptionWithContext(e, callbackContext); return; } PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, returnResults); pluginresult.setKeepCallback(true); callbackContext.sendPluginResult(pluginresult); } }; String number = args.getString(0); int timeOutDuration = args.getInt(1); String smsCode = args.getString(2); if(smsCode != null && smsCode != "null"){ FirebaseAuth.getInstance().getFirebaseAuthSettings().setAutoRetrievedSmsCodeForPhoneNumber(number, smsCode); } PhoneAuthProvider.getInstance().verifyPhoneNumber(number, // Phone number to verify timeOutDuration, // Timeout duration TimeUnit.SECONDS, // Unit of timeout cordovaActivity, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void createUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String email = args.getString(0); String password = args.getString(1); if(email == null || email.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); return; } if(password == null || password.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); return; } FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String email = args.getString(0); String password = args.getString(1); if(email == null || email.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); return; } if(password == null || password.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); return; } FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void authenticateUserWithGoogle(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String clientId = args.getString(0); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(clientId) .requestEmail() .build(); GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(FirebasePlugin.instance.cordovaActivity, gso); Intent signInIntent = mGoogleSignInClient.getSignInIntent(); FirebasePlugin.activityResultCallbackContext = callbackContext; FirebasePlugin.instance.cordovaInterface.startActivityForResult(FirebasePlugin.instance, signInIntent, GOOGLE_SIGN_IN); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void authenticateUserWithApple(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String locale = args.getString(0); OAuthProvider.Builder provider = OAuthProvider.newBuilder("apple.com"); if(locale != null){ provider.addCustomParameter("locale", locale); } Task pending = FirebaseAuth.getInstance().getPendingAuthResult(); if (pending != null) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Auth result is already pending")); pending .addOnSuccessListener(new AuthResultOnSuccessListener()) .addOnFailureListener(new AuthResultOnFailureListener()); } else { String id = FirebasePlugin.instance.saveAuthProvider(provider.build());; JSONObject returnResults = new JSONObject(); returnResults.put("instantVerification", true); returnResults.put("id", id); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInUserWithCustomToken(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String customToken = args.getString(0); if(customToken == null || customToken.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Custom token must be specified")); return; } FirebaseAuth.getInstance().signInWithCustomToken(customToken).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInUserAnonymously(final CallbackContext callbackContext){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } // // Firebase Performace // private HashMap traces = new HashMap(); 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) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } 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.incrementMetric(counterNamed, 1); callbackContext.success(); } else { callbackContext.error("Trace not found"); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } 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) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void setAnalyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { if(getMetaDataFromManifest(ANALYTICS_COLLECTION_ENABLED)){ callbackContext.error("Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); }else if(enabled && getPreference(ANALYTICS_COLLECTION_ENABLED)){ callbackContext.error("Analytics data collection is already set to enabled"); }else if(!enabled && !getPreference(ANALYTICS_COLLECTION_ENABLED)){ callbackContext.error("Analytics data collection is already set to disabled"); }else{ mFirebaseAnalytics.setAnalyticsCollectionEnabled(enabled); setPreference(ANALYTICS_COLLECTION_ENABLED, enabled); callbackContext.success(); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isAnalyticsCollectionEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(getPreference(ANALYTICS_COLLECTION_ENABLED) ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void setPerformanceCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { if(getMetaDataFromManifest(PERFORMANCE_COLLECTION_ENABLED)){ callbackContext.error("Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); }else if(enabled && getPreference(PERFORMANCE_COLLECTION_ENABLED)){ callbackContext.error("Performance data collection is already set to enabled"); }else if(!enabled && !getPreference(PERFORMANCE_COLLECTION_ENABLED)){ callbackContext.error("Performance data collection is already set to disabled"); }else{ FirebasePerformance.getInstance().setPerformanceCollectionEnabled(enabled); setPreference(PERFORMANCE_COLLECTION_ENABLED, enabled); callbackContext.success(); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isPerformanceCollectionEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(getPreference(PERFORMANCE_COLLECTION_ENABLED) ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void setCrashlyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { if(getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ callbackContext.error("Cannot set firebaseCrashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); }else if(enabled && getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ callbackContext.error("firebaseCrashlytics data collection is already set to enabled"); }else if(!enabled && !getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ callbackContext.error("firebaseCrashlytics data collection is already set to disabled"); }else{ setPreference(CRASHLYTICS_COLLECTION_ENABLED, enabled); callbackContext.success(); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isCrashlyticsCollectionEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(getPreference(CRASHLYTICS_COLLECTION_ENABLED) ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isCrashlyticsCollectionCurrentlyEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(isCrashlyticsEnabled ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } public void clearAllNotifications(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancelAll(); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void createChannel(final CallbackContext callbackContext, final JSONObject options) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { createChannel(options); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } protected static NotificationChannel createChannel(final JSONObject options) throws JSONException { NotificationChannel channel = null; // only call on Android O and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String id = options.getString("id"); Log.i(TAG, "Creating channel id="+id); if(channelExists(id)){ deleteChannel(id); } NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); String packageName = cordovaActivity.getPackageName(); String name = options.optString("name", ""); Log.d(TAG, "Channel "+id+" - name="+name); int importance = options.optInt("importance", NotificationManager.IMPORTANCE_HIGH); Log.d(TAG, "Channel "+id+" - importance="+importance); channel = new NotificationChannel(id, name, importance); // Description String description = options.optString("description", ""); Log.d(TAG, "Channel "+id+" - description="+description); channel.setDescription(description); // Light boolean light = options.optBoolean("light", true); Log.d(TAG, "Channel "+id+" - light="+light); channel.enableLights(light); int lightColor = options.optInt("lightColor", -1); if (lightColor != -1) { Log.d(TAG, "Channel "+id+" - lightColor="+lightColor); channel.setLightColor(lightColor); } // Visibility int visibility = options.optInt("visibility", NotificationCompat.VISIBILITY_PUBLIC); Log.d(TAG, "Channel "+id+" - visibility="+visibility); channel.setLockscreenVisibility(visibility); // Badge boolean badge = options.optBoolean("badge", true); Log.d(TAG, "Channel "+id+" - badge="+badge); channel.setShowBadge(badge); // Sound String sound = options.optString("sound", "default"); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build(); if ("ringtone".equals(sound)) { channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), audioAttributes); Log.d(TAG, "Channel "+id+" - sound=ringtone"); } else if (sound != null && !sound.contentEquals("default")) { Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/raw/" + sound); channel.setSound(soundUri, audioAttributes); Log.d(TAG, "Channel "+id+" - sound="+sound); } else if (sound != "false"){ channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes); Log.d(TAG, "Channel "+id+" - sound=default"); }else{ Log.d(TAG, "Channel "+id+" - sound=none"); } // Vibration: if vibration setting is an array set vibration pattern, else set enable vibration. JSONArray pattern = options.optJSONArray("vibration"); if (pattern != null) { int patternLength = pattern.length(); long[] patternArray = new long[patternLength]; for (int i = 0; i < patternLength; i++) { patternArray[i] = pattern.optLong(i); } channel.enableVibration(true); channel.setVibrationPattern(patternArray); Log.d(TAG, "Channel "+id+" - vibrate="+pattern); } else { boolean vibrate = options.optBoolean("vibration", true); channel.enableVibration(vibrate); Log.d(TAG, "Channel "+id+" - vibrate="+vibrate); } // Create channel nm.createNotificationChannel(channel); } return channel; } protected static void createDefaultChannel() throws JSONException { JSONObject options = new JSONObject(); options.put("id", defaultChannelId); options.put("name", defaultChannelName); createDefaultChannel(options); } protected static void createDefaultChannel(final JSONObject options) throws JSONException { defaultNotificationChannel = createChannel(options); } public void setDefaultChannel(final CallbackContext callbackContext, final JSONObject options) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { deleteChannel(defaultChannelId); String id = options.optString("id", null); if(id != null){ defaultChannelId = id; } String name = options.optString("name", null); if(name != null){ defaultChannelName = name; } createDefaultChannel(options); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void deleteChannel(final CallbackContext callbackContext, final String channelID) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { deleteChannel(channelID); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } protected static void deleteChannel(final String channelID){ // only call on Android O and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); nm.deleteNotificationChannel(channelID); } } public void listChannels(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { List notificationChannels = listChannels(); JSONArray channels = new JSONArray(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { for (NotificationChannel notificationChannel : notificationChannels) { JSONObject channel = new JSONObject(); channel.put("id", notificationChannel.getId()); channel.put("name", notificationChannel.getName()); channels.put(channel); } } callbackContext.success(channels); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public static List listChannels(){ List notificationChannels = null; // only call on Android O and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationChannels = nm.getNotificationChannels(); } return notificationChannels; } public static boolean channelExists(String channelId){ boolean exists = false; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ List notificationChannels = FirebasePlugin.listChannels(); if(notificationChannels != null){ for (NotificationChannel notificationChannel : notificationChannels) { if(notificationChannel.getId().equals(channelId)){ exists = true; } } } } return exists; } // // Firestore // private void addDocumentToFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String jsonDoc = args.getString(0); String collection = args.getString(1); firestore.collection(collection) .add(jsonStringToMap(jsonDoc)) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(DocumentReference documentReference) { callbackContext.success(documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void setDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String jsonDoc = args.getString(1); String collection = args.getString(2); firestore.collection(collection).document(documentId) .set(jsonStringToMap(jsonDoc)) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { callbackContext.success(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void updateDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String jsonDoc = args.getString(1); String collection = args.getString(2); firestore.collection(collection).document(documentId) .update(jsonStringToMap(jsonDoc)) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { callbackContext.success(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void deleteDocumentFromFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String collection = args.getString(1); firestore.collection(collection).document(documentId) .delete() .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { callbackContext.success(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void documentExistsInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String collection = args.getString(1); firestore.collection(collection).document(documentId) .get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { try { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); callbackContext.success(document != null && document.getData() != null ? 1 : 0); } else { Exception e = task.getException(); if(e != null){ handleExceptionWithContext(e, callbackContext); } } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void fetchDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String collection = args.getString(1); firestore.collection(collection).document(documentId) .get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { try { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document != null && document.getData() != null) { JSONObject jsonDoc = mapToJsonObject(document.getData()); callbackContext.success(jsonDoc); } else { callbackContext.error("No document found in collection"); } } else { Exception e = task.getException(); if(e != null){ handleExceptionWithContext(e, callbackContext); } } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void fetchFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String collection = args.getString(0); JSONArray filters = args.getJSONArray(1); Query query = firestore.collection(collection); for(int i = 0; i < filters.length(); i++) { JSONArray filter = filters.getJSONArray(i); switch(filter.getString(0)) { case "where": if (Objects.equals(filter.getString(2), new String("=="))) { query = query.whereEqualTo(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String("<"))) { query = query.whereLessThan(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String(">"))) { query = query.whereGreaterThan(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String("<="))) { query = query.whereLessThanOrEqualTo(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String(">="))) { query = query.whereGreaterThanOrEqualTo(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String("array-contains"))) { query = query.whereArrayContains(filter.getString(1), filter.getString(3)); } break; case "orderBy": Direction direction = Direction.ASCENDING; if (Objects.equals(filter.getString(2), new String("desc"))) { direction = Direction.DESCENDING; } query = query.orderBy(filter.getString(1), direction); break; case "startAt": query = query.startAt(filter.getString(1)); break; case "endAt": query = query.endAt(filter.getString(1)); break; case "limit": query = query.limit(filter.getLong(1)); break; } } query.get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { try { if (task.isSuccessful()) { JSONObject jsonDocs = new JSONObject(); for (QueryDocumentSnapshot document : task.getResult()) { jsonDocs.put(document.getId(), mapToJsonObject(document.getData())); } callbackContext.success(jsonDocs); } else { handleExceptionWithContext(task.getException(), callbackContext); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } protected static void handleExceptionWithContext(Exception e, CallbackContext context) { String msg = e.toString(); Log.e(TAG, msg); instance.logExceptionToCrashlytics(e); context.error(msg); } protected static void handleExceptionWithoutContext(Exception e){ String msg = e.toString(); Log.e(TAG, msg); if (instance != null) { instance.logExceptionToCrashlytics(e); instance.logErrorToWebview(msg); } } protected void logErrorToWebview(String msg){ Log.e(TAG, msg); executeGlobalJavascript("console.error(\""+TAG+"[native]: "+escapeDoubleQuotes(msg)+"\")"); } private String escapeDoubleQuotes(String string){ String escapedString = string.replace("\"", "\\\""); escapedString = escapedString.replace("%22", "\\%22"); return escapedString; } private void executeGlobalJavascript(final String jsString){ if(cordovaActivity == null) return; cordovaActivity.runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:" + jsString); } }); } private String saveAuthCredential(AuthCredential authCredential){ String id = this.generateId(); this.authCredentials.put(id, authCredential); return id; } private String saveAuthProvider(OAuthProvider authProvider){ String id = this.generateId(); this.authProviders.put(id, authProvider); return id; } private String generateId(){ Random r = new Random(); return Integer.toString(r.nextInt(1000+1)); } private boolean getMetaDataFromManifest(String name) throws Exception{ return applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean(name); } private void setPreference(String name, boolean value){ SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(name, value); editor.apply(); } private boolean getPreference(String name){ SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); return settings.getBoolean(name, false); } private void handleTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { try { if (task.isSuccessful()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); }else{ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, task.getException().getMessage())); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } private void handleAuthTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { try { if (task.isSuccessful()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); }else{ String errMessage = task.getException().getMessage(); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { errMessage = "Invalid verification code"; } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, errMessage)); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } private AuthCredential obtainAuthCredential(JSONObject jsonCredential) throws JSONException { AuthCredential authCredential = null; if(jsonCredential.has("verificationId") && jsonCredential.has("code")){ Log.d(TAG, "Using specified verificationId and code to authenticate"); authCredential = (AuthCredential) PhoneAuthProvider.getCredential(jsonCredential.getString("verificationId"), jsonCredential.getString("code")); }else if(jsonCredential.has("id") && FirebasePlugin.instance.authCredentials.containsKey(jsonCredential.getString("id"))){ Log.d(TAG, "Using native auth credential to authenticate"); authCredential = FirebasePlugin.instance.authCredentials.get(jsonCredential.getString("id")); } return authCredential; } private OAuthProvider obtainAuthProvider(JSONObject jsonCredential) throws JSONException{ OAuthProvider authProvider = null; if(jsonCredential.has("id") && FirebasePlugin.instance.authProviders.containsKey(jsonCredential.getString("id"))){ Log.d(TAG, "Using native auth provider to authenticate"); authProvider = FirebasePlugin.instance.authProviders.get(jsonCredential.getString("id")); } return authProvider; } private static class AuthResultOnSuccessListener implements OnSuccessListener { @Override public void onSuccess(AuthResult authResult) { Log.d(TAG, "AuthResult:onSuccess:" + authResult); if(FirebasePlugin.instance.authResultCallbackContext != null){ FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } } } private static class AuthResultOnFailureListener implements OnFailureListener { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "AuthResult:onFailure", e); if(FirebasePlugin.instance.authResultCallbackContext != null){ FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); } } } private static class AuthResultOnCompleteListener implements OnCompleteListener { private final CallbackContext callbackContext; public AuthResultOnCompleteListener(CallbackContext callbackContext) { this.callbackContext = callbackContext; } @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleAuthTaskOutcome(task, callbackContext); } } private static class AuthStateListener implements FirebaseAuth.AuthStateListener { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { try { if(!FirebasePlugin.instance.authStateChangeListenerInitialized){ FirebasePlugin.instance.authStateChangeListenerInitialized = true; }else{ FirebaseUser user = firebaseAuth.getCurrentUser(); FirebasePlugin.instance.executeGlobalJavascript(JS_GLOBAL_NAMESPACE+"_onAuthStateChange("+(user != null ? "true" : "false")+")"); } } catch (Exception e) { handleExceptionWithoutContext(e); } } } private Map jsonStringToMap(String jsonString) throws JSONException { Type type = new TypeToken>(){}.getType(); return gson.fromJson(jsonString, type); } private JSONObject mapToJsonObject(Map map) throws JSONException { String jsonString = gson.toJson(map); return new JSONObject(jsonString); } private void logMessageToCrashlytics(String message){ if(isCrashlyticsEnabled){ try{ firebaseCrashlytics.log(message); }catch (Exception e){ Log.e(TAG, e.getMessage()); } }else{ Log.e(TAG, "Cannot log message - firebaseCrashlytics collection is disabled"); } } private void logExceptionToCrashlytics(Exception exception){ if(isCrashlyticsEnabled){ try{ firebaseCrashlytics.recordException(exception); }catch (Exception e){ Log.e(TAG, e.getMessage()); } }else{ Log.e(TAG, "Cannot log exception - firebaseCrashlytics collection is disabled"); } } } \ No newline at end of file diff --git a/src/android/FirebasePluginMessagingService.java b/src/android/FirebasePluginMessagingService.java old mode 100755 new mode 100644 index 3f385d94f..1a6ca5e63 --- a/src/android/FirebasePluginMessagingService.java +++ b/src/android/FirebasePluginMessagingService.java @@ -1,348 +1 @@ -package org.apache.cordova.firebase; - -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.graphics.BitmapFactory; -import android.media.RingtoneManager; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import androidx.core.app.NotificationCompat; -import android.util.Log; -import android.app.Notification; -import android.text.TextUtils; -import android.content.ContentResolver; -import android.graphics.Color; - -import com.crashlytics.android.Crashlytics; -import com.google.firebase.messaging.FirebaseMessagingService; -import com.google.firebase.messaging.RemoteMessage; - -import java.util.Map; -import java.util.Random; - -public class FirebasePluginMessagingService extends FirebaseMessagingService { - - private static final String TAG = "FirebasePlugin"; - - static final String defaultSmallIconName = "notification_icon"; - static final String defaultLargeIconName = "notification_icon_large"; - - - /** - * Called if InstanceID token is updated. This may occur if the security of - * the previous token had been compromised. Note that this is called when the InstanceID token - * is initially generated so this is where you would retrieve the token. - */ - @Override - public void onNewToken(String refreshedToken) { - try{ - super.onNewToken(refreshedToken); - Log.d(TAG, "Refreshed token: " + refreshedToken); - FirebasePlugin.sendToken(refreshedToken); - }catch (Exception e){ - FirebasePlugin.handleExceptionWithoutContext(e); - } - } - - - /** - * Called when message is received. - * Called IF message is a data message (i.e. NOT sent from Firebase console) - * OR if message is a notification message (e.g. sent from Firebase console) AND app is in foreground. - * Notification messages received while app is in background will not be processed by this method; - * they are handled internally by the OS. - * - * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. - */ - @Override - public void onMessageReceived(RemoteMessage remoteMessage) { - try{ - // [START_EXCLUDE] - // There are two types of messages data messages and notification messages. Data messages are handled - // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type - // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app - // is in the foreground. When the app is in the background an automatically generated notification is displayed. - // When the user taps on the notification they are returned to the app. Messages containing both notification - // and data payloads are treated as notification messages. The Firebase console always sends notification - // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options - // [END_EXCLUDE] - - // Pass the message to the receiver manager so any registered receivers can decide to handle it - boolean wasHandled = FirebasePluginMessageReceiverManager.onMessageReceived(remoteMessage); - if (wasHandled) { - Log.d(TAG, "Message was handled by a registered receiver"); - - // Don't process the message in this method. - return; - } - - if(FirebasePlugin.applicationContext == null){ - FirebasePlugin.applicationContext = this.getApplicationContext(); - } - - // TODO(developer): Handle FCM messages here. - // Not getting messages here? See why this may be: https://goo.gl/39bRNJ - String messageType; - String title = null; - String body = null; - String id = null; - String sound = null; - String vibrate = null; - String light = null; - String color = null; - String icon = null; - String channelId = null; - String visibility = null; - String priority = null; - boolean foregroundNotification = false; - - Map data = remoteMessage.getData(); - - if (remoteMessage.getNotification() != null) { - // Notification message payload - Log.i(TAG, "Received message: notification"); - messageType = "notification"; - id = remoteMessage.getMessageId(); - RemoteMessage.Notification notification = remoteMessage.getNotification(); - title = notification.getTitle(); - body = notification.getBody(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - channelId = notification.getChannelId(); - } - sound = notification.getSound(); - color = notification.getColor(); - icon = notification.getIcon(); - }else{ - Log.i(TAG, "Received message: data"); - messageType = "data"; - } - - if (data != null) { - // Data message payload - if(data.containsKey("notification_foreground")){ - foregroundNotification = true; - } - if(data.containsKey("notification_title")) title = data.get("notification_title"); - if(data.containsKey("notification_body")) body = data.get("notification_body"); - if(data.containsKey("notification_android_channel_id")) channelId = data.get("notification_android_channel_id"); - if(data.containsKey("notification_android_id")) id = data.get("notification_android_id"); - if(data.containsKey("notification_android_sound")) sound = data.get("notification_android_sound"); - if(data.containsKey("notification_android_vibrate")) vibrate = data.get("notification_android_vibrate"); - if(data.containsKey("notification_android_light")) light = data.get("notification_android_light"); //String containing hex ARGB color, miliseconds on, miliseconds off, example: '#FFFF00FF,1000,3000' - if(data.containsKey("notification_android_color")) color = data.get("notification_android_color"); - if(data.containsKey("notification_android_icon")) icon = data.get("notification_android_icon"); - if(data.containsKey("notification_android_visibility")) visibility = data.get("notification_android_visibility"); - if(data.containsKey("notification_android_priority")) priority = data.get("notification_android_priority"); - } - - if (TextUtils.isEmpty(id)) { - Random rand = new Random(); - int n = rand.nextInt(50) + 1; - id = Integer.toString(n); - } - - Log.d(TAG, "From: " + remoteMessage.getFrom()); - Log.d(TAG, "Id: " + id); - Log.d(TAG, "Title: " + title); - Log.d(TAG, "Body: " + body); - Log.d(TAG, "Sound: " + sound); - Log.d(TAG, "Vibrate: " + vibrate); - Log.d(TAG, "Light: " + light); - Log.d(TAG, "Color: " + color); - Log.d(TAG, "Icon: " + icon); - Log.d(TAG, "Channel Id: " + channelId); - Log.d(TAG, "Visibility: " + visibility); - Log.d(TAG, "Priority: " + priority); - - - if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) { - boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title)); - sendMessage(remoteMessage, data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility); - } - }catch (Exception e){ - FirebasePlugin.handleExceptionWithoutContext(e); - } - } - - private void sendMessage(RemoteMessage remoteMessage, Map data, String messageType, String id, String title, String body, boolean showNotification, String sound, String vibrate, String light, String color, String icon, String channelId, String priority, String visibility) { - Log.d(TAG, "sendMessage(): messageType="+messageType+"; showNotification="+showNotification+"; id="+id+"; title="+title+"; body="+body+"; sound="+sound+"; vibrate="+vibrate+"; light="+light+"; color="+color+"; icon="+icon+"; channel="+channelId+"; data="+data.toString()); - Bundle bundle = new Bundle(); - for (String key : data.keySet()) { - bundle.putString(key, data.get(key)); - } - bundle.putString("messageType", messageType); - this.putKVInBundle("id", id, bundle); - this.putKVInBundle("title", title, bundle); - this.putKVInBundle("body", body, bundle); - this.putKVInBundle("sound", sound, bundle); - this.putKVInBundle("vibrate", vibrate, bundle); - this.putKVInBundle("light", light, bundle); - this.putKVInBundle("color", color, bundle); - this.putKVInBundle("icon", icon, bundle); - this.putKVInBundle("channel_id", channelId, bundle); - this.putKVInBundle("priority", priority, bundle); - this.putKVInBundle("visibility", visibility, bundle); - this.putKVInBundle("show_notification", String.valueOf(showNotification), bundle); - this.putKVInBundle("from", remoteMessage.getFrom(), bundle); - this.putKVInBundle("collapse_key", remoteMessage.getCollapseKey(), bundle); - this.putKVInBundle("sent_time", String.valueOf(remoteMessage.getSentTime()), bundle); - this.putKVInBundle("ttl", String.valueOf(remoteMessage.getTtl()), bundle); - - if (showNotification) { - Intent intent = new Intent(this, OnNotificationOpenReceiver.class); - intent.putExtras(bundle); - PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); - - // Channel - if(channelId == null || !FirebasePlugin.channelExists(channelId)){ - channelId = FirebasePlugin.defaultChannelId; - } - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ - Log.d(TAG, "Channel ID: "+channelId); - } - - NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId); - notificationBuilder - .setContentTitle(title) - .setContentText(body) - .setStyle(new NotificationCompat.BigTextStyle().bigText(body)) - .setAutoCancel(true) - .setContentIntent(pendingIntent); - - // On Android O+ the sound/lights/vibration are determined by the channel ID - if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){ - // Sound - if (sound == null) { - Log.d(TAG, "Sound: none"); - }else if (sound.equals("default")) { - notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); - Log.d(TAG, "Sound: default"); - }else{ - Uri soundPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/" + sound); - Log.d(TAG, "Sound: custom=" + sound+"; path="+soundPath.toString()); - notificationBuilder.setSound(soundPath); - } - - // Light - if (light != null) { - try { - String[] lightsComponents = color.replaceAll("\\s", "").split(","); - if (lightsComponents.length == 3) { - int lightArgb = Color.parseColor(lightsComponents[0]); - int lightOnMs = Integer.parseInt(lightsComponents[1]); - int lightOffMs = Integer.parseInt(lightsComponents[2]); - notificationBuilder.setLights(lightArgb, lightOnMs, lightOffMs); - Log.d(TAG, "Lights: color="+lightsComponents[0]+"; on(ms)="+lightsComponents[2]+"; off(ms)="+lightsComponents[3]); - } - - } catch (Exception e) {} - } - - // Vibrate - if (vibrate != null){ - try { - String[] sVibrations = vibrate.replaceAll("\\s", "").split(","); - long[] lVibrations = new long[sVibrations.length]; - int i=0; - for(String sVibration: sVibrations){ - lVibrations[i] = Integer.parseInt(sVibration.trim()); - i++; - } - notificationBuilder.setVibrate(lVibrations); - Log.d(TAG, "Vibrate: "+vibrate); - } catch (Exception e) { - Log.e(TAG, e.getMessage()); - } - } - } - - - // Icon - int defaultSmallIconResID = getResources().getIdentifier(defaultSmallIconName, "drawable", getPackageName()); - int customSmallIconResID = 0; - if(icon != null){ - customSmallIconResID = getResources().getIdentifier(icon, "drawable", getPackageName()); - } - - if (customSmallIconResID != 0) { - notificationBuilder.setSmallIcon(customSmallIconResID); - Log.d(TAG, "Small icon: custom="+icon); - }else if (defaultSmallIconResID != 0) { - Log.d(TAG, "Small icon: default="+defaultSmallIconName); - notificationBuilder.setSmallIcon(defaultSmallIconResID); - } else { - Log.d(TAG, "Small icon: application"); - notificationBuilder.setSmallIcon(getApplicationInfo().icon); - } - - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { - int defaultLargeIconResID = getResources().getIdentifier(defaultLargeIconName, "drawable", getPackageName()); - int customLargeIconResID = 0; - if(icon != null){ - customLargeIconResID = getResources().getIdentifier(icon+"_large", "drawable", getPackageName()); - } - - int largeIconResID; - if (customLargeIconResID != 0 || defaultLargeIconResID != 0) { - if (customLargeIconResID != 0) { - largeIconResID = customLargeIconResID; - Log.d(TAG, "Large icon: custom="+icon); - }else{ - Log.d(TAG, "Large icon: default="+defaultLargeIconName); - largeIconResID = defaultLargeIconResID; - } - notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), largeIconResID)); - } - } - - // Color - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { - int defaultColor = getResources().getColor(getResources().getIdentifier("accent", "color", getPackageName()), null); - if(color != null){ - notificationBuilder.setColor(Color.parseColor(color)); - Log.d(TAG, "Color: custom="+color); - }else{ - Log.d(TAG, "Color: default"); - notificationBuilder.setColor(defaultColor); - } - } - - // Visibility - int iVisibility = NotificationCompat.VISIBILITY_PUBLIC; - if(visibility != null){ - iVisibility = Integer.parseInt(visibility); - } - Log.d(TAG, "Visibility: " + iVisibility); - notificationBuilder.setVisibility(iVisibility); - - // Priority - int iPriority = NotificationCompat.PRIORITY_MAX; - if(priority != null){ - iPriority = Integer.parseInt(priority); - } - Log.d(TAG, "Priority: " + iPriority); - notificationBuilder.setPriority(iPriority); - - - // Build notification - Notification notification = notificationBuilder.build(); - - // Display notification - NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - Log.d(TAG, "show notification: "+notification.toString()); - notificationManager.notify(id.hashCode(), notification); - } - // Send to plugin - FirebasePlugin.sendMessage(bundle, this.getApplicationContext()); - } - - private void putKVInBundle(String k, String v, Bundle b){ - if(v != null && !b.containsKey(k)){ - b.putString(k, v); - } - } -} +package org.apache.cordova.firebase; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.core.app.NotificationCompat; import android.util.Log; import android.app.Notification; import android.text.TextUtils; import android.content.ContentResolver; import android.graphics.Color; import com.google.firebase.crashlytics.FirebaseCrashlytics; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.Map; import java.util.Random; public class FirebasePluginMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebasePlugin"; static final String defaultSmallIconName = "notification_icon"; static final String defaultLargeIconName = "notification_icon_large"; /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ @Override public void onNewToken(String refreshedToken) { try{ super.onNewToken(refreshedToken); Log.d(TAG, "Refreshed token: " + refreshedToken); FirebasePlugin.sendToken(refreshedToken); }catch (Exception e){ FirebasePlugin.handleExceptionWithoutContext(e); } } /** * Called when message is received. * Called IF message is a data message (i.e. NOT sent from Firebase console) * OR if message is a notification message (e.g. sent from Firebase console) AND app is in foreground. * Notification messages received while app is in background will not be processed by this method; * they are handled internally by the OS. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { try{ // [START_EXCLUDE] // There are two types of messages data messages and notification messages. Data messages are handled // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated notification is displayed. // When the user taps on the notification they are returned to the app. Messages containing both notification // and data payloads are treated as notification messages. The Firebase console always sends notification // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options // [END_EXCLUDE] // Pass the message to the receiver manager so any registered receivers can decide to handle it boolean wasHandled = FirebasePluginMessageReceiverManager.onMessageReceived(remoteMessage); if (wasHandled) { Log.d(TAG, "Message was handled by a registered receiver"); // Don't process the message in this method. return; } if(FirebasePlugin.applicationContext == null){ FirebasePlugin.applicationContext = this.getApplicationContext(); } // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ String messageType; String title = null; String body = null; String id = null; String sound = null; String vibrate = null; String light = null; String color = null; String icon = null; String channelId = null; String visibility = null; String priority = null; boolean foregroundNotification = false; Map data = remoteMessage.getData(); if (remoteMessage.getNotification() != null) { // Notification message payload Log.i(TAG, "Received message: notification"); messageType = "notification"; id = remoteMessage.getMessageId(); RemoteMessage.Notification notification = remoteMessage.getNotification(); title = notification.getTitle(); body = notification.getBody(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { channelId = notification.getChannelId(); } sound = notification.getSound(); color = notification.getColor(); icon = notification.getIcon(); }else{ Log.i(TAG, "Received message: data"); messageType = "data"; } if (data != null) { // Data message payload if(data.containsKey("notification_foreground")){ foregroundNotification = true; } if(data.containsKey("notification_title")) title = data.get("notification_title"); if(data.containsKey("notification_body")) body = data.get("notification_body"); if(data.containsKey("notification_android_channel_id")) channelId = data.get("notification_android_channel_id"); if(data.containsKey("notification_android_id")) id = data.get("notification_android_id"); if(data.containsKey("notification_android_sound")) sound = data.get("notification_android_sound"); if(data.containsKey("notification_android_vibrate")) vibrate = data.get("notification_android_vibrate"); if(data.containsKey("notification_android_light")) light = data.get("notification_android_light"); //String containing hex ARGB color, miliseconds on, miliseconds off, example: '#FFFF00FF,1000,3000' if(data.containsKey("notification_android_color")) color = data.get("notification_android_color"); if(data.containsKey("notification_android_icon")) icon = data.get("notification_android_icon"); if(data.containsKey("notification_android_visibility")) visibility = data.get("notification_android_visibility"); if(data.containsKey("notification_android_priority")) priority = data.get("notification_android_priority"); } if (TextUtils.isEmpty(id)) { Random rand = new Random(); int n = rand.nextInt(50) + 1; id = Integer.toString(n); } Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Id: " + id); Log.d(TAG, "Title: " + title); Log.d(TAG, "Body: " + body); Log.d(TAG, "Sound: " + sound); Log.d(TAG, "Vibrate: " + vibrate); Log.d(TAG, "Light: " + light); Log.d(TAG, "Color: " + color); Log.d(TAG, "Icon: " + icon); Log.d(TAG, "Channel Id: " + channelId); Log.d(TAG, "Visibility: " + visibility); Log.d(TAG, "Priority: " + priority); if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) { boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title)); sendMessage(remoteMessage, data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility); } }catch (Exception e){ FirebasePlugin.handleExceptionWithoutContext(e); } } private void sendMessage(RemoteMessage remoteMessage, Map data, String messageType, String id, String title, String body, boolean showNotification, String sound, String vibrate, String light, String color, String icon, String channelId, String priority, String visibility) { Log.d(TAG, "sendMessage(): messageType="+messageType+"; showNotification="+showNotification+"; id="+id+"; title="+title+"; body="+body+"; sound="+sound+"; vibrate="+vibrate+"; light="+light+"; color="+color+"; icon="+icon+"; channel="+channelId+"; data="+data.toString()); Bundle bundle = new Bundle(); for (String key : data.keySet()) { bundle.putString(key, data.get(key)); } bundle.putString("messageType", messageType); this.putKVInBundle("id", id, bundle); this.putKVInBundle("title", title, bundle); this.putKVInBundle("body", body, bundle); this.putKVInBundle("sound", sound, bundle); this.putKVInBundle("vibrate", vibrate, bundle); this.putKVInBundle("light", light, bundle); this.putKVInBundle("color", color, bundle); this.putKVInBundle("icon", icon, bundle); this.putKVInBundle("channel_id", channelId, bundle); this.putKVInBundle("priority", priority, bundle); this.putKVInBundle("visibility", visibility, bundle); this.putKVInBundle("show_notification", String.valueOf(showNotification), bundle); this.putKVInBundle("from", remoteMessage.getFrom(), bundle); this.putKVInBundle("collapse_key", remoteMessage.getCollapseKey(), bundle); this.putKVInBundle("sent_time", String.valueOf(remoteMessage.getSentTime()), bundle); this.putKVInBundle("ttl", String.valueOf(remoteMessage.getTtl()), bundle); if (showNotification) { Intent intent = new Intent(this, OnNotificationOpenReceiver.class); intent.putExtras(bundle); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // Channel if(channelId == null || !FirebasePlugin.channelExists(channelId)){ channelId = FirebasePlugin.defaultChannelId; } if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ Log.d(TAG, "Channel ID: "+channelId); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId); notificationBuilder .setContentTitle(title) .setContentText(body) .setStyle(new NotificationCompat.BigTextStyle().bigText(body)) .setAutoCancel(true) .setContentIntent(pendingIntent); // On Android O+ the sound/lights/vibration are determined by the channel ID if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){ // Sound if (sound == null) { Log.d(TAG, "Sound: none"); }else if (sound.equals("default")) { notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); Log.d(TAG, "Sound: default"); }else{ Uri soundPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/" + sound); Log.d(TAG, "Sound: custom=" + sound+"; path="+soundPath.toString()); notificationBuilder.setSound(soundPath); } // Light if (light != null) { try { String[] lightsComponents = color.replaceAll("\\s", "").split(","); if (lightsComponents.length == 3) { int lightArgb = Color.parseColor(lightsComponents[0]); int lightOnMs = Integer.parseInt(lightsComponents[1]); int lightOffMs = Integer.parseInt(lightsComponents[2]); notificationBuilder.setLights(lightArgb, lightOnMs, lightOffMs); Log.d(TAG, "Lights: color="+lightsComponents[0]+"; on(ms)="+lightsComponents[2]+"; off(ms)="+lightsComponents[3]); } } catch (Exception e) {} } // Vibrate if (vibrate != null){ try { String[] sVibrations = vibrate.replaceAll("\\s", "").split(","); long[] lVibrations = new long[sVibrations.length]; int i=0; for(String sVibration: sVibrations){ lVibrations[i] = Integer.parseInt(sVibration.trim()); i++; } notificationBuilder.setVibrate(lVibrations); Log.d(TAG, "Vibrate: "+vibrate); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } } // Icon int defaultSmallIconResID = getResources().getIdentifier(defaultSmallIconName, "drawable", getPackageName()); int customSmallIconResID = 0; if(icon != null){ customSmallIconResID = getResources().getIdentifier(icon, "drawable", getPackageName()); } if (customSmallIconResID != 0) { notificationBuilder.setSmallIcon(customSmallIconResID); Log.d(TAG, "Small icon: custom="+icon); }else if (defaultSmallIconResID != 0) { Log.d(TAG, "Small icon: default="+defaultSmallIconName); notificationBuilder.setSmallIcon(defaultSmallIconResID); } else { Log.d(TAG, "Small icon: application"); notificationBuilder.setSmallIcon(getApplicationInfo().icon); } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { int defaultLargeIconResID = getResources().getIdentifier(defaultLargeIconName, "drawable", getPackageName()); int customLargeIconResID = 0; if(icon != null){ customLargeIconResID = getResources().getIdentifier(icon+"_large", "drawable", getPackageName()); } int largeIconResID; if (customLargeIconResID != 0 || defaultLargeIconResID != 0) { if (customLargeIconResID != 0) { largeIconResID = customLargeIconResID; Log.d(TAG, "Large icon: custom="+icon); }else{ Log.d(TAG, "Large icon: default="+defaultLargeIconName); largeIconResID = defaultLargeIconResID; } notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), largeIconResID)); } } // Color if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { int defaultColor = getResources().getColor(getResources().getIdentifier("accent", "color", getPackageName()), null); if(color != null){ notificationBuilder.setColor(Color.parseColor(color)); Log.d(TAG, "Color: custom="+color); }else{ Log.d(TAG, "Color: default"); notificationBuilder.setColor(defaultColor); } } // Visibility int iVisibility = NotificationCompat.VISIBILITY_PUBLIC; if(visibility != null){ iVisibility = Integer.parseInt(visibility); } Log.d(TAG, "Visibility: " + iVisibility); notificationBuilder.setVisibility(iVisibility); // Priority int iPriority = NotificationCompat.PRIORITY_MAX; if(priority != null){ iPriority = Integer.parseInt(priority); } Log.d(TAG, "Priority: " + iPriority); notificationBuilder.setPriority(iPriority); // Build notification Notification notification = notificationBuilder.build(); // Display notification NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Log.d(TAG, "show notification: "+notification.toString()); notificationManager.notify(id.hashCode(), notification); } // Send to plugin FirebasePlugin.sendMessage(bundle, this.getApplicationContext()); } private void putKVInBundle(String k, String v, Bundle b){ if(v != null && !b.containsKey(k)){ b.putString(k, v); } } } \ No newline at end of file diff --git a/src/android/build.gradle b/src/android/build.gradle old mode 100755 new mode 100644 index 0befc68a3..2770e00ec --- a/src/android/build.gradle +++ b/src/android/build.gradle @@ -1,46 +1 @@ -buildscript { - repositories { - google() - maven { - url "https://maven.fabric.io/public" - } - mavenCentral() - jcenter() - } - dependencies { - classpath "io.fabric.tools:gradle:1.30.0" - classpath 'com.android.tools.build:gradle:3.4.1' - classpath 'com.google.gms:google-services:4.2.0' - } -} -repositories { - mavenCentral() - maven { - url "https://maven.google.com" - } -} - -cdvPluginPostBuildExtras.add({ - rootProject.subprojects { - if (name == "app") { - if (!plugins.hasPlugin('com.google.gms.google-services')) { - apply { - plugin com.google.gms.googleservices.GoogleServicesPlugin - } - - // Disable strict version check as it causes problems - com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true - } - } - } - // Use class instead of id (string) to be able to apply plugin from non-root gradle file - - apply plugin: com.crashlytics.tools.gradle.CrashlyticsPlugin - - // Enable Crashlytics NDK reporting - crashlytics { - enableNdk true - } -}) - - +buildscript { repositories { google() mavenCentral() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath 'com.google.gms:google-services:4.2.0' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1' } } repositories { mavenCentral() maven { url "https://maven.google.com" } } cdvPluginPostBuildExtras.add({ rootProject.subprojects { if (name == "app") { if (!plugins.hasPlugin('com.google.gms.google-services')) { apply { plugin com.google.gms.googleservices.GoogleServicesPlugin } // Disable strict version check as it causes problems com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true } } } // Use class instead of id (string) to be able to apply plugin from non-root gradle file apply plugin: com.google.firebase.crashlytics.buildtools.gradle.CrashlyticsPlugin android { buildTypes { release { firebaseCrashlytics { nativeSymbolUploadEnabled true } } } } }) \ No newline at end of file diff --git a/src/ios/AppDelegate+FirebasePlugin.h b/src/ios/AppDelegate+FirebasePlugin.h old mode 100755 new mode 100644 index 461b17e40..1edbb12c0 --- a/src/ios/AppDelegate+FirebasePlugin.h +++ b/src/ios/AppDelegate+FirebasePlugin.h @@ -1,11 +1 @@ -#import "AppDelegate.h" -#import - -@import UserNotifications; -@import AuthenticationServices; - -@interface AppDelegate (FirebasePlugin) -+ (AppDelegate *) instance; -@property (nonatomic, strong) NSNumber * _Nonnull applicationInBackground; -@property (NS_NONATOMIC_IOSONLY, nullable, weak) id delegate; -@end +#import "AppDelegate.h" #import @import UserNotifications; @import AuthenticationServices; @interface AppDelegate (FirebasePlugin) + (AppDelegate *) instance; @property (nonatomic, strong) NSNumber * _Nonnull applicationInBackground; @property (NS_NONATOMIC_IOSONLY, nullable, weak) id delegate; @end \ No newline at end of file diff --git a/src/ios/AppDelegate+FirebasePlugin.m b/src/ios/AppDelegate+FirebasePlugin.m index bf3d4d1c9..1251e46a7 100644 --- a/src/ios/AppDelegate+FirebasePlugin.m +++ b/src/ios/AppDelegate+FirebasePlugin.m @@ -1,567 +1 @@ -#import "AppDelegate+FirebasePlugin.h" -#import "FirebasePlugin.h" -#import "Firebase.h" -#import -#import - - -@import UserNotifications; -@import FirebaseFirestore; - -// Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices running iOS 10 and above. -// Implement FIRMessagingDelegate to receive data message via FCM for devices running iOS 10 and above. -@interface AppDelegate () -@end - -#define kApplicationInBackgroundKey @"applicationInBackground" -#define kDelegateKey @"delegate" - -@implementation AppDelegate (FirebasePlugin) - -static AppDelegate* instance; - -+ (AppDelegate*) instance { - return instance; -} - -static NSDictionary* mutableUserInfo; -static FIRAuthStateDidChangeListenerHandle authStateChangeListener; -static bool authStateChangeListenerInitialized = false; -static bool shouldEstablishDirectChannel = false; - -- (void)setDelegate:(id)delegate { - objc_setAssociatedObject(self, kDelegateKey, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (id)delegate { - return objc_getAssociatedObject(self, kDelegateKey); -} - -+ (void)load { - Method original = class_getInstanceMethod(self, @selector(application:didFinishLaunchingWithOptions:)); - Method swizzled = class_getInstanceMethod(self, @selector(application:swizzledDidFinishLaunchingWithOptions:)); - method_exchangeImplementations(original, swizzled); -} - -- (void)setApplicationInBackground:(NSNumber *)applicationInBackground { - objc_setAssociatedObject(self, kApplicationInBackgroundKey, applicationInBackground, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (NSNumber *)applicationInBackground { - return objc_getAssociatedObject(self, kApplicationInBackgroundKey); -} - -- (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - [self application:application swizzledDidFinishLaunchingWithOptions:launchOptions]; - - @try{ - instance = self; - - // get GoogleService-Info.plist file path - NSString *filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; - - // if file is successfully found, use it - if(filePath){ - [FirebasePlugin.firebasePlugin _logMessage:@"GoogleService-Info.plist found, setup: [FIRApp configureWithOptions]"]; - // create firebase configure options passing .plist as content - FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; - - // configure FIRApp with options - [FIRApp configureWithOptions:options]; - if([FirebasePlugin.firebasePlugin _shouldEnableCrashlytics]){ - [Fabric with:@[[Crashlytics class]]]; - } - } - - // no .plist found, try default App - if (![FIRApp defaultApp] && !filePath) { - [FirebasePlugin.firebasePlugin _logError:@"GoogleService-Info.plist NOT FOUND, setup: [FIRApp defaultApp]"]; - [FIRApp configure]; - } - - shouldEstablishDirectChannel = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"shouldEstablishDirectChannel"] boolValue]; - - // Set FCM messaging delegate - [FIRMessaging messaging].delegate = self; - [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; - - // Setup Firestore - [FirebasePlugin setFirestore:[FIRFirestore firestore]]; - - // Setup Google SignIn - [GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID; - [GIDSignIn sharedInstance].delegate = self; - - authStateChangeListener = [[FIRAuth auth] addAuthStateDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) { - @try { - if(!authStateChangeListenerInitialized){ - authStateChangeListenerInitialized = true; - }else{ - [FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthStateChange(%@)", (user != nil ? @"true": @"false")]]; - } - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } - }]; - - // Set UNUserNotificationCenter delegate - self.delegate = [UNUserNotificationCenter currentNotificationCenter].delegate; - [UNUserNotificationCenter currentNotificationCenter].delegate = self; - - // Set NSNotificationCenter observer - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:) - name:kFIRInstanceIDTokenRefreshNotification object:nil]; - - self.applicationInBackground = @(YES); - - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } - - return YES; -} - -- (void)applicationDidBecomeActive:(UIApplication *)application { - self.applicationInBackground = @(NO); - [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"Enter foreground: FCM direct channel = %@", shouldEstablishDirectChannel ? @"true" : @"false"]]; -} - -- (void)applicationDidEnterBackground:(UIApplication *)application { - self.applicationInBackground = @(YES); - [FIRMessaging messaging].shouldEstablishDirectChannel = false; - [FirebasePlugin.firebasePlugin _logMessage:@"Enter background: FCM direct channel = false"]; -} - -# pragma mark - Google SignIn -- (void)signIn:(GIDSignIn *)signIn -didSignInForUser:(GIDGoogleUser *)user - withError:(NSError *)error { - @try{ - CDVPluginResult* pluginResult; - if (error == nil) { - GIDAuthentication *authentication = user.authentication; - FIRAuthCredential *credential = - [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken - accessToken:authentication.accessToken]; - - int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; - NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; - [result setValue:@"true" forKey:@"instantVerification"]; - [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } - if ([FirebasePlugin firebasePlugin].googleSignInCallbackId != nil) { - [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].googleSignInCallbackId]; - } - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -- (void)signIn:(GIDSignIn *)signIn -didDisconnectWithUser:(GIDGoogleUser *)user - withError:(NSError *)error { - NSString* msg = @"Google SignIn delegate: didDisconnectWithUser"; - if(error != nil){ - [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"%@: %@", msg, error]]; - }else{ - [FirebasePlugin.firebasePlugin _logMessage:msg]; - } -} - -# pragma mark - FIRMessagingDelegate -- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRegistrationToken: %@", fcmToken]]; - @try{ - [FirebasePlugin.firebasePlugin sendToken:fcmToken]; - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -- (void)tokenRefreshNotification:(NSNotification *)notification { - // Note that this callback will be fired everytime a new token is generated, including the first - // time. So if you need to retrieve the token as soon as it is available this is where that - // should be done. - @try{ - [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, - NSError * _Nullable error) { - @try{ - if (error == nil) { - NSString *refreshedToken = result.token; - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"tokenRefreshNotification: %@", refreshedToken]]; - [FirebasePlugin.firebasePlugin sendToken:refreshedToken]; - }else{ - [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"tokenRefreshNotification: %@", error.description]]; - } - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } - }]; - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { - [FIRMessaging messaging].APNSToken = deviceToken; - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didRegisterForRemoteNotificationsWithDeviceToken: %@", deviceToken]]; - [FirebasePlugin.firebasePlugin sendApnsToken:[FirebasePlugin.firebasePlugin hexadecimalStringFromData:deviceToken]]; - - // Set UNUserNotificationCenter delegate - [UNUserNotificationCenter currentNotificationCenter].delegate = self; -} - -//Tells the app that a remote notification arrived that indicates there is data to be fetched. -// Called when a message arrives in the foreground and remote notifications permission has been granted -- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo - fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { - - @try{ - [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; - mutableUserInfo = [userInfo mutableCopy]; - NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; - bool isContentAvailable = false; - if([aps objectForKey:@"alert"] != nil){ - isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; - [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; - NSString* tap; - if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && !isContentAvailable){ - tap = @"background"; - } - [mutableUserInfo setValue:tap forKey:@"tap"]; - }else{ - [mutableUserInfo setValue:@"data" forKey:@"messageType"]; - } - - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRemoteNotification: %@", mutableUserInfo]]; - - completionHandler(UIBackgroundFetchResultNewData); - if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && isContentAvailable){ - [FirebasePlugin.firebasePlugin _logError:@"didReceiveRemoteNotification: omitting foreground notification as content-available:1 so system notification will be shown"]; - }else{ - [self processMessageForForegroundNotification:mutableUserInfo]; - } - if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] || !isContentAvailable){ - [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; - } - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. -// Called when a data message is arrives in the foreground and remote notifications permission has been NOT been granted -- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage { - @try{ - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveMessage: %@", remoteMessage.appData]]; - - NSDictionary* appData = [remoteMessage.appData mutableCopy]; - [appData setValue:@"data" forKey:@"messageType"]; - [self processMessageForForegroundNotification:appData]; - - // This will allow us to handle FCM data-only push messages even if the permission for push - // notifications is yet missing. This will only work when the app is in the foreground. - [FirebasePlugin.firebasePlugin sendNotification:appData]; - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -// Scans a message for keys which indicate a notification should be shown. -// If found, extracts relevant keys and uses then to display a local notification --(void)processMessageForForegroundNotification:(NSDictionary*)messageData { - bool showForegroundNotification = [messageData objectForKey:@"notification_foreground"]; - if(!showForegroundNotification){ - return; - } - - NSString* title = nil; - NSString* body = nil; - NSString* sound = nil; - NSNumber* badge = nil; - - // Extract APNS notification keys - NSDictionary* aps = [messageData objectForKey:@"aps"]; - if([aps objectForKey:@"alert"] != nil){ - NSDictionary* alert = [aps objectForKey:@"alert"]; - if([alert objectForKey:@"title"] != nil){ - title = [alert objectForKey:@"title"]; - } - if([alert objectForKey:@"body"] != nil){ - body = [alert objectForKey:@"body"]; - } - if([aps objectForKey:@"sound"] != nil){ - sound = [aps objectForKey:@"sound"]; - } - if([aps objectForKey:@"badge"] != nil){ - badge = [aps objectForKey:@"badge"]; - } - } - - // Extract data notification keys - if([messageData objectForKey:@"notification_title"] != nil){ - title = [messageData objectForKey:@"notification_title"]; - } - if([messageData objectForKey:@"notification_body"] != nil){ - body = [messageData objectForKey:@"notification_body"]; - } - if([messageData objectForKey:@"notification_ios_sound"] != nil){ - sound = [messageData objectForKey:@"notification_ios_sound"]; - } - if([messageData objectForKey:@"notification_ios_badge"] != nil){ - badge = [messageData objectForKey:@"notification_ios_badge"]; - } - - if(title == nil || body == nil){ - return; - } - - [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { - @try{ - if (settings.alertSetting == UNNotificationSettingEnabled) { - UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; - objNotificationContent.title = [NSString localizedUserNotificationStringForKey:title arguments:nil]; - objNotificationContent.body = [NSString localizedUserNotificationStringForKey:body arguments:nil]; - - NSDictionary* alert = [[NSDictionary alloc] initWithObjectsAndKeys: - title, @"title", - body, @"body" - , nil]; - NSMutableDictionary* aps = [[NSMutableDictionary alloc] initWithObjectsAndKeys: - alert, @"alert", - nil]; - - if(![sound isKindOfClass:[NSString class]] || [sound isEqualToString:@"default"]){ - objNotificationContent.sound = [UNNotificationSound defaultSound]; - [aps setValue:sound forKey:@"sound"]; - }else if(sound != nil){ - objNotificationContent.sound = [UNNotificationSound soundNamed:sound]; - [aps setValue:sound forKey:@"sound"]; - } - - if(badge != nil){ - [aps setValue:badge forKey:@"badge"]; - } - - NSString* messageType = @"data"; - if([mutableUserInfo objectForKey:@"messageType"] != nil){ - messageType = [mutableUserInfo objectForKey:@"messageType"]; - } - - NSDictionary* userInfo = [[NSDictionary alloc] initWithObjectsAndKeys: - @"true", @"notification_foreground", - messageType, @"messageType", - aps, @"aps" - , nil]; - - objNotificationContent.userInfo = userInfo; - - UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1f repeats:NO]; - UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:objNotificationContent trigger:trigger]; - [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { - if (!error) { - [FirebasePlugin.firebasePlugin _logMessage:@"Local Notification succeeded"]; - } else { - [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"Local Notification failed: %@", error.description]]; - } - }]; - }else{ - [FirebasePlugin.firebasePlugin _logError:@"processMessageForForegroundNotification: cannot show notification as permission denied"]; - } - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } - }]; -} - -- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { - [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description]]; -} - -// Asks the delegate how to handle a notification that arrived while the app was running in the foreground -// Called when an APS notification arrives when app is in foreground -- (void)userNotificationCenter:(UNUserNotificationCenter *)center - willPresentNotification:(UNNotification *)notification - withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { - - @try{ - [self.delegate userNotificationCenter:center - willPresentNotification:notification - withCompletionHandler:completionHandler]; - - if (![notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ - [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as not a supported UNNotificationTrigger"]; - return; - } - - [[FIRMessaging messaging] appDidReceiveMessage:notification.request.content.userInfo]; - - mutableUserInfo = [notification.request.content.userInfo mutableCopy]; - - NSString* messageType = [mutableUserInfo objectForKey:@"messageType"]; - if(![messageType isEqualToString:@"data"]){ - [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; - } - - // Print full message. - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: %@", mutableUserInfo]]; - - - NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; - bool isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; - if(isContentAvailable){ - [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as content-available:1 so system notification will be shown"]; - return; - } - - bool showForegroundNotification = [mutableUserInfo objectForKey:@"notification_foreground"]; - bool hasAlert = [aps objectForKey:@"alert"] != nil; - bool hasBadge = [aps objectForKey:@"badge"] != nil; - bool hasSound = [aps objectForKey:@"sound"] != nil; - - if(showForegroundNotification){ - [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: foreground notification alert=%@, badge=%@, sound=%@", hasAlert ? @"YES" : @"NO", hasBadge ? @"YES" : @"NO", hasSound ? @"YES" : @"NO"]]; - if(hasAlert && hasBadge && hasSound){ - completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); - }else if(hasAlert && hasBadge){ - completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge); - }else if(hasAlert && hasSound){ - completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound); - }else if(hasBadge && hasSound){ - completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); - }else if(hasAlert){ - completionHandler(UNNotificationPresentationOptionAlert); - }else if(hasBadge){ - completionHandler(UNNotificationPresentationOptionBadge); - }else if(hasSound){ - completionHandler(UNNotificationPresentationOptionSound); - } - }else{ - [FirebasePlugin.firebasePlugin _logMessage:@"willPresentNotification: foreground notification not set"]; - } - - if(![messageType isEqualToString:@"data"]){ - [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; - } - - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -// Asks the delegate to process the user's response to a delivered notification. -// Called when user taps on system notification -- (void) userNotificationCenter:(UNUserNotificationCenter *)center - didReceiveNotificationResponse:(UNNotificationResponse *)response - withCompletionHandler:(void (^)(void))completionHandler -{ - @try{ - [self.delegate userNotificationCenter:center - didReceiveNotificationResponse:response - withCompletionHandler:completionHandler]; - - if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![response.notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ - [FirebasePlugin.firebasePlugin _logMessage:@"didReceiveNotificationResponse: aborting as not a supported UNNotificationTrigger"]; - return; - } - - [[FIRMessaging messaging] appDidReceiveMessage:response.notification.request.content.userInfo]; - - mutableUserInfo = [response.notification.request.content.userInfo mutableCopy]; - - NSString* tap; - if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]]){ - tap = @"background"; - }else{ - tap = @"foreground"; - - } - [mutableUserInfo setValue:tap forKey:@"tap"]; - if([mutableUserInfo objectForKey:@"messageType"] == nil){ - [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; - } - - - // Print full message. - [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"didReceiveNotificationResponse: %@", mutableUserInfo]]; - - [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; - - completionHandler(); - - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -// Receive data message on iOS 10 devices. -- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { - // Print full message - [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"applicationReceivedRemoteMessage: %@", [remoteMessage appData]]]; -} - -// Apple Sign In -- (void)authorizationController:(ASAuthorizationController *)controller - didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) { - @try{ - CDVPluginResult* pluginResult; - NSString* errorMessage = nil; - FIROAuthCredential *credential; - - if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) { - ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential; - NSString *rawNonce = [FirebasePlugin appleSignInNonce]; - if(rawNonce == nil){ - errorMessage = @"Invalid state: A login callback was received, but no login request was sent."; - }else if (appleIDCredential.identityToken == nil) { - errorMessage = @"Unable to fetch identity token."; - }else{ - NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken - encoding:NSUTF8StringEncoding]; - if (idToken == nil) { - errorMessage = [NSString stringWithFormat:@"Unable to serialize id token from data: %@", appleIDCredential.identityToken]; - }else{ - // Initialize a Firebase credential. - credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" - IDToken:idToken - rawNonce:rawNonce]; - - int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; - NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; - [result setValue:@"true" forKey:@"instantVerification"]; - [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; - } - } - if(errorMessage != nil){ - [FirebasePlugin.firebasePlugin _logError:errorMessage]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; - } - if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { - [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; - } - } - }@catch (NSException *exception) { - [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; - } -} - -- (void)authorizationController:(ASAuthorizationController *)controller - didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) { - NSString* errorMessage = [NSString stringWithFormat:@"Sign in with Apple errored: %@", error]; - [FirebasePlugin.firebasePlugin _logError:errorMessage]; - if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; - [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; - } -} - -- (nonnull ASPresentationAnchor)presentationAnchorForAuthorizationController:(nonnull ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){ - return self.viewController.view.window; -} - -@end +#import "AppDelegate+FirebasePlugin.h" #import "FirebasePlugin.h" #import "Firebase.h" #import @import UserNotifications; @import FirebaseFirestore; // Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices running iOS 10 and above. // Implement FIRMessagingDelegate to receive data message via FCM for devices running iOS 10 and above. @interface AppDelegate () @end #define kApplicationInBackgroundKey @"applicationInBackground" #define kDelegateKey @"delegate" @implementation AppDelegate (FirebasePlugin) static AppDelegate* instance; + (AppDelegate*) instance { return instance; } static NSDictionary* mutableUserInfo; static FIRAuthStateDidChangeListenerHandle authStateChangeListener; static bool authStateChangeListenerInitialized = false; static bool shouldEstablishDirectChannel = false; - (void)setDelegate:(id)delegate { objc_setAssociatedObject(self, kDelegateKey, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (id)delegate { return objc_getAssociatedObject(self, kDelegateKey); } + (void)load { Method original = class_getInstanceMethod(self, @selector(application:didFinishLaunchingWithOptions:)); Method swizzled = class_getInstanceMethod(self, @selector(application:swizzledDidFinishLaunchingWithOptions:)); method_exchangeImplementations(original, swizzled); } - (void)setApplicationInBackground:(NSNumber *)applicationInBackground { objc_setAssociatedObject(self, kApplicationInBackgroundKey, applicationInBackground, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSNumber *)applicationInBackground { return objc_getAssociatedObject(self, kApplicationInBackgroundKey); } - (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self application:application swizzledDidFinishLaunchingWithOptions:launchOptions]; @try{ instance = self; // get GoogleService-Info.plist file path NSString *filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; // if file is successfully found, use it if(filePath){ [FirebasePlugin.firebasePlugin _logMessage:@"GoogleService-Info.plist found, setup: [FIRApp configureWithOptions]"]; // create firebase configure options passing .plist as content FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; // configure FIRApp with options [FIRApp configureWithOptions:options]; if([FirebasePlugin.firebasePlugin _shouldEnableCrashlytics]){ [FIRApp configure]; } } // no .plist found, try default App if (![FIRApp defaultApp] && !filePath) { [FirebasePlugin.firebasePlugin _logError:@"GoogleService-Info.plist NOT FOUND, setup: [FIRApp defaultApp]"]; [FIRApp configure]; } shouldEstablishDirectChannel = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"shouldEstablishDirectChannel"] boolValue]; // Set FCM messaging delegate [FIRMessaging messaging].delegate = self; [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; // Setup Firestore [FirebasePlugin setFirestore:[FIRFirestore firestore]]; // Setup Google SignIn [GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID; [GIDSignIn sharedInstance].delegate = self; authStateChangeListener = [[FIRAuth auth] addAuthStateDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) { @try { if(!authStateChangeListenerInitialized){ authStateChangeListenerInitialized = true; }else{ [FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthStateChange(%@)", (user != nil ? @"true": @"false")]]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } }]; // Set UNUserNotificationCenter delegate self.delegate = [UNUserNotificationCenter currentNotificationCenter].delegate; [UNUserNotificationCenter currentNotificationCenter].delegate = self; // Set NSNotificationCenter observer [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:) name:kFIRInstanceIDTokenRefreshNotification object:nil]; self.applicationInBackground = @(YES); }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } return YES; } - (void)applicationDidBecomeActive:(UIApplication *)application { self.applicationInBackground = @(NO); [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"Enter foreground: FCM direct channel = %@", shouldEstablishDirectChannel ? @"true" : @"false"]]; } - (void)applicationDidEnterBackground:(UIApplication *)application { self.applicationInBackground = @(YES); [FIRMessaging messaging].shouldEstablishDirectChannel = false; [FirebasePlugin.firebasePlugin _logMessage:@"Enter background: FCM direct channel = false"]; } # pragma mark - Google SignIn - (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error { @try{ CDVPluginResult* pluginResult; if (error == nil) { GIDAuthentication *authentication = user.authentication; FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken accessToken:authentication.accessToken]; int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; [result setValue:@"true" forKey:@"instantVerification"]; [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } if ([FirebasePlugin firebasePlugin].googleSignInCallbackId != nil) { [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].googleSignInCallbackId]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error { NSString* msg = @"Google SignIn delegate: didDisconnectWithUser"; if(error != nil){ [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"%@: %@", msg, error]]; }else{ [FirebasePlugin.firebasePlugin _logMessage:msg]; } } # pragma mark - FIRMessagingDelegate - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRegistrationToken: %@", fcmToken]]; @try{ [FirebasePlugin.firebasePlugin sendToken:fcmToken]; }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)tokenRefreshNotification:(NSNotification *)notification { // Note that this callback will be fired everytime a new token is generated, including the first // time. So if you need to retrieve the token as soon as it is available this is where that // should be done. @try{ [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { @try{ if (error == nil) { NSString *refreshedToken = result.token; [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"tokenRefreshNotification: %@", refreshedToken]]; [FirebasePlugin.firebasePlugin sendToken:refreshedToken]; }else{ [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"tokenRefreshNotification: %@", error.description]]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } }]; }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [FIRMessaging messaging].APNSToken = deviceToken; [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didRegisterForRemoteNotificationsWithDeviceToken: %@", deviceToken]]; [FirebasePlugin.firebasePlugin sendApnsToken:[FirebasePlugin.firebasePlugin hexadecimalStringFromData:deviceToken]]; // Set UNUserNotificationCenter delegate [UNUserNotificationCenter currentNotificationCenter].delegate = self; } //Tells the app that a remote notification arrived that indicates there is data to be fetched. // Called when a message arrives in the foreground and remote notifications permission has been granted - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { @try{ [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; mutableUserInfo = [userInfo mutableCopy]; NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; bool isContentAvailable = false; if([aps objectForKey:@"alert"] != nil){ isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; NSString* tap; if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && !isContentAvailable){ tap = @"background"; } [mutableUserInfo setValue:tap forKey:@"tap"]; }else{ [mutableUserInfo setValue:@"data" forKey:@"messageType"]; } [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRemoteNotification: %@", mutableUserInfo]]; completionHandler(UIBackgroundFetchResultNewData); if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && isContentAvailable){ [FirebasePlugin.firebasePlugin _logError:@"didReceiveRemoteNotification: omitting foreground notification as content-available:1 so system notification will be shown"]; }else{ [self processMessageForForegroundNotification:mutableUserInfo]; } if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] || !isContentAvailable){ [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. // Called when a data message is arrives in the foreground and remote notifications permission has been NOT been granted - (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage { @try{ [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveMessage: %@", remoteMessage.appData]]; NSDictionary* appData = [remoteMessage.appData mutableCopy]; [appData setValue:@"data" forKey:@"messageType"]; [self processMessageForForegroundNotification:appData]; // This will allow us to handle FCM data-only push messages even if the permission for push // notifications is yet missing. This will only work when the app is in the foreground. [FirebasePlugin.firebasePlugin sendNotification:appData]; }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Scans a message for keys which indicate a notification should be shown. // If found, extracts relevant keys and uses then to display a local notification -(void)processMessageForForegroundNotification:(NSDictionary*)messageData { bool showForegroundNotification = [messageData objectForKey:@"notification_foreground"]; if(!showForegroundNotification){ return; } NSString* title = nil; NSString* body = nil; NSString* sound = nil; NSNumber* badge = nil; // Extract APNS notification keys NSDictionary* aps = [messageData objectForKey:@"aps"]; if([aps objectForKey:@"alert"] != nil){ NSDictionary* alert = [aps objectForKey:@"alert"]; if([alert objectForKey:@"title"] != nil){ title = [alert objectForKey:@"title"]; } if([alert objectForKey:@"body"] != nil){ body = [alert objectForKey:@"body"]; } if([aps objectForKey:@"sound"] != nil){ sound = [aps objectForKey:@"sound"]; } if([aps objectForKey:@"badge"] != nil){ badge = [aps objectForKey:@"badge"]; } } // Extract data notification keys if([messageData objectForKey:@"notification_title"] != nil){ title = [messageData objectForKey:@"notification_title"]; } if([messageData objectForKey:@"notification_body"] != nil){ body = [messageData objectForKey:@"notification_body"]; } if([messageData objectForKey:@"notification_ios_sound"] != nil){ sound = [messageData objectForKey:@"notification_ios_sound"]; } if([messageData objectForKey:@"notification_ios_badge"] != nil){ badge = [messageData objectForKey:@"notification_ios_badge"]; } if(title == nil || body == nil){ return; } [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { @try{ if (settings.alertSetting == UNNotificationSettingEnabled) { UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; objNotificationContent.title = [NSString localizedUserNotificationStringForKey:title arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:body arguments:nil]; NSDictionary* alert = [[NSDictionary alloc] initWithObjectsAndKeys: title, @"title", body, @"body" , nil]; NSMutableDictionary* aps = [[NSMutableDictionary alloc] initWithObjectsAndKeys: alert, @"alert", nil]; if(![sound isKindOfClass:[NSString class]] || [sound isEqualToString:@"default"]){ objNotificationContent.sound = [UNNotificationSound defaultSound]; [aps setValue:sound forKey:@"sound"]; }else if(sound != nil){ objNotificationContent.sound = [UNNotificationSound soundNamed:sound]; [aps setValue:sound forKey:@"sound"]; } if(badge != nil){ [aps setValue:badge forKey:@"badge"]; } NSString* messageType = @"data"; if([mutableUserInfo objectForKey:@"messageType"] != nil){ messageType = [mutableUserInfo objectForKey:@"messageType"]; } NSDictionary* userInfo = [[NSDictionary alloc] initWithObjectsAndKeys: @"true", @"notification_foreground", messageType, @"messageType", aps, @"aps" , nil]; objNotificationContent.userInfo = userInfo; UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:objNotificationContent trigger:trigger]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { [FirebasePlugin.firebasePlugin _logMessage:@"Local Notification succeeded"]; } else { [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"Local Notification failed: %@", error.description]]; } }]; }else{ [FirebasePlugin.firebasePlugin _logError:@"processMessageForForegroundNotification: cannot show notification as permission denied"]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } }]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description]]; } // Asks the delegate how to handle a notification that arrived while the app was running in the foreground // Called when an APS notification arrives when app is in foreground - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { @try{ [self.delegate userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler]; if (![notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as not a supported UNNotificationTrigger"]; return; } [[FIRMessaging messaging] appDidReceiveMessage:notification.request.content.userInfo]; mutableUserInfo = [notification.request.content.userInfo mutableCopy]; NSString* messageType = [mutableUserInfo objectForKey:@"messageType"]; if(![messageType isEqualToString:@"data"]){ [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; } // Print full message. [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: %@", mutableUserInfo]]; NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; bool isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; if(isContentAvailable){ [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as content-available:1 so system notification will be shown"]; return; } bool showForegroundNotification = [mutableUserInfo objectForKey:@"notification_foreground"]; bool hasAlert = [aps objectForKey:@"alert"] != nil; bool hasBadge = [aps objectForKey:@"badge"] != nil; bool hasSound = [aps objectForKey:@"sound"] != nil; if(showForegroundNotification){ [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: foreground notification alert=%@, badge=%@, sound=%@", hasAlert ? @"YES" : @"NO", hasBadge ? @"YES" : @"NO", hasSound ? @"YES" : @"NO"]]; if(hasAlert && hasBadge && hasSound){ completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); }else if(hasAlert && hasBadge){ completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge); }else if(hasAlert && hasSound){ completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound); }else if(hasBadge && hasSound){ completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); }else if(hasAlert){ completionHandler(UNNotificationPresentationOptionAlert); }else if(hasBadge){ completionHandler(UNNotificationPresentationOptionBadge); }else if(hasSound){ completionHandler(UNNotificationPresentationOptionSound); } }else{ [FirebasePlugin.firebasePlugin _logMessage:@"willPresentNotification: foreground notification not set"]; } if(![messageType isEqualToString:@"data"]){ [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Asks the delegate to process the user's response to a delivered notification. // Called when user taps on system notification - (void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { @try{ [self.delegate userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![response.notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ [FirebasePlugin.firebasePlugin _logMessage:@"didReceiveNotificationResponse: aborting as not a supported UNNotificationTrigger"]; return; } [[FIRMessaging messaging] appDidReceiveMessage:response.notification.request.content.userInfo]; mutableUserInfo = [response.notification.request.content.userInfo mutableCopy]; NSString* tap; if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]]){ tap = @"background"; }else{ tap = @"foreground"; } [mutableUserInfo setValue:tap forKey:@"tap"]; if([mutableUserInfo objectForKey:@"messageType"] == nil){ [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; } // Print full message. [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"didReceiveNotificationResponse: %@", mutableUserInfo]]; [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; completionHandler(); }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Receive data message on iOS 10 devices. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { // Print full message [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"applicationReceivedRemoteMessage: %@", [remoteMessage appData]]]; } // Apple Sign In - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) { @try{ CDVPluginResult* pluginResult; NSString* errorMessage = nil; FIROAuthCredential *credential; if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) { ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential; NSString *rawNonce = [FirebasePlugin appleSignInNonce]; if(rawNonce == nil){ errorMessage = @"Invalid state: A login callback was received, but no login request was sent."; }else if (appleIDCredential.identityToken == nil) { errorMessage = @"Unable to fetch identity token."; }else{ NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding]; if (idToken == nil) { errorMessage = [NSString stringWithFormat:@"Unable to serialize id token from data: %@", appleIDCredential.identityToken]; }else{ // Initialize a Firebase credential. credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" IDToken:idToken rawNonce:rawNonce]; int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; [result setValue:@"true" forKey:@"instantVerification"]; [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; } } if(errorMessage != nil){ [FirebasePlugin.firebasePlugin _logError:errorMessage]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; } if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; } } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) { NSString* errorMessage = [NSString stringWithFormat:@"Sign in with Apple errored: %@", error]; [FirebasePlugin.firebasePlugin _logError:errorMessage]; if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; } } - (nonnull ASPresentationAnchor)presentationAnchorForAuthorizationController:(nonnull ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){ return self.viewController.view.window; } @end \ No newline at end of file diff --git a/src/ios/FirebasePlugin.m b/src/ios/FirebasePlugin.m index 83a4dd816..9bc00f36e 100644 --- a/src/ios/FirebasePlugin.m +++ b/src/ios/FirebasePlugin.m @@ -1,1782 +1 @@ -#import "FirebasePlugin.h" -#import "FirebasePluginMessageReceiverManager.h" -#import "AppDelegate+FirebasePlugin.h" -#import -#import "AppDelegate.h" -#import -#import -@import FirebaseInstanceID; -@import FirebaseMessaging; -@import FirebaseAnalytics; -@import FirebaseRemoteConfig; -@import FirebasePerformance; -@import FirebaseAuth; -@import UserNotifications; -@import CommonCrypto; -@import AuthenticationServices; - -@implementation FirebasePlugin - -@synthesize notificationCallbackId; -@synthesize tokenRefreshCallbackId; -@synthesize apnsTokenRefreshCallbackId; -@synthesize googleSignInCallbackId; -@synthesize appleSignInCallbackId; -@synthesize notificationStack; -@synthesize traces; - -static NSString*const LOG_TAG = @"FirebasePlugin[native]"; -static NSInteger const kNotificationStackSize = 10; -static NSString*const FIREBASE_CRASHLYTICS_COLLECTION_ENABLED = @"FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"; -static NSString*const FIREBASE_ANALYTICS_COLLECTION_ENABLED = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED"; -static NSString*const FIREBASE_PERFORMANCE_COLLECTION_ENABLED = @"FIREBASE_PERFORMANCE_COLLECTION_ENABLED"; - -static FirebasePlugin* firebasePlugin; -static BOOL registeredForRemoteNotifications = NO; -static BOOL isCrashlyticsEnabled = NO; -static NSMutableDictionary* authCredentials; -static NSString* currentNonce; // used for Apple Sign In -static FIRFirestore* firestore; -static NSUserDefaults* preferences; -static NSDictionary* googlePlist; - - -+ (FirebasePlugin*) firebasePlugin { - return firebasePlugin; -} - -+ (NSString*) appleSignInNonce { - return currentNonce; -} - -+ (void) setFirestore:(FIRFirestore*) firestoreInstance{ - firestore = firestoreInstance; -} - -// @override abstract -- (void)pluginInitialize { - NSLog(@"Starting Firebase plugin"); - firebasePlugin = self; - - @try { - preferences = [NSUserDefaults standardUserDefaults]; - googlePlist = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]]; - - if(![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ - isCrashlyticsEnabled = [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; - }else{ - isCrashlyticsEnabled = YES; - [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:YES]; - } - - if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ - [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:YES]; - } - - if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ - [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:YES]; - } - - // Check for permission and register for remote notifications if granted - [self _hasPermission:^(BOOL result) {}]; - - [GIDSignIn sharedInstance].presentingViewController = self.viewController; - - authCredentials = [[NSMutableDictionary alloc] init]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithoutContext:exception]; - } -} - -// @override abstract -- (void)handleOpenURL:(NSNotification*)notification{ - NSURL* url = [notification object]; - [[GIDSignIn sharedInstance] handleURL:url]; -} - -- (void)setAutoInitEnabled:(CDVInvokedUrlCommand *)command { - @try { - bool enabled = [[command.arguments objectAtIndex:0] boolValue]; - [self runOnMainThread:^{ - @try { - [FIRMessaging messaging].autoInitEnabled = enabled; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)isAutoInitEnabled:(CDVInvokedUrlCommand *)command { - @try { - - [self runOnMainThread:^{ - @try { - bool enabled =[FIRMessaging messaging].isAutoInitEnabled; - - CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; - [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -/* - * Remote notifications - */ - -- (void)getId:(CDVInvokedUrlCommand *)command { - __block CDVPluginResult *pluginResult; - - FIRInstanceIDHandler handler = ^(NSString *_Nullable instID, NSError *_Nullable error) { - @try { - if (error) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:instID]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }; - - @try { - [[FIRInstanceID instanceID] getIDWithHandler:handler]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)getToken:(CDVInvokedUrlCommand *)command { - @try { - [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, - NSError * _Nullable error) { - CDVPluginResult* pluginResult; - if (error == nil) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result.token]; - }else{ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)getAPNSToken:(CDVInvokedUrlCommand *)command { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self getAPNSToken]]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (NSString *)getAPNSToken { - NSString* hexToken = nil; - NSData* apnsToken = [FIRMessaging messaging].APNSToken; - if (apnsToken) { -#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 - // [deviceToken description] Starting with iOS 13 device token is like "{length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f ... 28f10282 14af515f }" - hexToken = [self hexadecimalStringFromData:apnsToken]; -#else - hexToken = [[apnsToken.description componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet]invertedSet]]componentsJoinedByString:@""]; -#endif - } - return hexToken; -} - -- (NSString *)hexadecimalStringFromData:(NSData *)data -{ - NSUInteger dataLength = data.length; - if (dataLength == 0) { - return nil; - } - - const unsigned char *dataBuffer = data.bytes; - NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)]; - for (int i = 0; i < dataLength; ++i) { - [hexString appendFormat:@"%02x", dataBuffer[i]]; - } - return [hexString copy]; -} - -- (void)hasPermission:(CDVInvokedUrlCommand *)command { - @try { - [self _hasPermission:^(BOOL enabled) { - CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; - [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - --(void)_hasPermission:(void (^)(BOOL result))completeBlock { - @try { - [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { - @try { - BOOL enabled = NO; - if (settings.alertSetting == UNNotificationSettingEnabled) { - enabled = YES; - [self registerForRemoteNotifications]; - } - NSLog(@"_hasPermission: %@", enabled ? @"YES" : @"NO"); - completeBlock(enabled); - }@catch (NSException *exception) { - [self handlePluginExceptionWithoutContext:exception]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithoutContext:exception]; - } -} - -- (void)grantPermission:(CDVInvokedUrlCommand *)command { - NSLog(@"grantPermission"); - @try { - [self _hasPermission:^(BOOL enabled) { - @try { - if(enabled){ - NSString* message = @"Permission is already granted - call hasPermission() to check before calling grantPermission()"; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }else{ - [UNUserNotificationCenter currentNotificationCenter].delegate = (id _Nullable) self; - UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge; - [[UNUserNotificationCenter currentNotificationCenter] - requestAuthorizationWithOptions:authOptions - completionHandler:^(BOOL granted, NSError * _Nullable error) { - @try { - NSLog(@"requestAuthorizationWithOptions: granted=%@", granted ? @"YES" : @"NO"); - CDVPluginResult* pluginResult; - if (error == nil) { - if(granted){ - [self registerForRemoteNotifications]; - } - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:granted]; - }else{ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - } - ]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)registerForRemoteNotifications { - NSLog(@"registerForRemoteNotifications"); - if(registeredForRemoteNotifications) return; - - [self runOnMainThread:^{ - @try { - [[UIApplication sharedApplication] registerForRemoteNotifications]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithoutContext:exception]; - } - registeredForRemoteNotifications = YES; - }]; -} - -- (void)setBadgeNumber:(CDVInvokedUrlCommand *)command { - @try { - int number = [[command.arguments objectAtIndex:0] intValue]; - [self runOnMainThread:^{ - @try { - [[UIApplication sharedApplication] setApplicationIconBadgeNumber:number]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)getBadgeNumber:(CDVInvokedUrlCommand *)command { - [self runOnMainThread:^{ - @try { - long badge = [[UIApplication sharedApplication] applicationIconBadgeNumber]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:badge]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)subscribe:(CDVInvokedUrlCommand *)command { - @try { - NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; - - [[FIRMessaging messaging] subscribeToTopic: topic]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)unsubscribe:(CDVInvokedUrlCommand *)command { - @try { - NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; - - [[FIRMessaging messaging] unsubscribeFromTopic: topic]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)unregister:(CDVInvokedUrlCommand *)command { - @try { - [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) { - CDVPluginResult* pluginResult; - if (error == nil) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - }else{ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - - - -- (void)onMessageReceived:(CDVInvokedUrlCommand *)command { - @try { - self.notificationCallbackId = command.callbackId; - - if (self.notificationStack != nil && [self.notificationStack count]) { - for (NSDictionary *userInfo in self.notificationStack) { - [self sendNotification:userInfo]; - } - [self.notificationStack removeAllObjects]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)onTokenRefresh:(CDVInvokedUrlCommand *)command { - self.tokenRefreshCallbackId = command.callbackId; - @try { - [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, - NSError * _Nullable error) { - @try { - if (error == nil) { - if (result.token != nil && error == nil) { - [self sendToken:result.token]; - } - }else{ - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)onApnsTokenReceived:(CDVInvokedUrlCommand *)command { - self.apnsTokenRefreshCallbackId = command.callbackId; - @try { - NSString* apnsToken = [self getAPNSToken]; - if(apnsToken != nil){ - [self sendApnsToken:apnsToken]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)sendNotification:(NSDictionary *)userInfo { - @try { - if([FirebasePluginMessageReceiverManager sendNotification:userInfo]){ - [self _logMessage:@"Message handled by custom receiver"]; - return; - } - if (self.notificationCallbackId != nil) { - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo]; - [pluginResult setKeepCallbackAsBool:YES]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:self.notificationCallbackId]; - } else { - if (!self.notificationStack) { - self.notificationStack = [[NSMutableArray alloc] init]; - } - - // stack notifications until a callback has been registered - [self.notificationStack addObject:userInfo]; - - if ([self.notificationStack count] >= kNotificationStackSize) { - [self.notificationStack removeLastObject]; - } - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :self.commandDelegate]; - } -} - -- (void)sendToken:(NSString *)token { - @try { - if (self.tokenRefreshCallbackId != nil) { - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; - [pluginResult setKeepCallbackAsBool:YES]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:self.tokenRefreshCallbackId]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :self.commandDelegate]; - } -} - -- (void)sendApnsToken:(NSString *)token { - @try { - if (self.apnsTokenRefreshCallbackId != nil) { - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; - [pluginResult setKeepCallbackAsBool:YES]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:self.apnsTokenRefreshCallbackId]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :self.commandDelegate]; - } -} - -- (void)clearAllNotifications:(CDVInvokedUrlCommand *)command { - [self runOnMainThread:^{ - @try { - [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1]; - [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -/* - * Authentication - */ -- (void)verifyPhoneNumber:(CDVInvokedUrlCommand *)command { - NSString* number = [command.arguments objectAtIndex:0]; - - @try { - [[FIRPhoneAuthProvider provider] - verifyPhoneNumber:number - UIDelegate:nil - completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) { - - @try { - CDVPluginResult* pluginResult; - if (error) { - // Verification code not sent. - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } else { - // Successful. - NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; - [result setValue:@"false" forKey:@"instantVerification"]; - [result setValue:verificationID forKey:@"verificationId"]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)createUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { - @try { - NSString* email = [command.arguments objectAtIndex:0]; - NSString* password = [command.arguments objectAtIndex:1]; - [[FIRAuth auth] createUserWithEmail:email - password:password - completion:^(FIRAuthDataResult * _Nullable authResult, - NSError * _Nullable error) { - @try { - [self handleAuthResult:authResult error:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)signInUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { - @try { - NSString* email = [command.arguments objectAtIndex:0]; - NSString* password = [command.arguments objectAtIndex:1]; - [[FIRAuth auth] signInWithEmail:email - password:password - completion:^(FIRAuthDataResult * _Nullable authResult, - NSError * _Nullable error) { - @try { - [self handleAuthResult:authResult error:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)signInUserWithCustomToken:(CDVInvokedUrlCommand*)command { - @try { - NSString* customToken = [command.arguments objectAtIndex:0]; - [[FIRAuth auth] signInWithCustomToken:customToken - completion:^(FIRAuthDataResult * _Nullable authResult, - NSError * _Nullable error) { - @try { - [self handleAuthResult:authResult error:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)signInUserAnonymously:(CDVInvokedUrlCommand*)command { - @try { - [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult, - NSError * _Nullable error) { - @try { - [self handleAuthResult:authResult error:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)authenticateUserWithGoogle:(CDVInvokedUrlCommand*)command{ - @try { - self.googleSignInCallbackId = command.callbackId; - [[GIDSignIn sharedInstance] signIn]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; - [pluginResult setKeepCallbackAsBool:YES]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)authenticateUserWithApple:(CDVInvokedUrlCommand*)command{ - @try { - CDVPluginResult *pluginResult; - if (@available(iOS 13.0, *)) { - self.appleSignInCallbackId = command.callbackId; - [self startSignInWithAppleFlow]; - - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; - [pluginResult setKeepCallbackAsBool:YES]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"OS version is too low - Apple Sign In requires iOS 13.0+"]; - } - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)signInWithCredential:(CDVInvokedUrlCommand*)command { - @try { - FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; - if(credential == nil) return; - - [[FIRAuth auth] signInWithCredential:credential - completion:^(FIRAuthDataResult * _Nullable authResult, - NSError * _Nullable error) { - [self handleAuthResult:authResult error:error command:command]; - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)reauthenticateWithCredential:(CDVInvokedUrlCommand*)command{ - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; - if(credential == nil) return; - - [user reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { - [self handleAuthResult:authResult error:error command:command]; - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)linkUserWithCredential:(CDVInvokedUrlCommand*)command { - @try { - FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; - if(credential == nil) return; - - [[FIRAuth auth].currentUser linkWithCredential:credential - completion:^(FIRAuthDataResult * _Nullable authResult, - NSError * _Nullable error) { - [self handleAuthResult:authResult error:error command:command]; - }]; - - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)isUserSignedIn:(CDVInvokedUrlCommand*)command { - @try { - bool isSignedIn = [FIRAuth auth].currentUser ? true : false; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isSignedIn] callbackId:command.callbackId]; - - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)signOutUser:(CDVInvokedUrlCommand*)command { - @try { - bool isSignedIn = [FIRAuth auth].currentUser ? true : false; - if(!isSignedIn){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - // Sign out of Google - if([[GIDSignIn sharedInstance] currentUser] != nil){ - [[GIDSignIn sharedInstance] signOut]; - } - - // Sign out of Firebase - NSError *signOutError; - BOOL status = [[FIRAuth auth] signOut:&signOutError]; - if (!status) { - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[NSString stringWithFormat:@"Error signing out: %@", signOutError]] callbackId:command.callbackId]; - }else{ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)getCurrentUser:(CDVInvokedUrlCommand *)command { - - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - [self extractAndReturnUserInfo:command]; - - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)reloadCurrentUser:(CDVInvokedUrlCommand *)command { - - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - [user reloadWithCompletion:^(NSError * _Nullable error) { - if (error != nil) { - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description] callbackId:command.callbackId]; - }else { - [self extractAndReturnUserInfo:command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void) extractAndReturnUserInfo:(CDVInvokedUrlCommand *)command { - FIRUser* user = [FIRAuth auth].currentUser; - NSMutableDictionary* userInfo = [NSMutableDictionary new]; - [userInfo setValue:user.displayName forKey:@"name"]; - [userInfo setValue:user.email forKey:@"email"]; - [userInfo setValue:@(user.isEmailVerified ? true : false) forKey:@"emailIsVerified"]; - [userInfo setValue:user.phoneNumber forKey:@"phoneNumber"]; - [userInfo setValue:user.photoURL ? user.photoURL.absoluteString : nil forKey:@"photoUrl"]; - [userInfo setValue:user.uid forKey:@"uid"]; - [userInfo setValue:@(user.isAnonymous ? true : false) forKey:@"isAnonymous"]; - [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) { - [userInfo setValue:token forKey:@"idToken"]; - [user getIDTokenResultWithCompletion:^(FIRAuthTokenResult * _Nullable tokenResult, NSError * _Nullable error) { - [userInfo setValue:tokenResult.signInProvider forKey:@"providerId"]; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo] callbackId:command.callbackId]; - }]; - }]; -} - -- (void)updateUserProfile:(CDVInvokedUrlCommand*)command { - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - NSDictionary* profile = [command.arguments objectAtIndex:0]; - - FIRUserProfileChangeRequest* changeRequest = [user profileChangeRequest]; - if([profile objectForKey:@"name"] != nil){ - changeRequest.displayName = [profile objectForKey:@"name"]; - } - if([profile objectForKey:@"photoUri"] != nil){ - changeRequest.photoURL = [NSURL URLWithString:[profile objectForKey:@"photoUri"]]; - } - - [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) { - @try { - [self handleResultWithPotentialError:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)updateUserEmail:(CDVInvokedUrlCommand*)command { - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - NSString* email = [command.arguments objectAtIndex:0]; - [user updateEmail:email completion:^(NSError *_Nullable error) { - @try { - [self handleResultWithPotentialError:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)sendUserEmailVerification:(CDVInvokedUrlCommand*)command{ - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - [user sendEmailVerificationWithCompletion:^(NSError *_Nullable error) { - @try { - [self handleResultWithPotentialError:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)updateUserPassword:(CDVInvokedUrlCommand*)command{ - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - NSString* password = [command.arguments objectAtIndex:0]; - [user updatePassword:password completion:^(NSError *_Nullable error) { - @try { - [self handleResultWithPotentialError:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)sendUserPasswordResetEmail:(CDVInvokedUrlCommand*)command{ - @try { - NSString* email = [command.arguments objectAtIndex:0]; - [[FIRAuth auth] sendPasswordResetWithEmail:email completion:^(NSError *_Nullable error) { - @try { - [self handleResultWithPotentialError:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)deleteUser:(CDVInvokedUrlCommand*)command{ - @try { - FIRUser* user = [FIRAuth auth].currentUser; - if(!user){ - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; - return; - } - - [user deleteWithCompletion:^(NSError *_Nullable error) { - @try { - [self handleResultWithPotentialError:error command:command]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)startSignInWithAppleFlow API_AVAILABLE(ios(13.0)){ - NSString *nonce = [self randomNonce:32]; - currentNonce = nonce; - ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init]; - ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest]; - request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail]; - request.nonce = [self stringBySha256HashingString:nonce]; - - ASAuthorizationController *authorizationController = - [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]]; - authorizationController.delegate = [AppDelegate instance]; - authorizationController.presentationContextProvider = [AppDelegate instance]; - [authorizationController performRequests]; -} - -- (NSString *)stringBySha256HashingString:(NSString *)input { - const char *string = [input UTF8String]; - unsigned char result[CC_SHA256_DIGEST_LENGTH]; - CC_SHA256(string, (CC_LONG)strlen(string), result); - - NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; - for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { - [hashed appendFormat:@"%02x", result[i]]; - } - return hashed; -} - -// Generates random nonce for Apple Sign In -- (NSString *)randomNonce:(NSInteger)length { - NSAssert(length > 0, @"Expected nonce to have positive length"); - NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"; - NSMutableString *result = [NSMutableString string]; - NSInteger remainingLength = length; - - while (remainingLength > 0) { - NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16]; - for (NSInteger i = 0; i < 16; i++) { - uint8_t random = 0; - int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random); - NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode); - - [randoms addObject:@(random)]; - } - - for (NSNumber *random in randoms) { - if (remainingLength == 0) { - break; - } - - if (random.unsignedIntValue < characterSet.length) { - unichar character = [characterSet characterAtIndex:random.unsignedIntValue]; - [result appendFormat:@"%C", character]; - remainingLength--; - } - } - } - - return result; -} - -/* - * Analytics - */ -- (void)setAnalyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - BOOL enabled = [[command argumentAtIndex:0] boolValue]; - CDVPluginResult* pluginResult; - if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; - }else if(enabled && [self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to enabled"]; - }else if(!enabled && ![self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to disabled"]; - }else{ - [FIRAnalytics setAnalyticsCollectionEnabled:enabled]; - [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:enabled]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)isAnalyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ - [self.commandDelegate runInBackground:^{ - @try { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)logEvent:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* name = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command argumentAtIndex:1]; - - [FIRAnalytics logEventWithName:name parameters:parameters]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)setScreenName:(CDVInvokedUrlCommand *)command { - @try { - NSString* name = [command.arguments objectAtIndex:0]; - - [FIRAnalytics setScreenName:name screenClass:NULL]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (void)setUserId:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* id = [command.arguments objectAtIndex:0]; - - [FIRAnalytics setUserID:id]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)setUserProperty:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* name = [command.arguments objectAtIndex:0]; - NSString* value = [command.arguments objectAtIndex:1]; - - [FIRAnalytics setUserPropertyString:value forName:name]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -/* - * Crashlytics - */ -- (BOOL) _shouldEnableCrashlytics { - return ![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES] && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; -} - -- (void)setCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - BOOL enabled = [[command argumentAtIndex:0] boolValue]; - CDVPluginResult* pluginResult; - if([self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Crashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; - }else if(enabled && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to enabled"]; - }else if(!enabled && ![self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to disabled"]; - }else{ - [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:enabled]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)isCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ - [self.commandDelegate runInBackground:^{ - @try { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)isCrashlyticsCollectionCurrentlyEnabled:(CDVInvokedUrlCommand*)command{ - [self.commandDelegate runInBackground:^{ - @try { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isCrashlyticsEnabled]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)logError:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - NSString* errorMessage = [command.arguments objectAtIndex:0]; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - @try { - if(!isCrashlyticsEnabled){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log error - Crashlytics collection is disabled"]; - } - // We can optionally be passed a stack trace from stackTrace.js which we'll put in userInfo. - else if ([command.arguments count] > 1) { - NSArray* stackFrames = [command.arguments objectAtIndex:1]; - - NSString* message = errorMessage; - NSString* name = @"Uncaught Javascript exception"; - NSMutableArray *customFrames = [[NSMutableArray alloc] init]; - - for (NSDictionary* stackFrame in stackFrames) { - CLSStackFrame *customFrame = [CLSStackFrame stackFrame]; - [customFrame setSymbol:stackFrame[@"functionName"]]; - [customFrame setFileName:stackFrame[@"fileName"]]; - [customFrame setLibrary:stackFrame[@"source"]]; - [customFrame setOffset:(uint64_t) [stackFrame[@"columnNumber"] intValue]]; - [customFrame setLineNumber:(uint32_t) [stackFrame[@"lineNumber"] intValue]]; - [customFrames addObject:customFrame]; - } - [[Crashlytics sharedInstance] recordCustomExceptionName:name reason:message frameArray:customFrames]; - }else{ - //TODO detect and handle non-stack userInfo and pass to recordError - NSMutableDictionary* userInfo = [[NSMutableDictionary alloc] init]; - NSError *error = [NSError errorWithDomain:errorMessage code:0 userInfo:userInfo]; - [CrashlyticsKit recordError:error]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } @catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - - }]; -} - -- (void)logMessage:(CDVInvokedUrlCommand*)command{ - [self.commandDelegate runInBackground:^{ - @try { - NSString* message = [command argumentAtIndex:0 withDefault:@""]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - if(!isCrashlyticsEnabled){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log message - Crashlytics collection is disabled"]; - }else if(message){ - CLSNSLog(@"%@",message); - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)sendCrash:(CDVInvokedUrlCommand*)command{ - [[Crashlytics sharedInstance] crash]; -} - -- (void)setCrashlyticsUserId:(CDVInvokedUrlCommand *)command { - @try { - NSString* userId = [command.arguments objectAtIndex:0]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - if(!isCrashlyticsEnabled){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set user ID - Crashlytics collection is disabled"]; - }else{ - [CrashlyticsKit setUserIdentifier:userId]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -/* - * Remote config - */ -- (void)fetch:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; - - if ([command.arguments count] > 0) { - int expirationDuration = [[command.arguments objectAtIndex:0] intValue]; - - [remoteConfig fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { - CDVPluginResult *pluginResult; - if (error != nil) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - }else if (status == FIRRemoteConfigFetchStatusSuccess) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; - } else { - [remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { - CDVPluginResult *pluginResult; - if (error != nil) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - }else if (status == FIRRemoteConfigFetchStatusSuccess) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)activateFetched:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; - [remoteConfig activateWithCompletionHandler:^(NSError * _Nullable error) { - CDVPluginResult *pluginResult; - if (error != nil) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)getValue:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* key = [command.arguments objectAtIndex:0]; - FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; - NSString* value = remoteConfig[key].stringValue; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:value]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)getInfo:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; - NSInteger minimumFetchInterval = remoteConfig.configSettings.minimumFetchInterval; - NSInteger fetchTimeout = remoteConfig.configSettings.fetchTimeout; - NSDate* lastFetchTime = remoteConfig.lastFetchTime; - FIRRemoteConfigFetchStatus lastFetchStatus = remoteConfig.lastFetchStatus; - // isDeveloperModeEnabled is deprecated new recommnded way to check is minimumFetchInterval == 0 - BOOL isDeveloperModeEnabled = minimumFetchInterval == 0 ? true : false; - - NSDictionary* configSettings = @{ - @"developerModeEnabled": [NSNumber numberWithBool:isDeveloperModeEnabled], - @"minimumFetchInterval": [NSNumber numberWithInteger:minimumFetchInterval], - @"fetchTimeout": [NSNumber numberWithInteger:fetchTimeout], - }; - - NSDictionary* infoObject = @{ - @"configSettings": configSettings, - @"fetchTimeMillis": (lastFetchTime ? [NSNumber numberWithInteger:(lastFetchTime.timeIntervalSince1970 * 1000)] : [NSNull null]), - @"lastFetchStatus": [NSNumber numberWithInteger:(lastFetchStatus)], - }; - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:infoObject]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -/* - * Performance - */ -- (void)setPerformanceCollectionEnabled:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - BOOL enabled = [[command argumentAtIndex:0] boolValue]; - CDVPluginResult* pluginResult; - if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; - }else if(enabled && [self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to enabled"]; - }else if(!enabled && ![self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to disabled"]; - }else{ - [[FIRPerformance sharedInstance] setDataCollectionEnabled:enabled]; - [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:enabled]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)isPerformanceCollectionEnabled:(CDVInvokedUrlCommand*)command{ - [self.commandDelegate runInBackground:^{ - @try { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)startTrace:(CDVInvokedUrlCommand *)command { - - [self.commandDelegate runInBackground:^{ - @try { - NSString* traceName = [command.arguments objectAtIndex:0]; - FIRTrace *trace = [self.traces objectForKey:traceName]; - - if ( self.traces == nil) { - self.traces = [NSMutableDictionary new]; - } - - if (trace == nil) { - trace = [FIRPerformance startTraceWithName:traceName]; - [self.traces setObject:trace forKey:traceName ]; - - } - - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)incrementCounter:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* traceName = [command.arguments objectAtIndex:0]; - NSString* counterNamed = [command.arguments objectAtIndex:1]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - FIRTrace *trace = (FIRTrace*)[self.traces objectForKey:traceName]; - - if (trace != nil) { - [trace incrementMetric:counterNamed byInt:1]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; - } - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)stopTrace:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* traceName = [command.arguments objectAtIndex:0]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - FIRTrace *trace = [self.traces objectForKey:traceName]; - - if (trace != nil) { - [trace stop]; - [self.traces removeObjectForKey:traceName]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; - } - - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -/* -* Firestore -*/ - -- (void)addDocumentToFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSDictionary* document = [command.arguments objectAtIndex:0]; - NSString* collection = [command.arguments objectAtIndex:1]; - __block FIRDocumentReference *ref = - [[firestore collectionWithPath:collection] addDocumentWithData:document completion:^(NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - } else { - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ref.documentID]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)setDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* documentId = [command.arguments objectAtIndex:0]; - NSDictionary* document = [command.arguments objectAtIndex:1]; - NSString* collection = [command.arguments objectAtIndex:2]; - - [[[firestore collectionWithPath:collection] documentWithPath:documentId] setData:document completion:^(NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - } else { - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)updateDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* documentId = [command.arguments objectAtIndex:0]; - NSDictionary* document = [command.arguments objectAtIndex:1]; - NSString* collection = [command.arguments objectAtIndex:2]; - - FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; - if(docRef != nil){ - [docRef updateData:document completion:^(NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - } else { - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; - } - }]; - }else{ - [self sendPluginError:@"Document not found in collection":command]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)deleteDocumentFromFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* documentId = [command.arguments objectAtIndex:0]; - NSString* collection = [command.arguments objectAtIndex:1]; - - [[[firestore collectionWithPath:collection] documentWithPath:documentId] - deleteDocumentWithCompletion:^(NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - } else { - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)documentExistsInFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* documentId = [command.arguments objectAtIndex:0]; - NSString* collection = [command.arguments objectAtIndex:1]; - - FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; - if(docRef != nil){ - [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - }else{ - BOOL docExists = snapshot.data != nil; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:docExists] callbackId:command.callbackId]; - } - }]; - }else{ - [self sendPluginError:@"Collection not found":command]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)fetchDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* documentId = [command.arguments objectAtIndex:0]; - NSString* collection = [command.arguments objectAtIndex:1]; - - FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; - if(docRef != nil){ - [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - } else if(snapshot.data != nil) { - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:snapshot.data] callbackId:command.callbackId]; - }else{ - [self sendPluginError:@"Document not found in collection":command]; - } - }]; - }else{ - [self sendPluginError:@"Collection not found":command]; - } - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -- (void)fetchFirestoreCollection:(CDVInvokedUrlCommand*)command { - [self.commandDelegate runInBackground:^{ - @try { - NSString* collection = [command.arguments objectAtIndex:0]; - NSArray* filters = [command.arguments objectAtIndex:1]; - FIRQuery* query = [firestore collectionWithPath:collection]; - - for (int i = 0; i < [filters count]; i++) { - NSArray* filter = [filters objectAtIndex:i]; - if ([[filter objectAtIndex:0] isEqualToString:@"where"]) { - if ([[filter objectAtIndex:2] isEqualToString:@"=="]) { - query = [query queryWhereField:[filter objectAtIndex:1] isEqualTo:[filter objectAtIndex:3]]; - } - if ([[filter objectAtIndex:2] isEqualToString:@"<"]) { - query = [query queryWhereField:[filter objectAtIndex:1] isLessThan:[filter objectAtIndex:3]]; - } - if ([[filter objectAtIndex:2] isEqualToString:@">"]) { - query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThan:[filter objectAtIndex:3]]; - } - if ([[filter objectAtIndex:2] isEqualToString:@"<="]) { - query = [query queryWhereField:[filter objectAtIndex:1] isLessThanOrEqualTo:[filter objectAtIndex:3]]; - } - if ([[filter objectAtIndex:2] isEqualToString:@">="]) { - query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThanOrEqualTo:[filter objectAtIndex:3]]; - } - if ([[filter objectAtIndex:2] isEqualToString:@"array-contains"]) { - query = [query queryWhereField:[filter objectAtIndex:1] arrayContains:[filter objectAtIndex:3]]; - } - continue; - } - if ([[filter objectAtIndex:0] isEqualToString:@"orderBy"]) { - query = [query queryOrderedByField:[filter objectAtIndex:1] descending:([[filter objectAtIndex:2] isEqualToString:@"desc"])]; - continue; - } - if ([[filter objectAtIndex:0] isEqualToString:@"startAt"]) { - query = [query queryStartingAtValues:[filter objectAtIndex:1]]; - continue; - } - if ([[filter objectAtIndex:0] isEqualToString:@"endAt"]) { - query = [query queryEndingAtValues:[filter objectAtIndex:1]]; - continue; - } - if ([[filter objectAtIndex:0] isEqualToString:@"limit"]) { - query = [query queryLimitedTo:[(NSNumber *)[filter objectAtIndex:1] integerValue]]; - continue; - } - } - - [query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { - if (error != nil) { - [self sendPluginError:error.localizedDescription:command]; - } else { - NSMutableDictionary* documents = [[NSMutableDictionary alloc] init];; - for (FIRDocumentSnapshot *document in snapshot.documents) { - [documents setObject:document.data forKey:document.documentID]; - } - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:documents] callbackId:command.callbackId]; - } - }]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } - }]; -} - -/********************************/ -#pragma mark - utility functions -/********************************/ -- (void) sendPluginError: (NSString*) errorMessage :(CDVInvokedUrlCommand*)command -{ - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; - [self _logError:errorMessage]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void) handlePluginExceptionWithContext: (NSException*) exception :(CDVInvokedUrlCommand*)command -{ - [self handlePluginExceptionWithoutContext:exception]; - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void) handlePluginExceptionWithoutContext: (NSException*) exception -{ - [self _logError:[NSString stringWithFormat:@"EXCEPTION: %@", exception.reason]]; -} - -- (void)executeGlobalJavascript: (NSString*)jsString -{ - [self.commandDelegate evalJs:jsString]; -} - -- (void)_logError: (NSString*)msg -{ - NSLog(@"%@ ERROR: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; - [self executeGlobalJavascript:jsString]; -} - -- (void)_logInfo: (NSString*)msg -{ - NSLog(@"%@ INFO: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; - [self executeGlobalJavascript:jsString]; -} - -- (void)_logMessage: (NSString*)msg -{ - NSLog(@"%@ LOG: %@", LOG_TAG, msg); - NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; - [self executeGlobalJavascript:jsString]; -} - -- (NSString*)escapeJavascriptString: (NSString*)str -{ - NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; - result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; - return result; -} - -- (void)runOnMainThread:(void (^)(void))completeBlock { - if (![NSThread isMainThread]) { - dispatch_sync(dispatch_get_main_queue(), ^{ - @try { - completeBlock(); - }@catch (NSException *exception) { - [self handlePluginExceptionWithoutContext:exception]; - } - }); - } else { - @try { - completeBlock(); - }@catch (NSException *exception) { - [self handlePluginExceptionWithoutContext:exception]; - } - } -} - -- (FIRAuthCredential*)obtainAuthCredential:(NSDictionary*)credential command:(CDVInvokedUrlCommand *)command { - FIRAuthCredential* authCredential = nil; - - if(credential == nil){ - NSString* errMsg = @"credential object must be passed as first and only argument"; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; - return authCredential; - } - - NSString* key = [credential objectForKey:@"id"]; - NSString* verificationId = [credential objectForKey:@"verificationId"]; - NSString* code = [credential objectForKey:@"code"]; - - if(key != nil){ - authCredential = [authCredentials objectForKey:key]; - if(authCredential == nil){ - NSString* errMsg = [NSString stringWithFormat:@"no native auth credential exists for specified id '%@'", key]; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; - } - }else if(verificationId != nil && code != nil){ - authCredential = [[FIRPhoneAuthProvider provider] - credentialWithVerificationID:verificationId - verificationCode:code]; - }else{ - NSString* errMsg = @"credential object must either specify the id key of an existing native auth credential or the verificationId/code keys must be specified for a phone number authentication"; - [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; - } - - return authCredential; -} - -- (void) handleAuthResult:(FIRAuthDataResult*) authResult error:(NSError*) error command:(CDVInvokedUrlCommand*)command { - @try { - CDVPluginResult* pluginResult; - if (error) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - }else if (authResult == nil) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"User not signed in"]; - }else{ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }@catch (NSException *exception) { - [self handlePluginExceptionWithContext:exception :command]; - } -} - -- (int) saveAuthCredential: (FIRAuthCredential*) authCredential { - int key = -1; - while (key < 0 || [authCredentials objectForKey:[NSNumber numberWithInt:key]] != nil) { - key = arc4random_uniform(100000); - } - - [authCredentials setObject:authCredential forKey:[NSNumber numberWithInt:key]]; - - return key; -} - -- (void) handleResultWithPotentialError:(NSError*) error command:(CDVInvokedUrlCommand*)command { - CDVPluginResult* pluginResult; - if (error) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; - }else{ - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - } - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void) setPreferenceFlag:(NSString*) name flag:(BOOL)flag { - [preferences setBool:flag forKey:name]; - [preferences synchronize]; -} - -- (BOOL) getPreferenceFlag:(NSString*) name { - if([preferences objectForKey:name] == nil){ - return false; - } - return [preferences boolForKey:name]; -} - -- (BOOL) getGooglePlistFlagWithDefaultValue:(NSString*) name defaultValue:(BOOL)defaultValue { - if([googlePlist objectForKey:name] == nil){ - return defaultValue; - } - return [[googlePlist objectForKey:name] isEqualToString:@"true"]; -} - - -# pragma mark - Stubs -- (void)createChannel:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - -- (void)setDefaultChannel:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - -- (void)deleteChannel:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} - -- (void)listChannels:(CDVInvokedUrlCommand *)command { - [self.commandDelegate runInBackground:^{ - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; -} -@end +#import "FirebasePlugin.h" #import "FirebasePluginMessageReceiverManager.h" #import "AppDelegate+FirebasePlugin.h" #import #import "AppDelegate.h" #import @import FirebaseInstanceID; @import FirebaseMessaging; @import FirebaseAnalytics; @import FirebaseRemoteConfig; @import FirebasePerformance; @import FirebaseAuth; @import UserNotifications; @import CommonCrypto; @import AuthenticationServices; @implementation FirebasePlugin @synthesize notificationCallbackId; @synthesize tokenRefreshCallbackId; @synthesize apnsTokenRefreshCallbackId; @synthesize googleSignInCallbackId; @synthesize appleSignInCallbackId; @synthesize notificationStack; @synthesize traces; static NSString*const LOG_TAG = @"FirebasePlugin[native]"; static NSInteger const kNotificationStackSize = 10; static NSString*const FIREBASE_CRASHLYTICS_COLLECTION_ENABLED = @"FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"; static NSString*const FIREBASE_ANALYTICS_COLLECTION_ENABLED = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED"; static NSString*const FIREBASE_PERFORMANCE_COLLECTION_ENABLED = @"FIREBASE_PERFORMANCE_COLLECTION_ENABLED"; static FirebasePlugin* firebasePlugin; static BOOL registeredForRemoteNotifications = NO; static BOOL isCrashlyticsEnabled = NO; static NSMutableDictionary* authCredentials; static NSString* currentNonce; // used for Apple Sign In static FIRFirestore* firestore; static NSUserDefaults* preferences; static NSDictionary* googlePlist; + (FirebasePlugin*) firebasePlugin { return firebasePlugin; } + (NSString*) appleSignInNonce { return currentNonce; } + (void) setFirestore:(FIRFirestore*) firestoreInstance{ firestore = firestoreInstance; } // @override abstract - (void)pluginInitialize { NSLog(@"Starting Firebase plugin"); firebasePlugin = self; @try { preferences = [NSUserDefaults standardUserDefaults]; googlePlist = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]]; if(![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ isCrashlyticsEnabled = [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; }else{ isCrashlyticsEnabled = YES; [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:YES]; } if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:YES]; } if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:YES]; } // Check for permission and register for remote notifications if granted [self _hasPermission:^(BOOL result) {}]; [GIDSignIn sharedInstance].presentingViewController = self.viewController; authCredentials = [[NSMutableDictionary alloc] init]; }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } } // @override abstract - (void)handleOpenURL:(NSNotification*)notification{ NSURL* url = [notification object]; [[GIDSignIn sharedInstance] handleURL:url]; } - (void)setAutoInitEnabled:(CDVInvokedUrlCommand *)command { @try { bool enabled = [[command.arguments objectAtIndex:0] boolValue]; [self runOnMainThread:^{ @try { [FIRMessaging messaging].autoInitEnabled = enabled; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)isAutoInitEnabled:(CDVInvokedUrlCommand *)command { @try { [self runOnMainThread:^{ @try { bool enabled =[FIRMessaging messaging].isAutoInitEnabled; CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } /* * Remote notifications */ - (void)getId:(CDVInvokedUrlCommand *)command { __block CDVPluginResult *pluginResult; FIRInstanceIDHandler handler = ^(NSString *_Nullable instID, NSError *_Nullable error) { @try { if (error) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:instID]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }; @try { [[FIRInstanceID instanceID] getIDWithHandler:handler]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getToken:(CDVInvokedUrlCommand *)command { @try { [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { CDVPluginResult* pluginResult; if (error == nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result.token]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getAPNSToken:(CDVInvokedUrlCommand *)command { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self getAPNSToken]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (NSString *)getAPNSToken { NSString* hexToken = nil; NSData* apnsToken = [FIRMessaging messaging].APNSToken; if (apnsToken) { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 // [deviceToken description] Starting with iOS 13 device token is like "{length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f ... 28f10282 14af515f }" hexToken = [self hexadecimalStringFromData:apnsToken]; #else hexToken = [[apnsToken.description componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet]invertedSet]]componentsJoinedByString:@""]; #endif } return hexToken; } - (NSString *)hexadecimalStringFromData:(NSData *)data { NSUInteger dataLength = data.length; if (dataLength == 0) { return nil; } const unsigned char *dataBuffer = data.bytes; NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)]; for (int i = 0; i < dataLength; ++i) { [hexString appendFormat:@"%02x", dataBuffer[i]]; } return [hexString copy]; } - (void)hasPermission:(CDVInvokedUrlCommand *)command { @try { [self _hasPermission:^(BOOL enabled) { CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } -(void)_hasPermission:(void (^)(BOOL result))completeBlock { @try { [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { @try { BOOL enabled = NO; if (settings.alertSetting == UNNotificationSettingEnabled) { enabled = YES; [self registerForRemoteNotifications]; } NSLog(@"_hasPermission: %@", enabled ? @"YES" : @"NO"); completeBlock(enabled); }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } } - (void)grantPermission:(CDVInvokedUrlCommand *)command { NSLog(@"grantPermission"); @try { [self _hasPermission:^(BOOL enabled) { @try { if(enabled){ NSString* message = @"Permission is already granted - call hasPermission() to check before calling grantPermission()"; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }else{ [UNUserNotificationCenter currentNotificationCenter].delegate = (id _Nullable) self; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { @try { NSLog(@"requestAuthorizationWithOptions: granted=%@", granted ? @"YES" : @"NO"); CDVPluginResult* pluginResult; if (error == nil) { if(granted){ [self registerForRemoteNotifications]; } pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:granted]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } ]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)registerForRemoteNotifications { NSLog(@"registerForRemoteNotifications"); if(registeredForRemoteNotifications) return; [self runOnMainThread:^{ @try { [[UIApplication sharedApplication] registerForRemoteNotifications]; }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } registeredForRemoteNotifications = YES; }]; } - (void)setBadgeNumber:(CDVInvokedUrlCommand *)command { @try { int number = [[command.arguments objectAtIndex:0] intValue]; [self runOnMainThread:^{ @try { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:number]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getBadgeNumber:(CDVInvokedUrlCommand *)command { [self runOnMainThread:^{ @try { long badge = [[UIApplication sharedApplication] applicationIconBadgeNumber]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:badge]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)subscribe:(CDVInvokedUrlCommand *)command { @try { NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; [[FIRMessaging messaging] subscribeToTopic: topic]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)unsubscribe:(CDVInvokedUrlCommand *)command { @try { NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; [[FIRMessaging messaging] unsubscribeFromTopic: topic]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)unregister:(CDVInvokedUrlCommand *)command { @try { [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) { CDVPluginResult* pluginResult; if (error == nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)onMessageReceived:(CDVInvokedUrlCommand *)command { @try { self.notificationCallbackId = command.callbackId; if (self.notificationStack != nil && [self.notificationStack count]) { for (NSDictionary *userInfo in self.notificationStack) { [self sendNotification:userInfo]; } [self.notificationStack removeAllObjects]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)onTokenRefresh:(CDVInvokedUrlCommand *)command { self.tokenRefreshCallbackId = command.callbackId; @try { [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { @try { if (error == nil) { if (result.token != nil && error == nil) { [self sendToken:result.token]; } }else{ CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)onApnsTokenReceived:(CDVInvokedUrlCommand *)command { self.apnsTokenRefreshCallbackId = command.callbackId; @try { NSString* apnsToken = [self getAPNSToken]; if(apnsToken != nil){ [self sendApnsToken:apnsToken]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)sendNotification:(NSDictionary *)userInfo { @try { if([FirebasePluginMessageReceiverManager sendNotification:userInfo]){ [self _logMessage:@"Message handled by custom receiver"]; return; } if (self.notificationCallbackId != nil) { CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self.notificationCallbackId]; } else { if (!self.notificationStack) { self.notificationStack = [[NSMutableArray alloc] init]; } // stack notifications until a callback has been registered [self.notificationStack addObject:userInfo]; if ([self.notificationStack count] >= kNotificationStackSize) { [self.notificationStack removeLastObject]; } } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :self.commandDelegate]; } } - (void)sendToken:(NSString *)token { @try { if (self.tokenRefreshCallbackId != nil) { CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self.tokenRefreshCallbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :self.commandDelegate]; } } - (void)sendApnsToken:(NSString *)token { @try { if (self.apnsTokenRefreshCallbackId != nil) { CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self.apnsTokenRefreshCallbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :self.commandDelegate]; } } - (void)clearAllNotifications:(CDVInvokedUrlCommand *)command { [self runOnMainThread:^{ @try { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1]; [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Authentication */ - (void)verifyPhoneNumber:(CDVInvokedUrlCommand *)command { NSString* number = [command.arguments objectAtIndex:0]; @try { [[FIRPhoneAuthProvider provider] verifyPhoneNumber:number UIDelegate:nil completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) { @try { CDVPluginResult* pluginResult; if (error) { // Verification code not sent. pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } else { // Successful. NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; [result setValue:@"false" forKey:@"instantVerification"]; [result setValue:verificationID forKey:@"verificationId"]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)createUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { @try { NSString* email = [command.arguments objectAtIndex:0]; NSString* password = [command.arguments objectAtIndex:1]; [[FIRAuth auth] createUserWithEmail:email password:password completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { @try { NSString* email = [command.arguments objectAtIndex:0]; NSString* password = [command.arguments objectAtIndex:1]; [[FIRAuth auth] signInWithEmail:email password:password completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInUserWithCustomToken:(CDVInvokedUrlCommand*)command { @try { NSString* customToken = [command.arguments objectAtIndex:0]; [[FIRAuth auth] signInWithCustomToken:customToken completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInUserAnonymously:(CDVInvokedUrlCommand*)command { @try { [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)authenticateUserWithGoogle:(CDVInvokedUrlCommand*)command{ @try { self.googleSignInCallbackId = command.callbackId; [[GIDSignIn sharedInstance] signIn]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)authenticateUserWithApple:(CDVInvokedUrlCommand*)command{ @try { CDVPluginResult *pluginResult; if (@available(iOS 13.0, *)) { self.appleSignInCallbackId = command.callbackId; [self startSignInWithAppleFlow]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; [pluginResult setKeepCallbackAsBool:YES]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"OS version is too low - Apple Sign In requires iOS 13.0+"]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInWithCredential:(CDVInvokedUrlCommand*)command { @try { FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; if(credential == nil) return; [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { [self handleAuthResult:authResult error:error command:command]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)reauthenticateWithCredential:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; if(credential == nil) return; [user reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { [self handleAuthResult:authResult error:error command:command]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)linkUserWithCredential:(CDVInvokedUrlCommand*)command { @try { FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; if(credential == nil) return; [[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { [self handleAuthResult:authResult error:error command:command]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)isUserSignedIn:(CDVInvokedUrlCommand*)command { @try { bool isSignedIn = [FIRAuth auth].currentUser ? true : false; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isSignedIn] callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signOutUser:(CDVInvokedUrlCommand*)command { @try { bool isSignedIn = [FIRAuth auth].currentUser ? true : false; if(!isSignedIn){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } // Sign out of Google if([[GIDSignIn sharedInstance] currentUser] != nil){ [[GIDSignIn sharedInstance] signOut]; } // Sign out of Firebase NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[NSString stringWithFormat:@"Error signing out: %@", signOutError]] callbackId:command.callbackId]; }else{ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getCurrentUser:(CDVInvokedUrlCommand *)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [self extractAndReturnUserInfo:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)reloadCurrentUser:(CDVInvokedUrlCommand *)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [user reloadWithCompletion:^(NSError * _Nullable error) { if (error != nil) { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description] callbackId:command.callbackId]; }else { [self extractAndReturnUserInfo:command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void) extractAndReturnUserInfo:(CDVInvokedUrlCommand *)command { FIRUser* user = [FIRAuth auth].currentUser; NSMutableDictionary* userInfo = [NSMutableDictionary new]; [userInfo setValue:user.displayName forKey:@"name"]; [userInfo setValue:user.email forKey:@"email"]; [userInfo setValue:@(user.isEmailVerified ? true : false) forKey:@"emailIsVerified"]; [userInfo setValue:user.phoneNumber forKey:@"phoneNumber"]; [userInfo setValue:user.photoURL ? user.photoURL.absoluteString : nil forKey:@"photoUrl"]; [userInfo setValue:user.uid forKey:@"uid"]; [userInfo setValue:@(user.isAnonymous ? true : false) forKey:@"isAnonymous"]; [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) { [userInfo setValue:token forKey:@"idToken"]; [user getIDTokenResultWithCompletion:^(FIRAuthTokenResult * _Nullable tokenResult, NSError * _Nullable error) { [userInfo setValue:tokenResult.signInProvider forKey:@"providerId"]; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo] callbackId:command.callbackId]; }]; }]; } - (void)updateUserProfile:(CDVInvokedUrlCommand*)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } NSDictionary* profile = [command.arguments objectAtIndex:0]; FIRUserProfileChangeRequest* changeRequest = [user profileChangeRequest]; if([profile objectForKey:@"name"] != nil){ changeRequest.displayName = [profile objectForKey:@"name"]; } if([profile objectForKey:@"photoUri"] != nil){ changeRequest.photoURL = [NSURL URLWithString:[profile objectForKey:@"photoUri"]]; } [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)updateUserEmail:(CDVInvokedUrlCommand*)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } NSString* email = [command.arguments objectAtIndex:0]; [user updateEmail:email completion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)sendUserEmailVerification:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [user sendEmailVerificationWithCompletion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)updateUserPassword:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } NSString* password = [command.arguments objectAtIndex:0]; [user updatePassword:password completion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)sendUserPasswordResetEmail:(CDVInvokedUrlCommand*)command{ @try { NSString* email = [command.arguments objectAtIndex:0]; [[FIRAuth auth] sendPasswordResetWithEmail:email completion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)deleteUser:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [user deleteWithCompletion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)startSignInWithAppleFlow API_AVAILABLE(ios(13.0)){ NSString *nonce = [self randomNonce:32]; currentNonce = nonce; ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init]; ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest]; request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail]; request.nonce = [self stringBySha256HashingString:nonce]; ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]]; authorizationController.delegate = [AppDelegate instance]; authorizationController.presentationContextProvider = [AppDelegate instance]; [authorizationController performRequests]; } - (NSString *)stringBySha256HashingString:(NSString *)input { const char *string = [input UTF8String]; unsigned char result[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(string, (CC_LONG)strlen(string), result); NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { [hashed appendFormat:@"%02x", result[i]]; } return hashed; } // Generates random nonce for Apple Sign In - (NSString *)randomNonce:(NSInteger)length { NSAssert(length > 0, @"Expected nonce to have positive length"); NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"; NSMutableString *result = [NSMutableString string]; NSInteger remainingLength = length; while (remainingLength > 0) { NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16]; for (NSInteger i = 0; i < 16; i++) { uint8_t random = 0; int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random); NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode); [randoms addObject:@(random)]; } for (NSNumber *random in randoms) { if (remainingLength == 0) { break; } if (random.unsignedIntValue < characterSet.length) { unichar character = [characterSet characterAtIndex:random.unsignedIntValue]; [result appendFormat:@"%C", character]; remainingLength--; } } } return result; } /* * Analytics */ - (void)setAnalyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { BOOL enabled = [[command argumentAtIndex:0] boolValue]; CDVPluginResult* pluginResult; if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; }else if(enabled && [self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to enabled"]; }else if(!enabled && ![self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to disabled"]; }else{ [FIRAnalytics setAnalyticsCollectionEnabled:enabled]; [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:enabled]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isAnalyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)logEvent:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* name = [command.arguments objectAtIndex:0]; NSDictionary *parameters = [command argumentAtIndex:1]; [FIRAnalytics logEventWithName:name parameters:parameters]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)setScreenName:(CDVInvokedUrlCommand *)command { @try { NSString* name = [command.arguments objectAtIndex:0]; [FIRAnalytics setScreenName:name screenClass:NULL]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)setUserId:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* id = [command.arguments objectAtIndex:0]; [FIRAnalytics setUserID:id]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)setUserProperty:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* name = [command.arguments objectAtIndex:0]; NSString* value = [command.arguments objectAtIndex:1]; [FIRAnalytics setUserPropertyString:value forName:name]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Crashlytics */ - (BOOL) _shouldEnableCrashlytics { return ![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES] && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; } - (void)setCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { BOOL enabled = [[command argumentAtIndex:0] boolValue]; CDVPluginResult* pluginResult; if([self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Crashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; }else if(enabled && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to enabled"]; }else if(!enabled && ![self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to disabled"]; }else{ [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:enabled]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isCrashlyticsCollectionCurrentlyEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isCrashlyticsEnabled]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)logError:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ NSString* errorMessage = [command.arguments objectAtIndex:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; @try { if(!isCrashlyticsEnabled){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log error - Crashlytics collection is disabled"]; } // We can optionally be passed a stack trace from stackTrace.js which we'll put in userInfo. else if ([command.arguments count] > 1) { NSArray* stackFrames = [command.arguments objectAtIndex:1]; NSString* message = errorMessage; NSString* name = @"Uncaught Javascript exception"; NSMutableArray *customFrames = [[NSMutableArray alloc] init]; FIRExceptionModel *exceptionModel = [FIRExceptionModel exceptionModelWithName:name reason:message]; for (NSDictionary* stackFrame in stackFrames) { FIRStackFrame *customFrame = [FIRStackFrame stackFrameWithSymbol:stackFrame[@"functionName"] file:stackFrame[@"fileName"] line:(uint32_t) [stackFrame[@"lineNumber"] intValue]]; [customFrames addObject:customFrame]; } exceptionModel.stackTrace = customFrames; [[FIRCrashlytics crashlytics] recordExceptionModel:exceptionModel]; }else{ //TODO detect and handle non-stack userInfo and pass to recordError NSMutableDictionary* userInfo = [[NSMutableDictionary alloc] init]; NSError *error = [NSError errorWithDomain:errorMessage code:0 userInfo:userInfo]; [[FIRCrashlytics crashlytics] recordError:error]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } @catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)logMessage:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { NSString* message = [command argumentAtIndex:0 withDefault:@""]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; if(!isCrashlyticsEnabled){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log message - Crashlytics collection is disabled"]; }else if(message){ [[FIRCrashlytics crashlytics] logWithFormat:@"%@", message]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)sendCrash:(CDVInvokedUrlCommand*)command{ assert(NO); } - (void)setCrashlyticsUserId:(CDVInvokedUrlCommand *)command { @try { NSString* userId = [command.arguments objectAtIndex:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; if(!isCrashlyticsEnabled){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set user ID - Crashlytics collection is disabled"]; }else{ [[FIRCrashlytics crashlytics] setUserID:userId]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } /* * Remote config */ - (void)fetch:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; if ([command.arguments count] > 0) { int expirationDuration = [[command.arguments objectAtIndex:0] intValue]; [remoteConfig fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { CDVPluginResult *pluginResult; if (error != nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else if (status == FIRRemoteConfigFetchStatusSuccess) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } else { [remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { CDVPluginResult *pluginResult; if (error != nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else if (status == FIRRemoteConfigFetchStatusSuccess) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)activateFetched:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; [remoteConfig activateWithCompletionHandler:^(NSError * _Nullable error) { CDVPluginResult *pluginResult; if (error != nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)getValue:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* key = [command.arguments objectAtIndex:0]; FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; NSString* value = remoteConfig[key].stringValue; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:value]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)getInfo:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; NSInteger minimumFetchInterval = remoteConfig.configSettings.minimumFetchInterval; NSInteger fetchTimeout = remoteConfig.configSettings.fetchTimeout; NSDate* lastFetchTime = remoteConfig.lastFetchTime; FIRRemoteConfigFetchStatus lastFetchStatus = remoteConfig.lastFetchStatus; // isDeveloperModeEnabled is deprecated new recommnded way to check is minimumFetchInterval == 0 BOOL isDeveloperModeEnabled = minimumFetchInterval == 0 ? true : false; NSDictionary* configSettings = @{ @"developerModeEnabled": [NSNumber numberWithBool:isDeveloperModeEnabled], @"minimumFetchInterval": [NSNumber numberWithInteger:minimumFetchInterval], @"fetchTimeout": [NSNumber numberWithInteger:fetchTimeout], }; NSDictionary* infoObject = @{ @"configSettings": configSettings, @"fetchTimeMillis": (lastFetchTime ? [NSNumber numberWithInteger:(lastFetchTime.timeIntervalSince1970 * 1000)] : [NSNull null]), @"lastFetchStatus": [NSNumber numberWithInteger:(lastFetchStatus)], }; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:infoObject]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Performance */ - (void)setPerformanceCollectionEnabled:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { BOOL enabled = [[command argumentAtIndex:0] boolValue]; CDVPluginResult* pluginResult; if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; }else if(enabled && [self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to enabled"]; }else if(!enabled && ![self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to disabled"]; }else{ [[FIRPerformance sharedInstance] setDataCollectionEnabled:enabled]; [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:enabled]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isPerformanceCollectionEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)startTrace:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* traceName = [command.arguments objectAtIndex:0]; FIRTrace *trace = [self.traces objectForKey:traceName]; if ( self.traces == nil) { self.traces = [NSMutableDictionary new]; } if (trace == nil) { trace = [FIRPerformance startTraceWithName:traceName]; [self.traces setObject:trace forKey:traceName ]; } CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)incrementCounter:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* traceName = [command.arguments objectAtIndex:0]; NSString* counterNamed = [command.arguments objectAtIndex:1]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; FIRTrace *trace = (FIRTrace*)[self.traces objectForKey:traceName]; if (trace != nil) { [trace incrementMetric:counterNamed byInt:1]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)stopTrace:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* traceName = [command.arguments objectAtIndex:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; FIRTrace *trace = [self.traces objectForKey:traceName]; if (trace != nil) { [trace stop]; [self.traces removeObjectForKey:traceName]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Firestore */ - (void)addDocumentToFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSDictionary* document = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; __block FIRDocumentReference *ref = [[firestore collectionWithPath:collection] addDocumentWithData:document completion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ref.documentID]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)setDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSDictionary* document = [command.arguments objectAtIndex:1]; NSString* collection = [command.arguments objectAtIndex:2]; [[[firestore collectionWithPath:collection] documentWithPath:documentId] setData:document completion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)updateDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSDictionary* document = [command.arguments objectAtIndex:1]; NSString* collection = [command.arguments objectAtIndex:2]; FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; if(docRef != nil){ [docRef updateData:document completion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }]; }else{ [self sendPluginError:@"Document not found in collection":command]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)deleteDocumentFromFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; [[[firestore collectionWithPath:collection] documentWithPath:documentId] deleteDocumentWithCompletion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)documentExistsInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; if(docRef != nil){ [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; }else{ BOOL docExists = snapshot.data != nil; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:docExists] callbackId:command.callbackId]; } }]; }else{ [self sendPluginError:@"Collection not found":command]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)fetchDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; if(docRef != nil){ [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else if(snapshot.data != nil) { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:snapshot.data] callbackId:command.callbackId]; }else{ [self sendPluginError:@"Document not found in collection":command]; } }]; }else{ [self sendPluginError:@"Collection not found":command]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)fetchFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* collection = [command.arguments objectAtIndex:0]; NSArray* filters = [command.arguments objectAtIndex:1]; FIRQuery* query = [firestore collectionWithPath:collection]; for (int i = 0; i < [filters count]; i++) { NSArray* filter = [filters objectAtIndex:i]; if ([[filter objectAtIndex:0] isEqualToString:@"where"]) { if ([[filter objectAtIndex:2] isEqualToString:@"=="]) { query = [query queryWhereField:[filter objectAtIndex:1] isEqualTo:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@"<"]) { query = [query queryWhereField:[filter objectAtIndex:1] isLessThan:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@">"]) { query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThan:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@"<="]) { query = [query queryWhereField:[filter objectAtIndex:1] isLessThanOrEqualTo:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@">="]) { query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThanOrEqualTo:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@"array-contains"]) { query = [query queryWhereField:[filter objectAtIndex:1] arrayContains:[filter objectAtIndex:3]]; } continue; } if ([[filter objectAtIndex:0] isEqualToString:@"orderBy"]) { query = [query queryOrderedByField:[filter objectAtIndex:1] descending:([[filter objectAtIndex:2] isEqualToString:@"desc"])]; continue; } if ([[filter objectAtIndex:0] isEqualToString:@"startAt"]) { query = [query queryStartingAtValues:[filter objectAtIndex:1]]; continue; } if ([[filter objectAtIndex:0] isEqualToString:@"endAt"]) { query = [query queryEndingAtValues:[filter objectAtIndex:1]]; continue; } if ([[filter objectAtIndex:0] isEqualToString:@"limit"]) { query = [query queryLimitedTo:[(NSNumber *)[filter objectAtIndex:1] integerValue]]; continue; } } [query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { NSMutableDictionary* documents = [[NSMutableDictionary alloc] init];; for (FIRDocumentSnapshot *document in snapshot.documents) { [documents setObject:document.data forKey:document.documentID]; } [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:documents] callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /********************************/ #pragma mark - utility functions /********************************/ - (void) sendPluginError: (NSString*) errorMessage :(CDVInvokedUrlCommand*)command { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; [self _logError:errorMessage]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void) handlePluginExceptionWithContext: (NSException*) exception :(CDVInvokedUrlCommand*)command { [self handlePluginExceptionWithoutContext:exception]; CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void) handlePluginExceptionWithoutContext: (NSException*) exception { [self _logError:[NSString stringWithFormat:@"EXCEPTION: %@", exception.reason]]; } - (void)executeGlobalJavascript: (NSString*)jsString { [self.commandDelegate evalJs:jsString]; } - (void)_logError: (NSString*)msg { NSLog(@"%@ ERROR: %@", LOG_TAG, msg); NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logInfo: (NSString*)msg { NSLog(@"%@ INFO: %@", LOG_TAG, msg); NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logMessage: (NSString*)msg { NSLog(@"%@ LOG: %@", LOG_TAG, msg); NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (NSString*)escapeJavascriptString: (NSString*)str { NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; return result; } - (void)runOnMainThread:(void (^)(void))completeBlock { if (![NSThread isMainThread]) { dispatch_sync(dispatch_get_main_queue(), ^{ @try { completeBlock(); }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } }); } else { @try { completeBlock(); }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } } } - (FIRAuthCredential*)obtainAuthCredential:(NSDictionary*)credential command:(CDVInvokedUrlCommand *)command { FIRAuthCredential* authCredential = nil; if(credential == nil){ NSString* errMsg = @"credential object must be passed as first and only argument"; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; return authCredential; } NSString* key = [credential objectForKey:@"id"]; NSString* verificationId = [credential objectForKey:@"verificationId"]; NSString* code = [credential objectForKey:@"code"]; if(key != nil){ authCredential = [authCredentials objectForKey:key]; if(authCredential == nil){ NSString* errMsg = [NSString stringWithFormat:@"no native auth credential exists for specified id '%@'", key]; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; } }else if(verificationId != nil && code != nil){ authCredential = [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationId verificationCode:code]; }else{ NSString* errMsg = @"credential object must either specify the id key of an existing native auth credential or the verificationId/code keys must be specified for a phone number authentication"; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; } return authCredential; } - (void) handleAuthResult:(FIRAuthDataResult*) authResult error:(NSError*) error command:(CDVInvokedUrlCommand*)command { @try { CDVPluginResult* pluginResult; if (error) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else if (authResult == nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"User not signed in"]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (int) saveAuthCredential: (FIRAuthCredential*) authCredential { int key = -1; while (key < 0 || [authCredentials objectForKey:[NSNumber numberWithInt:key]] != nil) { key = arc4random_uniform(100000); } [authCredentials setObject:authCredential forKey:[NSNumber numberWithInt:key]]; return key; } - (void) handleResultWithPotentialError:(NSError*) error command:(CDVInvokedUrlCommand*)command { CDVPluginResult* pluginResult; if (error) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void) setPreferenceFlag:(NSString*) name flag:(BOOL)flag { [preferences setBool:flag forKey:name]; [preferences synchronize]; } - (BOOL) getPreferenceFlag:(NSString*) name { if([preferences objectForKey:name] == nil){ return false; } return [preferences boolForKey:name]; } - (BOOL) getGooglePlistFlagWithDefaultValue:(NSString*) name defaultValue:(BOOL)defaultValue { if([googlePlist objectForKey:name] == nil){ return defaultValue; } return [[googlePlist objectForKey:name] isEqualToString:@"true"]; } # pragma mark - Stubs - (void)createChannel:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } - (void)setDefaultChannel:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } - (void)deleteChannel:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } - (void)listChannels:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } @end \ No newline at end of file From 95008a745acbbf91fa480f56a43f0fad23d5fa83 Mon Sep 17 00:00:00 2001 From: vivek Date: Tue, 16 Jun 2020 16:19:11 +0530 Subject: [PATCH 24/24] Reset line separator. --- README.md | 2938 ++++++++++++++++- plugin.xml | 145 +- scripts/ios/helper.js | 239 +- src/android/FirebasePlugin.java | 2533 +++++++++++++- .../FirebasePluginMessagingService.java | 349 +- src/android/build.gradle | 49 +- src/ios/AppDelegate+FirebasePlugin.h | 12 +- src/ios/AppDelegate+FirebasePlugin.m | 567 +++- src/ios/FirebasePlugin.m | 1779 +++++++++- 9 files changed, 8602 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 920b9b715..a652ce9f2 100644 --- a/README.md +++ b/README.md @@ -1 +1,2937 @@ -cordova-plugin-firebasex [![Latest Stable Version](https://img.shields.io/npm/v/cordova-plugin-firebasex.svg)](https://www.npmjs.com/package/cordova-plugin-firebasex) [![Total Downloads](https://img.shields.io/npm/dt/cordova-plugin-firebasex.svg)](https://npm-stat.com/charts.html?package=cordova-plugin-firebasex) ======================== Brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project. Upgraded to the Firebase Crahlytics SDK for both [Android](https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=android) [iOS](https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=ios) Supported platforms: Android and iOS **IMPORTANT:** Before opening an issue against this plugin, please read [Reporting issues](#reporting-issues). # cli_build branch This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). To use it, install an npm release with the `-cli` suffix, e.g.: cordova plugin add cordova-plugin-firebasex@9.1.2-cli Or install it directly from this branch: cordova plugin add https://github.com/dpa99c/cordova-plugin-firebasex#cli_build If you wish to use either of these components, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a major plugin release via the NPM registry and build using Xcode. [![donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZRD3W47HQ3EMJ) I dedicate a considerable amount of my free time to developing and maintaining this Cordova plugin, along with my other Open Source software. To help ensure this plugin is kept updated, new features are added and bugfixes are implemented quickly, please donate a couple of dollars (or a little more if you can stretch) as this will help me to afford to dedicate time to its maintenance. Please consider donating if you're using this plugin in an app that makes you money, if you're being paid to make the app, if you're asking for new features or priority bug fixes. **Table of Contents** - [Installation](#installation) - [Plugin variables](#plugin-variables) - [Android & iOS](#android--ios) - [Android only](#android-only) - [iOS only](#ios-only) - [Supported Cordova Versions](#supported-cordova-versions) - [Supported Mobile Platform Versions](#supported-mobile-platform-versions) - [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) - [Breaking API changes](#breaking-api-changes) - [Ionic 4+](#ionic-4) - [Ionic 3](#ionic-3) - [Build environment notes](#build-environment-notes) - [PhoneGap Build](#phonegap-build) - [Android-specific](#android-specific) - [Specifying Android library versions](#specifying-android-library-versions) - [AndroidX](#androidx) - [Google Play Services and Firebase libraries](#google-play-services-and-firebase-libraries) - [iOS-specific](#ios-specific) - [Specifying iOS library versions](#specifying-ios-library-versions) - [Cocoapods](#cocoapods) - [Out-of-date pods](#out-of-date-pods) - [Strip debug symbols](#strip-debug-symbols) - [Cordova CLI builds](#cordova-cli-builds) - [Firebase config setup](#firebase-config-setup) - [Disable data collection on startup](#disable-data-collection-on-startup) - [Example project](#example-project) - [Reporting issues](#reporting-issues) - [Reporting a bug or problem](#reporting-a-bug-or-problem) - [Requesting a new feature](#requesting-a-new-feature) - [Cloud messaging](#cloud-messaging) - [Background notifications](#background-notifications) - [Foreground notifications](#foreground-notifications) - [Android notifications](#android-notifications) - [Android background notifications](#android-background-notifications) - [Android foreground notifications](#android-foreground-notifications) - [Android Notification Channels](#android-notification-channels) - [Android 7 and below](#android-7-and-below) - [Android Notification Icons](#android-notification-icons) - [Android Default Notification Icon](#android-default-notification-icon) - [Android Large Notification Icon](#android-large-notification-icon) - [Android Custom Notification Icons](#android-custom-notification-icons) - [Android Notification Color](#android-notification-color) - [Android Notification Sound](#android-notification-sound) - [Android 8.0 and above](#android-80-and-above) - [On Android 7 and below](#on-android-7-and-below) - [iOS notifications](#ios-notifications) - [iOS background notifications](#ios-background-notifications) - [iOS notification sound](#ios-notification-sound) - [iOS badge number](#ios-badge-number) - [Data messages](#data-messages) - [Data message notifications](#data-message-notifications) - [Android data message notifications](#android-data-message-notifications) - [iOS data message notifications](#ios-data-message-notifications) - [Custom FCM message handling](#custom-fcm-message-handling) - [Android](#android) - [iOS](#ios) - [Example](#example) - [InApp Messaging](#inapp-messaging) - [Google Tag Manager](#google-tag-manager) - [Android](#android-1) - [iOS](#ios-1) - [API](#api) - [Notifications and data messages](#notifications-and-data-messages) - [getToken](#gettoken) - [getId](#getid) - [onTokenRefresh](#ontokenrefresh) - [getAPNSToken](#getapnstoken) - [onApnsTokenReceived](#onapnstokenreceived) - [onMessageReceived](#onmessagereceived) - [grantPermission](#grantpermission) - [hasPermission](#haspermission) - [unregister](#unregister) - [isAutoInitEnabled](#isautoinitenabled) - [setAutoInitEnabled](#setautoinitenabled) - [setBadgeNumber](#setbadgenumber) - [getBadgeNumber](#getbadgenumber) - [clearAllNotifications](#clearallnotifications) - [subscribe](#subscribe) - [unsubscribe](#unsubscribe) - [createChannel](#createchannel) - [setDefaultChannel](#setdefaultchannel) - [Default Android Channel Properties](#default-android-channel-properties) - [deleteChannel](#deletechannel) - [listChannels](#listchannels) - [Analytics](#analytics) - [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled) - [isAnalyticsCollectionEnabled](#isanalyticscollectionenabled) - [logEvent](#logevent) - [setScreenName](#setscreenname) - [setUserId](#setuserid) - [setUserProperty](#setuserproperty) - [Crashlytics](#crashlytics) - [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled) - [isCrashlyticsCollectionEnabled](#iscrashlyticscollectionenabled) - [isCrashlyticsCollectionCurrentlyEnabled](#iscrashlyticscollectioncurrentlyenabled) - [setCrashlyticsUserId](#setcrashlyticsuserid) - [sendCrash](#sendcrash) - [logMessage](#logmessage) - [logError](#logerror) - [Authentication](#authentication) - [isUserSignedIn](#isusersignedin) - [signOutUser](#signoutuser) - [getCurrentUser](#getcurrentuser) - [reloadCurrentUser](#reloadcurrentuser) - [updateUserProfile](#updateuserprofile) - [updateUserEmail](#updateuseremail) - [sendUserEmailVerification](#senduseremailverification) - [updateUserPassword](#updateuserpassword) - [sendUserPasswordResetEmail](#senduserpasswordresetemail) - [deleteUser](#deleteuser) - [createUserWithEmailAndPassword](#createuserwithemailandpassword) - [signInUserWithEmailAndPassword](#signinuserwithemailandpassword) - [signInUserWithCustomToken](#signinuserwithcustomtoken) - [signInUserAnonymously](#signinuseranonymously) - [verifyPhoneNumber](#verifyphonenumber) - [Android](#android-2) - [iOS](#ios-2) - [authenticateUserWithGoogle](#authenticateuserwithgoogle) - [Android](#android-3) - [authenticateUserWithApple](#authenticateuserwithapple) - [iOS](#ios-3) - [Android](#android-4) - [signInWithCredential](#signinwithcredential) - [linkUserWithCredential](#linkuserwithcredential) - [reauthenticateWithCredential](#reauthenticatewithcredential) - [registerAuthStateChangeListener](#registerauthstatechangelistener) - [Remote Config](#remote-config) - [fetch](#fetch) - [activateFetched](#activatefetched) - [getValue](#getvalue) - [getByteArray](#getbytearray) - [getInfo](#getinfo) - [setConfigSettings](#setconfigsettings) - [setDefaults](#setdefaults) - [Performance](#performance) - [setPerformanceCollectionEnabled](#setperformancecollectionenabled) - [isPerformanceCollectionEnabled](#isperformancecollectionenabled) - [startTrace](#starttrace) - [incrementCounter](#incrementcounter) - [stopTrace](#stoptrace) - [Firestore](#firestore) - [addDocumentToFirestoreCollection](#adddocumenttofirestorecollection) - [setDocumentInFirestoreCollection](#setdocumentinfirestorecollection) - [updateDocumentInFirestoreCollection](#updatedocumentinfirestorecollection) - [deleteDocumentFromFirestoreCollection](#deletedocumentfromfirestorecollection) - [documentExistsInFirestoreCollection](#documentexistsinfirestorecollection) - [fetchDocumentInFirestoreCollection](#fetchdocumentinfirestorecollection) - [fetchFirestoreCollection](#fetchfirestorecollection) - [Credits](#credits) # Installation Install the plugin by adding it to your project's config.xml: ```xml ``` or by running: ``` cordova plugin add cordova-plugin-firebasex ``` ## Plugin variables The following Cordova plugin variables are supported by the plugin. Note that these must be set at plugin installation time. If you wish to change plugin variables, you'll need to uninstall the plugin and reinstall it with the new variable values. ### Android & iOS - `FIREBASE_ANALYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Analytics data collection on app startup - `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` - whether to automatically enable Firebase Performance data collection on app startup - `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Crashlytics data collection on app startup See [Disable data collection on startup](#disable-data-collection-on-startup) for more info. ### Android only The following plugin variables are used to specify the Firebase SDK versions as Gradle dependencies on Android: - `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` - `ANDROID_PLAY_SERVICES_AUTH_VERSION` - `ANDROID_FIREBASE_ANALYTICS_VERSION` - `ANDROID_FIREBASE_MESSAGING_VERSION` - `ANDROID_FIREBASE_CONFIG_VERSION` - `ANDROID_FIREBASE_PERF_VERSION` - `ANDROID_FIREBASE_AUTH_VERSION` - `ANDROID_FIREBASE_FIRESTORE_VERSION` - `ANDROID_CRASHLYTICS_VERSION` - `ANDROID_CRASHLYTICS_NDK_VERSION` - `ANDROID_GSON_VERSION` See [Specifying Android library versions](#specifying-android-library-versions) for more info. - `ANDROID_ICON_ACCENT` - sets the default accent color for system notifications. See [Android Notification Color](#android-notification-color) for more info. ### iOS only - `IOS_STRIP_DEBUG` - prevents symbolification of all libraries included via Cocoapods. See [Strip debug symbols](#strip-debug-symbols) for more info. - e.g. `--variable IOS_STRIP_DEBUG=true` - Defaults to `false` if not specified. - `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info. - e.g. `--variable IOS_STRIP_DEBUG=true` - Defaults to `false` if not specified. - `IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL` - If `true` Firebase Messaging will automatically establish a socket-based, direct channel to the FCM server. - e.g. `--variable IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL=true` - Defaults to `false` if not specified. - See [`shouldEstablishDirectChannel`](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/c:objc(cs)FIRMessaging(py)shouldEstablishDirectChannel) - Note: Firebase Messaging iOS SDK version 7.0 will be a breaking change where the SDK will no longer support iOS Direct Channel API. ## Supported Cordova Versions - cordova: `>= 9` - cordova-android: `>= 8` - cordova-ios: `>= 5` ## Supported Mobile Platform Versions - Android `>= 4.1` - iOS `>= 10.0` ## Migrating from cordova-plugin-firebase This plugin is a fork of [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) which has been reworked to fix issues and add new functionality. If you already have [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) installed in your Cordova project, you need to completely remove it before installing this plugin otherwise they will conflict and cause build errors in your project. The safest way of doing this is as follows: rm -Rf platforms/android cordova plugin rm cordova-plugin-firebase rm -Rf plugins/ node_modules/ npm install cordova plugin add cordova-plugin-firebasex cordova platform add android ### Breaking API changes **IMPORTANT:** Recent versions of `cordova-plugin-firebasex` have made breaking changes to the plugin API in order to fix bugs or add more functionality. Therefore you can no longer directly substitute `cordova-plugin-firebasex` in place of `cordova-plugin-firebase` without making code changes. You should be aware of the following breaking changes compared with `cordova-plugin-firebase`: * Minimum supported Cordova versions * `cordova@9` (CLI) * `cordova-android@8` (Android platform) * `cordova-ios@5` (iOS platform) * Migrated to AndroidX from legacy Android Support Library * add dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) and [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) * Migrated to Cocoapods to satisfy Firebase SDK dependencies on iOS * `onNotificationOpen()` renamed to `onMessageReceived()` * `tap` parameter is only set when user taps on a notification (not when a message is received from FCM) * `tap=foreground|background` instead of `tap=true|false` * `hasPermission()` receives argument as a boolean (rather than an object with `isEnabled` key) * e.g. `FirebasePlugin.hasPermission(function(hasPermission){ console.log("Permission is " + (hasPermission ? "granted" : "denied")); });` * Adds support for foreground notifications and data notification messages ### Ionic 4+ Ionic Native provides a [FirebaseX Typescript wrapper](https://ionicframework.com/docs/native/firebase-x) for using `cordova-plugin-firebasex` with Ionic v4, v5 and above. Please see their documentation for usage. First install the package. ``` ionic cordova plugin add cordova-plugin-firebasex npm install @ionic-native/firebase-x ``` If you're using Angular, register it in your component/service's `NgModule` (for example, app.module.ts) as a provider. ```typescript import { FirebaseX } from "@ionic-native/firebase-x/ngx"; @NgModule({ //declarations, imports... providers: [ FirebaseX, //other providers... ] }) ``` Then you're good to go. ```typescript import { FirebaseX } from "@ionic-native/firebase-x/ngx"; //... constructor(private firebase: FirebaseX) this.firebase.getToken().then(token => console.log(`The token is ${token}`)) this.firebase.onMessageReceived().subscribe(data => console.log(`FCM message: ${data}`)); ``` **NOTE:** - This plugin provides only the Javascript API as documented below. - The Typescript wrapper is owned and maintain by Ionic. - Please [report any issues](https://github.com/ionic-team/ionic-native/issues) against the [Ionic Native repo](https://github.com/ionic-team/ionic-native/), not this one. - Any issues opened against this repo which relate to the Typescript wrapper **will be closed immediately**. ### Ionic 3 The above PR does not work for Ionic 3 so you (currently) can't use the [Ionic Native Firebase](https://ionicframework.com/docs/native/firebase) Typescript wrapper with Ionic 3. (i.e. `import { Firebase } from "@ionic-native/firebase"` will not work). To use `cordova-plugin-firebasex` with Ionic 3, you'll need to call its Javascript API directly from your Typescript app code, for example: ```typescript (window).FirebasePlugin.getToken(token => console.log(`token: ${token}`)) (window).FirebasePlugin.onMessageReceived((message) => { if (message.tap) { console.log(`Notification was tapped in the ${message.tap}`); } }) ``` If you want to make the `onMessageReceived()` JS API behave like the Ionic Native wrapper: ```javascript onNotificationOpen() { return new Observable(observer => { (window as any).FirebasePlugin.onMessageReceived((response) => { observer.next(response); }); }); } ... this.onNotificationOpen().subscribe(data => console.log(`FCM message: ${data}`)); ``` See the [cordova-plugin-firebasex-ionic3-test](https://github.com/dpa99c/cordova-plugin-firebasex-ionic3-test) example project for a demonstration of how to use the plugin with Ionic 3. # Build environment notes ## PhoneGap Build This plugin will not work with Phonegap Build (and other remote cloud build envs) do not support Cordova hook scripts as they are used by this plugin to configure the native platform projects. ## Android-specific ### Specifying Android library versions This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Gradle on Android. By default this plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned versions as ``'s, for example: ```xml ``` The Android defaults can be overridden at plugin installation time by specifying plugin variables as command-line arguments, for example: cordova plugin add cordova-plugin-firebasex --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 Or you can specify them as plugin variables in your `config.xml`, for example: ```xml ``` The following plugin variables are used to specify the following Gradle dependency versions on Android: - `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` => `com.google.android.gms:play-services-tagmanager` - `ANDROID_PLAY_SERVICES_AUTH_VERSION` => `com.google.android.gms:play-services-auth` - `ANDROID_FIREBASE_ANALYTICS_VERSION` => `com.google.firebase:firebase-analytics` - `ANDROID_FIREBASE_MESSAGING_VERSION` => `com.google.firebase:firebase-messaging` - `ANDROID_FIREBASE_CONFIG_VERSION` => `com.google.firebase:firebase-config` - `ANDROID_FIREBASE_PERF_VERSION` => `com.google.firebase:firebase-perf` - `ANDROID_FIREBASE_AUTH_VERSION` => `com.google.firebase:firebase-auth` - `ANDROID_FIREBASE_FIRESTORE_VERSION` => `com.google.firebase:firebase-firestore` - `ANDROID_CRASHLYTICS_VERSION` => `com.crashlytics.sdk.android:crashlytics` - `ANDROID_CRASHLYTICS_NDK_VERSION` => `com.crashlytics.sdk.android:crashlytics-ndk` - `ANDROID_GSON_VERSION` => `com.google.code.gson:gson` For example: cordova plugin add cordova-plugin-firebasex \ --variable ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION=17.0.0 \ --variable ANDROID_PLAY_SERVICES_AUTH_VERSION=17.0.0 \ --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 \ --variable ANDROID_FIREBASE_MESSAGING_VERSION=19.0.0 \ --variable ANDROID_FIREBASE_CONFIG_VERSION=18.0.0 \ --variable ANDROID_FIREBASE_PERF_VERSION=18.0.0 \ --variable ANDROID_FIREBASE_AUTH_VERSION=18.0.0 \ --variable ANDROID_CRASHLYTICS_VERSION=2.10.1 \ --variable ANDROID_CRASHLYTICS_NDK_VERSION=2.1.0 \ ### AndroidX This plugin has been migrated to use [AndroidX (Jetpack)](https://developer.android.com/jetpack/androidx/migrate) which is the successor to the [Android Support Library](https://developer.android.com/topic/libraries/support-library/index). This is implemented by adding a dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) which enables AndroidX in the Android platform of a Cordova project. This is because the [major release of the Firebase and Play Services libraries on 17 June 2019](https://developers.google.com/android/guides/releases#june_17_2019) were migrated to AndroidX. Therefore if your project includes any plugins which are dependent on the legacy Android Support Library, you should add [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) to your project. This plugin will dynamically migrate any plugin code from the Android Support Library to AndroidX equivalents. ## Google Play Services and Firebase libraries Your Android build may fail if you are installing multiple plugins that use the Google Play Services library. This is caused by plugins installing different versions of the Google Play Services library. This can be resolved by installing [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) which enables you to override the versions specified by other plugins in order to align them. Similarly, if your build is failing because multiple plugins are installing different versions of the Firebase library, you can try installing [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release) to align these. ## iOS-specific ### Specifying iOS library versions This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Cocoapods on iOS. This plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned iOS versions in the ``'s, for example: **It is currently not possible to override these at plugin installation time** because `cordova@9`/`cordova-ios@5` does not support the use of plugin variables in the ``'s `spec` attribute. Therefore if you need to change the specified versions, you'll currently need to do this by forking the plugin and editing the `plugin.xml` to change the specified `spec` values. ### Cocoapods This plugin relies on `cordova@9`/`cordova-ios@5` support for the [CocoaPods dependency manager]( https://cocoapods.org/) in order to satisfy the iOS Firebase SDK library dependencies. Therefore please make sure you have Cocoapods@>=1.8 installed in your iOS build environment - setup instructions can be found [here](https://cocoapods.org/). If building your project in Xcode, you need to open `YourProject.xcworkspace` (not `YourProject.xcodeproj`) so both your Cordova app project and the Pods project will be loaded into Xcode. You can list the pod dependencies in your Cordova iOS project by installing [cocoapods-dependencies](https://github.com/segiddins/cocoapods-dependencies): sudo gem install cocoapods-dependencies cd platforms/ios/ pod dependencies ### Out-of-date pods If you receive a build error such as this: None of your spec sources contain a spec satisfying the dependencies: `Firebase/Analytics (~> 6.1.0), Firebase/Analytics (= 6.1.0, ~> 6.1.0)`. Make sure your local Cocoapods repo is up-to-date by running `pod repo update` then run `pod install` in `/your_project/platforms/ios/`. ### Strip debug symbols If your iOS app build contains too many debug symbols (i.e. because you include lots of libraries via a Cocoapods), you might get an error (e.g. [issue #28](https://github.com/dpa99c/cordova-plugin-firebase/issues/28)) when you upload your binary to App Store Connect, e.g.: ITMS-90381: Too many symbol files - These symbols have no corresponding slice in any binary [16EBC8AC-DAA9-39CF-89EA-6A58EB5A5A2F.symbols, 1B105D69-2039-36A4-A04D-96C1C5BAF235.symbols, 476EACDF-583B-3B29-95B9-253CB41097C8.symbols, 9789B03B-6774-3BC9-A8F0-B9D44B08DCCB.symbols, 983BAE60-D245-3291-9F9C-D25E610846AC.symbols]. To prevent this, you can set the `IOS_STRIP_DEBUG` plugin variable which prevents symbolification of all libraries included via Cocoapods ([see here for more information](https://stackoverflow.com/a/48518656/777265)): cordova plugin add cordova-plugin-firebasex --variable IOS_STRIP_DEBUG=true By default this preference is set to `false`. Note: if you enable this setting, any crashes that occur within libraries included via Cocopods will not be recorded in Crashlytics or other crash reporting services. ### Cordova CLI builds If you are building (directly or indirectly) via the Cordova CLI and encounter build failures on iOS, this is likely due to [an issue with Cordova CLI builds for iOS](https://github.com/apache/cordova-ios/issues/659) when including certain pods into the build (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). Note that building from Xcode works fine, so if you are able then do this. Otherwise (e.g. if building via a CI) then you'll need to switch to using the [cli_build branch](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) of this plugin which removes the Firebase Inapp Messaging and Google Tag Manager SDK components that are causing the build issues. # Firebase config setup There's a handy [installation and setup guide on medium.com](https://medium.com/@felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821). However, if using this, remember this forked plugin is `cordova-plugin-firebasex` (not `cordova-plugin-firebase`). Download your Firebase configuration files, `GoogleService-Info.plist` for iOS and `google-services.json` for android, and place them in the root folder of your cordova project. Check out this [firebase article](https://support.google.com/firebase/answer/7015592) for details on how to download the files. ``` - My Project/ platforms/ plugins/ www/ config.xml google-services.json <-- GoogleService-Info.plist <-- ... ``` IMPORTANT: The Firebase SDK requires the configuration files to be present and valid, otherwise your app will crash on boot or Firebase features won't work. # Disable data collection on startup By default, analytics, performance and Crashlytics data will begin being collected as soon as the app starts up. However, for data protection or privacy reasons, you may wish to disable data collection until such time as the user has granted their permission. To do this, set the following plugin variables to `false` at plugin install time: * `FIREBASE_ANALYTICS_COLLECTION_ENABLED` * `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` * `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` cordova plugin add cordova-plugin-firebasex \ --variable FIREBASE_ANALYTICS_COLLECTION_ENABLED=false \ --variable FIREBASE_PERFORMANCE_COLLECTION_ENABLED=false \ --variable FIREBASE_CRASHLYTICS_COLLECTION_ENABLED=false This will disable data collection (on both Android & iOS) until you call [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled), [setPerformanceCollectionEnabled](#setperformancecollectionenabled) and [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled): FirebasePlugin.setAnalyticsCollectionEnabled(true); FirebasePlugin.setPerformanceCollectionEnabled(true); FirebasePlugin.setCrashlyticsCollectionEnabled(true); Notes: - Calling `setXCollectionEnabled()` will have no effect if the corresponding `FIREBASE_X_COLLECTION_ENABLED` variable is set to `true`. - Calling `setAnalyticsCollectionEnabled(true|false)` or `setPerformanceCollectionEnabled(true|false)` will enable/disable data collection during the current app session and across subsequent app sessions until such time as the same method is called again with a different value. - Calling `setCrashlyticsCollectionEnabled(true|false)` will enable/disable data collection during subsequent app sessions until such time as the same method is called again with a different value. It **does not** affect the current app session. # Example project An example project repo exists to demonstrate and validate the functionality of this plugin: https://github.com/dpa99c/cordova-plugin-firebasex-test Please use this as a working reference. Before reporting any issues, please (if possible) test against the example project to rule out causes external to this plugin. # Reporting issues **IMPORTANT:** Please read the following carefully. Failure to follow the issue template guidelines below will result in the issue being immediately closed. ## Reporting a bug or problem Before [opening a bug issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=bug_report.md&title=), please do the following: - *DO NOT* open issues asking for support in using/integrating the plugin into your project - Only open issues for suspected bugs/issues with the plugin that are generic and will affect other users - I don't have time to offer free technical support: this is free open-source software - Ask for help on StackOverflow, Ionic Forums, etc. - Use the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) as a known working reference - Any issues requesting support will be closed immediately. - *DO NOT* open issues related to the [Ionic Typescript wrapper for this plugin](https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/firebase-x/index.ts) - This is owned/maintained by [Ionic](https://github.com/ionic-team) and is not part of this plugin - Please raise such issues/PRs against [Ionic Native](https://github.com/ionic-team/ionic-native/) instead. - To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper). - Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately. - If you are migrating from [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section. - Read the above documentation thoroughly - For example, if you're having a build issue ensure you've read through the [build environment notes](#build-environment-notes) - If an iOS CLI build is failing, ensure you've read the [Cordova CLI builds](#cordova-cli-builds) section - Check the [CHANGELOG](https://github.com/dpa99c/cordova-plugin-firebasex/blob/master/CHANGELOG.md) for any breaking changes that may be causing your issue. - Check a similar issue (open or closed) does not already exist against this plugin. - Duplicates or near-duplicates will be closed immediately. - When [creating a new issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new/choose) - Choose the "Bug report" template - Fill out the relevant sections of the template and delete irrelevant sections - *WARNING:* Failure to complete the issue template will result in the issue being closed immediately. - Reproduce the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) - This will eliminate bugs in your code or conflicts with other code as possible causes of the issue - This will also validate your development environment using a known working codebase - If reproducing the issue using the example project is not possible, create an isolated test project that you are able to share - Include full verbose console output when reporting build issues - If the full console output is too large to insert directly into the Github issue, then post it on an external site such as [Pastebin](https://pastebin.com/) and link to it from the issue - Often the details of an error causing a build failure is hidden away when building with the CLI - To get the full detailed console output, append the `--verbose` flag to CLI build commands - e.g. `cordova build ios --verbose` - Failure to include the full console output will result in the issue being closed immediately - If the issue relates to the plugin documentation (and not the code), please of a [documentation issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=documentation-issue.md&title=) ## Requesting a new feature Before [opening a feature request issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=feature_request.md&title=), please do the following: - Check the above documentation to ensure the feature you are requesting doesn't already exist - Check the list if open/closed issues to check if there's a reason that feature hasn't been included already - Ensure the feature you are requesting is actually possible to implement and generically useful to other users than yourself - Where possible, post a link to the documentation related to the feature you are requesting - Include other relevant links, e.g. - Stack Overflow post illustrating a solution - Code within another Github repo that illustrates a solution # Cloud messaging

 

There are 2 distinct types of messages that can be sent by Firebase Cloud Messaging (FCM): - [Notification messages](https://firebase.google.com/docs/cloud-messaging/concept-options#notifications) - automatically displayed to the user by the operating system on behalf of the client app **while your app is not running or is in the background** - **if your app is in the foreground when the notification message arrives**, it is passed to the client app and it is the responsibility of the client app to display it. - have a predefined set of user-visible keys and an optional data payload of custom key-value pairs. - [Data messages](https://firebase.google.com/docs/cloud-messaging/concept-options#data_messages) - Client app is responsible for processing data messages. - Data messages have only custom key-value pairs. Note: only notification messages can be sent via the Firebase Console - data messages must be sent via the [FCM APIs](https://firebase.google.com/docs/cloud-messaging/server). ## Background notifications If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. By default, no callback is made to the plugin when the message arrives while the app is not in the foreground, since the display of the notification is entirely handled by the operating system. However, there are platform-specific circumstances where a callback can be made when the message arrives and the app is in the background that don't require user interaction to receive the message payload - see [Android background notifications](#android-background-notifications) and [iOS background notifications](#ios-background-notifications) for details. If the user taps the system notification, this launches/resumes the app and the notification title, body and optional data payload is passed to the [onMessageReceived](#onMessageReceived) callback. When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the background/not running, it will be passed the property `tap: "background"`. ## Foreground notifications If the notification message arrives while the app is in running in the foreground, by default **it will NOT be displayed as a system notification**. Instead the notification message payload will be passed to the [onMessageReceived](#onMessageReceived) callback for the plugin to handle (`tap` will not be set). If you include the `notification_foreground` key in the `data` payload, the plugin will also display a system notification upon receiving the notification messages while the app is running in the foreground. For example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "data": { "notification_foreground": "true", } } ``` When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the foreground, it will be passed the property `tap: "foreground"`. You can set additional properties of the foreground notification using the same key names as for [Data Message Notifications](#data-message-notification-keys). ## Android notifications Notifications on Android can be customised to specify the sound, icon, LED colour, etc. that's displayed when the notification arrives. ### Android background notifications If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. If a notification message arrives while the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. In addition to the title and body of the notification message, Android system notifications support specification of the following notification settings: - [Icon](#android-notification-icons) - [Sound](#android-notification-sound) - [Color accent](#android-notification-color) - [Channel ID](#android-notification-channels) (Android 8.0 (O) and above) - This channel configuration enables you to specify: - Sound - Vibration - LED light - Badge - Importance - Visibility - See [createChannel](#createchannel) for details. Note: on tapping a background notification, if your app is not running, only the `data` section of the notification message payload will be delivered to [onMessageReceived](#onMessageReceived). i.e. the notification title, body, etc. will not. Therefore if you need the properties of the notification message itself (e.g. title & body) to be delivered to [onMessageReceived](#onMessageReceived), you must duplicate these in the `data` section, e.g.: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "data": { "notification_body": "Notification body", "notification_title": "Notification title" } } ``` ### Android foreground notifications If the notification message arrives while the app is in the foreground, by default a system notification won't be displayed and the data will be passed to [onMessageReceived](#onMessageReceived). However, if you set the `notification_foreground` key in the `data` section of the notification message payload, this will cause the plugin to display system notification when the message is received while your app is in the foreground. You can customise the notification using the same keys as for [Android data message notifications](#android-data-message-notifications). ### Android Notification Channels - Android 8 (O) introduced [notification channels](https://developer.android.com/training/notify-user/channels). - Notification channels are configured by the app and used to determine the **sound/lights/vibration** settings of system notifications. - By default, this plugin creates a default channel with [default properties](#default-android-channel-properties) - These can be overridden via the [setDefaultChannel](#setdefaultchannel) function. - The plugin enables the creation of additional custom channels via the [createChannel](#createchannel) function. First you need to create a custom channel with the desired settings, for example: ```javascript var channel = { id: "my_channel_id", sound: "mysound", vibration: true, light: true, lightColor: parseInt("FF0000FF", 16).toString(), importance: 4, badge: true, visibility: 1 }; FirebasePlugin.createChannel(channel, function(){ console.log('Channel created: ' + channel.id); }, function(error){ console.log('Create channel error: ' + error); }); ``` Then reference it from your message payload: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "channel_id": "my_channel_id" } } } ``` #### Android 7 and below - the channel referenced in the message payload will be ignored - the sound setting of system notifications is specified in the notification message itself - see [Android Notification Sound](#android-notification-sound). ### Android Notification Icons By default the plugin will use the default app icon for notification messages. #### Android Default Notification Icon To define a custom default notification icon, you need to create the images and deploy them to the `/platforms/android/app/src/main/res/` folders. The easiest way to create the images is using the [Image Asset Studio in Android Studio](https://developer.android.com/studio/write/image-asset-studio#create-notification) or using the [Android Asset Studio webapp](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=notification_icon). The icons should be monochrome transparent PNGs with the following sizes: - mdpi: 24x24 - hdpi: 36x36 - xhdpi: 48x48 - xxhdpi: 72x72 - xxxhdpi: 96x96 Once you've created the images, you need to deploy them from your Cordova project to the native Android project. To do this, copy the `drawable-DPI` image directories into your Cordova project and add `` entries to the `` section of your `config.xml`, where `src` specifies the relative path to the images files within your Cordova project directory. For example, copy the`drawable-DPI` image directories to `/res/android/` and add the following to your `config.xml`: ```xml ``` The default notification icon images **must** be named `notification_icon.png`. You then need to add a `` block to the `config.xml` which will instruct Firebase to use your icon as the default for notifications: ```xml ``` #### Android Large Notification Icon The default notification icons above are monochrome, however you can additionally define a larger multi-coloured icon. **NOTE:** FCM currently does not support large icons in system notifications displayed for notification messages received in the while the app is in the background (or not running). So the large icon will currently only be used if specified in [data messages](#android-data-messages) or [foreground notifications](#foreground-notifications). The large icon image should be a PNG-24 that's 256x256 pixels and must be named `notification_icon_large.png` and should be placed in the `drawable-xxxhdpi` resource directory. As with the small icons, you'll need to add a `` entry to the `` section of your `config.xml`: ```xml ``` #### Android Custom Notification Icons You can define additional sets of notification icons in the same manner as above. These can be specified in notification or data messages. For example: ```xml ``` When sending an FCM notification message, you will then specify the icon name in the `android.notification` section, for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "icon": "my_icon", } }, "data": { "notification_foreground": "true", } } ``` You can also reference these icons in [data messages](#android-data-messages), for example: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_icon": "my_icon", } } ``` ### Android Notification Color On Android Lollipop (5.0/API 21) and above you can set the default accent color for the notification by adding a color setting. This is defined as an [ARGB colour](https://en.wikipedia.org/wiki/RGBA_color_space#ARGB_(word-order)) which the plugin sets by default to `#FF00FFFF` (cyan). Note: On Android 7 and above, the accent color can only be set for the notification displayed in the system tray area - the icon in the statusbar is always white. You can override this default by specifying a value using the `ANDROID_ICON_ACCENT` plugin variable during plugin installation, for example: cordova plugin add cordova-plugin-firebasex --variable ANDROID_ICON_ACCENT=#FF123456 You can override the default color accent by specifying the `colour` key as an RGB value in a notification message, e.g.: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "color": "#00ff00" } } } ``` And in a data message: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_color": "#00ff00" } } ``` ### Android Notification Sound You can specify custom sounds for notifications or play the device default notification sound. Custom sound files must be in `.mp3` format and deployed to the `/res/raw` directory in the Android project. To do this, you can add `` tags to your `config.xml` to deploy the files, for example: ```xml ``` To ensure your custom sounds works on all versions of Android, be sure to include both the channel name and sound name in your message payload (see below for details), for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "channel_id": "my_channel_id", "sound": "my_sound" } } } ``` #### Android 8.0 and above On Android 8.0 and above, the notification sound is specified by which [Android notification channel](#android-notification-channels) is referenced in the notification message payload. First create a channel that references your sound, for example: ```javascript var channel = { id: "my_channel_id", sound: "my_sound" }; FirebasePlugin.createChannel(channel, function(){ console.log('Channel created: ' + channel.id); }, function(error){ console.log('Create channel error: ' + error); }); ``` Then reference that channel in your message payload: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "channel_id": "my_channel_id" } } } ``` #### On Android 7 and below On Android 7 and below, you need to specify the sound file name in the `android.notification` section of the message payload. For example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "android": { "notification": { "sound": "my_sound" } } } ``` And in a data message by specifying it in the `data` section: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_sound": "my_sound" } } ``` - To play the default notification sound, set `"sound": "default"`. - To display a silent notification (no sound), omit the `sound` key from the message. ## iOS notifications Notifications on iOS can be customised to specify the sound and badge number that's displayed when the notification arrives. Notification settings are specified in the `apns.payload.aps` key of the notification message payload. For example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "apns": { "payload": { "aps": { "sound": "default", "badge": 1, "content-available": 1 } } } } ``` ### iOS background notifications If the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback can be invoked when the message arrives without requiring user interaction (i.e. tapping the system notification). To do this you must specify `"content-available": 1` in the `apns.payload.aps` section of the message payload - see the [Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW8) for more information. When the message arrives, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. ### iOS notification sound You can specify custom sounds for notifications or play the device default notification sound. Custom sound files must be in a supported audio format (see [this Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW10) for supported formats). For example to convert an `.mp3` file to the supported `.caf` format run: afconvert my_sound.mp3 my_sound.caf -d ima4 -f caff -v Sound files must be deployed with the iOS application bundle. To do this, you can add `` tags to your `config.xml` to deploy the files, for example: ```xml ``` In a notification message, specify the `sound` key in the `apns.payload.aps` section, for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "apns": { "payload": { "aps": { "sound": "my_sound.caf" } } } } ``` - To play the default notification sound, set `"sound": "default"`. - To display a silent notification (no sound), omit the `sound` key from the message. In a data message, specify the `notification_ios_sound` key in the `data` section: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_ios_sound": "my_sound.caf" } } ``` ### iOS badge number In a notification message, specify the `badge` key in the `apns.payload.aps` section, for example: ```json { "name": "my_notification", "notification": { "body": "Notification body", "title": "Notification title" }, "apns": { "payload": { "aps": { "badge": 1 } } } } ``` In a data message, specify the `notification_ios_badge` key in the `data` section: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_ios_badge": 1 } } ``` ## Data messages FCM data messages are sent as an arbitrary k/v structure and by default are passed to the app for it to handle them. **NOTE:** FCM data messages **cannot** be sent from the Firebase Console - they can only be sent via the FCM APIs. ### Data message notifications This plugin enables a data message to be displayed as a system notification. To have the app display a notification when the data message arrives, you need to set the `notification_foreground` key in the `data` section. You can then set a `notification_title` and `notification_body`, for example: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "foo" : "bar" } } ``` Additional platform-specific notification options can be set using the additional keys below (which are only relevant if the `notification_foreground` key is set). Note: [foreground notification messages](#foreground-notifications) can also make use of these keys. #### Android data message notifications On Android: - Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. - Data messages (not containing notification keys) that arrive while your app is **not running** will be passed to the `onMessageReceived()` Javascript handler when the app is next launched. - Data messages containing notification keys that arrive while your app is running or **not running** will be displayed as a system notification. The following Android-specific keys are supported and should be placed inside the `data` section: - `notification_android_icon` - name of a [custom notification icon](#android-custom-notification-icons) in the drawable resources - if not specified, the plugin will use the default `notification_icon` if it exists; otherwise the default app icon will be displayed - if a [large icon](#android-large-notification-icon) has been defined, it will also be displayed in the system notification. - `notification_android_color` - the [color accent](#android-notification-color) to use for the small notification icon - if not specified, the default color accent will be used - `notification_android_channel_id` - ID of the [notification channel](#android-notification-channels) to use to display the notification - Only applies to Android 8.0 and above - If not specified, the [default notification channel](#default-android-channel-properties) will be used. - You can override the default configuration for the default notification channel using [setDefaultChannel](#setdefaultchannel). - You can create additional channels using [createChannel](#createchannel). - `notification_android_priority` - Specifies the notification priority - Possible values: - `2` - Highest notification priority for your application's most important items that require the user's prompt attention or input. - `1` - Higher notification priority for more important notifications or alerts. - `0` - Default notification priority. - `-1` - Lower notification priority for items that are less important. - `-2` - Lowest notification priority. These items might not be shown to the user except under special circumstances, such as detailed notification logs. - Defaults to `2` if not specified. - `notification_android_visibility` - Specifies the notification visibility - Possible values: - `1` - Show this notification in its entirety on all lockscreens. - `0` - Show this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. - `-1` - Do not reveal any part of this notification on a secure lockscreen. - Defaults to `1` if not specified. The following keys only apply to Android 7 and below. On Android 8 and above they will be ignored - the `notification_android_channel_id` property should be used to specify a [notification channel](#android-notification-channels) with equivalent settings. - `notification_android_sound` - name of a sound resource to play as the [notification sound](#android-notification-sound) - if not specified, no sound is played - `default` plays the default device notification sound - otherwise should be the name of an `.mp3` file in the `/res/raw` directory, e.g. `my_sound.mp3` => `"sounds": "my_sound"` - `notification_android_lights` - color and pattern to use to blink the LED light - if not defined, LED will not blink - in the format `ARGB, time_on_ms, time_off_ms` where - `ARGB` is an ARGB color definition e.g. `#ffff0000` - `time_on_ms` is the time in milliseconds to turn the LED on for - `time_off_ms` is the time in milliseconds to turn the LED off for - e.g. `"lights": "#ffff0000, 250, 250"` - `notification_android_vibrate` - pattern of vibrations to use when the message arrives - if not specified, device will not vibrate - an array of numbers specifying the time in milliseconds to vibrate - e.g. `"vibrate": "500, 200, 500"` Example data message with Android notification keys: ```json { "name": "my_data_message", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_android_channel_id": "my_channel", "notification_android_priority": "2", "notification_android_visibility": "1", "notification_android_color": "#ff0000", "notification_android_icon": "coffee", "notification_android_sound": "my_sound", "notification_android_vibrate": "500, 200, 500", "notification_android_lights": "#ffff0000, 250, 250" } } ``` #### iOS data message notifications On iOS: - Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. - Data messages that arrive while your app is **not running** will **NOT be received by your app!** The following iOS-specific keys are supported and should be placed inside the `data` section: - `notification_ios_sound` - Sound to play when the notification is displayed - To play a custom sound, set the name of the sound file bundled with your app, e.g. `"sound": "my_sound.caf"` - see [iOS notification sound](#ios-notification-sound) for more info. - To play the default notification sound, set `"sound": "default"`. - To display a silent notification (no sound), omit the `sound` key from the message. - `notification_ios_badge` - Badge number to display on app icon on home screen. For example: ```json { "name": "my_data", "data" : { "notification_foreground": "true", "notification_body" : "Notification body", "notification_title": "Notification title", "notification_ios_sound": "my_sound.caf", "notification_ios_badge": 1 } } ``` ## Custom FCM message handling In some cases you may want to handle certain incoming FCM messages differently rather than with the default behaviour of this plugin. Therefore this plugin provides a mechanism by which you can implement your own custom FCM message handling for specific FCM messages which bypasses handling of those messages by this plugin. To do this requires you to write native handlers for Android & iOS which hook into the native code of this plugin. ### Android You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/android/FirebasePluginMessageReceiver.java) and implements the `onMessageReceived()` and `sendMessage()` abstract methods. ### iOS You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/ios/FirebasePluginMessageReceiver.h) and implements the `sendNotification()` abstract method. ### Example The [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) contains an [example plugin](https://github.com/dpa99c/cordova-plugin-firebasex-test/tree/master/plugins/cordova-plugin-customfcmreceiver) which implements a custom receiver class for both platforms. You can test this by building and running the example project app, and sending the [notification_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/notification_custom_receiver.json) and [data_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/data_custom_receiver.json) test messages using the [built-in FCM client](https://github.com/dpa99c/cordova-plugin-firebasex-test#messaging-client). # InApp Messaging The Firebase Inapp Messaging SDK component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). If you wish to use Firebase Inapp Messaging, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. # Google Tag Manager The Google Tag Manager component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). If you wish to use Google Tag Manager, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. # API The list of available methods for this plugin is described below. ## Notifications and data messages The plugin is capable of receiving push notifications and FCM data messages. See [Cloud messaging](#cloud-messaging) section for more. ### getToken Get the current FCM token. Null if the token has not been allocated yet by the Firebase SDK. **Parameters**: - {function} success - callback function which will be passed the {string} token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getToken(function(fcmToken) { console.log(fcmToken); }, function(error) { console.error(error); }); ``` Note that token will be null if it has not been established yet. ### getId Get the app instance ID (an constant ID which persists as long as the app is not uninstalled/reinstalled). Null if the ID has not been allocated yet by the Firebase SDK. **Parameters**: - {function} success - callback function which will be passed the {string} ID as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getId(function(appInstanceId) { console.log(appInstanceId); }, function(error) { console.error(error); }); ``` Note that token will be null if it has not been established yet. ### onTokenRefresh Registers a handler to call when the FCM token changes. This is the best way to get the token as soon as it has been allocated. This will be called on the first run after app install when a token is first allocated. It may also be called again under other circumstances, e.g. if `unregister()` is called or Firebase allocates a new token for other reasons. You can use this callback to return the token to you server to keep the FCM token associated with a given user up-to-date. **Parameters**: - {function} success - callback function which will be passed the {string} token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.onTokenRefresh(function(fcmToken) { console.log(fcmToken); }, function(error) { console.error(error); }); ``` ### getAPNSToken iOS only. Get the APNS token allocated for this app install. Note that token will be null if it has not been allocated yet. **Parameters**: - {function} success - callback function which will be passed the {string} APNS token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getAPNSToken(function(apnsToken) { console.log(apnsToken); }, function(error) { console.error(error); }); ``` ### onApnsTokenReceived iOS only. Registers a handler to call when the APNS token is allocated. This will be called once when remote notifications permission has been granted by the user at runtime. **Parameters**: - {function} success - callback function which will be passed the {string} token as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.onApnsTokenReceived(function(apnsToken) { console.log(apnsToken); }, function(error) { console.error(error); }); ``` ### onMessageReceived Registers a callback function to invoke when: - a notification or data message is received by the app - a system notification is tapped by the user **Parameters**: - {function} success - callback function which will be passed the {object} message as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.onMessageReceived(function(message) { console.log("Message type: " + message.messageType); if(message.messageType === "notification"){ console.log("Notification message received"); if(message.tap){ console.log("Tapped in " + message.tap); } } console.dir(message); }, function(error) { console.error(error); }); ``` The `message` object passed to the callback function will contain the platform-specific FCM message payload along with the following keys: - `messageType=notification|data` - indicates if received message is a notification or data message - `tap=foreground|background` - set if the call to `onMessageReceived()` was initiated by user tapping on a system notification. - indicates if the system notification was tapped while the app was in the foreground or background. - not set if no system notification was tapped (i.e. message was received directly from FCM rather than via a user tap on a system notification). Notification message flow: 1. App is in foreground: a. By default, when a notification message arrives the app receives the notification message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. 2. App is in background: a. User receives the notification message as a system notification in the device notification bar b. User taps the system notification which launches the app b. User receives the notification message payload in the `onMessageReceived` JavaScript callback Data message flow: 1. App is in foreground: a. By default, when a data message arrives the app receives the data message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. 2. App is in background: a. The app receives the data message in the `onMessageReceived` JavaScript callback while in the background b. If the data message contains the [data message notification keys](#data-message-notifications), the plugin will display a system notification for the data message while in the background. ### grantPermission Grant permission to receive push notifications (will trigger prompt) and return `hasPermission: true`. iOS only (Android will always return true). **Parameters**: - {function} success - callback function which will be passed the {boolean} permission result as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.grantPermission(function(hasPermission){ console.log("Permission was " + (hasPermission ? "granted" : "denied")); }); ``` ### hasPermission Check permission to receive push notifications and return the result to a callback function as boolean. On iOS, returns true is runtime permission for remote notifications is granted and enabled in Settings. On Android, returns true if remote notifications are enabled. **Parameters**: - {function} success - callback function which will be passed the {boolean} permission result as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.hasPermission(function(hasPermission){ console.log("Permission is " + (hasPermission ? "granted" : "denied")); }); ``` ### unregister Unregisters from Firebase by deleting the current device token. Use this to stop receiving push notifications associated with the current token. e.g. call this when you logout user from your app. By default, a new token will be generated as soon as the old one is removed. To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). **Parameters**: None ```javascript FirebasePlugin.unregister(); ``` ### isAutoInitEnabled Indicates whether autoinit is currently enabled. If so, new FCM tokens will be automatically generated. **Parameters**: - {function} success - callback function which will be passed the {boolean} result as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.isAutoInitEnabled(function(enabled){ console.log("Auto init is " + (enabled ? "enabled" : "disabled")); }); ``` ### setAutoInitEnabled Sets whether to autoinit new FCM tokens. By default, a new token will be generated as soon as the old one is removed. To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). **Parameters**: - {boolean} enabled - set true to enable, false to disable - {function} success - callback function to call on successful execution of operation. - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.setAutoInitEnabled(false, function(){ console.log("Auto init has been disabled "); FirebasePlugin.unregister(); }); ``` ### setBadgeNumber iOS only. Set a number on the icon badge: **Parameters**: - {integer} badgeNumber - number to set for the app badge ```javascript FirebasePlugin.setBadgeNumber(3); ``` Set 0 to clear the badge ```javascript FirebasePlugin.setBadgeNumber(0); ``` Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) ### getBadgeNumber iOS only. Get icon badge number: **Parameters**: - {function} success - callback function which will be passed the {integer} current badge number as an argument ```javascript FirebasePlugin.getBadgeNumber(function(n) { console.log(n); }); ``` Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) ### clearAllNotifications Clear all pending notifications from the drawer: **Parameters**: None ```javascript FirebasePlugin.clearAllNotifications(); ``` ### subscribe Subscribe to a topic. Topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. **Parameters**: - {string} topicName - name of topic to subscribe to ```javascript FirebasePlugin.subscribe("latest_news"); ``` ### unsubscribe Unsubscribe from a topic. This will stop you receiving messages for that topic **Parameters**: - {string} topicName - name of topic to unsubscribe from ```javascript FirebasePlugin.unsubscribe("latest_news"); ``` ### createChannel Android 8+ only. Creates a custom channel to be used by notification messages which have the channel property set in the message payload to the `id` of the created channel: - For background (system) notifications: `android.notification.channel_id` - For foreground/data notifications: `data.notification_android_channel_id` For each channel you may set the sound to be played, the color of the phone LED (if supported by the device), whether to vibrate and set vibration pattern (if supported by the device), importance and visibility. Channels should be created as soon as possible (on program start) so notifications can work as expected. A default channel is created by the plugin at app startup; the properties of this can be overridden see [setDefaultChannel](#setdefaultchannel) Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {object} - channel configuration object (see below for object keys/values) - {function} success - callback function which will be call on successful channel creation - {function} error - callback function which will be passed a {string} error message as an argument ```javascript // Define custom channel - all keys are except 'id' are optional. var channel = { // channel ID - must be unique per app package id: "my_channel_id", // Channel description. Default: empty string description: "Channel description", // Channel name. Default: empty string name: "Channel name", //The sound to play once a push comes. Default value: 'default' //Values allowed: //'default' - plays the default notification sound //'ringtone' - plays the currently set ringtone //'false' - silent; don't play any sound //filename - the filename of the sound file located in '/res/raw' without file extension (mysound.mp3 -> mysound) sound: "mysound", //Vibrate on new notification. Default value: true //Possible values: //Boolean - vibrate or not //Array - vibration pattern - e.g. [500, 200, 500] - milliseconds vibrate, milliseconds pause, vibrate, pause, etc. vibration: true, // Whether to blink the LED light: true, //LED color in ARGB format - this example BLUE color. If set to -1, light color will be default. Default value: -1. lightColor: parseInt("FF0000FF", 16).toString(), //Importance - integer from 0 to 4. Default value: 4 //0 - none - no sound, does not show in the shade //1 - min - no sound, only shows in the shade, below the fold //2 - low - no sound, shows in the shade, and potentially in the status bar //3 - default - shows everywhere, makes noise, but does not visually intrude //4 - high - shows everywhere, makes noise and peeks importance: 4, //Show badge over app icon when non handled pushes are present. Default value: true badge: true, //Show message on locked screen. Default value: 1 //Possible values (default 1): //-1 - secret - Do not reveal any part of the notification on a secure lockscreen. //0 - private - Show the notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. //1 - public - Show the notification in its entirety on all lockscreens. visibility: 1 }; // Create the channel FirebasePlugin.createChannel(channel, function(){ console.log('Channel created: ' + channel.id); }, function(error){ console.log('Create channel error: ' + error); }); ``` Example FCM v1 API notification message payload for invoking the above example channel: ```json { "notification": { "title":"Notification title", "body":"Notification body" }, "android": { "notification": { "channel_id": "my_channel_id" } } } ``` If your Android app plays multiple sounds or effects, it's a good idea to create a channel for each likely combination. This is because once a channel is created you cannot override sounds/effects. IE, expanding on the createChannel example: ```javascript let soundList = ["train","woop","clock","radar","sonar"]; for (let key of soundList) { let name = "yourchannelprefix_" + key; channel.id = name; channel.sound = key; channel.name = "Your description " + key; // Create the channel window.FirebasePlugin.createChannel(channel, function(){ console.log('Notification Channel created: ' + channel.id + " " + JSON.stringify(channel)); }, function(error){ console.log('Create notification channel error: ' + error); }); } ``` Note, if you just have one sound / effect combination that the user can customise, just use setDefaultChannel when any changes are made. ### setDefaultChannel Android 8+ only. Overrides the properties for the default channel. The default channel is used if no other channel exists or is specified in the notification. Any options not specified will not be overridden. Should be called as soon as possible (on app start) so default notifications will work as expected. Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {object} - channel configuration object - {function} success - callback function which will be call on successfully setting default channel - {function} error - callback function which will be passed a {string} error message as an argument ```javascript var channel = { id: "my_default_channel", name: "My Default Name", description: "My Default Description", sound: "ringtone", vibration: [500, 200, 500], light: true, lightColor: parseInt("FF0000FF", 16).toString(), importance: 4, badge: false, visibility: -1 }; FirebasePlugin.setDefaultChannel(channel, function(){ console.log('Default channel set'); }, function(error){ console.log('Set default channel error: ' + error); }); ``` ### Default Android Channel Properties The default channel is initialised at app startup with the following default settings: ```json { id: "fcm_default_channel", name: "Default", description: "", sound: "default", vibration: true, light: true, lightColor: -1, importance: 4, badge: true, visibility: 1 } ``` ### deleteChannel Android 8+ only. Removes a previously defined channel. Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {string} - id of channel to delete - {function} success - callback function which will be call on successfully deleting channel - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.deleteChannel("my_channel_id", function(){ console.log('Channel deleted'); }, function(error){ console.log('Delete channel error: ' + error); }); ``` ### listChannels Android 8+ only. Gets a list of all channels. Calling on Android 7 or below or another platform will have no effect. **Parameters**: - {function} success - callback function which will be passed the {array} of channel objects as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.listChannels( function(channels){ if(typeof channels == "undefined") return; for(var i=0;i Android


iOS
## Authentication ### isUserSignedIn Checks if there is a current Firebase user signed into the app. **Parameters**: - {function} success - callback function to pass {boolean} result to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.isUserSignedIn(function(isSignedIn) { console.log("User "+(isSignedIn ? "is" : "is not") + " signed in"); }, function(error) { console.error("Failed to check if user is signed in: " + error); }); ``` ### signOutUser Signs current Firebase user out of the app. **Parameters**: - {function} success - callback function to pass {boolean} result to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.signOutUser(function() { console.log("User signed out"); }, function(error) { console.error("Failed to sign out user: " + error); }); ``` ### getCurrentUser Returns details of the currently logged in user from local Firebase SDK. Note that some user properties will be empty is they are not defined in Firebase for the current user. **Parameters**: - {function} success - callback function to pass user {object} to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getCurrentUser(function(user) { console.log("Name: "+user.name); console.log("Email: "+user.email); console.log("Is email verified?: "+user.emailIsVerified); console.log("Phone number: "+user.phoneNumber); console.log("Photo URL: "+user.photoUrl); console.log("UID: "+user.uid); console.log("Provider ID: "+user.providerId); console.log("ID token: "+user.idToken); }, function(error) { console.error("Failed to get current user data: " + error); }); ``` ### reloadCurrentUser Loads details of the currently logged in user from remote Firebase server. This differs from `getCurrentUser()` which loads the locally cached details which may be stale. For example, if you want to check if a user has verified their email address, this method will guarantee the reported verified state is up-to-date. **Parameters**: - {function} success - callback function to pass user {object} to as an argument - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.reloadCurrentUser(function(user) { console.log("Name: "+user.name); console.log("Email: "+user.email); console.log("Is email verified?: "+user.emailIsVerified); console.log("Phone number: "+user.phoneNumber); console.log("Photo URL: "+user.photoUrl); console.log("UID: "+user.uid); console.log("Provider ID: "+user.providerId); console.log("ID token: "+user.idToken); }, function(error) { console.error("Failed to reload current user data: " + error); }); ``` ### updateUserProfile Updates the display name and/or photo URL of the current Firebase user signed into the app. **Parameters**: - {object} profile - new profile details: - {string} name - display name of user - {string} photoUri - URL of user profile photo - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.updateUserProfile({ name: "Homer Simpson", photoUri: "http://homer.simpson.com/photo.png" },function() { console.log("User profile successfully updated"); }, function(error) { console.error("Failed to update user profile: " + error); }); ``` ### updateUserEmail Updates/sets the email address of the current Firebase user signed into the app. **Parameters**: - {string} email - email address of user - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.updateUserEmail("user@somewhere.com",function() { console.log("User email successfully updated"); }, function(error) { console.error("Failed to update user email: " + error); }); ``` ### sendUserEmailVerification Sends a verification email to the currently configured email address of the current Firebase user signed into the app. When the user opens the contained link, their email address will have been verified. **Parameters**: - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.sendUserEmailVerification(function() { console.log("User verification email successfully sent"); }, function(error) { console.error("Failed to send user verification email: " + error); }); ``` ### updateUserPassword Updates/sets the account password for the current Firebase user signed into the app. **Parameters**: - {string} password - user-defined password - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.updateUserPassword("mypassword",function() { console.log("User password successfully updated"); }, function(error) { console.error("Failed to update user password: " + error); }); ``` ### sendUserPasswordResetEmail Sends a password reset email to the specified user email address. Note: doesn't require the Firebase user to be signed in to the app. **Parameters**: - {string} email - email address of user - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.sendUserPasswordResetEmail("user@somewhere.com",function() { console.log("User password reset email sent successfully"); }, function(error) { console.error("Failed to send user password reset email: " + error); }); ``` ### deleteUser Deletes the account of the current Firebase user signed into the app. **Parameters**: - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.deleteUser(function() { console.log("User account deleted"); }, function(error) { console.error("Failed to delete current user account: " + error); }); ``` ### createUserWithEmailAndPassword Creates a new email/password-based user account. If account creation is successful, user will be automatically signed in. **Parameters**: - {string} email - user email address. It is the responsibility of the app to ensure this is a valid email address. - {string} password - user password. It is the responsibility of the app to ensure the password is suitable. - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.createUserWithEmailAndPassword(email, password, function() { console.log("Successfully created email/password-based user account"); // User is now signed in }, function(error) { console.error("Failed to create email/password-based user account", error); }); ``` ### signInUserWithEmailAndPassword Signs in to an email/password-based user account. **Parameters**: - {string} email - user email address - {string} password - user password - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.signInUserWithEmailAndPassword(email, password, function() { console.log("Successfully signed in"); // User is now signed in }, function(error) { console.error("Failed to sign in", error); }); ``` ### signInUserWithCustomToken Signs in user with custom token. **Parameters**: - {string} customToken - the custom token - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.signInUserWithCustomToken(customToken, function() { console.log("Successfully signed in"); // User is now signed in }, function(error) { console.error("Failed to sign in", error); }); ``` ### signInUserAnonymously Signs in user anonymously. **Parameters**: - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.signInUserAnonymously(function() { console.log("Successfully signed in"); // User is now signed in }, function(error) { console.error("Failed to sign in", error); }); ``` ### verifyPhoneNumber Requests verification of a phone number. The resulting credential can be used to create/sign in to a phone number-based user account in your app or to link the phone number to an existing user account **NOTE: This will only work on physical devices with a SIM card (not iOS Simulator or Android Emulator)** In response to your request, you'll receive a verification ID which you can use in conjunction with the verification code to sign the user in. There are 3 verification scenarios: - Some Android devices support "instant verification" where the phone number can be instantly verified without sending or receiving an SMS. - In this case, the user doesn't need to do anything in order for you to sign them in and you don't need to provide any additional credentials in order to sign the user in or link the user account to an existing Firebase user account. - Some Android devices support "auto-retrieval" where Google Play services is able to detect the incoming verification SMS and perform verification with no user action required. - As above, the user doesn't need to do anything in order for you to sign them in. - For other Android devices and all iOS devices, the user must manually enter the verification code received in the SMS into your app. - This code be used, along with the accompanying verification ID, to sign the user in or link phone number to an existing Firebase user account. **Parameters**: - {function} success - callback function to pass {object} credentials to as an argument - {function} error - callback function which will be passed a {string} error message as an argument - {string} phoneNumber - phone number to verify - {integer} timeOutDuration - (optional) time to wait in seconds before timing out - {string} fakeVerificationCode - (optional) to test instant verification on Android ,specify a fake verification code to return for whitelisted phone numbers. - See [Firebase SDK Phone Auth Android Integration Testing](https://firebase.google.com/docs/auth/android/phone-auth#integration-testing) for more info. The success callback will be passed a credential object with the following possible properties: - {boolean} instantVerification - `true` if the Android device used instant verification to instantly verify the user without sending an SMS or used auto-retrieval to automatically read an incoming SMS. If this is `false`, the device will be sent an SMS containing the verification code. If the Android device supports auto-retrieval, on the device receiving the SMS, this success callback will be immediately invoked again with `instantVerification: true` and no user action will be required for verification since Google Play services will extract and submit the verification code. Otherwise the user must manually enter the verification code from the SMS into your app. Always `false` on iOS. - {string} id - the identifier of a native credential object which can be used for signing in the user. Will only be present if `instantVerification` is `true`. - {string} verificationId - the verification ID to be passed along with the verification code sent via SMS to sign the user in. Will only be present if `instantVerification` is `false`. Example usage: ```javascript var number = '+441234567890'; var timeOutDuration = 60; var fakeVerificationCode = '123456'; var awaitingSms = false; FirebasePlugin.verifyPhoneNumber(function(credential) { if(credential.instantVerification){ if(awaitingSms){ awaitingSms = false; // the Android device used auto-retrieval to extract and submit the verification code in the SMS so dismiss user input UI dismissUserPromptToInputCode(); } signInWithCredential(credential); }else{ awaitingSms = true; promptUserToInputCode() // you need to implement this .then(function(userEnteredCode){ awaitingSms = false; credential.code = userEnteredCode; // set the user-entered verification code on the credential object signInWithCredential(credential); }); } }, function(error) { console.error("Failed to verify phone number: " + JSON.stringify(error)); }, number, timeOutDuration, fakeVerificationCode); function signInWithCredential(credential){ FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); } ``` #### Android To use phone auth with your Android app, you need to configure your app SHA-1 hash in the android app configuration in the Firebase console. See [this guide](https://developers.google.com/android/guides/client-auth) to find how to your SHA-1 app hash. See the [Firebase phone auth integration guide for native Android](https://firebase.google.com/docs/auth/android/phone-auth) for more information. #### iOS When you call this method on iOS, FCM sends a silent push notification to the iOS device to verify it. So to use phone auth with your iOS app, you need to: - [setup your iOS app for push notifications](https://firebase.google.com/docs/cloud-messaging/ios/certs) - Verify that push notifications are arriving on your physical device - [Upload your APNs auth key to the Firebase console](https://firebase.google.com/docs/cloud-messaging/ios/client#upload_your_apns_authentication_key). You can [set up reCAPTCHA verification for iOS](https://firebase.google.com/docs/auth/ios/phone-auth#set-up-recaptcha-verification) automatically by specifying the `SETUP_RECAPTCHA_VERIFICATION` plugin variable at plugin install time: cordova plugin add cordova-plugin-firebasex --variable SETUP_RECAPTCHA_VERIFICATION=true This adds the `REVERSED_CLIENT_ID` from the `GoogleService-Info.plist` to the list of custom URL schemes in your Xcode project, so you don't need to do this manually. ### authenticateUserWithGoogle Authenticates the user with a Google account to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. **Parameters**: - {string} clientId - your OAuth 2.0 client ID - [see here](https://developers.google.com/identity/sign-in/android/start-integrating#get_your_backend_servers_oauth_20_client_id) how to obtain it. - {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: - {string} id - the identifier of a native credential object which can be used for signing in the user. - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.authenticateUserWithGoogle(clientId, function(credential) { FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); }, function(error) { console.error("Failed to authenticate with Google: " + error); }); ``` #### Android To use Google Sign-in in your Android app you need to do the following: - Add the SHA-1 fingerprint of your app's signing key to your Firebase project - Enable Google Sign-in in the Firebase console For details how to do the above, see the [Google Sign-In on Android page](https://firebase.google.com/docs/auth/android/google-signin) in the Firebase documentation. ### authenticateUserWithApple Authenticates the user with an Apple account using Sign In with Apple to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. **Parameters**: - {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: - {string} id - the identifier of a native credential object which can be used for signing in the user. - {function} error - callback function which will be passed a {string} error message as an argument - {string} locale - (Android only) the language to display Apple's Sign-in screen in. - Defaults to "en" (English) if not specified. - See [the Apple documentation](https://developer.apple.com/documentation/signinwithapplejs/incorporating_sign_in_with_apple_into_other_platforms###2112) for a list of supported locales. - The value is ignored on iOS which uses the locale of the device to determine the display language. Example usage: ```javascript FirebasePlugin.authenticateUserWithApple(function(credential) { FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); }, function(error) { console.error("Failed to authenticate with Apple: " + error); }, 'en_GB'); ``` #### iOS To use Sign In with Apple in your iOS app you need to do the following: - Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/ios/apple#before-you-begin) - After adding the `cordova-ios` platform, open the project workspace in Xcode (`platforms/ios/YourApp.xcworkspace`) and add the "Sign In with Apple" capability in the "Signing & Capabilities section" - Note: AFAIK there is currently no way to automate the addition of this capability #### Android To use Sign In with Apple in your Android app you need to do the following: - Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/android/apple#before-you-begin) ### signInWithCredential Signs the user into Firebase with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. See the [Android-](https://firebase.google.com/docs/auth/android/phone-auth#sign-in-the-user) and [iOS](https://firebase.google.com/docs/auth/ios/phone-auth#sign-in-the-user-with-the-verification-code)-specific Firebase documentation for more info. **Parameters**: - {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - {string} id - the identifier of a native credential object which can be used for signing in the user. Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. If true, you do not need to provide a user-entered verification. - Only present if the credential was obtained via `verifyPhoneNumber()` - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. - {function} success - callback function to call on successful sign-in using credentials - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript function signInWithCredential(credential){ FirebasePlugin.signInWithCredential(credential, function() { console.log("Successfully signed in"); }, function(error) { console.error("Failed to sign in", error); }); } ``` ### linkUserWithCredential Links an existing Firebase user account with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. See the [Android-](https://firebase.google.com/docs/auth/android/account-linking) and [iOS](https://firebase.google.com/docs/auth/ios/account-linking)-specific Firebase documentation for more info. **Parameters**: - {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - {string} id - the identifier of a native credential object which can be used for signing in the user. Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. If true, you do not need to provide a user-entered verification. - Only present if the credential was obtained via `verifyPhoneNumber()` - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. - {function} success - callback function to call on successful linking using credentials - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript function linkUserWithCredential(credential){ FirebasePlugin.linkUserWithCredential(credential, function() { console.log("Successfully linked"); }, function(error) { console.error("Failed to link", error); }); } ``` ### reauthenticateWithCredential Reauthenticates the currently signed in user with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. **Parameters**: - {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: - {string} id - the identifier of a native credential object which can be used for signing in the user. Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. If true, you do not need to provide a user-entered verification. - Only present if the credential was obtained via `verifyPhoneNumber()` - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. - {function} success - callback function to call on success - {function} error - callback function which will be passed a {string} error message as an argument Example usage: ```javascript FirebasePlugin.reauthenticateWithCredential(credential, function() { console.log("Successfully reauthenticated"); }, function(error) { console.error("Failed to reauthenticate", error); }); ``` ### registerAuthStateChangeListener Registers a Javascript function to invoke when Firebase Authentication state changes between user signed in/signed out. **Parameters**: - {function} fn - callback function to invoke when authentication state changes - Will be a passed a single boolean argument which is `true` if user just signed in and `false` if user just signed out. Example usage: ```javascript FirebasePlugin.registerAuthStateChangeListener(function(userSignedIn){ console.log("Auth state changed: User signed " + (userSignedIn ? "in" : "out")); }); ``` ## Remote Config ### fetch Fetch Remote Config parameter values for your app: **Parameters**: - {integer} cacheExpirationSeconds (optional) - cache expiration in seconds - {function} success - callback function on successfully fetching remote config - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.fetch(function () { // success callback }, function () { // error callback }); // or, specify the cacheExpirationSeconds FirebasePlugin.fetch(600, function () { // success callback }, function () { // error callback }); ``` ### activateFetched Activate the Remote Config fetched config: **Parameters**: - {function} success - callback function which will be passed a {boolean} argument indicating whether fetched config was successfully activated - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.activateFetched(function(activated) { // activated will be true if there was a fetched config activated, // or false if no fetched config was found, or the fetched config was already activated. console.log(activated); }, function(error) { console.error(error); }); ``` ### getValue Retrieve a Remote Config value: **Parameters**: - {string} key - key for which to fetch associated value - {function} success - callback function which will be passed a {any} argument containing the value stored against the specified key. - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getValue("key", function(value) { console.log(value); }, function(error) { console.error(error); }); ``` ### getByteArray Android only. Retrieve a Remote Config byte array: **Parameters**: - {string} key - key for which to fetch associated value - {function} success - callback function which will be passed a {string} argument containing the Base64 encoded string that represents the value stored against the specified key. - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getByteArray("key", function(bytes) { // a Base64 encoded string that represents the value for "key" console.log(bytes.base64); // a numeric array containing the values of the byte array (i.e. [0xFF, 0x00]) console.log(bytes.array); }, function(error) { console.error(error); }); ``` ### getInfo Get the current state of the FirebaseRemoteConfig singleton object: **Parameters**: - {function} success - callback function which will be passed an {object} argument containing the state info - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.getInfo(function(info) { // the status of the developer mode setting (true/false) console.log(info.configSettings.developerModeEnabled); // (iOS only) for how much (secs) fetch cache is valid and data will not be refetched console.log(info.configSettings.minimumFetchInterval); // (iOS only) value in seconds to abandon a pending fetch request made to the backend console.log(info.configSettings.fetchTimeout); // the timestamp (milliseconds since epoch) of the last successful fetch console.log(info.fetchTimeMillis); // the status of the most recent fetch attempt (int) // 0 = Config has never been fetched. // 1 = Config fetch succeeded. // 2 = Config fetch failed. // 3 = Config fetch was throttled. console.log(info.lastFetchStatus); }, function(error) { console.error(error); }); ``` ### setConfigSettings Android only. Change the settings for the FirebaseRemoteConfig object's operations: **Parameters**: - {object} configSettings - object specifying the remote config settings - {function} success - callback function to be call on successfully setting the remote config settings - {function} error - callback function which will be passed a {string} error message as an argument ```javascript var settings = { developerModeEnabled: true } FirebasePlugin.setConfigSettings(settings); ``` ### setDefaults Android only. Set defaults in the Remote Config: **Parameters**: - {object} defaultSettings - object specifying the default remote config settings - {function} success - callback function to be call on successfully setting the remote config setting defaults - {function} error - callback function which will be passed a {string} error message as an argument ```javascript // define defaults var defaults = { // map property name to value in Remote Config defaults mLong: 1000, mString: 'hello world', mDouble: 3.14, mBoolean: true, // map "mBase64" to a Remote Config byte array represented by a Base64 string // Note: the Base64 string is in an array in order to differentiate from a string config value mBase64: ["SGVsbG8gV29ybGQ="], // map "mBytes" to a Remote Config byte array represented by a numeric array mBytes: [0xFF, 0x00] } // set defaults FirebasePlugin.setDefaults(defaults); ``` ## Performance ### setPerformanceCollectionEnabled Manually enable/disable performance data collection, e.g. if [disabled on app startup](#disable-data-collection-on-startup). **Parameters**: - {boolean} setEnabled - whether to enable or disable performance data collection ```javascript FirebasePlugin.setPerformanceCollectionEnabled(true); // Enables performance data collection FirebasePlugin.setPerformanceCollectionEnabled(false); // Disables performance data collection ``` ### isPerformanceCollectionEnabled Indicates whether performance data collection is enabled. Notes: - This value applies both to the current app session and subsequent app sessions until such time as it is changed. - It returns the value set by [setPerformanceCollectionEnabled()](#setperformancecollectionenabled). - If automatic data collection was not [disabled on app startup](#disable-data-collection-on-startup), this will always return `true`. **Parameters**: - {function} success - callback function which will be invoked on success. Will be passed a {boolean} indicating if the setting is enabled. - {function} error - (optional) callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.isPerformanceCollectionEnabled(function(enabled){ console.log("Performance data collection is "+(enabled ? "enabled" : "disabled")); }, function(error){ console.error("Error getting Performance data collection setting: "+error); }); ``` ### startTrace Start a trace. **Parameters**: - {string} name - name of trace to start - {function} success - callback function to call on successfully starting trace - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.startTrace("test trace", success, error); ``` ### incrementCounter To count the performance-related events that occur in your app (such as cache hits or retries), add a line of code similar to the following whenever the event occurs, using a string other than retry to name that event if you are counting a different type of event: **Parameters**: - {string} name - name of trace - {string} counterName - name of counter to increment - {function} success - callback function to call on successfully incrementing counter - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.incrementCounter("test trace", "retry", success, error); ``` ### stopTrace Stop the trace **Parameters**: - {string} name - name of trace to stop - {function} success - callback function to call on successfully stopping trace - {function} error - callback function which will be passed a {string} error message as an argument ```javascript FirebasePlugin.stopTrace("test trace"); ``` ## Firestore These plugin API functions provide CRUD operations for working with documents in Firestore collections. Notes: - Only top-level Firestore collections are currently supported - [subcollections](https://firebase.google.com/docs/firestore/manage-data/structure-data#subcollections) (nested collections within documents) are currently not supported due to the complexity of mapping the native objects into the plugin's JS API layer. - A document object may contain values of primitive Javascript types `string`, `number`, `boolean`, `array` or `object`. Arrays and objects may contain nested structures of these types. - If a collection name referenced in a document write operation does not already exist, it will be created by the first write operation referencing it. ### addDocumentToFirestoreCollection Adds a new document to a Firestore collection, which will be allocated an auto-generated document ID. **Parameters**: - {object} document - document object to add to collection - {string} collection - name of top-level collection to add document to. - {function} success - callback function to call on successfully adding the document. Will be passed a {string} argument containing the auto-generated document ID that the document was stored against. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var document = { "a_string": "foo", "a_list": [1, 2, 3], "an_object": { "an_integer": 1, } }; var collection = "my_collection"; FirebasePlugin.addDocumentToFirestoreCollection(document, collection, function(documentId){ console.log("Successfully added document with id="+documentId); }, function(error){ console.error("Error adding document: "+error); }); ``` ### setDocumentInFirestoreCollection Sets (adds/replaces) a document with the given ID in a Firestore collection. **Parameters**: - {string} documentId - document ID to use when setting document in the collection. - {object} document - document object to set in collection. - {string} collection - name of top-level collection to set document in. - {function} success - callback function to call on successfully setting the document. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var document = { "a_string": "foo", "a_list": [1, 2, 3], "an_object": { "an_integer": 1, } }; var collection = "my_collection"; FirebasePlugin.setDocumentInFirestoreCollection(documentId, document, collection, function(){ console.log("Successfully set document with id="+documentId); }, function(error){ console.error("Error setting document: "+error); }); ``` ### updateDocumentInFirestoreCollection Updates an existing document with the given ID in a Firestore collection. This is a non-destructive update that will only overwrite existing keys in the existing document or add new ones if they don't already exist. If the no document with the specified ID exists in the collection, an error will be raised. **Parameters**: - {string} documentId - document ID of the document to update. - {object} document - entire document or document fragment to update existing document with. - {string} collection - name of top-level collection to update document in. - {function} success - callback function to call on successfully updating the document. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var documentFragment = { "a_string": "new value", "a_new_string": "bar" }; var collection = "my_collection"; FirebasePlugin.updateDocumentInFirestoreCollection(documentId, documentFragment, collection, function(){ console.log("Successfully updated document with id="+documentId); }, function(error){ console.error("Error updating document: "+error); }); ``` ### deleteDocumentFromFirestoreCollection Deletes an existing document with the given ID in a Firestore collection. Note: If the no document with the specified ID exists in the collection, the Firebase SDK will still return a successful outcome. **Parameters**: - {string} documentId - document ID of the document to delete. - {string} collection - name of top-level collection to delete document in. - {function} success - callback function to call on successfully deleting the document. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var collection = "my_collection"; FirebasePlugin.deleteDocumentFromFirestoreCollection(documentId, collection, function(){ console.log("Successfully deleted document with id="+documentId); }, function(error){ console.error("Error deleting document: "+error); }); ``` ### documentExistsInFirestoreCollection Indicates if a document with the given ID exists in a Firestore collection. **Parameters**: - {string} documentId - document ID of the document. - {string} collection - name of top-level collection to check for document. - {function} success - callback function to call pass result. Will be passed an {boolean} which is `true` if a document exists. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var collection = "my_collection"; FirebasePlugin.documentExistsInFirestoreCollection(documentId, collection, function(exists){ console.log("Document " + (exists ? "exists" : "doesn't exist")); }, function(error){ console.error("Error fetching document: "+error); }); ``` ### fetchDocumentInFirestoreCollection Fetches an existing document with the given ID from a Firestore collection. Note: If the no document with the specified ID exists in the collection, the error callback will be invoked. **Parameters**: - {string} documentId - document ID of the document to fetch. - {string} collection - name of top-level collection to fetch document from. - {function} success - callback function to call on successfully fetching the document. Will be passed an {object} contain the document contents. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var documentId = "my_doc"; var collection = "my_collection"; FirebasePlugin.fetchDocumentInFirestoreCollection(documentId, collection, function(document){ console.log("Successfully fetched document: "+JSON.stringify(document)); }, function(error){ console.error("Error fetching document: "+error); }); ``` ### fetchFirestoreCollection Fetches all the documents in the specific collection. **Parameters**: - {string} collection - name of top-level collection to fetch. - {array} filters - a list of filters to sort/filter the documents returned from your collection. - Supports `where`, `orderBy`, `startAt`, `endAt` and `limit` filters. - See the [Firestore documentation](https://firebase.google.com/docs/firestore/query-data/queries) for more details. - {function} success - callback function to call on successfully deleting the document. Will be passed an {object} containing all the documents in the collection, indexed by document ID. If a Firebase collection with that name does not exist or it contains no documents, the object will be empty. - {function} error - callback function which will be passed a {string} error message as an argument. ```javascript var collection = "my_collection"; var filters = [ ['where', 'field', '==', 'value'], ['orderBy', 'field', 'desc'] ]; FirebasePlugin.fetchFirestoreCollection(collection, filters, function(documents){ console.log("Successfully fetched collection: "+JSON.stringify(documents)); }, function(error){ console.error("Error fetching collection: "+error); }); ``` # Credits - [@robertarnesson](https://github.com/robertarnesson) for the original [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) from which this plugin is forked. - [@sagrawal31](https://github.com/sagrawal31) and [Wiz Panda](https://github.com/wizpanda) for contributions via [cordova-plugin-firebase-lib](https://github.com/wizpanda/cordova-plugin-firebase-lib). - [Full list of contributors](https://github.com/dpa99c/cordova-plugin-firebasex/graphs/contributors) \ No newline at end of file +cordova-plugin-firebasex [![Latest Stable Version](https://img.shields.io/npm/v/cordova-plugin-firebasex.svg)](https://www.npmjs.com/package/cordova-plugin-firebasex) [![Total Downloads](https://img.shields.io/npm/dt/cordova-plugin-firebasex.svg)](https://npm-stat.com/charts.html?package=cordova-plugin-firebasex) +======================== + +Brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project. + +Upgraded to the Firebase Crahlytics SDK for both [Android](https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=android) & [iOS](https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=ios) + +Supported platforms: Android and iOS + +**IMPORTANT:** Before opening an issue against this plugin, please read [Reporting issues](#reporting-issues). + +# cli_build branch +This branch of the plugin is specifically intended for those building (directly or indirectly) via the Cordova CLI. +It removes the Firebase Inapp Messaging and Google Tag Manager SDK components due to these causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). + +To use it, install an npm release with the `-cli` suffix, e.g.: + + cordova plugin add cordova-plugin-firebasex@9.1.2-cli + +Or install it directly from this branch: + + cordova plugin add https://github.com/dpa99c/cordova-plugin-firebasex#cli_build + +If you wish to use either of these components, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a major plugin release via the NPM registry and build using Xcode. + + +[![donate](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG_global.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ZRD3W47HQ3EMJ) + +I dedicate a considerable amount of my free time to developing and maintaining this Cordova plugin, along with my other Open Source software. +To help ensure this plugin is kept updated, new features are added and bugfixes are implemented quickly, please donate a couple of dollars (or a little more if you can stretch) as this will help me to afford to dedicate time to its maintenance. Please consider donating if you're using this plugin in an app that makes you money, if you're being paid to make the app, if you're asking for new features or priority bug fixes. + + + + + +**Table of Contents** + +- [Installation](#installation) + - [Plugin variables](#plugin-variables) + - [Android & iOS](#android--ios) + - [Android only](#android-only) + - [iOS only](#ios-only) + - [Supported Cordova Versions](#supported-cordova-versions) + - [Supported Mobile Platform Versions](#supported-mobile-platform-versions) + - [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) + - [Breaking API changes](#breaking-api-changes) + - [Ionic 4+](#ionic-4) + - [Ionic 3](#ionic-3) +- [Build environment notes](#build-environment-notes) + - [PhoneGap Build](#phonegap-build) + - [Android-specific](#android-specific) + - [Specifying Android library versions](#specifying-android-library-versions) + - [AndroidX](#androidx) + - [Google Play Services and Firebase libraries](#google-play-services-and-firebase-libraries) + - [iOS-specific](#ios-specific) + - [Specifying iOS library versions](#specifying-ios-library-versions) + - [Cocoapods](#cocoapods) + - [Out-of-date pods](#out-of-date-pods) + - [Strip debug symbols](#strip-debug-symbols) + - [Cordova CLI builds](#cordova-cli-builds) +- [Firebase config setup](#firebase-config-setup) +- [Disable data collection on startup](#disable-data-collection-on-startup) +- [Example project](#example-project) +- [Reporting issues](#reporting-issues) + - [Reporting a bug or problem](#reporting-a-bug-or-problem) + - [Requesting a new feature](#requesting-a-new-feature) +- [Cloud messaging](#cloud-messaging) + - [Background notifications](#background-notifications) + - [Foreground notifications](#foreground-notifications) + - [Android notifications](#android-notifications) + - [Android background notifications](#android-background-notifications) + - [Android foreground notifications](#android-foreground-notifications) + - [Android Notification Channels](#android-notification-channels) + - [Android 7 and below](#android-7-and-below) + - [Android Notification Icons](#android-notification-icons) + - [Android Default Notification Icon](#android-default-notification-icon) + - [Android Large Notification Icon](#android-large-notification-icon) + - [Android Custom Notification Icons](#android-custom-notification-icons) + - [Android Notification Color](#android-notification-color) + - [Android Notification Sound](#android-notification-sound) + - [Android 8.0 and above](#android-80-and-above) + - [On Android 7 and below](#on-android-7-and-below) + - [iOS notifications](#ios-notifications) + - [iOS background notifications](#ios-background-notifications) + - [iOS notification sound](#ios-notification-sound) + - [iOS badge number](#ios-badge-number) + - [Data messages](#data-messages) + - [Data message notifications](#data-message-notifications) + - [Android data message notifications](#android-data-message-notifications) + - [iOS data message notifications](#ios-data-message-notifications) + - [Custom FCM message handling](#custom-fcm-message-handling) + - [Android](#android) + - [iOS](#ios) + - [Example](#example) +- [InApp Messaging](#inapp-messaging) +- [Google Tag Manager](#google-tag-manager) + - [Android](#android-1) + - [iOS](#ios-1) +- [API](#api) + - [Notifications and data messages](#notifications-and-data-messages) + - [getToken](#gettoken) + - [getId](#getid) + - [onTokenRefresh](#ontokenrefresh) + - [getAPNSToken](#getapnstoken) + - [onApnsTokenReceived](#onapnstokenreceived) + - [onMessageReceived](#onmessagereceived) + - [grantPermission](#grantpermission) + - [hasPermission](#haspermission) + - [unregister](#unregister) + - [isAutoInitEnabled](#isautoinitenabled) + - [setAutoInitEnabled](#setautoinitenabled) + - [setBadgeNumber](#setbadgenumber) + - [getBadgeNumber](#getbadgenumber) + - [clearAllNotifications](#clearallnotifications) + - [subscribe](#subscribe) + - [unsubscribe](#unsubscribe) + - [createChannel](#createchannel) + - [setDefaultChannel](#setdefaultchannel) + - [Default Android Channel Properties](#default-android-channel-properties) + - [deleteChannel](#deletechannel) + - [listChannels](#listchannels) + - [Analytics](#analytics) + - [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled) + - [isAnalyticsCollectionEnabled](#isanalyticscollectionenabled) + - [logEvent](#logevent) + - [setScreenName](#setscreenname) + - [setUserId](#setuserid) + - [setUserProperty](#setuserproperty) + - [Crashlytics](#crashlytics) + - [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled) + - [isCrashlyticsCollectionEnabled](#iscrashlyticscollectionenabled) + - [isCrashlyticsCollectionCurrentlyEnabled](#iscrashlyticscollectioncurrentlyenabled) + - [setCrashlyticsUserId](#setcrashlyticsuserid) + - [sendCrash](#sendcrash) + - [logMessage](#logmessage) + - [logError](#logerror) + - [Authentication](#authentication) + - [isUserSignedIn](#isusersignedin) + - [signOutUser](#signoutuser) + - [getCurrentUser](#getcurrentuser) + - [reloadCurrentUser](#reloadcurrentuser) + - [updateUserProfile](#updateuserprofile) + - [updateUserEmail](#updateuseremail) + - [sendUserEmailVerification](#senduseremailverification) + - [updateUserPassword](#updateuserpassword) + - [sendUserPasswordResetEmail](#senduserpasswordresetemail) + - [deleteUser](#deleteuser) + - [createUserWithEmailAndPassword](#createuserwithemailandpassword) + - [signInUserWithEmailAndPassword](#signinuserwithemailandpassword) + - [signInUserWithCustomToken](#signinuserwithcustomtoken) + - [signInUserAnonymously](#signinuseranonymously) + - [verifyPhoneNumber](#verifyphonenumber) + - [Android](#android-2) + - [iOS](#ios-2) + - [authenticateUserWithGoogle](#authenticateuserwithgoogle) + - [Android](#android-3) + - [authenticateUserWithApple](#authenticateuserwithapple) + - [iOS](#ios-3) + - [Android](#android-4) + - [signInWithCredential](#signinwithcredential) + - [linkUserWithCredential](#linkuserwithcredential) + - [reauthenticateWithCredential](#reauthenticatewithcredential) + - [registerAuthStateChangeListener](#registerauthstatechangelistener) + - [Remote Config](#remote-config) + - [fetch](#fetch) + - [activateFetched](#activatefetched) + - [getValue](#getvalue) + - [getByteArray](#getbytearray) + - [getInfo](#getinfo) + - [setConfigSettings](#setconfigsettings) + - [setDefaults](#setdefaults) + - [Performance](#performance) + - [setPerformanceCollectionEnabled](#setperformancecollectionenabled) + - [isPerformanceCollectionEnabled](#isperformancecollectionenabled) + - [startTrace](#starttrace) + - [incrementCounter](#incrementcounter) + - [stopTrace](#stoptrace) + - [Firestore](#firestore) + - [addDocumentToFirestoreCollection](#adddocumenttofirestorecollection) + - [setDocumentInFirestoreCollection](#setdocumentinfirestorecollection) + - [updateDocumentInFirestoreCollection](#updatedocumentinfirestorecollection) + - [deleteDocumentFromFirestoreCollection](#deletedocumentfromfirestorecollection) + - [documentExistsInFirestoreCollection](#documentexistsinfirestorecollection) + - [fetchDocumentInFirestoreCollection](#fetchdocumentinfirestorecollection) + - [fetchFirestoreCollection](#fetchfirestorecollection) +- [Credits](#credits) + + + +# Installation +Install the plugin by adding it to your project's config.xml: +```xml + +``` +or by running: +``` +cordova plugin add cordova-plugin-firebasex +``` + +## Plugin variables +The following Cordova plugin variables are supported by the plugin. +Note that these must be set at plugin installation time. If you wish to change plugin variables, you'll need to uninstall the plugin and reinstall it with the new variable values. + +### Android & iOS +- `FIREBASE_ANALYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Analytics data collection on app startup +- `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` - whether to automatically enable Firebase Performance data collection on app startup +- `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` - whether to automatically enable Firebase Crashlytics data collection on app startup +See [Disable data collection on startup](#disable-data-collection-on-startup) for more info. + +### Android only +The following plugin variables are used to specify the Firebase SDK versions as Gradle dependencies on Android: +- `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` +- `ANDROID_PLAY_SERVICES_AUTH_VERSION` +- `ANDROID_FIREBASE_ANALYTICS_VERSION` +- `ANDROID_FIREBASE_MESSAGING_VERSION` +- `ANDROID_FIREBASE_CONFIG_VERSION` +- `ANDROID_FIREBASE_PERF_VERSION` +- `ANDROID_FIREBASE_AUTH_VERSION` +- `ANDROID_FIREBASE_FIRESTORE_VERSION` +- `ANDROID_CRASHLYTICS_VERSION` +- `ANDROID_CRASHLYTICS_NDK_VERSION` +- `ANDROID_GSON_VERSION` +See [Specifying Android library versions](#specifying-android-library-versions) for more info. + +- `ANDROID_ICON_ACCENT` - sets the default accent color for system notifications. See [Android Notification Color](#android-notification-color) for more info. + +### iOS only +- `IOS_STRIP_DEBUG` - prevents symbolification of all libraries included via Cocoapods. See [Strip debug symbols](#strip-debug-symbols) for more info. + - e.g. `--variable IOS_STRIP_DEBUG=true` + - Defaults to `false` if not specified. +- `SETUP_RECAPTCHA_VERIFICATION` - automatically sets up reCAPTCHA verification for phone authentication on iOS. See [verifyPhoneNumber](#verifyphonenumber) for more info. + - e.g. `--variable IOS_STRIP_DEBUG=true` + - Defaults to `false` if not specified. +- `IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL` - If `true` Firebase Messaging will automatically establish a socket-based, direct channel to the FCM server. + - e.g. `--variable IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL=true` + - Defaults to `false` if not specified. + - See [`shouldEstablishDirectChannel`](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#/c:objc(cs)FIRMessaging(py)shouldEstablishDirectChannel) + - Note: Firebase Messaging iOS SDK version 7.0 will be a breaking change where the SDK will no longer support iOS Direct Channel API. + +## Supported Cordova Versions +- cordova: `>= 9` +- cordova-android: `>= 8` +- cordova-ios: `>= 5` + +## Supported Mobile Platform Versions +- Android `>= 4.1` +- iOS `>= 10.0` + +## Migrating from cordova-plugin-firebase +This plugin is a fork of [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) which has been reworked to fix issues and add new functionality. +If you already have [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) installed in your Cordova project, you need to completely remove it before installing this plugin otherwise they will conflict and cause build errors in your project. The safest way of doing this is as follows: + + rm -Rf platforms/android + cordova plugin rm cordova-plugin-firebase + rm -Rf plugins/ node_modules/ + npm install + cordova plugin add cordova-plugin-firebasex + cordova platform add android + +### Breaking API changes +**IMPORTANT:** Recent versions of `cordova-plugin-firebasex` have made breaking changes to the plugin API in order to fix bugs or add more functionality. +Therefore you can no longer directly substitute `cordova-plugin-firebasex` in place of `cordova-plugin-firebase` without making code changes. + +You should be aware of the following breaking changes compared with `cordova-plugin-firebase`: +* Minimum supported Cordova versions + * `cordova@9` (CLI) + * `cordova-android@8` (Android platform) + * `cordova-ios@5` (iOS platform) +* Migrated to AndroidX from legacy Android Support Library + * add dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) and [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) +* Migrated to Cocoapods to satisfy Firebase SDK dependencies on iOS +* `onNotificationOpen()` renamed to `onMessageReceived()` + * `tap` parameter is only set when user taps on a notification (not when a message is received from FCM) + * `tap=foreground|background` instead of `tap=true|false` +* `hasPermission()` receives argument as a boolean (rather than an object with `isEnabled` key) + * e.g. `FirebasePlugin.hasPermission(function(hasPermission){ + console.log("Permission is " + (hasPermission ? "granted" : "denied")); + });` +* Adds support for foreground notifications and data notification messages + +### Ionic 4+ +Ionic Native provides a [FirebaseX Typescript wrapper](https://ionicframework.com/docs/native/firebase-x) for using `cordova-plugin-firebasex` with Ionic v4, v5 and above. +Please see their documentation for usage. + +First install the package. + +``` +ionic cordova plugin add cordova-plugin-firebasex +npm install @ionic-native/firebase-x +``` + +If you're using Angular, register it in your component/service's `NgModule` (for example, app.module.ts) as a provider. + +```typescript +import { FirebaseX } from "@ionic-native/firebase-x/ngx"; + +@NgModule({ + //declarations, imports... + providers: [ + FirebaseX, + //other providers... + ] +}) +``` + +Then you're good to go. +```typescript +import { FirebaseX } from "@ionic-native/firebase-x/ngx"; + +//... + +constructor(private firebase: FirebaseX) + +this.firebase.getToken().then(token => console.log(`The token is ${token}`)) +this.firebase.onMessageReceived().subscribe(data => console.log(`FCM message: ${data}`)); +``` + +**NOTE:** +- This plugin provides only the Javascript API as documented below. +- The Typescript wrapper is owned and maintain by Ionic. +- Please [report any issues](https://github.com/ionic-team/ionic-native/issues) against the [Ionic Native repo](https://github.com/ionic-team/ionic-native/), not this one. +- Any issues opened against this repo which relate to the Typescript wrapper **will be closed immediately**. + + +### Ionic 3 +The above PR does not work for Ionic 3 so you (currently) can't use the [Ionic Native Firebase](https://ionicframework.com/docs/native/firebase) Typescript wrapper with Ionic 3. +(i.e. `import { Firebase } from "@ionic-native/firebase"` will not work). + +To use `cordova-plugin-firebasex` with Ionic 3, you'll need to call its Javascript API directly from your Typescript app code, for example: + +```typescript +(window).FirebasePlugin.getToken(token => console.log(`token: ${token}`)) + +(window).FirebasePlugin.onMessageReceived((message) => { + if (message.tap) { console.log(`Notification was tapped in the ${message.tap}`); } +}) +``` + +If you want to make the `onMessageReceived()` JS API behave like the Ionic Native wrapper: + +```javascript +onNotificationOpen() { + return new Observable(observer => { + (window as any).FirebasePlugin.onMessageReceived((response) => { + observer.next(response); + }); + }); +} +... +this.onNotificationOpen().subscribe(data => console.log(`FCM message: ${data}`)); +``` + +See the [cordova-plugin-firebasex-ionic3-test](https://github.com/dpa99c/cordova-plugin-firebasex-ionic3-test) example project for a demonstration of how to use the plugin with Ionic 3. + +# Build environment notes + +## PhoneGap Build +This plugin will not work with Phonegap Build (and other remote cloud build envs) do not support Cordova hook scripts as they are used by this plugin to configure the native platform projects. + +## Android-specific + +### Specifying Android library versions +This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Gradle on Android. +By default this plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned versions as ``'s, for example: + +```xml + +``` + +The Android defaults can be overridden at plugin installation time by specifying plugin variables as command-line arguments, for example: + + cordova plugin add cordova-plugin-firebasex --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 + +Or you can specify them as plugin variables in your `config.xml`, for example: + +```xml + + + +``` + +The following plugin variables are used to specify the following Gradle dependency versions on Android: + +- `ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION` => `com.google.android.gms:play-services-tagmanager` +- `ANDROID_PLAY_SERVICES_AUTH_VERSION` => `com.google.android.gms:play-services-auth` +- `ANDROID_FIREBASE_ANALYTICS_VERSION` => `com.google.firebase:firebase-analytics` +- `ANDROID_FIREBASE_MESSAGING_VERSION` => `com.google.firebase:firebase-messaging` +- `ANDROID_FIREBASE_CONFIG_VERSION` => `com.google.firebase:firebase-config` +- `ANDROID_FIREBASE_PERF_VERSION` => `com.google.firebase:firebase-perf` +- `ANDROID_FIREBASE_AUTH_VERSION` => `com.google.firebase:firebase-auth` +- `ANDROID_FIREBASE_FIRESTORE_VERSION` => `com.google.firebase:firebase-firestore` +- `ANDROID_CRASHLYTICS_VERSION` => `com.crashlytics.sdk.android:crashlytics` +- `ANDROID_CRASHLYTICS_NDK_VERSION` => `com.crashlytics.sdk.android:crashlytics-ndk` +- `ANDROID_GSON_VERSION` => `com.google.code.gson:gson` + +For example: + + cordova plugin add cordova-plugin-firebasex \ + --variable ANDROID_PLAY_SERVICES_TAGMANAGER_VERSION=17.0.0 \ + --variable ANDROID_PLAY_SERVICES_AUTH_VERSION=17.0.0 \ + --variable ANDROID_FIREBASE_ANALYTICS_VERSION=17.0.0 \ + --variable ANDROID_FIREBASE_MESSAGING_VERSION=19.0.0 \ + --variable ANDROID_FIREBASE_CONFIG_VERSION=18.0.0 \ + --variable ANDROID_FIREBASE_PERF_VERSION=18.0.0 \ + --variable ANDROID_FIREBASE_AUTH_VERSION=18.0.0 \ + --variable ANDROID_CRASHLYTICS_VERSION=2.10.1 \ + --variable ANDROID_CRASHLYTICS_NDK_VERSION=2.1.0 \ + +### AndroidX +This plugin has been migrated to use [AndroidX (Jetpack)](https://developer.android.com/jetpack/androidx/migrate) which is the successor to the [Android Support Library](https://developer.android.com/topic/libraries/support-library/index). +This is implemented by adding a dependency on [cordova-plugin-androidx](https://github.com/dpa99c/cordova-plugin-androidx) which enables AndroidX in the Android platform of a Cordova project. + +This is because the [major release of the Firebase and Play Services libraries on 17 June 2019](https://developers.google.com/android/guides/releases#june_17_2019) were migrated to AndroidX. + +Therefore if your project includes any plugins which are dependent on the legacy Android Support Library, you should add [cordova-plugin-androidx-adapter](https://github.com/dpa99c/cordova-plugin-androidx-adapter) to your project. +This plugin will dynamically migrate any plugin code from the Android Support Library to AndroidX equivalents. + +## Google Play Services and Firebase libraries +Your Android build may fail if you are installing multiple plugins that use the Google Play Services library. +This is caused by plugins installing different versions of the Google Play Services library. +This can be resolved by installing [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) which enables you to override the versions specified by other plugins in order to align them. + +Similarly, if your build is failing because multiple plugins are installing different versions of the Firebase library, +you can try installing [cordova-android-firebase-gradle-release](https://github.com/dpa99c/cordova-android-firebase-gradle-release) to align these. + +## iOS-specific +### Specifying iOS library versions +This plugin depends on various components such as the Firebase SDK which are pulled in at build-time by Cocoapods on iOS. +This plugin pins specific versions of these in [its `plugin.xml`](https://github.com/dpa99c/cordova-plugin-firebase/blob/master/plugin.xml) where you can find the currently pinned iOS versions in the ``'s, for example: + + + +**It is currently not possible to override these at plugin installation time** because `cordova@9`/`cordova-ios@5` does not support the use of plugin variables in the ``'s `spec` attribute. +Therefore if you need to change the specified versions, you'll currently need to do this by forking the plugin and editing the `plugin.xml` to change the specified `spec` values. + +### Cocoapods +This plugin relies on `cordova@9`/`cordova-ios@5` support for the [CocoaPods dependency manager]( https://cocoapods.org/) in order to satisfy the iOS Firebase SDK library dependencies. + +Therefore please make sure you have Cocoapods@>=1.8 installed in your iOS build environment - setup instructions can be found [here](https://cocoapods.org/). + +If building your project in Xcode, you need to open `YourProject.xcworkspace` (not `YourProject.xcodeproj`) so both your Cordova app project and the Pods project will be loaded into Xcode. + +You can list the pod dependencies in your Cordova iOS project by installing [cocoapods-dependencies](https://github.com/segiddins/cocoapods-dependencies): + + sudo gem install cocoapods-dependencies + cd platforms/ios/ + pod dependencies + +### Out-of-date pods +If you receive a build error such as this: + + None of your spec sources contain a spec satisfying the dependencies: `Firebase/Analytics (~> 6.1.0), Firebase/Analytics (= 6.1.0, ~> 6.1.0)`. + +Make sure your local Cocoapods repo is up-to-date by running `pod repo update` then run `pod install` in `/your_project/platforms/ios/`. + +### Strip debug symbols +If your iOS app build contains too many debug symbols (i.e. because you include lots of libraries via a Cocoapods), you might get an error (e.g. [issue #28](https://github.com/dpa99c/cordova-plugin-firebase/issues/28)) when you upload your binary to App Store Connect, e.g.: + + ITMS-90381: Too many symbol files - These symbols have no corresponding slice in any binary [16EBC8AC-DAA9-39CF-89EA-6A58EB5A5A2F.symbols, 1B105D69-2039-36A4-A04D-96C1C5BAF235.symbols, 476EACDF-583B-3B29-95B9-253CB41097C8.symbols, 9789B03B-6774-3BC9-A8F0-B9D44B08DCCB.symbols, 983BAE60-D245-3291-9F9C-D25E610846AC.symbols]. + +To prevent this, you can set the `IOS_STRIP_DEBUG` plugin variable which prevents symbolification of all libraries included via Cocoapods ([see here for more information](https://stackoverflow.com/a/48518656/777265)): + + cordova plugin add cordova-plugin-firebasex --variable IOS_STRIP_DEBUG=true + +By default this preference is set to `false`. + +Note: if you enable this setting, any crashes that occur within libraries included via Cocopods will not be recorded in Crashlytics or other crash reporting services. + +### Cordova CLI builds +If you are building (directly or indirectly) via the Cordova CLI and encounter build failures on iOS, this is likely due to [an issue with Cordova CLI builds for iOS](https://github.com/apache/cordova-ios/issues/659) when including certain pods into the build (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). + +Note that building from Xcode works fine, so if you are able then do this. + +Otherwise (e.g. if building via a CI) then you'll need to switch to using the [cli_build branch](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) of this plugin which removes the Firebase Inapp Messaging and Google Tag Manager SDK components that are causing the build issues. + +# Firebase config setup +There's a handy [installation and setup guide on medium.com](https://medium.com/@felipepucinelli/how-to-add-push-notifications-in-your-cordova-application-using-firebase-69fac067e821). +However, if using this, remember this forked plugin is `cordova-plugin-firebasex` (not `cordova-plugin-firebase`). + +Download your Firebase configuration files, `GoogleService-Info.plist` for iOS and `google-services.json` for android, and place them in the root folder of your cordova project. +Check out this [firebase article](https://support.google.com/firebase/answer/7015592) for details on how to download the files. + +``` +- My Project/ + platforms/ + plugins/ + www/ + config.xml + google-services.json <-- + GoogleService-Info.plist <-- + ... +``` +IMPORTANT: The Firebase SDK requires the configuration files to be present and valid, otherwise your app will crash on boot or Firebase features won't work. + +# Disable data collection on startup +By default, analytics, performance and Crashlytics data will begin being collected as soon as the app starts up. +However, for data protection or privacy reasons, you may wish to disable data collection until such time as the user has granted their permission. + +To do this, set the following plugin variables to `false` at plugin install time: + +* `FIREBASE_ANALYTICS_COLLECTION_ENABLED` +* `FIREBASE_PERFORMANCE_COLLECTION_ENABLED` +* `FIREBASE_CRASHLYTICS_COLLECTION_ENABLED` + + + cordova plugin add cordova-plugin-firebasex \ + --variable FIREBASE_ANALYTICS_COLLECTION_ENABLED=false \ + --variable FIREBASE_PERFORMANCE_COLLECTION_ENABLED=false \ + --variable FIREBASE_CRASHLYTICS_COLLECTION_ENABLED=false + +This will disable data collection (on both Android & iOS) until you call [setAnalyticsCollectionEnabled](#setanalyticscollectionenabled), [setPerformanceCollectionEnabled](#setperformancecollectionenabled) and [setCrashlyticsCollectionEnabled](#setcrashlyticscollectionenabled): + + FirebasePlugin.setAnalyticsCollectionEnabled(true); + FirebasePlugin.setPerformanceCollectionEnabled(true); + FirebasePlugin.setCrashlyticsCollectionEnabled(true); + +Notes: +- Calling `setXCollectionEnabled()` will have no effect if the corresponding `FIREBASE_X_COLLECTION_ENABLED` variable is set to `true`. +- Calling `setAnalyticsCollectionEnabled(true|false)` or `setPerformanceCollectionEnabled(true|false)` will enable/disable data collection during the current app session and across subsequent app sessions until such time as the same method is called again with a different value. +- Calling `setCrashlyticsCollectionEnabled(true|false)` will enable/disable data collection during subsequent app sessions until such time as the same method is called again with a different value. It **does not** affect the current app session. + +# Example project +An example project repo exists to demonstrate and validate the functionality of this plugin: +https://github.com/dpa99c/cordova-plugin-firebasex-test + +Please use this as a working reference. + +Before reporting any issues, please (if possible) test against the example project to rule out causes external to this plugin. + +# Reporting issues +**IMPORTANT:** Please read the following carefully. +Failure to follow the issue template guidelines below will result in the issue being immediately closed. + +## Reporting a bug or problem +Before [opening a bug issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=bug_report.md&title=), please do the following: +- *DO NOT* open issues asking for support in using/integrating the plugin into your project + - Only open issues for suspected bugs/issues with the plugin that are generic and will affect other users + - I don't have time to offer free technical support: this is free open-source software + - Ask for help on StackOverflow, Ionic Forums, etc. + - Use the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) as a known working reference + - Any issues requesting support will be closed immediately. +- *DO NOT* open issues related to the [Ionic Typescript wrapper for this plugin](https://github.com/ionic-team/ionic-native/blob/master/src/%40ionic-native/plugins/firebase-x/index.ts) + - This is owned/maintained by [Ionic](https://github.com/ionic-team) and is not part of this plugin + - Please raise such issues/PRs against [Ionic Native](https://github.com/ionic-team/ionic-native/) instead. + - To verify an if an issue is caused by this plugin or its Typescript wrapper, please re-test using the vanilla Javascript plugin interface (without the Ionic Native wrapper). + - Any issue opened here which is obviously an Ionic Typescript wrapper issue will be closed immediately. +- If you are migrating from [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) to `cordova-plugin-firebasex` please make sure you have read the [Migrating from cordova-plugin-firebase](#migrating-from-cordova-plugin-firebase) section. +- Read the above documentation thoroughly + - For example, if you're having a build issue ensure you've read through the [build environment notes](#build-environment-notes) + - If an iOS CLI build is failing, ensure you've read the [Cordova CLI builds](#cordova-cli-builds) section +- Check the [CHANGELOG](https://github.com/dpa99c/cordova-plugin-firebasex/blob/master/CHANGELOG.md) for any breaking changes that may be causing your issue. +- Check a similar issue (open or closed) does not already exist against this plugin. + - Duplicates or near-duplicates will be closed immediately. +- When [creating a new issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new/choose) + - Choose the "Bug report" template + - Fill out the relevant sections of the template and delete irrelevant sections + - *WARNING:* Failure to complete the issue template will result in the issue being closed immediately. +- Reproduce the issue using the [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) + - This will eliminate bugs in your code or conflicts with other code as possible causes of the issue + - This will also validate your development environment using a known working codebase + - If reproducing the issue using the example project is not possible, create an isolated test project that you are able to share +- Include full verbose console output when reporting build issues + - If the full console output is too large to insert directly into the Github issue, then post it on an external site such as [Pastebin](https://pastebin.com/) and link to it from the issue + - Often the details of an error causing a build failure is hidden away when building with the CLI + - To get the full detailed console output, append the `--verbose` flag to CLI build commands + - e.g. `cordova build ios --verbose` + - Failure to include the full console output will result in the issue being closed immediately +- If the issue relates to the plugin documentation (and not the code), please of a [documentation issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=documentation-issue.md&title=) + +## Requesting a new feature +Before [opening a feature request issue](https://github.com/dpa99c/cordova-plugin-firebasex/issues/new?assignees=&labels=&template=feature_request.md&title=), please do the following: +- Check the above documentation to ensure the feature you are requesting doesn't already exist +- Check the list if open/closed issues to check if there's a reason that feature hasn't been included already +- Ensure the feature you are requesting is actually possible to implement and generically useful to other users than yourself +- Where possible, post a link to the documentation related to the feature you are requesting +- Include other relevant links, e.g. + - Stack Overflow post illustrating a solution + - Code within another Github repo that illustrates a solution + +# Cloud messaging + +

+ +   + +

+ +There are 2 distinct types of messages that can be sent by Firebase Cloud Messaging (FCM): + +- [Notification messages](https://firebase.google.com/docs/cloud-messaging/concept-options#notifications) + - automatically displayed to the user by the operating system on behalf of the client app **while your app is not running or is in the background** + - **if your app is in the foreground when the notification message arrives**, it is passed to the client app and it is the responsibility of the client app to display it. + - have a predefined set of user-visible keys and an optional data payload of custom key-value pairs. +- [Data messages](https://firebase.google.com/docs/cloud-messaging/concept-options#data_messages) + - Client app is responsible for processing data messages. + - Data messages have only custom key-value pairs. + +Note: only notification messages can be sent via the Firebase Console - data messages must be sent via the [FCM APIs](https://firebase.google.com/docs/cloud-messaging/server). + +## Background notifications +If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. + +By default, no callback is made to the plugin when the message arrives while the app is not in the foreground, since the display of the notification is entirely handled by the operating system. +However, there are platform-specific circumstances where a callback can be made when the message arrives and the app is in the background that don't require user interaction to receive the message payload - see [Android background notifications](#android-background-notifications) and [iOS background notifications](#ios-background-notifications) for details. + +If the user taps the system notification, this launches/resumes the app and the notification title, body and optional data payload is passed to the [onMessageReceived](#onMessageReceived) callback. + +When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the background/not running, it will be passed the property `tap: "background"`. + + +## Foreground notifications +If the notification message arrives while the app is in running in the foreground, by default **it will NOT be displayed as a system notification**. +Instead the notification message payload will be passed to the [onMessageReceived](#onMessageReceived) callback for the plugin to handle (`tap` will not be set). + +If you include the `notification_foreground` key in the `data` payload, the plugin will also display a system notification upon receiving the notification messages while the app is running in the foreground. +For example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "data": { + "notification_foreground": "true", + } +} +``` + +When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the foreground, it will be passed the property `tap: "foreground"`. + +You can set additional properties of the foreground notification using the same key names as for [Data Message Notifications](#data-message-notification-keys). + +## Android notifications +Notifications on Android can be customised to specify the sound, icon, LED colour, etc. that's displayed when the notification arrives. + +### Android background notifications +If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. + +If a notification message arrives while the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. + +If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. + +In addition to the title and body of the notification message, Android system notifications support specification of the following notification settings: +- [Icon](#android-notification-icons) +- [Sound](#android-notification-sound) +- [Color accent](#android-notification-color) +- [Channel ID](#android-notification-channels) (Android 8.0 (O) and above) + - This channel configuration enables you to specify: + - Sound + - Vibration + - LED light + - Badge + - Importance + - Visibility + - See [createChannel](#createchannel) for details. + +Note: on tapping a background notification, if your app is not running, only the `data` section of the notification message payload will be delivered to [onMessageReceived](#onMessageReceived). +i.e. the notification title, body, etc. will not. Therefore if you need the properties of the notification message itself (e.g. title & body) to be delivered to [onMessageReceived](#onMessageReceived), you must duplicate these in the `data` section, e.g.: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "data": { + "notification_body": "Notification body", + "notification_title": "Notification title" + } +} +``` + +### Android foreground notifications +If the notification message arrives while the app is in the foreground, by default a system notification won't be displayed and the data will be passed to [onMessageReceived](#onMessageReceived). + +However, if you set the `notification_foreground` key in the `data` section of the notification message payload, this will cause the plugin to display system notification when the message is received while your app is in the foreground. You can customise the notification using the same keys as for [Android data message notifications](#android-data-message-notifications). + +### Android Notification Channels +- Android 8 (O) introduced [notification channels](https://developer.android.com/training/notify-user/channels). +- Notification channels are configured by the app and used to determine the **sound/lights/vibration** settings of system notifications. +- By default, this plugin creates a default channel with [default properties](#default-android-channel-properties) + - These can be overridden via the [setDefaultChannel](#setdefaultchannel) function. +- The plugin enables the creation of additional custom channels via the [createChannel](#createchannel) function. + +First you need to create a custom channel with the desired settings, for example: + +```javascript +var channel = { + id: "my_channel_id", + sound: "mysound", + vibration: true, + light: true, + lightColor: parseInt("FF0000FF", 16).toString(), + importance: 4, + badge: true, + visibility: 1 +}; + +FirebasePlugin.createChannel(channel, +function(){ + console.log('Channel created: ' + channel.id); +}, +function(error){ + console.log('Create channel error: ' + error); +}); +``` + +Then reference it from your message payload: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "channel_id": "my_channel_id" + } + } +} +``` + +#### Android 7 and below +- the channel referenced in the message payload will be ignored +- the sound setting of system notifications is specified in the notification message itself - see [Android Notification Sound](#android-notification-sound). + + +### Android Notification Icons +By default the plugin will use the default app icon for notification messages. + +#### Android Default Notification Icon +To define a custom default notification icon, you need to create the images and deploy them to the `/platforms/android/app/src/main/res/` folders. +The easiest way to create the images is using the [Image Asset Studio in Android Studio](https://developer.android.com/studio/write/image-asset-studio#create-notification) or using the [Android Asset Studio webapp](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=notification_icon). + +The icons should be monochrome transparent PNGs with the following sizes: + +- mdpi: 24x24 +- hdpi: 36x36 +- xhdpi: 48x48 +- xxhdpi: 72x72 +- xxxhdpi: 96x96 + +Once you've created the images, you need to deploy them from your Cordova project to the native Android project. +To do this, copy the `drawable-DPI` image directories into your Cordova project and add `` entries to the `` section of your `config.xml`, where `src` specifies the relative path to the images files within your Cordova project directory. + +For example, copy the`drawable-DPI` image directories to `/res/android/` and add the following to your `config.xml`: + +```xml + + + + + + + +``` + +The default notification icon images **must** be named `notification_icon.png`. + +You then need to add a `` block to the `config.xml` which will instruct Firebase to use your icon as the default for notifications: + +```xml + + + + + +``` + + +#### Android Large Notification Icon +The default notification icons above are monochrome, however you can additionally define a larger multi-coloured icon. + +**NOTE:** FCM currently does not support large icons in system notifications displayed for notification messages received in the while the app is in the background (or not running). +So the large icon will currently only be used if specified in [data messages](#android-data-messages) or [foreground notifications](#foreground-notifications). + +The large icon image should be a PNG-24 that's 256x256 pixels and must be named `notification_icon_large.png` and should be placed in the `drawable-xxxhdpi` resource directory. +As with the small icons, you'll need to add a `` entry to the `` section of your `config.xml`: + +```xml + + + +``` + + +#### Android Custom Notification Icons +You can define additional sets of notification icons in the same manner as above. +These can be specified in notification or data messages. + +For example: + +```xml + + + + + + +``` + +When sending an FCM notification message, you will then specify the icon name in the `android.notification` section, for example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "icon": "my_icon", + } + }, + "data": { + "notification_foreground": "true", + } +} +``` + +You can also reference these icons in [data messages](#android-data-messages), for example: + +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_icon": "my_icon", + } +} +``` + + +### Android Notification Color +On Android Lollipop (5.0/API 21) and above you can set the default accent color for the notification by adding a color setting. +This is defined as an [ARGB colour](https://en.wikipedia.org/wiki/RGBA_color_space#ARGB_(word-order)) which the plugin sets by default to `#FF00FFFF` (cyan). +Note: On Android 7 and above, the accent color can only be set for the notification displayed in the system tray area - the icon in the statusbar is always white. + +You can override this default by specifying a value using the `ANDROID_ICON_ACCENT` plugin variable during plugin installation, for example: + + cordova plugin add cordova-plugin-firebasex --variable ANDROID_ICON_ACCENT=#FF123456 + +You can override the default color accent by specifying the `colour` key as an RGB value in a notification message, e.g.: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "color": "#00ff00" + } + } +} +``` + +And in a data message: + +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_color": "#00ff00" + } +} +``` + +### Android Notification Sound +You can specify custom sounds for notifications or play the device default notification sound. + +Custom sound files must be in `.mp3` format and deployed to the `/res/raw` directory in the Android project. +To do this, you can add `` tags to your `config.xml` to deploy the files, for example: + +```xml + + + +``` + +To ensure your custom sounds works on all versions of Android, be sure to include both the channel name and sound name in your message payload (see below for details), for example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "channel_id": "my_channel_id", + "sound": "my_sound" + } + } +} +``` + +#### Android 8.0 and above +On Android 8.0 and above, the notification sound is specified by which [Android notification channel](#android-notification-channels) is referenced in the notification message payload. +First create a channel that references your sound, for example: + +```javascript +var channel = { + id: "my_channel_id", + sound: "my_sound" +}; + +FirebasePlugin.createChannel(channel, +function(){ + console.log('Channel created: ' + channel.id); +}, +function(error){ + console.log('Create channel error: ' + error); +}); +``` + +Then reference that channel in your message payload: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "channel_id": "my_channel_id" + } + } +} +``` + +#### On Android 7 and below +On Android 7 and below, you need to specify the sound file name in the `android.notification` section of the message payload. +For example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "sound": "my_sound" + } + } +} +``` + +And in a data message by specifying it in the `data` section: + +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_sound": "my_sound" + } +} +``` + +- To play the default notification sound, set `"sound": "default"`. +- To display a silent notification (no sound), omit the `sound` key from the message. + +## iOS notifications +Notifications on iOS can be customised to specify the sound and badge number that's displayed when the notification arrives. + +Notification settings are specified in the `apns.payload.aps` key of the notification message payload. +For example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "apns": { + "payload": { + "aps": { + "sound": "default", + "badge": 1, + "content-available": 1 + } + } + } +} +``` + +### iOS background notifications +If the app is in the background but is still running (i.e. has not been task-killed) and the device is not in power-saving mode, the `onMessageReceived` callback can be invoked when the message arrives without requiring user interaction (i.e. tapping the system notification). +To do this you must specify `"content-available": 1` in the `apns.payload.aps` section of the message payload - see the [Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW8) for more information. +When the message arrives, the `onMessageReceived` callback will be invoked without the `tap` property, indicating the message was received without user interaction. +If the user then taps the system notification, the app will be brought to the foreground and `onMessageReceived` will be invoked **again**, this time with `tap: "background"` indicating that the user tapped the system notification while the app was in the background. + +### iOS notification sound +You can specify custom sounds for notifications or play the device default notification sound. + +Custom sound files must be in a supported audio format (see [this Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW10) for supported formats). +For example to convert an `.mp3` file to the supported `.caf` format run: + + afconvert my_sound.mp3 my_sound.caf -d ima4 -f caff -v + +Sound files must be deployed with the iOS application bundle. +To do this, you can add `` tags to your `config.xml` to deploy the files, for example: + +```xml + + + +``` + +In a notification message, specify the `sound` key in the `apns.payload.aps` section, for example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "apns": { + "payload": { + "aps": { + "sound": "my_sound.caf" + } + } + } +} +``` + +- To play the default notification sound, set `"sound": "default"`. +- To display a silent notification (no sound), omit the `sound` key from the message. + +In a data message, specify the `notification_ios_sound` key in the `data` section: + +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_ios_sound": "my_sound.caf" + } +} +``` + +### iOS badge number +In a notification message, specify the `badge` key in the `apns.payload.aps` section, for example: + +```json +{ + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "apns": { + "payload": { + "aps": { + "badge": 1 + } + } + } +} +``` + +In a data message, specify the `notification_ios_badge` key in the `data` section: + +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_ios_badge": 1 + } +} +``` + +## Data messages +FCM data messages are sent as an arbitrary k/v structure and by default are passed to the app for it to handle them. + +**NOTE:** FCM data messages **cannot** be sent from the Firebase Console - they can only be sent via the FCM APIs. + +### Data message notifications +This plugin enables a data message to be displayed as a system notification. +To have the app display a notification when the data message arrives, you need to set the `notification_foreground` key in the `data` section. +You can then set a `notification_title` and `notification_body`, for example: + +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "foo" : "bar" + } +} +``` + +Additional platform-specific notification options can be set using the additional keys below (which are only relevant if the `notification_foreground` key is set). + +Note: [foreground notification messages](#foreground-notifications) can also make use of these keys. + +#### Android data message notifications +On Android: +- Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. +- Data messages (not containing notification keys) that arrive while your app is **not running** will be passed to the `onMessageReceived()` Javascript handler when the app is next launched. +- Data messages containing notification keys that arrive while your app is running or **not running** will be displayed as a system notification. + +The following Android-specific keys are supported and should be placed inside the `data` section: + +- `notification_android_icon` - name of a [custom notification icon](#android-custom-notification-icons) in the drawable resources + - if not specified, the plugin will use the default `notification_icon` if it exists; otherwise the default app icon will be displayed + - if a [large icon](#android-large-notification-icon) has been defined, it will also be displayed in the system notification. +- `notification_android_color` - the [color accent](#android-notification-color) to use for the small notification icon + - if not specified, the default color accent will be used +- `notification_android_channel_id` - ID of the [notification channel](#android-notification-channels) to use to display the notification + - Only applies to Android 8.0 and above + - If not specified, the [default notification channel](#default-android-channel-properties) will be used. + - You can override the default configuration for the default notification channel using [setDefaultChannel](#setdefaultchannel). + - You can create additional channels using [createChannel](#createchannel). +- `notification_android_priority` - Specifies the notification priority + - Possible values: + - `2` - Highest notification priority for your application's most important items that require the user's prompt attention or input. + - `1` - Higher notification priority for more important notifications or alerts. + - `0` - Default notification priority. + - `-1` - Lower notification priority for items that are less important. + - `-2` - Lowest notification priority. These items might not be shown to the user except under special circumstances, such as detailed notification logs. + - Defaults to `2` if not specified. +- `notification_android_visibility` - Specifies the notification visibility + - Possible values: + - `1` - Show this notification in its entirety on all lockscreens. + - `0` - Show this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. + - `-1` - Do not reveal any part of this notification on a secure lockscreen. + - Defaults to `1` if not specified. + +The following keys only apply to Android 7 and below. +On Android 8 and above they will be ignored - the `notification_android_channel_id` property should be used to specify a [notification channel](#android-notification-channels) with equivalent settings. + +- `notification_android_sound` - name of a sound resource to play as the [notification sound](#android-notification-sound) + - if not specified, no sound is played + - `default` plays the default device notification sound + - otherwise should be the name of an `.mp3` file in the `/res/raw` directory, e.g. `my_sound.mp3` => `"sounds": "my_sound"` +- `notification_android_lights` - color and pattern to use to blink the LED light + - if not defined, LED will not blink + - in the format `ARGB, time_on_ms, time_off_ms` where + - `ARGB` is an ARGB color definition e.g. `#ffff0000` + - `time_on_ms` is the time in milliseconds to turn the LED on for + - `time_off_ms` is the time in milliseconds to turn the LED off for + - e.g. `"lights": "#ffff0000, 250, 250"` +- `notification_android_vibrate` - pattern of vibrations to use when the message arrives + - if not specified, device will not vibrate + - an array of numbers specifying the time in milliseconds to vibrate + - e.g. `"vibrate": "500, 200, 500"` + +Example data message with Android notification keys: + +```json +{ + "name": "my_data_message", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_channel_id": "my_channel", + "notification_android_priority": "2", + "notification_android_visibility": "1", + "notification_android_color": "#ff0000", + "notification_android_icon": "coffee", + "notification_android_sound": "my_sound", + "notification_android_vibrate": "500, 200, 500", + "notification_android_lights": "#ffff0000, 250, 250" + } +} +``` + +#### iOS data message notifications +On iOS: +- Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. +- Data messages that arrive while your app is **not running** will **NOT be received by your app!** + +The following iOS-specific keys are supported and should be placed inside the `data` section: + +- `notification_ios_sound` - Sound to play when the notification is displayed + - To play a custom sound, set the name of the sound file bundled with your app, e.g. `"sound": "my_sound.caf"` - see [iOS notification sound](#ios-notification-sound) for more info. + - To play the default notification sound, set `"sound": "default"`. + - To display a silent notification (no sound), omit the `sound` key from the message. +- `notification_ios_badge` - Badge number to display on app icon on home screen. + +For example: +```json +{ + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_ios_sound": "my_sound.caf", + "notification_ios_badge": 1 + } +} +``` + +## Custom FCM message handling +In some cases you may want to handle certain incoming FCM messages differently rather than with the default behaviour of this plugin. +Therefore this plugin provides a mechanism by which you can implement your own custom FCM message handling for specific FCM messages which bypasses handling of those messages by this plugin. +To do this requires you to write native handlers for Android & iOS which hook into the native code of this plugin. + +### Android +You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/android/FirebasePluginMessageReceiver.java) and implements the `onMessageReceived()` and `sendMessage()` abstract methods. + +### iOS +You'll need to add a native class which extends the [`FirebasePluginMessageReceiver` abstract class](src/ios/FirebasePluginMessageReceiver.h) and implements the `sendNotification()` abstract method. + +### Example +The [example project](https://github.com/dpa99c/cordova-plugin-firebasex-test) contains an [example plugin](https://github.com/dpa99c/cordova-plugin-firebasex-test/tree/master/plugins/cordova-plugin-customfcmreceiver) which implements a custom receiver class for both platforms. +You can test this by building and running the example project app, and sending the [notification_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/notification_custom_receiver.json) and [data_custom_receiver](https://github.com/dpa99c/cordova-plugin-firebasex-test/blob/master/messages/data_custom_receiver.json) test messages using the [built-in FCM client](https://github.com/dpa99c/cordova-plugin-firebasex-test#messaging-client). + +# InApp Messaging +The Firebase Inapp Messaging SDK component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). +If you wish to use Firebase Inapp Messaging, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. + +# Google Tag Manager +The Google Tag Manager component has been removed from this [cli_build](https://github.com/dpa99c/cordova-plugin-firebasex/tree/cli_build) branch of the plugin due to the iOS component causing CLI builds to fail (see [#326](https://github.com/dpa99c/cordova-plugin-firebasex/issues/326)). +If you wish to use Google Tag Manager, please use the [master](https://github.com/dpa99c/cordova-plugin-firebasex) branch or install a plugin release via the NPM registry and build using Xcode. + +# API +The list of available methods for this plugin is described below. + +## Notifications and data messages +The plugin is capable of receiving push notifications and FCM data messages. + +See [Cloud messaging](#cloud-messaging) section for more. + +### getToken +Get the current FCM token. +Null if the token has not been allocated yet by the Firebase SDK. + +**Parameters**: +- {function} success - callback function which will be passed the {string} token as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.getToken(function(fcmToken) { + console.log(fcmToken); +}, function(error) { + console.error(error); +}); +``` +Note that token will be null if it has not been established yet. + +### getId +Get the app instance ID (an constant ID which persists as long as the app is not uninstalled/reinstalled). +Null if the ID has not been allocated yet by the Firebase SDK. + +**Parameters**: +- {function} success - callback function which will be passed the {string} ID as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.getId(function(appInstanceId) { + console.log(appInstanceId); +}, function(error) { + console.error(error); +}); +``` +Note that token will be null if it has not been established yet. + +### onTokenRefresh +Registers a handler to call when the FCM token changes. +This is the best way to get the token as soon as it has been allocated. +This will be called on the first run after app install when a token is first allocated. +It may also be called again under other circumstances, e.g. if `unregister()` is called or Firebase allocates a new token for other reasons. +You can use this callback to return the token to you server to keep the FCM token associated with a given user up-to-date. + +**Parameters**: +- {function} success - callback function which will be passed the {string} token as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.onTokenRefresh(function(fcmToken) { + console.log(fcmToken); +}, function(error) { + console.error(error); +}); +``` + +### getAPNSToken +iOS only. +Get the APNS token allocated for this app install. +Note that token will be null if it has not been allocated yet. + +**Parameters**: +- {function} success - callback function which will be passed the {string} APNS token as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.getAPNSToken(function(apnsToken) { + console.log(apnsToken); +}, function(error) { + console.error(error); +}); +``` + +### onApnsTokenReceived +iOS only. +Registers a handler to call when the APNS token is allocated. +This will be called once when remote notifications permission has been granted by the user at runtime. + +**Parameters**: +- {function} success - callback function which will be passed the {string} token as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.onApnsTokenReceived(function(apnsToken) { + console.log(apnsToken); +}, function(error) { + console.error(error); +}); +``` + +### onMessageReceived +Registers a callback function to invoke when: +- a notification or data message is received by the app +- a system notification is tapped by the user + +**Parameters**: +- {function} success - callback function which will be passed the {object} message as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.onMessageReceived(function(message) { + console.log("Message type: " + message.messageType); + if(message.messageType === "notification"){ + console.log("Notification message received"); + if(message.tap){ + console.log("Tapped in " + message.tap); + } + } + console.dir(message); +}, function(error) { + console.error(error); +}); +``` + +The `message` object passed to the callback function will contain the platform-specific FCM message payload along with the following keys: +- `messageType=notification|data` - indicates if received message is a notification or data message +- `tap=foreground|background` - set if the call to `onMessageReceived()` was initiated by user tapping on a system notification. + - indicates if the system notification was tapped while the app was in the foreground or background. + - not set if no system notification was tapped (i.e. message was received directly from FCM rather than via a user tap on a system notification). + +Notification message flow: + +1. App is in foreground: + a. By default, when a notification message arrives the app receives the notification message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. + b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. +2. App is in background: + a. User receives the notification message as a system notification in the device notification bar + b. User taps the system notification which launches the app + b. User receives the notification message payload in the `onMessageReceived` JavaScript callback + +Data message flow: + +1. App is in foreground: + a. By default, when a data message arrives the app receives the data message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. + b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. +2. App is in background: + a. The app receives the data message in the `onMessageReceived` JavaScript callback while in the background + b. If the data message contains the [data message notification keys](#data-message-notifications), the plugin will display a system notification for the data message while in the background. + +### grantPermission +Grant permission to receive push notifications (will trigger prompt) and return `hasPermission: true`. +iOS only (Android will always return true). + +**Parameters**: +- {function} success - callback function which will be passed the {boolean} permission result as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.grantPermission(function(hasPermission){ + console.log("Permission was " + (hasPermission ? "granted" : "denied")); +}); +``` +### hasPermission +Check permission to receive push notifications and return the result to a callback function as boolean. +On iOS, returns true is runtime permission for remote notifications is granted and enabled in Settings. +On Android, returns true if remote notifications are enabled. + +**Parameters**: +- {function} success - callback function which will be passed the {boolean} permission result as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.hasPermission(function(hasPermission){ + console.log("Permission is " + (hasPermission ? "granted" : "denied")); +}); +``` + +### unregister +Unregisters from Firebase by deleting the current device token. +Use this to stop receiving push notifications associated with the current token. +e.g. call this when you logout user from your app. +By default, a new token will be generated as soon as the old one is removed. +To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). + +**Parameters**: None + +```javascript +FirebasePlugin.unregister(); +``` + +### isAutoInitEnabled +Indicates whether autoinit is currently enabled. +If so, new FCM tokens will be automatically generated. + +**Parameters**: +- {function} success - callback function which will be passed the {boolean} result as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + + +```javascript +FirebasePlugin.isAutoInitEnabled(function(enabled){ + console.log("Auto init is " + (enabled ? "enabled" : "disabled")); +}); + +``` + +### setAutoInitEnabled +Sets whether to autoinit new FCM tokens. +By default, a new token will be generated as soon as the old one is removed. +To prevent a new token being generated, by sure to disable autoinit using [`setAutoInitEnabled()`](#setautoinitenabled) before calling [`unregister()`](#unregister). + +**Parameters**: +- {boolean} enabled - set true to enable, false to disable +- {function} success - callback function to call on successful execution of operation. +- {function} error - callback function which will be passed a {string} error message as an argument + + +```javascript +FirebasePlugin.setAutoInitEnabled(false, function(){ + console.log("Auto init has been disabled "); + FirebasePlugin.unregister(); +}); + +``` + +### setBadgeNumber +iOS only. +Set a number on the icon badge: + +**Parameters**: +- {integer} badgeNumber - number to set for the app badge + +```javascript +FirebasePlugin.setBadgeNumber(3); +``` + +Set 0 to clear the badge +```javascript +FirebasePlugin.setBadgeNumber(0); +``` + +Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) + +### getBadgeNumber +iOS only. +Get icon badge number: + +**Parameters**: +- {function} success - callback function which will be passed the {integer} current badge number as an argument + +```javascript +FirebasePlugin.getBadgeNumber(function(n) { + console.log(n); +}); +``` + +Note: this function is no longer available on Android (see [#124](https://github.com/dpa99c/cordova-plugin-firebasex/issues/124)) + +### clearAllNotifications +Clear all pending notifications from the drawer: + +**Parameters**: None + +```javascript +FirebasePlugin.clearAllNotifications(); +``` + +### subscribe +Subscribe to a topic. + +Topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. + +**Parameters**: +- {string} topicName - name of topic to subscribe to + +```javascript +FirebasePlugin.subscribe("latest_news"); +``` + +### unsubscribe +Unsubscribe from a topic. + +This will stop you receiving messages for that topic + +**Parameters**: +- {string} topicName - name of topic to unsubscribe from + +```javascript +FirebasePlugin.unsubscribe("latest_news"); +``` + +### createChannel +Android 8+ only. +Creates a custom channel to be used by notification messages which have the channel property set in the message payload to the `id` of the created channel: +- For background (system) notifications: `android.notification.channel_id` +- For foreground/data notifications: `data.notification_android_channel_id` + +For each channel you may set the sound to be played, the color of the phone LED (if supported by the device), whether to vibrate and set vibration pattern (if supported by the device), importance and visibility. +Channels should be created as soon as possible (on program start) so notifications can work as expected. +A default channel is created by the plugin at app startup; the properties of this can be overridden see [setDefaultChannel](#setdefaultchannel) + +Calling on Android 7 or below or another platform will have no effect. + +**Parameters**: +- {object} - channel configuration object (see below for object keys/values) +- {function} success - callback function which will be call on successful channel creation +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +// Define custom channel - all keys are except 'id' are optional. +var channel = { + // channel ID - must be unique per app package + id: "my_channel_id", + + // Channel description. Default: empty string + description: "Channel description", + + // Channel name. Default: empty string + name: "Channel name", + + //The sound to play once a push comes. Default value: 'default' + //Values allowed: + //'default' - plays the default notification sound + //'ringtone' - plays the currently set ringtone + //'false' - silent; don't play any sound + //filename - the filename of the sound file located in '/res/raw' without file extension (mysound.mp3 -> mysound) + sound: "mysound", + + //Vibrate on new notification. Default value: true + //Possible values: + //Boolean - vibrate or not + //Array - vibration pattern - e.g. [500, 200, 500] - milliseconds vibrate, milliseconds pause, vibrate, pause, etc. + vibration: true, + + // Whether to blink the LED + light: true, + + //LED color in ARGB format - this example BLUE color. If set to -1, light color will be default. Default value: -1. + lightColor: parseInt("FF0000FF", 16).toString(), + + //Importance - integer from 0 to 4. Default value: 4 + //0 - none - no sound, does not show in the shade + //1 - min - no sound, only shows in the shade, below the fold + //2 - low - no sound, shows in the shade, and potentially in the status bar + //3 - default - shows everywhere, makes noise, but does not visually intrude + //4 - high - shows everywhere, makes noise and peeks + importance: 4, + + //Show badge over app icon when non handled pushes are present. Default value: true + badge: true, + + //Show message on locked screen. Default value: 1 + //Possible values (default 1): + //-1 - secret - Do not reveal any part of the notification on a secure lockscreen. + //0 - private - Show the notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. + //1 - public - Show the notification in its entirety on all lockscreens. + visibility: 1 +}; + +// Create the channel +FirebasePlugin.createChannel(channel, +function(){ + console.log('Channel created: ' + channel.id); +}, +function(error){ + console.log('Create channel error: ' + error); +}); +``` + +Example FCM v1 API notification message payload for invoking the above example channel: + +```json + +{ + "notification": + { + "title":"Notification title", + "body":"Notification body" + }, + "android": { + "notification": { + "channel_id": "my_channel_id" + } + } +} + +``` + +If your Android app plays multiple sounds or effects, it's a good idea to create a channel for each likely combination. This is because once a channel is created you cannot override sounds/effects. +IE, expanding on the createChannel example: +```javascript +let soundList = ["train","woop","clock","radar","sonar"]; +for (let key of soundList) { + let name = "yourchannelprefix_" + key; + channel.id = name; + channel.sound = key; + channel.name = "Your description " + key; + + // Create the channel + window.FirebasePlugin.createChannel(channel, + function(){ + console.log('Notification Channel created: ' + channel.id + " " + JSON.stringify(channel)); + }, + function(error){ + console.log('Create notification channel error: ' + error); + }); +} +``` + +Note, if you just have one sound / effect combination that the user can customise, just use setDefaultChannel when any changes are made. + + +### setDefaultChannel +Android 8+ only. +Overrides the properties for the default channel. +The default channel is used if no other channel exists or is specified in the notification. +Any options not specified will not be overridden. +Should be called as soon as possible (on app start) so default notifications will work as expected. +Calling on Android 7 or below or another platform will have no effect. + +**Parameters**: +- {object} - channel configuration object +- {function} success - callback function which will be call on successfully setting default channel +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +var channel = { + id: "my_default_channel", + name: "My Default Name", + description: "My Default Description", + sound: "ringtone", + vibration: [500, 200, 500], + light: true, + lightColor: parseInt("FF0000FF", 16).toString(), + importance: 4, + badge: false, + visibility: -1 +}; + +FirebasePlugin.setDefaultChannel(channel, +function(){ + console.log('Default channel set'); +}, +function(error){ + console.log('Set default channel error: ' + error); +}); +``` + +### Default Android Channel Properties +The default channel is initialised at app startup with the following default settings: + +```json +{ + id: "fcm_default_channel", + name: "Default", + description: "", + sound: "default", + vibration: true, + light: true, + lightColor: -1, + importance: 4, + badge: true, + visibility: 1 +} +``` + +### deleteChannel +Android 8+ only. +Removes a previously defined channel. +Calling on Android 7 or below or another platform will have no effect. + +**Parameters**: +- {string} - id of channel to delete +- {function} success - callback function which will be call on successfully deleting channel +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.deleteChannel("my_channel_id", +function(){ + console.log('Channel deleted'); +}, +function(error){ + console.log('Delete channel error: ' + error); +}); + +``` + +### listChannels +Android 8+ only. +Gets a list of all channels. +Calling on Android 7 or below or another platform will have no effect. + +**Parameters**: +- {function} success - callback function which will be passed the {array} of channel objects as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.listChannels( +function(channels){ + if(typeof channels == "undefined") + return; + + for(var i=0;i +Android +
+ + +

+iOS +
+ + + + +## Authentication + +### isUserSignedIn +Checks if there is a current Firebase user signed into the app. + +**Parameters**: +- {function} success - callback function to pass {boolean} result to as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.isUserSignedIn(function(isSignedIn) { + console.log("User "+(isSignedIn ? "is" : "is not") + " signed in"); + }, function(error) { + console.error("Failed to check if user is signed in: " + error); + }); +``` + +### signOutUser +Signs current Firebase user out of the app. + +**Parameters**: +- {function} success - callback function to pass {boolean} result to as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.signOutUser(function() { + console.log("User signed out"); + }, function(error) { + console.error("Failed to sign out user: " + error); + }); +``` + +### getCurrentUser +Returns details of the currently logged in user from local Firebase SDK. +Note that some user properties will be empty is they are not defined in Firebase for the current user. + +**Parameters**: +- {function} success - callback function to pass user {object} to as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.getCurrentUser(function(user) { + console.log("Name: "+user.name); + console.log("Email: "+user.email); + console.log("Is email verified?: "+user.emailIsVerified); + console.log("Phone number: "+user.phoneNumber); + console.log("Photo URL: "+user.photoUrl); + console.log("UID: "+user.uid); + console.log("Provider ID: "+user.providerId); + console.log("ID token: "+user.idToken); + }, function(error) { + console.error("Failed to get current user data: " + error); + }); +``` + +### reloadCurrentUser +Loads details of the currently logged in user from remote Firebase server. +This differs from `getCurrentUser()` which loads the locally cached details which may be stale. +For example, if you want to check if a user has verified their email address, this method will guarantee the reported verified state is up-to-date. + +**Parameters**: +- {function} success - callback function to pass user {object} to as an argument +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.reloadCurrentUser(function(user) { + console.log("Name: "+user.name); + console.log("Email: "+user.email); + console.log("Is email verified?: "+user.emailIsVerified); + console.log("Phone number: "+user.phoneNumber); + console.log("Photo URL: "+user.photoUrl); + console.log("UID: "+user.uid); + console.log("Provider ID: "+user.providerId); + console.log("ID token: "+user.idToken); + }, function(error) { + console.error("Failed to reload current user data: " + error); + }); +``` + +### updateUserProfile +Updates the display name and/or photo URL of the current Firebase user signed into the app. + +**Parameters**: +- {object} profile - new profile details: + - {string} name - display name of user + - {string} photoUri - URL of user profile photo +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.updateUserProfile({ + name: "Homer Simpson", + photoUri: "http://homer.simpson.com/photo.png" + },function() { + console.log("User profile successfully updated"); + }, function(error) { + console.error("Failed to update user profile: " + error); + }); +``` + +### updateUserEmail +Updates/sets the email address of the current Firebase user signed into the app. + +**Parameters**: +- {string} email - email address of user +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.updateUserEmail("user@somewhere.com",function() { + console.log("User email successfully updated"); + }, function(error) { + console.error("Failed to update user email: " + error); + }); +``` + +### sendUserEmailVerification +Sends a verification email to the currently configured email address of the current Firebase user signed into the app. +When the user opens the contained link, their email address will have been verified. + +**Parameters**: +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.sendUserEmailVerification(function() { + console.log("User verification email successfully sent"); + }, function(error) { + console.error("Failed to send user verification email: " + error); + }); +``` + +### updateUserPassword +Updates/sets the account password for the current Firebase user signed into the app. + +**Parameters**: +- {string} password - user-defined password +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.updateUserPassword("mypassword",function() { + console.log("User password successfully updated"); + }, function(error) { + console.error("Failed to update user password: " + error); + }); +``` + +### sendUserPasswordResetEmail +Sends a password reset email to the specified user email address. +Note: doesn't require the Firebase user to be signed in to the app. + +**Parameters**: +- {string} email - email address of user +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.sendUserPasswordResetEmail("user@somewhere.com",function() { + console.log("User password reset email sent successfully"); + }, function(error) { + console.error("Failed to send user password reset email: " + error); + }); +``` + +### deleteUser +Deletes the account of the current Firebase user signed into the app. + +**Parameters**: +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript + FirebasePlugin.deleteUser(function() { + console.log("User account deleted"); + }, function(error) { + console.error("Failed to delete current user account: " + error); + }); +``` + +### createUserWithEmailAndPassword +Creates a new email/password-based user account. +If account creation is successful, user will be automatically signed in. + +**Parameters**: +- {string} email - user email address. It is the responsibility of the app to ensure this is a valid email address. +- {string} password - user password. It is the responsibility of the app to ensure the password is suitable. +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript + FirebasePlugin.createUserWithEmailAndPassword(email, password, function() { + console.log("Successfully created email/password-based user account"); + // User is now signed in + }, function(error) { + console.error("Failed to create email/password-based user account", error); + }); +``` + +### signInUserWithEmailAndPassword +Signs in to an email/password-based user account. + +**Parameters**: +- {string} email - user email address +- {string} password - user password +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript + FirebasePlugin.signInUserWithEmailAndPassword(email, password, function() { + console.log("Successfully signed in"); + // User is now signed in + }, function(error) { + console.error("Failed to sign in", error); + }); +``` + +### signInUserWithCustomToken +Signs in user with custom token. + +**Parameters**: +- {string} customToken - the custom token +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript + FirebasePlugin.signInUserWithCustomToken(customToken, function() { + console.log("Successfully signed in"); + // User is now signed in + }, function(error) { + console.error("Failed to sign in", error); + }); +``` + +### signInUserAnonymously +Signs in user anonymously. + +**Parameters**: +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript + FirebasePlugin.signInUserAnonymously(function() { + console.log("Successfully signed in"); + // User is now signed in + }, function(error) { + console.error("Failed to sign in", error); + }); +``` + +### verifyPhoneNumber +Requests verification of a phone number. +The resulting credential can be used to create/sign in to a phone number-based user account in your app or to link the phone number to an existing user account + +**NOTE: This will only work on physical devices with a SIM card (not iOS Simulator or Android Emulator)** + +In response to your request, you'll receive a verification ID which you can use in conjunction with the verification code to sign the user in. + +There are 3 verification scenarios: +- Some Android devices support "instant verification" where the phone number can be instantly verified without sending or receiving an SMS. + - In this case, the user doesn't need to do anything in order for you to sign them in and you don't need to provide any additional credentials in order to sign the user in or link the user account to an existing Firebase user account. +- Some Android devices support "auto-retrieval" where Google Play services is able to detect the incoming verification SMS and perform verification with no user action required. + - As above, the user doesn't need to do anything in order for you to sign them in. +- For other Android devices and all iOS devices, the user must manually enter the verification code received in the SMS into your app. + - This code be used, along with the accompanying verification ID, to sign the user in or link phone number to an existing Firebase user account. + +**Parameters**: +- {function} success - callback function to pass {object} credentials to as an argument +- {function} error - callback function which will be passed a {string} error message as an argument +- {string} phoneNumber - phone number to verify +- {integer} timeOutDuration - (optional) time to wait in seconds before timing out +- {string} fakeVerificationCode - (optional) to test instant verification on Android ,specify a fake verification code to return for whitelisted phone numbers. + - See [Firebase SDK Phone Auth Android Integration Testing](https://firebase.google.com/docs/auth/android/phone-auth#integration-testing) for more info. + +The success callback will be passed a credential object with the following possible properties: +- {boolean} instantVerification - `true` if the Android device used instant verification to instantly verify the user without sending an SMS +or used auto-retrieval to automatically read an incoming SMS. +If this is `false`, the device will be sent an SMS containing the verification code. +If the Android device supports auto-retrieval, on the device receiving the SMS, this success callback will be immediately invoked again with `instantVerification: true` and no user action will be required for verification since Google Play services will extract and submit the verification code. +Otherwise the user must manually enter the verification code from the SMS into your app. +Always `false` on iOS. +- {string} id - the identifier of a native credential object which can be used for signing in the user. +Will only be present if `instantVerification` is `true`. +- {string} verificationId - the verification ID to be passed along with the verification code sent via SMS to sign the user in. +Will only be present if `instantVerification` is `false`. + +Example usage: + +```javascript +var number = '+441234567890'; +var timeOutDuration = 60; +var fakeVerificationCode = '123456'; +var awaitingSms = false; + +FirebasePlugin.verifyPhoneNumber(function(credential) { + + if(credential.instantVerification){ + if(awaitingSms){ + awaitingSms = false; + // the Android device used auto-retrieval to extract and submit the verification code in the SMS so dismiss user input UI + dismissUserPromptToInputCode(); + } + signInWithCredential(credential); + }else{ + awaitingSms = true; + promptUserToInputCode() // you need to implement this + .then(function(userEnteredCode){ + awaitingSms = false; + credential.code = userEnteredCode; // set the user-entered verification code on the credential object + signInWithCredential(credential); + }); + } +}, function(error) { + console.error("Failed to verify phone number: " + JSON.stringify(error)); +}, number, timeOutDuration, fakeVerificationCode); + +function signInWithCredential(credential){ + FirebasePlugin.signInWithCredential(credential, function() { + console.log("Successfully signed in"); + }, function(error) { + console.error("Failed to sign in", error); + }); +} +``` + +#### Android +To use phone auth with your Android app, you need to configure your app SHA-1 hash in the android app configuration in the Firebase console. +See [this guide](https://developers.google.com/android/guides/client-auth) to find how to your SHA-1 app hash. +See the [Firebase phone auth integration guide for native Android](https://firebase.google.com/docs/auth/android/phone-auth) for more information. + +#### iOS +When you call this method on iOS, FCM sends a silent push notification to the iOS device to verify it. +So to use phone auth with your iOS app, you need to: +- [setup your iOS app for push notifications](https://firebase.google.com/docs/cloud-messaging/ios/certs) +- Verify that push notifications are arriving on your physical device +- [Upload your APNs auth key to the Firebase console](https://firebase.google.com/docs/cloud-messaging/ios/client#upload_your_apns_authentication_key). + +You can [set up reCAPTCHA verification for iOS](https://firebase.google.com/docs/auth/ios/phone-auth#set-up-recaptcha-verification) automatically by specifying the `SETUP_RECAPTCHA_VERIFICATION` plugin variable at plugin install time: + + cordova plugin add cordova-plugin-firebasex --variable SETUP_RECAPTCHA_VERIFICATION=true + +This adds the `REVERSED_CLIENT_ID` from the `GoogleService-Info.plist` to the list of custom URL schemes in your Xcode project, so you don't need to do this manually. + +### authenticateUserWithGoogle +Authenticates the user with a Google account to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. + +**Parameters**: +- {string} clientId - your OAuth 2.0 client ID - [see here](https://developers.google.com/identity/sign-in/android/start-integrating#get_your_backend_servers_oauth_20_client_id) how to obtain it. +- {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: + - {string} id - the identifier of a native credential object which can be used for signing in the user. +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript +FirebasePlugin.authenticateUserWithGoogle(clientId, function(credential) { + FirebasePlugin.signInWithCredential(credential, function() { + console.log("Successfully signed in"); + }, function(error) { + console.error("Failed to sign in", error); + }); +}, function(error) { + console.error("Failed to authenticate with Google: " + error); +}); +``` + +#### Android +To use Google Sign-in in your Android app you need to do the following: +- Add the SHA-1 fingerprint of your app's signing key to your Firebase project +- Enable Google Sign-in in the Firebase console + +For details how to do the above, see the [Google Sign-In on Android page](https://firebase.google.com/docs/auth/android/google-signin) in the Firebase documentation. + +### authenticateUserWithApple +Authenticates the user with an Apple account using Sign In with Apple to obtain a credential that can be used to sign the user in/link to an existing user account/reauthenticate the user. + +**Parameters**: +- {function} success - callback function to pass {object} credentials to as an argument. The credential object has the following properties: + - {string} id - the identifier of a native credential object which can be used for signing in the user. +- {function} error - callback function which will be passed a {string} error message as an argument + - {string} locale - (Android only) the language to display Apple's Sign-in screen in. + - Defaults to "en" (English) if not specified. + - See [the Apple documentation](https://developer.apple.com/documentation/signinwithapplejs/incorporating_sign_in_with_apple_into_other_platforms###2112) for a list of supported locales. + - The value is ignored on iOS which uses the locale of the device to determine the display language. + +Example usage: + +```javascript + +FirebasePlugin.authenticateUserWithApple(function(credential) { + FirebasePlugin.signInWithCredential(credential, function() { + console.log("Successfully signed in"); + }, function(error) { + console.error("Failed to sign in", error); + }); +}, function(error) { + console.error("Failed to authenticate with Apple: " + error); +}, 'en_GB'); +``` +#### iOS +To use Sign In with Apple in your iOS app you need to do the following: +- Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/ios/apple#before-you-begin) +- After adding the `cordova-ios` platform, open the project workspace in Xcode (`platforms/ios/YourApp.xcworkspace`) and add the "Sign In with Apple" capability in the "Signing & Capabilities section" + - Note: AFAIK there is currently no way to automate the addition of this capability + +#### Android +To use Sign In with Apple in your Android app you need to do the following: +- Configure your app for Sign In with Apple as outlined in the [Firebase documentation's "Before you begin" section](https://firebase.google.com/docs/auth/android/apple#before-you-begin) + +### signInWithCredential +Signs the user into Firebase with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. +See the [Android-](https://firebase.google.com/docs/auth/android/phone-auth#sign-in-the-user) and [iOS](https://firebase.google.com/docs/auth/ios/phone-auth#sign-in-the-user-with-the-verification-code)-specific Firebase documentation for more info. + +**Parameters**: +- {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: + - {string} id - the identifier of a native credential object which can be used for signing in the user. + Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. + - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. + If true, you do not need to provide a user-entered verification. + - Only present if the credential was obtained via `verifyPhoneNumber()` + - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. + - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. + - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. +- {function} success - callback function to call on successful sign-in using credentials +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript +function signInWithCredential(credential){ + FirebasePlugin.signInWithCredential(credential, function() { + console.log("Successfully signed in"); + }, function(error) { + console.error("Failed to sign in", error); + }); +} + +``` + +### linkUserWithCredential +Links an existing Firebase user account with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. +See the [Android-](https://firebase.google.com/docs/auth/android/account-linking) and [iOS](https://firebase.google.com/docs/auth/ios/account-linking)-specific Firebase documentation for more info. + +**Parameters**: +- {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: + - {string} id - the identifier of a native credential object which can be used for signing in the user. + Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. + - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. + If true, you do not need to provide a user-entered verification. + - Only present if the credential was obtained via `verifyPhoneNumber()` + - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. + - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. + - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. +- {function} success - callback function to call on successful linking using credentials +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript +function linkUserWithCredential(credential){ + FirebasePlugin.linkUserWithCredential(credential, function() { + console.log("Successfully linked"); + }, function(error) { + console.error("Failed to link", error); + }); +} + +``` + +### reauthenticateWithCredential +Reauthenticates the currently signed in user with credentials obtained via an authentication method such as `verifyPhoneNumber()` or `authenticateUserWithGoogle()`. + +**Parameters**: +- {object} credential - a credential object returned by the success callback of an authentication method; may have the following keys: + - {string} id - the identifier of a native credential object which can be used for signing in the user. + Present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `true`, or if another authentication method was used such as `authenticateUserWithGoogle()`. + - {boolean} instantVerification - true if an Android device and instant verification or auto-retrieval was used to verify the user. + If true, you do not need to provide a user-entered verification. + - Only present if the credential was obtained via `verifyPhoneNumber()` + - {string} verificationId - the verification ID to accompany the user-entered verification code from the SMS. + - Only present if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`. + - {string} code - if the credential was obtained via `verifyPhoneNumber()` and `instantVerification` is `false`, you must set this to the activation code value as entered by the user from the received SMS message. +- {function} success - callback function to call on success +- {function} error - callback function which will be passed a {string} error message as an argument + +Example usage: + +```javascript + FirebasePlugin.reauthenticateWithCredential(credential, function() { + console.log("Successfully reauthenticated"); + }, function(error) { + console.error("Failed to reauthenticate", error); + }); +``` + +### registerAuthStateChangeListener +Registers a Javascript function to invoke when Firebase Authentication state changes between user signed in/signed out. + +**Parameters**: +- {function} fn - callback function to invoke when authentication state changes + - Will be a passed a single boolean argument which is `true` if user just signed in and `false` if user just signed out. + +Example usage: + +```javascript + FirebasePlugin.registerAuthStateChangeListener(function(userSignedIn){ + console.log("Auth state changed: User signed " + (userSignedIn ? "in" : "out")); + }); +``` + +## Remote Config + +### fetch +Fetch Remote Config parameter values for your app: + +**Parameters**: +- {integer} cacheExpirationSeconds (optional) - cache expiration in seconds +- {function} success - callback function on successfully fetching remote config +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.fetch(function () { + // success callback +}, function () { + // error callback +}); +// or, specify the cacheExpirationSeconds +FirebasePlugin.fetch(600, function () { + // success callback +}, function () { + // error callback +}); +``` + +### activateFetched +Activate the Remote Config fetched config: + +**Parameters**: +- {function} success - callback function which will be passed a {boolean} argument indicating whether fetched config was successfully activated +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.activateFetched(function(activated) { + // activated will be true if there was a fetched config activated, + // or false if no fetched config was found, or the fetched config was already activated. + console.log(activated); +}, function(error) { + console.error(error); +}); +``` + +### getValue +Retrieve a Remote Config value: + +**Parameters**: +- {string} key - key for which to fetch associated value +- {function} success - callback function which will be passed a {any} argument containing the value stored against the specified key. +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.getValue("key", function(value) { + console.log(value); +}, function(error) { + console.error(error); +}); +``` + +### getByteArray +Android only. +Retrieve a Remote Config byte array: + +**Parameters**: +- {string} key - key for which to fetch associated value +- {function} success - callback function which will be passed a {string} argument containing the Base64 encoded string that represents the value stored against the specified key. +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.getByteArray("key", function(bytes) { + // a Base64 encoded string that represents the value for "key" + console.log(bytes.base64); + // a numeric array containing the values of the byte array (i.e. [0xFF, 0x00]) + console.log(bytes.array); +}, function(error) { + console.error(error); +}); +``` + +### getInfo +Get the current state of the FirebaseRemoteConfig singleton object: + +**Parameters**: +- {function} success - callback function which will be passed an {object} argument containing the state info +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.getInfo(function(info) { + // the status of the developer mode setting (true/false) + console.log(info.configSettings.developerModeEnabled); + // (iOS only) for how much (secs) fetch cache is valid and data will not be refetched + console.log(info.configSettings.minimumFetchInterval); + // (iOS only) value in seconds to abandon a pending fetch request made to the backend + console.log(info.configSettings.fetchTimeout); + // the timestamp (milliseconds since epoch) of the last successful fetch + console.log(info.fetchTimeMillis); + // the status of the most recent fetch attempt (int) + // 0 = Config has never been fetched. + // 1 = Config fetch succeeded. + // 2 = Config fetch failed. + // 3 = Config fetch was throttled. + console.log(info.lastFetchStatus); +}, function(error) { + console.error(error); +}); +``` + +### setConfigSettings +Android only. +Change the settings for the FirebaseRemoteConfig object's operations: + +**Parameters**: +- {object} configSettings - object specifying the remote config settings +- {function} success - callback function to be call on successfully setting the remote config settings +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +var settings = { + developerModeEnabled: true +} +FirebasePlugin.setConfigSettings(settings); +``` + +### setDefaults +Android only. +Set defaults in the Remote Config: + +**Parameters**: +- {object} defaultSettings - object specifying the default remote config settings +- {function} success - callback function to be call on successfully setting the remote config setting defaults +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +// define defaults +var defaults = { + // map property name to value in Remote Config defaults + mLong: 1000, + mString: 'hello world', + mDouble: 3.14, + mBoolean: true, + // map "mBase64" to a Remote Config byte array represented by a Base64 string + // Note: the Base64 string is in an array in order to differentiate from a string config value + mBase64: ["SGVsbG8gV29ybGQ="], + // map "mBytes" to a Remote Config byte array represented by a numeric array + mBytes: [0xFF, 0x00] +} +// set defaults +FirebasePlugin.setDefaults(defaults); + +``` + +## Performance + +### setPerformanceCollectionEnabled +Manually enable/disable performance data collection, e.g. if [disabled on app startup](#disable-data-collection-on-startup). + +**Parameters**: +- {boolean} setEnabled - whether to enable or disable performance data collection + +```javascript +FirebasePlugin.setPerformanceCollectionEnabled(true); // Enables performance data collection + +FirebasePlugin.setPerformanceCollectionEnabled(false); // Disables performance data collection +``` + +### isPerformanceCollectionEnabled +Indicates whether performance data collection is enabled. + +Notes: +- This value applies both to the current app session and subsequent app sessions until such time as it is changed. +- It returns the value set by [setPerformanceCollectionEnabled()](#setperformancecollectionenabled). +- If automatic data collection was not [disabled on app startup](#disable-data-collection-on-startup), this will always return `true`. + +**Parameters**: +- {function} success - callback function which will be invoked on success. +Will be passed a {boolean} indicating if the setting is enabled. +- {function} error - (optional) callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.isPerformanceCollectionEnabled(function(enabled){ + console.log("Performance data collection is "+(enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("Error getting Performance data collection setting: "+error); +}); +``` + +### startTrace + +Start a trace. + +**Parameters**: +- {string} name - name of trace to start +- {function} success - callback function to call on successfully starting trace +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.startTrace("test trace", success, error); +``` + +### incrementCounter + +To count the performance-related events that occur in your app (such as cache hits or retries), add a line of code similar to the following whenever the event occurs, using a string other than retry to name that event if you are counting a different type of event: + +**Parameters**: +- {string} name - name of trace +- {string} counterName - name of counter to increment +- {function} success - callback function to call on successfully incrementing counter +- {function} error - callback function which will be passed a {string} error message as an argument + + +```javascript +FirebasePlugin.incrementCounter("test trace", "retry", success, error); +``` + +### stopTrace + +Stop the trace + +**Parameters**: +- {string} name - name of trace to stop +- {function} success - callback function to call on successfully stopping trace +- {function} error - callback function which will be passed a {string} error message as an argument + +```javascript +FirebasePlugin.stopTrace("test trace"); +``` + +## Firestore +These plugin API functions provide CRUD operations for working with documents in Firestore collections. + +Notes: +- Only top-level Firestore collections are currently supported - [subcollections](https://firebase.google.com/docs/firestore/manage-data/structure-data#subcollections) (nested collections within documents) are currently not supported due to the complexity of mapping the native objects into the plugin's JS API layer. +- A document object may contain values of primitive Javascript types `string`, `number`, `boolean`, `array` or `object`. +Arrays and objects may contain nested structures of these types. +- If a collection name referenced in a document write operation does not already exist, it will be created by the first write operation referencing it. + +### addDocumentToFirestoreCollection +Adds a new document to a Firestore collection, which will be allocated an auto-generated document ID. + +**Parameters**: +- {object} document - document object to add to collection +- {string} collection - name of top-level collection to add document to. +- {function} success - callback function to call on successfully adding the document. +Will be passed a {string} argument containing the auto-generated document ID that the document was stored against. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var document = { + "a_string": "foo", + "a_list": [1, 2, 3], + "an_object": { + "an_integer": 1, + } +}; +var collection = "my_collection"; +FirebasePlugin.addDocumentToFirestoreCollection(document, collection, function(documentId){ + console.log("Successfully added document with id="+documentId); +}, function(error){ + console.error("Error adding document: "+error); +}); +``` + +### setDocumentInFirestoreCollection +Sets (adds/replaces) a document with the given ID in a Firestore collection. + +**Parameters**: +- {string} documentId - document ID to use when setting document in the collection. +- {object} document - document object to set in collection. +- {string} collection - name of top-level collection to set document in. +- {function} success - callback function to call on successfully setting the document. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var documentId = "my_doc"; +var document = { + "a_string": "foo", + "a_list": [1, 2, 3], + "an_object": { + "an_integer": 1, + } +}; +var collection = "my_collection"; +FirebasePlugin.setDocumentInFirestoreCollection(documentId, document, collection, function(){ + console.log("Successfully set document with id="+documentId); +}, function(error){ + console.error("Error setting document: "+error); +}); +``` + +### updateDocumentInFirestoreCollection +Updates an existing document with the given ID in a Firestore collection. +This is a non-destructive update that will only overwrite existing keys in the existing document or add new ones if they don't already exist. +If the no document with the specified ID exists in the collection, an error will be raised. + +**Parameters**: +- {string} documentId - document ID of the document to update. +- {object} document - entire document or document fragment to update existing document with. +- {string} collection - name of top-level collection to update document in. +- {function} success - callback function to call on successfully updating the document. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var documentId = "my_doc"; +var documentFragment = { + "a_string": "new value", + "a_new_string": "bar" +}; +var collection = "my_collection"; +FirebasePlugin.updateDocumentInFirestoreCollection(documentId, documentFragment, collection, function(){ + console.log("Successfully updated document with id="+documentId); +}, function(error){ + console.error("Error updating document: "+error); +}); +``` + +### deleteDocumentFromFirestoreCollection +Deletes an existing document with the given ID in a Firestore collection. + +Note: If the no document with the specified ID exists in the collection, the Firebase SDK will still return a successful outcome. + +**Parameters**: +- {string} documentId - document ID of the document to delete. +- {string} collection - name of top-level collection to delete document in. +- {function} success - callback function to call on successfully deleting the document. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var documentId = "my_doc"; +var collection = "my_collection"; +FirebasePlugin.deleteDocumentFromFirestoreCollection(documentId, collection, function(){ + console.log("Successfully deleted document with id="+documentId); +}, function(error){ + console.error("Error deleting document: "+error); +}); +``` + +### documentExistsInFirestoreCollection +Indicates if a document with the given ID exists in a Firestore collection. + +**Parameters**: +- {string} documentId - document ID of the document. +- {string} collection - name of top-level collection to check for document. +- {function} success - callback function to call pass result. +Will be passed an {boolean} which is `true` if a document exists. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var documentId = "my_doc"; +var collection = "my_collection"; +FirebasePlugin.documentExistsInFirestoreCollection(documentId, collection, function(exists){ + console.log("Document " + (exists ? "exists" : "doesn't exist")); +}, function(error){ + console.error("Error fetching document: "+error); +}); +``` + +### fetchDocumentInFirestoreCollection +Fetches an existing document with the given ID from a Firestore collection. + +Note: If the no document with the specified ID exists in the collection, the error callback will be invoked. + +**Parameters**: +- {string} documentId - document ID of the document to fetch. +- {string} collection - name of top-level collection to fetch document from. +- {function} success - callback function to call on successfully fetching the document. +Will be passed an {object} contain the document contents. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var documentId = "my_doc"; +var collection = "my_collection"; +FirebasePlugin.fetchDocumentInFirestoreCollection(documentId, collection, function(document){ + console.log("Successfully fetched document: "+JSON.stringify(document)); +}, function(error){ + console.error("Error fetching document: "+error); +}); +``` + +### fetchFirestoreCollection +Fetches all the documents in the specific collection. + +**Parameters**: +- {string} collection - name of top-level collection to fetch. +- {array} filters - a list of filters to sort/filter the documents returned from your collection. + - Supports `where`, `orderBy`, `startAt`, `endAt` and `limit` filters. + - See the [Firestore documentation](https://firebase.google.com/docs/firestore/query-data/queries) for more details. +- {function} success - callback function to call on successfully deleting the document. +Will be passed an {object} containing all the documents in the collection, indexed by document ID. +If a Firebase collection with that name does not exist or it contains no documents, the object will be empty. +- {function} error - callback function which will be passed a {string} error message as an argument. + +```javascript +var collection = "my_collection"; +var filters = [ + ['where', 'field', '==', 'value'], + ['orderBy', 'field', 'desc'] +]; +FirebasePlugin.fetchFirestoreCollection(collection, filters, function(documents){ + console.log("Successfully fetched collection: "+JSON.stringify(documents)); +}, function(error){ + console.error("Error fetching collection: "+error); +}); +``` + +# Credits +- [@robertarnesson](https://github.com/robertarnesson) for the original [cordova-plugin-firebase](https://github.com/arnesson/cordova-plugin-firebase) from which this plugin is forked. +- [@sagrawal31](https://github.com/sagrawal31) and [Wiz Panda](https://github.com/wizpanda) for contributions via [cordova-plugin-firebase-lib](https://github.com/wizpanda/cordova-plugin-firebase-lib). +- [Full list of contributors](https://github.com/dpa99c/cordova-plugin-firebasex/graphs/contributors) diff --git a/plugin.xml b/plugin.xml index caba8cafa..e6697510a 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1 +1,144 @@ - Google Firebase Plugin MIT development production remote-notification \ No newline at end of file + + + Google Firebase Plugin + + MIT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + development + + + production + + + + remote-notification + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/ios/helper.js b/scripts/ios/helper.js index 1159adf47..4b539774d 100644 --- a/scripts/ios/helper.js +++ b/scripts/ios/helper.js @@ -1 +1,238 @@ -var fs = require("fs"); var path = require("path"); var utilities = require("../lib/utilities"); var xcode = require("xcode"); var plist = require('plist'); /** * This is used as the display text for the build phase block in XCode as well as the * inline comments inside of the .pbxproj file for the build script phase block. */ var comment = "\"Crashlytics\""; module.exports = { /** * Used to get the path to the XCode project's .pbxproj file. */ getXcodeProjectPath: function () { var appName = utilities.getAppName(); return path.join("platforms", "ios", appName + ".xcodeproj", "project.pbxproj"); }, /** * This helper is used to add a build phase to the XCode project which runs a shell * script during the build process. The script executes Crashlytics run command line * tool with the API and Secret keys. This tool is used to upload the debug symbols * (dSYMs) so that Crashlytics can display stack trace information in it's web console. */ addShellScriptBuildPhase: function (context, xcodeProjectPath) { // Read and parse the XCode project (.pxbproj) from disk. // File format information: http://www.monobjc.net/xcode-project-file-format.html var xcodeProject = xcode.project(xcodeProjectPath); xcodeProject.parseSync(); // Build the body of the script to be executed during the build phase. var script = '"' + '\\"${PODS_ROOT}/FirebaseCrashlytics/run\\"' + '"'; // Generate a unique ID for our new build phase. var id = xcodeProject.generateUuid(); // Create the build phase. xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[id] = { isa: "PBXShellScriptBuildPhase", buildActionMask: 2147483647, files: [], inputPaths: ['"' + '$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)' + '"'], name: comment, outputPaths: [], runOnlyForDeploymentPostprocessing: 0, shellPath: "/bin/sh", shellScript: script, showEnvVarsInLog: 0 }; // Add a comment to the block (viewable in the source of the pbxproj file). xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[id + "_comment"] = comment; // Add this new shell script build phase block to the targets. for (var nativeTargetId in xcodeProject.hash.project.objects.PBXNativeTarget) { // Skip over the comment blocks. if (nativeTargetId.indexOf("_comment") !== -1) { continue; } var nativeTarget = xcodeProject.hash.project.objects.PBXNativeTarget[nativeTargetId]; nativeTarget.buildPhases.push({ value: id, comment: comment }); } // Finally, write the .pbxproj back out to disk. fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); }, /** * This helper is used to remove the build phase from the XCode project that was added * by the addShellScriptBuildPhase() helper method. */ removeShellScriptBuildPhase: function (context, xcodeProjectPath) { // Read and parse the XCode project (.pxbproj) from disk. // File format information: http://www.monobjc.net/xcode-project-file-format.html var xcodeProject = xcode.project(xcodeProjectPath); xcodeProject.parseSync(); // First, we want to delete the build phase block itself. var buildPhases = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase; var commentTest = comment.replace(/"/g, ''); for (var buildPhaseId in buildPhases) { var buildPhase = xcodeProject.hash.project.objects.PBXShellScriptBuildPhase[buildPhaseId]; var shouldDelete = false; if (buildPhaseId.indexOf("_comment") === -1) { // Dealing with a build phase block. // If the name of this block matches ours, then we want to delete it. shouldDelete = buildPhase.name && buildPhase.name.indexOf(commentTest) !== -1; } else { // Dealing with a comment block. // If this is a comment block that matches ours, then we want to delete it. shouldDelete = buildPhase === commentTest; } if (shouldDelete) { delete buildPhases[buildPhaseId]; } } // Second, we want to delete the native target reference to the block. var nativeTargets = xcodeProject.hash.project.objects.PBXNativeTarget; for (var nativeTargetId in nativeTargets) { // Skip over the comment blocks. if (nativeTargetId.indexOf("_comment") !== -1) { continue; } var nativeTarget = nativeTargets[nativeTargetId]; // We remove the reference to the block by filtering out the the ones that match. nativeTarget.buildPhases = nativeTarget.buildPhases.filter(function (buildPhase) { return buildPhase.comment !== commentTest; }); } // Finally, write the .pbxproj back out to disk. fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); }, ensureRunpathSearchPath: function(context, xcodeProjectPath){ function addRunpathSearchBuildProperty(proj, build) { let LD_RUNPATH_SEARCH_PATHS = proj.getBuildProperty("LD_RUNPATH_SEARCH_PATHS", build); if (!Array.isArray(LD_RUNPATH_SEARCH_PATHS)) { LD_RUNPATH_SEARCH_PATHS = [LD_RUNPATH_SEARCH_PATHS]; } LD_RUNPATH_SEARCH_PATHS.forEach(LD_RUNPATH_SEARCH_PATH => { if (!LD_RUNPATH_SEARCH_PATH) { proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build); } if (LD_RUNPATH_SEARCH_PATH.indexOf("@executable_path/Frameworks") == -1) { var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); newValue += ' @executable_path/Frameworks\"'; proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); } if (LD_RUNPATH_SEARCH_PATH.indexOf("$(inherited)") == -1) { var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); newValue += ' $(inherited)\"'; proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); } }); } // Read and parse the XCode project (.pxbproj) from disk. // File format information: http://www.monobjc.net/xcode-project-file-format.html var xcodeProject = xcode.project(xcodeProjectPath); xcodeProject.parseSync(); // Add search paths build property addRunpathSearchBuildProperty(xcodeProject, "Debug"); addRunpathSearchBuildProperty(xcodeProject, "Release"); // Finally, write the .pbxproj back out to disk. fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); }, stripDebugSymbols: function(){ var podFilePath = 'platforms/ios/Podfile', podFile = fs.readFileSync(path.resolve(podFilePath)).toString(); if(!podFile.match('DEBUG_INFORMATION_FORMAT')){ podFile += "\npost_install do |installer|\n" + " installer.pods_project.targets.each do |target|\n" + " target.build_configurations.each do |config|\n" + " config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'\n" + " end\n" + " end\n" + "end"; fs.writeFileSync(path.resolve(podFilePath), podFile); console.log('cordova-plugin-firebasex: Applied IOS_STRIP_DEBUG to Podfile'); } }, applyPluginVarsToPlists: function(googlePlistPath, appPlistPath, pluginVariables){ var googlePlist = plist.parse(fs.readFileSync(path.resolve(googlePlistPath), 'utf8')), appPlist = plist.parse(fs.readFileSync(path.resolve(appPlistPath), 'utf8')), googlePlistModified = false, appPlistModified = false; if(typeof pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== 'undefined'){ googlePlist["FIREBASE_ANALYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } if(typeof pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== 'undefined'){ googlePlist["FIREBASE_PERFORMANCE_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } if(typeof pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== 'undefined'){ googlePlist["FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; googlePlistModified = true; } if(typeof pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] !== 'undefined'){ appPlist["shouldEstablishDirectChannel"] = (pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] === "true") ; appPlistModified = true; } if(pluginVariables['SETUP_RECAPTCHA_VERIFICATION'] === 'true'){ var reversedClientId = googlePlist['REVERSED_CLIENT_ID']; if(!appPlist['CFBundleURLTypes']) appPlist['CFBundleURLTypes'] = []; var entry, i; for(i=0; i { + if (!LD_RUNPATH_SEARCH_PATH) { + proj.addBuildProperty("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks\"", build); + } + if (LD_RUNPATH_SEARCH_PATH.indexOf("@executable_path/Frameworks") == -1) { + var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); + newValue += ' @executable_path/Frameworks\"'; + proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); + } + if (LD_RUNPATH_SEARCH_PATH.indexOf("$(inherited)") == -1) { + var newValue = LD_RUNPATH_SEARCH_PATH.substr(0, LD_RUNPATH_SEARCH_PATH.length - 1); + newValue += ' $(inherited)\"'; + proj.updateBuildProperty("LD_RUNPATH_SEARCH_PATHS", newValue, build); + } + }); + } + + // Read and parse the XCode project (.pxbproj) from disk. + // File format information: http://www.monobjc.net/xcode-project-file-format.html + var xcodeProject = xcode.project(xcodeProjectPath); + xcodeProject.parseSync(); + + // Add search paths build property + addRunpathSearchBuildProperty(xcodeProject, "Debug"); + addRunpathSearchBuildProperty(xcodeProject, "Release"); + + // Finally, write the .pbxproj back out to disk. + fs.writeFileSync(path.resolve(xcodeProjectPath), xcodeProject.writeSync()); + }, + stripDebugSymbols: function(){ + var podFilePath = 'platforms/ios/Podfile', + podFile = fs.readFileSync(path.resolve(podFilePath)).toString(); + if(!podFile.match('DEBUG_INFORMATION_FORMAT')){ + podFile += "\npost_install do |installer|\n" + + " installer.pods_project.targets.each do |target|\n" + + " target.build_configurations.each do |config|\n" + + " config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf'\n" + + " end\n" + + " end\n" + + "end"; + fs.writeFileSync(path.resolve(podFilePath), podFile); + console.log('cordova-plugin-firebasex: Applied IOS_STRIP_DEBUG to Podfile'); + } + }, + applyPluginVarsToPlists: function(googlePlistPath, appPlistPath, pluginVariables){ + var googlePlist = plist.parse(fs.readFileSync(path.resolve(googlePlistPath), 'utf8')), + appPlist = plist.parse(fs.readFileSync(path.resolve(appPlistPath), 'utf8')), + googlePlistModified = false, + appPlistModified = false; + + if(typeof pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== 'undefined'){ + googlePlist["FIREBASE_ANALYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_ANALYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; + googlePlistModified = true; + } + if(typeof pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== 'undefined'){ + googlePlist["FIREBASE_PERFORMANCE_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_PERFORMANCE_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; + googlePlistModified = true; + } + if(typeof pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== 'undefined'){ + googlePlist["FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"] = (pluginVariables['FIREBASE_CRASHLYTICS_COLLECTION_ENABLED'] !== "false" ? "true" : "false") ; + googlePlistModified = true; + } + if(typeof pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] !== 'undefined'){ + appPlist["shouldEstablishDirectChannel"] = (pluginVariables['IOS_SHOULD_ESTABLISH_DIRECT_CHANNEL'] === "true") ; + appPlistModified = true; + } + if(pluginVariables['SETUP_RECAPTCHA_VERIFICATION'] === 'true'){ + var reversedClientId = googlePlist['REVERSED_CLIENT_ID']; + + if(!appPlist['CFBundleURLTypes']) appPlist['CFBundleURLTypes'] = []; + var entry, i; + for(i=0; i notificationStack = null; private static CallbackContext notificationCallbackContext; private static CallbackContext tokenRefreshCallbackContext; private static CallbackContext activityResultCallbackContext; private static CallbackContext authResultCallbackContext; private static NotificationChannel defaultNotificationChannel = null; public static String defaultChannelId = null; public static String defaultChannelName = null; private Map authCredentials = new HashMap(); private Map authProviders = new HashMap(); @Override protected void pluginInitialize() { instance = this; cordovaActivity = this.cordova.getActivity(); applicationContext = cordovaActivity.getApplicationContext(); final Bundle extras = cordovaActivity.getIntent().getExtras(); FirebasePlugin.cordovaInterface = this.cordova; firebaseCrashlytics = FirebaseCrashlytics.getInstance(); this.cordova.getThreadPool().execute(new Runnable() { public void run() { try { Log.d(TAG, "Starting Firebase plugin"); if(!getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ isCrashlyticsEnabled = getPreference(CRASHLYTICS_COLLECTION_ENABLED); if(isCrashlyticsEnabled){ firebaseCrashlytics.setCrashlyticsCollectionEnabled(true); } }else{ isCrashlyticsEnabled = true; 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); } FirebaseApp.initializeApp(applicationContext); mFirebaseAnalytics = FirebaseAnalytics.getInstance(applicationContext); authStateListener = new AuthStateListener(); FirebaseAuth.getInstance().addAuthStateListener(authStateListener); firestore = FirebaseFirestore.getInstance(); gson = new Gson(); if (extras != null && extras.size() > 1) { if (FirebasePlugin.notificationStack == null) { FirebasePlugin.notificationStack = new ArrayList(); } 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{ 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("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("isAutoInitEnabled")) { isAutoInitEnabled(callbackContext); return true; } else if (action.equals("setAutoInitEnabled")) { setAutoInitEnabled(callbackContext, args.getBoolean(0)); return true; } else if (action.equals("unregister")) { this.unregister(callbackContext); return true; } else if (action.equals("onMessageReceived")) { this.onMessageReceived(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); 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")) { this.getByteArray(callbackContext, args.getString(0)); return true; } else if (action.equals("getValue")) { this.getValue(callbackContext, args.getString(0)); 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")) { this.setDefaults(callbackContext, args.getJSONObject(0)); return true; } else if (action.equals("verifyPhoneNumber")) { this.verifyPhoneNumber(callbackContext, args); return true; } else if (action.equals("authenticateUserWithGoogle")) { this.authenticateUserWithGoogle(callbackContext, args); return true; } else if (action.equals("authenticateUserWithApple")) { this.authenticateUserWithApple(callbackContext, args); return true; } else if (action.equals("createUserWithEmailAndPassword")) { this.createUserWithEmailAndPassword(callbackContext, args); return true; } else if (action.equals("signInUserWithEmailAndPassword")) { this.signInUserWithEmailAndPassword(callbackContext, args); return true; } else if (action.equals("signInUserWithCustomToken")) { this.signInUserWithCustomToken(callbackContext, args); return true; } else if (action.equals("signInUserAnonymously")) { this.signInUserAnonymously(callbackContext); return true; } else if (action.equals("signInWithCredential")) { this.signInWithCredential(callbackContext, args); return true; } else if (action.equals("linkUserWithCredential")) { this.linkUserWithCredential(callbackContext, args); return true; } else if (action.equals("reauthenticateWithCredential")) { this.reauthenticateWithCredential(callbackContext, args); return true; } else if (action.equals("isUserSignedIn")) { this.isUserSignedIn(callbackContext, args); return true; } else if (action.equals("signOutUser")) { this.signOutUser(callbackContext, args); return true; } else if (action.equals("getCurrentUser")) { this.getCurrentUser(callbackContext, args); return true; } else if (action.equals("reloadCurrentUser")) { this.reloadCurrentUser(callbackContext, args); return true; } else if (action.equals("updateUserProfile")) { this.updateUserProfile(callbackContext, args); return true; } else if (action.equals("updateUserEmail")) { this.updateUserEmail(callbackContext, args); return true; } else if (action.equals("sendUserEmailVerification")) { this.sendUserEmailVerification(callbackContext, args); return true; } else if (action.equals("updateUserPassword")) { this.updateUserPassword(callbackContext, args); return true; } else if (action.equals("sendUserPasswordResetEmail")) { this.sendUserPasswordResetEmail(callbackContext, args); return true; } else if (action.equals("deleteUser")) { this.deleteUser(callbackContext, args); 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("isAnalyticsCollectionEnabled")) { this.isAnalyticsCollectionEnabled(callbackContext); return true; } else if (action.equals("setPerformanceCollectionEnabled")) { this.setPerformanceCollectionEnabled(callbackContext, args.getBoolean(0)); return true; } else if (action.equals("isPerformanceCollectionEnabled")) { this.isPerformanceCollectionEnabled(callbackContext); return true; } else if (action.equals("setCrashlyticsCollectionEnabled")) { this.setCrashlyticsCollectionEnabled(callbackContext, args.getBoolean(0)); return true; } else if (action.equals("isCrashlyticsCollectionEnabled")) { this.isCrashlyticsCollectionEnabled(callbackContext); return true; } else if (action.equals("isCrashlyticsCollectionCurrentlyEnabled")) { this.isCrashlyticsCollectionCurrentlyEnabled(callbackContext); return true; } else if (action.equals("clearAllNotifications")) { this.clearAllNotifications(callbackContext); return true; } else if (action.equals("logMessage")) { logMessage(args, callbackContext); return true; } else if (action.equals("sendCrash")) { sendCrash(args, callbackContext); return true; } else if (action.equals("createChannel")) { this.createChannel(callbackContext, args.getJSONObject(0)); return true; } else if (action.equals("deleteChannel")) { this.deleteChannel(callbackContext, args.getString(0)); return true; } else if (action.equals("listChannels")) { this.listChannels(callbackContext); return true; } else if (action.equals("setDefaultChannel")) { this.setDefaultChannel(callbackContext, args.getJSONObject(0)); return true; } else if (action.equals("addDocumentToFirestoreCollection")) { this.addDocumentToFirestoreCollection(args, callbackContext); return true; } else if (action.equals("setDocumentInFirestoreCollection")) { this.setDocumentInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("updateDocumentInFirestoreCollection")) { this.updateDocumentInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("deleteDocumentFromFirestoreCollection")) { this.deleteDocumentFromFirestoreCollection(args, callbackContext); return true; } else if (action.equals("documentExistsInFirestoreCollection")) { this.documentExistsInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("fetchDocumentInFirestoreCollection")) { this.fetchDocumentInFirestoreCollection(args, callbackContext); return true; } else if (action.equals("fetchFirestoreCollection")) { this.fetchFirestoreCollection(args, callbackContext); return true; } else if (action.equals("grantPermission") || action.equals("setBadgeNumber") || action.equals("getBadgeNumber") ) { // Stubs for other platform methods callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true)); return true; }else{ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Invalid action: " + action)); return false; } }catch(Exception e){ handleExceptionWithContext(e, callbackContext); } 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; 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 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); JSONObject returnResults = new JSONObject(); returnResults.put("instantVerification", true); returnResults.put("id", id); FirebasePlugin.activityResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 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 { String currentToken = FirebaseInstanceId.getInstance().getToken(); if (currentToken != null) { FirebasePlugin.sendToken(currentToken); } } 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(); } 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 keys = bundle.keySet(); for (String key : keys) { try { json.put(key, bundle.get(key)); } catch (JSONException e) { handleExceptionWithContext(e, callbackContext); 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) { 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 getId(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String id = FirebaseInstanceId.getInstance().getId(); callbackContext.success(id); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } private void hasPermission(final CallbackContext callbackContext) { if(cordovaActivity == null) return; cordova.getThreadPool().execute(new Runnable() { public void run() { try { NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(cordovaActivity); boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); callbackContext.success(areNotificationsEnabled ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } private void unregister(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseInstanceId.getInstance().deleteInstanceId(); callbackContext.success(); } 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(isEnabled ? 1 : 0); } 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 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) { 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 - firebaseCrashlytics collection is disabled"); } } catch (Exception e) { logExceptionToCrashlytics(e); callbackContext.error(e.getMessage()); } } }); } private void logMessage(final JSONArray data, final CallbackContext callbackContext) { if(isCrashlyticsEnabled){ String message = data.optString(0); logMessageToCrashlytics(message); callbackContext.success(); }else{ callbackContext.error("Cannot log message - firebaseCrashlytics collection is disabled"); } } private void sendCrash(final JSONArray data, final CallbackContext callbackContext) { cordovaActivity.runOnUiThread(new Runnable() { @Override public void run() { throw new RuntimeException("This is a crash"); } }); } private void setCrashlyticsUserId(final CallbackContext callbackContext, final String userId) { cordovaActivity.runOnUiThread(new Runnable() { public void run() { try { if(isCrashlyticsEnabled){ firebaseCrashlytics.setUserId(userId); callbackContext.success(); }else{ callbackContext.error("Cannot set firebaseCrashlytics user ID - firebaseCrashlytics collection is disabled"); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void setScreenName(final CallbackContext callbackContext, final String name) { // This must be called on the main thread cordovaActivity.runOnUiThread(new Runnable() { public void run() { try { mFirebaseAnalytics.setCurrentScreen(cordovaActivity, name, null); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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 task) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { task.addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void data) { callbackContext.success(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void getByteArray(final CallbackContext callbackContext, final String key) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { byte[] bytes = FirebaseRemoteConfig.getInstance().getByteArray(key); JSONObject object = new JSONObject(); object.put("base64", Base64.encodeToString(bytes, Base64.DEFAULT)); object.put("array", new JSONArray(bytes)); callbackContext.success(object); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void getValue(final CallbackContext callbackContext, final String key) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseRemoteConfigValue value = FirebaseRemoteConfig.getInstance().getValue(key); callbackContext.success(value.asString()); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } 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) { handleExceptionWithContext(e, callbackContext); } } }); } private void setDefaults(final CallbackContext callbackContext, final JSONObject defaults) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults)); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private static Map defaultsToMap(JSONObject object) throws JSONException { final Map map = new HashMap(); for (Iterator 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; } public void isUserSignedIn(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { boolean isSignedIn = FirebaseAuth.getInstance().getCurrentUser() != null; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, isSignedIn)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signOutUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } // Sign out of Firebase FirebaseAuth.getInstance().signOut(); // Try to sign out of Google try{ GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build(); GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(cordovaActivity, gso); mGoogleSignInClient.signOut() .addOnCompleteListener(cordovaActivity, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } }); }catch(Exception googleSignOutException){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void getCurrentUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } extractAndReturnUserInfo(callbackContext); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void reloadCurrentUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } user.reload() .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { try { extractAndReturnUserInfo(callbackContext); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void extractAndReturnUserInfo(final CallbackContext callbackContext) throws Exception{ FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); JSONObject returnResults = new JSONObject(); returnResults.put("name", user.getDisplayName()); returnResults.put("email", user.getEmail()); returnResults.put("emailIsVerified", user.isEmailVerified()); returnResults.put("phoneNumber", user.getPhoneNumber()); returnResults.put("photoUrl", user.getPhotoUrl() == null ? null : user.getPhotoUrl().toString()); returnResults.put("uid", user.getUid()); returnResults.put("providerId", user.getIdToken(false).getResult().getSignInProvider()); returnResults.put("isAnonymous", user.isAnonymous()); user.getIdToken(true).addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(GetTokenResult result) { try { String idToken = result.getToken(); returnResults.put("idToken", idToken); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void updateUserProfile(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } JSONObject profile = args.getJSONObject(0); UserProfileChangeRequest profileUpdates; if(profile.has("name") && profile.has("photoUri")){ profileUpdates = new UserProfileChangeRequest.Builder() .setDisplayName(profile.getString("name")) .setPhotoUri(Uri.parse(profile.getString("photoUri"))) .build(); }else if(profile.has("name")){ profileUpdates = new UserProfileChangeRequest.Builder() .setDisplayName(profile.getString("name")) .build(); }else if(profile.has("photoUri")){ profileUpdates = new UserProfileChangeRequest.Builder() .setPhotoUri(Uri.parse(profile.getString("photoUri"))) .build(); }else{ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "'name' and/or 'photoUri' keys must be specified in the profile object")); return; } user.updateProfile(profileUpdates) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void updateUserEmail(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } String email = args.getString(0); user.updateEmail(email) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void sendUserEmailVerification(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void updateUserPassword(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } String password = args.getString(0); user.updatePassword(password) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void sendUserPasswordResetEmail(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseAuth auth = FirebaseAuth.getInstance(); String email = args.getString(0); auth.sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void deleteUser(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } user.delete() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void reauthenticateWithCredential(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if(user == null){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); return; } JSONObject jsonCredential = args.getJSONObject(0); if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); return; } AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); if(authCredential != null){ user.reauthenticate(authCredential) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); } }); return; } OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); if(authProvider != null){ FirebasePlugin.instance.authResultCallbackContext = callbackContext; user.startActivityForReauthenticateWithProvider(FirebasePlugin.cordovaActivity, authProvider) .addOnSuccessListener(new AuthResultOnSuccessListener()) .addOnFailureListener(new AuthResultOnFailureListener()); return; } //ELSE callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInWithCredential(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject jsonCredential = args.getJSONObject(0); if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); return; } AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); if(authCredential != null){ FirebaseAuth.getInstance().signInWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); return; } OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); if(authProvider != null){ FirebasePlugin.instance.authResultCallbackContext = callbackContext; FirebaseAuth.getInstance().startActivityForSignInWithProvider(FirebasePlugin.cordovaActivity, authProvider) .addOnSuccessListener(new AuthResultOnSuccessListener()) .addOnFailureListener(new AuthResultOnFailureListener()); return; } //ELSE callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void linkUserWithCredential(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject jsonCredential = args.getJSONObject(0); if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); return; } AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); if(authCredential != null){ FirebaseAuth.getInstance().getCurrentUser().linkWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); return; } //ELSE callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private boolean isValidJsonCredential(JSONObject jsonCredential) throws JSONException{ return jsonCredential.has("id") || (jsonCredential.has("verificationId") && jsonCredential.has("code")); } private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks; public void verifyPhoneNumber( final CallbackContext callbackContext, final JSONArray args ) { 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"); String id = FirebasePlugin.instance.saveAuthCredential((AuthCredential) credential); JSONObject returnResults = new JSONObject(); try { returnResults.put("instantVerification", true); returnResults.put("id", id); } catch(JSONException e){ handleExceptionWithContext(e, callbackContext); 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; 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"; }else{ errorMsg = e.getMessage(); } 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) { handleExceptionWithContext(e, callbackContext); return; } PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, returnResults); pluginresult.setKeepCallback(true); callbackContext.sendPluginResult(pluginresult); } }; String number = args.getString(0); int timeOutDuration = args.getInt(1); String smsCode = args.getString(2); if(smsCode != null && smsCode != "null"){ FirebaseAuth.getInstance().getFirebaseAuthSettings().setAutoRetrievedSmsCodeForPhoneNumber(number, smsCode); } PhoneAuthProvider.getInstance().verifyPhoneNumber(number, // Phone number to verify timeOutDuration, // Timeout duration TimeUnit.SECONDS, // Unit of timeout cordovaActivity, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void createUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String email = args.getString(0); String password = args.getString(1); if(email == null || email.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); return; } if(password == null || password.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); return; } FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String email = args.getString(0); String password = args.getString(1); if(email == null || email.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); return; } if(password == null || password.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); return; } FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void authenticateUserWithGoogle(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String clientId = args.getString(0); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(clientId) .requestEmail() .build(); GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(FirebasePlugin.instance.cordovaActivity, gso); Intent signInIntent = mGoogleSignInClient.getSignInIntent(); FirebasePlugin.activityResultCallbackContext = callbackContext; FirebasePlugin.instance.cordovaInterface.startActivityForResult(FirebasePlugin.instance, signInIntent, GOOGLE_SIGN_IN); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void authenticateUserWithApple(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String locale = args.getString(0); OAuthProvider.Builder provider = OAuthProvider.newBuilder("apple.com"); if(locale != null){ provider.addCustomParameter("locale", locale); } Task pending = FirebaseAuth.getInstance().getPendingAuthResult(); if (pending != null) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Auth result is already pending")); pending .addOnSuccessListener(new AuthResultOnSuccessListener()) .addOnFailureListener(new AuthResultOnFailureListener()); } else { String id = FirebasePlugin.instance.saveAuthProvider(provider.build());; JSONObject returnResults = new JSONObject(); returnResults.put("instantVerification", true); returnResults.put("id", id); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInUserWithCustomToken(final CallbackContext callbackContext, final JSONArray args){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { String customToken = args.getString(0); if(customToken == null || customToken.equals("")){ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Custom token must be specified")); return; } FirebaseAuth.getInstance().signInWithCustomToken(customToken).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void signInUserAnonymously(final CallbackContext callbackContext){ cordova.getThreadPool().execute(new Runnable() { public void run() { try { FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } // // Firebase Performace // private HashMap traces = new HashMap(); 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) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } 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.incrementMetric(counterNamed, 1); callbackContext.success(); } else { callbackContext.error("Trace not found"); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } 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) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void setAnalyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { if(getMetaDataFromManifest(ANALYTICS_COLLECTION_ENABLED)){ callbackContext.error("Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); }else if(enabled && getPreference(ANALYTICS_COLLECTION_ENABLED)){ callbackContext.error("Analytics data collection is already set to enabled"); }else if(!enabled && !getPreference(ANALYTICS_COLLECTION_ENABLED)){ callbackContext.error("Analytics data collection is already set to disabled"); }else{ mFirebaseAnalytics.setAnalyticsCollectionEnabled(enabled); setPreference(ANALYTICS_COLLECTION_ENABLED, enabled); callbackContext.success(); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isAnalyticsCollectionEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(getPreference(ANALYTICS_COLLECTION_ENABLED) ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void setPerformanceCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { if(getMetaDataFromManifest(PERFORMANCE_COLLECTION_ENABLED)){ callbackContext.error("Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); }else if(enabled && getPreference(PERFORMANCE_COLLECTION_ENABLED)){ callbackContext.error("Performance data collection is already set to enabled"); }else if(!enabled && !getPreference(PERFORMANCE_COLLECTION_ENABLED)){ callbackContext.error("Performance data collection is already set to disabled"); }else{ FirebasePerformance.getInstance().setPerformanceCollectionEnabled(enabled); setPreference(PERFORMANCE_COLLECTION_ENABLED, enabled); callbackContext.success(); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isPerformanceCollectionEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(getPreference(PERFORMANCE_COLLECTION_ENABLED) ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void setCrashlyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { if(getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ callbackContext.error("Cannot set firebaseCrashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); }else if(enabled && getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ callbackContext.error("firebaseCrashlytics data collection is already set to enabled"); }else if(!enabled && !getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ callbackContext.error("firebaseCrashlytics data collection is already set to disabled"); }else{ setPreference(CRASHLYTICS_COLLECTION_ENABLED, enabled); callbackContext.success(); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isCrashlyticsCollectionEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(getPreference(CRASHLYTICS_COLLECTION_ENABLED) ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } private void isCrashlyticsCollectionCurrentlyEnabled(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { callbackContext.success(isCrashlyticsEnabled ? 1 : 0); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); e.printStackTrace(); } } }); } public void clearAllNotifications(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); nm.cancelAll(); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void createChannel(final CallbackContext callbackContext, final JSONObject options) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { createChannel(options); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } protected static NotificationChannel createChannel(final JSONObject options) throws JSONException { NotificationChannel channel = null; // only call on Android O and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String id = options.getString("id"); Log.i(TAG, "Creating channel id="+id); if(channelExists(id)){ deleteChannel(id); } NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); String packageName = cordovaActivity.getPackageName(); String name = options.optString("name", ""); Log.d(TAG, "Channel "+id+" - name="+name); int importance = options.optInt("importance", NotificationManager.IMPORTANCE_HIGH); Log.d(TAG, "Channel "+id+" - importance="+importance); channel = new NotificationChannel(id, name, importance); // Description String description = options.optString("description", ""); Log.d(TAG, "Channel "+id+" - description="+description); channel.setDescription(description); // Light boolean light = options.optBoolean("light", true); Log.d(TAG, "Channel "+id+" - light="+light); channel.enableLights(light); int lightColor = options.optInt("lightColor", -1); if (lightColor != -1) { Log.d(TAG, "Channel "+id+" - lightColor="+lightColor); channel.setLightColor(lightColor); } // Visibility int visibility = options.optInt("visibility", NotificationCompat.VISIBILITY_PUBLIC); Log.d(TAG, "Channel "+id+" - visibility="+visibility); channel.setLockscreenVisibility(visibility); // Badge boolean badge = options.optBoolean("badge", true); Log.d(TAG, "Channel "+id+" - badge="+badge); channel.setShowBadge(badge); // Sound String sound = options.optString("sound", "default"); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build(); if ("ringtone".equals(sound)) { channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), audioAttributes); Log.d(TAG, "Channel "+id+" - sound=ringtone"); } else if (sound != null && !sound.contentEquals("default")) { Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/raw/" + sound); channel.setSound(soundUri, audioAttributes); Log.d(TAG, "Channel "+id+" - sound="+sound); } else if (sound != "false"){ channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes); Log.d(TAG, "Channel "+id+" - sound=default"); }else{ Log.d(TAG, "Channel "+id+" - sound=none"); } // Vibration: if vibration setting is an array set vibration pattern, else set enable vibration. JSONArray pattern = options.optJSONArray("vibration"); if (pattern != null) { int patternLength = pattern.length(); long[] patternArray = new long[patternLength]; for (int i = 0; i < patternLength; i++) { patternArray[i] = pattern.optLong(i); } channel.enableVibration(true); channel.setVibrationPattern(patternArray); Log.d(TAG, "Channel "+id+" - vibrate="+pattern); } else { boolean vibrate = options.optBoolean("vibration", true); channel.enableVibration(vibrate); Log.d(TAG, "Channel "+id+" - vibrate="+vibrate); } // Create channel nm.createNotificationChannel(channel); } return channel; } protected static void createDefaultChannel() throws JSONException { JSONObject options = new JSONObject(); options.put("id", defaultChannelId); options.put("name", defaultChannelName); createDefaultChannel(options); } protected static void createDefaultChannel(final JSONObject options) throws JSONException { defaultNotificationChannel = createChannel(options); } public void setDefaultChannel(final CallbackContext callbackContext, final JSONObject options) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { deleteChannel(defaultChannelId); String id = options.optString("id", null); if(id != null){ defaultChannelId = id; } String name = options.optString("name", null); if(name != null){ defaultChannelName = name; } createDefaultChannel(options); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public void deleteChannel(final CallbackContext callbackContext, final String channelID) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { deleteChannel(channelID); callbackContext.success(); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } protected static void deleteChannel(final String channelID){ // only call on Android O and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); nm.deleteNotificationChannel(channelID); } } public void listChannels(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { try { List notificationChannels = listChannels(); JSONArray channels = new JSONArray(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { for (NotificationChannel notificationChannel : notificationChannels) { JSONObject channel = new JSONObject(); channel.put("id", notificationChannel.getId()); channel.put("name", notificationChannel.getName()); channels.put(channel); } } callbackContext.success(channels); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } public static List listChannels(){ List notificationChannels = null; // only call on Android O and above if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationChannels = nm.getNotificationChannels(); } return notificationChannels; } public static boolean channelExists(String channelId){ boolean exists = false; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ List notificationChannels = FirebasePlugin.listChannels(); if(notificationChannels != null){ for (NotificationChannel notificationChannel : notificationChannels) { if(notificationChannel.getId().equals(channelId)){ exists = true; } } } } return exists; } // // Firestore // private void addDocumentToFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String jsonDoc = args.getString(0); String collection = args.getString(1); firestore.collection(collection) .add(jsonStringToMap(jsonDoc)) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(DocumentReference documentReference) { callbackContext.success(documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void setDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String jsonDoc = args.getString(1); String collection = args.getString(2); firestore.collection(collection).document(documentId) .set(jsonStringToMap(jsonDoc)) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { callbackContext.success(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void updateDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String jsonDoc = args.getString(1); String collection = args.getString(2); firestore.collection(collection).document(documentId) .update(jsonStringToMap(jsonDoc)) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { callbackContext.success(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void deleteDocumentFromFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String collection = args.getString(1); firestore.collection(collection).document(documentId) .delete() .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { callbackContext.success(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void documentExistsInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String collection = args.getString(1); firestore.collection(collection).document(documentId) .get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { try { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); callbackContext.success(document != null && document.getData() != null ? 1 : 0); } else { Exception e = task.getException(); if(e != null){ handleExceptionWithContext(e, callbackContext); } } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void fetchDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String documentId = args.getString(0); String collection = args.getString(1); firestore.collection(collection).document(documentId) .get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { try { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document != null && document.getData() != null) { JSONObject jsonDoc = mapToJsonObject(document.getData()); callbackContext.success(jsonDoc); } else { callbackContext.error("No document found in collection"); } } else { Exception e = task.getException(); if(e != null){ handleExceptionWithContext(e, callbackContext); } } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { handleExceptionWithContext(e, callbackContext); } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } private void fetchFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { public void run() { try { String collection = args.getString(0); JSONArray filters = args.getJSONArray(1); Query query = firestore.collection(collection); for(int i = 0; i < filters.length(); i++) { JSONArray filter = filters.getJSONArray(i); switch(filter.getString(0)) { case "where": if (Objects.equals(filter.getString(2), new String("=="))) { query = query.whereEqualTo(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String("<"))) { query = query.whereLessThan(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String(">"))) { query = query.whereGreaterThan(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String("<="))) { query = query.whereLessThanOrEqualTo(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String(">="))) { query = query.whereGreaterThanOrEqualTo(filter.getString(1), filter.getString(3)); } if (Objects.equals(filter.getString(2), new String("array-contains"))) { query = query.whereArrayContains(filter.getString(1), filter.getString(3)); } break; case "orderBy": Direction direction = Direction.ASCENDING; if (Objects.equals(filter.getString(2), new String("desc"))) { direction = Direction.DESCENDING; } query = query.orderBy(filter.getString(1), direction); break; case "startAt": query = query.startAt(filter.getString(1)); break; case "endAt": query = query.endAt(filter.getString(1)); break; case "limit": query = query.limit(filter.getLong(1)); break; } } query.get() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { try { if (task.isSuccessful()) { JSONObject jsonDocs = new JSONObject(); for (QueryDocumentSnapshot document : task.getResult()) { jsonDocs.put(document.getId(), mapToJsonObject(document.getData())); } callbackContext.success(jsonDocs); } else { handleExceptionWithContext(task.getException(), callbackContext); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } }); } protected static void handleExceptionWithContext(Exception e, CallbackContext context) { String msg = e.toString(); Log.e(TAG, msg); instance.logExceptionToCrashlytics(e); context.error(msg); } protected static void handleExceptionWithoutContext(Exception e){ String msg = e.toString(); Log.e(TAG, msg); if (instance != null) { instance.logExceptionToCrashlytics(e); instance.logErrorToWebview(msg); } } protected void logErrorToWebview(String msg){ Log.e(TAG, msg); executeGlobalJavascript("console.error(\""+TAG+"[native]: "+escapeDoubleQuotes(msg)+"\")"); } private String escapeDoubleQuotes(String string){ String escapedString = string.replace("\"", "\\\""); escapedString = escapedString.replace("%22", "\\%22"); return escapedString; } private void executeGlobalJavascript(final String jsString){ if(cordovaActivity == null) return; cordovaActivity.runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:" + jsString); } }); } private String saveAuthCredential(AuthCredential authCredential){ String id = this.generateId(); this.authCredentials.put(id, authCredential); return id; } private String saveAuthProvider(OAuthProvider authProvider){ String id = this.generateId(); this.authProviders.put(id, authProvider); return id; } private String generateId(){ Random r = new Random(); return Integer.toString(r.nextInt(1000+1)); } private boolean getMetaDataFromManifest(String name) throws Exception{ return applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean(name); } private void setPreference(String name, boolean value){ SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(name, value); editor.apply(); } private boolean getPreference(String name){ SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); return settings.getBoolean(name, false); } private void handleTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { try { if (task.isSuccessful()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); }else{ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, task.getException().getMessage())); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } private void handleAuthTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { try { if (task.isSuccessful()) { callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); }else{ String errMessage = task.getException().getMessage(); if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { errMessage = "Invalid verification code"; } callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, errMessage)); } } catch (Exception e) { handleExceptionWithContext(e, callbackContext); } } private AuthCredential obtainAuthCredential(JSONObject jsonCredential) throws JSONException { AuthCredential authCredential = null; if(jsonCredential.has("verificationId") && jsonCredential.has("code")){ Log.d(TAG, "Using specified verificationId and code to authenticate"); authCredential = (AuthCredential) PhoneAuthProvider.getCredential(jsonCredential.getString("verificationId"), jsonCredential.getString("code")); }else if(jsonCredential.has("id") && FirebasePlugin.instance.authCredentials.containsKey(jsonCredential.getString("id"))){ Log.d(TAG, "Using native auth credential to authenticate"); authCredential = FirebasePlugin.instance.authCredentials.get(jsonCredential.getString("id")); } return authCredential; } private OAuthProvider obtainAuthProvider(JSONObject jsonCredential) throws JSONException{ OAuthProvider authProvider = null; if(jsonCredential.has("id") && FirebasePlugin.instance.authProviders.containsKey(jsonCredential.getString("id"))){ Log.d(TAG, "Using native auth provider to authenticate"); authProvider = FirebasePlugin.instance.authProviders.get(jsonCredential.getString("id")); } return authProvider; } private static class AuthResultOnSuccessListener implements OnSuccessListener { @Override public void onSuccess(AuthResult authResult) { Log.d(TAG, "AuthResult:onSuccess:" + authResult); if(FirebasePlugin.instance.authResultCallbackContext != null){ FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); } } } private static class AuthResultOnFailureListener implements OnFailureListener { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "AuthResult:onFailure", e); if(FirebasePlugin.instance.authResultCallbackContext != null){ FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); } } } private static class AuthResultOnCompleteListener implements OnCompleteListener { private final CallbackContext callbackContext; public AuthResultOnCompleteListener(CallbackContext callbackContext) { this.callbackContext = callbackContext; } @Override public void onComplete(@NonNull Task task) { FirebasePlugin.instance.handleAuthTaskOutcome(task, callbackContext); } } private static class AuthStateListener implements FirebaseAuth.AuthStateListener { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { try { if(!FirebasePlugin.instance.authStateChangeListenerInitialized){ FirebasePlugin.instance.authStateChangeListenerInitialized = true; }else{ FirebaseUser user = firebaseAuth.getCurrentUser(); FirebasePlugin.instance.executeGlobalJavascript(JS_GLOBAL_NAMESPACE+"_onAuthStateChange("+(user != null ? "true" : "false")+")"); } } catch (Exception e) { handleExceptionWithoutContext(e); } } } private Map jsonStringToMap(String jsonString) throws JSONException { Type type = new TypeToken>(){}.getType(); return gson.fromJson(jsonString, type); } private JSONObject mapToJsonObject(Map map) throws JSONException { String jsonString = gson.toJson(map); return new JSONObject(jsonString); } private void logMessageToCrashlytics(String message){ if(isCrashlyticsEnabled){ try{ firebaseCrashlytics.log(message); }catch (Exception e){ Log.e(TAG, e.getMessage()); } }else{ Log.e(TAG, "Cannot log message - firebaseCrashlytics collection is disabled"); } } private void logExceptionToCrashlytics(Exception exception){ if(isCrashlyticsEnabled){ try{ firebaseCrashlytics.recordException(exception); }catch (Exception e){ Log.e(TAG, e.getMessage()); } }else{ Log.e(TAG, "Cannot log exception - firebaseCrashlytics collection is disabled"); } } } \ No newline at end of file +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.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; + +import android.util.Base64; +import android.util.Log; + +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.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.analytics.FirebaseAnalytics; +import com.google.firebase.auth.AuthCredential; +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.firestore.CollectionReference; +import com.google.firebase.firestore.DocumentReference; +import com.google.firebase.firestore.DocumentSnapshot; +import com.google.firebase.firestore.FirebaseFirestore; +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.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 org.apache.cordova.CallbackContext; +import org.apache.cordova.CordovaInterface; +import org.apache.cordova.CordovaPlugin; +import org.apache.cordova.PluginResult; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +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; + +// 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.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 Gson gson; + private FirebaseAuth.AuthStateListener authStateListener; + private boolean authStateChangeListenerInitialized = false; + private static CordovaInterface cordovaInterface = null; + protected static Context applicationContext = null; + private static Activity cordovaActivity = null; + private boolean isCrashlyticsEnabled = false; + + 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 boolean inBackground = true; + private static ArrayList notificationStack = null; + private static CallbackContext notificationCallbackContext; + private static CallbackContext tokenRefreshCallbackContext; + private static CallbackContext activityResultCallbackContext; + private static CallbackContext authResultCallbackContext; + + private static NotificationChannel defaultNotificationChannel = null; + public static String defaultChannelId = null; + public static String defaultChannelName = null; + + private Map authCredentials = new HashMap(); + private Map authProviders = new HashMap(); + + @Override + protected void pluginInitialize() { + instance = this; + cordovaActivity = this.cordova.getActivity(); + applicationContext = cordovaActivity.getApplicationContext(); + final Bundle extras = cordovaActivity.getIntent().getExtras(); + FirebasePlugin.cordovaInterface = this.cordova; + firebaseCrashlytics = FirebaseCrashlytics.getInstance(); + this.cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + Log.d(TAG, "Starting Firebase plugin"); + + if(!getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ + isCrashlyticsEnabled = getPreference(CRASHLYTICS_COLLECTION_ENABLED); + if(isCrashlyticsEnabled){ + firebaseCrashlytics.setCrashlyticsCollectionEnabled(true); + } + }else{ + isCrashlyticsEnabled = true; + 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); + } + + FirebaseApp.initializeApp(applicationContext); + mFirebaseAnalytics = FirebaseAnalytics.getInstance(applicationContext); + + authStateListener = new AuthStateListener(); + FirebaseAuth.getInstance().addAuthStateListener(authStateListener); + + firestore = FirebaseFirestore.getInstance(); + gson = new Gson(); + + if (extras != null && extras.size() > 1) { + if (FirebasePlugin.notificationStack == null) { + FirebasePlugin.notificationStack = new ArrayList(); + } + 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{ + 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("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("isAutoInitEnabled")) { + isAutoInitEnabled(callbackContext); + return true; + } else if (action.equals("setAutoInitEnabled")) { + setAutoInitEnabled(callbackContext, args.getBoolean(0)); + return true; + } else if (action.equals("unregister")) { + this.unregister(callbackContext); + return true; + } else if (action.equals("onMessageReceived")) { + this.onMessageReceived(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); + 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")) { + this.getByteArray(callbackContext, args.getString(0)); + return true; + } else if (action.equals("getValue")) { + this.getValue(callbackContext, args.getString(0)); + 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")) { + this.setDefaults(callbackContext, args.getJSONObject(0)); + return true; + } else if (action.equals("verifyPhoneNumber")) { + this.verifyPhoneNumber(callbackContext, args); + return true; + } else if (action.equals("authenticateUserWithGoogle")) { + this.authenticateUserWithGoogle(callbackContext, args); + return true; + } else if (action.equals("authenticateUserWithApple")) { + this.authenticateUserWithApple(callbackContext, args); + return true; + } else if (action.equals("createUserWithEmailAndPassword")) { + this.createUserWithEmailAndPassword(callbackContext, args); + return true; + } else if (action.equals("signInUserWithEmailAndPassword")) { + this.signInUserWithEmailAndPassword(callbackContext, args); + return true; + } else if (action.equals("signInUserWithCustomToken")) { + this.signInUserWithCustomToken(callbackContext, args); + return true; + } else if (action.equals("signInUserAnonymously")) { + this.signInUserAnonymously(callbackContext); + return true; + } else if (action.equals("signInWithCredential")) { + this.signInWithCredential(callbackContext, args); + return true; + } else if (action.equals("linkUserWithCredential")) { + this.linkUserWithCredential(callbackContext, args); + return true; + } else if (action.equals("reauthenticateWithCredential")) { + this.reauthenticateWithCredential(callbackContext, args); + return true; + } else if (action.equals("isUserSignedIn")) { + this.isUserSignedIn(callbackContext, args); + return true; + } else if (action.equals("signOutUser")) { + this.signOutUser(callbackContext, args); + return true; + } else if (action.equals("getCurrentUser")) { + this.getCurrentUser(callbackContext, args); + return true; + } else if (action.equals("reloadCurrentUser")) { + this.reloadCurrentUser(callbackContext, args); + return true; + } else if (action.equals("updateUserProfile")) { + this.updateUserProfile(callbackContext, args); + return true; + } else if (action.equals("updateUserEmail")) { + this.updateUserEmail(callbackContext, args); + return true; + } else if (action.equals("sendUserEmailVerification")) { + this.sendUserEmailVerification(callbackContext, args); + return true; + } else if (action.equals("updateUserPassword")) { + this.updateUserPassword(callbackContext, args); + return true; + } else if (action.equals("sendUserPasswordResetEmail")) { + this.sendUserPasswordResetEmail(callbackContext, args); + return true; + } else if (action.equals("deleteUser")) { + this.deleteUser(callbackContext, args); + 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("isAnalyticsCollectionEnabled")) { + this.isAnalyticsCollectionEnabled(callbackContext); + return true; + } else if (action.equals("setPerformanceCollectionEnabled")) { + this.setPerformanceCollectionEnabled(callbackContext, args.getBoolean(0)); + return true; + } else if (action.equals("isPerformanceCollectionEnabled")) { + this.isPerformanceCollectionEnabled(callbackContext); + return true; + } else if (action.equals("setCrashlyticsCollectionEnabled")) { + this.setCrashlyticsCollectionEnabled(callbackContext, args.getBoolean(0)); + return true; + } else if (action.equals("isCrashlyticsCollectionEnabled")) { + this.isCrashlyticsCollectionEnabled(callbackContext); + return true; + } else if (action.equals("isCrashlyticsCollectionCurrentlyEnabled")) { + this.isCrashlyticsCollectionCurrentlyEnabled(callbackContext); + return true; + } else if (action.equals("clearAllNotifications")) { + this.clearAllNotifications(callbackContext); + return true; + } else if (action.equals("logMessage")) { + logMessage(args, callbackContext); + return true; + } else if (action.equals("sendCrash")) { + sendCrash(args, callbackContext); + return true; + } else if (action.equals("createChannel")) { + this.createChannel(callbackContext, args.getJSONObject(0)); + return true; + } else if (action.equals("deleteChannel")) { + this.deleteChannel(callbackContext, args.getString(0)); + return true; + } else if (action.equals("listChannels")) { + this.listChannels(callbackContext); + return true; + } else if (action.equals("setDefaultChannel")) { + this.setDefaultChannel(callbackContext, args.getJSONObject(0)); + return true; + } else if (action.equals("addDocumentToFirestoreCollection")) { + this.addDocumentToFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("setDocumentInFirestoreCollection")) { + this.setDocumentInFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("updateDocumentInFirestoreCollection")) { + this.updateDocumentInFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("deleteDocumentFromFirestoreCollection")) { + this.deleteDocumentFromFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("documentExistsInFirestoreCollection")) { + this.documentExistsInFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("fetchDocumentInFirestoreCollection")) { + this.fetchDocumentInFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("fetchFirestoreCollection")) { + this.fetchFirestoreCollection(args, callbackContext); + return true; + } else if (action.equals("grantPermission") + || action.equals("setBadgeNumber") + || action.equals("getBadgeNumber") + ) { + // Stubs for other platform methods + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true)); + return true; + }else{ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Invalid action: " + action)); + return false; + } + }catch(Exception e){ + handleExceptionWithContext(e, callbackContext); + } + 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; + 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 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); + + JSONObject returnResults = new JSONObject(); + returnResults.put("instantVerification", true); + returnResults.put("id", id); + FirebasePlugin.activityResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 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 { + String currentToken = FirebaseInstanceId.getInstance().getToken(); + if (currentToken != null) { + FirebasePlugin.sendToken(currentToken); + } + } 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(); + } + 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 keys = bundle.keySet(); + for (String key : keys) { + try { + json.put(key, bundle.get(key)); + } catch (JSONException e) { + handleExceptionWithContext(e, callbackContext); + 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) { + 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 getId(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String id = FirebaseInstanceId.getInstance().getId(); + callbackContext.success(id); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void hasPermission(final CallbackContext callbackContext) { + if(cordovaActivity == null) return; + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(cordovaActivity); + boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled(); + callbackContext.success(areNotificationsEnabled ? 1 : 0); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void unregister(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseInstanceId.getInstance().deleteInstanceId(); + callbackContext.success(); + } 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(isEnabled ? 1 : 0); + } 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 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) { + 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 - firebaseCrashlytics collection is disabled"); + } + } catch (Exception e) { + logExceptionToCrashlytics(e); + callbackContext.error(e.getMessage()); + } + } + }); + } + + private void logMessage(final JSONArray data, + final CallbackContext callbackContext) { + + if(isCrashlyticsEnabled){ + String message = data.optString(0); + logMessageToCrashlytics(message); + callbackContext.success(); + }else{ + callbackContext.error("Cannot log message - firebaseCrashlytics collection is disabled"); + } + } + + private void sendCrash(final JSONArray data, + final CallbackContext callbackContext) { + + cordovaActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + throw new RuntimeException("This is a crash"); + } + }); + } + + + private void setCrashlyticsUserId(final CallbackContext callbackContext, final String userId) { + cordovaActivity.runOnUiThread(new Runnable() { + public void run() { + try { + if(isCrashlyticsEnabled){ + firebaseCrashlytics.setUserId(userId); + callbackContext.success(); + }else{ + callbackContext.error("Cannot set firebaseCrashlytics user ID - firebaseCrashlytics collection is disabled"); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void setScreenName(final CallbackContext callbackContext, final String name) { + // This must be called on the main thread + cordovaActivity.runOnUiThread(new Runnable() { + public void run() { + try { + mFirebaseAnalytics.setCurrentScreen(cordovaActivity, name, null); + callbackContext.success(); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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 task) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + task.addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void data) { + callbackContext.success(); + } + }).addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void getByteArray(final CallbackContext callbackContext, final String key) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + byte[] bytes = FirebaseRemoteConfig.getInstance().getByteArray(key); + JSONObject object = new JSONObject(); + object.put("base64", Base64.encodeToString(bytes, Base64.DEFAULT)); + object.put("array", new JSONArray(bytes)); + callbackContext.success(object); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void getValue(final CallbackContext callbackContext, final String key) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseRemoteConfigValue value = FirebaseRemoteConfig.getInstance().getValue(key); + callbackContext.success(value.asString()); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void setDefaults(final CallbackContext callbackContext, final JSONObject defaults) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseRemoteConfig.getInstance().setDefaults(defaultsToMap(defaults)); + callbackContext.success(); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private static Map defaultsToMap(JSONObject object) throws JSONException { + final Map map = new HashMap(); + + for (Iterator 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; + } + + + public void isUserSignedIn(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + boolean isSignedIn = FirebaseAuth.getInstance().getCurrentUser() != null; + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, isSignedIn)); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void signOutUser(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + // Sign out of Firebase + FirebaseAuth.getInstance().signOut(); + + // Try to sign out of Google + try{ + GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build(); + GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(cordovaActivity, gso); + mGoogleSignInClient.signOut() + .addOnCompleteListener(cordovaActivity, new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + } + }); + }catch(Exception googleSignOutException){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + } + + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void getCurrentUser(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + extractAndReturnUserInfo(callbackContext); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void reloadCurrentUser(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + user.reload() + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void aVoid) { + try { + extractAndReturnUserInfo(callbackContext); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void extractAndReturnUserInfo(final CallbackContext callbackContext) throws Exception{ + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + JSONObject returnResults = new JSONObject(); + returnResults.put("name", user.getDisplayName()); + returnResults.put("email", user.getEmail()); + returnResults.put("emailIsVerified", user.isEmailVerified()); + returnResults.put("phoneNumber", user.getPhoneNumber()); + returnResults.put("photoUrl", user.getPhotoUrl() == null ? null : user.getPhotoUrl().toString()); + returnResults.put("uid", user.getUid()); + returnResults.put("providerId", user.getIdToken(false).getResult().getSignInProvider()); + returnResults.put("isAnonymous", user.isAnonymous()); + + user.getIdToken(true).addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(GetTokenResult result) { + try { + String idToken = result.getToken(); + returnResults.put("idToken", idToken); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void updateUserProfile(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + + JSONObject profile = args.getJSONObject(0); + UserProfileChangeRequest profileUpdates; + if(profile.has("name") && profile.has("photoUri")){ + profileUpdates = new UserProfileChangeRequest.Builder() + .setDisplayName(profile.getString("name")) + .setPhotoUri(Uri.parse(profile.getString("photoUri"))) + .build(); + }else if(profile.has("name")){ + profileUpdates = new UserProfileChangeRequest.Builder() + .setDisplayName(profile.getString("name")) + .build(); + }else if(profile.has("photoUri")){ + profileUpdates = new UserProfileChangeRequest.Builder() + .setPhotoUri(Uri.parse(profile.getString("photoUri"))) + .build(); + }else{ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "'name' and/or 'photoUri' keys must be specified in the profile object")); + return; + } + + user.updateProfile(profileUpdates) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void updateUserEmail(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + + String email = args.getString(0); + user.updateEmail(email) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void sendUserEmailVerification(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + + user.sendEmailVerification() + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void updateUserPassword(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + + String password = args.getString(0); + user.updatePassword(password) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void sendUserPasswordResetEmail(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseAuth auth = FirebaseAuth.getInstance(); + String email = args.getString(0); + auth.sendPasswordResetEmail(email) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void deleteUser(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + + user.delete() + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void reauthenticateWithCredential(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); + if(user == null){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No user is currently signed")); + return; + } + + JSONObject jsonCredential = args.getJSONObject(0); + if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); + return; + } + + AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); + if(authCredential != null){ + user.reauthenticate(authCredential) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleTaskOutcome(task, callbackContext); + } + }); + return; + } + + OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); + if(authProvider != null){ + FirebasePlugin.instance.authResultCallbackContext = callbackContext; + user.startActivityForReauthenticateWithProvider(FirebasePlugin.cordovaActivity, authProvider) + .addOnSuccessListener(new AuthResultOnSuccessListener()) + .addOnFailureListener(new AuthResultOnFailureListener()); + return; + } + + //ELSE + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); + + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + + + public void signInWithCredential(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + JSONObject jsonCredential = args.getJSONObject(0); + if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); + return; + } + + AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); + if(authCredential != null){ + FirebaseAuth.getInstance().signInWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); + return; + } + + OAuthProvider authProvider = FirebasePlugin.instance.obtainAuthProvider(jsonCredential); + if(authProvider != null){ + FirebasePlugin.instance.authResultCallbackContext = callbackContext; + FirebaseAuth.getInstance().startActivityForSignInWithProvider(FirebasePlugin.cordovaActivity, authProvider) + .addOnSuccessListener(new AuthResultOnSuccessListener()) + .addOnFailureListener(new AuthResultOnFailureListener()); + return; + } + + //ELSE + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void linkUserWithCredential(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + JSONObject jsonCredential = args.getJSONObject(0); + if(!FirebasePlugin.instance.isValidJsonCredential(jsonCredential)){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No auth credentials specified")); + return; + } + + AuthCredential authCredential = FirebasePlugin.instance.obtainAuthCredential(jsonCredential); + if(authCredential != null){ + FirebaseAuth.getInstance().getCurrentUser().linkWithCredential(authCredential).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); + return; + } + + //ELSE + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Specified native auth credential id does not exist")); + + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private boolean isValidJsonCredential(JSONObject jsonCredential) throws JSONException{ + return jsonCredential.has("id") || (jsonCredential.has("verificationId") && jsonCredential.has("code")); + } + + private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks; + + public void verifyPhoneNumber( + final CallbackContext callbackContext, + final JSONArray args + ) { + 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"); + + String id = FirebasePlugin.instance.saveAuthCredential((AuthCredential) credential); + + JSONObject returnResults = new JSONObject(); + try { + returnResults.put("instantVerification", true); + returnResults.put("id", id); + } catch(JSONException e){ + handleExceptionWithContext(e, callbackContext); + 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; + 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"; + }else{ + errorMsg = e.getMessage(); + } + 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) { + handleExceptionWithContext(e, callbackContext); + return; + } + PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, returnResults); + pluginresult.setKeepCallback(true); + callbackContext.sendPluginResult(pluginresult); + } + }; + + String number = args.getString(0); + int timeOutDuration = args.getInt(1); + String smsCode = args.getString(2); + + if(smsCode != null && smsCode != "null"){ + FirebaseAuth.getInstance().getFirebaseAuthSettings().setAutoRetrievedSmsCodeForPhoneNumber(number, smsCode); + } + + PhoneAuthProvider.getInstance().verifyPhoneNumber(number, // Phone number to verify + timeOutDuration, // Timeout duration + TimeUnit.SECONDS, // Unit of timeout + cordovaActivity, // Activity (for callback binding) + mCallbacks); // OnVerificationStateChangedCallbacks + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void createUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String email = args.getString(0); + String password = args.getString(1); + + if(email == null || email.equals("")){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); + return; + } + + if(password == null || password.equals("")){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); + return; + } + + FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void signInUserWithEmailAndPassword(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String email = args.getString(0); + String password = args.getString(1); + + if(email == null || email.equals("")){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User email address must be specified")); + return; + } + + if(password == null || password.equals("")){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "User password must be specified")); + return; + } + + FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + + public void authenticateUserWithGoogle(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String clientId = args.getString(0); + + GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) + .requestIdToken(clientId) + .requestEmail() + .build(); + + GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(FirebasePlugin.instance.cordovaActivity, gso); + Intent signInIntent = mGoogleSignInClient.getSignInIntent(); + FirebasePlugin.activityResultCallbackContext = callbackContext; + FirebasePlugin.instance.cordovaInterface.startActivityForResult(FirebasePlugin.instance, signInIntent, GOOGLE_SIGN_IN); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void authenticateUserWithApple(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String locale = args.getString(0); + OAuthProvider.Builder provider = OAuthProvider.newBuilder("apple.com"); + if(locale != null){ + provider.addCustomParameter("locale", locale); + } + Task pending = FirebaseAuth.getInstance().getPendingAuthResult(); + if (pending != null) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Auth result is already pending")); + pending + .addOnSuccessListener(new AuthResultOnSuccessListener()) + .addOnFailureListener(new AuthResultOnFailureListener()); + } else { + String id = FirebasePlugin.instance.saveAuthProvider(provider.build());; + JSONObject returnResults = new JSONObject(); + returnResults.put("instantVerification", true); + returnResults.put("id", id); + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, returnResults)); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void signInUserWithCustomToken(final CallbackContext callbackContext, final JSONArray args){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String customToken = args.getString(0); + + if(customToken == null || customToken.equals("")){ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Custom token must be specified")); + return; + } + + FirebaseAuth.getInstance().signInWithCustomToken(customToken).addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void signInUserAnonymously(final CallbackContext callbackContext){ + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(cordova.getActivity(), new AuthResultOnCompleteListener(callbackContext)); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + // + // Firebase Performace + // + + private HashMap traces = new HashMap(); + + 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) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + 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.incrementMetric(counterNamed, 1); + callbackContext.success(); + } else { + callbackContext.error("Trace not found"); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + 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) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void setAnalyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + if(getMetaDataFromManifest(ANALYTICS_COLLECTION_ENABLED)){ + callbackContext.error("Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); + }else if(enabled && getPreference(ANALYTICS_COLLECTION_ENABLED)){ + callbackContext.error("Analytics data collection is already set to enabled"); + }else if(!enabled && !getPreference(ANALYTICS_COLLECTION_ENABLED)){ + callbackContext.error("Analytics data collection is already set to disabled"); + }else{ + mFirebaseAnalytics.setAnalyticsCollectionEnabled(enabled); + setPreference(ANALYTICS_COLLECTION_ENABLED, enabled); + callbackContext.success(); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void isAnalyticsCollectionEnabled(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + callbackContext.success(getPreference(ANALYTICS_COLLECTION_ENABLED) ? 1 : 0); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void setPerformanceCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + if(getMetaDataFromManifest(PERFORMANCE_COLLECTION_ENABLED)){ + callbackContext.error("Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); + }else if(enabled && getPreference(PERFORMANCE_COLLECTION_ENABLED)){ + callbackContext.error("Performance data collection is already set to enabled"); + }else if(!enabled && !getPreference(PERFORMANCE_COLLECTION_ENABLED)){ + callbackContext.error("Performance data collection is already set to disabled"); + }else{ + FirebasePerformance.getInstance().setPerformanceCollectionEnabled(enabled); + setPreference(PERFORMANCE_COLLECTION_ENABLED, enabled); + callbackContext.success(); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void isPerformanceCollectionEnabled(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + callbackContext.success(getPreference(PERFORMANCE_COLLECTION_ENABLED) ? 1 : 0); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void setCrashlyticsCollectionEnabled(final CallbackContext callbackContext, final boolean enabled) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + if(getMetaDataFromManifest(CRASHLYTICS_COLLECTION_ENABLED)){ + callbackContext.error("Cannot set firebaseCrashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the manifest"); + }else if(enabled && getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ + callbackContext.error("firebaseCrashlytics data collection is already set to enabled"); + }else if(!enabled && !getPreference(CRASHLYTICS_COLLECTION_ENABLED)){ + callbackContext.error("firebaseCrashlytics data collection is already set to disabled"); + }else{ + setPreference(CRASHLYTICS_COLLECTION_ENABLED, enabled); + callbackContext.success(); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void isCrashlyticsCollectionEnabled(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + callbackContext.success(getPreference(CRASHLYTICS_COLLECTION_ENABLED) ? 1 : 0); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + private void isCrashlyticsCollectionCurrentlyEnabled(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + callbackContext.success(isCrashlyticsEnabled ? 1 : 0); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + e.printStackTrace(); + } + } + }); + } + + public void clearAllNotifications(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); + nm.cancelAll(); + callbackContext.success(); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void createChannel(final CallbackContext callbackContext, final JSONObject options) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + createChannel(options); + callbackContext.success(); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + protected static NotificationChannel createChannel(final JSONObject options) throws JSONException { + NotificationChannel channel = null; + // only call on Android O and above + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + String id = options.getString("id"); + Log.i(TAG, "Creating channel id="+id); + + if(channelExists(id)){ + deleteChannel(id); + } + + NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); + String packageName = cordovaActivity.getPackageName(); + + String name = options.optString("name", ""); + Log.d(TAG, "Channel "+id+" - name="+name); + + int importance = options.optInt("importance", NotificationManager.IMPORTANCE_HIGH); + Log.d(TAG, "Channel "+id+" - importance="+importance); + + channel = new NotificationChannel(id, + name, + importance); + + // Description + String description = options.optString("description", ""); + Log.d(TAG, "Channel "+id+" - description="+description); + channel.setDescription(description); + + // Light + boolean light = options.optBoolean("light", true); + Log.d(TAG, "Channel "+id+" - light="+light); + channel.enableLights(light); + + int lightColor = options.optInt("lightColor", -1); + if (lightColor != -1) { + Log.d(TAG, "Channel "+id+" - lightColor="+lightColor); + channel.setLightColor(lightColor); + } + + // Visibility + int visibility = options.optInt("visibility", NotificationCompat.VISIBILITY_PUBLIC); + Log.d(TAG, "Channel "+id+" - visibility="+visibility); + channel.setLockscreenVisibility(visibility); + + // Badge + boolean badge = options.optBoolean("badge", true); + Log.d(TAG, "Channel "+id+" - badge="+badge); + channel.setShowBadge(badge); + + // Sound + String sound = options.optString("sound", "default"); + AudioAttributes audioAttributes = new AudioAttributes.Builder() + .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) + .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build(); + if ("ringtone".equals(sound)) { + channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), audioAttributes); + Log.d(TAG, "Channel "+id+" - sound=ringtone"); + } else if (sound != null && !sound.contentEquals("default")) { + Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + packageName + "/raw/" + sound); + channel.setSound(soundUri, audioAttributes); + Log.d(TAG, "Channel "+id+" - sound="+sound); + } else if (sound != "false"){ + channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), audioAttributes); + Log.d(TAG, "Channel "+id+" - sound=default"); + }else{ + Log.d(TAG, "Channel "+id+" - sound=none"); + } + + // Vibration: if vibration setting is an array set vibration pattern, else set enable vibration. + JSONArray pattern = options.optJSONArray("vibration"); + if (pattern != null) { + int patternLength = pattern.length(); + long[] patternArray = new long[patternLength]; + for (int i = 0; i < patternLength; i++) { + patternArray[i] = pattern.optLong(i); + } + channel.enableVibration(true); + channel.setVibrationPattern(patternArray); + Log.d(TAG, "Channel "+id+" - vibrate="+pattern); + } else { + boolean vibrate = options.optBoolean("vibration", true); + channel.enableVibration(vibrate); + Log.d(TAG, "Channel "+id+" - vibrate="+vibrate); + } + + // Create channel + nm.createNotificationChannel(channel); + } + return channel; + } + + protected static void createDefaultChannel() throws JSONException { + JSONObject options = new JSONObject(); + options.put("id", defaultChannelId); + options.put("name", defaultChannelName); + createDefaultChannel(options); + } + + protected static void createDefaultChannel(final JSONObject options) throws JSONException { + defaultNotificationChannel = createChannel(options); + } + + public void setDefaultChannel(final CallbackContext callbackContext, final JSONObject options) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + deleteChannel(defaultChannelId); + + String id = options.optString("id", null); + if(id != null){ + defaultChannelId = id; + } + + String name = options.optString("name", null); + if(name != null){ + defaultChannelName = name; + } + createDefaultChannel(options); + callbackContext.success(); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public void deleteChannel(final CallbackContext callbackContext, final String channelID) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + deleteChannel(channelID); + callbackContext.success(); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + protected static void deleteChannel(final String channelID){ + // only call on Android O and above + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); + nm.deleteNotificationChannel(channelID); + } + } + + public void listChannels(final CallbackContext callbackContext) { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + List notificationChannels = listChannels(); + JSONArray channels = new JSONArray(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + for (NotificationChannel notificationChannel : notificationChannels) { + JSONObject channel = new JSONObject(); + channel.put("id", notificationChannel.getId()); + channel.put("name", notificationChannel.getName()); + channels.put(channel); + } + } + callbackContext.success(channels); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + public static List listChannels(){ + List notificationChannels = null; + // only call on Android O and above + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + NotificationManager nm = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE); + notificationChannels = nm.getNotificationChannels(); + } + return notificationChannels; + } + + public static boolean channelExists(String channelId){ + boolean exists = false; + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ + List notificationChannels = FirebasePlugin.listChannels(); + if(notificationChannels != null){ + for (NotificationChannel notificationChannel : notificationChannels) { + if(notificationChannel.getId().equals(channelId)){ + exists = true; + } + } + } + } + return exists; + } + + // + // Firestore + // + private void addDocumentToFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String jsonDoc = args.getString(0); + String collection = args.getString(1); + + firestore.collection(collection) + .add(jsonStringToMap(jsonDoc)) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(DocumentReference documentReference) { + callbackContext.success(documentReference.getId()); + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void setDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String documentId = args.getString(0); + String jsonDoc = args.getString(1); + String collection = args.getString(2); + + firestore.collection(collection).document(documentId) + .set(jsonStringToMap(jsonDoc)) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void aVoid) { + callbackContext.success(); + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void updateDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String documentId = args.getString(0); + String jsonDoc = args.getString(1); + String collection = args.getString(2); + + firestore.collection(collection).document(documentId) + .update(jsonStringToMap(jsonDoc)) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void aVoid) { + callbackContext.success(); + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void deleteDocumentFromFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String documentId = args.getString(0); + String collection = args.getString(1); + + firestore.collection(collection).document(documentId) + .delete() + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void aVoid) { + callbackContext.success(); + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void documentExistsInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String documentId = args.getString(0); + String collection = args.getString(1); + + firestore.collection(collection).document(documentId) + .get() + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + try { + if (task.isSuccessful()) { + DocumentSnapshot document = task.getResult(); + callbackContext.success(document != null && document.getData() != null ? 1 : 0); + } else { + Exception e = task.getException(); + if(e != null){ + handleExceptionWithContext(e, callbackContext); + } + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void fetchDocumentInFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String documentId = args.getString(0); + String collection = args.getString(1); + + firestore.collection(collection).document(documentId) + .get() + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + try { + if (task.isSuccessful()) { + DocumentSnapshot document = task.getResult(); + if (document != null && document.getData() != null) { + JSONObject jsonDoc = mapToJsonObject(document.getData()); + callbackContext.success(jsonDoc); + } else { + callbackContext.error("No document found in collection"); + } + } else { + Exception e = task.getException(); + if(e != null){ + handleExceptionWithContext(e, callbackContext); + } + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + handleExceptionWithContext(e, callbackContext); + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + private void fetchFirestoreCollection(JSONArray args, CallbackContext callbackContext) throws JSONException { + cordova.getThreadPool().execute(new Runnable() { + public void run() { + try { + String collection = args.getString(0); + JSONArray filters = args.getJSONArray(1); + Query query = firestore.collection(collection); + + for(int i = 0; i < filters.length(); i++) { + JSONArray filter = filters.getJSONArray(i); + switch(filter.getString(0)) { + case "where": + if (Objects.equals(filter.getString(2), new String("=="))) { + query = query.whereEqualTo(filter.getString(1), filter.getString(3)); + } + if (Objects.equals(filter.getString(2), new String("<"))) { + query = query.whereLessThan(filter.getString(1), filter.getString(3)); + } + if (Objects.equals(filter.getString(2), new String(">"))) { + query = query.whereGreaterThan(filter.getString(1), filter.getString(3)); + } + if (Objects.equals(filter.getString(2), new String("<="))) { + query = query.whereLessThanOrEqualTo(filter.getString(1), filter.getString(3)); + } + if (Objects.equals(filter.getString(2), new String(">="))) { + query = query.whereGreaterThanOrEqualTo(filter.getString(1), filter.getString(3)); + } + if (Objects.equals(filter.getString(2), new String("array-contains"))) { + query = query.whereArrayContains(filter.getString(1), filter.getString(3)); + } + break; + case "orderBy": + Direction direction = Direction.ASCENDING; + if (Objects.equals(filter.getString(2), new String("desc"))) { + direction = Direction.DESCENDING; + } + query = query.orderBy(filter.getString(1), direction); + break; + case "startAt": + query = query.startAt(filter.getString(1)); + break; + case "endAt": + query = query.endAt(filter.getString(1)); + break; + case "limit": + query = query.limit(filter.getLong(1)); + break; + } + } + + query.get() + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + try { + if (task.isSuccessful()) { + JSONObject jsonDocs = new JSONObject(); + for (QueryDocumentSnapshot document : task.getResult()) { + jsonDocs.put(document.getId(), mapToJsonObject(document.getData())); + } + callbackContext.success(jsonDocs); + } else { + handleExceptionWithContext(task.getException(), callbackContext); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + }); + } + + + protected static void handleExceptionWithContext(Exception e, CallbackContext context) { + String msg = e.toString(); + Log.e(TAG, msg); + instance.logExceptionToCrashlytics(e); + context.error(msg); + } + + protected static void handleExceptionWithoutContext(Exception e){ + String msg = e.toString(); + Log.e(TAG, msg); + if (instance != null) { + instance.logExceptionToCrashlytics(e); + instance.logErrorToWebview(msg); + } + } + + protected void logErrorToWebview(String msg){ + Log.e(TAG, msg); + executeGlobalJavascript("console.error(\""+TAG+"[native]: "+escapeDoubleQuotes(msg)+"\")"); + } + + private String escapeDoubleQuotes(String string){ + String escapedString = string.replace("\"", "\\\""); + escapedString = escapedString.replace("%22", "\\%22"); + return escapedString; + } + + private void executeGlobalJavascript(final String jsString){ + if(cordovaActivity == null) return; + cordovaActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + webView.loadUrl("javascript:" + jsString); + } + }); + } + + private String saveAuthCredential(AuthCredential authCredential){ + String id = this.generateId(); + this.authCredentials.put(id, authCredential); + return id; + } + + private String saveAuthProvider(OAuthProvider authProvider){ + String id = this.generateId(); + this.authProviders.put(id, authProvider); + return id; + } + + private String generateId(){ + Random r = new Random(); + return Integer.toString(r.nextInt(1000+1)); + } + + private boolean getMetaDataFromManifest(String name) throws Exception{ + return applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA).metaData.getBoolean(name); + } + + private void setPreference(String name, boolean value){ + SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); + SharedPreferences.Editor editor = settings.edit(); + editor.putBoolean(name, value); + editor.apply(); + } + + private boolean getPreference(String name){ + SharedPreferences settings = cordovaActivity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); + return settings.getBoolean(name, false); + } + + private void handleTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { + try { + if (task.isSuccessful()) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + }else{ + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, task.getException().getMessage())); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + + private void handleAuthTaskOutcome(@NonNull Task task, CallbackContext callbackContext) { + try { + if (task.isSuccessful()) { + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + }else{ + String errMessage = task.getException().getMessage(); + if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { + errMessage = "Invalid verification code"; + } + callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, errMessage)); + } + } catch (Exception e) { + handleExceptionWithContext(e, callbackContext); + } + } + + private AuthCredential obtainAuthCredential(JSONObject jsonCredential) throws JSONException { + AuthCredential authCredential = null; + if(jsonCredential.has("verificationId") && jsonCredential.has("code")){ + Log.d(TAG, "Using specified verificationId and code to authenticate"); + authCredential = (AuthCredential) PhoneAuthProvider.getCredential(jsonCredential.getString("verificationId"), jsonCredential.getString("code")); + }else if(jsonCredential.has("id") && FirebasePlugin.instance.authCredentials.containsKey(jsonCredential.getString("id"))){ + Log.d(TAG, "Using native auth credential to authenticate"); + authCredential = FirebasePlugin.instance.authCredentials.get(jsonCredential.getString("id")); + } + return authCredential; + } + + private OAuthProvider obtainAuthProvider(JSONObject jsonCredential) throws JSONException{ + OAuthProvider authProvider = null; + if(jsonCredential.has("id") && FirebasePlugin.instance.authProviders.containsKey(jsonCredential.getString("id"))){ + Log.d(TAG, "Using native auth provider to authenticate"); + authProvider = FirebasePlugin.instance.authProviders.get(jsonCredential.getString("id")); + } + return authProvider; + } + + + private static class AuthResultOnSuccessListener implements OnSuccessListener { + @Override + public void onSuccess(AuthResult authResult) { + Log.d(TAG, "AuthResult:onSuccess:" + authResult); + if(FirebasePlugin.instance.authResultCallbackContext != null){ + FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK)); + } + } + } + + private static class AuthResultOnFailureListener implements OnFailureListener { + @Override + public void onFailure(@NonNull Exception e) { + Log.w(TAG, "AuthResult:onFailure", e); + if(FirebasePlugin.instance.authResultCallbackContext != null){ + FirebasePlugin.instance.authResultCallbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.getMessage())); + } + } + } + + private static class AuthResultOnCompleteListener implements OnCompleteListener { + private final CallbackContext callbackContext; + + public AuthResultOnCompleteListener(CallbackContext callbackContext) { + this.callbackContext = callbackContext; + } + + @Override + public void onComplete(@NonNull Task task) { + FirebasePlugin.instance.handleAuthTaskOutcome(task, callbackContext); + } + } + + private static class AuthStateListener implements FirebaseAuth.AuthStateListener { + @Override + public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { + try { + if(!FirebasePlugin.instance.authStateChangeListenerInitialized){ + FirebasePlugin.instance.authStateChangeListenerInitialized = true; + }else{ + FirebaseUser user = firebaseAuth.getCurrentUser(); + FirebasePlugin.instance.executeGlobalJavascript(JS_GLOBAL_NAMESPACE+"_onAuthStateChange("+(user != null ? "true" : "false")+")"); + } + } catch (Exception e) { + handleExceptionWithoutContext(e); + } + } + } + + private Map jsonStringToMap(String jsonString) throws JSONException { + Type type = new TypeToken>(){}.getType(); + return gson.fromJson(jsonString, type); + } + + + private JSONObject mapToJsonObject(Map map) throws JSONException { + String jsonString = gson.toJson(map); + return new JSONObject(jsonString); + } + + private void logMessageToCrashlytics(String message){ + if(isCrashlyticsEnabled){ + try{ + firebaseCrashlytics.log(message); + }catch (Exception e){ + Log.e(TAG, e.getMessage()); + } + }else{ + Log.e(TAG, "Cannot log message - firebaseCrashlytics collection is disabled"); + } + } + + private void logExceptionToCrashlytics(Exception exception){ + if(isCrashlyticsEnabled){ + try{ + firebaseCrashlytics.recordException(exception); + }catch (Exception e){ + Log.e(TAG, e.getMessage()); + } + }else{ + Log.e(TAG, "Cannot log exception - firebaseCrashlytics collection is disabled"); + } + } +} diff --git a/src/android/FirebasePluginMessagingService.java b/src/android/FirebasePluginMessagingService.java index 1a6ca5e63..92e6aafb3 100644 --- a/src/android/FirebasePluginMessagingService.java +++ b/src/android/FirebasePluginMessagingService.java @@ -1 +1,348 @@ -package org.apache.cordova.firebase; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.core.app.NotificationCompat; import android.util.Log; import android.app.Notification; import android.text.TextUtils; import android.content.ContentResolver; import android.graphics.Color; import com.google.firebase.crashlytics.FirebaseCrashlytics; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import java.util.Map; import java.util.Random; public class FirebasePluginMessagingService extends FirebaseMessagingService { private static final String TAG = "FirebasePlugin"; static final String defaultSmallIconName = "notification_icon"; static final String defaultLargeIconName = "notification_icon_large"; /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is called when the InstanceID token * is initially generated so this is where you would retrieve the token. */ @Override public void onNewToken(String refreshedToken) { try{ super.onNewToken(refreshedToken); Log.d(TAG, "Refreshed token: " + refreshedToken); FirebasePlugin.sendToken(refreshedToken); }catch (Exception e){ FirebasePlugin.handleExceptionWithoutContext(e); } } /** * Called when message is received. * Called IF message is a data message (i.e. NOT sent from Firebase console) * OR if message is a notification message (e.g. sent from Firebase console) AND app is in foreground. * Notification messages received while app is in background will not be processed by this method; * they are handled internally by the OS. * * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. */ @Override public void onMessageReceived(RemoteMessage remoteMessage) { try{ // [START_EXCLUDE] // There are two types of messages data messages and notification messages. Data messages are handled // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app // is in the foreground. When the app is in the background an automatically generated notification is displayed. // When the user taps on the notification they are returned to the app. Messages containing both notification // and data payloads are treated as notification messages. The Firebase console always sends notification // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options // [END_EXCLUDE] // Pass the message to the receiver manager so any registered receivers can decide to handle it boolean wasHandled = FirebasePluginMessageReceiverManager.onMessageReceived(remoteMessage); if (wasHandled) { Log.d(TAG, "Message was handled by a registered receiver"); // Don't process the message in this method. return; } if(FirebasePlugin.applicationContext == null){ FirebasePlugin.applicationContext = this.getApplicationContext(); } // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ String messageType; String title = null; String body = null; String id = null; String sound = null; String vibrate = null; String light = null; String color = null; String icon = null; String channelId = null; String visibility = null; String priority = null; boolean foregroundNotification = false; Map data = remoteMessage.getData(); if (remoteMessage.getNotification() != null) { // Notification message payload Log.i(TAG, "Received message: notification"); messageType = "notification"; id = remoteMessage.getMessageId(); RemoteMessage.Notification notification = remoteMessage.getNotification(); title = notification.getTitle(); body = notification.getBody(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { channelId = notification.getChannelId(); } sound = notification.getSound(); color = notification.getColor(); icon = notification.getIcon(); }else{ Log.i(TAG, "Received message: data"); messageType = "data"; } if (data != null) { // Data message payload if(data.containsKey("notification_foreground")){ foregroundNotification = true; } if(data.containsKey("notification_title")) title = data.get("notification_title"); if(data.containsKey("notification_body")) body = data.get("notification_body"); if(data.containsKey("notification_android_channel_id")) channelId = data.get("notification_android_channel_id"); if(data.containsKey("notification_android_id")) id = data.get("notification_android_id"); if(data.containsKey("notification_android_sound")) sound = data.get("notification_android_sound"); if(data.containsKey("notification_android_vibrate")) vibrate = data.get("notification_android_vibrate"); if(data.containsKey("notification_android_light")) light = data.get("notification_android_light"); //String containing hex ARGB color, miliseconds on, miliseconds off, example: '#FFFF00FF,1000,3000' if(data.containsKey("notification_android_color")) color = data.get("notification_android_color"); if(data.containsKey("notification_android_icon")) icon = data.get("notification_android_icon"); if(data.containsKey("notification_android_visibility")) visibility = data.get("notification_android_visibility"); if(data.containsKey("notification_android_priority")) priority = data.get("notification_android_priority"); } if (TextUtils.isEmpty(id)) { Random rand = new Random(); int n = rand.nextInt(50) + 1; id = Integer.toString(n); } Log.d(TAG, "From: " + remoteMessage.getFrom()); Log.d(TAG, "Id: " + id); Log.d(TAG, "Title: " + title); Log.d(TAG, "Body: " + body); Log.d(TAG, "Sound: " + sound); Log.d(TAG, "Vibrate: " + vibrate); Log.d(TAG, "Light: " + light); Log.d(TAG, "Color: " + color); Log.d(TAG, "Icon: " + icon); Log.d(TAG, "Channel Id: " + channelId); Log.d(TAG, "Visibility: " + visibility); Log.d(TAG, "Priority: " + priority); if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) { boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title)); sendMessage(remoteMessage, data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility); } }catch (Exception e){ FirebasePlugin.handleExceptionWithoutContext(e); } } private void sendMessage(RemoteMessage remoteMessage, Map data, String messageType, String id, String title, String body, boolean showNotification, String sound, String vibrate, String light, String color, String icon, String channelId, String priority, String visibility) { Log.d(TAG, "sendMessage(): messageType="+messageType+"; showNotification="+showNotification+"; id="+id+"; title="+title+"; body="+body+"; sound="+sound+"; vibrate="+vibrate+"; light="+light+"; color="+color+"; icon="+icon+"; channel="+channelId+"; data="+data.toString()); Bundle bundle = new Bundle(); for (String key : data.keySet()) { bundle.putString(key, data.get(key)); } bundle.putString("messageType", messageType); this.putKVInBundle("id", id, bundle); this.putKVInBundle("title", title, bundle); this.putKVInBundle("body", body, bundle); this.putKVInBundle("sound", sound, bundle); this.putKVInBundle("vibrate", vibrate, bundle); this.putKVInBundle("light", light, bundle); this.putKVInBundle("color", color, bundle); this.putKVInBundle("icon", icon, bundle); this.putKVInBundle("channel_id", channelId, bundle); this.putKVInBundle("priority", priority, bundle); this.putKVInBundle("visibility", visibility, bundle); this.putKVInBundle("show_notification", String.valueOf(showNotification), bundle); this.putKVInBundle("from", remoteMessage.getFrom(), bundle); this.putKVInBundle("collapse_key", remoteMessage.getCollapseKey(), bundle); this.putKVInBundle("sent_time", String.valueOf(remoteMessage.getSentTime()), bundle); this.putKVInBundle("ttl", String.valueOf(remoteMessage.getTtl()), bundle); if (showNotification) { Intent intent = new Intent(this, OnNotificationOpenReceiver.class); intent.putExtras(bundle); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // Channel if(channelId == null || !FirebasePlugin.channelExists(channelId)){ channelId = FirebasePlugin.defaultChannelId; } if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ Log.d(TAG, "Channel ID: "+channelId); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId); notificationBuilder .setContentTitle(title) .setContentText(body) .setStyle(new NotificationCompat.BigTextStyle().bigText(body)) .setAutoCancel(true) .setContentIntent(pendingIntent); // On Android O+ the sound/lights/vibration are determined by the channel ID if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){ // Sound if (sound == null) { Log.d(TAG, "Sound: none"); }else if (sound.equals("default")) { notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); Log.d(TAG, "Sound: default"); }else{ Uri soundPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/" + sound); Log.d(TAG, "Sound: custom=" + sound+"; path="+soundPath.toString()); notificationBuilder.setSound(soundPath); } // Light if (light != null) { try { String[] lightsComponents = color.replaceAll("\\s", "").split(","); if (lightsComponents.length == 3) { int lightArgb = Color.parseColor(lightsComponents[0]); int lightOnMs = Integer.parseInt(lightsComponents[1]); int lightOffMs = Integer.parseInt(lightsComponents[2]); notificationBuilder.setLights(lightArgb, lightOnMs, lightOffMs); Log.d(TAG, "Lights: color="+lightsComponents[0]+"; on(ms)="+lightsComponents[2]+"; off(ms)="+lightsComponents[3]); } } catch (Exception e) {} } // Vibrate if (vibrate != null){ try { String[] sVibrations = vibrate.replaceAll("\\s", "").split(","); long[] lVibrations = new long[sVibrations.length]; int i=0; for(String sVibration: sVibrations){ lVibrations[i] = Integer.parseInt(sVibration.trim()); i++; } notificationBuilder.setVibrate(lVibrations); Log.d(TAG, "Vibrate: "+vibrate); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } } // Icon int defaultSmallIconResID = getResources().getIdentifier(defaultSmallIconName, "drawable", getPackageName()); int customSmallIconResID = 0; if(icon != null){ customSmallIconResID = getResources().getIdentifier(icon, "drawable", getPackageName()); } if (customSmallIconResID != 0) { notificationBuilder.setSmallIcon(customSmallIconResID); Log.d(TAG, "Small icon: custom="+icon); }else if (defaultSmallIconResID != 0) { Log.d(TAG, "Small icon: default="+defaultSmallIconName); notificationBuilder.setSmallIcon(defaultSmallIconResID); } else { Log.d(TAG, "Small icon: application"); notificationBuilder.setSmallIcon(getApplicationInfo().icon); } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { int defaultLargeIconResID = getResources().getIdentifier(defaultLargeIconName, "drawable", getPackageName()); int customLargeIconResID = 0; if(icon != null){ customLargeIconResID = getResources().getIdentifier(icon+"_large", "drawable", getPackageName()); } int largeIconResID; if (customLargeIconResID != 0 || defaultLargeIconResID != 0) { if (customLargeIconResID != 0) { largeIconResID = customLargeIconResID; Log.d(TAG, "Large icon: custom="+icon); }else{ Log.d(TAG, "Large icon: default="+defaultLargeIconName); largeIconResID = defaultLargeIconResID; } notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), largeIconResID)); } } // Color if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { int defaultColor = getResources().getColor(getResources().getIdentifier("accent", "color", getPackageName()), null); if(color != null){ notificationBuilder.setColor(Color.parseColor(color)); Log.d(TAG, "Color: custom="+color); }else{ Log.d(TAG, "Color: default"); notificationBuilder.setColor(defaultColor); } } // Visibility int iVisibility = NotificationCompat.VISIBILITY_PUBLIC; if(visibility != null){ iVisibility = Integer.parseInt(visibility); } Log.d(TAG, "Visibility: " + iVisibility); notificationBuilder.setVisibility(iVisibility); // Priority int iPriority = NotificationCompat.PRIORITY_MAX; if(priority != null){ iPriority = Integer.parseInt(priority); } Log.d(TAG, "Priority: " + iPriority); notificationBuilder.setPriority(iPriority); // Build notification Notification notification = notificationBuilder.build(); // Display notification NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Log.d(TAG, "show notification: "+notification.toString()); notificationManager.notify(id.hashCode(), notification); } // Send to plugin FirebasePlugin.sendMessage(bundle, this.getApplicationContext()); } private void putKVInBundle(String k, String v, Bundle b){ if(v != null && !b.containsKey(k)){ b.putString(k, v); } } } \ No newline at end of file +package org.apache.cordova.firebase; + +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.graphics.BitmapFactory; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import androidx.core.app.NotificationCompat; +import android.util.Log; +import android.app.Notification; +import android.text.TextUtils; +import android.content.ContentResolver; +import android.graphics.Color; + +import com.google.firebase.crashlytics.FirebaseCrashlytics; +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; + +import java.util.Map; +import java.util.Random; + +public class FirebasePluginMessagingService extends FirebaseMessagingService { + + private static final String TAG = "FirebasePlugin"; + + static final String defaultSmallIconName = "notification_icon"; + static final String defaultLargeIconName = "notification_icon_large"; + + + /** + * Called if InstanceID token is updated. This may occur if the security of + * the previous token had been compromised. Note that this is called when the InstanceID token + * is initially generated so this is where you would retrieve the token. + */ + @Override + public void onNewToken(String refreshedToken) { + try{ + super.onNewToken(refreshedToken); + Log.d(TAG, "Refreshed token: " + refreshedToken); + FirebasePlugin.sendToken(refreshedToken); + }catch (Exception e){ + FirebasePlugin.handleExceptionWithoutContext(e); + } + } + + + /** + * Called when message is received. + * Called IF message is a data message (i.e. NOT sent from Firebase console) + * OR if message is a notification message (e.g. sent from Firebase console) AND app is in foreground. + * Notification messages received while app is in background will not be processed by this method; + * they are handled internally by the OS. + * + * @param remoteMessage Object representing the message received from Firebase Cloud Messaging. + */ + @Override + public void onMessageReceived(RemoteMessage remoteMessage) { + try{ + // [START_EXCLUDE] + // There are two types of messages data messages and notification messages. Data messages are handled + // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type + // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app + // is in the foreground. When the app is in the background an automatically generated notification is displayed. + // When the user taps on the notification they are returned to the app. Messages containing both notification + // and data payloads are treated as notification messages. The Firebase console always sends notification + // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options + // [END_EXCLUDE] + + // Pass the message to the receiver manager so any registered receivers can decide to handle it + boolean wasHandled = FirebasePluginMessageReceiverManager.onMessageReceived(remoteMessage); + if (wasHandled) { + Log.d(TAG, "Message was handled by a registered receiver"); + + // Don't process the message in this method. + return; + } + + if(FirebasePlugin.applicationContext == null){ + FirebasePlugin.applicationContext = this.getApplicationContext(); + } + + // TODO(developer): Handle FCM messages here. + // Not getting messages here? See why this may be: https://goo.gl/39bRNJ + String messageType; + String title = null; + String body = null; + String id = null; + String sound = null; + String vibrate = null; + String light = null; + String color = null; + String icon = null; + String channelId = null; + String visibility = null; + String priority = null; + boolean foregroundNotification = false; + + Map data = remoteMessage.getData(); + + if (remoteMessage.getNotification() != null) { + // Notification message payload + Log.i(TAG, "Received message: notification"); + messageType = "notification"; + id = remoteMessage.getMessageId(); + RemoteMessage.Notification notification = remoteMessage.getNotification(); + title = notification.getTitle(); + body = notification.getBody(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + channelId = notification.getChannelId(); + } + sound = notification.getSound(); + color = notification.getColor(); + icon = notification.getIcon(); + }else{ + Log.i(TAG, "Received message: data"); + messageType = "data"; + } + + if (data != null) { + // Data message payload + if(data.containsKey("notification_foreground")){ + foregroundNotification = true; + } + if(data.containsKey("notification_title")) title = data.get("notification_title"); + if(data.containsKey("notification_body")) body = data.get("notification_body"); + if(data.containsKey("notification_android_channel_id")) channelId = data.get("notification_android_channel_id"); + if(data.containsKey("notification_android_id")) id = data.get("notification_android_id"); + if(data.containsKey("notification_android_sound")) sound = data.get("notification_android_sound"); + if(data.containsKey("notification_android_vibrate")) vibrate = data.get("notification_android_vibrate"); + if(data.containsKey("notification_android_light")) light = data.get("notification_android_light"); //String containing hex ARGB color, miliseconds on, miliseconds off, example: '#FFFF00FF,1000,3000' + if(data.containsKey("notification_android_color")) color = data.get("notification_android_color"); + if(data.containsKey("notification_android_icon")) icon = data.get("notification_android_icon"); + if(data.containsKey("notification_android_visibility")) visibility = data.get("notification_android_visibility"); + if(data.containsKey("notification_android_priority")) priority = data.get("notification_android_priority"); + } + + if (TextUtils.isEmpty(id)) { + Random rand = new Random(); + int n = rand.nextInt(50) + 1; + id = Integer.toString(n); + } + + Log.d(TAG, "From: " + remoteMessage.getFrom()); + Log.d(TAG, "Id: " + id); + Log.d(TAG, "Title: " + title); + Log.d(TAG, "Body: " + body); + Log.d(TAG, "Sound: " + sound); + Log.d(TAG, "Vibrate: " + vibrate); + Log.d(TAG, "Light: " + light); + Log.d(TAG, "Color: " + color); + Log.d(TAG, "Icon: " + icon); + Log.d(TAG, "Channel Id: " + channelId); + Log.d(TAG, "Visibility: " + visibility); + Log.d(TAG, "Priority: " + priority); + + + if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) { + boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title)); + sendMessage(remoteMessage, data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility); + } + }catch (Exception e){ + FirebasePlugin.handleExceptionWithoutContext(e); + } + } + + private void sendMessage(RemoteMessage remoteMessage, Map data, String messageType, String id, String title, String body, boolean showNotification, String sound, String vibrate, String light, String color, String icon, String channelId, String priority, String visibility) { + Log.d(TAG, "sendMessage(): messageType="+messageType+"; showNotification="+showNotification+"; id="+id+"; title="+title+"; body="+body+"; sound="+sound+"; vibrate="+vibrate+"; light="+light+"; color="+color+"; icon="+icon+"; channel="+channelId+"; data="+data.toString()); + Bundle bundle = new Bundle(); + for (String key : data.keySet()) { + bundle.putString(key, data.get(key)); + } + bundle.putString("messageType", messageType); + this.putKVInBundle("id", id, bundle); + this.putKVInBundle("title", title, bundle); + this.putKVInBundle("body", body, bundle); + this.putKVInBundle("sound", sound, bundle); + this.putKVInBundle("vibrate", vibrate, bundle); + this.putKVInBundle("light", light, bundle); + this.putKVInBundle("color", color, bundle); + this.putKVInBundle("icon", icon, bundle); + this.putKVInBundle("channel_id", channelId, bundle); + this.putKVInBundle("priority", priority, bundle); + this.putKVInBundle("visibility", visibility, bundle); + this.putKVInBundle("show_notification", String.valueOf(showNotification), bundle); + this.putKVInBundle("from", remoteMessage.getFrom(), bundle); + this.putKVInBundle("collapse_key", remoteMessage.getCollapseKey(), bundle); + this.putKVInBundle("sent_time", String.valueOf(remoteMessage.getSentTime()), bundle); + this.putKVInBundle("ttl", String.valueOf(remoteMessage.getTtl()), bundle); + + if (showNotification) { + Intent intent = new Intent(this, OnNotificationOpenReceiver.class); + intent.putExtras(bundle); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT); + + // Channel + if(channelId == null || !FirebasePlugin.channelExists(channelId)){ + channelId = FirebasePlugin.defaultChannelId; + } + if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ + Log.d(TAG, "Channel ID: "+channelId); + } + + NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId); + notificationBuilder + .setContentTitle(title) + .setContentText(body) + .setStyle(new NotificationCompat.BigTextStyle().bigText(body)) + .setAutoCancel(true) + .setContentIntent(pendingIntent); + + // On Android O+ the sound/lights/vibration are determined by the channel ID + if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){ + // Sound + if (sound == null) { + Log.d(TAG, "Sound: none"); + }else if (sound.equals("default")) { + notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); + Log.d(TAG, "Sound: default"); + }else{ + Uri soundPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/" + sound); + Log.d(TAG, "Sound: custom=" + sound+"; path="+soundPath.toString()); + notificationBuilder.setSound(soundPath); + } + + // Light + if (light != null) { + try { + String[] lightsComponents = color.replaceAll("\\s", "").split(","); + if (lightsComponents.length == 3) { + int lightArgb = Color.parseColor(lightsComponents[0]); + int lightOnMs = Integer.parseInt(lightsComponents[1]); + int lightOffMs = Integer.parseInt(lightsComponents[2]); + notificationBuilder.setLights(lightArgb, lightOnMs, lightOffMs); + Log.d(TAG, "Lights: color="+lightsComponents[0]+"; on(ms)="+lightsComponents[2]+"; off(ms)="+lightsComponents[3]); + } + + } catch (Exception e) {} + } + + // Vibrate + if (vibrate != null){ + try { + String[] sVibrations = vibrate.replaceAll("\\s", "").split(","); + long[] lVibrations = new long[sVibrations.length]; + int i=0; + for(String sVibration: sVibrations){ + lVibrations[i] = Integer.parseInt(sVibration.trim()); + i++; + } + notificationBuilder.setVibrate(lVibrations); + Log.d(TAG, "Vibrate: "+vibrate); + } catch (Exception e) { + Log.e(TAG, e.getMessage()); + } + } + } + + + // Icon + int defaultSmallIconResID = getResources().getIdentifier(defaultSmallIconName, "drawable", getPackageName()); + int customSmallIconResID = 0; + if(icon != null){ + customSmallIconResID = getResources().getIdentifier(icon, "drawable", getPackageName()); + } + + if (customSmallIconResID != 0) { + notificationBuilder.setSmallIcon(customSmallIconResID); + Log.d(TAG, "Small icon: custom="+icon); + }else if (defaultSmallIconResID != 0) { + Log.d(TAG, "Small icon: default="+defaultSmallIconName); + notificationBuilder.setSmallIcon(defaultSmallIconResID); + } else { + Log.d(TAG, "Small icon: application"); + notificationBuilder.setSmallIcon(getApplicationInfo().icon); + } + + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { + int defaultLargeIconResID = getResources().getIdentifier(defaultLargeIconName, "drawable", getPackageName()); + int customLargeIconResID = 0; + if(icon != null){ + customLargeIconResID = getResources().getIdentifier(icon+"_large", "drawable", getPackageName()); + } + + int largeIconResID; + if (customLargeIconResID != 0 || defaultLargeIconResID != 0) { + if (customLargeIconResID != 0) { + largeIconResID = customLargeIconResID; + Log.d(TAG, "Large icon: custom="+icon); + }else{ + Log.d(TAG, "Large icon: default="+defaultLargeIconName); + largeIconResID = defaultLargeIconResID; + } + notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), largeIconResID)); + } + } + + // Color + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { + int defaultColor = getResources().getColor(getResources().getIdentifier("accent", "color", getPackageName()), null); + if(color != null){ + notificationBuilder.setColor(Color.parseColor(color)); + Log.d(TAG, "Color: custom="+color); + }else{ + Log.d(TAG, "Color: default"); + notificationBuilder.setColor(defaultColor); + } + } + + // Visibility + int iVisibility = NotificationCompat.VISIBILITY_PUBLIC; + if(visibility != null){ + iVisibility = Integer.parseInt(visibility); + } + Log.d(TAG, "Visibility: " + iVisibility); + notificationBuilder.setVisibility(iVisibility); + + // Priority + int iPriority = NotificationCompat.PRIORITY_MAX; + if(priority != null){ + iPriority = Integer.parseInt(priority); + } + Log.d(TAG, "Priority: " + iPriority); + notificationBuilder.setPriority(iPriority); + + + // Build notification + Notification notification = notificationBuilder.build(); + + // Display notification + NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + Log.d(TAG, "show notification: "+notification.toString()); + notificationManager.notify(id.hashCode(), notification); + } + // Send to plugin + FirebasePlugin.sendMessage(bundle, this.getApplicationContext()); + } + + private void putKVInBundle(String k, String v, Bundle b){ + if(v != null && !b.containsKey(k)){ + b.putString(k, v); + } + } +} diff --git a/src/android/build.gradle b/src/android/build.gradle index 2770e00ec..b08cef742 100644 --- a/src/android/build.gradle +++ b/src/android/build.gradle @@ -1 +1,48 @@ -buildscript { repositories { google() mavenCentral() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath 'com.google.gms:google-services:4.2.0' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1' } } repositories { mavenCentral() maven { url "https://maven.google.com" } } cdvPluginPostBuildExtras.add({ rootProject.subprojects { if (name == "app") { if (!plugins.hasPlugin('com.google.gms.google-services')) { apply { plugin com.google.gms.googleservices.GoogleServicesPlugin } // Disable strict version check as it causes problems com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true } } } // Use class instead of id (string) to be able to apply plugin from non-root gradle file apply plugin: com.google.firebase.crashlytics.buildtools.gradle.CrashlyticsPlugin android { buildTypes { release { firebaseCrashlytics { nativeSymbolUploadEnabled true } } } } }) \ No newline at end of file +buildscript { + repositories { + google() + mavenCentral() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.4.1' + classpath 'com.google.gms:google-services:4.2.0' + classpath 'com.google.firebase:firebase-crashlytics-gradle:2.1.1' + } +} +repositories { + mavenCentral() + maven { + url "https://maven.google.com" + } +} + +cdvPluginPostBuildExtras.add({ + rootProject.subprojects { + if (name == "app") { + if (!plugins.hasPlugin('com.google.gms.google-services')) { + apply { + plugin com.google.gms.googleservices.GoogleServicesPlugin + } + + // Disable strict version check as it causes problems + com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true + } + } + } + // Use class instead of id (string) to be able to apply plugin from non-root gradle file + + apply plugin: com.google.firebase.crashlytics.buildtools.gradle.CrashlyticsPlugin + + android { + buildTypes { + release { + firebaseCrashlytics { + nativeSymbolUploadEnabled true + } + } + } + } +}) + + diff --git a/src/ios/AppDelegate+FirebasePlugin.h b/src/ios/AppDelegate+FirebasePlugin.h index 1edbb12c0..0a93f08da 100644 --- a/src/ios/AppDelegate+FirebasePlugin.h +++ b/src/ios/AppDelegate+FirebasePlugin.h @@ -1 +1,11 @@ -#import "AppDelegate.h" #import @import UserNotifications; @import AuthenticationServices; @interface AppDelegate (FirebasePlugin) + (AppDelegate *) instance; @property (nonatomic, strong) NSNumber * _Nonnull applicationInBackground; @property (NS_NONATOMIC_IOSONLY, nullable, weak) id delegate; @end \ No newline at end of file +#import "AppDelegate.h" +#import + +@import UserNotifications; +@import AuthenticationServices; + +@interface AppDelegate (FirebasePlugin) ++ (AppDelegate *) instance; +@property (nonatomic, strong) NSNumber * _Nonnull applicationInBackground; +@property (NS_NONATOMIC_IOSONLY, nullable, weak) id delegate; +@end diff --git a/src/ios/AppDelegate+FirebasePlugin.m b/src/ios/AppDelegate+FirebasePlugin.m index 1251e46a7..d6fd6d74a 100644 --- a/src/ios/AppDelegate+FirebasePlugin.m +++ b/src/ios/AppDelegate+FirebasePlugin.m @@ -1 +1,566 @@ -#import "AppDelegate+FirebasePlugin.h" #import "FirebasePlugin.h" #import "Firebase.h" #import @import UserNotifications; @import FirebaseFirestore; // Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices running iOS 10 and above. // Implement FIRMessagingDelegate to receive data message via FCM for devices running iOS 10 and above. @interface AppDelegate () @end #define kApplicationInBackgroundKey @"applicationInBackground" #define kDelegateKey @"delegate" @implementation AppDelegate (FirebasePlugin) static AppDelegate* instance; + (AppDelegate*) instance { return instance; } static NSDictionary* mutableUserInfo; static FIRAuthStateDidChangeListenerHandle authStateChangeListener; static bool authStateChangeListenerInitialized = false; static bool shouldEstablishDirectChannel = false; - (void)setDelegate:(id)delegate { objc_setAssociatedObject(self, kDelegateKey, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (id)delegate { return objc_getAssociatedObject(self, kDelegateKey); } + (void)load { Method original = class_getInstanceMethod(self, @selector(application:didFinishLaunchingWithOptions:)); Method swizzled = class_getInstanceMethod(self, @selector(application:swizzledDidFinishLaunchingWithOptions:)); method_exchangeImplementations(original, swizzled); } - (void)setApplicationInBackground:(NSNumber *)applicationInBackground { objc_setAssociatedObject(self, kApplicationInBackgroundKey, applicationInBackground, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSNumber *)applicationInBackground { return objc_getAssociatedObject(self, kApplicationInBackgroundKey); } - (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self application:application swizzledDidFinishLaunchingWithOptions:launchOptions]; @try{ instance = self; // get GoogleService-Info.plist file path NSString *filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; // if file is successfully found, use it if(filePath){ [FirebasePlugin.firebasePlugin _logMessage:@"GoogleService-Info.plist found, setup: [FIRApp configureWithOptions]"]; // create firebase configure options passing .plist as content FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; // configure FIRApp with options [FIRApp configureWithOptions:options]; if([FirebasePlugin.firebasePlugin _shouldEnableCrashlytics]){ [FIRApp configure]; } } // no .plist found, try default App if (![FIRApp defaultApp] && !filePath) { [FirebasePlugin.firebasePlugin _logError:@"GoogleService-Info.plist NOT FOUND, setup: [FIRApp defaultApp]"]; [FIRApp configure]; } shouldEstablishDirectChannel = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"shouldEstablishDirectChannel"] boolValue]; // Set FCM messaging delegate [FIRMessaging messaging].delegate = self; [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; // Setup Firestore [FirebasePlugin setFirestore:[FIRFirestore firestore]]; // Setup Google SignIn [GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID; [GIDSignIn sharedInstance].delegate = self; authStateChangeListener = [[FIRAuth auth] addAuthStateDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) { @try { if(!authStateChangeListenerInitialized){ authStateChangeListenerInitialized = true; }else{ [FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthStateChange(%@)", (user != nil ? @"true": @"false")]]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } }]; // Set UNUserNotificationCenter delegate self.delegate = [UNUserNotificationCenter currentNotificationCenter].delegate; [UNUserNotificationCenter currentNotificationCenter].delegate = self; // Set NSNotificationCenter observer [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:) name:kFIRInstanceIDTokenRefreshNotification object:nil]; self.applicationInBackground = @(YES); }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } return YES; } - (void)applicationDidBecomeActive:(UIApplication *)application { self.applicationInBackground = @(NO); [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"Enter foreground: FCM direct channel = %@", shouldEstablishDirectChannel ? @"true" : @"false"]]; } - (void)applicationDidEnterBackground:(UIApplication *)application { self.applicationInBackground = @(YES); [FIRMessaging messaging].shouldEstablishDirectChannel = false; [FirebasePlugin.firebasePlugin _logMessage:@"Enter background: FCM direct channel = false"]; } # pragma mark - Google SignIn - (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error { @try{ CDVPluginResult* pluginResult; if (error == nil) { GIDAuthentication *authentication = user.authentication; FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken accessToken:authentication.accessToken]; int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; [result setValue:@"true" forKey:@"instantVerification"]; [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } if ([FirebasePlugin firebasePlugin].googleSignInCallbackId != nil) { [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].googleSignInCallbackId]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error { NSString* msg = @"Google SignIn delegate: didDisconnectWithUser"; if(error != nil){ [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"%@: %@", msg, error]]; }else{ [FirebasePlugin.firebasePlugin _logMessage:msg]; } } # pragma mark - FIRMessagingDelegate - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRegistrationToken: %@", fcmToken]]; @try{ [FirebasePlugin.firebasePlugin sendToken:fcmToken]; }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)tokenRefreshNotification:(NSNotification *)notification { // Note that this callback will be fired everytime a new token is generated, including the first // time. So if you need to retrieve the token as soon as it is available this is where that // should be done. @try{ [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { @try{ if (error == nil) { NSString *refreshedToken = result.token; [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"tokenRefreshNotification: %@", refreshedToken]]; [FirebasePlugin.firebasePlugin sendToken:refreshedToken]; }else{ [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"tokenRefreshNotification: %@", error.description]]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } }]; }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [FIRMessaging messaging].APNSToken = deviceToken; [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didRegisterForRemoteNotificationsWithDeviceToken: %@", deviceToken]]; [FirebasePlugin.firebasePlugin sendApnsToken:[FirebasePlugin.firebasePlugin hexadecimalStringFromData:deviceToken]]; // Set UNUserNotificationCenter delegate [UNUserNotificationCenter currentNotificationCenter].delegate = self; } //Tells the app that a remote notification arrived that indicates there is data to be fetched. // Called when a message arrives in the foreground and remote notifications permission has been granted - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { @try{ [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; mutableUserInfo = [userInfo mutableCopy]; NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; bool isContentAvailable = false; if([aps objectForKey:@"alert"] != nil){ isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; NSString* tap; if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && !isContentAvailable){ tap = @"background"; } [mutableUserInfo setValue:tap forKey:@"tap"]; }else{ [mutableUserInfo setValue:@"data" forKey:@"messageType"]; } [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRemoteNotification: %@", mutableUserInfo]]; completionHandler(UIBackgroundFetchResultNewData); if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && isContentAvailable){ [FirebasePlugin.firebasePlugin _logError:@"didReceiveRemoteNotification: omitting foreground notification as content-available:1 so system notification will be shown"]; }else{ [self processMessageForForegroundNotification:mutableUserInfo]; } if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] || !isContentAvailable){ [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. // Called when a data message is arrives in the foreground and remote notifications permission has been NOT been granted - (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage { @try{ [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveMessage: %@", remoteMessage.appData]]; NSDictionary* appData = [remoteMessage.appData mutableCopy]; [appData setValue:@"data" forKey:@"messageType"]; [self processMessageForForegroundNotification:appData]; // This will allow us to handle FCM data-only push messages even if the permission for push // notifications is yet missing. This will only work when the app is in the foreground. [FirebasePlugin.firebasePlugin sendNotification:appData]; }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Scans a message for keys which indicate a notification should be shown. // If found, extracts relevant keys and uses then to display a local notification -(void)processMessageForForegroundNotification:(NSDictionary*)messageData { bool showForegroundNotification = [messageData objectForKey:@"notification_foreground"]; if(!showForegroundNotification){ return; } NSString* title = nil; NSString* body = nil; NSString* sound = nil; NSNumber* badge = nil; // Extract APNS notification keys NSDictionary* aps = [messageData objectForKey:@"aps"]; if([aps objectForKey:@"alert"] != nil){ NSDictionary* alert = [aps objectForKey:@"alert"]; if([alert objectForKey:@"title"] != nil){ title = [alert objectForKey:@"title"]; } if([alert objectForKey:@"body"] != nil){ body = [alert objectForKey:@"body"]; } if([aps objectForKey:@"sound"] != nil){ sound = [aps objectForKey:@"sound"]; } if([aps objectForKey:@"badge"] != nil){ badge = [aps objectForKey:@"badge"]; } } // Extract data notification keys if([messageData objectForKey:@"notification_title"] != nil){ title = [messageData objectForKey:@"notification_title"]; } if([messageData objectForKey:@"notification_body"] != nil){ body = [messageData objectForKey:@"notification_body"]; } if([messageData objectForKey:@"notification_ios_sound"] != nil){ sound = [messageData objectForKey:@"notification_ios_sound"]; } if([messageData objectForKey:@"notification_ios_badge"] != nil){ badge = [messageData objectForKey:@"notification_ios_badge"]; } if(title == nil || body == nil){ return; } [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { @try{ if (settings.alertSetting == UNNotificationSettingEnabled) { UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; objNotificationContent.title = [NSString localizedUserNotificationStringForKey:title arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:body arguments:nil]; NSDictionary* alert = [[NSDictionary alloc] initWithObjectsAndKeys: title, @"title", body, @"body" , nil]; NSMutableDictionary* aps = [[NSMutableDictionary alloc] initWithObjectsAndKeys: alert, @"alert", nil]; if(![sound isKindOfClass:[NSString class]] || [sound isEqualToString:@"default"]){ objNotificationContent.sound = [UNNotificationSound defaultSound]; [aps setValue:sound forKey:@"sound"]; }else if(sound != nil){ objNotificationContent.sound = [UNNotificationSound soundNamed:sound]; [aps setValue:sound forKey:@"sound"]; } if(badge != nil){ [aps setValue:badge forKey:@"badge"]; } NSString* messageType = @"data"; if([mutableUserInfo objectForKey:@"messageType"] != nil){ messageType = [mutableUserInfo objectForKey:@"messageType"]; } NSDictionary* userInfo = [[NSDictionary alloc] initWithObjectsAndKeys: @"true", @"notification_foreground", messageType, @"messageType", aps, @"aps" , nil]; objNotificationContent.userInfo = userInfo; UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1f repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:objNotificationContent trigger:trigger]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { [FirebasePlugin.firebasePlugin _logMessage:@"Local Notification succeeded"]; } else { [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"Local Notification failed: %@", error.description]]; } }]; }else{ [FirebasePlugin.firebasePlugin _logError:@"processMessageForForegroundNotification: cannot show notification as permission denied"]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } }]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description]]; } // Asks the delegate how to handle a notification that arrived while the app was running in the foreground // Called when an APS notification arrives when app is in foreground - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { @try{ [self.delegate userNotificationCenter:center willPresentNotification:notification withCompletionHandler:completionHandler]; if (![notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as not a supported UNNotificationTrigger"]; return; } [[FIRMessaging messaging] appDidReceiveMessage:notification.request.content.userInfo]; mutableUserInfo = [notification.request.content.userInfo mutableCopy]; NSString* messageType = [mutableUserInfo objectForKey:@"messageType"]; if(![messageType isEqualToString:@"data"]){ [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; } // Print full message. [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: %@", mutableUserInfo]]; NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; bool isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; if(isContentAvailable){ [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as content-available:1 so system notification will be shown"]; return; } bool showForegroundNotification = [mutableUserInfo objectForKey:@"notification_foreground"]; bool hasAlert = [aps objectForKey:@"alert"] != nil; bool hasBadge = [aps objectForKey:@"badge"] != nil; bool hasSound = [aps objectForKey:@"sound"] != nil; if(showForegroundNotification){ [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: foreground notification alert=%@, badge=%@, sound=%@", hasAlert ? @"YES" : @"NO", hasBadge ? @"YES" : @"NO", hasSound ? @"YES" : @"NO"]]; if(hasAlert && hasBadge && hasSound){ completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); }else if(hasAlert && hasBadge){ completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge); }else if(hasAlert && hasSound){ completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound); }else if(hasBadge && hasSound){ completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); }else if(hasAlert){ completionHandler(UNNotificationPresentationOptionAlert); }else if(hasBadge){ completionHandler(UNNotificationPresentationOptionBadge); }else if(hasSound){ completionHandler(UNNotificationPresentationOptionSound); } }else{ [FirebasePlugin.firebasePlugin _logMessage:@"willPresentNotification: foreground notification not set"]; } if(![messageType isEqualToString:@"data"]){ [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Asks the delegate to process the user's response to a delivered notification. // Called when user taps on system notification - (void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { @try{ [self.delegate userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![response.notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ [FirebasePlugin.firebasePlugin _logMessage:@"didReceiveNotificationResponse: aborting as not a supported UNNotificationTrigger"]; return; } [[FIRMessaging messaging] appDidReceiveMessage:response.notification.request.content.userInfo]; mutableUserInfo = [response.notification.request.content.userInfo mutableCopy]; NSString* tap; if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]]){ tap = @"background"; }else{ tap = @"foreground"; } [mutableUserInfo setValue:tap forKey:@"tap"]; if([mutableUserInfo objectForKey:@"messageType"] == nil){ [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; } // Print full message. [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"didReceiveNotificationResponse: %@", mutableUserInfo]]; [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; completionHandler(); }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } // Receive data message on iOS 10 devices. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { // Print full message [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"applicationReceivedRemoteMessage: %@", [remoteMessage appData]]]; } // Apple Sign In - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) { @try{ CDVPluginResult* pluginResult; NSString* errorMessage = nil; FIROAuthCredential *credential; if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) { ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential; NSString *rawNonce = [FirebasePlugin appleSignInNonce]; if(rawNonce == nil){ errorMessage = @"Invalid state: A login callback was received, but no login request was sent."; }else if (appleIDCredential.identityToken == nil) { errorMessage = @"Unable to fetch identity token."; }else{ NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding]; if (idToken == nil) { errorMessage = [NSString stringWithFormat:@"Unable to serialize id token from data: %@", appleIDCredential.identityToken]; }else{ // Initialize a Firebase credential. credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" IDToken:idToken rawNonce:rawNonce]; int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; [result setValue:@"true" forKey:@"instantVerification"]; [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; } } if(errorMessage != nil){ [FirebasePlugin.firebasePlugin _logError:errorMessage]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; } if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; } } }@catch (NSException *exception) { [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; } } - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) { NSString* errorMessage = [NSString stringWithFormat:@"Sign in with Apple errored: %@", error]; [FirebasePlugin.firebasePlugin _logError:errorMessage]; if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; } } - (nonnull ASPresentationAnchor)presentationAnchorForAuthorizationController:(nonnull ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){ return self.viewController.view.window; } @end \ No newline at end of file +#import "AppDelegate+FirebasePlugin.h" +#import "FirebasePlugin.h" +#import "Firebase.h" +#import + + +@import UserNotifications; +@import FirebaseFirestore; + +// Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices running iOS 10 and above. +// Implement FIRMessagingDelegate to receive data message via FCM for devices running iOS 10 and above. +@interface AppDelegate () +@end + +#define kApplicationInBackgroundKey @"applicationInBackground" +#define kDelegateKey @"delegate" + +@implementation AppDelegate (FirebasePlugin) + +static AppDelegate* instance; + ++ (AppDelegate*) instance { + return instance; +} + +static NSDictionary* mutableUserInfo; +static FIRAuthStateDidChangeListenerHandle authStateChangeListener; +static bool authStateChangeListenerInitialized = false; +static bool shouldEstablishDirectChannel = false; + +- (void)setDelegate:(id)delegate { + objc_setAssociatedObject(self, kDelegateKey, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (id)delegate { + return objc_getAssociatedObject(self, kDelegateKey); +} + ++ (void)load { + Method original = class_getInstanceMethod(self, @selector(application:didFinishLaunchingWithOptions:)); + Method swizzled = class_getInstanceMethod(self, @selector(application:swizzledDidFinishLaunchingWithOptions:)); + method_exchangeImplementations(original, swizzled); +} + +- (void)setApplicationInBackground:(NSNumber *)applicationInBackground { + objc_setAssociatedObject(self, kApplicationInBackgroundKey, applicationInBackground, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (NSNumber *)applicationInBackground { + return objc_getAssociatedObject(self, kApplicationInBackgroundKey); +} + +- (BOOL)application:(UIApplication *)application swizzledDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + [self application:application swizzledDidFinishLaunchingWithOptions:launchOptions]; + + @try{ + instance = self; + + // get GoogleService-Info.plist file path + NSString *filePath = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]; + + // if file is successfully found, use it + if(filePath){ + [FirebasePlugin.firebasePlugin _logMessage:@"GoogleService-Info.plist found, setup: [FIRApp configureWithOptions]"]; + // create firebase configure options passing .plist as content + FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath]; + + // configure FIRApp with options + [FIRApp configureWithOptions:options]; + if([FirebasePlugin.firebasePlugin _shouldEnableCrashlytics]){ + [FIRApp configure]; + } + } + + // no .plist found, try default App + if (![FIRApp defaultApp] && !filePath) { + [FirebasePlugin.firebasePlugin _logError:@"GoogleService-Info.plist NOT FOUND, setup: [FIRApp defaultApp]"]; + [FIRApp configure]; + } + + shouldEstablishDirectChannel = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"shouldEstablishDirectChannel"] boolValue]; + + // Set FCM messaging delegate + [FIRMessaging messaging].delegate = self; + [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; + + // Setup Firestore + [FirebasePlugin setFirestore:[FIRFirestore firestore]]; + + // Setup Google SignIn + [GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID; + [GIDSignIn sharedInstance].delegate = self; + + authStateChangeListener = [[FIRAuth auth] addAuthStateDidChangeListener:^(FIRAuth * _Nonnull auth, FIRUser * _Nullable user) { + @try { + if(!authStateChangeListenerInitialized){ + authStateChangeListenerInitialized = true; + }else{ + [FirebasePlugin.firebasePlugin executeGlobalJavascript:[NSString stringWithFormat:@"FirebasePlugin._onAuthStateChange(%@)", (user != nil ? @"true": @"false")]]; + } + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } + }]; + + // Set UNUserNotificationCenter delegate + self.delegate = [UNUserNotificationCenter currentNotificationCenter].delegate; + [UNUserNotificationCenter currentNotificationCenter].delegate = self; + + // Set NSNotificationCenter observer + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:) + name:kFIRInstanceIDTokenRefreshNotification object:nil]; + + self.applicationInBackground = @(YES); + + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } + + return YES; +} + +- (void)applicationDidBecomeActive:(UIApplication *)application { + self.applicationInBackground = @(NO); + [FIRMessaging messaging].shouldEstablishDirectChannel = shouldEstablishDirectChannel; + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"Enter foreground: FCM direct channel = %@", shouldEstablishDirectChannel ? @"true" : @"false"]]; +} + +- (void)applicationDidEnterBackground:(UIApplication *)application { + self.applicationInBackground = @(YES); + [FIRMessaging messaging].shouldEstablishDirectChannel = false; + [FirebasePlugin.firebasePlugin _logMessage:@"Enter background: FCM direct channel = false"]; +} + +# pragma mark - Google SignIn +- (void)signIn:(GIDSignIn *)signIn +didSignInForUser:(GIDGoogleUser *)user + withError:(NSError *)error { + @try{ + CDVPluginResult* pluginResult; + if (error == nil) { + GIDAuthentication *authentication = user.authentication; + FIRAuthCredential *credential = + [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken + accessToken:authentication.accessToken]; + + int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; + NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; + [result setValue:@"true" forKey:@"instantVerification"]; + [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } + if ([FirebasePlugin firebasePlugin].googleSignInCallbackId != nil) { + [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].googleSignInCallbackId]; + } + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +- (void)signIn:(GIDSignIn *)signIn +didDisconnectWithUser:(GIDGoogleUser *)user + withError:(NSError *)error { + NSString* msg = @"Google SignIn delegate: didDisconnectWithUser"; + if(error != nil){ + [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"%@: %@", msg, error]]; + }else{ + [FirebasePlugin.firebasePlugin _logMessage:msg]; + } +} + +# pragma mark - FIRMessagingDelegate +- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRegistrationToken: %@", fcmToken]]; + @try{ + [FirebasePlugin.firebasePlugin sendToken:fcmToken]; + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +- (void)tokenRefreshNotification:(NSNotification *)notification { + // Note that this callback will be fired everytime a new token is generated, including the first + // time. So if you need to retrieve the token as soon as it is available this is where that + // should be done. + @try{ + [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, + NSError * _Nullable error) { + @try{ + if (error == nil) { + NSString *refreshedToken = result.token; + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"tokenRefreshNotification: %@", refreshedToken]]; + [FirebasePlugin.firebasePlugin sendToken:refreshedToken]; + }else{ + [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"tokenRefreshNotification: %@", error.description]]; + } + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } + }]; + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { + [FIRMessaging messaging].APNSToken = deviceToken; + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didRegisterForRemoteNotificationsWithDeviceToken: %@", deviceToken]]; + [FirebasePlugin.firebasePlugin sendApnsToken:[FirebasePlugin.firebasePlugin hexadecimalStringFromData:deviceToken]]; + + // Set UNUserNotificationCenter delegate + [UNUserNotificationCenter currentNotificationCenter].delegate = self; +} + +//Tells the app that a remote notification arrived that indicates there is data to be fetched. +// Called when a message arrives in the foreground and remote notifications permission has been granted +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo + fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { + + @try{ + [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; + mutableUserInfo = [userInfo mutableCopy]; + NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; + bool isContentAvailable = false; + if([aps objectForKey:@"alert"] != nil){ + isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; + [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; + NSString* tap; + if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && !isContentAvailable){ + tap = @"background"; + } + [mutableUserInfo setValue:tap forKey:@"tap"]; + }else{ + [mutableUserInfo setValue:@"data" forKey:@"messageType"]; + } + + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveRemoteNotification: %@", mutableUserInfo]]; + + completionHandler(UIBackgroundFetchResultNewData); + if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] && isContentAvailable){ + [FirebasePlugin.firebasePlugin _logError:@"didReceiveRemoteNotification: omitting foreground notification as content-available:1 so system notification will be shown"]; + }else{ + [self processMessageForForegroundNotification:mutableUserInfo]; + } + if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]] || !isContentAvailable){ + [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; + } + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. +// Called when a data message is arrives in the foreground and remote notifications permission has been NOT been granted +- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage { + @try{ + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"didReceiveMessage: %@", remoteMessage.appData]]; + + NSDictionary* appData = [remoteMessage.appData mutableCopy]; + [appData setValue:@"data" forKey:@"messageType"]; + [self processMessageForForegroundNotification:appData]; + + // This will allow us to handle FCM data-only push messages even if the permission for push + // notifications is yet missing. This will only work when the app is in the foreground. + [FirebasePlugin.firebasePlugin sendNotification:appData]; + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +// Scans a message for keys which indicate a notification should be shown. +// If found, extracts relevant keys and uses then to display a local notification +-(void)processMessageForForegroundNotification:(NSDictionary*)messageData { + bool showForegroundNotification = [messageData objectForKey:@"notification_foreground"]; + if(!showForegroundNotification){ + return; + } + + NSString* title = nil; + NSString* body = nil; + NSString* sound = nil; + NSNumber* badge = nil; + + // Extract APNS notification keys + NSDictionary* aps = [messageData objectForKey:@"aps"]; + if([aps objectForKey:@"alert"] != nil){ + NSDictionary* alert = [aps objectForKey:@"alert"]; + if([alert objectForKey:@"title"] != nil){ + title = [alert objectForKey:@"title"]; + } + if([alert objectForKey:@"body"] != nil){ + body = [alert objectForKey:@"body"]; + } + if([aps objectForKey:@"sound"] != nil){ + sound = [aps objectForKey:@"sound"]; + } + if([aps objectForKey:@"badge"] != nil){ + badge = [aps objectForKey:@"badge"]; + } + } + + // Extract data notification keys + if([messageData objectForKey:@"notification_title"] != nil){ + title = [messageData objectForKey:@"notification_title"]; + } + if([messageData objectForKey:@"notification_body"] != nil){ + body = [messageData objectForKey:@"notification_body"]; + } + if([messageData objectForKey:@"notification_ios_sound"] != nil){ + sound = [messageData objectForKey:@"notification_ios_sound"]; + } + if([messageData objectForKey:@"notification_ios_badge"] != nil){ + badge = [messageData objectForKey:@"notification_ios_badge"]; + } + + if(title == nil || body == nil){ + return; + } + + [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { + @try{ + if (settings.alertSetting == UNNotificationSettingEnabled) { + UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; + objNotificationContent.title = [NSString localizedUserNotificationStringForKey:title arguments:nil]; + objNotificationContent.body = [NSString localizedUserNotificationStringForKey:body arguments:nil]; + + NSDictionary* alert = [[NSDictionary alloc] initWithObjectsAndKeys: + title, @"title", + body, @"body" + , nil]; + NSMutableDictionary* aps = [[NSMutableDictionary alloc] initWithObjectsAndKeys: + alert, @"alert", + nil]; + + if(![sound isKindOfClass:[NSString class]] || [sound isEqualToString:@"default"]){ + objNotificationContent.sound = [UNNotificationSound defaultSound]; + [aps setValue:sound forKey:@"sound"]; + }else if(sound != nil){ + objNotificationContent.sound = [UNNotificationSound soundNamed:sound]; + [aps setValue:sound forKey:@"sound"]; + } + + if(badge != nil){ + [aps setValue:badge forKey:@"badge"]; + } + + NSString* messageType = @"data"; + if([mutableUserInfo objectForKey:@"messageType"] != nil){ + messageType = [mutableUserInfo objectForKey:@"messageType"]; + } + + NSDictionary* userInfo = [[NSDictionary alloc] initWithObjectsAndKeys: + @"true", @"notification_foreground", + messageType, @"messageType", + aps, @"aps" + , nil]; + + objNotificationContent.userInfo = userInfo; + + UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1f repeats:NO]; + UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:objNotificationContent trigger:trigger]; + [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { + if (!error) { + [FirebasePlugin.firebasePlugin _logMessage:@"Local Notification succeeded"]; + } else { + [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"Local Notification failed: %@", error.description]]; + } + }]; + }else{ + [FirebasePlugin.firebasePlugin _logError:@"processMessageForForegroundNotification: cannot show notification as permission denied"]; + } + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } + }]; +} + +- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { + [FirebasePlugin.firebasePlugin _logError:[NSString stringWithFormat:@"didFailToRegisterForRemoteNotificationsWithError: %@", error.description]]; +} + +// Asks the delegate how to handle a notification that arrived while the app was running in the foreground +// Called when an APS notification arrives when app is in foreground +- (void)userNotificationCenter:(UNUserNotificationCenter *)center + willPresentNotification:(UNNotification *)notification + withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler { + + @try{ + [self.delegate userNotificationCenter:center + willPresentNotification:notification + withCompletionHandler:completionHandler]; + + if (![notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ + [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as not a supported UNNotificationTrigger"]; + return; + } + + [[FIRMessaging messaging] appDidReceiveMessage:notification.request.content.userInfo]; + + mutableUserInfo = [notification.request.content.userInfo mutableCopy]; + + NSString* messageType = [mutableUserInfo objectForKey:@"messageType"]; + if(![messageType isEqualToString:@"data"]){ + [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; + } + + // Print full message. + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: %@", mutableUserInfo]]; + + + NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; + bool isContentAvailable = [[aps objectForKey:@"content-available"] isEqualToNumber:[NSNumber numberWithInt:1]]; + if(isContentAvailable){ + [FirebasePlugin.firebasePlugin _logError:@"willPresentNotification: aborting as content-available:1 so system notification will be shown"]; + return; + } + + bool showForegroundNotification = [mutableUserInfo objectForKey:@"notification_foreground"]; + bool hasAlert = [aps objectForKey:@"alert"] != nil; + bool hasBadge = [aps objectForKey:@"badge"] != nil; + bool hasSound = [aps objectForKey:@"sound"] != nil; + + if(showForegroundNotification){ + [FirebasePlugin.firebasePlugin _logMessage:[NSString stringWithFormat:@"willPresentNotification: foreground notification alert=%@, badge=%@, sound=%@", hasAlert ? @"YES" : @"NO", hasBadge ? @"YES" : @"NO", hasSound ? @"YES" : @"NO"]]; + if(hasAlert && hasBadge && hasSound){ + completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); + }else if(hasAlert && hasBadge){ + completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionBadge); + }else if(hasAlert && hasSound){ + completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound); + }else if(hasBadge && hasSound){ + completionHandler(UNNotificationPresentationOptionBadge + UNNotificationPresentationOptionSound); + }else if(hasAlert){ + completionHandler(UNNotificationPresentationOptionAlert); + }else if(hasBadge){ + completionHandler(UNNotificationPresentationOptionBadge); + }else if(hasSound){ + completionHandler(UNNotificationPresentationOptionSound); + } + }else{ + [FirebasePlugin.firebasePlugin _logMessage:@"willPresentNotification: foreground notification not set"]; + } + + if(![messageType isEqualToString:@"data"]){ + [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; + } + + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +// Asks the delegate to process the user's response to a delivered notification. +// Called when user taps on system notification +- (void) userNotificationCenter:(UNUserNotificationCenter *)center + didReceiveNotificationResponse:(UNNotificationResponse *)response + withCompletionHandler:(void (^)(void))completionHandler +{ + @try{ + [self.delegate userNotificationCenter:center + didReceiveNotificationResponse:response + withCompletionHandler:completionHandler]; + + if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![response.notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ + [FirebasePlugin.firebasePlugin _logMessage:@"didReceiveNotificationResponse: aborting as not a supported UNNotificationTrigger"]; + return; + } + + [[FIRMessaging messaging] appDidReceiveMessage:response.notification.request.content.userInfo]; + + mutableUserInfo = [response.notification.request.content.userInfo mutableCopy]; + + NSString* tap; + if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]]){ + tap = @"background"; + }else{ + tap = @"foreground"; + + } + [mutableUserInfo setValue:tap forKey:@"tap"]; + if([mutableUserInfo objectForKey:@"messageType"] == nil){ + [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; + } + + + // Print full message. + [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"didReceiveNotificationResponse: %@", mutableUserInfo]]; + + [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; + + completionHandler(); + + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +// Receive data message on iOS 10 devices. +- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { + // Print full message + [FirebasePlugin.firebasePlugin _logInfo:[NSString stringWithFormat:@"applicationReceivedRemoteMessage: %@", [remoteMessage appData]]]; +} + +// Apple Sign In +- (void)authorizationController:(ASAuthorizationController *)controller + didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) { + @try{ + CDVPluginResult* pluginResult; + NSString* errorMessage = nil; + FIROAuthCredential *credential; + + if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) { + ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential; + NSString *rawNonce = [FirebasePlugin appleSignInNonce]; + if(rawNonce == nil){ + errorMessage = @"Invalid state: A login callback was received, but no login request was sent."; + }else if (appleIDCredential.identityToken == nil) { + errorMessage = @"Unable to fetch identity token."; + }else{ + NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken + encoding:NSUTF8StringEncoding]; + if (idToken == nil) { + errorMessage = [NSString stringWithFormat:@"Unable to serialize id token from data: %@", appleIDCredential.identityToken]; + }else{ + // Initialize a Firebase credential. + credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" + IDToken:idToken + rawNonce:rawNonce]; + + int key = [[FirebasePlugin firebasePlugin] saveAuthCredential:credential]; + NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; + [result setValue:@"true" forKey:@"instantVerification"]; + [result setValue:[NSNumber numberWithInt:key] forKey:@"id"]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; + } + } + if(errorMessage != nil){ + [FirebasePlugin.firebasePlugin _logError:errorMessage]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; + } + if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { + [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; + } + } + }@catch (NSException *exception) { + [FirebasePlugin.firebasePlugin handlePluginExceptionWithoutContext:exception]; + } +} + +- (void)authorizationController:(ASAuthorizationController *)controller + didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) { + NSString* errorMessage = [NSString stringWithFormat:@"Sign in with Apple errored: %@", error]; + [FirebasePlugin.firebasePlugin _logError:errorMessage]; + if ([FirebasePlugin firebasePlugin].appleSignInCallbackId != nil) { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; + [[FirebasePlugin firebasePlugin].commandDelegate sendPluginResult:pluginResult callbackId:[FirebasePlugin firebasePlugin].appleSignInCallbackId]; + } +} + +- (nonnull ASPresentationAnchor)presentationAnchorForAuthorizationController:(nonnull ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){ + return self.viewController.view.window; +} + +@end diff --git a/src/ios/FirebasePlugin.m b/src/ios/FirebasePlugin.m index 9bc00f36e..1a184a1f1 100644 --- a/src/ios/FirebasePlugin.m +++ b/src/ios/FirebasePlugin.m @@ -1 +1,1778 @@ -#import "FirebasePlugin.h" #import "FirebasePluginMessageReceiverManager.h" #import "AppDelegate+FirebasePlugin.h" #import #import "AppDelegate.h" #import @import FirebaseInstanceID; @import FirebaseMessaging; @import FirebaseAnalytics; @import FirebaseRemoteConfig; @import FirebasePerformance; @import FirebaseAuth; @import UserNotifications; @import CommonCrypto; @import AuthenticationServices; @implementation FirebasePlugin @synthesize notificationCallbackId; @synthesize tokenRefreshCallbackId; @synthesize apnsTokenRefreshCallbackId; @synthesize googleSignInCallbackId; @synthesize appleSignInCallbackId; @synthesize notificationStack; @synthesize traces; static NSString*const LOG_TAG = @"FirebasePlugin[native]"; static NSInteger const kNotificationStackSize = 10; static NSString*const FIREBASE_CRASHLYTICS_COLLECTION_ENABLED = @"FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"; static NSString*const FIREBASE_ANALYTICS_COLLECTION_ENABLED = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED"; static NSString*const FIREBASE_PERFORMANCE_COLLECTION_ENABLED = @"FIREBASE_PERFORMANCE_COLLECTION_ENABLED"; static FirebasePlugin* firebasePlugin; static BOOL registeredForRemoteNotifications = NO; static BOOL isCrashlyticsEnabled = NO; static NSMutableDictionary* authCredentials; static NSString* currentNonce; // used for Apple Sign In static FIRFirestore* firestore; static NSUserDefaults* preferences; static NSDictionary* googlePlist; + (FirebasePlugin*) firebasePlugin { return firebasePlugin; } + (NSString*) appleSignInNonce { return currentNonce; } + (void) setFirestore:(FIRFirestore*) firestoreInstance{ firestore = firestoreInstance; } // @override abstract - (void)pluginInitialize { NSLog(@"Starting Firebase plugin"); firebasePlugin = self; @try { preferences = [NSUserDefaults standardUserDefaults]; googlePlist = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]]; if(![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ isCrashlyticsEnabled = [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; }else{ isCrashlyticsEnabled = YES; [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:YES]; } if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:YES]; } if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:YES]; } // Check for permission and register for remote notifications if granted [self _hasPermission:^(BOOL result) {}]; [GIDSignIn sharedInstance].presentingViewController = self.viewController; authCredentials = [[NSMutableDictionary alloc] init]; }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } } // @override abstract - (void)handleOpenURL:(NSNotification*)notification{ NSURL* url = [notification object]; [[GIDSignIn sharedInstance] handleURL:url]; } - (void)setAutoInitEnabled:(CDVInvokedUrlCommand *)command { @try { bool enabled = [[command.arguments objectAtIndex:0] boolValue]; [self runOnMainThread:^{ @try { [FIRMessaging messaging].autoInitEnabled = enabled; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)isAutoInitEnabled:(CDVInvokedUrlCommand *)command { @try { [self runOnMainThread:^{ @try { bool enabled =[FIRMessaging messaging].isAutoInitEnabled; CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } /* * Remote notifications */ - (void)getId:(CDVInvokedUrlCommand *)command { __block CDVPluginResult *pluginResult; FIRInstanceIDHandler handler = ^(NSString *_Nullable instID, NSError *_Nullable error) { @try { if (error) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:instID]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }; @try { [[FIRInstanceID instanceID] getIDWithHandler:handler]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getToken:(CDVInvokedUrlCommand *)command { @try { [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { CDVPluginResult* pluginResult; if (error == nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result.token]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getAPNSToken:(CDVInvokedUrlCommand *)command { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self getAPNSToken]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (NSString *)getAPNSToken { NSString* hexToken = nil; NSData* apnsToken = [FIRMessaging messaging].APNSToken; if (apnsToken) { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 // [deviceToken description] Starting with iOS 13 device token is like "{length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f ... 28f10282 14af515f }" hexToken = [self hexadecimalStringFromData:apnsToken]; #else hexToken = [[apnsToken.description componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet]invertedSet]]componentsJoinedByString:@""]; #endif } return hexToken; } - (NSString *)hexadecimalStringFromData:(NSData *)data { NSUInteger dataLength = data.length; if (dataLength == 0) { return nil; } const unsigned char *dataBuffer = data.bytes; NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)]; for (int i = 0; i < dataLength; ++i) { [hexString appendFormat:@"%02x", dataBuffer[i]]; } return [hexString copy]; } - (void)hasPermission:(CDVInvokedUrlCommand *)command { @try { [self _hasPermission:^(BOOL enabled) { CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } -(void)_hasPermission:(void (^)(BOOL result))completeBlock { @try { [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { @try { BOOL enabled = NO; if (settings.alertSetting == UNNotificationSettingEnabled) { enabled = YES; [self registerForRemoteNotifications]; } NSLog(@"_hasPermission: %@", enabled ? @"YES" : @"NO"); completeBlock(enabled); }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } } - (void)grantPermission:(CDVInvokedUrlCommand *)command { NSLog(@"grantPermission"); @try { [self _hasPermission:^(BOOL enabled) { @try { if(enabled){ NSString* message = @"Permission is already granted - call hasPermission() to check before calling grantPermission()"; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }else{ [UNUserNotificationCenter currentNotificationCenter].delegate = (id _Nullable) self; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { @try { NSLog(@"requestAuthorizationWithOptions: granted=%@", granted ? @"YES" : @"NO"); CDVPluginResult* pluginResult; if (error == nil) { if(granted){ [self registerForRemoteNotifications]; } pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:granted]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } ]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)registerForRemoteNotifications { NSLog(@"registerForRemoteNotifications"); if(registeredForRemoteNotifications) return; [self runOnMainThread:^{ @try { [[UIApplication sharedApplication] registerForRemoteNotifications]; }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } registeredForRemoteNotifications = YES; }]; } - (void)setBadgeNumber:(CDVInvokedUrlCommand *)command { @try { int number = [[command.arguments objectAtIndex:0] intValue]; [self runOnMainThread:^{ @try { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:number]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getBadgeNumber:(CDVInvokedUrlCommand *)command { [self runOnMainThread:^{ @try { long badge = [[UIApplication sharedApplication] applicationIconBadgeNumber]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:badge]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)subscribe:(CDVInvokedUrlCommand *)command { @try { NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; [[FIRMessaging messaging] subscribeToTopic: topic]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)unsubscribe:(CDVInvokedUrlCommand *)command { @try { NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; [[FIRMessaging messaging] unsubscribeFromTopic: topic]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)unregister:(CDVInvokedUrlCommand *)command { @try { [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) { CDVPluginResult* pluginResult; if (error == nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)onMessageReceived:(CDVInvokedUrlCommand *)command { @try { self.notificationCallbackId = command.callbackId; if (self.notificationStack != nil && [self.notificationStack count]) { for (NSDictionary *userInfo in self.notificationStack) { [self sendNotification:userInfo]; } [self.notificationStack removeAllObjects]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)onTokenRefresh:(CDVInvokedUrlCommand *)command { self.tokenRefreshCallbackId = command.callbackId; @try { [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { @try { if (error == nil) { if (result.token != nil && error == nil) { [self sendToken:result.token]; } }else{ CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)onApnsTokenReceived:(CDVInvokedUrlCommand *)command { self.apnsTokenRefreshCallbackId = command.callbackId; @try { NSString* apnsToken = [self getAPNSToken]; if(apnsToken != nil){ [self sendApnsToken:apnsToken]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)sendNotification:(NSDictionary *)userInfo { @try { if([FirebasePluginMessageReceiverManager sendNotification:userInfo]){ [self _logMessage:@"Message handled by custom receiver"]; return; } if (self.notificationCallbackId != nil) { CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self.notificationCallbackId]; } else { if (!self.notificationStack) { self.notificationStack = [[NSMutableArray alloc] init]; } // stack notifications until a callback has been registered [self.notificationStack addObject:userInfo]; if ([self.notificationStack count] >= kNotificationStackSize) { [self.notificationStack removeLastObject]; } } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :self.commandDelegate]; } } - (void)sendToken:(NSString *)token { @try { if (self.tokenRefreshCallbackId != nil) { CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self.tokenRefreshCallbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :self.commandDelegate]; } } - (void)sendApnsToken:(NSString *)token { @try { if (self.apnsTokenRefreshCallbackId != nil) { CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self.apnsTokenRefreshCallbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :self.commandDelegate]; } } - (void)clearAllNotifications:(CDVInvokedUrlCommand *)command { [self runOnMainThread:^{ @try { [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1]; [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Authentication */ - (void)verifyPhoneNumber:(CDVInvokedUrlCommand *)command { NSString* number = [command.arguments objectAtIndex:0]; @try { [[FIRPhoneAuthProvider provider] verifyPhoneNumber:number UIDelegate:nil completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) { @try { CDVPluginResult* pluginResult; if (error) { // Verification code not sent. pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } else { // Successful. NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; [result setValue:@"false" forKey:@"instantVerification"]; [result setValue:verificationID forKey:@"verificationId"]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)createUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { @try { NSString* email = [command.arguments objectAtIndex:0]; NSString* password = [command.arguments objectAtIndex:1]; [[FIRAuth auth] createUserWithEmail:email password:password completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { @try { NSString* email = [command.arguments objectAtIndex:0]; NSString* password = [command.arguments objectAtIndex:1]; [[FIRAuth auth] signInWithEmail:email password:password completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInUserWithCustomToken:(CDVInvokedUrlCommand*)command { @try { NSString* customToken = [command.arguments objectAtIndex:0]; [[FIRAuth auth] signInWithCustomToken:customToken completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInUserAnonymously:(CDVInvokedUrlCommand*)command { @try { [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { @try { [self handleAuthResult:authResult error:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)authenticateUserWithGoogle:(CDVInvokedUrlCommand*)command{ @try { self.googleSignInCallbackId = command.callbackId; [[GIDSignIn sharedInstance] signIn]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; [pluginResult setKeepCallbackAsBool:YES]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)authenticateUserWithApple:(CDVInvokedUrlCommand*)command{ @try { CDVPluginResult *pluginResult; if (@available(iOS 13.0, *)) { self.appleSignInCallbackId = command.callbackId; [self startSignInWithAppleFlow]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; [pluginResult setKeepCallbackAsBool:YES]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"OS version is too low - Apple Sign In requires iOS 13.0+"]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signInWithCredential:(CDVInvokedUrlCommand*)command { @try { FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; if(credential == nil) return; [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { [self handleAuthResult:authResult error:error command:command]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)reauthenticateWithCredential:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; if(credential == nil) return; [user reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { [self handleAuthResult:authResult error:error command:command]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)linkUserWithCredential:(CDVInvokedUrlCommand*)command { @try { FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; if(credential == nil) return; [[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { [self handleAuthResult:authResult error:error command:command]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)isUserSignedIn:(CDVInvokedUrlCommand*)command { @try { bool isSignedIn = [FIRAuth auth].currentUser ? true : false; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isSignedIn] callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)signOutUser:(CDVInvokedUrlCommand*)command { @try { bool isSignedIn = [FIRAuth auth].currentUser ? true : false; if(!isSignedIn){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } // Sign out of Google if([[GIDSignIn sharedInstance] currentUser] != nil){ [[GIDSignIn sharedInstance] signOut]; } // Sign out of Firebase NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[NSString stringWithFormat:@"Error signing out: %@", signOutError]] callbackId:command.callbackId]; }else{ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)getCurrentUser:(CDVInvokedUrlCommand *)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [self extractAndReturnUserInfo:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)reloadCurrentUser:(CDVInvokedUrlCommand *)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [user reloadWithCompletion:^(NSError * _Nullable error) { if (error != nil) { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description] callbackId:command.callbackId]; }else { [self extractAndReturnUserInfo:command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void) extractAndReturnUserInfo:(CDVInvokedUrlCommand *)command { FIRUser* user = [FIRAuth auth].currentUser; NSMutableDictionary* userInfo = [NSMutableDictionary new]; [userInfo setValue:user.displayName forKey:@"name"]; [userInfo setValue:user.email forKey:@"email"]; [userInfo setValue:@(user.isEmailVerified ? true : false) forKey:@"emailIsVerified"]; [userInfo setValue:user.phoneNumber forKey:@"phoneNumber"]; [userInfo setValue:user.photoURL ? user.photoURL.absoluteString : nil forKey:@"photoUrl"]; [userInfo setValue:user.uid forKey:@"uid"]; [userInfo setValue:@(user.isAnonymous ? true : false) forKey:@"isAnonymous"]; [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) { [userInfo setValue:token forKey:@"idToken"]; [user getIDTokenResultWithCompletion:^(FIRAuthTokenResult * _Nullable tokenResult, NSError * _Nullable error) { [userInfo setValue:tokenResult.signInProvider forKey:@"providerId"]; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo] callbackId:command.callbackId]; }]; }]; } - (void)updateUserProfile:(CDVInvokedUrlCommand*)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } NSDictionary* profile = [command.arguments objectAtIndex:0]; FIRUserProfileChangeRequest* changeRequest = [user profileChangeRequest]; if([profile objectForKey:@"name"] != nil){ changeRequest.displayName = [profile objectForKey:@"name"]; } if([profile objectForKey:@"photoUri"] != nil){ changeRequest.photoURL = [NSURL URLWithString:[profile objectForKey:@"photoUri"]]; } [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)updateUserEmail:(CDVInvokedUrlCommand*)command { @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } NSString* email = [command.arguments objectAtIndex:0]; [user updateEmail:email completion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)sendUserEmailVerification:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [user sendEmailVerificationWithCompletion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)updateUserPassword:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } NSString* password = [command.arguments objectAtIndex:0]; [user updatePassword:password completion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)sendUserPasswordResetEmail:(CDVInvokedUrlCommand*)command{ @try { NSString* email = [command.arguments objectAtIndex:0]; [[FIRAuth auth] sendPasswordResetWithEmail:email completion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)deleteUser:(CDVInvokedUrlCommand*)command{ @try { FIRUser* user = [FIRAuth auth].currentUser; if(!user){ [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; return; } [user deleteWithCompletion:^(NSError *_Nullable error) { @try { [self handleResultWithPotentialError:error command:command]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)startSignInWithAppleFlow API_AVAILABLE(ios(13.0)){ NSString *nonce = [self randomNonce:32]; currentNonce = nonce; ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init]; ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest]; request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail]; request.nonce = [self stringBySha256HashingString:nonce]; ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]]; authorizationController.delegate = [AppDelegate instance]; authorizationController.presentationContextProvider = [AppDelegate instance]; [authorizationController performRequests]; } - (NSString *)stringBySha256HashingString:(NSString *)input { const char *string = [input UTF8String]; unsigned char result[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(string, (CC_LONG)strlen(string), result); NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { [hashed appendFormat:@"%02x", result[i]]; } return hashed; } // Generates random nonce for Apple Sign In - (NSString *)randomNonce:(NSInteger)length { NSAssert(length > 0, @"Expected nonce to have positive length"); NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"; NSMutableString *result = [NSMutableString string]; NSInteger remainingLength = length; while (remainingLength > 0) { NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16]; for (NSInteger i = 0; i < 16; i++) { uint8_t random = 0; int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random); NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode); [randoms addObject:@(random)]; } for (NSNumber *random in randoms) { if (remainingLength == 0) { break; } if (random.unsignedIntValue < characterSet.length) { unichar character = [characterSet characterAtIndex:random.unsignedIntValue]; [result appendFormat:@"%C", character]; remainingLength--; } } } return result; } /* * Analytics */ - (void)setAnalyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { BOOL enabled = [[command argumentAtIndex:0] boolValue]; CDVPluginResult* pluginResult; if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; }else if(enabled && [self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to enabled"]; }else if(!enabled && ![self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to disabled"]; }else{ [FIRAnalytics setAnalyticsCollectionEnabled:enabled]; [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:enabled]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isAnalyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)logEvent:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* name = [command.arguments objectAtIndex:0]; NSDictionary *parameters = [command argumentAtIndex:1]; [FIRAnalytics logEventWithName:name parameters:parameters]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)setScreenName:(CDVInvokedUrlCommand *)command { @try { NSString* name = [command.arguments objectAtIndex:0]; [FIRAnalytics setScreenName:name screenClass:NULL]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (void)setUserId:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* id = [command.arguments objectAtIndex:0]; [FIRAnalytics setUserID:id]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)setUserProperty:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* name = [command.arguments objectAtIndex:0]; NSString* value = [command.arguments objectAtIndex:1]; [FIRAnalytics setUserPropertyString:value forName:name]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Crashlytics */ - (BOOL) _shouldEnableCrashlytics { return ![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES] && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; } - (void)setCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { BOOL enabled = [[command argumentAtIndex:0] boolValue]; CDVPluginResult* pluginResult; if([self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Crashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; }else if(enabled && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to enabled"]; }else if(!enabled && ![self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to disabled"]; }else{ [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:enabled]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isCrashlyticsCollectionCurrentlyEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isCrashlyticsEnabled]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)logError:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ NSString* errorMessage = [command.arguments objectAtIndex:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; @try { if(!isCrashlyticsEnabled){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log error - Crashlytics collection is disabled"]; } // We can optionally be passed a stack trace from stackTrace.js which we'll put in userInfo. else if ([command.arguments count] > 1) { NSArray* stackFrames = [command.arguments objectAtIndex:1]; NSString* message = errorMessage; NSString* name = @"Uncaught Javascript exception"; NSMutableArray *customFrames = [[NSMutableArray alloc] init]; FIRExceptionModel *exceptionModel = [FIRExceptionModel exceptionModelWithName:name reason:message]; for (NSDictionary* stackFrame in stackFrames) { FIRStackFrame *customFrame = [FIRStackFrame stackFrameWithSymbol:stackFrame[@"functionName"] file:stackFrame[@"fileName"] line:(uint32_t) [stackFrame[@"lineNumber"] intValue]]; [customFrames addObject:customFrame]; } exceptionModel.stackTrace = customFrames; [[FIRCrashlytics crashlytics] recordExceptionModel:exceptionModel]; }else{ //TODO detect and handle non-stack userInfo and pass to recordError NSMutableDictionary* userInfo = [[NSMutableDictionary alloc] init]; NSError *error = [NSError errorWithDomain:errorMessage code:0 userInfo:userInfo]; [[FIRCrashlytics crashlytics] recordError:error]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } @catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)logMessage:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { NSString* message = [command argumentAtIndex:0 withDefault:@""]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; if(!isCrashlyticsEnabled){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log message - Crashlytics collection is disabled"]; }else if(message){ [[FIRCrashlytics crashlytics] logWithFormat:@"%@", message]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)sendCrash:(CDVInvokedUrlCommand*)command{ assert(NO); } - (void)setCrashlyticsUserId:(CDVInvokedUrlCommand *)command { @try { NSString* userId = [command.arguments objectAtIndex:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; if(!isCrashlyticsEnabled){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set user ID - Crashlytics collection is disabled"]; }else{ [[FIRCrashlytics crashlytics] setUserID:userId]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } /* * Remote config */ - (void)fetch:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; if ([command.arguments count] > 0) { int expirationDuration = [[command.arguments objectAtIndex:0] intValue]; [remoteConfig fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { CDVPluginResult *pluginResult; if (error != nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else if (status == FIRRemoteConfigFetchStatusSuccess) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } else { [remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { CDVPluginResult *pluginResult; if (error != nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else if (status == FIRRemoteConfigFetchStatusSuccess) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)activateFetched:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; [remoteConfig activateWithCompletionHandler:^(NSError * _Nullable error) { CDVPluginResult *pluginResult; if (error != nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)getValue:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* key = [command.arguments objectAtIndex:0]; FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; NSString* value = remoteConfig[key].stringValue; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:value]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)getInfo:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; NSInteger minimumFetchInterval = remoteConfig.configSettings.minimumFetchInterval; NSInteger fetchTimeout = remoteConfig.configSettings.fetchTimeout; NSDate* lastFetchTime = remoteConfig.lastFetchTime; FIRRemoteConfigFetchStatus lastFetchStatus = remoteConfig.lastFetchStatus; // isDeveloperModeEnabled is deprecated new recommnded way to check is minimumFetchInterval == 0 BOOL isDeveloperModeEnabled = minimumFetchInterval == 0 ? true : false; NSDictionary* configSettings = @{ @"developerModeEnabled": [NSNumber numberWithBool:isDeveloperModeEnabled], @"minimumFetchInterval": [NSNumber numberWithInteger:minimumFetchInterval], @"fetchTimeout": [NSNumber numberWithInteger:fetchTimeout], }; NSDictionary* infoObject = @{ @"configSettings": configSettings, @"fetchTimeMillis": (lastFetchTime ? [NSNumber numberWithInteger:(lastFetchTime.timeIntervalSince1970 * 1000)] : [NSNull null]), @"lastFetchStatus": [NSNumber numberWithInteger:(lastFetchStatus)], }; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:infoObject]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Performance */ - (void)setPerformanceCollectionEnabled:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { BOOL enabled = [[command argumentAtIndex:0] boolValue]; CDVPluginResult* pluginResult; if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; }else if(enabled && [self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to enabled"]; }else if(!enabled && ![self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to disabled"]; }else{ [[FIRPerformance sharedInstance] setDataCollectionEnabled:enabled]; [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:enabled]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)isPerformanceCollectionEnabled:(CDVInvokedUrlCommand*)command{ [self.commandDelegate runInBackground:^{ @try { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)startTrace:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* traceName = [command.arguments objectAtIndex:0]; FIRTrace *trace = [self.traces objectForKey:traceName]; if ( self.traces == nil) { self.traces = [NSMutableDictionary new]; } if (trace == nil) { trace = [FIRPerformance startTraceWithName:traceName]; [self.traces setObject:trace forKey:traceName ]; } CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)incrementCounter:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* traceName = [command.arguments objectAtIndex:0]; NSString* counterNamed = [command.arguments objectAtIndex:1]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; FIRTrace *trace = (FIRTrace*)[self.traces objectForKey:traceName]; if (trace != nil) { [trace incrementMetric:counterNamed byInt:1]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)stopTrace:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ @try { NSString* traceName = [command.arguments objectAtIndex:0]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; FIRTrace *trace = [self.traces objectForKey:traceName]; if (trace != nil) { [trace stop]; [self.traces removeObjectForKey:traceName]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } else { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /* * Firestore */ - (void)addDocumentToFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSDictionary* document = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; __block FIRDocumentReference *ref = [[firestore collectionWithPath:collection] addDocumentWithData:document completion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ref.documentID]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)setDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSDictionary* document = [command.arguments objectAtIndex:1]; NSString* collection = [command.arguments objectAtIndex:2]; [[[firestore collectionWithPath:collection] documentWithPath:documentId] setData:document completion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)updateDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSDictionary* document = [command.arguments objectAtIndex:1]; NSString* collection = [command.arguments objectAtIndex:2]; FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; if(docRef != nil){ [docRef updateData:document completion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }]; }else{ [self sendPluginError:@"Document not found in collection":command]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)deleteDocumentFromFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; [[[firestore collectionWithPath:collection] documentWithPath:documentId] deleteDocumentWithCompletion:^(NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)documentExistsInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; if(docRef != nil){ [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; }else{ BOOL docExists = snapshot.data != nil; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:docExists] callbackId:command.callbackId]; } }]; }else{ [self sendPluginError:@"Collection not found":command]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)fetchDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* documentId = [command.arguments objectAtIndex:0]; NSString* collection = [command.arguments objectAtIndex:1]; FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; if(docRef != nil){ [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else if(snapshot.data != nil) { [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:snapshot.data] callbackId:command.callbackId]; }else{ [self sendPluginError:@"Document not found in collection":command]; } }]; }else{ [self sendPluginError:@"Collection not found":command]; } }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } - (void)fetchFirestoreCollection:(CDVInvokedUrlCommand*)command { [self.commandDelegate runInBackground:^{ @try { NSString* collection = [command.arguments objectAtIndex:0]; NSArray* filters = [command.arguments objectAtIndex:1]; FIRQuery* query = [firestore collectionWithPath:collection]; for (int i = 0; i < [filters count]; i++) { NSArray* filter = [filters objectAtIndex:i]; if ([[filter objectAtIndex:0] isEqualToString:@"where"]) { if ([[filter objectAtIndex:2] isEqualToString:@"=="]) { query = [query queryWhereField:[filter objectAtIndex:1] isEqualTo:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@"<"]) { query = [query queryWhereField:[filter objectAtIndex:1] isLessThan:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@">"]) { query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThan:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@"<="]) { query = [query queryWhereField:[filter objectAtIndex:1] isLessThanOrEqualTo:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@">="]) { query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThanOrEqualTo:[filter objectAtIndex:3]]; } if ([[filter objectAtIndex:2] isEqualToString:@"array-contains"]) { query = [query queryWhereField:[filter objectAtIndex:1] arrayContains:[filter objectAtIndex:3]]; } continue; } if ([[filter objectAtIndex:0] isEqualToString:@"orderBy"]) { query = [query queryOrderedByField:[filter objectAtIndex:1] descending:([[filter objectAtIndex:2] isEqualToString:@"desc"])]; continue; } if ([[filter objectAtIndex:0] isEqualToString:@"startAt"]) { query = [query queryStartingAtValues:[filter objectAtIndex:1]]; continue; } if ([[filter objectAtIndex:0] isEqualToString:@"endAt"]) { query = [query queryEndingAtValues:[filter objectAtIndex:1]]; continue; } if ([[filter objectAtIndex:0] isEqualToString:@"limit"]) { query = [query queryLimitedTo:[(NSNumber *)[filter objectAtIndex:1] integerValue]]; continue; } } [query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { [self sendPluginError:error.localizedDescription:command]; } else { NSMutableDictionary* documents = [[NSMutableDictionary alloc] init];; for (FIRDocumentSnapshot *document in snapshot.documents) { [documents setObject:document.data forKey:document.documentID]; } [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:documents] callbackId:command.callbackId]; } }]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } }]; } /********************************/ #pragma mark - utility functions /********************************/ - (void) sendPluginError: (NSString*) errorMessage :(CDVInvokedUrlCommand*)command { CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; [self _logError:errorMessage]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void) handlePluginExceptionWithContext: (NSException*) exception :(CDVInvokedUrlCommand*)command { [self handlePluginExceptionWithoutContext:exception]; CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void) handlePluginExceptionWithoutContext: (NSException*) exception { [self _logError:[NSString stringWithFormat:@"EXCEPTION: %@", exception.reason]]; } - (void)executeGlobalJavascript: (NSString*)jsString { [self.commandDelegate evalJs:jsString]; } - (void)_logError: (NSString*)msg { NSLog(@"%@ ERROR: %@", LOG_TAG, msg); NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logInfo: (NSString*)msg { NSLog(@"%@ INFO: %@", LOG_TAG, msg); NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (void)_logMessage: (NSString*)msg { NSLog(@"%@ LOG: %@", LOG_TAG, msg); NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; [self executeGlobalJavascript:jsString]; } - (NSString*)escapeJavascriptString: (NSString*)str { NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; return result; } - (void)runOnMainThread:(void (^)(void))completeBlock { if (![NSThread isMainThread]) { dispatch_sync(dispatch_get_main_queue(), ^{ @try { completeBlock(); }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } }); } else { @try { completeBlock(); }@catch (NSException *exception) { [self handlePluginExceptionWithoutContext:exception]; } } } - (FIRAuthCredential*)obtainAuthCredential:(NSDictionary*)credential command:(CDVInvokedUrlCommand *)command { FIRAuthCredential* authCredential = nil; if(credential == nil){ NSString* errMsg = @"credential object must be passed as first and only argument"; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; return authCredential; } NSString* key = [credential objectForKey:@"id"]; NSString* verificationId = [credential objectForKey:@"verificationId"]; NSString* code = [credential objectForKey:@"code"]; if(key != nil){ authCredential = [authCredentials objectForKey:key]; if(authCredential == nil){ NSString* errMsg = [NSString stringWithFormat:@"no native auth credential exists for specified id '%@'", key]; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; } }else if(verificationId != nil && code != nil){ authCredential = [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationId verificationCode:code]; }else{ NSString* errMsg = @"credential object must either specify the id key of an existing native auth credential or the verificationId/code keys must be specified for a phone number authentication"; [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; } return authCredential; } - (void) handleAuthResult:(FIRAuthDataResult*) authResult error:(NSError*) error command:(CDVInvokedUrlCommand*)command { @try { CDVPluginResult* pluginResult; if (error) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else if (authResult == nil) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"User not signed in"]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }@catch (NSException *exception) { [self handlePluginExceptionWithContext:exception :command]; } } - (int) saveAuthCredential: (FIRAuthCredential*) authCredential { int key = -1; while (key < 0 || [authCredentials objectForKey:[NSNumber numberWithInt:key]] != nil) { key = arc4random_uniform(100000); } [authCredentials setObject:authCredential forKey:[NSNumber numberWithInt:key]]; return key; } - (void) handleResultWithPotentialError:(NSError*) error command:(CDVInvokedUrlCommand*)command { CDVPluginResult* pluginResult; if (error) { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; }else{ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void) setPreferenceFlag:(NSString*) name flag:(BOOL)flag { [preferences setBool:flag forKey:name]; [preferences synchronize]; } - (BOOL) getPreferenceFlag:(NSString*) name { if([preferences objectForKey:name] == nil){ return false; } return [preferences boolForKey:name]; } - (BOOL) getGooglePlistFlagWithDefaultValue:(NSString*) name defaultValue:(BOOL)defaultValue { if([googlePlist objectForKey:name] == nil){ return defaultValue; } return [[googlePlist objectForKey:name] isEqualToString:@"true"]; } # pragma mark - Stubs - (void)createChannel:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } - (void)setDefaultChannel:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } - (void)deleteChannel:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } - (void)listChannels:(CDVInvokedUrlCommand *)command { [self.commandDelegate runInBackground:^{ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; }]; } @end \ No newline at end of file +#import "FirebasePlugin.h" +#import "FirebasePluginMessageReceiverManager.h" +#import "AppDelegate+FirebasePlugin.h" +#import +#import "AppDelegate.h" +#import +@import FirebaseInstanceID; +@import FirebaseMessaging; +@import FirebaseAnalytics; +@import FirebaseRemoteConfig; +@import FirebasePerformance; +@import FirebaseAuth; +@import UserNotifications; +@import CommonCrypto; +@import AuthenticationServices; + +@implementation FirebasePlugin + +@synthesize notificationCallbackId; +@synthesize tokenRefreshCallbackId; +@synthesize apnsTokenRefreshCallbackId; +@synthesize googleSignInCallbackId; +@synthesize appleSignInCallbackId; +@synthesize notificationStack; +@synthesize traces; + +static NSString*const LOG_TAG = @"FirebasePlugin[native]"; +static NSInteger const kNotificationStackSize = 10; +static NSString*const FIREBASE_CRASHLYTICS_COLLECTION_ENABLED = @"FIREBASE_CRASHLYTICS_COLLECTION_ENABLED"; +static NSString*const FIREBASE_ANALYTICS_COLLECTION_ENABLED = @"FIREBASE_ANALYTICS_COLLECTION_ENABLED"; +static NSString*const FIREBASE_PERFORMANCE_COLLECTION_ENABLED = @"FIREBASE_PERFORMANCE_COLLECTION_ENABLED"; + +static FirebasePlugin* firebasePlugin; +static BOOL registeredForRemoteNotifications = NO; +static BOOL isCrashlyticsEnabled = NO; +static NSMutableDictionary* authCredentials; +static NSString* currentNonce; // used for Apple Sign In +static FIRFirestore* firestore; +static NSUserDefaults* preferences; +static NSDictionary* googlePlist; + + ++ (FirebasePlugin*) firebasePlugin { + return firebasePlugin; +} + ++ (NSString*) appleSignInNonce { + return currentNonce; +} + ++ (void) setFirestore:(FIRFirestore*) firestoreInstance{ + firestore = firestoreInstance; +} + +// @override abstract +- (void)pluginInitialize { + NSLog(@"Starting Firebase plugin"); + firebasePlugin = self; + + @try { + preferences = [NSUserDefaults standardUserDefaults]; + googlePlist = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"GoogleService-Info" ofType:@"plist"]]; + + if(![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ + isCrashlyticsEnabled = [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; + }else{ + isCrashlyticsEnabled = YES; + [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:YES]; + } + + if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ + [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:YES]; + } + + if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ + [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:YES]; + } + + // Check for permission and register for remote notifications if granted + [self _hasPermission:^(BOOL result) {}]; + + [GIDSignIn sharedInstance].presentingViewController = self.viewController; + + authCredentials = [[NSMutableDictionary alloc] init]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithoutContext:exception]; + } +} + +// @override abstract +- (void)handleOpenURL:(NSNotification*)notification{ + NSURL* url = [notification object]; + [[GIDSignIn sharedInstance] handleURL:url]; +} + +- (void)setAutoInitEnabled:(CDVInvokedUrlCommand *)command { + @try { + bool enabled = [[command.arguments objectAtIndex:0] boolValue]; + [self runOnMainThread:^{ + @try { + [FIRMessaging messaging].autoInitEnabled = enabled; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)isAutoInitEnabled:(CDVInvokedUrlCommand *)command { + @try { + + [self runOnMainThread:^{ + @try { + bool enabled =[FIRMessaging messaging].isAutoInitEnabled; + + CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; + [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +/* + * Remote notifications + */ + +- (void)getId:(CDVInvokedUrlCommand *)command { + __block CDVPluginResult *pluginResult; + + FIRInstanceIDHandler handler = ^(NSString *_Nullable instID, NSError *_Nullable error) { + @try { + if (error) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:instID]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }; + + @try { + [[FIRInstanceID instanceID] getIDWithHandler:handler]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)getToken:(CDVInvokedUrlCommand *)command { + @try { + [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, + NSError * _Nullable error) { + CDVPluginResult* pluginResult; + if (error == nil) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:result.token]; + }else{ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)getAPNSToken:(CDVInvokedUrlCommand *)command { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self getAPNSToken]]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (NSString *)getAPNSToken { + NSString* hexToken = nil; + NSData* apnsToken = [FIRMessaging messaging].APNSToken; + if (apnsToken) { +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + // [deviceToken description] Starting with iOS 13 device token is like "{length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f ... 28f10282 14af515f }" + hexToken = [self hexadecimalStringFromData:apnsToken]; +#else + hexToken = [[apnsToken.description componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet]invertedSet]]componentsJoinedByString:@""]; +#endif + } + return hexToken; +} + +- (NSString *)hexadecimalStringFromData:(NSData *)data +{ + NSUInteger dataLength = data.length; + if (dataLength == 0) { + return nil; + } + + const unsigned char *dataBuffer = data.bytes; + NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)]; + for (int i = 0; i < dataLength; ++i) { + [hexString appendFormat:@"%02x", dataBuffer[i]]; + } + return [hexString copy]; +} + +- (void)hasPermission:(CDVInvokedUrlCommand *)command { + @try { + [self _hasPermission:^(BOOL enabled) { + CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:enabled]; + [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +-(void)_hasPermission:(void (^)(BOOL result))completeBlock { + @try { + [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { + @try { + BOOL enabled = NO; + if (settings.alertSetting == UNNotificationSettingEnabled) { + enabled = YES; + [self registerForRemoteNotifications]; + } + NSLog(@"_hasPermission: %@", enabled ? @"YES" : @"NO"); + completeBlock(enabled); + }@catch (NSException *exception) { + [self handlePluginExceptionWithoutContext:exception]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithoutContext:exception]; + } +} + +- (void)grantPermission:(CDVInvokedUrlCommand *)command { + NSLog(@"grantPermission"); + @try { + [self _hasPermission:^(BOOL enabled) { + @try { + if(enabled){ + NSString* message = @"Permission is already granted - call hasPermission() to check before calling grantPermission()"; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }else{ + [UNUserNotificationCenter currentNotificationCenter].delegate = (id _Nullable) self; + UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge; + [[UNUserNotificationCenter currentNotificationCenter] + requestAuthorizationWithOptions:authOptions + completionHandler:^(BOOL granted, NSError * _Nullable error) { + @try { + NSLog(@"requestAuthorizationWithOptions: granted=%@", granted ? @"YES" : @"NO"); + CDVPluginResult* pluginResult; + if (error == nil) { + if(granted){ + [self registerForRemoteNotifications]; + } + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:granted]; + }else{ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + } + ]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)registerForRemoteNotifications { + NSLog(@"registerForRemoteNotifications"); + if(registeredForRemoteNotifications) return; + + [self runOnMainThread:^{ + @try { + [[UIApplication sharedApplication] registerForRemoteNotifications]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithoutContext:exception]; + } + registeredForRemoteNotifications = YES; + }]; +} + +- (void)setBadgeNumber:(CDVInvokedUrlCommand *)command { + @try { + int number = [[command.arguments objectAtIndex:0] intValue]; + [self runOnMainThread:^{ + @try { + [[UIApplication sharedApplication] setApplicationIconBadgeNumber:number]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)getBadgeNumber:(CDVInvokedUrlCommand *)command { + [self runOnMainThread:^{ + @try { + long badge = [[UIApplication sharedApplication] applicationIconBadgeNumber]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:badge]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)subscribe:(CDVInvokedUrlCommand *)command { + @try { + NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; + + [[FIRMessaging messaging] subscribeToTopic: topic]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)unsubscribe:(CDVInvokedUrlCommand *)command { + @try { + NSString* topic = [NSString stringWithFormat:@"%@", [command.arguments objectAtIndex:0]]; + + [[FIRMessaging messaging] unsubscribeFromTopic: topic]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)unregister:(CDVInvokedUrlCommand *)command { + @try { + [[FIRInstanceID instanceID] deleteIDWithHandler:^void(NSError *_Nullable error) { + CDVPluginResult* pluginResult; + if (error == nil) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + }else{ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + + + +- (void)onMessageReceived:(CDVInvokedUrlCommand *)command { + @try { + self.notificationCallbackId = command.callbackId; + + if (self.notificationStack != nil && [self.notificationStack count]) { + for (NSDictionary *userInfo in self.notificationStack) { + [self sendNotification:userInfo]; + } + [self.notificationStack removeAllObjects]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)onTokenRefresh:(CDVInvokedUrlCommand *)command { + self.tokenRefreshCallbackId = command.callbackId; + @try { + [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, + NSError * _Nullable error) { + @try { + if (error == nil) { + if (result.token != nil && error == nil) { + [self sendToken:result.token]; + } + }else{ + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)onApnsTokenReceived:(CDVInvokedUrlCommand *)command { + self.apnsTokenRefreshCallbackId = command.callbackId; + @try { + NSString* apnsToken = [self getAPNSToken]; + if(apnsToken != nil){ + [self sendApnsToken:apnsToken]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)sendNotification:(NSDictionary *)userInfo { + @try { + if([FirebasePluginMessageReceiverManager sendNotification:userInfo]){ + [self _logMessage:@"Message handled by custom receiver"]; + return; + } + if (self.notificationCallbackId != nil) { + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo]; + [pluginResult setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:self.notificationCallbackId]; + } else { + if (!self.notificationStack) { + self.notificationStack = [[NSMutableArray alloc] init]; + } + + // stack notifications until a callback has been registered + [self.notificationStack addObject:userInfo]; + + if ([self.notificationStack count] >= kNotificationStackSize) { + [self.notificationStack removeLastObject]; + } + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :self.commandDelegate]; + } +} + +- (void)sendToken:(NSString *)token { + @try { + if (self.tokenRefreshCallbackId != nil) { + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; + [pluginResult setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:self.tokenRefreshCallbackId]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :self.commandDelegate]; + } +} + +- (void)sendApnsToken:(NSString *)token { + @try { + if (self.apnsTokenRefreshCallbackId != nil) { + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:token]; + [pluginResult setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:self.apnsTokenRefreshCallbackId]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :self.commandDelegate]; + } +} + +- (void)clearAllNotifications:(CDVInvokedUrlCommand *)command { + [self runOnMainThread:^{ + @try { + [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1]; + [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +/* + * Authentication + */ +- (void)verifyPhoneNumber:(CDVInvokedUrlCommand *)command { + NSString* number = [command.arguments objectAtIndex:0]; + + @try { + [[FIRPhoneAuthProvider provider] + verifyPhoneNumber:number + UIDelegate:nil + completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) { + + @try { + CDVPluginResult* pluginResult; + if (error) { + // Verification code not sent. + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } else { + // Successful. + NSMutableDictionary* result = [[NSMutableDictionary alloc] init]; + [result setValue:@"false" forKey:@"instantVerification"]; + [result setValue:verificationID forKey:@"verificationId"]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)createUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { + @try { + NSString* email = [command.arguments objectAtIndex:0]; + NSString* password = [command.arguments objectAtIndex:1]; + [[FIRAuth auth] createUserWithEmail:email + password:password + completion:^(FIRAuthDataResult * _Nullable authResult, + NSError * _Nullable error) { + @try { + [self handleAuthResult:authResult error:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)signInUserWithEmailAndPassword:(CDVInvokedUrlCommand*)command { + @try { + NSString* email = [command.arguments objectAtIndex:0]; + NSString* password = [command.arguments objectAtIndex:1]; + [[FIRAuth auth] signInWithEmail:email + password:password + completion:^(FIRAuthDataResult * _Nullable authResult, + NSError * _Nullable error) { + @try { + [self handleAuthResult:authResult error:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)signInUserWithCustomToken:(CDVInvokedUrlCommand*)command { + @try { + NSString* customToken = [command.arguments objectAtIndex:0]; + [[FIRAuth auth] signInWithCustomToken:customToken + completion:^(FIRAuthDataResult * _Nullable authResult, + NSError * _Nullable error) { + @try { + [self handleAuthResult:authResult error:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)signInUserAnonymously:(CDVInvokedUrlCommand*)command { + @try { + [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult, + NSError * _Nullable error) { + @try { + [self handleAuthResult:authResult error:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)authenticateUserWithGoogle:(CDVInvokedUrlCommand*)command{ + @try { + self.googleSignInCallbackId = command.callbackId; + [[GIDSignIn sharedInstance] signIn]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; + [pluginResult setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)authenticateUserWithApple:(CDVInvokedUrlCommand*)command{ + @try { + CDVPluginResult *pluginResult; + if (@available(iOS 13.0, *)) { + self.appleSignInCallbackId = command.callbackId; + [self startSignInWithAppleFlow]; + + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT]; + [pluginResult setKeepCallbackAsBool:YES]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"OS version is too low - Apple Sign In requires iOS 13.0+"]; + } + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)signInWithCredential:(CDVInvokedUrlCommand*)command { + @try { + FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; + if(credential == nil) return; + + [[FIRAuth auth] signInWithCredential:credential + completion:^(FIRAuthDataResult * _Nullable authResult, + NSError * _Nullable error) { + [self handleAuthResult:authResult error:error command:command]; + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)reauthenticateWithCredential:(CDVInvokedUrlCommand*)command{ + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; + if(credential == nil) return; + + [user reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { + [self handleAuthResult:authResult error:error command:command]; + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)linkUserWithCredential:(CDVInvokedUrlCommand*)command { + @try { + FIRAuthCredential* credential = [self obtainAuthCredential:[command.arguments objectAtIndex:0] command:command]; + if(credential == nil) return; + + [[FIRAuth auth].currentUser linkWithCredential:credential + completion:^(FIRAuthDataResult * _Nullable authResult, + NSError * _Nullable error) { + [self handleAuthResult:authResult error:error command:command]; + }]; + + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)isUserSignedIn:(CDVInvokedUrlCommand*)command { + @try { + bool isSignedIn = [FIRAuth auth].currentUser ? true : false; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isSignedIn] callbackId:command.callbackId]; + + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)signOutUser:(CDVInvokedUrlCommand*)command { + @try { + bool isSignedIn = [FIRAuth auth].currentUser ? true : false; + if(!isSignedIn){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + // Sign out of Google + if([[GIDSignIn sharedInstance] currentUser] != nil){ + [[GIDSignIn sharedInstance] signOut]; + } + + // Sign out of Firebase + NSError *signOutError; + BOOL status = [[FIRAuth auth] signOut:&signOutError]; + if (!status) { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[NSString stringWithFormat:@"Error signing out: %@", signOutError]] callbackId:command.callbackId]; + }else{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)getCurrentUser:(CDVInvokedUrlCommand *)command { + + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + [self extractAndReturnUserInfo:command]; + + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)reloadCurrentUser:(CDVInvokedUrlCommand *)command { + + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + [user reloadWithCompletion:^(NSError * _Nullable error) { + if (error != nil) { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description] callbackId:command.callbackId]; + }else { + [self extractAndReturnUserInfo:command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void) extractAndReturnUserInfo:(CDVInvokedUrlCommand *)command { + FIRUser* user = [FIRAuth auth].currentUser; + NSMutableDictionary* userInfo = [NSMutableDictionary new]; + [userInfo setValue:user.displayName forKey:@"name"]; + [userInfo setValue:user.email forKey:@"email"]; + [userInfo setValue:@(user.isEmailVerified ? true : false) forKey:@"emailIsVerified"]; + [userInfo setValue:user.phoneNumber forKey:@"phoneNumber"]; + [userInfo setValue:user.photoURL ? user.photoURL.absoluteString : nil forKey:@"photoUrl"]; + [userInfo setValue:user.uid forKey:@"uid"]; + [userInfo setValue:@(user.isAnonymous ? true : false) forKey:@"isAnonymous"]; + [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) { + [userInfo setValue:token forKey:@"idToken"]; + [user getIDTokenResultWithCompletion:^(FIRAuthTokenResult * _Nullable tokenResult, NSError * _Nullable error) { + [userInfo setValue:tokenResult.signInProvider forKey:@"providerId"]; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:userInfo] callbackId:command.callbackId]; + }]; + }]; +} + +- (void)updateUserProfile:(CDVInvokedUrlCommand*)command { + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + NSDictionary* profile = [command.arguments objectAtIndex:0]; + + FIRUserProfileChangeRequest* changeRequest = [user profileChangeRequest]; + if([profile objectForKey:@"name"] != nil){ + changeRequest.displayName = [profile objectForKey:@"name"]; + } + if([profile objectForKey:@"photoUri"] != nil){ + changeRequest.photoURL = [NSURL URLWithString:[profile objectForKey:@"photoUri"]]; + } + + [changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) { + @try { + [self handleResultWithPotentialError:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)updateUserEmail:(CDVInvokedUrlCommand*)command { + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + NSString* email = [command.arguments objectAtIndex:0]; + [user updateEmail:email completion:^(NSError *_Nullable error) { + @try { + [self handleResultWithPotentialError:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)sendUserEmailVerification:(CDVInvokedUrlCommand*)command{ + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + [user sendEmailVerificationWithCompletion:^(NSError *_Nullable error) { + @try { + [self handleResultWithPotentialError:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)updateUserPassword:(CDVInvokedUrlCommand*)command{ + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + NSString* password = [command.arguments objectAtIndex:0]; + [user updatePassword:password completion:^(NSError *_Nullable error) { + @try { + [self handleResultWithPotentialError:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)sendUserPasswordResetEmail:(CDVInvokedUrlCommand*)command{ + @try { + NSString* email = [command.arguments objectAtIndex:0]; + [[FIRAuth auth] sendPasswordResetWithEmail:email completion:^(NSError *_Nullable error) { + @try { + [self handleResultWithPotentialError:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)deleteUser:(CDVInvokedUrlCommand*)command{ + @try { + FIRUser* user = [FIRAuth auth].currentUser; + if(!user){ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No user is currently signed"] callbackId:command.callbackId]; + return; + } + + [user deleteWithCompletion:^(NSError *_Nullable error) { + @try { + [self handleResultWithPotentialError:error command:command]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)startSignInWithAppleFlow API_AVAILABLE(ios(13.0)){ + NSString *nonce = [self randomNonce:32]; + currentNonce = nonce; + ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init]; + ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest]; + request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail]; + request.nonce = [self stringBySha256HashingString:nonce]; + + ASAuthorizationController *authorizationController = + [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]]; + authorizationController.delegate = [AppDelegate instance]; + authorizationController.presentationContextProvider = [AppDelegate instance]; + [authorizationController performRequests]; +} + +- (NSString *)stringBySha256HashingString:(NSString *)input { + const char *string = [input UTF8String]; + unsigned char result[CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(string, (CC_LONG)strlen(string), result); + + NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; + for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { + [hashed appendFormat:@"%02x", result[i]]; + } + return hashed; +} + +// Generates random nonce for Apple Sign In +- (NSString *)randomNonce:(NSInteger)length { + NSAssert(length > 0, @"Expected nonce to have positive length"); + NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"; + NSMutableString *result = [NSMutableString string]; + NSInteger remainingLength = length; + + while (remainingLength > 0) { + NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16]; + for (NSInteger i = 0; i < 16; i++) { + uint8_t random = 0; + int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random); + NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode); + + [randoms addObject:@(random)]; + } + + for (NSNumber *random in randoms) { + if (remainingLength == 0) { + break; + } + + if (random.unsignedIntValue < characterSet.length) { + unichar character = [characterSet characterAtIndex:random.unsignedIntValue]; + [result appendFormat:@"%C", character]; + remainingLength--; + } + } + } + + return result; +} + +/* + * Analytics + */ +- (void)setAnalyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + BOOL enabled = [[command argumentAtIndex:0] boolValue]; + CDVPluginResult* pluginResult; + if([self getGooglePlistFlagWithDefaultValue:FIREBASE_ANALYTICS_COLLECTION_ENABLED defaultValue:YES]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Analytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; + }else if(enabled && [self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to enabled"]; + }else if(!enabled && ![self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Analytics data collection is already set to disabled"]; + }else{ + [FIRAnalytics setAnalyticsCollectionEnabled:enabled]; + [self setPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED flag:enabled]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)isAnalyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ + [self.commandDelegate runInBackground:^{ + @try { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_ANALYTICS_COLLECTION_ENABLED]]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)logEvent:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* name = [command.arguments objectAtIndex:0]; + NSDictionary *parameters = [command argumentAtIndex:1]; + + [FIRAnalytics logEventWithName:name parameters:parameters]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)setScreenName:(CDVInvokedUrlCommand *)command { + @try { + NSString* name = [command.arguments objectAtIndex:0]; + + [FIRAnalytics setScreenName:name screenClass:NULL]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (void)setUserId:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* id = [command.arguments objectAtIndex:0]; + + [FIRAnalytics setUserID:id]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)setUserProperty:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* name = [command.arguments objectAtIndex:0]; + NSString* value = [command.arguments objectAtIndex:1]; + + [FIRAnalytics setUserPropertyString:value forName:name]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +/* + * Crashlytics + */ +- (BOOL) _shouldEnableCrashlytics { + return ![self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES] && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]; +} + +- (void)setCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + BOOL enabled = [[command argumentAtIndex:0] boolValue]; + CDVPluginResult* pluginResult; + if([self getGooglePlistFlagWithDefaultValue:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED defaultValue:YES]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Crashlytics data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; + }else if(enabled && [self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to enabled"]; + }else if(!enabled && ![self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Crashlytics data collection is already set to disabled"]; + }else{ + [self setPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED flag:enabled]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)isCrashlyticsCollectionEnabled:(CDVInvokedUrlCommand*)command{ + [self.commandDelegate runInBackground:^{ + @try { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_CRASHLYTICS_COLLECTION_ENABLED]]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)isCrashlyticsCollectionCurrentlyEnabled:(CDVInvokedUrlCommand*)command{ + [self.commandDelegate runInBackground:^{ + @try { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isCrashlyticsEnabled]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)logError:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + NSString* errorMessage = [command.arguments objectAtIndex:0]; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + @try { + if(!isCrashlyticsEnabled){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log error - Crashlytics collection is disabled"]; + } + // We can optionally be passed a stack trace from stackTrace.js which we'll put in userInfo. + else if ([command.arguments count] > 1) { + NSArray* stackFrames = [command.arguments objectAtIndex:1]; + + NSString* message = errorMessage; + NSString* name = @"Uncaught Javascript exception"; + NSMutableArray *customFrames = [[NSMutableArray alloc] init]; + FIRExceptionModel *exceptionModel = [FIRExceptionModel exceptionModelWithName:name reason:message]; + + for (NSDictionary* stackFrame in stackFrames) { + FIRStackFrame *customFrame = [FIRStackFrame stackFrameWithSymbol:stackFrame[@"functionName"] file:stackFrame[@"fileName"] line:(uint32_t) [stackFrame[@"lineNumber"] intValue]]; + [customFrames addObject:customFrame]; + } + exceptionModel.stackTrace = customFrames; + [[FIRCrashlytics crashlytics] recordExceptionModel:exceptionModel]; + }else{ + //TODO detect and handle non-stack userInfo and pass to recordError + NSMutableDictionary* userInfo = [[NSMutableDictionary alloc] init]; + NSError *error = [NSError errorWithDomain:errorMessage code:0 userInfo:userInfo]; + [[FIRCrashlytics crashlytics] recordError:error]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } @catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + + }]; +} + +- (void)logMessage:(CDVInvokedUrlCommand*)command{ + [self.commandDelegate runInBackground:^{ + @try { + NSString* message = [command argumentAtIndex:0 withDefault:@""]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + if(!isCrashlyticsEnabled){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot log message - Crashlytics collection is disabled"]; + }else if(message){ + [[FIRCrashlytics crashlytics] logWithFormat:@"%@", message]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)sendCrash:(CDVInvokedUrlCommand*)command{ + assert(NO); +} + +- (void)setCrashlyticsUserId:(CDVInvokedUrlCommand *)command { + @try { + NSString* userId = [command.arguments objectAtIndex:0]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + if(!isCrashlyticsEnabled){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set user ID - Crashlytics collection is disabled"]; + }else{ + [[FIRCrashlytics crashlytics] setUserID:userId]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +/* + * Remote config + */ +- (void)fetch:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; + + if ([command.arguments count] > 0) { + int expirationDuration = [[command.arguments objectAtIndex:0] intValue]; + + [remoteConfig fetchWithExpirationDuration:expirationDuration completionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { + CDVPluginResult *pluginResult; + if (error != nil) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + }else if (status == FIRRemoteConfigFetchStatusSuccess) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; + } else { + [remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { + CDVPluginResult *pluginResult; + if (error != nil) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + }else if (status == FIRRemoteConfigFetchStatusSuccess) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)activateFetched:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; + [remoteConfig activateWithCompletionHandler:^(NSError * _Nullable error) { + CDVPluginResult *pluginResult; + if (error != nil) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)getValue:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* key = [command.arguments objectAtIndex:0]; + FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; + NSString* value = remoteConfig[key].stringValue; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:value]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)getInfo:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + FIRRemoteConfig* remoteConfig = [FIRRemoteConfig remoteConfig]; + NSInteger minimumFetchInterval = remoteConfig.configSettings.minimumFetchInterval; + NSInteger fetchTimeout = remoteConfig.configSettings.fetchTimeout; + NSDate* lastFetchTime = remoteConfig.lastFetchTime; + FIRRemoteConfigFetchStatus lastFetchStatus = remoteConfig.lastFetchStatus; + // isDeveloperModeEnabled is deprecated new recommnded way to check is minimumFetchInterval == 0 + BOOL isDeveloperModeEnabled = minimumFetchInterval == 0 ? true : false; + + NSDictionary* configSettings = @{ + @"developerModeEnabled": [NSNumber numberWithBool:isDeveloperModeEnabled], + @"minimumFetchInterval": [NSNumber numberWithInteger:minimumFetchInterval], + @"fetchTimeout": [NSNumber numberWithInteger:fetchTimeout], + }; + + NSDictionary* infoObject = @{ + @"configSettings": configSettings, + @"fetchTimeMillis": (lastFetchTime ? [NSNumber numberWithInteger:(lastFetchTime.timeIntervalSince1970 * 1000)] : [NSNull null]), + @"lastFetchStatus": [NSNumber numberWithInteger:(lastFetchStatus)], + }; + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:infoObject]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +/* + * Performance + */ +- (void)setPerformanceCollectionEnabled:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + BOOL enabled = [[command argumentAtIndex:0] boolValue]; + CDVPluginResult* pluginResult; + if([self getGooglePlistFlagWithDefaultValue:FIREBASE_PERFORMANCE_COLLECTION_ENABLED defaultValue:YES]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot set Performance data collection at runtime as it's hard-coded to ENABLED at build-time in the plist"]; + }else if(enabled && [self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to enabled"]; + }else if(!enabled && ![self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]){ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Performance data collection is already set to disabled"]; + }else{ + [[FIRPerformance sharedInstance] setDataCollectionEnabled:enabled]; + [self setPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED flag:enabled]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)isPerformanceCollectionEnabled:(CDVInvokedUrlCommand*)command{ + [self.commandDelegate runInBackground:^{ + @try { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[self getPreferenceFlag:FIREBASE_PERFORMANCE_COLLECTION_ENABLED]]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)startTrace:(CDVInvokedUrlCommand *)command { + + [self.commandDelegate runInBackground:^{ + @try { + NSString* traceName = [command.arguments objectAtIndex:0]; + FIRTrace *trace = [self.traces objectForKey:traceName]; + + if ( self.traces == nil) { + self.traces = [NSMutableDictionary new]; + } + + if (trace == nil) { + trace = [FIRPerformance startTraceWithName:traceName]; + [self.traces setObject:trace forKey:traceName ]; + + } + + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)incrementCounter:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* traceName = [command.arguments objectAtIndex:0]; + NSString* counterNamed = [command.arguments objectAtIndex:1]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + FIRTrace *trace = (FIRTrace*)[self.traces objectForKey:traceName]; + + if (trace != nil) { + [trace incrementMetric:counterNamed byInt:1]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; + } + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)stopTrace:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* traceName = [command.arguments objectAtIndex:0]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + FIRTrace *trace = [self.traces objectForKey:traceName]; + + if (trace != nil) { + [trace stop]; + [self.traces removeObjectForKey:traceName]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } else { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Trace not found"]; + } + + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +/* +* Firestore +*/ + +- (void)addDocumentToFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSDictionary* document = [command.arguments objectAtIndex:0]; + NSString* collection = [command.arguments objectAtIndex:1]; + __block FIRDocumentReference *ref = + [[firestore collectionWithPath:collection] addDocumentWithData:document completion:^(NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + } else { + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ref.documentID]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)setDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* documentId = [command.arguments objectAtIndex:0]; + NSDictionary* document = [command.arguments objectAtIndex:1]; + NSString* collection = [command.arguments objectAtIndex:2]; + + [[[firestore collectionWithPath:collection] documentWithPath:documentId] setData:document completion:^(NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + } else { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)updateDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* documentId = [command.arguments objectAtIndex:0]; + NSDictionary* document = [command.arguments objectAtIndex:1]; + NSString* collection = [command.arguments objectAtIndex:2]; + + FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; + if(docRef != nil){ + [docRef updateData:document completion:^(NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + } else { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; + } + }]; + }else{ + [self sendPluginError:@"Document not found in collection":command]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)deleteDocumentFromFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* documentId = [command.arguments objectAtIndex:0]; + NSString* collection = [command.arguments objectAtIndex:1]; + + [[[firestore collectionWithPath:collection] documentWithPath:documentId] + deleteDocumentWithCompletion:^(NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + } else { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)documentExistsInFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* documentId = [command.arguments objectAtIndex:0]; + NSString* collection = [command.arguments objectAtIndex:1]; + + FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; + if(docRef != nil){ + [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + }else{ + BOOL docExists = snapshot.data != nil; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:docExists] callbackId:command.callbackId]; + } + }]; + }else{ + [self sendPluginError:@"Collection not found":command]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)fetchDocumentInFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* documentId = [command.arguments objectAtIndex:0]; + NSString* collection = [command.arguments objectAtIndex:1]; + + FIRDocumentReference* docRef = [[firestore collectionWithPath:collection] documentWithPath:documentId]; + if(docRef != nil){ + [docRef getDocumentWithCompletion:^(FIRDocumentSnapshot * _Nullable snapshot, NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + } else if(snapshot.data != nil) { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:snapshot.data] callbackId:command.callbackId]; + }else{ + [self sendPluginError:@"Document not found in collection":command]; + } + }]; + }else{ + [self sendPluginError:@"Collection not found":command]; + } + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +- (void)fetchFirestoreCollection:(CDVInvokedUrlCommand*)command { + [self.commandDelegate runInBackground:^{ + @try { + NSString* collection = [command.arguments objectAtIndex:0]; + NSArray* filters = [command.arguments objectAtIndex:1]; + FIRQuery* query = [firestore collectionWithPath:collection]; + + for (int i = 0; i < [filters count]; i++) { + NSArray* filter = [filters objectAtIndex:i]; + if ([[filter objectAtIndex:0] isEqualToString:@"where"]) { + if ([[filter objectAtIndex:2] isEqualToString:@"=="]) { + query = [query queryWhereField:[filter objectAtIndex:1] isEqualTo:[filter objectAtIndex:3]]; + } + if ([[filter objectAtIndex:2] isEqualToString:@"<"]) { + query = [query queryWhereField:[filter objectAtIndex:1] isLessThan:[filter objectAtIndex:3]]; + } + if ([[filter objectAtIndex:2] isEqualToString:@">"]) { + query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThan:[filter objectAtIndex:3]]; + } + if ([[filter objectAtIndex:2] isEqualToString:@"<="]) { + query = [query queryWhereField:[filter objectAtIndex:1] isLessThanOrEqualTo:[filter objectAtIndex:3]]; + } + if ([[filter objectAtIndex:2] isEqualToString:@">="]) { + query = [query queryWhereField:[filter objectAtIndex:1] isGreaterThanOrEqualTo:[filter objectAtIndex:3]]; + } + if ([[filter objectAtIndex:2] isEqualToString:@"array-contains"]) { + query = [query queryWhereField:[filter objectAtIndex:1] arrayContains:[filter objectAtIndex:3]]; + } + continue; + } + if ([[filter objectAtIndex:0] isEqualToString:@"orderBy"]) { + query = [query queryOrderedByField:[filter objectAtIndex:1] descending:([[filter objectAtIndex:2] isEqualToString:@"desc"])]; + continue; + } + if ([[filter objectAtIndex:0] isEqualToString:@"startAt"]) { + query = [query queryStartingAtValues:[filter objectAtIndex:1]]; + continue; + } + if ([[filter objectAtIndex:0] isEqualToString:@"endAt"]) { + query = [query queryEndingAtValues:[filter objectAtIndex:1]]; + continue; + } + if ([[filter objectAtIndex:0] isEqualToString:@"limit"]) { + query = [query queryLimitedTo:[(NSNumber *)[filter objectAtIndex:1] integerValue]]; + continue; + } + } + + [query getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { + if (error != nil) { + [self sendPluginError:error.localizedDescription:command]; + } else { + NSMutableDictionary* documents = [[NSMutableDictionary alloc] init];; + for (FIRDocumentSnapshot *document in snapshot.documents) { + [documents setObject:document.data forKey:document.documentID]; + } + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:documents] callbackId:command.callbackId]; + } + }]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } + }]; +} + +/********************************/ +#pragma mark - utility functions +/********************************/ +- (void) sendPluginError: (NSString*) errorMessage :(CDVInvokedUrlCommand*)command +{ + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage]; + [self _logError:errorMessage]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (void) handlePluginExceptionWithContext: (NSException*) exception :(CDVInvokedUrlCommand*)command +{ + [self handlePluginExceptionWithoutContext:exception]; + CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:exception.reason]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (void) handlePluginExceptionWithoutContext: (NSException*) exception +{ + [self _logError:[NSString stringWithFormat:@"EXCEPTION: %@", exception.reason]]; +} + +- (void)executeGlobalJavascript: (NSString*)jsString +{ + [self.commandDelegate evalJs:jsString]; +} + +- (void)_logError: (NSString*)msg +{ + NSLog(@"%@ ERROR: %@", LOG_TAG, msg); + NSString* jsString = [NSString stringWithFormat:@"console.error(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; + [self executeGlobalJavascript:jsString]; +} + +- (void)_logInfo: (NSString*)msg +{ + NSLog(@"%@ INFO: %@", LOG_TAG, msg); + NSString* jsString = [NSString stringWithFormat:@"console.info(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; + [self executeGlobalJavascript:jsString]; +} + +- (void)_logMessage: (NSString*)msg +{ + NSLog(@"%@ LOG: %@", LOG_TAG, msg); + NSString* jsString = [NSString stringWithFormat:@"console.log(\"%@: %@\")", LOG_TAG, [self escapeJavascriptString:msg]]; + [self executeGlobalJavascript:jsString]; +} + +- (NSString*)escapeJavascriptString: (NSString*)str +{ + NSString* result = [str stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""]; + result = [result stringByReplacingOccurrencesOfString: @"\n" withString: @"\\\n"]; + return result; +} + +- (void)runOnMainThread:(void (^)(void))completeBlock { + if (![NSThread isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + @try { + completeBlock(); + }@catch (NSException *exception) { + [self handlePluginExceptionWithoutContext:exception]; + } + }); + } else { + @try { + completeBlock(); + }@catch (NSException *exception) { + [self handlePluginExceptionWithoutContext:exception]; + } + } +} + +- (FIRAuthCredential*)obtainAuthCredential:(NSDictionary*)credential command:(CDVInvokedUrlCommand *)command { + FIRAuthCredential* authCredential = nil; + + if(credential == nil){ + NSString* errMsg = @"credential object must be passed as first and only argument"; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; + return authCredential; + } + + NSString* key = [credential objectForKey:@"id"]; + NSString* verificationId = [credential objectForKey:@"verificationId"]; + NSString* code = [credential objectForKey:@"code"]; + + if(key != nil){ + authCredential = [authCredentials objectForKey:key]; + if(authCredential == nil){ + NSString* errMsg = [NSString stringWithFormat:@"no native auth credential exists for specified id '%@'", key]; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; + } + }else if(verificationId != nil && code != nil){ + authCredential = [[FIRPhoneAuthProvider provider] + credentialWithVerificationID:verificationId + verificationCode:code]; + }else{ + NSString* errMsg = @"credential object must either specify the id key of an existing native auth credential or the verificationId/code keys must be specified for a phone number authentication"; + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errMsg] callbackId:command.callbackId]; + } + + return authCredential; +} + +- (void) handleAuthResult:(FIRAuthDataResult*) authResult error:(NSError*) error command:(CDVInvokedUrlCommand*)command { + @try { + CDVPluginResult* pluginResult; + if (error) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + }else if (authResult == nil) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"User not signed in"]; + }else{ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }@catch (NSException *exception) { + [self handlePluginExceptionWithContext:exception :command]; + } +} + +- (int) saveAuthCredential: (FIRAuthCredential*) authCredential { + int key = -1; + while (key < 0 || [authCredentials objectForKey:[NSNumber numberWithInt:key]] != nil) { + key = arc4random_uniform(100000); + } + + [authCredentials setObject:authCredential forKey:[NSNumber numberWithInt:key]]; + + return key; +} + +- (void) handleResultWithPotentialError:(NSError*) error command:(CDVInvokedUrlCommand*)command { + CDVPluginResult* pluginResult; + if (error) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.description]; + }else{ + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + } + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (void) setPreferenceFlag:(NSString*) name flag:(BOOL)flag { + [preferences setBool:flag forKey:name]; + [preferences synchronize]; +} + +- (BOOL) getPreferenceFlag:(NSString*) name { + if([preferences objectForKey:name] == nil){ + return false; + } + return [preferences boolForKey:name]; +} + +- (BOOL) getGooglePlistFlagWithDefaultValue:(NSString*) name defaultValue:(BOOL)defaultValue { + if([googlePlist objectForKey:name] == nil){ + return defaultValue; + } + return [[googlePlist objectForKey:name] isEqualToString:@"true"]; +} + + +# pragma mark - Stubs +- (void)createChannel:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; +} + +- (void)setDefaultChannel:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; +} + +- (void)deleteChannel:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; +} + +- (void)listChannels:(CDVInvokedUrlCommand *)command { + [self.commandDelegate runInBackground:^{ + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; +} +@end