diff --git a/.npmignore b/.npmignore new file mode 100644 index 00000000..2e0642a1 --- /dev/null +++ b/.npmignore @@ -0,0 +1 @@ +platforms/android/libraryproject/ \ No newline at end of file diff --git a/docs/MESSAGING.md b/docs/MESSAGING.md index 5eff21eb..ceb014ff 100644 --- a/docs/MESSAGING.md +++ b/docs/MESSAGING.md @@ -11,9 +11,10 @@ Version 3.3.0 of this plugin added FCM support (which is the successor of GCM). Although using push messages in your Firebase app is really easy setting it up is not. Traditionally, especially for iOS. ### Android -Work in progress. +Uncomment `firebase-messaging` in [include.gradle](../platforms/android/include.gradle) ### iOS +Uncomment `Firebase/Messaging` in [Podfile](../platforms/ios/Podfile) #### Receiving remote notifications in the background Open `app/App_Resources/iOS/Info.plist` and add this to the bottom: @@ -43,6 +44,7 @@ Any pending notifications (while your app was not in the foreground) will trigge console.log("Body: " + message.body); // if your server passed a custom property called 'foo', then do this: console.log("Value of 'foo': " + message.foo); + } }); ``` @@ -52,6 +54,41 @@ You don't _have_ to provide the handler during `init` - you can also do it throu firebase.addOnMessageReceivedCallback( function(message) { // .. - }); + } + ); +``` + +### Pushing to individual devices +If you want to send push messages to individual devices, either from your own backend or the FCM console, you need the push token. + +Similarly to the message callback you can either wire this through `init` or as a separate function: + +```js + firebase.init({ + onPushTokenReceivedCallback: function(token) { + console.log("Firebase push token: " + token); + } }); ``` + +.. or: + +```js + firebase.addOnPushTokenReceivedCallback( + function(token) { + // .. + } + ); +``` + +## Testing +Using the Firebase Console gives you most flexibility, but you can quickly and easily test from the command line as well: + +``` +curl -X POST --header "Authorization: key=SERVER_KEY" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"priority\": \"High\", \"to\": \"DEVICE_TOKEN\"}" +``` + +* SERVER_KEY: see below +* DEVICE_TOKEN: the on you got in `addOnPushTokenReceivedCallback` or `init`'s `onPushTokenReceivedCallback` + +Push server key diff --git a/docs/images/push-server-key.png b/docs/images/push-server-key.png new file mode 100644 index 00000000..feb56d7b Binary files /dev/null and b/docs/images/push-server-key.png differ diff --git a/firebase-common.js b/firebase-common.js index fd78b013..520e1e0a 100755 --- a/firebase-common.js +++ b/firebase-common.js @@ -26,15 +26,10 @@ firebase.QueryRangeType = { }; firebase.instance = null; - firebase.firebaseRemoteConfig = null; - firebase.authStateListeners = []; - firebase._receivedNotificationCallback = null; -firebase._pendingNotifications = []; - firebase.addAuthStateListener = function(listener) { if (firebase.authStateListeners.indexOf(listener) === -1) { firebase.authStateListeners.push(listener); diff --git a/firebase.android.js b/firebase.android.js index f2eae9ef..b6016169 100755 --- a/firebase.android.js +++ b/firebase.android.js @@ -1,6 +1,41 @@ var appModule = require("application"); var firebase = require("./firebase-common"); +firebase._launchNotification = null; + +(function() { + if (typeof(com.google.firebase.messaging) === "undefined") { + return; + } + appModule.onLaunch = function(intent) { + var extras = intent.getExtras(); + if (extras !== null) { + var result = { + foreground: false + }; + + var iterator = extras.keySet().iterator(); + while (iterator.hasNext()) { + var key = iterator.next(); + if (key !== "from" && key !== "collapse_key") { + result[key] = extras.get(key); + } + } + + // in case this was a cold start we don't have the _receivedNotificationCallback yet + if (firebase._receivedNotificationCallback === null) { + firebase._launchNotification = result; + } else { + // add a little delay just to make sure clients alerting this message will see it as the UI needs to settle + setTimeout(function() { + firebase._receivedNotificationCallback(result); + }); + } + } + }; + +})(); + firebase.toHashMap = function(obj) { var node = new java.util.HashMap(); for (var property in obj) { @@ -134,13 +169,12 @@ firebase.init = function (arg) { // Firebase notifications (FCM) if (typeof(com.google.firebase.messaging) !== "undefined") { - console.log("--- has messaging!"); - // TODO see iOS: - // firebase._addObserver(kFIRInstanceIDTokenRefreshNotification, firebase._onTokenRefreshNotification); if (arg.onMessageReceivedCallback !== undefined) { - console.log("--- adding messaging callback!"); firebase.addOnMessageReceivedCallback(arg.onMessageReceivedCallback); } + if (arg.onPushTokenReceivedCallback !== undefined) { + firebase.addOnPushTokenReceivedCallback(arg.onPushTokenReceivedCallback); + } } resolve(firebase.instance); @@ -160,7 +194,22 @@ firebase.addOnMessageReceivedCallback = function (callback) { } firebase._receivedNotificationCallback = callback; - firebase._processPendingNotifications(); + + org.nativescript.plugins.firebase.FirebasePlugin.setOnNotificationReceivedCallback( + new org.nativescript.plugins.firebase.FirebasePluginListener({ + success: function(notification) { + console.log("---------- received notification: " + notification); + callback(JSON.parse(notification)); + } + }) + ); + + // if the app was launched from a notification, process it now + if (firebase._launchNotification !== null) { + callback(firebase._launchNotification); + firebase._launchNotification = null; + } + resolve(); } catch (ex) { console.log("Error in firebase.addOnMessageReceivedCallback: " + ex); @@ -169,6 +218,30 @@ firebase.addOnMessageReceivedCallback = function (callback) { }); }; +firebase.addOnPushTokenReceivedCallback = function (callback) { + return new Promise(function (resolve, reject) { + try { + if (typeof(com.google.firebase.messaging) === "undefined") { + reject("Uncomment firebase-messaging in the plugin's include.gradle first"); + return; + } + + org.nativescript.plugins.firebase.FirebasePlugin.setOnPushTokenReceivedCallback( + new org.nativescript.plugins.firebase.FirebasePluginListener({ + success: function(token) { + callback(token); + } + }) + ); + + resolve(); + } catch (ex) { + console.log("Error in firebase.addOnPushTokenReceivedCallback: " + ex); + reject(ex); + } + }); +}; + firebase.getRemoteConfigDefaults = function (properties) { var defaults = {}; for (var p in properties) { @@ -180,6 +253,13 @@ firebase.getRemoteConfigDefaults = function (properties) { return defaults; }; +firebase._isGooglePlayServicesAvailable = function () { + var context = appModule.android.foregroundActivity; + var playServiceStatusSuccess = com.google.android.gms.common.ConnectionResult.SUCCESS; // 0 + var playServicesStatus = com.google.android.gms.common.GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context); + return playServicesStatus === playServiceStatusSuccess; +}; + firebase.getRemoteConfig = function (arg) { return new Promise(function (resolve, reject) { try { @@ -193,6 +273,11 @@ firebase.getRemoteConfig = function (arg) { return; } + if (!firebase._isGooglePlayServicesAvailable()) { + reject("Google Play services is required for this feature, but not available on this device"); + return; + } + // Get a Remote Config object instance firebaseRemoteConfig = com.google.firebase.remoteconfig.FirebaseRemoteConfig.getInstance(); @@ -236,7 +321,6 @@ firebase.getRemoteConfig = function (arg) { var onFailureListener = new com.google.android.gms.tasks.OnFailureListener({ onFailure: function (exception) { - console.log("--- onFailureListener: " + exception); if (exception == "com.google.firebase.remoteconfig.FirebaseRemoteConfigFetchThrottledException") { returnMethod(true); } else { @@ -323,6 +407,11 @@ function toLoginResult(user) { firebase.login = function (arg) { return new Promise(function (resolve, reject) { try { + if (!firebase._isGooglePlayServicesAvailable()) { + reject("Google Play services is required for this feature, but not available on this device"); + return; + } + var firebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance(); var onCompleteListener = new com.google.android.gms.tasks.OnCompleteListener({ onComplete: function (task) { diff --git a/firebase.d.ts b/firebase.d.ts index 26cae6a6..4624bde8 100644 --- a/firebase.d.ts +++ b/firebase.d.ts @@ -203,20 +203,27 @@ declare module "nativescript-plugin-firebase" { /** * The returned object in the callback handler of the addOnMessageReceivedCallback function. + * * Note that any custom data you send from your server will be available as * key/value properties on the Message object. */ export interface Message { + /** + * Indicated whether or not the notification was received while the app was in the foreground. + */ + foreground: boolean; /** * The main text shown in the notificiation. + * Not available on Android when the notification was received in the background. */ - body: string; + body?: string; /** * Optional title, shown above the body in the notification. + * Not available on Android when the notification was received in the background. */ title?: string; /** - * iOS badge number + * iOS badge count, as sent from the server. */ badge?: number; } @@ -226,6 +233,7 @@ declare module "nativescript-plugin-firebase" { export function logout(): Promise; export function getRemoteConfig(options: GetRemoteConfigOptions): Promise; export function addOnMessageReceivedCallback(onMessageReceived: (data: Message) => void): Promise; + export function addOnPushTokenReceivedCallback(onPushTokenReceived: (data: string) => void): Promise; export function createUser(options: CreateUserOptions): Promise; export function deleteUser(): Promise; export function resetPassword(options: ResetPasswordOptions): Promise; diff --git a/firebase.ios.js b/firebase.ios.js index d8c75898..7b01426a 100755 --- a/firebase.ios.js +++ b/firebase.ios.js @@ -4,6 +4,8 @@ var types = require("utils/types"); var frame = require("ui/frame"); firebase._messagingConnected = null; +firebase._pendingNotifications = []; +firebase._receivedPushTokenCallback = null; firebase._addObserver = function (eventName, callback) { return NSNotificationCenter.defaultCenter().addObserverForNameObjectQueueUsingBlock(eventName, null, NSOperationQueue.mainQueue(), callback); @@ -36,14 +38,15 @@ firebase.addAppDelegateMethods = function(appDelegate) { var userInfoJSON = firebase.toJsObject(userInfo); if (application.applicationState === UIApplicationState.UIApplicationStateActive) { - // foreground if (firebase._receivedNotificationCallback !== null) { + userInfoJSON.foreground = true; firebase._receivedNotificationCallback(userInfoJSON); } else { + userInfoJSON.foreground = false; firebase._pendingNotifications.push(userInfoJSON); } } else { - // background + userInfoJSON.foreground = false; firebase._pendingNotifications.push(userInfoJSON); } }; @@ -68,6 +71,23 @@ firebase.addOnMessageReceivedCallback = function (callback) { }); }; +firebase.addOnPushTokenReceivedCallback = function (callback) { + return new Promise(function (resolve, reject) { + try { + if (typeof(FIRMessaging) === "undefined") { + reject("Enable FIRMessaging in Podfile first"); + return; + } + + firebase._receivedPushTokenCallback = callback; + resolve(); + } catch (ex) { + console.log("Error in firebase.addOnPushTokenReceivedCallback: " + ex); + reject(ex); + } + }); +}; + firebase._processPendingNotifications = function() { if (firebase._receivedNotificationCallback !== null) { for (var p in firebase._pendingNotifications) { @@ -252,9 +272,14 @@ firebase.init = function (arg) { // Firebase notifications (FCM) if (typeof(FIRMessaging) !== "undefined") { firebase._addObserver(kFIRInstanceIDTokenRefreshNotification, firebase._onTokenRefreshNotification); + if (arg.onMessageReceivedCallback !== undefined) { firebase.addOnMessageReceivedCallback(arg.onMessageReceivedCallback); } + + if (arg.onPushTokenReceivedCallback !== undefined) { + firebase.addOnPushTokenReceivedCallback(arg.onPushTokenReceivedCallback); + } } resolve(firebase.instance); @@ -272,6 +297,11 @@ firebase._onTokenRefreshNotification = function (notification) { } console.log("Firebase FCM token received: " + token); + + if (firebase._receivedPushTokenCallback) { + firebase._receivedPushTokenCallback(token); + } + FIRMessaging.messaging().connectWithCompletion(function(error) { if (error !== null) { // this is not fatal at all but still would like to know how often this happens diff --git a/platforms/android/README.md b/platforms/android/README.md new file mode 100755 index 00000000..a2a3f7d0 --- /dev/null +++ b/platforms/android/README.md @@ -0,0 +1,15 @@ +For more sophisticated handling of Firebase Messaging we need to implement 2 services. +Those services must be configured in `AndroidManifest.xml` and we need to ship 2 additional classes. + +To make it as easy as possible for consumers of this plugin we bundle those bith in an `.aar` file. + +Steps to update the `.aar` file: + +* Clone this repo +* Start Android Studio and pick 'import existing project' > `{this repo}/platforms/android/libraryproject` +* Update `firebase/src/main/AndroidManifest.xml` as needed +* Open the Gradle toolwindow +* Run `firebase > Tasks > build > build` +* The (release) `.aar` will be generated in `firebase/build/outputs/aar` +* Copy that to the `platforms/android` folder, replacing the old `.aar` +* Commit and push the changes as usual \ No newline at end of file diff --git a/platforms/android/firebase-release.aar b/platforms/android/firebase-release.aar new file mode 100644 index 00000000..0ddfbdbc Binary files /dev/null and b/platforms/android/firebase-release.aar differ diff --git a/platforms/android/include.gradle b/platforms/android/include.gradle index 871c20c9..530e82ea 100644 --- a/platforms/android/include.gradle +++ b/platforms/android/include.gradle @@ -13,12 +13,12 @@ repositories { } dependencies { - // make sure you have these versions by updating your local Android SDK's (Android Support repo and Google repo) + // make sure you have these versions by updating your local Android SDK's (Android Support repo and Google repo) compile "com.google.firebase:firebase-database:9.0.2" compile "com.google.firebase:firebase-auth:9.0.2" // for reading google-services.json and configuration - compile "com.google.android.gms:play-services:9.0.2" + compile "com.google.android.gms:play-services-base:9.0.2" // Uncomment if you want to use 'Remote Config' // compile "com.google.firebase:firebase-config:9.0.2" diff --git a/platforms/android/libraryproject/.gitignore b/platforms/android/libraryproject/.gitignore new file mode 100755 index 00000000..c6cbe562 --- /dev/null +++ b/platforms/android/libraryproject/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/platforms/android/libraryproject/app/.gitignore b/platforms/android/libraryproject/app/.gitignore new file mode 100755 index 00000000..796b96d1 --- /dev/null +++ b/platforms/android/libraryproject/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/platforms/android/libraryproject/app/build.gradle b/platforms/android/libraryproject/app/build.gradle new file mode 100755 index 00000000..51a6faeb --- /dev/null +++ b/platforms/android/libraryproject/app/build.gradle @@ -0,0 +1,25 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 23 + buildToolsVersion "23.0.2" + + defaultConfig { + applicationId "org.nativescript.plugins.bluetooth" + minSdkVersion 14 + targetSdkVersion 23 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + testCompile 'junit:junit:4.12' +} diff --git a/platforms/android/libraryproject/app/proguard-rules.pro b/platforms/android/libraryproject/app/proguard-rules.pro new file mode 100755 index 00000000..98e8a3a8 --- /dev/null +++ b/platforms/android/libraryproject/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/eddyverbruggen/Toolshed/android-sdk-macosx/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/platforms/android/libraryproject/app/src/main/AndroidManifest.xml b/platforms/android/libraryproject/app/src/main/AndroidManifest.xml new file mode 100755 index 00000000..219cc6b6 --- /dev/null +++ b/platforms/android/libraryproject/app/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/platforms/android/libraryproject/app/src/main/res/mipmap-hdpi/ic_launcher.png b/platforms/android/libraryproject/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100755 index 00000000..cde69bcc Binary files /dev/null and b/platforms/android/libraryproject/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/platforms/android/libraryproject/app/src/main/res/mipmap-mdpi/ic_launcher.png b/platforms/android/libraryproject/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100755 index 00000000..c133a0cb Binary files /dev/null and b/platforms/android/libraryproject/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/platforms/android/libraryproject/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/platforms/android/libraryproject/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100755 index 00000000..bfa42f0e Binary files /dev/null and b/platforms/android/libraryproject/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/platforms/android/libraryproject/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/platforms/android/libraryproject/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100755 index 00000000..324e72cd Binary files /dev/null and b/platforms/android/libraryproject/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/platforms/android/libraryproject/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/platforms/android/libraryproject/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100755 index 00000000..aee44e13 Binary files /dev/null and b/platforms/android/libraryproject/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/platforms/android/libraryproject/app/src/main/res/values/colors.xml b/platforms/android/libraryproject/app/src/main/res/values/colors.xml new file mode 100755 index 00000000..5a077b3a --- /dev/null +++ b/platforms/android/libraryproject/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #3F51B5 + #303F9F + #FF4081 + diff --git a/platforms/android/libraryproject/app/src/main/res/values/strings.xml b/platforms/android/libraryproject/app/src/main/res/values/strings.xml new file mode 100755 index 00000000..0f05168f --- /dev/null +++ b/platforms/android/libraryproject/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Bluetooth + diff --git a/platforms/android/libraryproject/app/src/main/res/values/styles.xml b/platforms/android/libraryproject/app/src/main/res/values/styles.xml new file mode 100755 index 00000000..705be277 --- /dev/null +++ b/platforms/android/libraryproject/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/platforms/android/libraryproject/build.gradle b/platforms/android/libraryproject/build.gradle new file mode 100755 index 00000000..03bced9f --- /dev/null +++ b/platforms/android/libraryproject/build.gradle @@ -0,0 +1,23 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.1.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/platforms/android/libraryproject/firebase/.gitignore b/platforms/android/libraryproject/firebase/.gitignore new file mode 100644 index 00000000..796b96d1 --- /dev/null +++ b/platforms/android/libraryproject/firebase/.gitignore @@ -0,0 +1 @@ +/build diff --git a/platforms/android/libraryproject/firebase/build.gradle b/platforms/android/libraryproject/firebase/build.gradle new file mode 100644 index 00000000..bb407907 --- /dev/null +++ b/platforms/android/libraryproject/firebase/build.gradle @@ -0,0 +1,26 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion 23 + buildToolsVersion "23.0.3" + + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile 'com.google.firebase:firebase-messaging:9.0.2' +// compile 'com.android.support:appcompat-v7:23.+' + compile fileTree(dir: 'libs', include: ['*.jar']) +// testCompile 'junit:junit:4.12' +} diff --git a/platforms/android/libraryproject/firebase/proguard-rules.pro b/platforms/android/libraryproject/firebase/proguard-rules.pro new file mode 100644 index 00000000..98e8a3a8 --- /dev/null +++ b/platforms/android/libraryproject/firebase/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/eddyverbruggen/Toolshed/android-sdk-macosx/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/platforms/android/libraryproject/firebase/src/main/AndroidManifest.xml b/platforms/android/libraryproject/firebase/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e56a220f --- /dev/null +++ b/platforms/android/libraryproject/firebase/src/main/AndroidManifest.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/FirebasePlugin.java b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/FirebasePlugin.java new file mode 100644 index 00000000..9374c411 --- /dev/null +++ b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/FirebasePlugin.java @@ -0,0 +1,54 @@ +package org.nativescript.plugins.firebase; + +import android.util.Log; + +public class FirebasePlugin { + + static final String TAG = "FirebasePlugin"; + + private static String cachedToken; + private static String cachedNotification; + + private static FirebasePluginListener onPushTokenReceivedCallback; + private static FirebasePluginListener onNotificationReceivedCallback; + + public static void setOnPushTokenReceivedCallback(FirebasePluginListener callbacks) { + Log.d(TAG, "******* Setting onPushTokenReceivedCallback"); + onPushTokenReceivedCallback = callbacks; + if (cachedToken != null) { + Log.d(TAG, "******* Setting onPushTokenReceivedCallback - cachedToken is available"); + executeOnPushTokenReceivedCallback(cachedToken); + cachedToken = null; + } + } + + public static void setOnNotificationReceivedCallback(FirebasePluginListener callbacks) { + Log.d(TAG, "******* Setting onNotificationReceivedCallback"); + onNotificationReceivedCallback = callbacks; + if (cachedNotification != null) { + Log.d(TAG, "******* Setting onNotificationReceivedCallback - cachedNotification is available"); + executeOnNotificationReceivedCallback(cachedNotification); + cachedNotification = null; + } + } + + public static void executeOnPushTokenReceivedCallback(String token) { + if (onPushTokenReceivedCallback != null) { + Log.d(TAG, "******* Sending message to client"); + onPushTokenReceivedCallback.success(token); + } else { + Log.d(TAG, "******* No callback function - caching the data for later retrieval."); + cachedToken = token; + } + } + + public static void executeOnNotificationReceivedCallback(String notification) { + if (onNotificationReceivedCallback != null) { + Log.d(TAG, "******* Sending message to client"); + onNotificationReceivedCallback.success(notification); + } else { + Log.d(TAG, "******* No callback function - caching the data for later retrieval."); + cachedNotification = notification; + } + } +} diff --git a/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/FirebasePluginListener.java b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/FirebasePluginListener.java new file mode 100644 index 00000000..d8ec70a5 --- /dev/null +++ b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/FirebasePluginListener.java @@ -0,0 +1,6 @@ +package org.nativescript.plugins.firebase; + +public interface FirebasePluginListener { + void success(Object data); + void error(Object data); +} diff --git a/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/MyFirebaseInstanceIDService.java b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/MyFirebaseInstanceIDService.java new file mode 100644 index 00000000..e2741793 --- /dev/null +++ b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/MyFirebaseInstanceIDService.java @@ -0,0 +1,16 @@ +package org.nativescript.plugins.firebase; + +import com.google.firebase.iid.FirebaseInstanceId; +import com.google.firebase.iid.FirebaseInstanceIdService; + +public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { + + @Override + public void onTokenRefresh() { + // Get updated InstanceID token (may be null in case the device has no internet) + final String refreshedToken = FirebaseInstanceId.getInstance().getToken(); + + // Send to client + FirebasePlugin.executeOnPushTokenReceivedCallback(refreshedToken); + } +} diff --git a/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/MyFirebaseMessagingService.java b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/MyFirebaseMessagingService.java new file mode 100644 index 00000000..ec3b5d10 --- /dev/null +++ b/platforms/android/libraryproject/firebase/src/main/java/org/nativescript/plugins/firebase/MyFirebaseMessagingService.java @@ -0,0 +1,61 @@ +package org.nativescript.plugins.firebase; + +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Map; + +/** + * This class takes care of notifications received while the app is in the foreground. + */ +public class MyFirebaseMessagingService extends FirebaseMessagingService { + + @Override + public void onMessageReceived(RemoteMessage remoteMessage) { + RemoteMessage.Notification not = remoteMessage.getNotification(); + try { + JSONObject json = new JSONObject() + .put("title", not.getTitle()) + .put("body", not.getBody()) + .put("foreground", true); + + Map data = remoteMessage.getData(); + for (Map.Entry stringStringEntry : data.entrySet()) { + json.put(stringStringEntry.getKey(), stringStringEntry.getValue()); + } + + FirebasePlugin.executeOnNotificationReceivedCallback(json.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + + /* + private void sendNotification(String messageBody) { + Intent intent = new Intent(this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, + PendingIntent.FLAG_ONE_SHOT); + + Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) + .setSmallIcon(R.drawable.ic_stat_ic_notification) + .setContentTitle("FCM Message") + .setContentText(messageBody) + .setAutoCancel(true) + .setSound(defaultSoundUri) + .setContentIntent(pendingIntent); + + NotificationManager notificationManager = + (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + + // 0 = id of notification + notificationManager.notify(0, notificationBuilder.build()); + } +*/ + +} diff --git a/platforms/android/libraryproject/firebase/src/main/res/values/strings.xml b/platforms/android/libraryproject/firebase/src/main/res/values/strings.xml new file mode 100644 index 00000000..e73f40a9 --- /dev/null +++ b/platforms/android/libraryproject/firebase/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Firebase + diff --git a/platforms/android/libraryproject/gradle.properties b/platforms/android/libraryproject/gradle.properties new file mode 100755 index 00000000..1d3591c8 --- /dev/null +++ b/platforms/android/libraryproject/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true \ No newline at end of file diff --git a/platforms/android/libraryproject/gradle/wrapper/gradle-wrapper.jar b/platforms/android/libraryproject/gradle/wrapper/gradle-wrapper.jar new file mode 100755 index 00000000..13372aef Binary files /dev/null and b/platforms/android/libraryproject/gradle/wrapper/gradle-wrapper.jar differ diff --git a/platforms/android/libraryproject/gradle/wrapper/gradle-wrapper.properties b/platforms/android/libraryproject/gradle/wrapper/gradle-wrapper.properties new file mode 100755 index 00000000..122a0dca --- /dev/null +++ b/platforms/android/libraryproject/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Dec 28 10:00:20 PST 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip diff --git a/platforms/android/libraryproject/gradlew b/platforms/android/libraryproject/gradlew new file mode 100755 index 00000000..9d82f789 --- /dev/null +++ b/platforms/android/libraryproject/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/platforms/android/libraryproject/gradlew.bat b/platforms/android/libraryproject/gradlew.bat new file mode 100755 index 00000000..8a0b282a --- /dev/null +++ b/platforms/android/libraryproject/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/platforms/android/libraryproject/settings.gradle b/platforms/android/libraryproject/settings.gradle new file mode 100755 index 00000000..c4b4a0b0 --- /dev/null +++ b/platforms/android/libraryproject/settings.gradle @@ -0,0 +1 @@ +include ':firebase'