From 6205af7ba2701aedeb37d8b022ab5a854c4bb0ef Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Wed, 17 Mar 2021 12:55:32 -0300 Subject: [PATCH 01/55] Update Android and iOS Versions * Update Android to 4.2.0 and iOS to 3.2.3 --- plugin.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin.xml b/plugin.xml index 05cd5d78..73e1b9a5 100644 --- a/plugin.xml +++ b/plugin.xml @@ -26,7 +26,7 @@ - + @@ -88,7 +88,7 @@ production - + From 2c83794a993719445f26e771ef51a4b9bb87993d Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Wed, 17 Mar 2021 13:12:34 -0300 Subject: [PATCH 02/55] Migrate OneSignalPush.java file --- src/android/com/plugin/gcm/OneSignalPush.java | 72 +++++-------------- 1 file changed, 17 insertions(+), 55 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index 76c35c6c..de6f87e7 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -1,7 +1,7 @@ /** * Modified MIT License * - * Copyright 2017 OneSignal + * Copyright 2021 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,24 +28,17 @@ package com.plugin.gcm; import android.util.Log; + +import com.onesignal.OSInAppMessageAction; +import com.onesignal.OSNotificationReceivedEvent; +import com.onesignal.OneSignal; + import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import com.onesignal.OneSignal; -import com.onesignal.OSNotification; -import com.onesignal.OSNotificationOpenResult; -import com.onesignal.OSInAppMessageAction; -import com.onesignal.OneSignal.NotificationOpenedHandler; -import com.onesignal.OneSignal.NotificationReceivedHandler; -import com.onesignal.OneSignal.InAppMessageClickHandler; - -import com.onesignal.OSPermissionObserver; -import com.onesignal.OSEmailSubscriptionObserver; -import com.onesignal.OSSubscriptionObserver; - public class OneSignalPush extends CordovaPlugin { private static final String TAG = "OneSignalPush"; @@ -127,22 +120,10 @@ public boolean init(CallbackContext callbackContext, JSONArray data) { String googleProjectNumber = data.getString(1); OneSignal.sdkType = "cordova"; - OneSignal.Builder builder = OneSignal.getCurrentOrNewInitBuilder(); - builder.unsubscribeWhenNotificationsAreDisabled(true); - builder.filterOtherGCMReceivers(true); - builder.setInAppMessageClickHandler(new CordovaInAppMessageClickHandler(inAppMessageClickedCallbackContext)); - - OneSignal.init(this.cordova.getActivity(), - googleProjectNumber, - appId, - new CordovaNotificationOpenedHandler(notifOpenedCallbackContext), - new CordovaNotificationReceivedHandler(notifReceivedCallbackContext) - ); - // data.getJSONObject(2) is for iOS settings. - - int displayOption = data.getInt(3); - OneSignal.setInFocusDisplaying(displayOption); + OneSignal.setInAppMessageClickHandler(new CordovaInAppMessageClickHandler(inAppMessageClickedCallbackContext)); + OneSignal.setAppId(appId); + OneSignal.initWithContext(this.cordova.getActivity()); return true; } catch (JSONException e) { @@ -155,7 +136,6 @@ public boolean init(CallbackContext callbackContext, JSONArray data) { public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { boolean result = false; - switch(action) { case SET_NOTIFICATION_OPENED_HANDLER: result = setNotificationOpenedHandler(callbackContext); @@ -322,37 +302,19 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo * Handlers */ - private class CordovaNotificationReceivedHandler implements NotificationReceivedHandler { - - private CallbackContext jsNotificationReceivedCallBack; - - public CordovaNotificationReceivedHandler(CallbackContext inCallbackContext) { - jsNotificationReceivedCallBack = inCallbackContext; - } - - @Override - public void notificationReceived(OSNotification notification) { - try { - CallbackHelper.callbackSuccess(jsNotificationReceivedCallBack, new JSONObject(notification.stringify())); - } - catch (Throwable t) { - t.printStackTrace(); - } - } - } - - private class CordovaNotificationOpenedHandler implements NotificationOpenedHandler { + private class CordovaNotificationInForegroundHandler implements OneSignal.OSNotificationWillShowInForegroundHandler { private CallbackContext jsNotificationOpenedCallBack; - public CordovaNotificationOpenedHandler(CallbackContext inCallbackContext) { + public CordovaNotificationInForegroundHandler(CallbackContext inCallbackContext) { jsNotificationOpenedCallBack = inCallbackContext; } @Override - public void notificationOpened(OSNotificationOpenResult result) { + public void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) { try { - CallbackHelper.callbackSuccess(jsNotificationOpenedCallBack, new JSONObject(result.stringify())); + notificationReceivedEvent.complete(notificationReceivedEvent.getNotification()); + CallbackHelper.callbackSuccess(jsNotificationOpenedCallBack, new JSONObject(notificationReceivedEvent.toJSONObject().toString())); } catch (Throwable t) { t.printStackTrace(); @@ -360,7 +322,7 @@ public void notificationOpened(OSNotificationOpenResult result) { } } - private class CordovaInAppMessageClickHandler implements InAppMessageClickHandler { + private class CordovaInAppMessageClickHandler implements OneSignal.OSInAppMessageClickHandler { private CallbackContext jsInAppMessageClickedCallback; @@ -381,7 +343,7 @@ public void inAppMessageClicked(OSInAppMessageAction result) { @Override public void onDestroy() { - OneSignal.removeNotificationOpenedHandler(); - OneSignal.removeNotificationReceivedHandler(); + OneSignal.setNotificationOpenedHandler(null); + OneSignal.setNotificationWillShowInForegroundHandler(null); } } From c8ae25024263fca28e787d071f16215cee72a9ce Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Wed, 17 Mar 2021 13:12:51 -0300 Subject: [PATCH 03/55] Migrate OneSignalOutcomeController.java file --- .../plugin/gcm/OneSignalOutcomeController.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalOutcomeController.java b/src/android/com/plugin/gcm/OneSignalOutcomeController.java index a671a8ad..cc35ef7b 100644 --- a/src/android/com/plugin/gcm/OneSignalOutcomeController.java +++ b/src/android/com/plugin/gcm/OneSignalOutcomeController.java @@ -2,12 +2,12 @@ import android.util.Log; +import androidx.annotation.Nullable; + +import com.onesignal.OSOutcomeEvent; import com.onesignal.OneSignal; -import com.onesignal.OutcomeEvent; -import com.onesignal.OneSignal.OutcomeCallback; import org.apache.cordova.CallbackContext; - import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -20,9 +20,9 @@ public static boolean sendUniqueOutcome(CallbackContext callbackContext, JSONArr try { final CallbackContext jsSendUniqueOutcomeCallback = callbackContext; final String name = data.getString(0); - OneSignal.sendUniqueOutcome(name, new OutcomeCallback(){ + OneSignal.sendUniqueOutcome(name, new OneSignal.OutcomeCallback(){ @Override - public void onSuccess(OutcomeEvent outcomeEvent) { + public void onSuccess(@Nullable OSOutcomeEvent outcomeEvent) { if (outcomeEvent == null) CallbackHelper.callbackSuccess(jsSendUniqueOutcomeCallback, new JSONObject()); else { @@ -45,9 +45,9 @@ public static boolean sendOutcome(CallbackContext callbackContext, JSONArray dat try { final CallbackContext jsSendOutcomeCallback = callbackContext; final String name = data.getString(0); - OneSignal.sendOutcome(name, new OutcomeCallback() { + OneSignal.sendOutcome(name, new OneSignal.OutcomeCallback(){ @Override - public void onSuccess(OutcomeEvent outcomeEvent) { + public void onSuccess(@Nullable OSOutcomeEvent outcomeEvent) { if (outcomeEvent == null) CallbackHelper.callbackSuccess(jsSendOutcomeCallback, new JSONObject()); else { @@ -71,9 +71,9 @@ public static boolean sendOutcomeWithValue(CallbackContext callbackContext, JSON final CallbackContext jsSendOutcomeWithValueCallback = callbackContext; final String name = data.getString(0); final float value = Double.valueOf(data.optDouble(1)).floatValue(); - OneSignal.sendOutcomeWithValue(name, value, new OutcomeCallback() { + OneSignal.sendOutcomeWithValue(name, value,new OneSignal.OutcomeCallback(){ @Override - public void onSuccess(OutcomeEvent outcomeEvent) { + public void onSuccess(@Nullable OSOutcomeEvent outcomeEvent) { if (outcomeEvent == null) CallbackHelper.callbackSuccess(jsSendOutcomeWithValueCallback, new JSONObject()); else { From f8b41736a89689095b0433dc47bd4953eff1616d Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Wed, 17 Mar 2021 13:19:01 -0300 Subject: [PATCH 04/55] Migrate OneSignalController.java file * Update OneSignalPush.java after OneSignalController.java migration --- .../com/plugin/gcm/OneSignalController.java | 100 ++++++------------ src/android/com/plugin/gcm/OneSignalPush.java | 16 +-- 2 files changed, 35 insertions(+), 81 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalController.java b/src/android/com/plugin/gcm/OneSignalController.java index 8755d81b..2f319183 100644 --- a/src/android/com/plugin/gcm/OneSignalController.java +++ b/src/android/com/plugin/gcm/OneSignalController.java @@ -1,25 +1,17 @@ package com.plugin.gcm; -import android.util.Log; +import com.onesignal.OSDeviceState; +import com.onesignal.OneSignal; +import com.onesignal.OneSignal.PostNotificationResponseHandler; + import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; + import java.util.ArrayList; import java.util.Collection; - -import com.onesignal.OneSignal; -import com.onesignal.OSNotification; -import com.onesignal.OSNotificationOpenResult; -import com.onesignal.OSInAppMessageAction; - -import com.onesignal.OneSignal.NotificationOpenedHandler; -import com.onesignal.OneSignal.NotificationReceivedHandler; -import com.onesignal.OneSignal.GetTagsHandler; -import com.onesignal.OneSignal.IdsAvailableHandler; -import com.onesignal.OneSignal.PostNotificationResponseHandler; - public class OneSignalController { private static CallbackContext notifReceivedCallbackContext; private static CallbackContext notifOpenedCallbackContext; @@ -32,7 +24,7 @@ public class OneSignalController { */ public static boolean getTags(CallbackContext callbackContext) { final CallbackContext jsTagsAvailableCallBack = callbackContext; - OneSignal.getTags(new GetTagsHandler() { + OneSignal.getTags(new OneSignal.OSGetTagsHandler() { @Override public void tagsAvailable(JSONObject tags) { CallbackHelper.callbackSuccess(jsTagsAvailableCallBack, tags); @@ -67,14 +59,16 @@ public static boolean deleteTags(JSONArray data) { /** * Subscriptions */ - public static boolean getPermissionSubscriptionState(CallbackContext callbackContext) { - CallbackHelper.callbackSuccess(callbackContext, OneSignal.getPermissionSubscriptionState().toJSONObject()); + public static boolean getDeviceState(CallbackContext callbackContext) { + OSDeviceState deviceState = OneSignal.getDeviceState(); + if (deviceState != null) + CallbackHelper.callbackSuccess(callbackContext, deviceState.toJSONObject()); return true; } - public static boolean setSubscription(JSONArray data) { + public static boolean disablePush(JSONArray data) { try { - OneSignal.setSubscription(data.getBoolean(0)); + OneSignal.disablePush(data.getBoolean(0)); return true; } catch (Throwable t) { @@ -147,59 +141,22 @@ public static boolean registerForPushNotifications() { } public static boolean getIds(CallbackContext callbackContext) { - final CallbackContext jsIdsAvailableCallBack = callbackContext; - OneSignal.idsAvailable(new IdsAvailableHandler() { - @Override - public void idsAvailable(String userId, String registrationId) { - JSONObject jsonIds = new JSONObject(); - try { - jsonIds.put("userId", userId); - if (registrationId != null) - jsonIds.put("pushToken", registrationId); - else - jsonIds.put("pushToken", ""); - - CallbackHelper.callbackSuccess(jsIdsAvailableCallBack, jsonIds); - } - catch (Throwable t) { - t.printStackTrace(); - } - } - }); - return true; - } + OSDeviceState deviceState = OneSignal.getDeviceState(); - public static boolean enableVibrate(JSONArray data) { - try { - OneSignal.enableVibrate(data.getBoolean(0)); - return true; - } - catch (Throwable t) { - t.printStackTrace(); + if (deviceState == null) return false; - } - } - public static boolean enableSound(JSONArray data) { + JSONObject jsonIds = new JSONObject(); try { - OneSignal.enableSound(data.getBoolean(0)); - return true; - } - catch (Throwable t) { + jsonIds.put("userId", deviceState.getUserId()); + jsonIds.put("pushToken", deviceState.getPushToken() == null ? "" : deviceState.getPushToken()); + + CallbackHelper.callbackSuccess(callbackContext, jsonIds); + } catch (Throwable t) { t.printStackTrace(); - return false; } - } - public static boolean setInFocusDisplaying(JSONArray data) { - try { - OneSignal.setInFocusDisplaying(data.getInt(0)); - return true; - } - catch (JSONException e) { - Log.e(TAG, "execute: Got JSON Exception " + e.getMessage()); - return false; - } + return true; } public static void setLogLevel(JSONArray data) { @@ -214,7 +171,6 @@ public static void setLogLevel(JSONArray data) { public static boolean userProvidedConsent(CallbackContext callbackContext) { boolean providedConsent = OneSignal.userProvidedPrivacyConsent(); - final CallbackContext jsUserProvidedConsentContext = callbackContext; CallbackHelper.callbackSuccessBoolean(callbackContext, providedConsent); return true; } @@ -247,9 +203,14 @@ public static boolean setExternalUserId(final CallbackContext callback, JSONArra OneSignal.setExternalUserId(data.getString(0), authHashToken, new OneSignal.OSExternalUserIdUpdateCompletionHandler() { @Override - public void onComplete(JSONObject results) { + public void onSuccess(JSONObject results) { CallbackHelper.callbackSuccess(callback, results); } + + @Override + public void onFailure(OneSignal.ExternalIdError error) { + CallbackHelper.callbackError(callback, error.getMessage()); + } }); return true; } catch (JSONException e) { @@ -261,9 +222,14 @@ public void onComplete(JSONObject results) { public static boolean removeExternalUserId(final CallbackContext callback) { OneSignal.removeExternalUserId(new OneSignal.OSExternalUserIdUpdateCompletionHandler() { @Override - public void onComplete(JSONObject results) { + public void onSuccess(JSONObject results) { CallbackHelper.callbackSuccess(callback, results); } + + @Override + public void onFailure(OneSignal.ExternalIdError error) { + CallbackHelper.callbackError(callback, error.getMessage()); + } }); return true; } diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index de6f87e7..c0647c1e 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -153,10 +153,6 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = init(callbackContext, data); break; - case SET_IN_FOCUS_DISPLAYING: - result = OneSignalController.setInFocusDisplaying(data); - break; - case ADD_PERMISSION_OBSERVER: result = OneSignalObserverController.addPermissionObserver(callbackContext); break; @@ -174,7 +170,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo break; case GET_PERMISSION_SUBCRIPTION_STATE: - result = OneSignalController.getPermissionSubscriptionState(callbackContext); + result = OneSignalController.getDeviceState(callbackContext); break; case GET_IDS: @@ -193,16 +189,8 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.registerForPushNotifications(); break; - case ENABLE_VIBRATE: - result = OneSignalController.enableVibrate(data); - break; - - case ENABLE_SOUND: - result = OneSignalController.enableSound(data); - break; - case SET_SUBSCRIPTION: - result = OneSignalController.setSubscription(data); + result = OneSignalController.disablePush(data); break; case POST_NOTIFICATION: From baced83896fe1f97f9da9c004cb7bd089a660993 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Wed, 17 Mar 2021 13:21:08 -0300 Subject: [PATCH 05/55] Migrate OneSignalEmailController.java file * Update OneSignalPush.java after OneSignalEmailController.java migration --- .../plugin/gcm/OneSignalEmailController.java | 145 ++++++++---------- src/android/com/plugin/gcm/OneSignalPush.java | 4 - 2 files changed, 68 insertions(+), 81 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalEmailController.java b/src/android/com/plugin/gcm/OneSignalEmailController.java index b4598530..a7586a9c 100644 --- a/src/android/com/plugin/gcm/OneSignalEmailController.java +++ b/src/android/com/plugin/gcm/OneSignalEmailController.java @@ -1,97 +1,88 @@ package com.plugin.gcm; +import com.onesignal.OneSignal; +import com.onesignal.OneSignal.EmailUpdateError; +import com.onesignal.OneSignal.EmailUpdateHandler; + import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import com.onesignal.OneSignal; -import com.onesignal.OneSignal.EmailUpdateHandler; -import com.onesignal.OneSignal.EmailUpdateError; - - public class OneSignalEmailController { - public static boolean setEmail(CallbackContext callbackContext, JSONArray data) { - final CallbackContext jsSetEmailContext = callbackContext; - try { - OneSignal.setEmail(data.getString(0), data.getString(1), new EmailUpdateHandler() { - @Override - public void onSuccess() { - CallbackHelper.callbackSuccess(jsSetEmailContext, null); - } + public static boolean setEmail(CallbackContext callbackContext, JSONArray data) { + final CallbackContext jsSetEmailContext = callbackContext; + try { + OneSignal.setEmail(data.getString(0), data.getString(1), new EmailUpdateHandler() { + @Override + public void onSuccess() { + CallbackHelper.callbackSuccess(jsSetEmailContext, null); + } - @Override - public void onFailure(EmailUpdateError error) { - try { - JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); - CallbackHelper.callbackError(jsSetEmailContext, errorObject); - } catch (JSONException e) { - e.printStackTrace(); - } - } - }); + @Override + public void onFailure(EmailUpdateError error) { + try { + JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); + CallbackHelper.callbackError(jsSetEmailContext, errorObject); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); - return true; - } catch(Throwable t) { - t.printStackTrace(); - return false; + return true; + } catch (Throwable t) { + t.printStackTrace(); + return false; + } } - } - public static boolean setUnauthenticatedEmail(CallbackContext callbackContext, JSONArray data) { - final CallbackContext jsSetEmailContext = callbackContext; - try { - OneSignal.setEmail(data.getString(0), null, new EmailUpdateHandler() { - @Override - public void onSuccess() { - CallbackHelper.callbackSuccess(jsSetEmailContext, null); - } + public static boolean setUnauthenticatedEmail(CallbackContext callbackContext, JSONArray data) { + final CallbackContext jsSetEmailContext = callbackContext; + try { + OneSignal.setEmail(data.getString(0), null, new EmailUpdateHandler() { + @Override + public void onSuccess() { + CallbackHelper.callbackSuccess(jsSetEmailContext, null); + } - @Override - public void onFailure(EmailUpdateError error) { - try { - JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); - CallbackHelper.callbackError(jsSetEmailContext, errorObject); - } catch (JSONException e) { - e.printStackTrace(); - } - } - }); + @Override + public void onFailure(EmailUpdateError error) { + try { + JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); + CallbackHelper.callbackError(jsSetEmailContext, errorObject); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); - return true; - } catch (Throwable t) { - t.printStackTrace(); - return false; + return true; + } catch (Throwable t) { + t.printStackTrace(); + return false; + } } - } - - public static boolean logoutEmail(CallbackContext callbackContext) { - final CallbackContext jsSetEmailContext = callbackContext; - OneSignal.logoutEmail(new EmailUpdateHandler() { - @Override - public void onSuccess() { - CallbackHelper.callbackSuccess(jsSetEmailContext, null); - } - @Override - public void onFailure(EmailUpdateError error) { - try { - JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); - CallbackHelper.callbackError(jsSetEmailContext, errorObject); - } catch (JSONException e) { - e.printStackTrace(); - } - } - }); + public static boolean logoutEmail(CallbackContext callbackContext) { + final CallbackContext jsSetEmailContext = callbackContext; + OneSignal.logoutEmail(new EmailUpdateHandler() { + @Override + public void onSuccess() { + CallbackHelper.callbackSuccess(jsSetEmailContext, null); + } - return true; - } + @Override + public void onFailure(EmailUpdateError error) { + try { + JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); + CallbackHelper.callbackError(jsSetEmailContext, errorObject); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); - public static void syncHashedEmail(JSONArray data) { - try { - OneSignal.syncHashedEmail(data.getString(0)); - } catch(Throwable t) { - t.printStackTrace(); + return true; } - } } diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index c0647c1e..d7a4e492 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -201,10 +201,6 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo OneSignalController.promptLocation(); break; - case SYNC_HASHED_EMAIL: - OneSignalEmailController.syncHashedEmail(data); - break; - case SET_LOG_LEVEL: OneSignalController.setLogLevel(data); break; From f561c29fdae8047e2ea1c0ee2a9f433f78a317e8 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Wed, 17 Mar 2021 13:28:38 -0300 Subject: [PATCH 06/55] Migrate OneSignalInAppMessagingController.java file --- .../OneSignalInAppMessagingController.java | 125 ++++++++++-------- 1 file changed, 71 insertions(+), 54 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java b/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java index 090d94c2..c60f2162 100644 --- a/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java +++ b/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java @@ -1,76 +1,93 @@ package com.plugin.gcm; -import org.apache.cordova.CallbackContext; +import com.onesignal.OneSignal; +import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; -import com.onesignal.OneSignal; +public class OneSignalInAppMessagingController { + // This is to prevent an issue where if two Javascript calls are made to OneSignal expecting a callback then only one would fire. + private static void callbackSuccess(CallbackContext callbackContext, JSONObject jsonObject) { + if (jsonObject == null) // in case there are no data + jsonObject = new JSONObject(); -public class OneSignalInAppMessagingController { + PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jsonObject); + pluginResult.setKeepCallback(true); + callbackContext.sendPluginResult(pluginResult); + } - // This is to prevent an issue where if two Javascript calls are made to OneSignal expecting a callback then only one would fire. - private static void callbackSuccess(CallbackContext callbackContext, JSONObject jsonObject) { - if (jsonObject == null) // in case there are no data - jsonObject = new JSONObject(); + public static boolean addTriggers(JSONArray data) { + try { + JSONObject triggersObject = data.getJSONObject(0); + Map triggers = new HashMap<>(); + Iterator keys = triggersObject.keys(); - PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, jsonObject); - pluginResult.setKeepCallback(true); - callbackContext.sendPluginResult(pluginResult); - } - + while (keys.hasNext()) { + String key = keys.next(); + triggers.put(key, triggersObject.get(key)); + } - public static boolean addTriggers(JSONArray data) { - try { - OneSignal.addTriggersFromJsonString(data.getJSONObject(0).toString()); - return true; - } catch (JSONException e) { - e.printStackTrace(); - return false; + OneSignal.addTriggers(triggers); + return true; + } catch (JSONException e) { + e.printStackTrace(); + return false; + } } - } - public static boolean removeTriggersForKeys(JSONArray data) { - try{ - OneSignal.removeTriggersForKeysFromJsonArrayString(data.getString(0)); - return true; - } catch (JSONException e){ - e.printStackTrace(); - return false; - } - } + public static boolean removeTriggersForKeys(JSONArray data) { + try { + JSONArray triggerKeysArray = data.getJSONArray(0); + List triggerKeys = new ArrayList<>(); + + for (int i = 0; i < triggerKeysArray.length(); i++) { + triggerKeys.add(triggerKeysArray.getString(i)); + } - public static boolean getTriggerValueForKey(CallbackContext callbackContext, JSONArray data) { - try { - Object value = OneSignal.getTriggerValueForKey(data.getString(0)); - if (value == null) { - callbackSuccess(callbackContext, new JSONObject()); - } else { - callbackSuccess(callbackContext, new JSONObject( - "{value:" - + value.toString() - + "}")); - } - return true; - } catch (JSONException e){ - e.printStackTrace(); - return false; + OneSignal.removeTriggersForKeys(triggerKeys); + return true; + } catch (JSONException e) { + e.printStackTrace(); + return false; + } } - } - public static boolean pauseInAppMessages(JSONArray data) { - try { - OneSignal.pauseInAppMessages(data.getBoolean(0)); - return true; - } catch (JSONException e){ - e.printStackTrace(); - return false; + public static boolean getTriggerValueForKey(CallbackContext callbackContext, JSONArray data) { + try { + Object value = OneSignal.getTriggerValueForKey(data.getString(0)); + if (value == null) { + callbackSuccess(callbackContext, new JSONObject()); + } else { + callbackSuccess(callbackContext, new JSONObject( + "{value:" + + value.toString() + + "}")); + } + return true; + } catch (JSONException e) { + e.printStackTrace(); + return false; + } } - } -} + public static boolean pauseInAppMessages(JSONArray data) { + try { + OneSignal.pauseInAppMessages(data.getBoolean(0)); + return true; + } catch (JSONException e) { + e.printStackTrace(); + return false; + } + } +} From 62ef85537237b2ac35fb7f8e21c5f9e18baecda3 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 18 Mar 2021 13:18:18 -0300 Subject: [PATCH 07/55] Migrate OneSignalPush.m and header --- src/ios/OneSignalPush.h | 7 ++---- src/ios/OneSignalPush.m | 56 +++++++++++------------------------------ 2 files changed, 16 insertions(+), 47 deletions(-) diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index dc173535..87c666be 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -37,8 +37,7 @@ - (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand*)command; - (void)init:(CDVInvokedUrlCommand*)command; -- (void)setInFocusDisplaying:(CDVInvokedUrlCommand*)command; -- (void)getPermissionSubscriptionState:(CDVInvokedUrlCommand*)command; +- (void)getDeviceState:(CDVInvokedUrlCommand*)command; - (void)addPermissionObserver:(CDVInvokedUrlCommand*)command; - (void)addSubscriptionObserver:(CDVInvokedUrlCommand*)command; @@ -49,12 +48,10 @@ - (void)sendTags:(CDVInvokedUrlCommand*)command; - (void)deleteTags:(CDVInvokedUrlCommand*)command; - (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand*)command; -- (void)registerForPushNotifications:(CDVInvokedUrlCommand*)command; -- (void)setSubscription:(CDVInvokedUrlCommand*)command; +- (void)disablePush:(CDVInvokedUrlCommand*)command; - (void)postNotification:(CDVInvokedUrlCommand*)command; - (void)setLogLevel:(CDVInvokedUrlCommand*)command; - (void)promptLocation:(CDVInvokedUrlCommand*)command; -- (void)syncHashedEmail:(CDVInvokedUrlCommand*)command; - (void)setLocationShared:(CDVInvokedUrlCommand *)command; //email diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 4bffac46..3fc29867 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -93,24 +93,9 @@ void processNotificationOpened(OSNotificationOpenedResult* result) { void initOneSignalObject(NSDictionary* launchOptions, const char* appId, int displayOption, BOOL inAppLaunchURL, BOOL autoPrompt, BOOL fromColdStart) { [OneSignal setValue:@"cordova" forKey:@"mSDKType"]; - NSString* appIdStr = (appId ? [NSString stringWithUTF8String: appId] : nil); - NSDictionary *iOSSettings = initialLaunchFired ? @{kOSSettingsKeyAutoPrompt : @(autoPrompt), - kOSSettingsKeyInFocusDisplayOption : @(displayOption), - kOSSettingsKeyInAppLaunchURL : @(inAppLaunchURL), - @"kOSSettingsKeyInOmitNoAppIdLogging": @(fromColdStart)} : @{@"kOSSettingsKeyInOmitNoAppIdLogging": @(fromColdStart), - kOSSettingsKeyAutoPrompt : @false - }; - - [OneSignal initWithLaunchOptions:launchOptions appId:appIdStr handleNotificationReceived:^(OSNotification* _notif) { - notification = _notif; - if (pluginCommandDelegate) - processNotificationReceived(_notif); - } handleNotificationAction:^(OSNotificationOpenedResult* openResult) { - actionNotification = openResult; - if (pluginCommandDelegate) - processNotificationOpened(openResult); - } settings: iOSSettings]; - + NSString* appIdStr = (appId ? [NSString stringWithUTF8String: appId] : nil); + [OneSignal setAppId:appIdStr]; + [OneSignal initWithLaunchOptions:launchOptions]; initialLaunchFired = true; } @@ -209,12 +194,9 @@ - (void)getTags:(CDVInvokedUrlCommand*)command { - (void)getIds:(CDVInvokedUrlCommand*)command { getIdsCallbackId = command.callbackId; - [OneSignal IdsAvailable:^(NSString* userId, NSString* pushToken) { - if (pushToken == nil) - pushToken = @""; - - successCallback(getIdsCallbackId, @{@"userId" : userId, @"pushToken" : pushToken}); - }]; + OSDeviceState *deviceState = [OneSignal getDeviceState]; + if (deviceState) + successCallback(getIdsCallbackId, @{@"userId" : deviceState.userId, @"pushToken" : deviceState.pushToken}); } - (void)sendTags:(CDVInvokedUrlCommand*)command { @@ -225,10 +207,6 @@ - (void)deleteTags:(CDVInvokedUrlCommand*)command { [OneSignal deleteTags:command.arguments]; } -- (void)registerForPushNotifications:(CDVInvokedUrlCommand*)command { - [OneSignal registerForPushNotifications]; -} - - (void)setLocationShared:(CDVInvokedUrlCommand *)command { [OneSignal setLocationShared:[command.arguments[0] boolValue]]; } @@ -240,8 +218,8 @@ - (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand*)comman }]; } -- (void)setSubscription:(CDVInvokedUrlCommand*)command { - [OneSignal setSubscription:[command.arguments[0] boolValue]]; +- (void)disablePush:(CDVInvokedUrlCommand*)command { + [OneSignal disablePush:[command.arguments[0] boolValue]]; } - (void)postNotification:(CDVInvokedUrlCommand*)command { @@ -264,10 +242,6 @@ - (void)promptLocation:(CDVInvokedUrlCommand*)command { [OneSignal promptLocation]; } -- (void)syncHashedEmail:(CDVInvokedUrlCommand*)command { - [OneSignal syncHashedEmail:command.arguments[0]]; -} - - (void)setLogLevel:(CDVInvokedUrlCommand*)command { NSDictionary* options = command.arguments[0]; [OneSignal setLogLevel:[options[@"logLevel"] intValue] visualLevel:[options[@"visualLevel"] intValue]]; @@ -278,13 +252,8 @@ - (void)enableVibrate:(CDVInvokedUrlCommand*)command {} - (void)enableSound:(CDVInvokedUrlCommand*)command {} - (void)clearOneSignalNotifications:(CDVInvokedUrlCommand*)command {} - -- (void)setInFocusDisplaying:(CDVInvokedUrlCommand*)command { - OneSignal.inFocusDisplayType = [(NSNumber*)command.arguments[0] intValue]; -} - -- (void)getPermissionSubscriptionState:(CDVInvokedUrlCommand*)command { - successCallback(command.callbackId, [[OneSignal getPermissionSubscriptionState] toDictionary]); +- (void)getDeviceState:(CDVInvokedUrlCommand*)command { + successCallback(command.callbackId, [[OneSignal getDeviceState] jsonRepresentation]); } - (void)addPermissionObserver:(CDVInvokedUrlCommand*)command { @@ -371,7 +340,7 @@ - (void)setExternalUserId:(CDVInvokedUrlCommand *)command { [OneSignal setExternalUserId:externalId withExternalIdAuthHashToken:authHashToken withSuccess:^(NSDictionary *results) { successCallback(setExternalIdCallbackId, results); } withFailure: ^(NSError* error) { - [OneSignal onesignal_Log:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"Set external user id Failure with error: %@", error]]; + [OneSignal onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"Set external user id Failure with error: %@", error]]; failureCallback(setExternalIdCallbackId, error.userInfo); }]; } @@ -379,6 +348,9 @@ - (void)setExternalUserId:(CDVInvokedUrlCommand *)command { - (void)removeExternalUserId:(CDVInvokedUrlCommand *)command { [OneSignal removeExternalUserId:^(NSDictionary *results) { successCallback(command.callbackId, results); + } withFailure:^(NSError* error) { + [OneSignal onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"Remove external user id Failure with error: %@", error]]; + failureCallback(command.callbackId, error.userInfo); }]; } From 427c8100273504f4eb64eded5e724efa8f4330d5 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 18 Mar 2021 16:55:12 -0300 Subject: [PATCH 08/55] Add missing and delete depreacted methods to OneSignalPush.m and header * Add consentGranted, requiresUserPrivacyConsent * Add setLaunchURLsInApp * Add isLocationShared * Add registerForProvisionalAuthorization * Add setProvidesNotificationSettingsView * Delete getIds, replace with getDeviceState * Delete setNotificationReceivedHandler, replace with setNotificationWillShowInForegroundHandler --- src/ios/OneSignalPush.h | 103 ++++++++++++++------------- src/ios/OneSignalPush.m | 153 +++++++++++++++++++++------------------- 2 files changed, 137 insertions(+), 119 deletions(-) diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index 87c666be..ff4181a5 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -33,53 +33,60 @@ @interface OneSignalPush : CDVPlugin -- (void)setNotificationReceivedHandler:(CDVInvokedUrlCommand*)command; -- (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand*)command; -- (void)init:(CDVInvokedUrlCommand*)command; - -- (void)getDeviceState:(CDVInvokedUrlCommand*)command; - -- (void)addPermissionObserver:(CDVInvokedUrlCommand*)command; -- (void)addSubscriptionObserver:(CDVInvokedUrlCommand*)command; -- (void)addEmailSubscriptionObserver:(CDVInvokedUrlCommand *)command; - -- (void)getTags:(CDVInvokedUrlCommand*)command; -- (void)getIds:(CDVInvokedUrlCommand*)command; -- (void)sendTags:(CDVInvokedUrlCommand*)command; -- (void)deleteTags:(CDVInvokedUrlCommand*)command; -- (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand*)command; -- (void)disablePush:(CDVInvokedUrlCommand*)command; -- (void)postNotification:(CDVInvokedUrlCommand*)command; -- (void)setLogLevel:(CDVInvokedUrlCommand*)command; -- (void)promptLocation:(CDVInvokedUrlCommand*)command; -- (void)setLocationShared:(CDVInvokedUrlCommand *)command; - -//email -- (void)setEmail:(CDVInvokedUrlCommand *)command; -- (void)setUnauthenticatedEmail:(CDVInvokedUrlCommand *)command; -- (void)logoutEmail:(CDVInvokedUrlCommand *)command; - -// Android Only -- (void)enableVibrate:(CDVInvokedUrlCommand*)command; -- (void)enableSound:(CDVInvokedUrlCommand*)command; -- (void)clearOneSignalNotifications:(CDVInvokedUrlCommand*)command; - -- (void)userProvidedPrivacyConsent:(CDVInvokedUrlCommand *)command; -- (void)setRequiresUserPrivacyConsent:(CDVInvokedUrlCommand *)command; -- (void)provideUserConsent:(CDVInvokedUrlCommand *)command; - -- (void)setExternalUserId:(CDVInvokedUrlCommand *)command; -- (void)removeExternalUserId:(CDVInvokedUrlCommand *)command; +- (void)setProvidesNotificationSettingsView:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setNotificationWillShowInForegroundHandler:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)init:(CDVInvokedUrlCommand* _Nonnull)command; + +- (void)getDeviceState:(CDVInvokedUrlCommand* _Nonnull)command; + +- (void)addPermissionObserver:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)addSubscriptionObserver:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)addEmailSubscriptionObserver:(CDVInvokedUrlCommand* _Nonnull)command; + +- (void)setLogLevel:(CDVInvokedUrlCommand* _Nonnull)command; + +- (void)getTags:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)sendTags:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)deleteTags:(CDVInvokedUrlCommand* _Nonnull)command; + +- (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)registerForProvisionalAuthorization:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)disablePush:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)postNotification:(CDVInvokedUrlCommand* _Nonnull)command; + +// Email +- (void)setEmail:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setUnauthenticatedEmail:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)logoutEmail:(CDVInvokedUrlCommand* _Nonnull)command; + +// Start Android Only +- (void)clearOneSignalNotifications:(CDVInvokedUrlCommand* _Nonnull)command; +// End Android Only + +- (void)consentGranted:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)requiresUserPrivacyConsent:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setRequiresUserPrivacyConsent:(CDVInvokedUrlCommand* _Nonnull)command; + +- (void)setExternalUserId:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)removeExternalUserId:(CDVInvokedUrlCommand* _Nonnull)command; -// in app -- (void)setInAppMessageClickHandler:(CDVInvokedUrlCommand*)command; -- (void)addTriggers:(CDVInvokedUrlCommand*)command; -- (void)removeTriggersForKeys:(CDVInvokedUrlCommand*)command; -- (void)getTriggerValueForKey:(CDVInvokedUrlCommand*)command; -- (void)pauseInAppMessages:(CDVInvokedUrlCommand*)command; - -// outcomes -- (void)sendOutcome:(CDVInvokedUrlCommand*)command; -- (void)sendUniqueOutcome:(CDVInvokedUrlCommand*)command; -- (void)sendOutcomeWithValue:(CDVInvokedUrlCommand*)command; +// In App Message +- (void)setLaunchURLsInApp:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setInAppMessageClickHandler:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)addTriggers:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)removeTriggersForKeys:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)getTriggerValueForKey:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)pauseInAppMessages:(CDVInvokedUrlCommand* _Nonnull)command; + +// Outcomes +- (void)sendOutcome:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)sendUniqueOutcome:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)sendOutcomeWithValue:(CDVInvokedUrlCommand* _Nonnull)command; + +// Location +- (void)promptLocation:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setLocationShared:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)isLocationShared:(CDVInvokedUrlCommand* _Nonnull)command; + @end diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 3fc29867..f2b5ced4 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -1,7 +1,7 @@ /** * Modified MIT License * - * Copyright 2017 OneSignal + * Copyright 2021 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -31,7 +31,7 @@ #import "OneSignalPush.h" #import -NSString* notificationReceivedCallbackId; +NSString* notificationWillShowInForegoundCallbackId; NSString* notificationOpenedCallbackId; NSString* getTagsCallbackId; NSString* getIdsCallbackId; @@ -64,7 +64,7 @@ void failureCallback(NSString* callbackId, NSDictionary* data) { [pluginCommandDelegate sendPluginResult:commandResult callbackId:callbackId]; } -void processNotificationReceived(OSNotification* _notif) { +void processNotificationWillShowInForeground(OSNotification* _notif) { NSString * data = [_notif stringify]; NSError *jsonError; NSData *objectData = [data dataUsingEncoding:NSUTF8StringEncoding]; @@ -72,7 +72,7 @@ void processNotificationReceived(OSNotification* _notif) { options:NSJSONReadingMutableContainers error:&jsonError]; if(!jsonError) { - successCallback(notificationReceivedCallbackId, json); + successCallback(notificationWillShowInForegoundCallbackId, json); notification = nil; } } @@ -90,10 +90,9 @@ void processNotificationOpened(OSNotificationOpenedResult* result) { } } -void initOneSignalObject(NSDictionary* launchOptions, const char* appId, int displayOption, BOOL inAppLaunchURL, BOOL autoPrompt, BOOL fromColdStart) { - [OneSignal setValue:@"cordova" forKey:@"mSDKType"]; - +void initOneSignalObject(NSDictionary* launchOptions, const char* appId) { NSString* appIdStr = (appId ? [NSString stringWithUTF8String: appId] : nil); + [OneSignal setMSDKType:@"cordova"]; [OneSignal setAppId:appIdStr]; [OneSignal initWithLaunchOptions:launchOptions]; initialLaunchFired = true; @@ -123,7 +122,7 @@ + (void)load { static Class delegateClass = nil; -- (void) setOneSignalCordovaDelegate:(id)delegate { +- (void)setOneSignalCordovaDelegate:(id)delegate { if(delegateClass != nil) return; delegateClass = [delegate class]; @@ -134,7 +133,7 @@ - (void) setOneSignalCordovaDelegate:(id)delegate { } - (BOOL)oneSignalApplication:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { - initOneSignalObject(launchOptions, nil, 1, YES, NO, YES); + initOneSignalObject(launchOptions, nil); if ([self respondsToSelector:@selector(oneSignalApplication:didFinishLaunchingWithOptions:)]) return [self oneSignalApplication:application didFinishLaunchingWithOptions:launchOptions]; @@ -153,12 +152,17 @@ - (void)onOSSubscriptionChanged:(OSSubscriptionStateChanges*)stateChanges { successCallback(subscriptionObserverCallbackId, [stateChanges toDictionary]); } --(void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges *)stateChanges { +- (void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges *)stateChanges { successCallback(emailSubscriptionCallbackId, [stateChanges toDictionary]); } -- (void)setNotificationReceivedHandler:(CDVInvokedUrlCommand*)command { - notificationReceivedCallbackId = command.callbackId; +- (void)setProvidesNotificationSettingsView:(CDVInvokedUrlCommand *)command { + BOOL providesView = command.arguments[0]; + [OneSignal setProvidesNotificationSettingsView:providesView]; +} + +- (void)setNotificationWillShowInForegroundHandler:(CDVInvokedUrlCommand*)command { + notificationWillShowInForegoundCallbackId = command.callbackId; } - (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand*)command { @@ -170,21 +174,44 @@ - (void)init:(CDVInvokedUrlCommand*)command { pluginCommandDelegate = self.commandDelegate; NSString* appId = (NSString*)command.arguments[0]; - NSDictionary* settings = command.arguments[2] == [NSNull null] ? @{} : (NSDictionary*)command.arguments[2]; - - BOOL inAppLaunchURL = settings[@"kOSSettingsKeyInAppLaunchURL"] ? [(NSNumber*)settings[@"kOSSettingsKeyInAppLaunchURL"] boolValue] : YES; - BOOL autoPrompt = settings[@"kOSSettingsKeyAutoPrompt"] ? [(NSNumber*)settings[@"kOSSettingsKeyAutoPrompt"] boolValue] : YES; - - int displayOption = [(NSNumber*)command.arguments[3] intValue]; - - initOneSignalObject(nil, [appId UTF8String], displayOption, inAppLaunchURL, autoPrompt, NO); + initOneSignalObject(nil, [appId UTF8String]); if (notification) - processNotificationReceived(notification); + processNotificationWillShowInForeground(notification); if (actionNotification) processNotificationOpened(actionNotification); } +- (void)getDeviceState:(CDVInvokedUrlCommand*)command { + successCallback(command.callbackId, [[OneSignal getDeviceState] jsonRepresentation]); +} + +- (void)addPermissionObserver:(CDVInvokedUrlCommand*)command { + bool first = permissionObserverCallbackId == nil; + permissionObserverCallbackId = command.callbackId; + if (first) + [OneSignal addPermissionObserver:self]; +} + +- (void)addSubscriptionObserver:(CDVInvokedUrlCommand*)command { + bool first = subscriptionObserverCallbackId == nil; + subscriptionObserverCallbackId = command.callbackId; + if (first) + [OneSignal addSubscriptionObserver:self]; +} + +- (void)addEmailSubscriptionObserver:(CDVInvokedUrlCommand *)command { + bool first = emailSubscriptionCallbackId == nil; + emailSubscriptionCallbackId = command.callbackId; + if (first) + [OneSignal addEmailSubscriptionObserver:self]; +} + +- (void)setLogLevel:(CDVInvokedUrlCommand*)command { + NSDictionary* options = command.arguments[0]; + [OneSignal setLogLevel:[options[@"logLevel"] intValue] visualLevel:[options[@"visualLevel"] intValue]]; +} + - (void)getTags:(CDVInvokedUrlCommand*)command { getTagsCallbackId = command.callbackId; [OneSignal getTags:^(NSDictionary* result) { @@ -192,13 +219,6 @@ - (void)getTags:(CDVInvokedUrlCommand*)command { }]; } -- (void)getIds:(CDVInvokedUrlCommand*)command { - getIdsCallbackId = command.callbackId; - OSDeviceState *deviceState = [OneSignal getDeviceState]; - if (deviceState) - successCallback(getIdsCallbackId, @{@"userId" : deviceState.userId, @"pushToken" : deviceState.pushToken}); -} - - (void)sendTags:(CDVInvokedUrlCommand*)command { [OneSignal sendTags:command.arguments[0]]; } @@ -207,10 +227,6 @@ - (void)deleteTags:(CDVInvokedUrlCommand*)command { [OneSignal deleteTags:command.arguments]; } -- (void)setLocationShared:(CDVInvokedUrlCommand *)command { - [OneSignal setLocationShared:[command.arguments[0] boolValue]]; -} - - (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand*)command { promptForPushNotificationsWithUserResponseCallbackId = command.callbackId; [OneSignal promptForPushNotificationsWithUserResponse:^(BOOL accepted) { @@ -218,6 +234,10 @@ - (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand*)comman }]; } +- (void)registerForProvisionalAuthorization:(CDVInvokedUrlCommand *)command { + +} + - (void)disablePush:(CDVInvokedUrlCommand*)command { [OneSignal disablePush:[command.arguments[0] boolValue]]; } @@ -238,45 +258,6 @@ - (void)postNotification:(CDVInvokedUrlCommand*)command { }]; } -- (void)promptLocation:(CDVInvokedUrlCommand*)command { - [OneSignal promptLocation]; -} - -- (void)setLogLevel:(CDVInvokedUrlCommand*)command { - NSDictionary* options = command.arguments[0]; - [OneSignal setLogLevel:[options[@"logLevel"] intValue] visualLevel:[options[@"visualLevel"] intValue]]; -} - -// Android only -- (void)enableVibrate:(CDVInvokedUrlCommand*)command {} -- (void)enableSound:(CDVInvokedUrlCommand*)command {} -- (void)clearOneSignalNotifications:(CDVInvokedUrlCommand*)command {} - -- (void)getDeviceState:(CDVInvokedUrlCommand*)command { - successCallback(command.callbackId, [[OneSignal getDeviceState] jsonRepresentation]); -} - -- (void)addPermissionObserver:(CDVInvokedUrlCommand*)command { - bool first = permissionObserverCallbackId == nil; - permissionObserverCallbackId = command.callbackId; - if (first) - [OneSignal addPermissionObserver:self]; -} - -- (void)addSubscriptionObserver:(CDVInvokedUrlCommand*)command { - bool first = subscriptionObserverCallbackId == nil; - subscriptionObserverCallbackId = command.callbackId; - if (first) - [OneSignal addSubscriptionObserver:self]; -} - -- (void)addEmailSubscriptionObserver:(CDVInvokedUrlCommand *)command { - bool first = emailSubscriptionCallbackId == nil; - emailSubscriptionCallbackId = command.callbackId; - if (first) - [OneSignal addEmailSubscriptionObserver:self]; -} - - (void)setEmail:(CDVInvokedUrlCommand *)command { setEmailCallbackId = command.callbackId; @@ -312,6 +293,19 @@ - (void)logoutEmail:(CDVInvokedUrlCommand *)command { }]; } + +// Start Android only +- (void)clearOneSignalNotifications:(CDVInvokedUrlCommand*)command {} +// Finish Android only + +- (void)consentGranted:(CDVInvokedUrlCommand *)command { + +} + +- (void)requiresUserPrivacyConsent:(CDVInvokedUrlCommand *)command { + +} + - (void)userProvidedPrivacyConsent:(CDVInvokedUrlCommand *)command { CDVPluginResult* commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:!OneSignal.requiresUserPrivacyConsent]; commandResult.keepCallback = @1; @@ -358,6 +352,11 @@ - (void)removeExternalUserId:(CDVInvokedUrlCommand *)command { * In-App Messaging */ +- (void)setLaunchURLsInApp:(CDVInvokedUrlCommand *)command { + BOOL launchInApp = command.arguments[0]; + [OneSignal setLaunchURLsInApp:launchInApp]; +} + - (void)setInAppMessageClickHandler:(CDVInvokedUrlCommand*)command { [OneSignal setInAppMessageClickHandler:^(OSInAppMessageAction* action) { NSDictionary *result = @{ @@ -418,4 +417,16 @@ - (void)sendOutcomeWithValue:(CDVInvokedUrlCommand*)command { }]; } +- (void)promptLocation:(CDVInvokedUrlCommand*)command { + [OneSignal promptLocation]; +} + +- (void)setLocationShared:(CDVInvokedUrlCommand *)command { + [OneSignal setLocationShared:[command.arguments[0] boolValue]]; +} + +- (void)isLocationShared:(CDVInvokedUrlCommand *)command { + +} + @end From 722ec4599f2db8252410853156b2ae6a7d1e3f1d Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 22 Mar 2021 12:36:06 -0300 Subject: [PATCH 09/55] Add missing methods Android * Rename getIds to getDeviceState * Add unsubscribeWhenNotificationsAreDisabled method * Add removeNotification method * Add removeGroupedNotifications method * Add requiresUserPrivacyConsent method * Add isInAppMessagingPaused method --- .../com/plugin/gcm/OneSignalController.java | 153 ++++++++++-------- .../OneSignalInAppMessagingController.java | 6 + .../gcm/OneSignalOutcomeController.java | 60 +++---- src/android/com/plugin/gcm/OneSignalPush.java | 97 ++++++----- 4 files changed, 175 insertions(+), 141 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalController.java b/src/android/com/plugin/gcm/OneSignalController.java index 2f319183..5800b4d9 100644 --- a/src/android/com/plugin/gcm/OneSignalController.java +++ b/src/android/com/plugin/gcm/OneSignalController.java @@ -13,23 +13,46 @@ import java.util.Collection; public class OneSignalController { - private static CallbackContext notifReceivedCallbackContext; - private static CallbackContext notifOpenedCallbackContext; - private static CallbackContext inAppMessageClickedCallbackContext; - private static final String TAG = "OneSignalPush"; + /** + * Subscriptions + */ + public static boolean getDeviceState(CallbackContext callbackContext) { + OSDeviceState deviceState = OneSignal.getDeviceState(); + if (deviceState != null) + CallbackHelper.callbackSuccess(callbackContext, deviceState.toJSONObject()); + return true; + } + + public static boolean disablePush(JSONArray data) { + try { + OneSignal.disablePush(data.getBoolean(0)); + return true; + } + catch (Throwable t) { + t.printStackTrace(); + return false; + } + } + + /** + * Misc + */ + public static void setLogLevel(JSONArray data) { + try { + JSONObject jo = data.getJSONObject(0); + OneSignal.setLogLevel(jo.optInt("logLevel", 0), jo.optInt("visualLevel", 0)); + } catch (Throwable t) { + t.printStackTrace(); + } + } /** * Tags */ public static boolean getTags(CallbackContext callbackContext) { final CallbackContext jsTagsAvailableCallBack = callbackContext; - OneSignal.getTags(new OneSignal.OSGetTagsHandler() { - @Override - public void tagsAvailable(JSONObject tags) { - CallbackHelper.callbackSuccess(jsTagsAvailableCallBack, tags); - } - }); + OneSignal.getTags(tags -> CallbackHelper.callbackSuccess(jsTagsAvailableCallBack, tags)); return true; } @@ -56,27 +79,6 @@ public static boolean deleteTags(JSONArray data) { } } - /** - * Subscriptions - */ - public static boolean getDeviceState(CallbackContext callbackContext) { - OSDeviceState deviceState = OneSignal.getDeviceState(); - if (deviceState != null) - CallbackHelper.callbackSuccess(callbackContext, deviceState.toJSONObject()); - return true; - } - - public static boolean disablePush(JSONArray data) { - try { - OneSignal.disablePush(data.getBoolean(0)); - return true; - } - catch (Throwable t) { - t.printStackTrace(); - return false; - } - } - /** * Notifications */ @@ -116,65 +118,61 @@ public static boolean clearOneSignalNotifications() { } } - /** - * Location - */ - - public static void promptLocation() { - OneSignal.promptLocation(); + public static boolean removeNotification(JSONArray data) { + try { + OneSignal.removeNotification(data.getInt(0)); + return true; + } catch (Throwable t) { + t.printStackTrace(); + return false; + } } - public static void setLocationShared(JSONArray data) { + public static boolean removeGroupedNotifications(JSONArray data) { try { - OneSignal.setLocationShared(data.getBoolean(0)); - } catch (JSONException e) { - e.printStackTrace(); + OneSignal.removeGroupedNotifications(data.getString(0)); + return true; + } catch (Throwable t) { + t.printStackTrace(); + return false; } } - /** - * Misc - */ public static boolean registerForPushNotifications() { // doesn't apply to Android return true; } - public static boolean getIds(CallbackContext callbackContext) { - OSDeviceState deviceState = OneSignal.getDeviceState(); - - if (deviceState == null) - return false; - - JSONObject jsonIds = new JSONObject(); - try { - jsonIds.put("userId", deviceState.getUserId()); - jsonIds.put("pushToken", deviceState.getPushToken() == null ? "" : deviceState.getPushToken()); - - CallbackHelper.callbackSuccess(callbackContext, jsonIds); - } catch (Throwable t) { - t.printStackTrace(); - } - + public static boolean promptForPushNotificationsWithUserResponse() { + // doesn't apply to Android return true; } - public static void setLogLevel(JSONArray data) { + public static boolean unsubscribeWhenNotificationsAreDisabled(JSONArray data) { try { - JSONObject jo = data.getJSONObject(0); - OneSignal.setLogLevel(jo.optInt("logLevel", 0), jo.optInt("visualLevel", 0)); - } - catch(Throwable t) { - t.printStackTrace(); + OneSignal.unsubscribeWhenNotificationsAreDisabled(data.getBoolean(0)); + return true; + } catch (JSONException e) { + e.printStackTrace(); } + return false; } + /** + * Privacy consent + */ public static boolean userProvidedConsent(CallbackContext callbackContext) { boolean providedConsent = OneSignal.userProvidedPrivacyConsent(); CallbackHelper.callbackSuccessBoolean(callbackContext, providedConsent); return true; } + public static boolean requiresUserPrivacyConsent(CallbackContext callbackContext) { + boolean requiresUserPrivacyConsent = OneSignal.requiresUserPrivacyConsent(); + CallbackHelper.callbackSuccessBoolean(callbackContext, requiresUserPrivacyConsent); + return true; + } + public static boolean setRequiresConsent(CallbackContext callbackContext, JSONArray data) { try { OneSignal.setRequiresUserPrivacyConsent(data.getBoolean(0)); @@ -185,7 +183,7 @@ public static boolean setRequiresConsent(CallbackContext callbackContext, JSONAr } } - public static boolean grantConsent(JSONArray data) { + public static boolean provideUserConsent(JSONArray data) { try { OneSignal.provideUserConsent(data.getBoolean(0)); return true; @@ -195,6 +193,9 @@ public static boolean grantConsent(JSONArray data) { } } + /** + * External User Is + */ public static boolean setExternalUserId(final CallbackContext callback, JSONArray data) { try { String authHashToken = null; @@ -234,4 +235,22 @@ public void onFailure(OneSignal.ExternalIdError error) { return true; } + /** + * Location + */ + public static void promptLocation() { + OneSignal.promptLocation(); + } + + public static void setLocationShared(JSONArray data) { + try { + OneSignal.setLocationShared(data.getBoolean(0)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void isLocationShared(JSONArray data) { + // doesn't apply to Android + } } \ No newline at end of file diff --git a/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java b/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java index c60f2162..3ae89aac 100644 --- a/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java +++ b/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java @@ -90,4 +90,10 @@ public static boolean pauseInAppMessages(JSONArray data) { } } + public static boolean isInAppMessagingPaused(CallbackContext callbackContext) { + boolean inAppMessagingPaused = OneSignal.isInAppMessagingPaused(); + CallbackHelper.callbackSuccessBoolean(callbackContext, inAppMessagingPaused); + return true; + } + } diff --git a/src/android/com/plugin/gcm/OneSignalOutcomeController.java b/src/android/com/plugin/gcm/OneSignalOutcomeController.java index cc35ef7b..fd83a58e 100644 --- a/src/android/com/plugin/gcm/OneSignalOutcomeController.java +++ b/src/android/com/plugin/gcm/OneSignalOutcomeController.java @@ -2,9 +2,6 @@ import android.util.Log; -import androidx.annotation.Nullable; - -import com.onesignal.OSOutcomeEvent; import com.onesignal.OneSignal; import org.apache.cordova.CallbackContext; @@ -20,17 +17,14 @@ public static boolean sendUniqueOutcome(CallbackContext callbackContext, JSONArr try { final CallbackContext jsSendUniqueOutcomeCallback = callbackContext; final String name = data.getString(0); - OneSignal.sendUniqueOutcome(name, new OneSignal.OutcomeCallback(){ - @Override - public void onSuccess(@Nullable OSOutcomeEvent outcomeEvent) { - if (outcomeEvent == null) - CallbackHelper.callbackSuccess(jsSendUniqueOutcomeCallback, new JSONObject()); - else { - try { - CallbackHelper.callbackSuccess(jsSendUniqueOutcomeCallback, outcomeEvent.toJSONObject()); - } catch (JSONException e) { - Log.e(TAG, "sendUniqueOutcome with name: " + name + ", failed with message: " + e.getMessage()); - } + OneSignal.sendUniqueOutcome(name, outcomeEvent -> { + if (outcomeEvent == null) + CallbackHelper.callbackSuccess(jsSendUniqueOutcomeCallback, new JSONObject()); + else { + try { + CallbackHelper.callbackSuccess(jsSendUniqueOutcomeCallback, outcomeEvent.toJSONObject()); + } catch (JSONException e) { + Log.e(TAG, "sendUniqueOutcome with name: " + name + ", failed with message: " + e.getMessage()); } } }); @@ -45,17 +39,14 @@ public static boolean sendOutcome(CallbackContext callbackContext, JSONArray dat try { final CallbackContext jsSendOutcomeCallback = callbackContext; final String name = data.getString(0); - OneSignal.sendOutcome(name, new OneSignal.OutcomeCallback(){ - @Override - public void onSuccess(@Nullable OSOutcomeEvent outcomeEvent) { - if (outcomeEvent == null) - CallbackHelper.callbackSuccess(jsSendOutcomeCallback, new JSONObject()); - else { - try { - CallbackHelper.callbackSuccess(jsSendOutcomeCallback, outcomeEvent.toJSONObject()); - } catch (JSONException e) { - Log.e(TAG, "sendOutcome with name: " + name + ", failed with message: " + e.getMessage()); - } + OneSignal.sendOutcome(name, outcomeEvent -> { + if (outcomeEvent == null) + CallbackHelper.callbackSuccess(jsSendOutcomeCallback, new JSONObject()); + else { + try { + CallbackHelper.callbackSuccess(jsSendOutcomeCallback, outcomeEvent.toJSONObject()); + } catch (JSONException e) { + Log.e(TAG, "sendOutcome with name: " + name + ", failed with message: " + e.getMessage()); } } }); @@ -71,17 +62,14 @@ public static boolean sendOutcomeWithValue(CallbackContext callbackContext, JSON final CallbackContext jsSendOutcomeWithValueCallback = callbackContext; final String name = data.getString(0); final float value = Double.valueOf(data.optDouble(1)).floatValue(); - OneSignal.sendOutcomeWithValue(name, value,new OneSignal.OutcomeCallback(){ - @Override - public void onSuccess(@Nullable OSOutcomeEvent outcomeEvent) { - if (outcomeEvent == null) - CallbackHelper.callbackSuccess(jsSendOutcomeWithValueCallback, new JSONObject()); - else { - try { - CallbackHelper.callbackSuccess(jsSendOutcomeWithValueCallback, outcomeEvent.toJSONObject()); - } catch (JSONException e) { - Log.e(TAG, "sendOutcomeWithValue with name: " + name + " and value: " + value + ", failed with message: " + e.getMessage()); - } + OneSignal.sendOutcomeWithValue(name, value, outcomeEvent -> { + if (outcomeEvent == null) + CallbackHelper.callbackSuccess(jsSendOutcomeWithValueCallback, new JSONObject()); + else { + try { + CallbackHelper.callbackSuccess(jsSendOutcomeWithValueCallback, outcomeEvent.toJSONObject()); + } catch (JSONException e) { + Log.e(TAG, "sendOutcomeWithValue with name: " + name + " and value: " + value + ", failed with message: " + e.getMessage()); } } }); diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index d7a4e492..3e18980b 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -42,45 +42,45 @@ public class OneSignalPush extends CordovaPlugin { private static final String TAG = "OneSignalPush"; - private static final String SET_NOTIFICATION_RECEIVED_HANDLER = "setNotificationReceivedHandler"; + private static final String SET_NOTIFICATION_WILL_SHOW_IN_FOREGROUND_HANDLER = "setNotificationWillShowInForegroundHandler"; private static final String SET_NOTIFICATION_OPENED_HANDLER = "setNotificationOpenedHandler"; private static final String SET_IN_APP_MESSAGE_CLICK_HANDLER = "setInAppMessageClickHandler"; private static final String INIT = "init"; - private static final String SET_IN_FOCUS_DISPLAYING = "setInFocusDisplaying"; - - private static final String GET_PERMISSION_SUBCRIPTION_STATE = "getPermissionSubscriptionState"; - private static final String GET_IDS = "getIds"; + private static final String GET_DEVICE_STATE = "getDeviceState"; private static final String ADD_PERMISSION_OBSERVER = "addPermissionObserver"; private static final String ADD_SUBSCRIPTION_OBSERVER = "addSubscriptionObserver"; + private static final String ADD_EMAIL_SUBSCRIPTION_OBSERVER = "addEmailSubscriptionObserver"; private static final String GET_TAGS = "getTags"; private static final String DELETE_TAGS = "deleteTags"; private static final String SEND_TAGS = "sendTags"; - private static final String SYNC_HASHED_EMAIL = "syncHashedEmail"; private static final String REGISTER_FOR_PUSH_NOTIFICATIONS = "registerForPushNotifications"; - private static final String ENABLE_VIBRATE = "enableVibrate"; - private static final String ENABLE_SOUND = "enableSound"; + private static final String PROMPT_FOR_PUSH_NOTIFICATIONS_WITH_USER_RESPONSE = "promptForPushNotificationsWithUserResponse"; + private static final String UNSUBSCRIBE_WHEN_NOTIFICATIONS_DISABLED = "unsubscribeWhenNotificationsAreDisabled"; - private static final String SET_SUBSCRIPTION = "setSubscription"; - private static final String POST_NOTIFICATION = "postNotification"; - private static final String PROMPT_LOCATION = "promptLocation"; private static final String CLEAR_ONESIGNAL_NOTIFICATIONS = "clearOneSignalNotifications"; + private static final String REMOVE_NOTIFICATION = "removeNotification"; + private static final String REMOVE_GROUPED_NOTIFICATIONS = "removeGroupedNotifications"; + + private static final String DISABLE_PUSH = "disablePush"; + private static final String POST_NOTIFICATION = "postNotification"; private static final String SET_EMAIL = "setEmail"; private static final String SET_UNAUTHENTICATED_EMAIL = "setUnauthenticatedEmail"; private static final String LOGOUT_EMAIL = "logoutEmail"; - private static final String ADD_EMAIL_SUBSCRIPTION_OBSERVER = "addEmailSubscriptionObserver"; private static final String SET_LOG_LEVEL = "setLogLevel"; private static final String SET_LOCATION_SHARED = "setLocationShared"; + private static final String PROMPT_LOCATION = "promptLocation"; private static final String USER_PROVIDED_CONSENT = "userProvidedPrivacyConsent"; + private static final String REQUIRES_CONSENT = "requiresUserPrivacyConsent"; private static final String SET_REQUIRES_CONSENT = "setRequiresUserPrivacyConsent"; - private static final String GRANT_CONSENT = "provideUserConsent"; + private static final String PROVIDE_USER_CONSENT = "provideUserConsent"; private static final String SET_EXTERNAL_USER_ID = "setExternalUserId"; private static final String REMOVE_EXTERNAL_USER_ID = "removeExternalUserId"; @@ -88,19 +88,21 @@ public class OneSignalPush extends CordovaPlugin { private static final String ADD_TRIGGERS = "addTriggers"; private static final String REMOVE_TRIGGERS_FOR_KEYS = "removeTriggersForKeys"; private static final String GET_TRIGGER_VALUE_FOR_KEY = "getTriggerValueForKey"; + private static final String PAUSE_IN_APP_MESSAGES = "pauseInAppMessages"; + private static final String IN_APP_MESSAGING_PAUSED = "isInAppMessagingPaused"; private static final String SEND_OUTCOME = "sendOutcome"; private static final String SEND_UNIQUE_OUTCOME = "sendUniqueOutcome"; private static final String SEND_OUTCOME_WITH_VALUE = "sendOutcomeWithValue"; - private static CallbackContext notifReceivedCallbackContext; + private static CallbackContext notifWillShowInForegroundCallbackContext; private static CallbackContext notifOpenedCallbackContext; private static CallbackContext inAppMessageClickedCallbackContext; - public static boolean setNotificationReceivedHandler(CallbackContext callbackContext) { - notifReceivedCallbackContext = callbackContext; + public static boolean setNotificationWillShowInForegroundHandler(CallbackContext callbackContext) { + notifWillShowInForegroundCallbackContext = callbackContext; return true; } @@ -117,7 +119,6 @@ public static boolean setInAppMessageClickHandler(CallbackContext callbackContex public boolean init(CallbackContext callbackContext, JSONArray data) { try { String appId = data.getString(0); - String googleProjectNumber = data.getString(1); OneSignal.sdkType = "cordova"; @@ -141,8 +142,8 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = setNotificationOpenedHandler(callbackContext); break; - case SET_NOTIFICATION_RECEIVED_HANDLER: - result = setNotificationReceivedHandler(callbackContext); + case SET_NOTIFICATION_WILL_SHOW_IN_FOREGROUND_HANDLER: + result = setNotificationWillShowInForegroundHandler(callbackContext); break; case SET_IN_APP_MESSAGE_CLICK_HANDLER: @@ -153,6 +154,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = init(callbackContext, data); break; + case GET_DEVICE_STATE: + result = OneSignalController.getDeviceState(callbackContext); + break; + case ADD_PERMISSION_OBSERVER: result = OneSignalObserverController.addPermissionObserver(callbackContext); break; @@ -169,14 +174,6 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.getTags(callbackContext); break; - case GET_PERMISSION_SUBCRIPTION_STATE: - result = OneSignalController.getDeviceState(callbackContext); - break; - - case GET_IDS: - result = OneSignalController.getIds(callbackContext); - break; - case SEND_TAGS: result = OneSignalController.sendTags(data); break; @@ -189,7 +186,27 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.registerForPushNotifications(); break; - case SET_SUBSCRIPTION: + case PROMPT_FOR_PUSH_NOTIFICATIONS_WITH_USER_RESPONSE: + result = OneSignalController.promptForPushNotificationsWithUserResponse(); + break; + + case UNSUBSCRIBE_WHEN_NOTIFICATIONS_DISABLED: + result = OneSignalController.unsubscribeWhenNotificationsAreDisabled(data); + break; + + case CLEAR_ONESIGNAL_NOTIFICATIONS: + result = OneSignalController.clearOneSignalNotifications(); + break; + + case REMOVE_NOTIFICATION: + result = OneSignalController.removeNotification(data); + break; + + case REMOVE_GROUPED_NOTIFICATIONS: + result = OneSignalController.removeGroupedNotifications(data); + break; + + case DISABLE_PUSH: result = OneSignalController.disablePush(data); break; @@ -197,18 +214,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.postNotification(callbackContext, data); break; - case PROMPT_LOCATION: - OneSignalController.promptLocation(); - break; - case SET_LOG_LEVEL: OneSignalController.setLogLevel(data); break; - case CLEAR_ONESIGNAL_NOTIFICATIONS: - result = OneSignalController.clearOneSignalNotifications(); - break; - case SET_EMAIL: result = OneSignalEmailController.setEmail(callbackContext, data); break; @@ -221,6 +230,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalEmailController.logoutEmail(callbackContext); break; + case PROMPT_LOCATION: + OneSignalController.promptLocation(); + break; + case SET_LOCATION_SHARED: OneSignalController.setLocationShared(data); break; @@ -229,12 +242,16 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.userProvidedConsent(callbackContext); break; + case REQUIRES_CONSENT: + result = OneSignalController.requiresUserPrivacyConsent(callbackContext); + break; + case SET_REQUIRES_CONSENT: result = OneSignalController.setRequiresConsent(callbackContext, data); break; - case GRANT_CONSENT: - result = OneSignalController.grantConsent(data); + case PROVIDE_USER_CONSENT: + result = OneSignalController.provideUserConsent(data); break; case SET_EXTERNAL_USER_ID: @@ -261,6 +278,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalInAppMessagingController.pauseInAppMessages(data); break; + case IN_APP_MESSAGING_PAUSED: + result = OneSignalInAppMessagingController.isInAppMessagingPaused(callbackContext); + break; + case SEND_OUTCOME: result = OneSignalOutcomeController.sendOutcome(callbackContext, data); break; From e068bd9ad66faff93da8860812f9a6e01445fc4a Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 22 Mar 2021 17:13:50 -0300 Subject: [PATCH 10/55] Add support to new methods OneSignal.js * Remove support to deprecated methods * Remove _googleProjectNumber, _iOSSettings * Replace _notificationReceivedDelegate with _notificationWillShowInForegroundDelegate * Remove OSInFocusDisplayOption * Remove inFocusDisplaying * Replace getIds with getDeviceState * Remove getPermissionSubscriptionState * Remove enableSound and enableVibrate * Replace setSubscription with disablePush * Remove syncHashedEmail --- www/OneSignal.js | 151 ++++++++++++++++++----------------------------- 1 file changed, 59 insertions(+), 92 deletions(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index b2b90e4e..1efadb51 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -27,42 +27,30 @@ var OneSignal = function() { var _appID = ""; - var _googleProjectNumber = ""; - var _iOSSettings = {}; - var _notificationReceivedDelegate = function() {}; + var _notificationWillShowInForegroundDelegate = function() {}; var _notificationOpenedDelegate = function() {}; var _inAppMessageClickDelegate = function () {}; }; -OneSignal.prototype.OSInFocusDisplayOption = { - None: 0, - InAppAlert : 1, - Notification : 2 -}; - OneSignal.prototype.OSNotificationPermission = { NotDetermined: 0, Authorized: 1, Denied: 2 }; -OneSignal._displayOption = OneSignal.prototype.OSInFocusDisplayOption.InAppAlert; - OneSignal._permissionObserverList = []; OneSignal._subscriptionObserverList = []; OneSignal._emailSubscriptionObserverList = []; // You must call init before any other OneSignal function. -// Android - googleProjectNumber: Deprecated; pulled from dashboard, local value is ignored -OneSignal.prototype.startInit = function(appId, googleProjectNumber) { +OneSignal.prototype.startInit = function(appId) { OneSignal._appID = appId; - OneSignal._googleProjectNumber = googleProjectNumber; return this; }; -OneSignal.prototype.handleNotificationReceived = function(handleNotificationReceivedCallback) { - OneSignal._notificationReceivedDelegate = handleNotificationReceivedCallback; +OneSignal.prototype.handleNotificationWillShowInForeground = function(handleNotificationWillShowInForegroundCallback) { + OneSignal._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; return this; }; @@ -76,27 +64,13 @@ OneSignal.prototype.handleInAppMessageClicked = function(handler) { return this; }; -OneSignal.prototype.inFocusDisplaying = function(display) { - OneSignal._displayOption = display; - return this; -}; - -//Possible settings keys: -// kOSSettingsKeyInAppLaunchURL: Bool. Enable in-app webviews for urls. Default: Enabled -// kOSSettingsKeyAutoPrompt: Bool. Enable automatic prompting for notifications. Default: Enabled -OneSignal.prototype.iOSSettings = function(settings) { - OneSignal._iOSSettings = settings; - return this; -}; - OneSignal.prototype.endInit = function() { - - //Pass notification received handler - cordova.exec(OneSignal._notificationReceivedDelegate, function(){}, "OneSignalPush", "setNotificationReceivedHandler", []); + // Pass notification received handler + cordova.exec(OneSignal._notificationWillShowInForegroundDelegate, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); cordova.exec(OneSignal._notificationOpenedDelegate, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); cordova.exec(OneSignal._inAppMessageClickDelegate, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); - //Call Init - cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignal._appID, OneSignal._googleProjectNumber, OneSignal._iOSSettings, OneSignal._displayOption]); + // Call Init + cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignal._appID]); }; OneSignal._processFunctionList = function(array, param) { @@ -113,14 +87,8 @@ OneSignal._formatPermissionObj = function(state) { } }; -OneSignal.prototype.addPermissionObserver = function(callback) { - OneSignal._permissionObserverList.push(callback); - var permissionCallBackProcessor = function(state) { - OneSignal._formatPermissionObj(state.to); - OneSignal._formatPermissionObj(state.from); - OneSignal._processFunctionList(OneSignal._permissionObserverList, state); - }; - cordova.exec(permissionCallBackProcessor, function(){}, "OneSignalPush", "addPermissionObserver", []); +OneSignal.prototype.getDeviceState = function(deviceStateReceivedCallBack) { + cordova.exec(deviceStateReceivedCallBack, function(){}, "OneSignalPush", "getDeviceState", []); }; OneSignal.prototype.addSubscriptionObserver = function(callback) { @@ -139,21 +107,14 @@ OneSignal.prototype.addEmailSubscriptionObserver = function(callback) { cordova.exec(emailSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addEmailSubscriptionObserver", []); }; -OneSignal.prototype.setInFocusDisplaying = function(displayType) { - OneSignal._displayOption = displayType; - cordova.exec(function(){}, function(){}, "OneSignalPush", "setInFocusDisplaying", [displayType]); -}; - -OneSignal.prototype.getPermissionSubscriptionState = function(callback) { - var internalCallBackProcessor = function(state) { - OneSignal._formatPermissionObj(state.permissionStatus); - callback(state); +OneSignal.prototype.addPermissionObserver = function(callback) { + OneSignal._permissionObserverList.push(callback); + var permissionCallBackProcessor = function(state) { + OneSignal._formatPermissionObj(state.to); + OneSignal._formatPermissionObj(state.from); + OneSignal._processFunctionList(OneSignal._permissionObserverList, state); }; - cordova.exec(internalCallBackProcessor, function(){}, "OneSignalPush", "getPermissionSubscriptionState", []); -}; - -OneSignal.prototype.getIds = function(IdsReceivedCallBack) { - cordova.exec(IdsReceivedCallBack, function(){}, "OneSignalPush", "getIds", []); + cordova.exec(permissionCallBackProcessor, function(){}, "OneSignalPush", "addPermissionObserver", []); }; OneSignal.prototype.getTags = function(tagsReceivedCallBack) { @@ -178,12 +139,13 @@ OneSignal.prototype.deleteTags = function(keys) { cordova.exec(function(){}, function(){}, "OneSignalPush", "deleteTags", keys); }; -// Only applies to iOS(does nothing on Android as it always silently registers) +// Only applies to iOS (does nothing on Android as it always silently registers) // Call only if you passed false to autoRegister OneSignal.prototype.registerForPushNotifications = function() { cordova.exec(function(){}, function(){}, "OneSignalPush", "registerForPushNotifications", []); }; +// Only applies to iOS (does nothing on Android as it always silently registers without user permission) OneSignal.prototype.promptForPushNotificationsWithUserResponse = function(callback) { var internalCallback = function(data) { callback(data.accepted === "true"); @@ -195,22 +157,24 @@ OneSignal.prototype.clearOneSignalNotifications = function() { cordova.exec(function(){}, function(){}, "OneSignalPush", "clearOneSignalNotifications", []); }; -// Only applies to Android, vibrate is on by default but can be disabled by passing in false. -OneSignal.prototype.enableVibrate = function(enable) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "enableVibrate", [enable]); +// Only applies to Android. +// If notifications are disabled for your app, unsubscribe the user from OneSignal. +OneSignal.prototype.unsubscribeWhenNotificationsAreDisabled = function(unsubscribe) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "unsubscribeWhenNotificationsAreDisabled", [unsubscribe]); }; -// Only applies to Android, sound is on by default but can be disabled by passing in false. -OneSignal.prototype.enableSound = function(enable) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "enableSound", [enable]); +// Only applies to Android. Cancels a single OneSignal notification based on its Android notification integer ID +OneSignal.prototype.removeNotification = function(id) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "removeNotification", []); }; -OneSignal.prototype.enableNotificationsWhenActive = function(enable) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "enableNotificationsWhenActive", [enable]); +// Only applies to Android. Cancels a single OneSignal notification based on its Android notification group ID +OneSignal.prototype.removeGroupedNotifications = function(groupId) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "removeGroupedNotifications", [groupId]); }; -OneSignal.prototype.setSubscription = function(enable) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "setSubscription", [enable]); +OneSignal.prototype.disablePush = function(disable) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "disablePush", [disable]); }; OneSignal.prototype.postNotification = function(jsonData, onSuccess, onFailure) { @@ -223,24 +187,29 @@ OneSignal.prototype.postNotification = function(jsonData, onSuccess, onFailure) cordova.exec(onSuccess, onFailure, "OneSignalPush", "postNotification", [jsonData]); }; -OneSignal.prototype.promptLocation = function() { - cordova.exec(function(){}, function(){}, "OneSignalPush", "promptLocation", []); +OneSignal.prototype.setLogLevel = function(logLevel) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "setLogLevel", [logLevel]); }; -OneSignal.prototype.syncHashedEmail = function(email) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "syncHashedEmail", [email]); +OneSignal.prototype.userProvidedPrivacyConsent = function(callback) { + cordova.exec(callback, function(){}, "OneSignalPush", "userProvidedPrivacyConsent", []); }; -OneSignal.prototype.setLogLevel = function(logLevel) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "setLogLevel", [logLevel]); +OneSignal.prototype.requiresUserPrivacyConsent = function(callback) { + cordova.exec(callback, function(){}, "OneSignalPush", "requiresUserPrivacyConsent", []); }; -OneSignal.prototype.setLocationShared = function(shared) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "setLocationShared", [shared]); +OneSignal.prototype.setRequiresUserPrivacyConsent = function(required) { + cordova.exec(function() {}, function() {}, "OneSignalPush", "setRequiresUserPrivacyConsent", [required]); }; -//email +OneSignal.prototype.provideUserConsent = function(granted) { + cordova.exec(function() {}, function() {}, "OneSignalPush", "provideUserConsent", [granted]); +}; +/** + * Email + */ OneSignal.prototype.setEmail = function(email, emailAuthToken, onSuccess, onFailure) { if (onSuccess == null) onSuccess = function() {}; @@ -271,18 +240,6 @@ OneSignal.prototype.logoutEmail = function(onSuccess, onFailure) { cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutEmail", []); }; -OneSignal.prototype.userProvidedPrivacyConsent = function(callback) { - cordova.exec(callback, function(){}, "OneSignalPush", "userProvidedPrivacyConsent", []); -}; - -OneSignal.prototype.setRequiresUserPrivacyConsent = function(required) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "setRequiresUserPrivacyConsent", [required]); -}; - -OneSignal.prototype.provideUserConsent = function(granted) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "provideUserConsent", [granted]); -}; - /** Possible function usages setExternalUserId(externalId: string?): void setExternalUserId(externalId: string?, callback: function): void @@ -328,9 +285,8 @@ OneSignal.prototype.removeExternalUserId = function(externalUserIdCallback) { }; /** - * in app messaging + * In app messaging */ - OneSignal.prototype.addTriggers = function(triggers) { Object.keys(triggers).forEach(function(key){ // forces values to be string types @@ -370,9 +326,8 @@ OneSignal.prototype.pauseInAppMessages = function(pause) { }; /** - * outcomes + * Outcomes */ - OneSignal.prototype.sendOutcome = function(name, callback) { if (typeof callback === "undefined") callback = function() {}; @@ -421,6 +376,18 @@ OneSignal.prototype.sendOutcomeWithValue = function(name, value, callback) { cordova.exec(sendOutcomeWithValueCallback, function() {}, "OneSignalPush", "sendOutcomeWithValue", [name, Number(value)]); }; +/** + * Location + */ + +OneSignal.prototype.promptLocation = function() { + cordova.exec(function(){}, function(){}, "OneSignalPush", "promptLocation", []); +}; + +OneSignal.prototype.setLocationShared = function(shared) { + cordova.exec(function() {}, function() {}, "OneSignalPush", "setLocationShared", [shared]); +}; + //------------------------------------------------------------------- if(!window.plugins) From 96cfc553353e463b5f46660e284ae85bd8a0b98b Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 22 Mar 2021 18:27:20 -0300 Subject: [PATCH 11/55] Update OneSignal.js and Android module * Update based on iOS method implementations * Update iOS OneSignalPush files, implement Android methods unsubscribeWhenNotificationsAreDisabled, removeNotification, removeGroupedNotifications * Add userProvidedPrivacyConsent method * Replace consentGranted with provideUserConsent * Implement isLocationShared * Replace registerForPushNotifications with registerForProvisionalAuthorization --- .../com/plugin/gcm/OneSignalController.java | 2 +- src/android/com/plugin/gcm/OneSignalPush.java | 6 +- src/ios/OneSignalPush.h | 16 ++-- src/ios/OneSignalPush.m | 87 ++++++++++++------- www/OneSignal.js | 9 +- 5 files changed, 75 insertions(+), 45 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalController.java b/src/android/com/plugin/gcm/OneSignalController.java index 5800b4d9..ef3d3a08 100644 --- a/src/android/com/plugin/gcm/OneSignalController.java +++ b/src/android/com/plugin/gcm/OneSignalController.java @@ -138,7 +138,7 @@ public static boolean removeGroupedNotifications(JSONArray data) { } } - public static boolean registerForPushNotifications() { + public static boolean registerForProvisionalAuthorization() { // doesn't apply to Android return true; } diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index 3e18980b..a99e4230 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -57,7 +57,7 @@ public class OneSignalPush extends CordovaPlugin { private static final String DELETE_TAGS = "deleteTags"; private static final String SEND_TAGS = "sendTags"; - private static final String REGISTER_FOR_PUSH_NOTIFICATIONS = "registerForPushNotifications"; + private static final String REGISTER_FOR_PROVISIONAL_AUTHORIZATION = "registerForProvisionalAuthorization"; private static final String PROMPT_FOR_PUSH_NOTIFICATIONS_WITH_USER_RESPONSE = "promptForPushNotificationsWithUserResponse"; private static final String UNSUBSCRIBE_WHEN_NOTIFICATIONS_DISABLED = "unsubscribeWhenNotificationsAreDisabled"; @@ -182,8 +182,8 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.deleteTags(data); break; - case REGISTER_FOR_PUSH_NOTIFICATIONS: - result = OneSignalController.registerForPushNotifications(); + case REGISTER_FOR_PROVISIONAL_AUTHORIZATION: + result = OneSignalController.registerForProvisionalAuthorization(); break; case PROMPT_FOR_PUSH_NOTIFICATIONS_WITH_USER_RESPONSE: diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index ff4181a5..1b80154e 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -55,21 +55,25 @@ - (void)disablePush:(CDVInvokedUrlCommand* _Nonnull)command; - (void)postNotification:(CDVInvokedUrlCommand* _Nonnull)command; -// Email -- (void)setEmail:(CDVInvokedUrlCommand* _Nonnull)command; -- (void)setUnauthenticatedEmail:(CDVInvokedUrlCommand* _Nonnull)command; -- (void)logoutEmail:(CDVInvokedUrlCommand* _Nonnull)command; - // Start Android Only - (void)clearOneSignalNotifications:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)unsubscribeWhenNotificationsAreDisabled:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)removeNotification:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)removeGroupedNotifications:(CDVInvokedUrlCommand* _Nonnull)command; // End Android Only -- (void)consentGranted:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)userProvidedPrivacyConsent:(CDVInvokedUrlCommand* _Nonnull)command; - (void)requiresUserPrivacyConsent:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setRequiresUserPrivacyConsent:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)provideUserConsent:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setExternalUserId:(CDVInvokedUrlCommand* _Nonnull)command; - (void)removeExternalUserId:(CDVInvokedUrlCommand* _Nonnull)command; + +// Email +- (void)setEmail:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setUnauthenticatedEmail:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)logoutEmail:(CDVInvokedUrlCommand* _Nonnull)command; // In App Message - (void)setLaunchURLsInApp:(CDVInvokedUrlCommand* _Nonnull)command; diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index f2b5ced4..7e53697b 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -39,6 +39,7 @@ NSString* permissionObserverCallbackId; NSString* subscriptionObserverCallbackId; NSString* promptForPushNotificationsWithUserResponseCallbackId; +NSString* registerForProvisionalAuthorizationCallbackId; NSString* setEmailCallbackId; NSString* setUnauthenticatedEmailCallbackId; NSString* setExternalIdCallbackId; @@ -235,7 +236,10 @@ - (void)promptForPushNotificationsWithUserResponse:(CDVInvokedUrlCommand*)comman } - (void)registerForProvisionalAuthorization:(CDVInvokedUrlCommand *)command { - + registerForProvisionalAuthorizationCallbackId = command.callbackId; + [OneSignal registerForProvisionalAuthorization:^(BOOL accepted) { + successCallback(registerForProvisionalAuthorizationCallbackId, @{@"accepted": (accepted ? @"true" : @"false")}); + }]; } - (void)disablePush:(CDVInvokedUrlCommand*)command { @@ -258,6 +262,40 @@ - (void)postNotification:(CDVInvokedUrlCommand*)command { }]; } +// Start Android only +- (void)clearOneSignalNotifications:(CDVInvokedUrlCommand*)command {} + +- (void)unsubscribeWhenNotificationsAreDisabled:(CDVInvokedUrlCommand *)command {} + +- (void)removeNotification:(CDVInvokedUrlCommand *)command {} + +- (void)removeGroupedNotifications:(CDVInvokedUrlCommand *)command {} +// Finish Android only + +- (void)userProvidedPrivacyConsent:(CDVInvokedUrlCommand *)command { + CDVPluginResult* commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:!OneSignal.requiresUserPrivacyConsent]; + commandResult.keepCallback = @1; + [pluginCommandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; +} + +- (void)requiresUserPrivacyConsent:(CDVInvokedUrlCommand *)command { + BOOL requiresUserPrivacyConsent = [OneSignal requiresUserPrivacyConsent]; + NSDictionary *result = @{ + @"value" : @(requiresUserPrivacyConsent) + }; + successCallback(command.callbackId, result); +} + +- (void)setRequiresUserPrivacyConsent:(CDVInvokedUrlCommand *)command { + if (command.arguments.count >= 1) + [OneSignal setRequiresUserPrivacyConsent:[command.arguments[0] boolValue]]; +} + +- (void)provideUserConsent:(CDVInvokedUrlCommand *)command { + if (command.arguments.count >= 1) + [OneSignal consentGranted:[command.arguments[0] boolValue]]; +} + - (void)setEmail:(CDVInvokedUrlCommand *)command { setEmailCallbackId = command.callbackId; @@ -293,35 +331,6 @@ - (void)logoutEmail:(CDVInvokedUrlCommand *)command { }]; } - -// Start Android only -- (void)clearOneSignalNotifications:(CDVInvokedUrlCommand*)command {} -// Finish Android only - -- (void)consentGranted:(CDVInvokedUrlCommand *)command { - -} - -- (void)requiresUserPrivacyConsent:(CDVInvokedUrlCommand *)command { - -} - -- (void)userProvidedPrivacyConsent:(CDVInvokedUrlCommand *)command { - CDVPluginResult* commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:!OneSignal.requiresUserPrivacyConsent]; - commandResult.keepCallback = @1; - [pluginCommandDelegate sendPluginResult:commandResult callbackId:command.callbackId]; -} - -- (void)setRequiresUserPrivacyConsent:(CDVInvokedUrlCommand *)command { - if (command.arguments.count >= 1) - [OneSignal setRequiresUserPrivacyConsent:[command.arguments[0] boolValue]]; -} - -- (void)provideUserConsent:(CDVInvokedUrlCommand *)command { - if (command.arguments.count >= 1) - [OneSignal consentGranted:[command.arguments[0] boolValue]]; -} - - (void)setExternalUserId:(CDVInvokedUrlCommand *)command { setExternalIdCallbackId = command.callbackId; @@ -392,6 +401,10 @@ - (void)pauseInAppMessages:(CDVInvokedUrlCommand*)command { [OneSignal pauseInAppMessages:pause]; } +/** + * Outcomes + */ + - (void)sendOutcome:(CDVInvokedUrlCommand*)command { NSString *name = command.arguments[0]; @@ -417,16 +430,24 @@ - (void)sendOutcomeWithValue:(CDVInvokedUrlCommand*)command { }]; } +/** + * Location + */ + - (void)promptLocation:(CDVInvokedUrlCommand*)command { - [OneSignal promptLocation]; + [OneSignal promptLocation]; } - (void)setLocationShared:(CDVInvokedUrlCommand *)command { - [OneSignal setLocationShared:[command.arguments[0] boolValue]]; + [OneSignal setLocationShared:[command.arguments[0] boolValue]]; } - (void)isLocationShared:(CDVInvokedUrlCommand *)command { - + BOOL locationShared = [OneSignal isLocationShared]; + NSDictionary *result = @{ + @"value" : @(locationShared) + }; + successCallback(command.callbackId, result); } @end diff --git a/www/OneSignal.js b/www/OneSignal.js index 1efadb51..b7f82d38 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -141,8 +141,8 @@ OneSignal.prototype.deleteTags = function(keys) { // Only applies to iOS (does nothing on Android as it always silently registers) // Call only if you passed false to autoRegister -OneSignal.prototype.registerForPushNotifications = function() { - cordova.exec(function(){}, function(){}, "OneSignalPush", "registerForPushNotifications", []); +OneSignal.prototype.registerForProvisionalAuthorization = function() { + cordova.exec(function(){}, function(){}, "OneSignalPush", "registerForProvisionalAuthorization", []); }; // Only applies to iOS (does nothing on Android as it always silently registers without user permission) @@ -153,6 +153,7 @@ OneSignal.prototype.promptForPushNotificationsWithUserResponse = function(callba cordova.exec(internalCallback, function(){}, "OneSignalPush", "promptForPushNotificationsWithUserResponse", []); }; +// Only applies to Android. OneSignal.prototype.clearOneSignalNotifications = function() { cordova.exec(function(){}, function(){}, "OneSignalPush", "clearOneSignalNotifications", []); }; @@ -388,6 +389,10 @@ OneSignal.prototype.setLocationShared = function(shared) { cordova.exec(function() {}, function() {}, "OneSignalPush", "setLocationShared", [shared]); }; +OneSignal.prototype.isLocationShared = function(shared) { + cordova.exec(function() {}, function() {}, "OneSignalPush", "isLocationShared", [shared]); +}; + //------------------------------------------------------------------- if(!window.plugins) From 42968980db7147d0e66b57040fdac5ab1cfa766f Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 30 Mar 2021 15:20:05 -0300 Subject: [PATCH 12/55] Add Notification foreground handling Android --- src/android/com/plugin/gcm/OneSignalPush.java | 73 +++++++++++++++++-- www/OneSignal.js | 10 ++- 2 files changed, 73 insertions(+), 10 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index a99e4230..7c367609 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -30,6 +30,8 @@ import android.util.Log; import com.onesignal.OSInAppMessageAction; +import com.onesignal.OSNotification; +import com.onesignal.OSNotificationOpenedResult; import com.onesignal.OSNotificationReceivedEvent; import com.onesignal.OneSignal; @@ -37,7 +39,8 @@ import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; -import org.json.JSONObject; + +import java.util.HashMap; public class OneSignalPush extends CordovaPlugin { private static final String TAG = "OneSignalPush"; @@ -45,6 +48,7 @@ public class OneSignalPush extends CordovaPlugin { private static final String SET_NOTIFICATION_WILL_SHOW_IN_FOREGROUND_HANDLER = "setNotificationWillShowInForegroundHandler"; private static final String SET_NOTIFICATION_OPENED_HANDLER = "setNotificationOpenedHandler"; private static final String SET_IN_APP_MESSAGE_CLICK_HANDLER = "setInAppMessageClickHandler"; + private static final String COMPLETE_NOTIFICATION = "completeNotification"; private static final String INIT = "init"; private static final String GET_DEVICE_STATE = "getDeviceState"; @@ -96,11 +100,12 @@ public class OneSignalPush extends CordovaPlugin { private static final String SEND_UNIQUE_OUTCOME = "sendUniqueOutcome"; private static final String SEND_OUTCOME_WITH_VALUE = "sendOutcomeWithValue"; + private static final HashMap notificationReceivedEventCache = new HashMap<>(); + private static CallbackContext notifWillShowInForegroundCallbackContext; private static CallbackContext notifOpenedCallbackContext; private static CallbackContext inAppMessageClickedCallbackContext; - public static boolean setNotificationWillShowInForegroundHandler(CallbackContext callbackContext) { notifWillShowInForegroundCallbackContext = callbackContext; return true; @@ -123,6 +128,8 @@ public boolean init(CallbackContext callbackContext, JSONArray data) { OneSignal.sdkType = "cordova"; OneSignal.setInAppMessageClickHandler(new CordovaInAppMessageClickHandler(inAppMessageClickedCallbackContext)); + OneSignal.setNotificationOpenedHandler(new CordovaNotificationOpenHandler(notifOpenedCallbackContext)); + OneSignal.setNotificationWillShowInForegroundHandler(new CordovaNotificationInForegroundHandler(notifWillShowInForegroundCallbackContext)); OneSignal.setAppId(appId); OneSignal.initWithContext(this.cordova.getActivity()); @@ -150,6 +157,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = setInAppMessageClickHandler(callbackContext); break; + case COMPLETE_NOTIFICATION: + result = completeNotification(data); + break; + case INIT: result = init(callbackContext, data); break; @@ -302,6 +313,29 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo return result; } + private boolean completeNotification(JSONArray data) { + try { + String notificationId = data.getString(0); + boolean shouldDisplay = data.getBoolean(0); + + OSNotificationReceivedEvent notificationReceivedEvent = notificationReceivedEventCache.get(notificationId); + + if (notificationReceivedEvent == null) { + OneSignal.onesignalLog(OneSignal.LOG_LEVEL.ERROR, "Could not find notification completion block with id: " + notificationId); + return false; + } + + if (shouldDisplay) + notificationReceivedEvent.complete(notificationReceivedEvent.getNotification()); + else + notificationReceivedEvent.complete(null); + + return true; + } catch (JSONException e) { + e.printStackTrace(); + } + return false; + } /** * Handlers @@ -309,19 +343,44 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo private class CordovaNotificationInForegroundHandler implements OneSignal.OSNotificationWillShowInForegroundHandler { - private CallbackContext jsNotificationOpenedCallBack; + private CallbackContext jsNotificationInForegroundCallBack; public CordovaNotificationInForegroundHandler(CallbackContext inCallbackContext) { - jsNotificationOpenedCallBack = inCallbackContext; + jsNotificationInForegroundCallBack = inCallbackContext; } @Override public void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) { try { - notificationReceivedEvent.complete(notificationReceivedEvent.getNotification()); - CallbackHelper.callbackSuccess(jsNotificationOpenedCallBack, new JSONObject(notificationReceivedEvent.toJSONObject().toString())); + if (jsNotificationInForegroundCallBack == null) { + notificationReceivedEvent.complete(notificationReceivedEvent.getNotification()); + return; + } + + OSNotification notification = notificationReceivedEvent.getNotification(); + notificationReceivedEventCache.put(notification.getNotificationId(), notificationReceivedEvent); + + CallbackHelper.callbackSuccess(jsNotificationInForegroundCallBack, notificationReceivedEvent.toJSONObject()); + } catch (Throwable t) { + t.printStackTrace(); } - catch (Throwable t) { + } + } + + private class CordovaNotificationOpenHandler implements OneSignal.OSNotificationOpenedHandler { + + private CallbackContext jsNotificationOpenedCallBack; + + public CordovaNotificationOpenHandler(CallbackContext inCallbackContext) { + jsNotificationOpenedCallBack = inCallbackContext; + } + + @Override + public void notificationOpened(OSNotificationOpenedResult result) { + try { + if (jsNotificationOpenedCallBack != null) + CallbackHelper.callbackSuccess(jsNotificationOpenedCallBack, result.toJSONObject()); + } catch (Throwable t) { t.printStackTrace(); } } diff --git a/www/OneSignal.js b/www/OneSignal.js index b7f82d38..a60de7dc 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -27,9 +27,9 @@ var OneSignal = function() { var _appID = ""; - var _notificationWillShowInForegroundDelegate = function() {}; - var _notificationOpenedDelegate = function() {}; - var _inAppMessageClickDelegate = function () {}; + var _notificationWillShowInForegroundDelegate = function(notificationReceived) {}; + var _notificationOpenedDelegate = function(notificationOpened) {}; + var _inAppMessageClickDelegate = function (action) {}; }; OneSignal.prototype.OSNotificationPermission = { @@ -87,6 +87,10 @@ OneSignal._formatPermissionObj = function(state) { } }; +OneSignal.prototype.completeNotification = function(notificationId, shouldDisplay) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [notificationId, shouldDisplay]); +}; + OneSignal.prototype.getDeviceState = function(deviceStateReceivedCallBack) { cordova.exec(deviceStateReceivedCallBack, function(){}, "OneSignalPush", "getDeviceState", []); }; From 217a13cc9999c9db642944cb8978f8badcba960d Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 1 Apr 2021 13:40:48 -0300 Subject: [PATCH 13/55] Fix completeNotification method --- src/android/com/plugin/gcm/OneSignalPush.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index 7c367609..696a74fc 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -316,7 +316,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo private boolean completeNotification(JSONArray data) { try { String notificationId = data.getString(0); - boolean shouldDisplay = data.getBoolean(0); + boolean shouldDisplay = data.getBoolean(1); OSNotificationReceivedEvent notificationReceivedEvent = notificationReceivedEventCache.get(notificationId); From cc56dfd219332127b55c41f5b2a857554f3c4e90 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 1 Apr 2021 13:41:02 -0300 Subject: [PATCH 14/55] Fix removeNotification method --- www/OneSignal.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index a60de7dc..337b1ebf 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -170,7 +170,7 @@ OneSignal.prototype.unsubscribeWhenNotificationsAreDisabled = function(unsubscri // Only applies to Android. Cancels a single OneSignal notification based on its Android notification integer ID OneSignal.prototype.removeNotification = function(id) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "removeNotification", []); + cordova.exec(function(){}, function(){}, "OneSignalPush", "removeNotification", [id]); }; // Only applies to Android. Cancels a single OneSignal notification based on its Android notification group ID From eb94a139977559202c4dca28e7d15996375af07d Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 1 Apr 2021 17:12:28 -0300 Subject: [PATCH 15/55] Add isLocationShared Method support on Android --- src/android/com/plugin/gcm/OneSignalController.java | 4 +++- src/android/com/plugin/gcm/OneSignalPush.java | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/android/com/plugin/gcm/OneSignalController.java b/src/android/com/plugin/gcm/OneSignalController.java index ef3d3a08..a95e6f56 100644 --- a/src/android/com/plugin/gcm/OneSignalController.java +++ b/src/android/com/plugin/gcm/OneSignalController.java @@ -250,7 +250,9 @@ public static void setLocationShared(JSONArray data) { } } - public static void isLocationShared(JSONArray data) { + public static boolean isLocationShared(CallbackContext callbackContext) { // doesn't apply to Android + CallbackHelper.callbackSuccessBoolean(callbackContext, false); + return true; } } \ No newline at end of file diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index 696a74fc..9580637f 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -79,6 +79,7 @@ public class OneSignalPush extends CordovaPlugin { private static final String SET_LOG_LEVEL = "setLogLevel"; private static final String SET_LOCATION_SHARED = "setLocationShared"; + private static final String IS_LOCATION_SHARED = "isLocationShared"; private static final String PROMPT_LOCATION = "promptLocation"; private static final String USER_PROVIDED_CONSENT = "userProvidedPrivacyConsent"; @@ -249,6 +250,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo OneSignalController.setLocationShared(data); break; + case IS_LOCATION_SHARED: + result = OneSignalController.isLocationShared(callbackContext); + break; + case USER_PROVIDED_CONSENT: result = OneSignalController.userProvidedConsent(callbackContext); break; From 166a9d62cc2d89f099f77364d13b4bcbc4041ed3 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 1 Apr 2021 17:36:02 -0300 Subject: [PATCH 16/55] Add Notification foreground handling iOS --- src/ios/OneSignalPush.h | 3 ++- src/ios/OneSignalPush.m | 50 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index 1b80154e..7a8f7fc6 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -1,7 +1,7 @@ /** * Modified MIT License * - * Copyright 2017 OneSignal + * Copyright 2021 OneSignal * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -36,6 +36,7 @@ - (void)setProvidesNotificationSettingsView:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setNotificationWillShowInForegroundHandler:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)completeNotification:(CDVInvokedUrlCommand* _Nonnull)command; - (void)init:(CDVInvokedUrlCommand* _Nonnull)command; - (void)getDeviceState:(CDVInvokedUrlCommand* _Nonnull)command; diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 7e53697b..54396134 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -143,6 +143,13 @@ - (BOOL)oneSignalApplication:(UIApplication*)application didFinishLaunchingWithO @end +@interface OneSignalPush () + +@property (strong, nonatomic) NSMutableDictionary* notificationCompletionCache; +@property (strong, nonatomic) NSMutableDictionary* receivedNotificationCache; + +@end + @implementation OneSignalPush - (void)onOSPermissionChanged:(OSPermissionStateChanges*)stateChanges { @@ -170,15 +177,52 @@ - (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand*)command { notificationOpenedCallbackId = command.callbackId; } -- (void)init:(CDVInvokedUrlCommand*)command { +- (void)completeNotification:(CDVInvokedUrlCommand*)command { + NSString *notificationId = command.arguments[0]; + BOOL shouldDisplay = [command.arguments[1] boolValue]; + OSNotificationDisplayResponse completion = self.notificationCompletionCache[notificationId]; + if (!completion) { + [OneSignal onesignalLog:ONE_S_LL_ERROR message:[NSString stringWithFormat:@"OneSignal (objc): could not find notification completion block with id: %@", notificationId]]; + return; + } + + if (shouldDisplay) { + OSNotification *notification = self.receivedNotificationCache[notificationId]; + completion(notification); + } else { + completion(nil); + } + + [self.notificationCompletionCache removeObjectForKey:notificationId]; + [self.receivedNotificationCache removeObjectForKey:notificationId]; +} + +- (void)init:(CDVInvokedUrlCommand*)command { + _receivedNotificationCache = [NSMutableDictionary new]; + _notificationCompletionCache = [NSMutableDictionary new];; + pluginCommandDelegate = self.commandDelegate; NSString* appId = (NSString*)command.arguments[0]; initOneSignalObject(nil, [appId UTF8String]); - - if (notification) + + [OneSignal setNotificationOpenedHandler:^(OSNotificationOpenedResult * _Nonnull result) { + actionNotification = result; + if (pluginCommandDelegate) + processNotificationOpened(actionNotification); + }]; + [OneSignal setNotificationWillShowInForegroundHandler:^(OSNotification *notification, OSNotificationDisplayResponse completion) { + if (!notificationWillShowInForegoundCallbackId) { + completion(notification); + return; + } + + self.receivedNotificationCache[notification.notificationId] = notification; + self.notificationCompletionCache[notification.notificationId] = completion; processNotificationWillShowInForeground(notification); + }]; + if (actionNotification) processNotificationOpened(actionNotification); } From f96119d82247c4db33b8c43a379d43f71ca4ee77 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 1 Apr 2021 17:51:02 -0300 Subject: [PATCH 17/55] Add isLocationShared method call from cordova to native --- www/OneSignal.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index 337b1ebf..30564338 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -393,8 +393,8 @@ OneSignal.prototype.setLocationShared = function(shared) { cordova.exec(function() {}, function() {}, "OneSignalPush", "setLocationShared", [shared]); }; -OneSignal.prototype.isLocationShared = function(shared) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "isLocationShared", [shared]); +OneSignal.prototype.isLocationShared = function(callback) { + cordova.exec(callback, function() {}, "OneSignalPush", "isLocationShared", []); }; //------------------------------------------------------------------- From 2e0800f265eedfa421ff96bf674024ffe98ccdcf Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 13 Apr 2021 14:46:12 -0300 Subject: [PATCH 18/55] Add NotificationReceivedEvent and OSNotification classes * Add foreground classes for better user experiencie support, now both android and iOS will call window.plugins.OneSignal.completeNotification(notificationReceivedEvent.notification, true); --- www/OneSignal.js | 130 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 125 insertions(+), 5 deletions(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index 30564338..a86d05df 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -65,8 +65,13 @@ OneSignal.prototype.handleInAppMessageClicked = function(handler) { }; OneSignal.prototype.endInit = function() { + + var foregroundParsingHandler = function(notificationReceived) { + OneSignal._notificationWillShowInForegroundDelegate(new NotificationReceivedEvent(notificationReceived)); + }; + // Pass notification received handler - cordova.exec(OneSignal._notificationWillShowInForegroundDelegate, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); + cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); cordova.exec(OneSignal._notificationOpenedDelegate, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); cordova.exec(OneSignal._inAppMessageClickDelegate, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); // Call Init @@ -87,8 +92,8 @@ OneSignal._formatPermissionObj = function(state) { } }; -OneSignal.prototype.completeNotification = function(notificationId, shouldDisplay) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [notificationId, shouldDisplay]); +OneSignal.prototype.completeNotification = function(notification, shouldDisplay) { + cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [notification.notificationId, shouldDisplay]); }; OneSignal.prototype.getDeviceState = function(deviceStateReceivedCallBack) { @@ -126,7 +131,7 @@ OneSignal.prototype.getTags = function(tagsReceivedCallBack) { }; OneSignal.prototype.sendTag = function(key, value) { - jsonKeyValue = {}; + var jsonKeyValue = {}; jsonKeyValue[key] = value; cordova.exec(function(){}, function(){}, "OneSignalPush", "sendTags", [jsonKeyValue]); }; @@ -397,6 +402,120 @@ OneSignal.prototype.isLocationShared = function(callback) { cordova.exec(callback, function() {}, "OneSignalPush", "isLocationShared", []); }; +class OSNotification { + constructor(receivedEvent) { + this.notificationId = receivedEvent.notificationId; + this.body = receivedEvent.body; + this.title = receivedEvent.title; + + this.actionButtons = receivedEvent.actionButtons; + this.additionalData = receivedEvent.additionalData; + this.rawPayload = receivedEvent.rawPayload; + this.launchURL = receivedEvent.launchURL; + this.sound = receivedEvent.sound; + + // Android + if (receivedEvent.groupKey) { + this.groupKey = receivedEvent.groupKey; + } + if (receivedEvent.ledColor) { + this.ledColor = receivedEvent.ledColor; + } + if (receivedEvent.priority) { + this.priority = receivedEvent.priority; + } + if (receivedEvent.smallIcon) { + this.smallIcon = receivedEvent.smallIcon; + } + if (receivedEvent.largeIcon) { + this.largeIcon = receivedEvent.largeIcon; + } + if (receivedEvent.bigPicture) { + this.bigPicture = receivedEvent.bigPicture; + } + if (receivedEvent.collapseId) { + this.collapseId = receivedEvent.collapseId; + } + if (receivedEvent.groupMessage) { + this.groupMessage = receivedEvent.groupMessage; + } + if (receivedEvent.fromProjectNumber) { + this.fromProjectNumber = receivedEvent.fromProjectNumber; + } + if (receivedEvent.smallIconAccentColor) { + this.smallIconAccentColor = receivedEvent.smallIconAccentColor; + } + if (receivedEvent.lockScreenVisibililty) { + this.lockScreenVisibility = receivedEvent.lockScreenVisibililty; + } + if (receivedEvent.androidNotificationId) { + this.androidNotificationId = receivedEvent.androidNotificationId; + } + + // iOS + if (receivedEvent.badge) { + this.badge = receivedEvent.badge; + } + if (receivedEvent.category) { + this.category = receivedEvent.category; + } + if (receivedEvent.threadId) { + this.threadId = receivedEvent.threadId; + } + if (receivedEvent.subtitle) { + this.subtitle = receivedEvent.subtitle; + } + if (receivedEvent.templateId) { + this.templateId = receivedEvent.templateId; + } + if (receivedEvent.attachments) { + this.attachments = receivedEvent.attachments; + } + if (receivedEvent.templateName) { + this.templateName = receivedEvent.templateName; + } + if (receivedEvent.mutableContent) { + this.mutableContent = receivedEvent.mutableContent; + } + if (receivedEvent.badgeIncrement) { + this.badgeIncrement = receivedEvent.badgeIncrement; + } + if (receivedEvent.contentAvailable) { + this.contentAvailable = receivedEvent.contentAvailable; + } + } +} + +class NotificationReceivedEvent { + constructor(receivedEvent) { + if (receivedEvent.notification) { + // Android case + this.notification = new OSNotification(receivedEvent.notification); + } else { + // iOS case + this.notification = new OSNotification(receivedEvent); + } + } + + complete(notification) { + if (!notification) { + // if the notificationReceivedEvent is null, we want to call the native-side + // complete/completion with null to silence the notification + cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, false]); + return; + } + + // if the notificationReceivedEvent is not null, we want to pass the specific event + // future: Android side: make the notification modifiable + // iOS & Android: the notification id is associated with the native-side complete handler / completion block + cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, true]); + } + + getNotification() { + return this.notification; + } +} + //------------------------------------------------------------------- if(!window.plugins) @@ -405,5 +524,6 @@ if(!window.plugins) if (!window.plugins.OneSignal) window.plugins.OneSignal = new OneSignal(); -if (typeof module != 'undefined' && module.exports) +if (typeof module != 'undefined' && module.exports) { module.exports = OneSignal; +} From 7d825d764da63f847a56dc7059c63480394fac2c Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 16 Apr 2021 15:38:53 -0300 Subject: [PATCH 19/55] Add handler classes * Add OSActionButton and OSAndroidBackgroundImageLayout for Android notification parsing * Add OSNotificationOpenedResult and OSNotificationAction for notification open handler * Add class OSInAppMessageAction for in app message click handler --- www/OneSignal.js | 211 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 204 insertions(+), 7 deletions(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index a86d05df..13a46850 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -70,10 +70,18 @@ OneSignal.prototype.endInit = function() { OneSignal._notificationWillShowInForegroundDelegate(new NotificationReceivedEvent(notificationReceived)); }; + var notificationOpenedHandler = function(json) { + OneSignal._notificationOpenedDelegate(new OSNotificationOpenedResult(json)); + }; + + var inAppMessageClickHandler = function(json) { + OneSignal._inAppMessageClickDelegate(new OSInAppMessageAction(json)); + }; + // Pass notification received handler cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); - cordova.exec(OneSignal._notificationOpenedDelegate, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); - cordova.exec(OneSignal._inAppMessageClickDelegate, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); + cordova.exec(notificationOpenedHandler, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); + cordova.exec(inAppMessageClickHandler, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); // Call Init cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignal._appID]); }; @@ -404,82 +412,191 @@ OneSignal.prototype.isLocationShared = function(callback) { class OSNotification { constructor(receivedEvent) { + /// The OneSignal notification ID for this notification this.notificationId = receivedEvent.notificationId; + /// The body (should contain most of the text) this.body = receivedEvent.body; + /// The title for the notification this.title = receivedEvent.title; - - this.actionButtons = receivedEvent.actionButtons; + /// Any additional custom data you want to send along + /// with this notification. this.additionalData = receivedEvent.additionalData; + /// A hashmap object representing the raw key/value + /// properties of the push notification this.rawPayload = receivedEvent.rawPayload; + /// If set, he launch URL will be opened when the user + /// taps on your push notification. You can control + /// whether or not it opens in an in-app webview or + /// in Safari (with iOS). this.launchURL = receivedEvent.launchURL; + /// The sound file (ie. ping.aiff) that should be played + /// when the notification is received this.sound = receivedEvent.sound; + /// Any buttons you want to add to the notification. + /// The notificationOpened handler will provide an + /// OSNotificationAction object, which will contain + /// the ID of the Action the user tapped. + if (receivedEvent.actionButtons) { + this.actionButtons = []; + for (let btn of receivedEvent.actionButtons) { + this.actionButtons.push(new OSActionButton(btn)); + } + } + // Android + + /// (Android only) + /// All notifications with the same group key + /// from the same app will be grouped together if (receivedEvent.groupKey) { this.groupKey = receivedEvent.groupKey; } + /// (Android Only) + /// The color to use to light up the LED (if + /// applicable) when the notification is received + /// Given in hex ARGB format. if (receivedEvent.ledColor) { this.ledColor = receivedEvent.ledColor; } + /// (Android Only) + /// The priority used with GCM/FCM to describe how + /// urgent the notification is. A higher priority + /// means the notification will be delivered faster. + /// Default = 10. if (receivedEvent.priority) { this.priority = receivedEvent.priority; } + /// (Android Only) + /// The filename of the image to use as the small + /// icon for the notification if (receivedEvent.smallIcon) { this.smallIcon = receivedEvent.smallIcon; } + /// (Android Only) + /// The filename for the image to use as the large + /// icon for the notification if (receivedEvent.largeIcon) { this.largeIcon = receivedEvent.largeIcon; } + /// (Android Only) + /// The URL or filename for the image to use as + /// the big picture for the notification if (receivedEvent.bigPicture) { this.bigPicture = receivedEvent.bigPicture; } + /// (Android Only) + /// The collapse ID for the notification + /// As opposed to groupKey (which causes stacking), + /// the collapse ID will completely replace any + /// previously received push notifications that + /// use the same collapse_id if (receivedEvent.collapseId) { this.collapseId = receivedEvent.collapseId; } + /// (Android only) Android 6 and earlier only + /// The message to display when multiple + /// notifications have been stacked together. + /// Note: Android 7 allows groups (stacks) + /// to be expanded, so group message is no + /// longer necessary if (receivedEvent.groupMessage) { this.groupMessage = receivedEvent.groupMessage; } + /// (Android Only) + /// Tells you what project number/sender ID + /// the notification was sent from if (receivedEvent.fromProjectNumber) { this.fromProjectNumber = receivedEvent.fromProjectNumber; } + /// (Android Only) + /// The accent color to use on the notification + /// Hex value in ARGB format (it's a normal + /// hex color value, but it includes the alpha + /// channel in addition to red, green, blue) if (receivedEvent.smallIconAccentColor) { this.smallIconAccentColor = receivedEvent.smallIconAccentColor; } + /// (Android only) API level 21+ + /// Sets the visibility of the notification + /// 1 = Public (default) + /// 0 = Private (hidden from lock screen + /// if user set 'Hide Sensitive content') + /// -1 = Secret (doesn't appear at all) if (receivedEvent.lockScreenVisibililty) { this.lockScreenVisibility = receivedEvent.lockScreenVisibililty; } + /// (Android Only) + /// The android notification ID (not same as the OneSignal + /// notification ID) if (receivedEvent.androidNotificationId) { this.androidNotificationId = receivedEvent.androidNotificationId; } + /// (Android Only) + /// Describes the background image layout of the + /// notification (if set) + if (receivedEvent.backgroundImageLayout) { + this.backgroundImageLayout = new OSAndroidBackgroundImageLayout(receivedEvent.backgroundImageLayout); + } + /// (Android Only) + /// Summary notifications grouped + /// Notification payload will have the most recent notification received. + if (receivedEvent.groupedNotifications && receivedEvent.groupedNotifications.length) { + this.groupedNotifications = receivedEvent.groupedNotificationss.map(function(num) { + return new OSNotification(item); + }); + } // iOS + + /// (iOS Only) + /// If you set the badge to a specific value, this integer + /// property will be that value if (receivedEvent.badge) { this.badge = receivedEvent.badge; } + /// (iOS Only) + /// The category for this notification. This can trigger custom + /// behavior (ie. if this notification should display a + /// custom Content Extension for custom UI) if (receivedEvent.category) { this.category = receivedEvent.category; } - if (receivedEvent.threadId) { - this.threadId = receivedEvent.threadId; - } + /// (iOS Only) + /// The subtitle of the notification if (receivedEvent.subtitle) { this.subtitle = receivedEvent.subtitle; } + /// If this notification was created from a Template on the + /// OneSignal dashboard, this will be the ID of that template if (receivedEvent.templateId) { this.templateId = receivedEvent.templateId; } + /// (iOS Only) + /// Any attachments (images, sounds, videos) you want + /// to display with this notification. if (receivedEvent.attachments) { this.attachments = receivedEvent.attachments; } + /// The name of the template (if any) that was used to + /// create this push notification if (receivedEvent.templateName) { this.templateName = receivedEvent.templateName; } + /// (iOS Only) + /// Tells the system to launch the Notification Extension Service if (receivedEvent.mutableContent) { this.mutableContent = receivedEvent.mutableContent; } + /// (iOS Only) + /// If you want to increment the badge by some value, this + /// integer will be the increment/decrement if (receivedEvent.badgeIncrement) { this.badgeIncrement = receivedEvent.badgeIncrement; } + /// (iOS Only) + /// Tells the system to launch your app in the background (ie. if + /// content is available to download in the background) if (receivedEvent.contentAvailable) { this.contentAvailable = receivedEvent.contentAvailable; } @@ -515,6 +632,86 @@ class NotificationReceivedEvent { return this.notification; } } + +/// Represents a button sent as part of a push notification +class OSActionButton { + constructor(json) { + /// The custom unique ID for this button + this.id = json.id; + /// The text to display for the button + this.text = json.text; + + /// (Android only) + /// The URL/filename to show as the + /// button's icon + if (json.icon) { + this.icon = json.icon; + } + } +} + +/// (Android Only) +/// This class represents the background image layout +/// used for push notifications that show a background image +class OSAndroidBackgroundImageLayout { + constructor(json) { + /// (Android Only) + /// The image URL/filename to show as the background image + if (json.image) { + this.image = json.image; + } + /// (Android Only) + /// The color of the title text + if (json.titleTextColor) { + this.titleTextColor = json.titleTextColor; + } + /// (Android Only) + /// The color of the body text + if (json.bodyTextColor) { + this.bodyTextColor = json.bodyTextColor; + } + } +} + +/// An instance of this class represents a user interaction with +/// your push notification, ie. if they tap a button +class OSNotificationOpenedResult { + constructor(json) { + this.notification = new OSNotification(json.notification); + + if (json.action) { + this.action = new OSNotificationAction(json.action); + } + } +} + +/// Represents an action taken on a push notification, such as +/// tapping the notification (or a button on the notification), +/// or if your `inFocusDisplayType` is set to true - if they +/// tapped 'close'. +class OSNotificationAction { + constructor(json) { + /// The ID of the button on your notification + /// that the user tapped + this.actionId = json.actionId; + + /// An int that represents whether the user `opened` or + /// took a more specific `action` (such as tapping a button + /// on the notification) + this.type = json.type; + } +} + +class OSInAppMessageAction { + constructor(json) { + this.clickName = json.click_name; + this.clickUrl = json.click_url; + this.firstClick = json.first_click; + this.closesMessage = json.closes_message; + } +} + + //------------------------------------------------------------------- From 3393ea975758f829043a4af59611cbcde79656b8 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 16 Apr 2021 20:04:29 -0300 Subject: [PATCH 20/55] Edit plugin.xml file * Increase Android version to 4.3.0 and iOS version to 3.4.0 * Remove Windows support * Remove Amazon Fire config --- plugin.xml | 47 ++--------------------------------------------- 1 file changed, 2 insertions(+), 45 deletions(-) diff --git a/plugin.xml b/plugin.xml index 73e1b9a5..f4795b7e 100644 --- a/plugin.xml +++ b/plugin.xml @@ -26,7 +26,7 @@ - + @@ -35,26 +35,6 @@ - - - - - - - - - - - - - - - - - - @@ -75,12 +55,6 @@ - - - remote-notification - - - development @@ -88,28 +62,11 @@ production - + - - - - - - - - - - - - - - - - - From 6fa318e5e75f5cdb199af14199dab44ad4c144f1 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 16 Apr 2021 20:10:22 -0300 Subject: [PATCH 21/55] Remove build pattern from init * Rename startInit to setAppId * Remove endInit * Make all set handlers independant --- src/android/com/plugin/gcm/OneSignalPush.java | 34 +++++---------- src/ios/OneSignalPush.m | 28 ++++++------ www/OneSignal.js | 43 +++++++++---------- 3 files changed, 44 insertions(+), 61 deletions(-) diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/plugin/gcm/OneSignalPush.java index 9580637f..80349898 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/plugin/gcm/OneSignalPush.java @@ -103,34 +103,27 @@ public class OneSignalPush extends CordovaPlugin { private static final HashMap notificationReceivedEventCache = new HashMap<>(); - private static CallbackContext notifWillShowInForegroundCallbackContext; - private static CallbackContext notifOpenedCallbackContext; - private static CallbackContext inAppMessageClickedCallbackContext; - - public static boolean setNotificationWillShowInForegroundHandler(CallbackContext callbackContext) { - notifWillShowInForegroundCallbackContext = callbackContext; + public boolean setNotificationWillShowInForegroundHandler(CallbackContext callbackContext) { + OneSignal.setNotificationWillShowInForegroundHandler(new CordovaNotificationInForegroundHandler(callbackContext)); return true; } - public static boolean setNotificationOpenedHandler(CallbackContext callbackContext) { - notifOpenedCallbackContext = callbackContext; + public boolean setNotificationOpenedHandler(CallbackContext callbackContext) { + OneSignal.setNotificationOpenedHandler(new CordovaNotificationOpenHandler(callbackContext)); return true; } - public static boolean setInAppMessageClickHandler(CallbackContext callbackContext) { - inAppMessageClickedCallbackContext = callbackContext; + public boolean setInAppMessageClickHandler(CallbackContext callbackContext) { + OneSignal.setInAppMessageClickHandler(new CordovaInAppMessageClickHandler(callbackContext)); return true; } - public boolean init(CallbackContext callbackContext, JSONArray data) { + public boolean init(JSONArray data) { try { String appId = data.getString(0); OneSignal.sdkType = "cordova"; - OneSignal.setInAppMessageClickHandler(new CordovaInAppMessageClickHandler(inAppMessageClickedCallbackContext)); - OneSignal.setNotificationOpenedHandler(new CordovaNotificationOpenHandler(notifOpenedCallbackContext)); - OneSignal.setNotificationWillShowInForegroundHandler(new CordovaNotificationInForegroundHandler(notifWillShowInForegroundCallbackContext)); OneSignal.setAppId(appId); OneSignal.initWithContext(this.cordova.getActivity()); @@ -163,7 +156,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo break; case INIT: - result = init(callbackContext, data); + result = init(data); break; case GET_DEVICE_STATE: @@ -346,7 +339,7 @@ private boolean completeNotification(JSONArray data) { * Handlers */ - private class CordovaNotificationInForegroundHandler implements OneSignal.OSNotificationWillShowInForegroundHandler { + private static class CordovaNotificationInForegroundHandler implements OneSignal.OSNotificationWillShowInForegroundHandler { private CallbackContext jsNotificationInForegroundCallBack; @@ -357,11 +350,6 @@ public CordovaNotificationInForegroundHandler(CallbackContext inCallbackContext) @Override public void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) { try { - if (jsNotificationInForegroundCallBack == null) { - notificationReceivedEvent.complete(notificationReceivedEvent.getNotification()); - return; - } - OSNotification notification = notificationReceivedEvent.getNotification(); notificationReceivedEventCache.put(notification.getNotificationId(), notificationReceivedEvent); @@ -372,7 +360,7 @@ public void notificationWillShowInForeground(OSNotificationReceivedEvent notific } } - private class CordovaNotificationOpenHandler implements OneSignal.OSNotificationOpenedHandler { + private static class CordovaNotificationOpenHandler implements OneSignal.OSNotificationOpenedHandler { private CallbackContext jsNotificationOpenedCallBack; @@ -391,7 +379,7 @@ public void notificationOpened(OSNotificationOpenedResult result) { } } - private class CordovaInAppMessageClickHandler implements OneSignal.OSInAppMessageClickHandler { + private static class CordovaInAppMessageClickHandler implements OneSignal.OSInAppMessageClickHandler { private CallbackContext jsInAppMessageClickedCallback; diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 54396134..5108bd79 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -171,10 +171,22 @@ - (void)setProvidesNotificationSettingsView:(CDVInvokedUrlCommand *)command { - (void)setNotificationWillShowInForegroundHandler:(CDVInvokedUrlCommand*)command { notificationWillShowInForegoundCallbackId = command.callbackId; + + [OneSignal setNotificationWillShowInForegroundHandler:^(OSNotification *notification, OSNotificationDisplayResponse completion) { + self.receivedNotificationCache[notification.notificationId] = notification; + self.notificationCompletionCache[notification.notificationId] = completion; + processNotificationWillShowInForeground(notification); + }]; } - (void)setNotificationOpenedHandler:(CDVInvokedUrlCommand*)command { notificationOpenedCallbackId = command.callbackId; + + [OneSignal setNotificationOpenedHandler:^(OSNotificationOpenedResult * _Nonnull result) { + actionNotification = result; + if (pluginCommandDelegate) + processNotificationOpened(actionNotification); + }]; } - (void)completeNotification:(CDVInvokedUrlCommand*)command { @@ -206,22 +218,6 @@ - (void)init:(CDVInvokedUrlCommand*)command { NSString* appId = (NSString*)command.arguments[0]; initOneSignalObject(nil, [appId UTF8String]); - - [OneSignal setNotificationOpenedHandler:^(OSNotificationOpenedResult * _Nonnull result) { - actionNotification = result; - if (pluginCommandDelegate) - processNotificationOpened(actionNotification); - }]; - [OneSignal setNotificationWillShowInForegroundHandler:^(OSNotification *notification, OSNotificationDisplayResponse completion) { - if (!notificationWillShowInForegoundCallbackId) { - completion(notification); - return; - } - - self.receivedNotificationCache[notification.notificationId] = notification; - self.notificationCompletionCache[notification.notificationId] = completion; - processNotificationWillShowInForeground(notification); - }]; if (actionNotification) processNotificationOpened(actionNotification); diff --git a/www/OneSignal.js b/www/OneSignal.js index 13a46850..2011b9ab 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -27,7 +27,7 @@ var OneSignal = function() { var _appID = ""; - var _notificationWillShowInForegroundDelegate = function(notificationReceived) {}; + var _notificationWillShowInForegroundDelegate = null; //Sintax function(notificationReceived) {}; var _notificationOpenedDelegate = function(notificationOpened) {}; var _inAppMessageClickDelegate = function (action) {}; }; @@ -44,46 +44,45 @@ OneSignal._emailSubscriptionObserverList = []; // You must call init before any other OneSignal function. -OneSignal.prototype.startInit = function(appId) { +OneSignal.prototype.setAppId = function(appId) { OneSignal._appID = appId; - return this; + + cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignal._appID]); }; OneSignal.prototype.handleNotificationWillShowInForeground = function(handleNotificationWillShowInForegroundCallback) { OneSignal._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; - return this; + + var foregroundParsingHandler = function(notificationReceived) { + let notificationReceivedEvent = new NotificationReceivedEvent(notificationReceived) + if (OneSignal._notificationWillShowInForegroundDelegate != null) { + OneSignal._notificationWillShowInForegroundDelegate(notificationReceivedEvent); + } else { + notificationReceivedEvent.complete(notificationReceivedEvent.notification); + } + }; + + cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); }; OneSignal.prototype.handleNotificationOpened = function(handleNotificationOpenedCallback) { OneSignal._notificationOpenedDelegate = handleNotificationOpenedCallback; - return this; -}; - -OneSignal.prototype.handleInAppMessageClicked = function(handler) { - OneSignal._inAppMessageClickDelegate = handler; - return this; -}; - -OneSignal.prototype.endInit = function() { - - var foregroundParsingHandler = function(notificationReceived) { - OneSignal._notificationWillShowInForegroundDelegate(new NotificationReceivedEvent(notificationReceived)); - }; var notificationOpenedHandler = function(json) { OneSignal._notificationOpenedDelegate(new OSNotificationOpenedResult(json)); }; + cordova.exec(notificationOpenedHandler, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); +}; + +OneSignal.prototype.handleInAppMessageClicked = function(handler) { + OneSignal._inAppMessageClickDelegate = handler; + var inAppMessageClickHandler = function(json) { OneSignal._inAppMessageClickDelegate(new OSInAppMessageAction(json)); }; - // Pass notification received handler - cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); - cordova.exec(notificationOpenedHandler, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); cordova.exec(inAppMessageClickHandler, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); - // Call Init - cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignal._appID]); }; OneSignal._processFunctionList = function(array, param) { From e06adc375e0036536b9242fa8318d8c6dcad0925 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 16 Apr 2021 20:58:34 -0300 Subject: [PATCH 22/55] Rename Android package * Rename package to com.onesignal.cordova --- plugin.xml | 16 ++++++++-------- .../cordova}/CallbackHelper.java | 2 +- .../cordova}/OneSignalController.java | 2 +- .../cordova}/OneSignalEmailController.java | 2 +- .../OneSignalInAppMessagingController.java | 2 +- .../cordova}/OneSignalObserverController.java | 2 +- .../cordova}/OneSignalOutcomeController.java | 2 +- .../gcm => onesignal/cordova}/OneSignalPush.java | 2 +- 8 files changed, 15 insertions(+), 15 deletions(-) rename src/android/com/{plugin/gcm => onesignal/cordova}/CallbackHelper.java (98%) rename src/android/com/{plugin/gcm => onesignal/cordova}/OneSignalController.java (99%) rename src/android/com/{plugin/gcm => onesignal/cordova}/OneSignalEmailController.java (99%) rename src/android/com/{plugin/gcm => onesignal/cordova}/OneSignalInAppMessagingController.java (99%) rename src/android/com/{plugin/gcm => onesignal/cordova}/OneSignalObserverController.java (98%) rename src/android/com/{plugin/gcm => onesignal/cordova}/OneSignalOutcomeController.java (98%) rename src/android/com/{plugin/gcm => onesignal/cordova}/OneSignalPush.java (99%) diff --git a/plugin.xml b/plugin.xml index f4795b7e..a52e1207 100644 --- a/plugin.xml +++ b/plugin.xml @@ -31,17 +31,17 @@ - + - - - - - - - + + + + + + + diff --git a/src/android/com/plugin/gcm/CallbackHelper.java b/src/android/com/onesignal/cordova/CallbackHelper.java similarity index 98% rename from src/android/com/plugin/gcm/CallbackHelper.java rename to src/android/com/onesignal/cordova/CallbackHelper.java index d1dd2b27..7e261dc7 100644 --- a/src/android/com/plugin/gcm/CallbackHelper.java +++ b/src/android/com/onesignal/cordova/CallbackHelper.java @@ -1,4 +1,4 @@ -package com.plugin.gcm; +package com.onesignal.cordova; import org.apache.cordova.CallbackContext; import org.json.JSONObject; diff --git a/src/android/com/plugin/gcm/OneSignalController.java b/src/android/com/onesignal/cordova/OneSignalController.java similarity index 99% rename from src/android/com/plugin/gcm/OneSignalController.java rename to src/android/com/onesignal/cordova/OneSignalController.java index a95e6f56..9253b80f 100644 --- a/src/android/com/plugin/gcm/OneSignalController.java +++ b/src/android/com/onesignal/cordova/OneSignalController.java @@ -1,4 +1,4 @@ -package com.plugin.gcm; +package com.onesignal.cordova; import com.onesignal.OSDeviceState; import com.onesignal.OneSignal; diff --git a/src/android/com/plugin/gcm/OneSignalEmailController.java b/src/android/com/onesignal/cordova/OneSignalEmailController.java similarity index 99% rename from src/android/com/plugin/gcm/OneSignalEmailController.java rename to src/android/com/onesignal/cordova/OneSignalEmailController.java index a7586a9c..7a7e4e6f 100644 --- a/src/android/com/plugin/gcm/OneSignalEmailController.java +++ b/src/android/com/onesignal/cordova/OneSignalEmailController.java @@ -1,4 +1,4 @@ -package com.plugin.gcm; +package com.onesignal.cordova; import com.onesignal.OneSignal; import com.onesignal.OneSignal.EmailUpdateError; diff --git a/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java b/src/android/com/onesignal/cordova/OneSignalInAppMessagingController.java similarity index 99% rename from src/android/com/plugin/gcm/OneSignalInAppMessagingController.java rename to src/android/com/onesignal/cordova/OneSignalInAppMessagingController.java index 3ae89aac..8645559f 100644 --- a/src/android/com/plugin/gcm/OneSignalInAppMessagingController.java +++ b/src/android/com/onesignal/cordova/OneSignalInAppMessagingController.java @@ -1,4 +1,4 @@ -package com.plugin.gcm; +package com.onesignal.cordova; import com.onesignal.OneSignal; diff --git a/src/android/com/plugin/gcm/OneSignalObserverController.java b/src/android/com/onesignal/cordova/OneSignalObserverController.java similarity index 98% rename from src/android/com/plugin/gcm/OneSignalObserverController.java rename to src/android/com/onesignal/cordova/OneSignalObserverController.java index 8c0df697..2562100d 100644 --- a/src/android/com/plugin/gcm/OneSignalObserverController.java +++ b/src/android/com/onesignal/cordova/OneSignalObserverController.java @@ -1,4 +1,4 @@ -package com.plugin.gcm; +package com.onesignal.cordova; import org.apache.cordova.CallbackContext; diff --git a/src/android/com/plugin/gcm/OneSignalOutcomeController.java b/src/android/com/onesignal/cordova/OneSignalOutcomeController.java similarity index 98% rename from src/android/com/plugin/gcm/OneSignalOutcomeController.java rename to src/android/com/onesignal/cordova/OneSignalOutcomeController.java index fd83a58e..d25caa0e 100644 --- a/src/android/com/plugin/gcm/OneSignalOutcomeController.java +++ b/src/android/com/onesignal/cordova/OneSignalOutcomeController.java @@ -1,4 +1,4 @@ -package com.plugin.gcm; +package com.onesignal.cordova; import android.util.Log; diff --git a/src/android/com/plugin/gcm/OneSignalPush.java b/src/android/com/onesignal/cordova/OneSignalPush.java similarity index 99% rename from src/android/com/plugin/gcm/OneSignalPush.java rename to src/android/com/onesignal/cordova/OneSignalPush.java index 80349898..9731ccaa 100644 --- a/src/android/com/plugin/gcm/OneSignalPush.java +++ b/src/android/com/onesignal/cordova/OneSignalPush.java @@ -25,7 +25,7 @@ * THE SOFTWARE. */ -package com.plugin.gcm; +package com.onesignal.cordova; import android.util.Log; From eb435bdacad025e20dc7895d279b20cbac222ffa Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 16 Apr 2021 21:15:21 -0300 Subject: [PATCH 23/55] Add OSDeviceState class support * Standarize keys between platforms --- www/OneSignal.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index 2011b9ab..802c28e9 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -104,7 +104,10 @@ OneSignal.prototype.completeNotification = function(notification, shouldDisplay) }; OneSignal.prototype.getDeviceState = function(deviceStateReceivedCallBack) { - cordova.exec(deviceStateReceivedCallBack, function(){}, "OneSignalPush", "getDeviceState", []); + var deviceStateCallback = function(json) { + deviceStateReceivedCallBack(new OSDeviceState(json)); + }; + cordova.exec(deviceStateCallback, function(){}, "OneSignalPush", "getDeviceState", []); }; OneSignal.prototype.addSubscriptionObserver = function(callback) { @@ -710,7 +713,28 @@ class OSInAppMessageAction { } } +class OSDeviceState { + constructor(json) { + console.log("OSDeviceState: " + JSON.stringify(json)); + if (json.hasNotificationPermission) { + this.hasNotificationPermission = json.hasNotificationPermission; + } else { + this.hasNotificationPermission = json.areNotificationsEnabled; + } + if (json.notificationPermissionStatus != null) { + this.notificationPermissionStatus = json.notificationPermissionStatus; + } + + this.pushDisabled = json.isPushDisabled; + this.subscribed = json.isSubscribed; + this.emailSubscribed = json.isEmailSubscribed; + this.userId = json.userId; + this.pushToken = json.pushToken; + this.emailUserId = json.emailUserId; + this.emailAddress = json.emailAddress; + } +} //------------------------------------------------------------------- From 702dcd54c8bba4ebb0842e27ff92bff6cf299f2a Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 16 Apr 2021 22:05:10 -0300 Subject: [PATCH 24/55] Add StateChanges classes * Add OSSubscriptionStateChanges and OSSubscriptionState * Add OSEmailSubscriptionStateChanges and OSEmailSubscriptionState * Add OSPermissionStateChanges and OSPermissionState --- www/OneSignal.js | 115 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 93 insertions(+), 22 deletions(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index 802c28e9..73eb6de6 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -27,7 +27,7 @@ var OneSignal = function() { var _appID = ""; - var _notificationWillShowInForegroundDelegate = null; //Sintax function(notificationReceived) {}; + var _notificationWillShowInForegroundDelegate = function(notificationReceived) {}; var _notificationOpenedDelegate = function(notificationOpened) {}; var _inAppMessageClickDelegate = function (action) {}; }; @@ -54,12 +54,7 @@ OneSignal.prototype.handleNotificationWillShowInForeground = function(handleNoti OneSignal._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; var foregroundParsingHandler = function(notificationReceived) { - let notificationReceivedEvent = new NotificationReceivedEvent(notificationReceived) - if (OneSignal._notificationWillShowInForegroundDelegate != null) { - OneSignal._notificationWillShowInForegroundDelegate(notificationReceivedEvent); - } else { - notificationReceivedEvent.complete(notificationReceivedEvent.notification); - } + OneSignal._notificationWillShowInForegroundDelegate(new NotificationReceivedEvent(notificationReceived)); }; cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); @@ -90,15 +85,6 @@ OneSignal._processFunctionList = function(array, param) { array[i](param); }; -OneSignal._formatPermissionObj = function(state) { - // If Android format, match it to the iOS format - if ("undefined" !== typeof state.enabled) { - state.hasPrompted = true; - state.state = state.enabled ? OneSignal.prototype.OSNotificationPermission.Authorized : OneSignal.prototype.OSNotificationPermission.Denied; - delete state.enabled - } -}; - OneSignal.prototype.completeNotification = function(notification, shouldDisplay) { cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [notification.notificationId, shouldDisplay]); }; @@ -113,7 +99,7 @@ OneSignal.prototype.getDeviceState = function(deviceStateReceivedCallBack) { OneSignal.prototype.addSubscriptionObserver = function(callback) { OneSignal._subscriptionObserverList.push(callback); var subscriptionCallBackProcessor = function(state) { - OneSignal._processFunctionList(OneSignal._subscriptionObserverList, state); + OneSignal._processFunctionList(OneSignal._subscriptionObserverList, new OSSubscriptionStateChanges(state)); }; cordova.exec(subscriptionCallBackProcessor, function(){}, "OneSignalPush", "addSubscriptionObserver", []); }; @@ -121,7 +107,7 @@ OneSignal.prototype.addSubscriptionObserver = function(callback) { OneSignal.prototype.addEmailSubscriptionObserver = function(callback) { OneSignal._emailSubscriptionObserverList.push(callback); var emailSubscriptionCallbackProcessor = function(state) { - OneSignal._processFunctionList(OneSignal._emailSubscriptionObserverList, state); + OneSignal._processFunctionList(OneSignal._emailSubscriptionObserverList, new OSEmailSubscriptionStateChanges(state)); }; cordova.exec(emailSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addEmailSubscriptionObserver", []); }; @@ -129,9 +115,7 @@ OneSignal.prototype.addEmailSubscriptionObserver = function(callback) { OneSignal.prototype.addPermissionObserver = function(callback) { OneSignal._permissionObserverList.push(callback); var permissionCallBackProcessor = function(state) { - OneSignal._formatPermissionObj(state.to); - OneSignal._formatPermissionObj(state.from); - OneSignal._processFunctionList(OneSignal._permissionObserverList, state); + OneSignal._processFunctionList(OneSignal._permissionObserverList, new OSPermissionStateChanges(state)); }; cordova.exec(permissionCallBackProcessor, function(){}, "OneSignalPush", "addPermissionObserver", []); }; @@ -715,7 +699,6 @@ class OSInAppMessageAction { class OSDeviceState { constructor(json) { - console.log("OSDeviceState: " + JSON.stringify(json)); if (json.hasNotificationPermission) { this.hasNotificationPermission = json.hasNotificationPermission; } else { @@ -736,6 +719,94 @@ class OSDeviceState { } } +class OSPermissionState { + constructor(json) { + if (json.status != null) { + this.status = json.status; + } else { + this.status = json.areNotificationsEnabled ? OneSignal.prototype.OSNotificationPermission.Authorized : OneSignal.prototype.OSNotificationPermission.Denied; + } + + // iOS only + if (json.provisional != null) { + this.provisional = json.provisional; + } else { + this.provisional = false; + } + + // iOS only + if (json.hasPrompted != null) { + this.hasPrompted = json.hasPrompted; + } else { + this.hasPrompted = false; + } + } +} + +class OSPermissionStateChanges { + constructor(json) { + if (json.from) { + this.from = new OSPermissionState(json.from); + } + if (json.to) { + this.to = new OSPermissionState(json.to); + } + } +} + +/// Represents the current user's subscription state with OneSignal +class OSSubscriptionState { + constructor(json) { + /// A boolean parameter that indicates if the user + /// is subscribed to your app with OneSignal + /// This is only true if the `userId`, `pushToken`, and + /// `userSubscriptionSetting` parameters are defined/true. + this.subscribed = json.isSubscribed; + + /// The current user's User ID (AKA playerID) with OneSignal + this.userId = json.userId; + + /// The APNS (iOS), GCM/FCM (Android) push token + this.pushToken = json.pushToken; + } +} + +/// An instance of this class describes a change in the user's OneSignal +/// push notification subscription state, ie. the user subscribed to +/// push notifications with your app. +class OSSubscriptionStateChanges { + constructor(json) { + if (json.from) { + this.from = new OSSubscriptionState(json.from); + } + if (json.to) { + this.to = new OSSubscriptionState(json.to); + } + } +} + +/// Represents the user's OneSignal email subscription state, +class OSEmailSubscriptionState { + constructor(json) { + this.subscribed = json.isSubscribed; + this.emailAddress = json.emailAddress; + this.emailUserId = json.emailUserId; + } +} + +/// An instance of this class describes a change in the user's +/// email subscription state with OneSignal +class OSEmailSubscriptionStateChanges { + constructor(json) { + if (json.from) { + this.from = new OSEmailSubscriptionState(json.from); + } + if (json.to) { + this.to = new OSEmailSubscriptionState(json.to); + } + } +} + //------------------------------------------------------------------- if(!window.plugins) From 7ac93fdd4d2ca81cc94735f09d3db108fae105b1 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 20 Apr 2021 14:59:39 -0300 Subject: [PATCH 25/55] Move handles classes definition to single file * Move OSInAppMessageAction to InAppMessage.js * Move OSDeviceState, OSPermissionState, OSPermissionStateChanges, OSSubscriptionState, OSSubscriptionStateChanges, OSEmailSubscriptionState and OSEmailSubscriptionStateChanges to Subscription.js * Move OSNotificationReceivedEvent, OSNotification, OSAndroidBackgroundImageLayout and OSActionButton to NotificationReceived.js * Move OSNotificationOpenedResult and OSNotificationAction to NotificationOpened.js --- plugin.xml | 8 + www/InAppMessage.js | 8 + www/NotificationOpened.js | 28 +++ www/NotificationReceived.js | 261 ++++++++++++++++++++++ www/OneSignal.js | 422 +----------------------------------- www/Subscription.js | 102 +++++++++ 6 files changed, 417 insertions(+), 412 deletions(-) create mode 100644 www/InAppMessage.js create mode 100644 www/NotificationOpened.js create mode 100644 www/NotificationReceived.js create mode 100644 www/Subscription.js diff --git a/plugin.xml b/plugin.xml index a52e1207..f9c17a92 100644 --- a/plugin.xml +++ b/plugin.xml @@ -35,6 +35,10 @@ + + + + @@ -66,6 +70,10 @@ + + + + diff --git a/www/InAppMessage.js b/www/InAppMessage.js new file mode 100644 index 00000000..63664367 --- /dev/null +++ b/www/InAppMessage.js @@ -0,0 +1,8 @@ +function OSInAppMessageAction (json) { + this.clickName = json.click_name; + this.clickUrl = json.click_url; + this.firstClick = json.first_click; + this.closesMessage = json.closes_message; +} + +module.exports = OSInAppMessageAction; \ No newline at end of file diff --git a/www/NotificationOpened.js b/www/NotificationOpened.js new file mode 100644 index 00000000..10c8cacc --- /dev/null +++ b/www/NotificationOpened.js @@ -0,0 +1,28 @@ +var OSNotification = require('./NotificationReceived').OSNotification; + +/// An instance of this class represents a user interaction with +/// your push notification, ie. if they tap a button +function OSNotificationOpenedResult (json) { + this.notification = new OSNotification(json.notification); + + if (json.action) { + this.action = new OSNotificationAction(json.action); + } +} + +/// Represents an action taken on a push notification, such as +/// tapping the notification (or a button on the notification), +/// or if your `inFocusDisplayType` is set to true - if they +/// tapped 'close'. +function OSNotificationAction (json) { + /// The ID of the button on your notification + /// that the user tapped + this.actionId = json.actionId; + + /// An int that represents whether the user `opened` or + /// took a more specific `action` (such as tapping a button + /// on the notification) + this.type = json.type; +} + +module.exports = OSNotificationOpenedResult; \ No newline at end of file diff --git a/www/NotificationReceived.js b/www/NotificationReceived.js new file mode 100644 index 00000000..1457ad7a --- /dev/null +++ b/www/NotificationReceived.js @@ -0,0 +1,261 @@ +function OSNotification (receivedEvent) { + /// The OneSignal notification ID for this notification + this.notificationId = receivedEvent.notificationId; + /// The body (should contain most of the text) + this.body = receivedEvent.body; + /// The title for the notification + this.title = receivedEvent.title; + /// Any additional custom data you want to send along + /// with this notification. + this.additionalData = receivedEvent.additionalData; + /// A hashmap object representing the raw key/value + /// properties of the push notification + this.rawPayload = receivedEvent.rawPayload; + /// If set, he launch URL will be opened when the user + /// taps on your push notification. You can control + /// whether or not it opens in an in-app webview or + /// in Safari (with iOS). + this.launchURL = receivedEvent.launchURL; + /// The sound file (ie. ping.aiff) that should be played + /// when the notification is received + this.sound = receivedEvent.sound; + + /// Any buttons you want to add to the notification. + /// The notificationOpened handler will provide an + /// OSNotificationAction object, which will contain + /// the ID of the Action the user tapped. + if (receivedEvent.actionButtons) { + this.actionButtons = []; + for (let btn of receivedEvent.actionButtons) { + this.actionButtons.push(new OSActionButton(btn)); + } + } + + // Android + + /// (Android only) + /// All notifications with the same group key + /// from the same app will be grouped together + if (receivedEvent.groupKey) { + this.groupKey = receivedEvent.groupKey; + } + /// (Android Only) + /// The color to use to light up the LED (if + /// applicable) when the notification is received + /// Given in hex ARGB format. + if (receivedEvent.ledColor) { + this.ledColor = receivedEvent.ledColor; + } + /// (Android Only) + /// The priority used with GCM/FCM to describe how + /// urgent the notification is. A higher priority + /// means the notification will be delivered faster. + /// Default = 10. + if (receivedEvent.priority) { + this.priority = receivedEvent.priority; + } + /// (Android Only) + /// The filename of the image to use as the small + /// icon for the notification + if (receivedEvent.smallIcon) { + this.smallIcon = receivedEvent.smallIcon; + } + /// (Android Only) + /// The filename for the image to use as the large + /// icon for the notification + if (receivedEvent.largeIcon) { + this.largeIcon = receivedEvent.largeIcon; + } + /// (Android Only) + /// The URL or filename for the image to use as + /// the big picture for the notification + if (receivedEvent.bigPicture) { + this.bigPicture = receivedEvent.bigPicture; + } + /// (Android Only) + /// The collapse ID for the notification + /// As opposed to groupKey (which causes stacking), + /// the collapse ID will completely replace any + /// previously received push notifications that + /// use the same collapse_id + if (receivedEvent.collapseId) { + this.collapseId = receivedEvent.collapseId; + } + /// (Android only) Android 6 and earlier only + /// The message to display when multiple + /// notifications have been stacked together. + /// Note: Android 7 allows groups (stacks) + /// to be expanded, so group message is no + /// longer necessary + if (receivedEvent.groupMessage) { + this.groupMessage = receivedEvent.groupMessage; + } + /// (Android Only) + /// Tells you what project number/sender ID + /// the notification was sent from + if (receivedEvent.fromProjectNumber) { + this.fromProjectNumber = receivedEvent.fromProjectNumber; + } + /// (Android Only) + /// The accent color to use on the notification + /// Hex value in ARGB format (it's a normal + /// hex color value, but it includes the alpha + /// channel in addition to red, green, blue) + if (receivedEvent.smallIconAccentColor) { + this.smallIconAccentColor = receivedEvent.smallIconAccentColor; + } + /// (Android only) API level 21+ + /// Sets the visibility of the notification + /// 1 = Public (default) + /// 0 = Private (hidden from lock screen + /// if user set 'Hide Sensitive content') + /// -1 = Secret (doesn't appear at all) + if (receivedEvent.lockScreenVisibililty) { + this.lockScreenVisibility = receivedEvent.lockScreenVisibililty; + } + /// (Android Only) + /// The android notification ID (not same as the OneSignal + /// notification ID) + if (receivedEvent.androidNotificationId) { + this.androidNotificationId = receivedEvent.androidNotificationId; + } + /// (Android Only) + /// Describes the background image layout of the + /// notification (if set) + if (receivedEvent.backgroundImageLayout) { + this.backgroundImageLayout = new OSAndroidBackgroundImageLayout(receivedEvent.backgroundImageLayout); + } + /// (Android Only) + /// Summary notifications grouped + /// Notification payload will have the most recent notification received. + if (receivedEvent.groupedNotifications && receivedEvent.groupedNotifications.length) { + this.groupedNotifications = receivedEvent.groupedNotificationss.map(function(num) { + return new OSNotification(item); + }); + } + + // iOS + + /// (iOS Only) + /// If you set the badge to a specific value, this integer + /// property will be that value + if (receivedEvent.badge) { + this.badge = receivedEvent.badge; + } + /// (iOS Only) + /// The category for this notification. This can trigger custom + /// behavior (ie. if this notification should display a + /// custom Content Extension for custom UI) + if (receivedEvent.category) { + this.category = receivedEvent.category; + } + /// (iOS Only) + /// The subtitle of the notification + if (receivedEvent.subtitle) { + this.subtitle = receivedEvent.subtitle; + } + /// If this notification was created from a Template on the + /// OneSignal dashboard, this will be the ID of that template + if (receivedEvent.templateId) { + this.templateId = receivedEvent.templateId; + } + /// (iOS Only) + /// Any attachments (images, sounds, videos) you want + /// to display with this notification. + if (receivedEvent.attachments) { + this.attachments = receivedEvent.attachments; + } + /// The name of the template (if any) that was used to + /// create this push notification + if (receivedEvent.templateName) { + this.templateName = receivedEvent.templateName; + } + /// (iOS Only) + /// Tells the system to launch the Notification Extension Service + if (receivedEvent.mutableContent) { + this.mutableContent = receivedEvent.mutableContent; + } + /// (iOS Only) + /// If you want to increment the badge by some value, this + /// integer will be the increment/decrement + if (receivedEvent.badgeIncrement) { + this.badgeIncrement = receivedEvent.badgeIncrement; + } + /// (iOS Only) + /// Tells the system to launch your app in the background (ie. if + /// content is available to download in the background) + if (receivedEvent.contentAvailable) { + this.contentAvailable = receivedEvent.contentAvailable; + } +} + +/// Represents a button sent as part of a push notification +class OSActionButton { + constructor(json) { + /// The custom unique ID for this button + this.id = json.id; + /// The text to display for the button + this.text = json.text; + + /// (Android only) + /// The URL/filename to show as the + /// button's icon + if (json.icon) { + this.icon = json.icon; + } + } +} + +/// (Android Only) +/// This class represents the background image layout +/// used for push notifications that show a background image +class OSAndroidBackgroundImageLayout { + constructor(json) { + /// (Android Only) + /// The image URL/filename to show as the background image + if (json.image) { + this.image = json.image; + } + /// (Android Only) + /// The color of the title text + if (json.titleTextColor) { + this.titleTextColor = json.titleTextColor; + } + /// (Android Only) + /// The color of the body text + if (json.bodyTextColor) { + this.bodyTextColor = json.bodyTextColor; + } + } +} + +var OSNotificationReceivedEvent = { + create : function (receivedEvent) { + if (receivedEvent.notification) { + // Android case + this.notification = new OSNotification(receivedEvent.notification); + } else { + // iOS case + this.notification = new OSNotification(receivedEvent); + } + return this; + }, + complete : function (notification) { + if (!notification) { + // if the notificationReceivedEvent is null, we want to call the native-side + // complete/completion with null to silence the notification + cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, false]); + return; + } + + // if the notificationReceivedEvent is not null, we want to pass the specific event + // future: Android side: make the notification modifiable + // iOS & Android: the notification id is associated with the native-side complete handler / completion block + cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, true]); + } +}; + +module.exports = { + OSNotification: OSNotification, + OSNotificationReceivedEvent: OSNotificationReceivedEvent +}; \ No newline at end of file diff --git a/www/OneSignal.js b/www/OneSignal.js index 73eb6de6..8f3966e6 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -25,6 +25,14 @@ * THE SOFTWARE. */ +var OSNotificationReceivedEvent = require('./NotificationReceived').OSNotificationReceivedEvent; +var OSNotificationOpenedResult = require('./NotificationOpened'); +var OSInAppMessageAction = require('./InAppMessage'); +var OSDeviceState = require('./Subscription').OSDeviceState; +var OSPermissionStateChanges = require('./Subscription').OSPermissionStateChanges; +var OSSubscriptionStateChanges = require('./Subscription').OSSubscriptionStateChanges; +var OSEmailSubscriptionStateChanges = require('./Subscription').OSEmailSubscriptionStateChanges; + var OneSignal = function() { var _appID = ""; var _notificationWillShowInForegroundDelegate = function(notificationReceived) {}; @@ -54,7 +62,8 @@ OneSignal.prototype.handleNotificationWillShowInForeground = function(handleNoti OneSignal._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; var foregroundParsingHandler = function(notificationReceived) { - OneSignal._notificationWillShowInForegroundDelegate(new NotificationReceivedEvent(notificationReceived)); + console.log("foregroundParsingHandler " + JSON.stringify(notificationReceived)); + OneSignal._notificationWillShowInForegroundDelegate(OSNotificationReceivedEvent.create(notificationReceived)); }; cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); @@ -396,417 +405,6 @@ OneSignal.prototype.isLocationShared = function(callback) { cordova.exec(callback, function() {}, "OneSignalPush", "isLocationShared", []); }; -class OSNotification { - constructor(receivedEvent) { - /// The OneSignal notification ID for this notification - this.notificationId = receivedEvent.notificationId; - /// The body (should contain most of the text) - this.body = receivedEvent.body; - /// The title for the notification - this.title = receivedEvent.title; - /// Any additional custom data you want to send along - /// with this notification. - this.additionalData = receivedEvent.additionalData; - /// A hashmap object representing the raw key/value - /// properties of the push notification - this.rawPayload = receivedEvent.rawPayload; - /// If set, he launch URL will be opened when the user - /// taps on your push notification. You can control - /// whether or not it opens in an in-app webview or - /// in Safari (with iOS). - this.launchURL = receivedEvent.launchURL; - /// The sound file (ie. ping.aiff) that should be played - /// when the notification is received - this.sound = receivedEvent.sound; - - /// Any buttons you want to add to the notification. - /// The notificationOpened handler will provide an - /// OSNotificationAction object, which will contain - /// the ID of the Action the user tapped. - if (receivedEvent.actionButtons) { - this.actionButtons = []; - for (let btn of receivedEvent.actionButtons) { - this.actionButtons.push(new OSActionButton(btn)); - } - } - - // Android - - /// (Android only) - /// All notifications with the same group key - /// from the same app will be grouped together - if (receivedEvent.groupKey) { - this.groupKey = receivedEvent.groupKey; - } - /// (Android Only) - /// The color to use to light up the LED (if - /// applicable) when the notification is received - /// Given in hex ARGB format. - if (receivedEvent.ledColor) { - this.ledColor = receivedEvent.ledColor; - } - /// (Android Only) - /// The priority used with GCM/FCM to describe how - /// urgent the notification is. A higher priority - /// means the notification will be delivered faster. - /// Default = 10. - if (receivedEvent.priority) { - this.priority = receivedEvent.priority; - } - /// (Android Only) - /// The filename of the image to use as the small - /// icon for the notification - if (receivedEvent.smallIcon) { - this.smallIcon = receivedEvent.smallIcon; - } - /// (Android Only) - /// The filename for the image to use as the large - /// icon for the notification - if (receivedEvent.largeIcon) { - this.largeIcon = receivedEvent.largeIcon; - } - /// (Android Only) - /// The URL or filename for the image to use as - /// the big picture for the notification - if (receivedEvent.bigPicture) { - this.bigPicture = receivedEvent.bigPicture; - } - /// (Android Only) - /// The collapse ID for the notification - /// As opposed to groupKey (which causes stacking), - /// the collapse ID will completely replace any - /// previously received push notifications that - /// use the same collapse_id - if (receivedEvent.collapseId) { - this.collapseId = receivedEvent.collapseId; - } - /// (Android only) Android 6 and earlier only - /// The message to display when multiple - /// notifications have been stacked together. - /// Note: Android 7 allows groups (stacks) - /// to be expanded, so group message is no - /// longer necessary - if (receivedEvent.groupMessage) { - this.groupMessage = receivedEvent.groupMessage; - } - /// (Android Only) - /// Tells you what project number/sender ID - /// the notification was sent from - if (receivedEvent.fromProjectNumber) { - this.fromProjectNumber = receivedEvent.fromProjectNumber; - } - /// (Android Only) - /// The accent color to use on the notification - /// Hex value in ARGB format (it's a normal - /// hex color value, but it includes the alpha - /// channel in addition to red, green, blue) - if (receivedEvent.smallIconAccentColor) { - this.smallIconAccentColor = receivedEvent.smallIconAccentColor; - } - /// (Android only) API level 21+ - /// Sets the visibility of the notification - /// 1 = Public (default) - /// 0 = Private (hidden from lock screen - /// if user set 'Hide Sensitive content') - /// -1 = Secret (doesn't appear at all) - if (receivedEvent.lockScreenVisibililty) { - this.lockScreenVisibility = receivedEvent.lockScreenVisibililty; - } - /// (Android Only) - /// The android notification ID (not same as the OneSignal - /// notification ID) - if (receivedEvent.androidNotificationId) { - this.androidNotificationId = receivedEvent.androidNotificationId; - } - /// (Android Only) - /// Describes the background image layout of the - /// notification (if set) - if (receivedEvent.backgroundImageLayout) { - this.backgroundImageLayout = new OSAndroidBackgroundImageLayout(receivedEvent.backgroundImageLayout); - } - /// (Android Only) - /// Summary notifications grouped - /// Notification payload will have the most recent notification received. - if (receivedEvent.groupedNotifications && receivedEvent.groupedNotifications.length) { - this.groupedNotifications = receivedEvent.groupedNotificationss.map(function(num) { - return new OSNotification(item); - }); - } - - // iOS - - /// (iOS Only) - /// If you set the badge to a specific value, this integer - /// property will be that value - if (receivedEvent.badge) { - this.badge = receivedEvent.badge; - } - /// (iOS Only) - /// The category for this notification. This can trigger custom - /// behavior (ie. if this notification should display a - /// custom Content Extension for custom UI) - if (receivedEvent.category) { - this.category = receivedEvent.category; - } - /// (iOS Only) - /// The subtitle of the notification - if (receivedEvent.subtitle) { - this.subtitle = receivedEvent.subtitle; - } - /// If this notification was created from a Template on the - /// OneSignal dashboard, this will be the ID of that template - if (receivedEvent.templateId) { - this.templateId = receivedEvent.templateId; - } - /// (iOS Only) - /// Any attachments (images, sounds, videos) you want - /// to display with this notification. - if (receivedEvent.attachments) { - this.attachments = receivedEvent.attachments; - } - /// The name of the template (if any) that was used to - /// create this push notification - if (receivedEvent.templateName) { - this.templateName = receivedEvent.templateName; - } - /// (iOS Only) - /// Tells the system to launch the Notification Extension Service - if (receivedEvent.mutableContent) { - this.mutableContent = receivedEvent.mutableContent; - } - /// (iOS Only) - /// If you want to increment the badge by some value, this - /// integer will be the increment/decrement - if (receivedEvent.badgeIncrement) { - this.badgeIncrement = receivedEvent.badgeIncrement; - } - /// (iOS Only) - /// Tells the system to launch your app in the background (ie. if - /// content is available to download in the background) - if (receivedEvent.contentAvailable) { - this.contentAvailable = receivedEvent.contentAvailable; - } - } -} - -class NotificationReceivedEvent { - constructor(receivedEvent) { - if (receivedEvent.notification) { - // Android case - this.notification = new OSNotification(receivedEvent.notification); - } else { - // iOS case - this.notification = new OSNotification(receivedEvent); - } - } - - complete(notification) { - if (!notification) { - // if the notificationReceivedEvent is null, we want to call the native-side - // complete/completion with null to silence the notification - cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, false]); - return; - } - - // if the notificationReceivedEvent is not null, we want to pass the specific event - // future: Android side: make the notification modifiable - // iOS & Android: the notification id is associated with the native-side complete handler / completion block - cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, true]); - } - - getNotification() { - return this.notification; - } -} - -/// Represents a button sent as part of a push notification -class OSActionButton { - constructor(json) { - /// The custom unique ID for this button - this.id = json.id; - /// The text to display for the button - this.text = json.text; - - /// (Android only) - /// The URL/filename to show as the - /// button's icon - if (json.icon) { - this.icon = json.icon; - } - } -} - -/// (Android Only) -/// This class represents the background image layout -/// used for push notifications that show a background image -class OSAndroidBackgroundImageLayout { - constructor(json) { - /// (Android Only) - /// The image URL/filename to show as the background image - if (json.image) { - this.image = json.image; - } - /// (Android Only) - /// The color of the title text - if (json.titleTextColor) { - this.titleTextColor = json.titleTextColor; - } - /// (Android Only) - /// The color of the body text - if (json.bodyTextColor) { - this.bodyTextColor = json.bodyTextColor; - } - } -} - -/// An instance of this class represents a user interaction with -/// your push notification, ie. if they tap a button -class OSNotificationOpenedResult { - constructor(json) { - this.notification = new OSNotification(json.notification); - - if (json.action) { - this.action = new OSNotificationAction(json.action); - } - } -} - -/// Represents an action taken on a push notification, such as -/// tapping the notification (or a button on the notification), -/// or if your `inFocusDisplayType` is set to true - if they -/// tapped 'close'. -class OSNotificationAction { - constructor(json) { - /// The ID of the button on your notification - /// that the user tapped - this.actionId = json.actionId; - - /// An int that represents whether the user `opened` or - /// took a more specific `action` (such as tapping a button - /// on the notification) - this.type = json.type; - } -} - -class OSInAppMessageAction { - constructor(json) { - this.clickName = json.click_name; - this.clickUrl = json.click_url; - this.firstClick = json.first_click; - this.closesMessage = json.closes_message; - } -} - -class OSDeviceState { - constructor(json) { - if (json.hasNotificationPermission) { - this.hasNotificationPermission = json.hasNotificationPermission; - } else { - this.hasNotificationPermission = json.areNotificationsEnabled; - } - - if (json.notificationPermissionStatus != null) { - this.notificationPermissionStatus = json.notificationPermissionStatus; - } - - this.pushDisabled = json.isPushDisabled; - this.subscribed = json.isSubscribed; - this.emailSubscribed = json.isEmailSubscribed; - this.userId = json.userId; - this.pushToken = json.pushToken; - this.emailUserId = json.emailUserId; - this.emailAddress = json.emailAddress; - } -} - -class OSPermissionState { - constructor(json) { - if (json.status != null) { - this.status = json.status; - } else { - this.status = json.areNotificationsEnabled ? OneSignal.prototype.OSNotificationPermission.Authorized : OneSignal.prototype.OSNotificationPermission.Denied; - } - - // iOS only - if (json.provisional != null) { - this.provisional = json.provisional; - } else { - this.provisional = false; - } - - // iOS only - if (json.hasPrompted != null) { - this.hasPrompted = json.hasPrompted; - } else { - this.hasPrompted = false; - } - } -} - -class OSPermissionStateChanges { - constructor(json) { - if (json.from) { - this.from = new OSPermissionState(json.from); - } - if (json.to) { - this.to = new OSPermissionState(json.to); - } - } -} - -/// Represents the current user's subscription state with OneSignal -class OSSubscriptionState { - constructor(json) { - /// A boolean parameter that indicates if the user - /// is subscribed to your app with OneSignal - /// This is only true if the `userId`, `pushToken`, and - /// `userSubscriptionSetting` parameters are defined/true. - this.subscribed = json.isSubscribed; - - /// The current user's User ID (AKA playerID) with OneSignal - this.userId = json.userId; - - /// The APNS (iOS), GCM/FCM (Android) push token - this.pushToken = json.pushToken; - } -} - -/// An instance of this class describes a change in the user's OneSignal -/// push notification subscription state, ie. the user subscribed to -/// push notifications with your app. -class OSSubscriptionStateChanges { - constructor(json) { - if (json.from) { - this.from = new OSSubscriptionState(json.from); - } - if (json.to) { - this.to = new OSSubscriptionState(json.to); - } - } -} - -/// Represents the user's OneSignal email subscription state, -class OSEmailSubscriptionState { - constructor(json) { - this.subscribed = json.isSubscribed; - this.emailAddress = json.emailAddress; - this.emailUserId = json.emailUserId; - } -} - -/// An instance of this class describes a change in the user's -/// email subscription state with OneSignal -class OSEmailSubscriptionStateChanges { - constructor(json) { - if (json.from) { - this.from = new OSEmailSubscriptionState(json.from); - } - if (json.to) { - this.to = new OSEmailSubscriptionState(json.to); - } - } -} - //------------------------------------------------------------------- if(!window.plugins) diff --git a/www/Subscription.js b/www/Subscription.js new file mode 100644 index 00000000..1212d8b5 --- /dev/null +++ b/www/Subscription.js @@ -0,0 +1,102 @@ +function OSDeviceState(json) { + if (json.hasNotificationPermission) { + this.hasNotificationPermission = json.hasNotificationPermission; + } else { + this.hasNotificationPermission = json.areNotificationsEnabled; + } + + if (json.notificationPermissionStatus != null) { + this.notificationPermissionStatus = json.notificationPermissionStatus; + } + + this.pushDisabled = json.isPushDisabled; + this.subscribed = json.isSubscribed; + this.emailSubscribed = json.isEmailSubscribed; + this.userId = json.userId; + this.pushToken = json.pushToken; + this.emailUserId = json.emailUserId; + this.emailAddress = json.emailAddress; +} + +function OSPermissionState(json) { + if (json.status != null) { + this.status = json.status; + } else { + this.status = json.areNotificationsEnabled ? OneSignal.prototype.OSNotificationPermission.Authorized : OneSignal.prototype.OSNotificationPermission.Denied; + } + + // iOS only + if (json.provisional != null) { + this.provisional = json.provisional; + } else { + this.provisional = false; + } + + // iOS only + if (json.hasPrompted != null) { + this.hasPrompted = json.hasPrompted; + } else { + this.hasPrompted = false; + } +} + +function OSPermissionStateChanges(json) { + if (json.from) { + this.from = new OSPermissionState(json.from); + } + if (json.to) { + this.to = new OSPermissionState(json.to); + } +} + +/// Represents the current user's subscription state with OneSignal +function OSSubscriptionState(json) { + /// A boolean parameter that indicates if the user + /// is subscribed to your app with OneSignal + /// This is only true if the `userId`, `pushToken`, and + /// `userSubscriptionSetting` parameters are defined/true. + this.subscribed = json.isSubscribed; + + /// The current user's User ID (AKA playerID) with OneSignal + this.userId = json.userId; + + /// The APNS (iOS), GCM/FCM (Android) push token + this.pushToken = json.pushToken; +} + +/// An instance of this class describes a change in the user's OneSignal +/// push notification subscription state, ie. the user subscribed to +/// push notifications with your app. +function OSSubscriptionStateChanges(json) { + if (json.from) { + this.from = new OSSubscriptionState(json.from); + } + if (json.to) { + this.to = new OSSubscriptionState(json.to); + } +} + +/// Represents the user's OneSignal email subscription state, +function OSEmailSubscriptionState(json) { + this.subscribed = json.isSubscribed; + this.emailAddress = json.emailAddress; + this.emailUserId = json.emailUserId; +} + +/// An instance of this class describes a change in the user's +/// email subscription state with OneSignal +function OSEmailSubscriptionStateChanges(json) { + if (json.from) { + this.from = new OSEmailSubscriptionState(json.from); + } + if (json.to) { + this.to = new OSEmailSubscriptionState(json.to); + } +} + +module.exports = { + OSDeviceState: OSDeviceState, + OSPermissionStateChanges: OSPermissionStateChanges, + OSSubscriptionStateChanges: OSSubscriptionStateChanges, + OSEmailSubscriptionStateChanges: OSEmailSubscriptionStateChanges, +}; \ No newline at end of file From 277cd13c9b33f89623337b58d744963860e93061 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 20 Apr 2021 15:12:16 -0300 Subject: [PATCH 26/55] Codereview improvements --- .../com/onesignal/cordova/OneSignalController.java | 2 +- www/NotificationReceived.js | 3 +-- www/OneSignal.js | 2 +- www/Subscription.js | 8 ++++---- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/android/com/onesignal/cordova/OneSignalController.java b/src/android/com/onesignal/cordova/OneSignalController.java index 9253b80f..d5fcebdd 100644 --- a/src/android/com/onesignal/cordova/OneSignalController.java +++ b/src/android/com/onesignal/cordova/OneSignalController.java @@ -251,7 +251,7 @@ public static void setLocationShared(JSONArray data) { } public static boolean isLocationShared(CallbackContext callbackContext) { - // doesn't apply to Android + // Need to be implemented in Android CallbackHelper.callbackSuccessBoolean(callbackContext, false); return true; } diff --git a/www/NotificationReceived.js b/www/NotificationReceived.js index 1457ad7a..10c7a25b 100644 --- a/www/NotificationReceived.js +++ b/www/NotificationReceived.js @@ -50,8 +50,7 @@ function OSNotification (receivedEvent) { /// The priority used with GCM/FCM to describe how /// urgent the notification is. A higher priority /// means the notification will be delivered faster. - /// Default = 10. - if (receivedEvent.priority) { + if (typeof(receivedEvent.priority) != "undefined") { this.priority = receivedEvent.priority; } /// (Android Only) diff --git a/www/OneSignal.js b/www/OneSignal.js index 8f3966e6..bad02b17 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -134,7 +134,7 @@ OneSignal.prototype.getTags = function(tagsReceivedCallBack) { }; OneSignal.prototype.sendTag = function(key, value) { - var jsonKeyValue = {}; + const jsonKeyValue = {}; jsonKeyValue[key] = value; cordova.exec(function(){}, function(){}, "OneSignalPush", "sendTags", [jsonKeyValue]); }; diff --git a/www/Subscription.js b/www/Subscription.js index 1212d8b5..52b1cf95 100644 --- a/www/Subscription.js +++ b/www/Subscription.js @@ -5,7 +5,7 @@ function OSDeviceState(json) { this.hasNotificationPermission = json.areNotificationsEnabled; } - if (json.notificationPermissionStatus != null) { + if (json.notificationPermissionStatus !== null) { this.notificationPermissionStatus = json.notificationPermissionStatus; } @@ -19,21 +19,21 @@ function OSDeviceState(json) { } function OSPermissionState(json) { - if (json.status != null) { + if (json.status !== null) { this.status = json.status; } else { this.status = json.areNotificationsEnabled ? OneSignal.prototype.OSNotificationPermission.Authorized : OneSignal.prototype.OSNotificationPermission.Denied; } // iOS only - if (json.provisional != null) { + if (json.provisional !== null) { this.provisional = json.provisional; } else { this.provisional = false; } // iOS only - if (json.hasPrompted != null) { + if (json.hasPrompted !== null) { this.hasPrompted = json.hasPrompted; } else { this.hasPrompted = false; From 5957466b69a98ea3a53185a434dec6d212f47c41 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 26 Apr 2021 12:06:23 -0300 Subject: [PATCH 27/55] Add callback to registerForProvisionalAuthorization --- www/OneSignal.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/www/OneSignal.js b/www/OneSignal.js index bad02b17..a258208c 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -153,8 +153,8 @@ OneSignal.prototype.deleteTags = function(keys) { // Only applies to iOS (does nothing on Android as it always silently registers) // Call only if you passed false to autoRegister -OneSignal.prototype.registerForProvisionalAuthorization = function() { - cordova.exec(function(){}, function(){}, "OneSignalPush", "registerForProvisionalAuthorization", []); +OneSignal.prototype.registerForProvisionalAuthorization = function(provisionalAuthCallback) { + cordova.exec(provisionalAuthCallback, function(){}, "OneSignalPush", "registerForProvisionalAuthorization", []); }; // Only applies to iOS (does nothing on Android as it always silently registers without user permission) From 0ae43c8397d5c98175ad58935891ca37550ec2af Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 26 Apr 2021 12:06:48 -0300 Subject: [PATCH 28/55] Edit plugin.xml file * Return *-Info.plist config * Remove SystemConfiguration.framework --- plugin.xml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/plugin.xml b/plugin.xml index f9c17a92..985e7b26 100644 --- a/plugin.xml +++ b/plugin.xml @@ -57,7 +57,11 @@ - + + + remote-notification + + development From 84207cb1d65b20fe57022fd869ba335c74d20c42 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 26 Apr 2021 12:08:42 -0300 Subject: [PATCH 29/55] Remove Windows phone platform --- package.json | 2 -- plugin.xml | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/package.json b/package.json index 7d6d3576..221b9d1e 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,6 @@ "platforms": [ "android", "ios", - "windows", "amazon-fireos" ], "engines": [ @@ -53,7 +52,6 @@ "platforms": [ "android", "ios", - "windows", "amazon-fireos" ] }, diff --git a/plugin.xml b/plugin.xml index 985e7b26..acbd0ef2 100644 --- a/plugin.xml +++ b/plugin.xml @@ -9,7 +9,7 @@ OneSignal is a high volume Push Notification service for mobile apps. In addition to basic notification delivery, OneSignal also provides tools to localize, target, schedule, A/B test, and automate notifications that you send. - push,notification,push notification,push notifications,apns,gcm,adm,retention,messaging,ios,android,windows phone + push,notification,push notification,push notifications,apns,gcm,adm,retention,messaging,ios,android MIT From 009d84684bff8266dba736a64a948aa4843a307e Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 26 Apr 2021 12:29:37 -0300 Subject: [PATCH 30/55] Share js-module between platforms --- plugin.xml | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/plugin.xml b/plugin.xml index acbd0ef2..8a8bafb8 100644 --- a/plugin.xml +++ b/plugin.xml @@ -25,6 +25,11 @@ + + + + + @@ -35,10 +40,6 @@ - - - - @@ -74,10 +75,6 @@ - - - - From e558581d08e493e66e394cf3228e76c91dffd0a8 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 26 Apr 2021 12:31:01 -0300 Subject: [PATCH 31/55] Remove space after subscriptionObserverCallbackId --- src/ios/OneSignalPush.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 5108bd79..36c050ac 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -235,7 +235,7 @@ - (void)addPermissionObserver:(CDVInvokedUrlCommand*)command { } - (void)addSubscriptionObserver:(CDVInvokedUrlCommand*)command { - bool first = subscriptionObserverCallbackId == nil; + bool first = subscriptionObserverCallbackId == nil; subscriptionObserverCallbackId = command.callbackId; if (first) [OneSignal addSubscriptionObserver:self]; From de60d99512b75c82057603579ef16bcc8ddc035e Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 30 Apr 2021 15:32:07 -0300 Subject: [PATCH 32/55] Codereview comments --- src/android/com/onesignal/cordova/OneSignalController.java | 2 +- .../com/onesignal/cordova/OneSignalOutcomeController.java | 2 +- www/NotificationOpened.js | 2 +- www/NotificationReceived.js | 4 ++-- www/Subscription.js | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/android/com/onesignal/cordova/OneSignalController.java b/src/android/com/onesignal/cordova/OneSignalController.java index d5fcebdd..e35d1ccc 100644 --- a/src/android/com/onesignal/cordova/OneSignalController.java +++ b/src/android/com/onesignal/cordova/OneSignalController.java @@ -255,4 +255,4 @@ public static boolean isLocationShared(CallbackContext callbackContext) { CallbackHelper.callbackSuccessBoolean(callbackContext, false); return true; } -} \ No newline at end of file +} diff --git a/src/android/com/onesignal/cordova/OneSignalOutcomeController.java b/src/android/com/onesignal/cordova/OneSignalOutcomeController.java index d25caa0e..9d9f2129 100644 --- a/src/android/com/onesignal/cordova/OneSignalOutcomeController.java +++ b/src/android/com/onesignal/cordova/OneSignalOutcomeController.java @@ -79,4 +79,4 @@ public static boolean sendOutcomeWithValue(CallbackContext callbackContext, JSON return false; } } -} \ No newline at end of file +} diff --git a/www/NotificationOpened.js b/www/NotificationOpened.js index 10c8cacc..c341042f 100644 --- a/www/NotificationOpened.js +++ b/www/NotificationOpened.js @@ -25,4 +25,4 @@ function OSNotificationAction (json) { this.type = json.type; } -module.exports = OSNotificationOpenedResult; \ No newline at end of file +module.exports = OSNotificationOpenedResult; diff --git a/www/NotificationReceived.js b/www/NotificationReceived.js index 10c7a25b..d224e336 100644 --- a/www/NotificationReceived.js +++ b/www/NotificationReceived.js @@ -50,7 +50,7 @@ function OSNotification (receivedEvent) { /// The priority used with GCM/FCM to describe how /// urgent the notification is. A higher priority /// means the notification will be delivered faster. - if (typeof(receivedEvent.priority) != "undefined") { + if (typeof(receivedEvent.priority) !== "undefined") { this.priority = receivedEvent.priority; } /// (Android Only) @@ -257,4 +257,4 @@ var OSNotificationReceivedEvent = { module.exports = { OSNotification: OSNotification, OSNotificationReceivedEvent: OSNotificationReceivedEvent -}; \ No newline at end of file +}; diff --git a/www/Subscription.js b/www/Subscription.js index 52b1cf95..6308efe0 100644 --- a/www/Subscription.js +++ b/www/Subscription.js @@ -99,4 +99,4 @@ module.exports = { OSPermissionStateChanges: OSPermissionStateChanges, OSSubscriptionStateChanges: OSSubscriptionStateChanges, OSEmailSubscriptionStateChanges: OSEmailSubscriptionStateChanges, -}; \ No newline at end of file +}; From dfaedfc072522beae351cee67a5b28c2d9a1efd2 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 30 Apr 2021 17:26:12 -0300 Subject: [PATCH 33/55] Release commit beta cut 1 --- package.json | 2 +- plugin.xml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 221b9d1e..5547b1f0 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "2.11.4", + "version": "3.0.0-beta1", "name": "onesignal-cordova-plugin", "cordova_name": "OneSignal Push Notifications", diff --git a/plugin.xml b/plugin.xml index 8a8bafb8..a5e4e920 100644 --- a/plugin.xml +++ b/plugin.xml @@ -2,7 +2,7 @@ + version="3.0.0-beta1"> OneSignal Push Notifications Josh Kasten, Bradley Hesse, Rodrigo Gomez-Palacio @@ -31,7 +31,7 @@ - + @@ -71,7 +71,7 @@ production - + From f8d8333cb3b131f65c96857f0bf4a23fe57decb3 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 24 May 2021 19:31:17 -0300 Subject: [PATCH 34/55] Add SMS integration * Add setSMSNumber and logoutSMSNumber methods --- plugin.xml | 1 + .../com/onesignal/cordova/OneSignalPush.java | 16 ++++ .../cordova/OneSignalSMSController.java | 88 +++++++++++++++++++ src/ios/OneSignalPush.h | 5 ++ src/ios/OneSignalPush.m | 38 ++++++++ www/OneSignal.js | 33 +++++++ 6 files changed, 181 insertions(+) create mode 100644 src/android/com/onesignal/cordova/OneSignalSMSController.java diff --git a/plugin.xml b/plugin.xml index a5e4e920..27f3a036 100644 --- a/plugin.xml +++ b/plugin.xml @@ -43,6 +43,7 @@ + diff --git a/src/android/com/onesignal/cordova/OneSignalPush.java b/src/android/com/onesignal/cordova/OneSignalPush.java index 9731ccaa..6896c048 100644 --- a/src/android/com/onesignal/cordova/OneSignalPush.java +++ b/src/android/com/onesignal/cordova/OneSignalPush.java @@ -76,6 +76,10 @@ public class OneSignalPush extends CordovaPlugin { private static final String SET_UNAUTHENTICATED_EMAIL = "setUnauthenticatedEmail"; private static final String LOGOUT_EMAIL = "logoutEmail"; + private static final String SET_SMS_NUMBER = "setSMSNumber"; + private static final String SET_UNAUTHENTICATED_SMS_NUMBER = "setUnauthenticatedSMSNumber"; + private static final String LOGOUT_SMS_NUMBER = "logoutSMSNumber"; + private static final String SET_LOG_LEVEL = "setLogLevel"; private static final String SET_LOCATION_SHARED = "setLocationShared"; @@ -235,6 +239,18 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalEmailController.logoutEmail(callbackContext); break; + case SET_SMS_NUMBER: + result = OneSignalSMSController.setSMSNumber(callbackContext, data); + break; + + case SET_UNAUTHENTICATED_SMS_NUMBER: + result = OneSignalSMSController.setUnauthenticatedEmail(callbackContext, data); + break; + + case LOGOUT_SMS_NUMBER: + result = OneSignalSMSController.logoutSMSNumber(callbackContext); + break; + case PROMPT_LOCATION: OneSignalController.promptLocation(); break; diff --git a/src/android/com/onesignal/cordova/OneSignalSMSController.java b/src/android/com/onesignal/cordova/OneSignalSMSController.java new file mode 100644 index 00000000..67830a80 --- /dev/null +++ b/src/android/com/onesignal/cordova/OneSignalSMSController.java @@ -0,0 +1,88 @@ +package com.onesignal.cordova; + +import com.onesignal.OneSignal; +import com.onesignal.OneSignal.EmailUpdateError; +import com.onesignal.OneSignal.EmailUpdateHandler; + +import org.apache.cordova.CallbackContext; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class OneSignalSMSController { + public static boolean setSMSNumber(CallbackContext callbackContext, JSONArray data) { + final CallbackContext jsSetSMSNumberContext = callbackContext; + try { + OneSignal.setSMSNumber(data.getString(0), data.getString(1), new OneSignal.OSSMSUpdateHandler() { + @Override + public void onSuccess(JSONObject result) { + CallbackHelper.callbackSuccess(jsSetSMSNumberContext, result); + } + + @Override + public void onFailure(OneSignal.OSSMSUpdateError error) { + try { + JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); + CallbackHelper.callbackError(jsSetSMSNumberContext, errorObject); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); + + return true; + } catch (Throwable t) { + t.printStackTrace(); + return false; + } + } + + public static boolean setUnauthenticatedEmail(CallbackContext callbackContext, JSONArray data) { + final CallbackContext jsSetSMSNumberContext = callbackContext; + try { + OneSignal.setSMSNumber(data.getString(0), null, new OneSignal.OSSMSUpdateHandler() { + @Override + public void onSuccess(JSONObject result) { + CallbackHelper.callbackSuccess(jsSetSMSNumberContext, result); + } + + @Override + public void onFailure(OneSignal.OSSMSUpdateError error) { + try { + JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); + CallbackHelper.callbackError(jsSetSMSNumberContext, errorObject); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); + + return true; + } catch (Throwable t) { + t.printStackTrace(); + return false; + } + } + + public static boolean logoutSMSNumber(CallbackContext callbackContext) { + final CallbackContext jsSetSMSNumberContext = callbackContext; + OneSignal.logoutSMSNumber(new OneSignal.OSSMSUpdateHandler() { + @Override + public void onSuccess(JSONObject result) { + CallbackHelper.callbackSuccess(jsSetSMSNumberContext, result); + } + + @Override + public void onFailure(OneSignal.OSSMSUpdateError error) { + try { + JSONObject errorObject = new JSONObject("{'error' : '" + error.getMessage() + "'}"); + CallbackHelper.callbackError(jsSetSMSNumberContext, errorObject); + } catch (JSONException e) { + e.printStackTrace(); + } + } + }); + + return true; + } +} diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index 7a8f7fc6..e852e032 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -75,6 +75,11 @@ - (void)setEmail:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setUnauthenticatedEmail:(CDVInvokedUrlCommand* _Nonnull)command; - (void)logoutEmail:(CDVInvokedUrlCommand* _Nonnull)command; + +// SMS +- (void)setSMSNumber:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setUnauthenticatedSMSNumber:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)logoutSMSNumber:(CDVInvokedUrlCommand* _Nonnull)command; // In App Message - (void)setLaunchURLsInApp:(CDVInvokedUrlCommand* _Nonnull)command; diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 36c050ac..ecda34a5 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -42,8 +42,11 @@ NSString* registerForProvisionalAuthorizationCallbackId; NSString* setEmailCallbackId; NSString* setUnauthenticatedEmailCallbackId; +NSString* setSMSNumberCallbackId; +NSString* setUnauthenticatedSMSNumberCallbackId; NSString* setExternalIdCallbackId; NSString* logoutEmailCallbackId; +NSString* logoutSMSNumberCallbackId; NSString* emailSubscriptionCallbackId; OSNotificationOpenedResult* actionNotification; @@ -371,6 +374,41 @@ - (void)logoutEmail:(CDVInvokedUrlCommand *)command { }]; } +- (void)setSMSNumber:(CDVInvokedUrlCommand *)command { + setSMSNumberCallbackId = command.callbackId; + + NSString *smsNumber = command.arguments[0]; + NSString *smsAuthHashToken = command.arguments[1]; + + [OneSignal setSMSNumber:smsNumber withSMSAuthHashToken:smsAuthHashToken withSuccess:^(NSDictionary *results){ + successCallback(setSMSNumberCallbackId, results); + } withFailure:^(NSError *error) { + failureCallback(setSMSNumberCallbackId, error.userInfo); + }]; +} + +- (void)setUnauthenticatedSMSNumber:(CDVInvokedUrlCommand *)command { + setUnauthenticatedSMSNumberCallbackId = command.callbackId; + + NSString *smsNumber = command.arguments[0]; + + [OneSignal setSMSNumber:smsNumber withSuccess:^(NSDictionary *results){ + successCallback(setUnauthenticatedSMSNumberCallbackId, results); + } withFailure:^(NSError *error) { + failureCallback(setUnauthenticatedSMSNumberCallbackId, error.userInfo); + }]; +} + +- (void)logoutSMSNumber:(CDVInvokedUrlCommand *)command { + logoutSMSNumberCallbackId = command.callbackId; + + [OneSignal logoutSMSNumberWithSuccess:^(NSDictionary *results){ + successCallback(logoutSMSNumberCallbackId, results); + } withFailure:^(NSError *error) { + failureCallback(logoutSMSNumberCallbackId, error.userInfo); + }]; +} + - (void)setExternalUserId:(CDVInvokedUrlCommand *)command { setExternalIdCallbackId = command.callbackId; diff --git a/www/OneSignal.js b/www/OneSignal.js index a258208c..5551c492 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -253,6 +253,39 @@ OneSignal.prototype.logoutEmail = function(onSuccess, onFailure) { cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutEmail", []); }; +/** + * SMS + */ +OneSignal.prototype.setSMSNumber = function(smsNumber, smsAuthToken, onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + if (onFailure == null) + onFailure = function() {}; + + if (typeof smsAuthToken == 'function') { + onFailure = onSuccess; + onSuccess = smsAuthToken; + + cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedSMSNumber", [smsNumber]); + } else if (smsAuthToken == undefined) { + cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedSMSNumber", [smsNumber]); + } else { + cordova.exec(onSuccess, onFailure, "OneSignalPush", "setSMSNumber", [smsNumber, smsAuthToken]); + } +}; + +OneSignal.prototype.logoutSMSNumber = function(onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + + if (onFailure == null) + onFailure = function() {}; + + cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutSMSNumber", []); +}; + /** Possible function usages setExternalUserId(externalId: string?): void setExternalUserId(externalId: string?, callback: function): void From 137a6c7b568a96f1516448cc6dc1a6dc97a02fd1 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 24 May 2021 20:18:53 -0300 Subject: [PATCH 35/55] Add SMS SubscriptionObserver * Add setSMSSubscriptionObserver method --- .../cordova/OneSignalObserverController.java | 20 ++++++++++++++++++- .../com/onesignal/cordova/OneSignalPush.java | 5 +++++ src/ios/OneSignalPush.h | 1 + src/ios/OneSignalPush.m | 12 +++++++++++ www/OneSignal.js | 10 ++++++++++ www/Subscription.js | 19 ++++++++++++++++++ 6 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/android/com/onesignal/cordova/OneSignalObserverController.java b/src/android/com/onesignal/cordova/OneSignalObserverController.java index 2562100d..5c7ff02d 100644 --- a/src/android/com/onesignal/cordova/OneSignalObserverController.java +++ b/src/android/com/onesignal/cordova/OneSignalObserverController.java @@ -10,19 +10,23 @@ import com.onesignal.OSPermissionObserver; import com.onesignal.OSEmailSubscriptionObserver; +import com.onesignal.OSSMSSubscriptionObserver; import com.onesignal.OSSubscriptionObserver; import com.onesignal.OSPermissionStateChanges; import com.onesignal.OSSubscriptionStateChanges; import com.onesignal.OSEmailSubscriptionStateChanges; +import com.onesignal.OSSMSSubscriptionStateChanges; public class OneSignalObserverController { private static CallbackContext jsPermissionObserverCallBack; private static CallbackContext jsSubscriptionObserverCallBack; private static CallbackContext jsEmailSubscriptionObserverCallBack; + private static CallbackContext jsSMSSubscriptionObserverCallBack; private static OSPermissionObserver permissionObserver; private static OSSubscriptionObserver subscriptionObserver; private static OSEmailSubscriptionObserver emailSubscriptionObserver; + private static OSSMSSubscriptionObserver smsSubscriptionObserver; // This is to prevent an issue where if two Javascript calls are made to OneSignal expecting a callback then only one would fire. private static void callbackSuccess(CallbackContext callbackContext, JSONObject jsonObject) { @@ -75,4 +79,18 @@ public void onOSEmailSubscriptionChanged(OSEmailSubscriptionStateChanges stateCh } return true; } -} \ No newline at end of file + + public static boolean addSMSSubscriptionObserver(CallbackContext callbackContext) { + jsSMSSubscriptionObserverCallBack = callbackContext; + if (smsSubscriptionObserver == null) { + smsSubscriptionObserver = new OSSMSSubscriptionObserver() { + @Override + public void onSMSSubscriptionChanged(OSSMSSubscriptionStateChanges stateChanges) { + callbackSuccess(jsSMSSubscriptionObserverCallBack, stateChanges.toJSONObject()); + } + }; + OneSignal.addSMSSubscriptionObserver(smsSubscriptionObserver); + } + return true; + } +} diff --git a/src/android/com/onesignal/cordova/OneSignalPush.java b/src/android/com/onesignal/cordova/OneSignalPush.java index 6896c048..c66d7172 100644 --- a/src/android/com/onesignal/cordova/OneSignalPush.java +++ b/src/android/com/onesignal/cordova/OneSignalPush.java @@ -56,6 +56,7 @@ public class OneSignalPush extends CordovaPlugin { private static final String ADD_PERMISSION_OBSERVER = "addPermissionObserver"; private static final String ADD_SUBSCRIPTION_OBSERVER = "addSubscriptionObserver"; private static final String ADD_EMAIL_SUBSCRIPTION_OBSERVER = "addEmailSubscriptionObserver"; + private static final String ADD_SMS_SUBSCRIPTION_OBSERVER = "addSMSSubscriptionObserver"; private static final String GET_TAGS = "getTags"; private static final String DELETE_TAGS = "deleteTags"; @@ -179,6 +180,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalObserverController.addEmailSubscriptionObserver(callbackContext); break; + case ADD_SMS_SUBSCRIPTION_OBSERVER: + result = OneSignalObserverController.addSMSSubscriptionObserver(callbackContext); + break; + case GET_TAGS: result = OneSignalController.getTags(callbackContext); break; diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index e852e032..e4b1aaf3 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -44,6 +44,7 @@ - (void)addPermissionObserver:(CDVInvokedUrlCommand* _Nonnull)command; - (void)addSubscriptionObserver:(CDVInvokedUrlCommand* _Nonnull)command; - (void)addEmailSubscriptionObserver:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)addSMSSubscriptionObserver:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setLogLevel:(CDVInvokedUrlCommand* _Nonnull)command; diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index ecda34a5..676bb4be 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -48,6 +48,7 @@ NSString* logoutEmailCallbackId; NSString* logoutSMSNumberCallbackId; NSString* emailSubscriptionCallbackId; +NSString* smsSubscriptionCallbackId; OSNotificationOpenedResult* actionNotification; OSNotification *notification; @@ -167,6 +168,10 @@ - (void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges *)stateCha successCallback(emailSubscriptionCallbackId, [stateChanges toDictionary]); } +- (void)onOSSMSSubscriptionChanged:(OSSMSSubscriptionStateChanges *)stateChanges { + successCallback(smsSubscriptionCallbackId, [stateChanges toDictionary]); +} + - (void)setProvidesNotificationSettingsView:(CDVInvokedUrlCommand *)command { BOOL providesView = command.arguments[0]; [OneSignal setProvidesNotificationSettingsView:providesView]; @@ -251,6 +256,13 @@ - (void)addEmailSubscriptionObserver:(CDVInvokedUrlCommand *)command { [OneSignal addEmailSubscriptionObserver:self]; } +- (void)addSMSSubscriptionObserver:(CDVInvokedUrlCommand *)command { + bool first = smsSubscriptionCallbackId == nil; + smsSubscriptionCallbackId = command.callbackId; + if (first) + [OneSignal addSMSSubscriptionObserver:self]; +} + - (void)setLogLevel:(CDVInvokedUrlCommand*)command { NSDictionary* options = command.arguments[0]; [OneSignal setLogLevel:[options[@"logLevel"] intValue] visualLevel:[options[@"visualLevel"] intValue]]; diff --git a/www/OneSignal.js b/www/OneSignal.js index 5551c492..c9c2aab0 100644 --- a/www/OneSignal.js +++ b/www/OneSignal.js @@ -32,6 +32,7 @@ var OSDeviceState = require('./Subscription').OSDeviceState; var OSPermissionStateChanges = require('./Subscription').OSPermissionStateChanges; var OSSubscriptionStateChanges = require('./Subscription').OSSubscriptionStateChanges; var OSEmailSubscriptionStateChanges = require('./Subscription').OSEmailSubscriptionStateChanges; +var OSSMSSubscriptionStateChanges = require('./Subscription').OSSMSSubscriptionStateChanges; var OneSignal = function() { var _appID = ""; @@ -49,6 +50,7 @@ OneSignal.prototype.OSNotificationPermission = { OneSignal._permissionObserverList = []; OneSignal._subscriptionObserverList = []; OneSignal._emailSubscriptionObserverList = []; +OneSignal._smsSubscriptionObserverList = []; // You must call init before any other OneSignal function. @@ -121,6 +123,14 @@ OneSignal.prototype.addEmailSubscriptionObserver = function(callback) { cordova.exec(emailSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addEmailSubscriptionObserver", []); }; +OneSignal.prototype.addSMSSubscriptionObserver = function(callback) { + OneSignal._smsSubscriptionObserverList.push(callback); + var smsSubscriptionCallbackProcessor = function(state) { + OneSignal._processFunctionList(OneSignal._smsSubscriptionObserverList, new OSSMSSubscriptionStateChanges(state)); + }; + cordova.exec(smsSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addSMSSubscriptionObserver", []); +}; + OneSignal.prototype.addPermissionObserver = function(callback) { OneSignal._permissionObserverList.push(callback); var permissionCallBackProcessor = function(state) { diff --git a/www/Subscription.js b/www/Subscription.js index 6308efe0..cda3b938 100644 --- a/www/Subscription.js +++ b/www/Subscription.js @@ -94,9 +94,28 @@ function OSEmailSubscriptionStateChanges(json) { } } +/// Represents the user's OneSignal SMS subscription state, +function OSSMSSubscriptionState(json) { + this.subscribed = json.isSubscribed; + this.smsNumber = json.smsNumber; + this.smsUserId = json.smsUserId; +} + +/// An instance of this class describes a change in the user's +/// SMS subscription state with OneSignal +function OSSMSSubscriptionStateChanges(json) { + if (json.from) { + this.from = new OSSMSSubscriptionState(json.from); + } + if (json.to) { + this.to = new OSSMSSubscriptionState(json.to); + } +} + module.exports = { OSDeviceState: OSDeviceState, OSPermissionStateChanges: OSPermissionStateChanges, OSSubscriptionStateChanges: OSSubscriptionStateChanges, OSEmailSubscriptionStateChanges: OSEmailSubscriptionStateChanges, + OSSMSSubscriptionStateChanges: OSSMSSubscriptionStateChanges, }; From b09593fca1de83469a562ef0407cdedd8b587796 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 24 May 2021 20:22:14 -0300 Subject: [PATCH 36/55] Add DeviceState SMS data * Include SMS data under OSDeviceState --- www/Subscription.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/www/Subscription.js b/www/Subscription.js index cda3b938..fd7d61f2 100644 --- a/www/Subscription.js +++ b/www/Subscription.js @@ -12,10 +12,13 @@ function OSDeviceState(json) { this.pushDisabled = json.isPushDisabled; this.subscribed = json.isSubscribed; this.emailSubscribed = json.isEmailSubscribed; + this.smsSubscribed = json.isSMSSubscribed; this.userId = json.userId; this.pushToken = json.pushToken; this.emailUserId = json.emailUserId; this.emailAddress = json.emailAddress; + this.smsUserId = json.smsUserId; + this.smsNumber = json.smsNumber; } function OSPermissionState(json) { From ef01f6985493812699274a6a95fd0a1626990c55 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 31 May 2021 20:41:42 -0300 Subject: [PATCH 37/55] Add TypeScript support * Create typing files * Rename OneSignal.js to OneSignalPlugin.js * Export typed OneSignal --- package.json | 5 + plugin.xml | 2 +- typing/Extras.d.ts | 9 + typing/Notification.d.ts | 53 +++++ typing/OneSignalPlugin.d.ts | 338 ++++++++++++++++++++++++++ typing/Outcomes.d.ts | 7 + typing/Subscription.d.ts | 45 ++++ typing/index.d.ts | 8 + www/OneSignal.js | 461 ------------------------------------ www/OneSignalPlugin.js | 454 +++++++++++++++++++++++++++++++++++ 10 files changed, 920 insertions(+), 462 deletions(-) create mode 100644 typing/Extras.d.ts create mode 100644 typing/Notification.d.ts create mode 100644 typing/OneSignalPlugin.d.ts create mode 100644 typing/Outcomes.d.ts create mode 100644 typing/Subscription.d.ts create mode 100644 typing/index.d.ts delete mode 100644 www/OneSignal.js create mode 100644 www/OneSignalPlugin.js diff --git a/package.json b/package.json index 5547b1f0..77074278 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,8 @@ "cordova_name": "OneSignal Push Notifications", "description": "OneSignal is a high volume Push Notification service for mobile apps. In addition to basic notification delivery, OneSignal also provides tools to localize, target, schedule, and automate notifications that you send.", "license": "MIT", + "main": "www/OneSignal.js", + "typings": "typings/index.d.ts", "keywords": [ "push", "notification", @@ -25,6 +27,9 @@ "ios", "amazon-fireos" ], + "dependencies": { + "typescript": "^4.1.3" + }, "engines": [ { "name": "cordova-android", diff --git a/plugin.xml b/plugin.xml index 27f3a036..1fef0601 100644 --- a/plugin.xml +++ b/plugin.xml @@ -13,7 +13,7 @@ MIT - + diff --git a/typing/Extras.d.ts b/typing/Extras.d.ts new file mode 100644 index 00000000..bf689082 --- /dev/null +++ b/typing/Extras.d.ts @@ -0,0 +1,9 @@ + /* O P T I O N T Y P E V A L U E S */ +// 0 = None, 1 = Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose +export type LogLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6; + +/* O B S E R V E R C H A N G E E V E N T S */ +export interface ChangeEvent { + from : T; + to : T; +} diff --git a/typing/Notification.d.ts b/typing/Notification.d.ts new file mode 100644 index 00000000..62f49928 --- /dev/null +++ b/typing/Notification.d.ts @@ -0,0 +1,53 @@ +// 0 = NotificationClicked, 1 = ButtonClicked +export type OpenedEventActionType = 0 | 1; + + /* N O T I F I C A T I O N S */ +export interface OSNotification { + body : string; + sound ?: string; + title ?: string; + launchURL ?: string; + rawPayload : object | string; // platform bridges return different types + actionButtons ?: object[]; + additionalData : object; + notificationId : string; + // android only + groupKey ?: string; + groupMessage ?: string; + ledColor ?: string; + priority ?: number; + smallIcon ?: string; + largeIcon ?: string; + bigPicture ?: string; + collapseId ?: string; + fromProjectNumber ?: string; + smallIconAccentColor ?: string; + lockScreenVisibility ?: string; + androidNotificationId ?: number; + // ios only + badge ?: string; + badgeIncrement ?: string; + category ?: string; + threadId ?: string; + subtitle ?: string; + templateId ?: string; + templateName ?: string; + attachments ?: object; + mutableContent ?: boolean; + contentAvailable ?: string; +} + +/* N O T I F I C A T I O N & I A M E V E N T S */ +export interface NotificationReceivedEvent { + complete : (notification?: OSNotification) => void; + getNotification : () => OSNotification; +}; + +export interface OpenedEvent { + action : OpenedEventAction; + notification : OSNotification; +} + +export interface OpenedEventAction { + type : OpenedEventActionType +} \ No newline at end of file diff --git a/typing/OneSignalPlugin.d.ts b/typing/OneSignalPlugin.d.ts new file mode 100644 index 00000000..d91c5d91 --- /dev/null +++ b/typing/OneSignalPlugin.d.ts @@ -0,0 +1,338 @@ +import { NotificationReceivedEvent, OpenedEvent, OpenedEventAction } from './Notification'; +import { OutcomeEvent } from './Outcomes'; +import { PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange, DeviceState } from './Subscription'; +import { LogLevel, ChangeEvent } from './Extras'; + +/* O N E S I G N A L I N T E R F A C E */ +export interface OneSignalPlugin{ + /** + * Completes OneSignal initialization by setting the OneSignal Application ID. + * @param {string} appId + * @returns void + */ + setAppId(appId: string): void; + + /** + * Add a callback that fires when the native push permission changes. + * @param {(event:ChangeEvent)=>void} observer + * @returns void + */ + addPermissionObserver(observer: (event: ChangeEvent) => void): void; + + /** + * Add a callback that fires when the OneSignal subscription state changes. + * @param {(event:ChangeEvent)=>void} observer + * @returns void + */ + addSubscriptionObserver(observer: (event: ChangeEvent) => void): void; + + /** + * Add a callback that fires when the OneSignal email subscription changes. + * @param {(event:ChangeEvent)=>void} observer + * @returns void + */ + addEmailSubscriptionObserver(observer: (event: ChangeEvent) => void): void; + + /** + * Add a callback that fires when the OneSignal sms subscription changes. + * @param {(event:ChangeEvent)=>void} observer + * @returns void + */ + addSMSSubscriptionObserver(observer: (event: ChangeEvent) => void): void; + + /** + * Set the callback to run just before displaying a notification while the app is in focus. + * @param {(event:NotificationReceivedEvent)=>void} handler + * @returns void + */ + setNotificationWillShowInForegroundHandler(handler: (event: NotificationReceivedEvent) => void): void; + + /** + * Set the callback to run on notification open. + * @param {(openedEvent:OpenedEvent)=>void} handler + * @returns void + */ + setNotificationOpenedHandler(handler: (openedEvent: OpenedEvent) => void): void; + + /** + * Prompts the iOS user for push notifications. + * @param {(response:boolean)=>void} handler + * @returns void + */ + promptForPushNotificationsWithUserResponse(handler?: (response: boolean) => void): void; + + /** + * Only applies to iOS (does nothing on Android as it always silently registers) + * Request for Direct-To-History push notification authorization + * + * For more information: https://documentation.onesignal.com/docs/ios-customizations#provisional-push-notifications + * + * @param {(response:boolean)=>void} handler + * @returns void + */ + registerForProvisionalAuthorization(handler?: (response: boolean) => void): void; + + /** + * Disable the push notification subscription to OneSignal. + * @param {boolean} disable + * @returns void + */ + disablePush(disable: boolean): void; + + /** + * Android Only. If notifications are disabled for your application, unsubscribe the user from OneSignal. + * @param {boolean} unsubscribe + * @returns void + */ + unsubscribeWhenNotificationsAreDisabled(unsubscribe: boolean): void; + + /** + * True if the application has location share activated, false otherwise + * @returns Promise + */ + isLocationShared(): Promise; + + /** + * Disable or enable location collection (defaults to enabled if your app has location permission). + * @param {boolean} shared + * @returns void + */ + setLocationShared(shared: boolean): void; + + /** + * Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. + * @returns void + */ + promptLocation(): void; + + /** + * This method returns a "snapshot" of the device state for when it was called. + * @returns Promise + */ + getDeviceState(): Promise; + + /** + * Tag a user based on an app event of your choosing so they can be targeted later via segments. + * @param {string} key + * @param {string} value + * @returns void + */ + sendTag(key: string, value: string): void; + + /** + * Tag a user wiht multiple tags based on an app event of your choosing so they can be targeted later via segments. + * @param {object} tags + * @returns void + */ + sendTags(tags: object): void; + + /** + * Retrieve a list of tags that have been set on the user from the OneSignal server. + * @param {(tags:object)=>void} handler + * @returns void + */ + getTags(handler: (tags: object) => void): void; + + /** + * Deletes a single tag that was previously set on a user. + * @param {string} key + * @returns void + */ + deleteTag(key: string): void; + + /** + * Deletes multiple tags that were previously set on a user. + * @param {string[]} keys + */ + deleteTags(keys: string[]); + + /** + * Allows you to set the user's email address with the OneSignal SDK. + * @param {string} email + * @param {string} authCode + * @param {Function} handler + * @returns void + */ + setEmail(email: string, authCode?: string, handler?: Function): void; + + /** + * If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device. + * @param {Function} handler + */ + logoutEmail(handler?: Function); + + /** + * Allows you to set the user's SMS number with the OneSignal SDK. + * @param {string} smsNumber + * @param {string} authCode + * @param {Function} handler + * @returns void + */ + setSMSNumber(smsNumber: string, authCode?: string, handler?: Function): void; + + /** + * If your app implements logout functionality, you can call logoutSMSNumber to dissociate the SMS number from the device. + * @param {Function} handler + */ + logoutSMSNumber(handler?: Function); + + /** + * Send a notification + * @param {string} notificationObjectString - JSON string payload (see REST API reference) + * @param {(success:object)=>void} onSuccess + * @param {(failure:object)=>void} onFailure + * @returns void + */ + postNotification(notificationObjectString: string, onSuccess?: (success: object) => void, onFailure?: (failure: object) => void): void; + + /** + * Android Only. iOS provides a standard way to clear notifications by clearing badge count. + * @returns void + */ + clearOneSignalNotifications(): void; + + /** + * Removes a single OneSignal notification based on its Android notification integer id. + * @param {number} id - notification id to cancel + * @returns void + */ + removeNotification(id: number): void; + + /** + * Removes all OneSignal notifications based on its Android notification group Id. + * @param {string} id - notification group id to cancel + * @returns void + */ + removeGroupedNotifications(id: string): void; + + /** + * Allows you to use your own system's user ID's to send push notifications to your users. + * @param {string} externalId + * @param {(results:object)=>void} handler + * @returns void + */ + setExternalUserId(externalId: string, handlerOrAuth?: ((results: object) => void) | string, handler?: (results: object) => void): void; + + /** + * Removes whatever was set as the current user's external user ID. + * @param {(results:object)=>void} handler + * @returns void + */ + removeExternalUserId(handler?: (results: object) => void): void; + + /** + * Sets an In-App Message click event handler. + * @param {(action:InAppMessageAction)=>void} handler + * @returns void + */ + setInAppMessageClickHandler(handler: (action: InAppMessageAction) => void): void; + + /** + * Add an In-App Message Trigger. + * @param {string} key + * @param {string} value + * @returns void + */ + addTrigger(key: string, value: string): void; + + /** + * Adds Multiple In-App Message Triggers. + * @param {object} triggers + * @returns void + */ + addTriggers(triggers: object): void; + + /** + * Removes a list of triggers based on a collection of keys. + * @param {string[]} keys + * @returns void + */ + removeTriggersForKeys(keys: string[]): void; + + /** + * Removes a list of triggers based on a key. + * @param {string} key + * @returns void + */ + removeTriggerForKey(key: string): void; + + /** + * Gets a trigger value for a provided trigger key. + * @param {string} key + * @returns void + */ + getTriggerValueForKey(key: string): Promise; + + /** + * Pause & unpause In-App Messages + * @param {boolean} pause + * @returns void + */ + pauseInAppMessages(pause: boolean): void; + + /** + * Increases the "Count" of this Outcome by 1 and will be counted each time sent. + * @param {string} name + * @param {(event:OutcomeEvent)=>void} handler + * @returns void + */ + sendOutcome(name: string, handler?: (event: OutcomeEvent) => void): void; + + /** + * Increases "Count" by 1 only once. This can only be attributed to a single notification. + * @param {string} name + * @param {(event:OutcomeEvent)=>void} handler + * @returns void + */ + sendUniqueOutcome(name: string, handler?: (event: OutcomeEvent) => void): void; + + /** + * Increases the "Count" of this Outcome by 1 and the "Sum" by the value. Will be counted each time sent. + * If the method is called outside of an attribution window, it will be unattributed until a new session occurs. + * @param {string} name + * @param {string|number} value + * @param {(event:OutcomeEvent)=>void} handler + * @returns void + */ + sendOutcomeWithValue(name: string, value: string|number, handler?: (event: OutcomeEvent) => void): void; + + /** + * Enable logging to help debug if you run into an issue setting up OneSignal. + * @param {LogLevel} nsLogLevel - Sets the logging level to print to the Android LogCat log or Xcode log. + * @param {LogLevel} visualLogLevel - Sets the logging level to show as alert dialogs. + * @returns void + */ + setLogLevel(nsLogLevel: LogLevel, visualLogLevel: LogLevel): void; + + /** + * Clears all handlers and observers. + * @returns void + */ + clearHandlers(): void; + + /** + * Did the user provide privacy consent for GDPR purposes. + * @returns Promise + */ + userProvidedPrivacyConsent(): Promise; + + /** + * True if the application requires user privacy consent, false otherwise + * @returns Promise + */ + requiresUserPrivacyConsent(): Promise; + + /** + * For GDPR users, your application should call this method before setting the App ID. + * @param {boolean} required + * @returns void + */ + setRequiresUserPrivacyConsent(required: boolean): void; + + /** + * If your application is set to require the user's privacy consent, you can provide this consent using this method. + * @param {boolean} granted + * @returns void + */ + provideUserConsent(granted: boolean): void; +} \ No newline at end of file diff --git a/typing/Outcomes.d.ts b/typing/Outcomes.d.ts new file mode 100644 index 00000000..b52215c3 --- /dev/null +++ b/typing/Outcomes.d.ts @@ -0,0 +1,7 @@ +export interface OutcomeEvent { + session : string; + id : string; + timestamp : number; + weight : number; + notification_ids: string[]; +} diff --git a/typing/Subscription.d.ts b/typing/Subscription.d.ts new file mode 100644 index 00000000..c670dda9 --- /dev/null +++ b/typing/Subscription.d.ts @@ -0,0 +1,45 @@ +// 0 = NotDetermined, 1 = Denied, 2 = Authorized, 3 = Provisional, 4 = Ephemeral +export type IosPermissionStatus = 0 | 1 | 2 | 3 | 4; + +/* D E V I C E */ +export interface DeviceState { + userId : string; + pushToken : string; + emailUserId : string; + emailAddress : string; + smsUserId : string; + smsNumber : string; + isSubscribed : boolean; + isPushDisabled : boolean; + isEmailSubscribed : boolean; + isSMSSubscribed : boolean; + hasNotificationPermission ?: boolean; // ios only + notificationPermissionStatus ?: IosPermissionStatus; // ios only + // areNotificationsEnabled (android) not included since it is converted to hasNotificationPermission in bridge +} + +export interface PermissionChange { + status ?: IosPermissionStatus; // ios + hasPrompted ?: boolean; // ios + provisional ?: boolean; // ios + areNotificationsEnabled ?: boolean; // android +}; + +export interface SubscriptionChange { + userId ?: string; + pushToken ?: string; + isSubscribed : boolean; + isPushDisabled : boolean; +}; + +export interface EmailSubscriptionChange { + emailAddress ?: string; + emailUserId ?: string; + isEmailSubscribed : boolean; +}; + +export interface SMSSubscriptionChange { + smsNumber ?: string; + smsUserId ?: string; + isSMSSubscribed : boolean; +}; diff --git a/typing/index.d.ts b/typing/index.d.ts new file mode 100644 index 00000000..89114ead --- /dev/null +++ b/typing/index.d.ts @@ -0,0 +1,8 @@ +import { OSNotification, NotificationReceivedEvent, OpenedEvent, OpenedEventAction, OpenedEventActionType } from './Notification'; +import { OutcomeEvent } from './Outcomes'; +import { PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange, DeviceState, IosPermissionStatus } from './Subscription'; +import { LogLevel, ChangeEvent } from './Extras'; +import { OneSignalPlugin } from './OneSignalPlugin'; +export declare const OneSignal: OneSignalPlugin; +export { OneSignalPlugin }; +export default OneSignal; \ No newline at end of file diff --git a/www/OneSignal.js b/www/OneSignal.js deleted file mode 100644 index c9c2aab0..00000000 --- a/www/OneSignal.js +++ /dev/null @@ -1,461 +0,0 @@ -/** - * Modified MIT License - * - * Copyright 2019 OneSignal - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * 1. The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * 2. All copies of substantial portions of the Software may only be used in connection - * with services provided by OneSignal. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -var OSNotificationReceivedEvent = require('./NotificationReceived').OSNotificationReceivedEvent; -var OSNotificationOpenedResult = require('./NotificationOpened'); -var OSInAppMessageAction = require('./InAppMessage'); -var OSDeviceState = require('./Subscription').OSDeviceState; -var OSPermissionStateChanges = require('./Subscription').OSPermissionStateChanges; -var OSSubscriptionStateChanges = require('./Subscription').OSSubscriptionStateChanges; -var OSEmailSubscriptionStateChanges = require('./Subscription').OSEmailSubscriptionStateChanges; -var OSSMSSubscriptionStateChanges = require('./Subscription').OSSMSSubscriptionStateChanges; - -var OneSignal = function() { - var _appID = ""; - var _notificationWillShowInForegroundDelegate = function(notificationReceived) {}; - var _notificationOpenedDelegate = function(notificationOpened) {}; - var _inAppMessageClickDelegate = function (action) {}; -}; - -OneSignal.prototype.OSNotificationPermission = { - NotDetermined: 0, - Authorized: 1, - Denied: 2 -}; - -OneSignal._permissionObserverList = []; -OneSignal._subscriptionObserverList = []; -OneSignal._emailSubscriptionObserverList = []; -OneSignal._smsSubscriptionObserverList = []; - - -// You must call init before any other OneSignal function. -OneSignal.prototype.setAppId = function(appId) { - OneSignal._appID = appId; - - cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignal._appID]); -}; - -OneSignal.prototype.handleNotificationWillShowInForeground = function(handleNotificationWillShowInForegroundCallback) { - OneSignal._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; - - var foregroundParsingHandler = function(notificationReceived) { - console.log("foregroundParsingHandler " + JSON.stringify(notificationReceived)); - OneSignal._notificationWillShowInForegroundDelegate(OSNotificationReceivedEvent.create(notificationReceived)); - }; - - cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); -}; - -OneSignal.prototype.handleNotificationOpened = function(handleNotificationOpenedCallback) { - OneSignal._notificationOpenedDelegate = handleNotificationOpenedCallback; - - var notificationOpenedHandler = function(json) { - OneSignal._notificationOpenedDelegate(new OSNotificationOpenedResult(json)); - }; - - cordova.exec(notificationOpenedHandler, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); -}; - -OneSignal.prototype.handleInAppMessageClicked = function(handler) { - OneSignal._inAppMessageClickDelegate = handler; - - var inAppMessageClickHandler = function(json) { - OneSignal._inAppMessageClickDelegate(new OSInAppMessageAction(json)); - }; - - cordova.exec(inAppMessageClickHandler, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); -}; - -OneSignal._processFunctionList = function(array, param) { - for (var i = 0; i < array.length; i++) - array[i](param); -}; - -OneSignal.prototype.completeNotification = function(notification, shouldDisplay) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [notification.notificationId, shouldDisplay]); -}; - -OneSignal.prototype.getDeviceState = function(deviceStateReceivedCallBack) { - var deviceStateCallback = function(json) { - deviceStateReceivedCallBack(new OSDeviceState(json)); - }; - cordova.exec(deviceStateCallback, function(){}, "OneSignalPush", "getDeviceState", []); -}; - -OneSignal.prototype.addSubscriptionObserver = function(callback) { - OneSignal._subscriptionObserverList.push(callback); - var subscriptionCallBackProcessor = function(state) { - OneSignal._processFunctionList(OneSignal._subscriptionObserverList, new OSSubscriptionStateChanges(state)); - }; - cordova.exec(subscriptionCallBackProcessor, function(){}, "OneSignalPush", "addSubscriptionObserver", []); -}; - -OneSignal.prototype.addEmailSubscriptionObserver = function(callback) { - OneSignal._emailSubscriptionObserverList.push(callback); - var emailSubscriptionCallbackProcessor = function(state) { - OneSignal._processFunctionList(OneSignal._emailSubscriptionObserverList, new OSEmailSubscriptionStateChanges(state)); - }; - cordova.exec(emailSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addEmailSubscriptionObserver", []); -}; - -OneSignal.prototype.addSMSSubscriptionObserver = function(callback) { - OneSignal._smsSubscriptionObserverList.push(callback); - var smsSubscriptionCallbackProcessor = function(state) { - OneSignal._processFunctionList(OneSignal._smsSubscriptionObserverList, new OSSMSSubscriptionStateChanges(state)); - }; - cordova.exec(smsSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addSMSSubscriptionObserver", []); -}; - -OneSignal.prototype.addPermissionObserver = function(callback) { - OneSignal._permissionObserverList.push(callback); - var permissionCallBackProcessor = function(state) { - OneSignal._processFunctionList(OneSignal._permissionObserverList, new OSPermissionStateChanges(state)); - }; - cordova.exec(permissionCallBackProcessor, function(){}, "OneSignalPush", "addPermissionObserver", []); -}; - -OneSignal.prototype.getTags = function(tagsReceivedCallBack) { - cordova.exec(tagsReceivedCallBack, function(){}, "OneSignalPush", "getTags", []); -}; - -OneSignal.prototype.sendTag = function(key, value) { - const jsonKeyValue = {}; - jsonKeyValue[key] = value; - cordova.exec(function(){}, function(){}, "OneSignalPush", "sendTags", [jsonKeyValue]); -}; - -OneSignal.prototype.sendTags = function(tags) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "sendTags", [tags]); -}; - -OneSignal.prototype.deleteTag = function(key) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "deleteTags", [key]); -}; - -OneSignal.prototype.deleteTags = function(keys) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "deleteTags", keys); -}; - -// Only applies to iOS (does nothing on Android as it always silently registers) -// Call only if you passed false to autoRegister -OneSignal.prototype.registerForProvisionalAuthorization = function(provisionalAuthCallback) { - cordova.exec(provisionalAuthCallback, function(){}, "OneSignalPush", "registerForProvisionalAuthorization", []); -}; - -// Only applies to iOS (does nothing on Android as it always silently registers without user permission) -OneSignal.prototype.promptForPushNotificationsWithUserResponse = function(callback) { - var internalCallback = function(data) { - callback(data.accepted === "true"); - }; - cordova.exec(internalCallback, function(){}, "OneSignalPush", "promptForPushNotificationsWithUserResponse", []); -}; - -// Only applies to Android. -OneSignal.prototype.clearOneSignalNotifications = function() { - cordova.exec(function(){}, function(){}, "OneSignalPush", "clearOneSignalNotifications", []); -}; - -// Only applies to Android. -// If notifications are disabled for your app, unsubscribe the user from OneSignal. -OneSignal.prototype.unsubscribeWhenNotificationsAreDisabled = function(unsubscribe) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "unsubscribeWhenNotificationsAreDisabled", [unsubscribe]); -}; - -// Only applies to Android. Cancels a single OneSignal notification based on its Android notification integer ID -OneSignal.prototype.removeNotification = function(id) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "removeNotification", [id]); -}; - -// Only applies to Android. Cancels a single OneSignal notification based on its Android notification group ID -OneSignal.prototype.removeGroupedNotifications = function(groupId) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "removeGroupedNotifications", [groupId]); -}; - -OneSignal.prototype.disablePush = function(disable) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "disablePush", [disable]); -}; - -OneSignal.prototype.postNotification = function(jsonData, onSuccess, onFailure) { - if (onSuccess == null) - onSuccess = function() {}; - - if (onFailure == null) - onFailure = function() {}; - - cordova.exec(onSuccess, onFailure, "OneSignalPush", "postNotification", [jsonData]); -}; - -OneSignal.prototype.setLogLevel = function(logLevel) { - cordova.exec(function(){}, function(){}, "OneSignalPush", "setLogLevel", [logLevel]); -}; - -OneSignal.prototype.userProvidedPrivacyConsent = function(callback) { - cordova.exec(callback, function(){}, "OneSignalPush", "userProvidedPrivacyConsent", []); -}; - -OneSignal.prototype.requiresUserPrivacyConsent = function(callback) { - cordova.exec(callback, function(){}, "OneSignalPush", "requiresUserPrivacyConsent", []); -}; - -OneSignal.prototype.setRequiresUserPrivacyConsent = function(required) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "setRequiresUserPrivacyConsent", [required]); -}; - -OneSignal.prototype.provideUserConsent = function(granted) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "provideUserConsent", [granted]); -}; - -/** - * Email - */ -OneSignal.prototype.setEmail = function(email, emailAuthToken, onSuccess, onFailure) { - if (onSuccess == null) - onSuccess = function() {}; - - if (onFailure == null) - onFailure = function() {}; - - if (typeof emailAuthToken == 'function') { - onFailure = onSuccess; - onSuccess = emailAuthToken; - - cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedEmail", [email]); - } else if (emailAuthToken == undefined) { - cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedEmail", [email]); - } else { - cordova.exec(onSuccess, onFailure, "OneSignalPush", "setEmail", [email, emailAuthToken]); - } -}; - -OneSignal.prototype.logoutEmail = function(onSuccess, onFailure) { - if (onSuccess == null) - onSuccess = function() {}; - - - if (onFailure == null) - onFailure = function() {}; - - cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutEmail", []); -}; - -/** - * SMS - */ -OneSignal.prototype.setSMSNumber = function(smsNumber, smsAuthToken, onSuccess, onFailure) { - if (onSuccess == null) - onSuccess = function() {}; - - if (onFailure == null) - onFailure = function() {}; - - if (typeof smsAuthToken == 'function') { - onFailure = onSuccess; - onSuccess = smsAuthToken; - - cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedSMSNumber", [smsNumber]); - } else if (smsAuthToken == undefined) { - cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedSMSNumber", [smsNumber]); - } else { - cordova.exec(onSuccess, onFailure, "OneSignalPush", "setSMSNumber", [smsNumber, smsAuthToken]); - } -}; - -OneSignal.prototype.logoutSMSNumber = function(onSuccess, onFailure) { - if (onSuccess == null) - onSuccess = function() {}; - - - if (onFailure == null) - onFailure = function() {}; - - cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutSMSNumber", []); -}; - -/** Possible function usages - setExternalUserId(externalId: string?): void - setExternalUserId(externalId: string?, callback: function): void - setExternalUserId(externalId: string?, externalIdAuthHash: string?, callback: function): void -*/ -OneSignal.prototype.setExternalUserId = function(externalId, varArg1, varArg2) { - if (externalId == undefined) - externalId = null; - - var externalIdAuthHash = null; - var callback = function() {}; - - if (typeof varArg1 === "function") { - // Method was called like setExternalUserId(externalId: string?, callback: function) - callback = varArg1; - } - else if (typeof varArg1 === "string") { - // Method was called like setExternalUserId(externalId: string?, externalIdAuthHash: string?, callback: function) - externalIdAuthHash = varArg1; - callback = varArg2; - } - else if (typeof varArg1 === "undefined") { - // Method was called like setExternalUserId(externalId: string?) - // Defaults defined above for externalIdAuthHash and callback - } - else { - // This does not catch all possible wrongly typed params but prevents a good number of them - console.error("Invalid param types passed to OneSignal.setExternalUserId(). Definition is setExternalUserId(externalId: string?, externalIdAuthHash: string?, callback?: function): void") - return; - } - - var passToNativeParams = [externalId]; - if (externalIdAuthHash !== null) - passToNativeParams.push(externalIdAuthHash) - cordova.exec(callback, function() {}, "OneSignalPush", "setExternalUserId", passToNativeParams); -}; - -OneSignal.prototype.removeExternalUserId = function(externalUserIdCallback) { - if (externalUserIdCallback == undefined) - externalUserIdCallback = function() {}; - - cordova.exec(externalUserIdCallback, function() {}, "OneSignalPush", "removeExternalUserId", []); -}; - -/** - * In app messaging - */ -OneSignal.prototype.addTriggers = function(triggers) { - Object.keys(triggers).forEach(function(key){ - // forces values to be string types - if (typeof triggers[key] !== "string") { - triggers[key] = JSON.stringify(triggers[key]); - } - }); - cordova.exec(function() {}, function() {}, "OneSignalPush", "addTriggers", [triggers]); -}; - -OneSignal.prototype.addTrigger = function(key, value) { - var obj = {}; - obj[key] = value; - OneSignal.prototype.addTriggers(obj); -}; - -OneSignal.prototype.removeTriggerForKey = function(key) { - OneSignal.prototype.removeTriggersForKeys([key]); -}; - -OneSignal.prototype.removeTriggersForKeys = function(keys) { - if (!Array.isArray(keys)){ - console.error("OneSignal: removeTriggersForKeys: argument must be of type Array") - } - cordova.exec(function() {}, function() {}, "OneSignalPush", "removeTriggersForKeys", [keys]); -}; - -OneSignal.prototype.getTriggerValueForKey = function(key, callback) { - var getTriggerValueForKeyCallback = function(obj) { - callback(obj.value); - }; - cordova.exec(getTriggerValueForKeyCallback, function() {}, "OneSignalPush", "getTriggerValueForKey", [key]); -}; - -OneSignal.prototype.pauseInAppMessages = function(pause) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "pauseInAppMessages", [pause]); -}; - -/** - * Outcomes - */ -OneSignal.prototype.sendOutcome = function(name, callback) { - if (typeof callback === "undefined") - callback = function() {}; - - if (typeof callback !== "function") { - console.error("OneSignal: sendOutcome: must provide a valid callback"); - return; - } - - const sendOutcomeCallback = function(result) { - callback(result); - }; - - cordova.exec(sendOutcomeCallback, function() {}, "OneSignalPush", "sendOutcome", [name]); -}; - -OneSignal.prototype.sendUniqueOutcome = function(name, callback) { - if (typeof callback === "undefined") - callback = function() {}; - - if (typeof callback !== "function") { - console.error("OneSignal: sendUniqueOutcome: must provide a valid callback"); - return; - } - - const sendUniqueOutcomeCallback = function(result) { - callback(result); - }; - - cordova.exec(sendUniqueOutcomeCallback, function() {}, "OneSignalPush", "sendUniqueOutcome", [name]); -}; - -OneSignal.prototype.sendOutcomeWithValue = function(name, value, callback) { - if (typeof callback === "undefined") - callback = function() {}; - - if (typeof callback !== "function") { - console.error("OneSignal: sendOutcomeWithValue: must provide a valid callback"); - return; - } - - const sendOutcomeWithValueCallback = function(result) { - callback(result); - }; - - cordova.exec(sendOutcomeWithValueCallback, function() {}, "OneSignalPush", "sendOutcomeWithValue", [name, Number(value)]); -}; - -/** - * Location - */ - -OneSignal.prototype.promptLocation = function() { - cordova.exec(function(){}, function(){}, "OneSignalPush", "promptLocation", []); -}; - -OneSignal.prototype.setLocationShared = function(shared) { - cordova.exec(function() {}, function() {}, "OneSignalPush", "setLocationShared", [shared]); -}; - -OneSignal.prototype.isLocationShared = function(callback) { - cordova.exec(callback, function() {}, "OneSignalPush", "isLocationShared", []); -}; - -//------------------------------------------------------------------- - -if(!window.plugins) - window.plugins = {}; - -if (!window.plugins.OneSignal) - window.plugins.OneSignal = new OneSignal(); - -if (typeof module != 'undefined' && module.exports) { - module.exports = OneSignal; -} diff --git a/www/OneSignalPlugin.js b/www/OneSignalPlugin.js new file mode 100644 index 00000000..47a165f2 --- /dev/null +++ b/www/OneSignalPlugin.js @@ -0,0 +1,454 @@ +/** + * Modified MIT License + * + * Copyright 2019 OneSignal + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * 1. The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * 2. All copies of substantial portions of the Software may only be used in connection + * with services provided by OneSignal. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +var OSNotificationReceivedEvent = require('./NotificationReceived').OSNotificationReceivedEvent; +var OSNotificationOpenedResult = require('./NotificationOpened'); +var OSInAppMessageAction = require('./InAppMessage'); +var OSDeviceState = require('./Subscription').OSDeviceState; +var OSPermissionStateChanges = require('./Subscription').OSPermissionStateChanges; +var OSSubscriptionStateChanges = require('./Subscription').OSSubscriptionStateChanges; +var OSEmailSubscriptionStateChanges = require('./Subscription').OSEmailSubscriptionStateChanges; +var OSSMSSubscriptionStateChanges = require('./Subscription').OSSMSSubscriptionStateChanges; + +var OneSignalPlugin = function() { + var _appID = ""; + var _notificationWillShowInForegroundDelegate = function(notificationReceived) {}; + var _notificationOpenedDelegate = function(notificationOpened) {}; + var _inAppMessageClickDelegate = function (action) {}; +}; + +OneSignalPlugin.prototype.OSNotificationPermission = { + NotDetermined: 0, + Authorized: 1, + Denied: 2 +}; + +OneSignalPlugin._permissionObserverList = []; +OneSignalPlugin._subscriptionObserverList = []; +OneSignalPlugin._emailSubscriptionObserverList = []; +OneSignalPlugin._smsSubscriptionObserverList = []; + +// You must call init before any other OneSignal function. +OneSignalPlugin.prototype.setAppId = function(appId) { + OneSignalPlugin._appID = appId; + + window.cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignalPlugin._appID]); +}; + +OneSignalPlugin.prototype.handleNotificationWillShowInForeground = function(handleNotificationWillShowInForegroundCallback) { + OneSignalPlugin._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; + + var foregroundParsingHandler = function(notificationReceived) { + console.log("foregroundParsingHandler " + JSON.stringify(notificationReceived)); + OneSignalPlugin._notificationWillShowInForegroundDelegate(OSNotificationReceivedEvent.create(notificationReceived)); + }; + + window.cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); +}; + +OneSignalPlugin.prototype.handleNotificationOpened = function(handleNotificationOpenedCallback) { + OneSignalPlugin._notificationOpenedDelegate = handleNotificationOpenedCallback; + + var notificationOpenedHandler = function(json) { + OneSignalPlugin._notificationOpenedDelegate(new OSNotificationOpenedResult(json)); + }; + + window.cordova.exec(notificationOpenedHandler, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); +}; + +OneSignalPlugin.prototype.handleInAppMessageClicked = function(handler) { + OneSignalPlugin._inAppMessageClickDelegate = handler; + + var inAppMessageClickHandler = function(json) { + OneSignalPlugin._inAppMessageClickDelegate(new OSInAppMessageAction(json)); + }; + + window.cordova.exec(inAppMessageClickHandler, function() {}, "OneSignalPush", "setInAppMessageClickHandler", []); +}; + +OneSignalPlugin._processFunctionList = function(array, param) { + for (var i = 0; i < array.length; i++) + array[i](param); +}; + +OneSignalPlugin.prototype.completeNotification = function(notification, shouldDisplay) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [notification.notificationId, shouldDisplay]); +}; + +OneSignalPlugin.prototype.getDeviceState = function(deviceStateReceivedCallBack) { + var deviceStateCallback = function(json) { + deviceStateReceivedCallBack(new OSDeviceState(json)); + }; + window.cordova.exec(deviceStateCallback, function(){}, "OneSignalPush", "getDeviceState", []); +}; + +OneSignalPlugin.prototype.addSubscriptionObserver = function(callback) { + OneSignalPlugin._subscriptionObserverList.push(callback); + var subscriptionCallBackProcessor = function(state) { + OneSignalPlugin._processFunctionList(OneSignalPlugin._subscriptionObserverList, new OSSubscriptionStateChanges(state)); + }; + window.cordova.exec(subscriptionCallBackProcessor, function(){}, "OneSignalPush", "addSubscriptionObserver", []); +}; + +OneSignalPlugin.prototype.addEmailSubscriptionObserver = function(callback) { + OneSignalPlugin._emailSubscriptionObserverList.push(callback); + var emailSubscriptionCallbackProcessor = function(state) { + OneSignalPlugin._processFunctionList(OneSignalPlugin._emailSubscriptionObserverList, new OSEmailSubscriptionStateChanges(state)); + }; + window.cordova.exec(emailSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addEmailSubscriptionObserver", []); +}; + +OneSignalPlugin.prototype.addSMSSubscriptionObserver = function(callback) { + OneSignalPlugin._smsSubscriptionObserverList.push(callback); + var smsSubscriptionCallbackProcessor = function(state) { + OneSignalPlugin._processFunctionList(OneSignalPlugin._smsSubscriptionObserverList, new OSSMSSubscriptionStateChanges(state)); + }; + window.cordova.exec(smsSubscriptionCallbackProcessor, function(){}, "OneSignalPush", "addSMSSubscriptionObserver", []); +}; + +OneSignalPlugin.prototype.addPermissionObserver = function(callback) { + OneSignalPlugin._permissionObserverList.push(callback); + var permissionCallBackProcessor = function(state) { + OneSignalPlugin._processFunctionList(OneSignalPlugin._permissionObserverList, new OSPermissionStateChanges(state)); + }; + window.cordova.exec(permissionCallBackProcessor, function(){}, "OneSignalPush", "addPermissionObserver", []); +}; + +OneSignalPlugin.prototype.getTags = function(tagsReceivedCallBack) { + window.cordova.exec(tagsReceivedCallBack, function(){}, "OneSignalPush", "getTags", []); +}; + +OneSignalPlugin.prototype.sendTag = function(key, value) { + const jsonKeyValue = {}; + jsonKeyValue[key] = value; + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "sendTags", [jsonKeyValue]); +}; + +OneSignalPlugin.prototype.sendTags = function(tags) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "sendTags", [tags]); +}; + +OneSignalPlugin.prototype.deleteTag = function(key) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "deleteTags", [key]); +}; + +OneSignalPlugin.prototype.deleteTags = function(keys) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "deleteTags", keys); +}; + +// Only applies to iOS (does nothing on Android as it always silently registers) +// Call only if you passed false to autoRegister +OneSignalPlugin.prototype.registerForProvisionalAuthorization = function(provisionalAuthCallback) { + window.cordova.exec(provisionalAuthCallback, function(){}, "OneSignalPush", "registerForProvisionalAuthorization", []); +}; + +// Only applies to iOS (does nothing on Android as it always silently registers without user permission) +OneSignalPlugin.prototype.promptForPushNotificationsWithUserResponse = function(callback) { + var internalCallback = function(data) { + callback(data.accepted === "true"); + }; + window.cordova.exec(internalCallback, function(){}, "OneSignalPush", "promptForPushNotificationsWithUserResponse", []); +}; + +// Only applies to Android. +OneSignalPlugin.prototype.clearOneSignalNotifications = function() { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "clearOneSignalNotifications", []); +}; + +// Only applies to Android. +// If notifications are disabled for your app, unsubscribe the user from OneSignalPlugin. +OneSignalPlugin.prototype.unsubscribeWhenNotificationsAreDisabled = function(unsubscribe) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "unsubscribeWhenNotificationsAreDisabled", [unsubscribe]); +}; + +// Only applies to Android. Cancels a single OneSignal notification based on its Android notification integer ID +OneSignalPlugin.prototype.removeNotification = function(id) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "removeNotification", [id]); +}; + +// Only applies to Android. Cancels a single OneSignal notification based on its Android notification group ID +OneSignalPlugin.prototype.removeGroupedNotifications = function(groupId) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "removeGroupedNotifications", [groupId]); +}; + +OneSignalPlugin.prototype.disablePush = function(disable) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "disablePush", [disable]); +}; + +OneSignalPlugin.prototype.postNotification = function(jsonData, onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + if (onFailure == null) + onFailure = function() {}; + + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "postNotification", [jsonData]); +}; + +OneSignalPlugin.prototype.setLogLevel = function(logLevel) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "setLogLevel", [logLevel]); +}; + +OneSignalPlugin.prototype.userProvidedPrivacyConsent = function(callback) { + window.cordova.exec(callback, function(){}, "OneSignalPush", "userProvidedPrivacyConsent", []); +}; + +OneSignalPlugin.prototype.requiresUserPrivacyConsent = function(callback) { + window.cordova.exec(callback, function(){}, "OneSignalPush", "requiresUserPrivacyConsent", []); +}; + +OneSignalPlugin.prototype.setRequiresUserPrivacyConsent = function(required) { + window.cordova.exec(function() {}, function() {}, "OneSignalPush", "setRequiresUserPrivacyConsent", [required]); +}; + +OneSignalPlugin.prototype.provideUserConsent = function(granted) { + window.cordova.exec(function() {}, function() {}, "OneSignalPush", "provideUserConsent", [granted]); +}; + +/** + * Email + */ +OneSignalPlugin.prototype.setEmail = function(email, emailAuthToken, onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + if (onFailure == null) + onFailure = function() {}; + + if (typeof emailAuthToken == 'function') { + onFailure = onSuccess; + onSuccess = emailAuthToken; + + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedEmail", [email]); + } else if (emailAuthToken == undefined) { + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedEmail", [email]); + } else { + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "setEmail", [email, emailAuthToken]); + } +}; + +OneSignalPlugin.prototype.logoutEmail = function(onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + + if (onFailure == null) + onFailure = function() {}; + + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutEmail", []); +}; + +/** + * SMS + */ +OneSignalPlugin.prototype.setSMSNumber = function(smsNumber, smsAuthToken, onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + if (onFailure == null) + onFailure = function() {}; + + if (typeof smsAuthToken == 'function') { + onFailure = onSuccess; + onSuccess = smsAuthToken; + + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedSMSNumber", [smsNumber]); + } else if (smsAuthToken == undefined) { + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "setUnauthenticatedSMSNumber", [smsNumber]); + } else { + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "setSMSNumber", [smsNumber, smsAuthToken]); + } +}; + +OneSignalPlugin.prototype.logoutSMSNumber = function(onSuccess, onFailure) { + if (onSuccess == null) + onSuccess = function() {}; + + + if (onFailure == null) + onFailure = function() {}; + + window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "logoutSMSNumber", []); +}; + +/** Possible function usages + setExternalUserId(externalId: string?): void + setExternalUserId(externalId: string?, callback: function): void + setExternalUserId(externalId: string?, externalIdAuthHash: string?, callback: function): void +*/ +OneSignalPlugin.prototype.setExternalUserId = function(externalId, varArg1, varArg2) { + if (externalId == undefined) + externalId = null; + + var externalIdAuthHash = null; + var callback = function() {}; + + if (typeof varArg1 === "function") { + // Method was called like setExternalUserId(externalId: string?, callback: function) + callback = varArg1; + } + else if (typeof varArg1 === "string") { + // Method was called like setExternalUserId(externalId: string?, externalIdAuthHash: string?, callback: function) + externalIdAuthHash = varArg1; + callback = varArg2; + } + else if (typeof varArg1 === "undefined") { + // Method was called like setExternalUserId(externalId: string?) + // Defaults defined above for externalIdAuthHash and callback + } + else { + // This does not catch all possible wrongly typed params but prevents a good number of them + console.error("Invalid param types passed to OneSignalPlugin.setExternalUserId(). Definition is setExternalUserId(externalId: string?, externalIdAuthHash: string?, callback?: function): void") + return; + } + + var passToNativeParams = [externalId]; + if (externalIdAuthHash !== null) + passToNativeParams.push(externalIdAuthHash) + window.cordova.exec(callback, function() {}, "OneSignalPush", "setExternalUserId", passToNativeParams); +}; + +OneSignalPlugin.prototype.removeExternalUserId = function(externalUserIdCallback) { + if (externalUserIdCallback == undefined) + externalUserIdCallback = function() {}; + + window.cordova.exec(externalUserIdCallback, function() {}, "OneSignalPush", "removeExternalUserId", []); +}; + +/** + * In app messaging + */ +OneSignalPlugin.prototype.addTriggers = function(triggers) { + Object.keys(triggers).forEach(function(key){ + // forces values to be string types + if (typeof triggers[key] !== "string") { + triggers[key] = JSON.stringify(triggers[key]); + } + }); + window.cordova.exec(function() {}, function() {}, "OneSignalPush", "addTriggers", [triggers]); +}; + +OneSignalPlugin.prototype.addTrigger = function(key, value) { + var obj = {}; + obj[key] = value; + OneSignalPlugin.prototype.addTriggers(obj); +}; + +OneSignalPlugin.prototype.removeTriggerForKey = function(key) { + OneSignalPlugin.prototype.removeTriggersForKeys([key]); +}; + +OneSignalPlugin.prototype.removeTriggersForKeys = function(keys) { + if (!Array.isArray(keys)){ + console.error("OneSignal: removeTriggersForKeys: argument must be of type Array") + } + window.cordova.exec(function() {}, function() {}, "OneSignalPush", "removeTriggersForKeys", [keys]); +}; + +OneSignalPlugin.prototype.getTriggerValueForKey = function(key, callback) { + var getTriggerValueForKeyCallback = function(obj) { + callback(obj.value); + }; + window.cordova.exec(getTriggerValueForKeyCallback, function() {}, "OneSignalPush", "getTriggerValueForKey", [key]); +}; + +OneSignalPlugin.prototype.pauseInAppMessages = function(pause) { + window.cordova.exec(function() {}, function() {}, "OneSignalPush", "pauseInAppMessages", [pause]); +}; + +/** + * Outcomes + */ +OneSignalPlugin.prototype.sendOutcome = function(name, callback) { + if (typeof callback === "undefined") + callback = function() {}; + + if (typeof callback !== "function") { + console.error("OneSignal: sendOutcome: must provide a valid callback"); + return; + } + + const sendOutcomeCallback = function(result) { + callback(result); + }; + + window.cordova.exec(sendOutcomeCallback, function() {}, "OneSignalPush", "sendOutcome", [name]); +}; + +OneSignalPlugin.prototype.sendUniqueOutcome = function(name, callback) { + if (typeof callback === "undefined") + callback = function() {}; + + if (typeof callback !== "function") { + console.error("OneSignal: sendUniqueOutcome: must provide a valid callback"); + return; + } + + const sendUniqueOutcomeCallback = function(result) { + callback(result); + }; + + window.cordova.exec(sendUniqueOutcomeCallback, function() {}, "OneSignalPush", "sendUniqueOutcome", [name]); +}; + +OneSignalPlugin.prototype.sendOutcomeWithValue = function(name, value, callback) { + if (typeof callback === "undefined") + callback = function() {}; + + if (typeof callback !== "function") { + console.error("OneSignal: sendOutcomeWithValue: must provide a valid callback"); + return; + } + + const sendOutcomeWithValueCallback = function(result) { + callback(result); + }; + + window.cordova.exec(sendOutcomeWithValueCallback, function() {}, "OneSignalPush", "sendOutcomeWithValue", [name, Number(value)]); +}; + +/** + * Location + */ + +OneSignalPlugin.prototype.promptLocation = function() { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "promptLocation", []); +}; + +OneSignalPlugin.prototype.setLocationShared = function(shared) { + window.cordova.exec(function() {}, function() {}, "OneSignalPush", "setLocationShared", [shared]); +}; + +OneSignalPlugin.prototype.isLocationShared = function(callback) { + window.cordova.exec(callback, function() {}, "OneSignalPush", "isLocationShared", []); +}; + +//------------------------------------------------------------------- + +var OneSignal = new OneSignalPlugin(); + +module.exports = OneSignal; \ No newline at end of file From 9adbed23a394493a5c92b5e01b3fd38b405e4c2b Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 11 Jun 2021 15:30:08 -0300 Subject: [PATCH 38/55] Code review comments * Add new lines to end of file * Add InAppMessage ts * Rename typing directory to types --- package.json | 4 ++-- {typing => types}/Extras.d.ts | 0 types/InAppMessage.d.ts | 8 ++++++++ {typing => types}/Notification.d.ts | 4 ++-- {typing => types}/OneSignalPlugin.d.ts | 5 +++-- {typing => types}/Outcomes.d.ts | 0 {typing => types}/Subscription.d.ts | 10 +++++----- {typing => types}/index.d.ts | 3 ++- www/OneSignalPlugin.js | 2 +- 9 files changed, 23 insertions(+), 13 deletions(-) rename {typing => types}/Extras.d.ts (100%) create mode 100644 types/InAppMessage.d.ts rename {typing => types}/Notification.d.ts (99%) rename {typing => types}/OneSignalPlugin.d.ts (99%) rename {typing => types}/Outcomes.d.ts (100%) rename {typing => types}/Subscription.d.ts (95%) rename {typing => types}/index.d.ts (86%) diff --git a/package.json b/package.json index 77074278..a239c459 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,8 @@ "cordova_name": "OneSignal Push Notifications", "description": "OneSignal is a high volume Push Notification service for mobile apps. In addition to basic notification delivery, OneSignal also provides tools to localize, target, schedule, and automate notifications that you send.", "license": "MIT", - "main": "www/OneSignal.js", - "typings": "typings/index.d.ts", + "main": "www/OneSignalPlugin.js", + "typings": "types/index.d.ts", "keywords": [ "push", "notification", diff --git a/typing/Extras.d.ts b/types/Extras.d.ts similarity index 100% rename from typing/Extras.d.ts rename to types/Extras.d.ts diff --git a/types/InAppMessage.d.ts b/types/InAppMessage.d.ts new file mode 100644 index 00000000..9239858b --- /dev/null +++ b/types/InAppMessage.d.ts @@ -0,0 +1,8 @@ +export interface InAppMessageAction { + closes_message : boolean; + first_click : boolean; + click_name ?: string; + click_url ?: string; + outcomes ?: object[]; + tags ?: object; +} diff --git a/typing/Notification.d.ts b/types/Notification.d.ts similarity index 99% rename from typing/Notification.d.ts rename to types/Notification.d.ts index 62f49928..959e5164 100644 --- a/typing/Notification.d.ts +++ b/types/Notification.d.ts @@ -41,7 +41,7 @@ export interface OSNotification { export interface NotificationReceivedEvent { complete : (notification?: OSNotification) => void; getNotification : () => OSNotification; -}; +} export interface OpenedEvent { action : OpenedEventAction; @@ -50,4 +50,4 @@ export interface OpenedEvent { export interface OpenedEventAction { type : OpenedEventActionType -} \ No newline at end of file +} diff --git a/typing/OneSignalPlugin.d.ts b/types/OneSignalPlugin.d.ts similarity index 99% rename from typing/OneSignalPlugin.d.ts rename to types/OneSignalPlugin.d.ts index d91c5d91..f0d91609 100644 --- a/typing/OneSignalPlugin.d.ts +++ b/types/OneSignalPlugin.d.ts @@ -1,10 +1,11 @@ import { NotificationReceivedEvent, OpenedEvent, OpenedEventAction } from './Notification'; import { OutcomeEvent } from './Outcomes'; +import { InAppMessageAction } from './InAppMessage'; import { PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange, DeviceState } from './Subscription'; import { LogLevel, ChangeEvent } from './Extras'; /* O N E S I G N A L I N T E R F A C E */ -export interface OneSignalPlugin{ +export interface OneSignalPlugin { /** * Completes OneSignal initialization by setting the OneSignal Application ID. * @param {string} appId @@ -335,4 +336,4 @@ export interface OneSignalPlugin{ * @returns void */ provideUserConsent(granted: boolean): void; -} \ No newline at end of file +} diff --git a/typing/Outcomes.d.ts b/types/Outcomes.d.ts similarity index 100% rename from typing/Outcomes.d.ts rename to types/Outcomes.d.ts diff --git a/typing/Subscription.d.ts b/types/Subscription.d.ts similarity index 95% rename from typing/Subscription.d.ts rename to types/Subscription.d.ts index c670dda9..af7a6e1c 100644 --- a/typing/Subscription.d.ts +++ b/types/Subscription.d.ts @@ -13,7 +13,7 @@ export interface DeviceState { isPushDisabled : boolean; isEmailSubscribed : boolean; isSMSSubscribed : boolean; - hasNotificationPermission ?: boolean; // ios only + hasNotificationPermission ?: boolean; notificationPermissionStatus ?: IosPermissionStatus; // ios only // areNotificationsEnabled (android) not included since it is converted to hasNotificationPermission in bridge } @@ -23,23 +23,23 @@ export interface PermissionChange { hasPrompted ?: boolean; // ios provisional ?: boolean; // ios areNotificationsEnabled ?: boolean; // android -}; +} export interface SubscriptionChange { userId ?: string; pushToken ?: string; isSubscribed : boolean; isPushDisabled : boolean; -}; +} export interface EmailSubscriptionChange { emailAddress ?: string; emailUserId ?: string; isEmailSubscribed : boolean; -}; +} export interface SMSSubscriptionChange { smsNumber ?: string; smsUserId ?: string; isSMSSubscribed : boolean; -}; +} diff --git a/typing/index.d.ts b/types/index.d.ts similarity index 86% rename from typing/index.d.ts rename to types/index.d.ts index 89114ead..74356afd 100644 --- a/typing/index.d.ts +++ b/types/index.d.ts @@ -1,8 +1,9 @@ import { OSNotification, NotificationReceivedEvent, OpenedEvent, OpenedEventAction, OpenedEventActionType } from './Notification'; import { OutcomeEvent } from './Outcomes'; +import { InAppMessageAction } from './InAppMessage'; import { PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange, DeviceState, IosPermissionStatus } from './Subscription'; import { LogLevel, ChangeEvent } from './Extras'; import { OneSignalPlugin } from './OneSignalPlugin'; export declare const OneSignal: OneSignalPlugin; export { OneSignalPlugin }; -export default OneSignal; \ No newline at end of file +export default OneSignal; diff --git a/www/OneSignalPlugin.js b/www/OneSignalPlugin.js index 47a165f2..91ddca08 100644 --- a/www/OneSignalPlugin.js +++ b/www/OneSignalPlugin.js @@ -451,4 +451,4 @@ OneSignalPlugin.prototype.isLocationShared = function(callback) { var OneSignal = new OneSignalPlugin(); -module.exports = OneSignal; \ No newline at end of file +module.exports = OneSignal; From 15c3cd8a4ec3aa4660046d9c0e4e0ab34ddacfff Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Fri, 11 Jun 2021 15:35:40 -0300 Subject: [PATCH 39/55] Remove TS dependency --- package.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/package.json b/package.json index a239c459..6d12ae11 100644 --- a/package.json +++ b/package.json @@ -27,9 +27,6 @@ "ios", "amazon-fireos" ], - "dependencies": { - "typescript": "^4.1.3" - }, "engines": [ { "name": "cordova-android", From f1ff88e002754168c5ca782bd0c0c33192060d75 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 14 Jun 2021 15:17:11 -0300 Subject: [PATCH 40/55] Indent plugin file --- plugin.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin.xml b/plugin.xml index 1fef0601..32aae165 100644 --- a/plugin.xml +++ b/plugin.xml @@ -56,7 +56,7 @@ - + From 1805c895f33a19e926d798d8d34ef74a6942e465 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 14 Jun 2021 15:18:06 -0300 Subject: [PATCH 41/55] Remove unnecessary imports --- types/index.d.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/types/index.d.ts b/types/index.d.ts index 74356afd..72402e35 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,8 +1,3 @@ -import { OSNotification, NotificationReceivedEvent, OpenedEvent, OpenedEventAction, OpenedEventActionType } from './Notification'; -import { OutcomeEvent } from './Outcomes'; -import { InAppMessageAction } from './InAppMessage'; -import { PermissionChange, SubscriptionChange, EmailSubscriptionChange, SMSSubscriptionChange, DeviceState, IosPermissionStatus } from './Subscription'; -import { LogLevel, ChangeEvent } from './Extras'; import { OneSignalPlugin } from './OneSignalPlugin'; export declare const OneSignal: OneSignalPlugin; export { OneSignalPlugin }; From 85c237672ca2f119760001edfe689484366f8123 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 14 Jun 2021 15:59:43 -0300 Subject: [PATCH 42/55] Update OneSignal Plugin methods * Update methods to new names, rename from handleNotificationWillShowInForeground to setNotificationWillShowInForegroundHandler, rename from handleNotificationOpened to setNotificationOpenedHandler, rename from handleInAppMessageClicked to setInAppMessageClickHandler * Update setLogLevel params * Add OSSMSSubscriptionObserver to OneSignalPush.h * Add Notification getNotification method to OSNotificationReceivedEvent * Update export method to be compatible with TS and window.plugin import --- .../onesignal/cordova/OneSignalController.java | 5 +++-- src/ios/OneSignalPush.h | 2 +- src/ios/OneSignalPush.m | 3 +-- www/NotificationReceived.js | 4 ++++ www/OneSignalPlugin.js | 17 +++++++++++------ 5 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/android/com/onesignal/cordova/OneSignalController.java b/src/android/com/onesignal/cordova/OneSignalController.java index e35d1ccc..a3378472 100644 --- a/src/android/com/onesignal/cordova/OneSignalController.java +++ b/src/android/com/onesignal/cordova/OneSignalController.java @@ -40,8 +40,9 @@ public static boolean disablePush(JSONArray data) { */ public static void setLogLevel(JSONArray data) { try { - JSONObject jo = data.getJSONObject(0); - OneSignal.setLogLevel(jo.optInt("logLevel", 0), jo.optInt("visualLevel", 0)); + int logLevel = data.getInt(0); + int visualLevel = data.getInt(1); + OneSignal.setLogLevel(logLevel, visualLevel); } catch (Throwable t) { t.printStackTrace(); } diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index e4b1aaf3..40a839d7 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -31,7 +31,7 @@ #import -@interface OneSignalPush : CDVPlugin +@interface OneSignalPush : CDVPlugin - (void)setProvidesNotificationSettingsView:(CDVInvokedUrlCommand* _Nonnull)command; - (void)setNotificationWillShowInForegroundHandler:(CDVInvokedUrlCommand* _Nonnull)command; diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index 676bb4be..e5a1dc64 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -264,8 +264,7 @@ - (void)addSMSSubscriptionObserver:(CDVInvokedUrlCommand *)command { } - (void)setLogLevel:(CDVInvokedUrlCommand*)command { - NSDictionary* options = command.arguments[0]; - [OneSignal setLogLevel:[options[@"logLevel"] intValue] visualLevel:[options[@"visualLevel"] intValue]]; + [OneSignal setLogLevel:[command.arguments[0] intValue] visualLevel:[command.arguments[1] intValue]]; } - (void)getTags:(CDVInvokedUrlCommand*)command { diff --git a/www/NotificationReceived.js b/www/NotificationReceived.js index d224e336..84c459d3 100644 --- a/www/NotificationReceived.js +++ b/www/NotificationReceived.js @@ -229,6 +229,7 @@ class OSAndroidBackgroundImageLayout { } var OSNotificationReceivedEvent = { + notification: null, create : function (receivedEvent) { if (receivedEvent.notification) { // Android case @@ -251,6 +252,9 @@ var OSNotificationReceivedEvent = { // future: Android side: make the notification modifiable // iOS & Android: the notification id is associated with the native-side complete handler / completion block cordova.exec(function(){}, function(){}, "OneSignalPush", "completeNotification", [this.notification.notificationId, true]); + }, + getNotification: function() { + return this.notification; } }; diff --git a/www/OneSignalPlugin.js b/www/OneSignalPlugin.js index 91ddca08..103d0562 100644 --- a/www/OneSignalPlugin.js +++ b/www/OneSignalPlugin.js @@ -59,7 +59,7 @@ OneSignalPlugin.prototype.setAppId = function(appId) { window.cordova.exec(function() {}, function(){}, "OneSignalPush", "init", [OneSignalPlugin._appID]); }; -OneSignalPlugin.prototype.handleNotificationWillShowInForeground = function(handleNotificationWillShowInForegroundCallback) { +OneSignalPlugin.prototype.setNotificationWillShowInForegroundHandler = function(handleNotificationWillShowInForegroundCallback) { OneSignalPlugin._notificationWillShowInForegroundDelegate = handleNotificationWillShowInForegroundCallback; var foregroundParsingHandler = function(notificationReceived) { @@ -70,7 +70,7 @@ OneSignalPlugin.prototype.handleNotificationWillShowInForeground = function(hand window.cordova.exec(foregroundParsingHandler, function(){}, "OneSignalPush", "setNotificationWillShowInForegroundHandler", []); }; -OneSignalPlugin.prototype.handleNotificationOpened = function(handleNotificationOpenedCallback) { +OneSignalPlugin.prototype.setNotificationOpenedHandler = function(handleNotificationOpenedCallback) { OneSignalPlugin._notificationOpenedDelegate = handleNotificationOpenedCallback; var notificationOpenedHandler = function(json) { @@ -80,7 +80,7 @@ OneSignalPlugin.prototype.handleNotificationOpened = function(handleNotification window.cordova.exec(notificationOpenedHandler, function(){}, "OneSignalPush", "setNotificationOpenedHandler", []); }; -OneSignalPlugin.prototype.handleInAppMessageClicked = function(handler) { +OneSignalPlugin.prototype.setInAppMessageClickHandler = function(handler) { OneSignalPlugin._inAppMessageClickDelegate = handler; var inAppMessageClickHandler = function(json) { @@ -209,8 +209,8 @@ OneSignalPlugin.prototype.postNotification = function(jsonData, onSuccess, onFai window.cordova.exec(onSuccess, onFailure, "OneSignalPush", "postNotification", [jsonData]); }; -OneSignalPlugin.prototype.setLogLevel = function(logLevel) { - window.cordova.exec(function(){}, function(){}, "OneSignalPush", "setLogLevel", [logLevel]); +OneSignalPlugin.prototype.setLogLevel = function(nsLogLevel, visualLogLevel) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "setLogLevel", [nsLogLevel, visualLogLevel]); }; OneSignalPlugin.prototype.userProvidedPrivacyConsent = function(callback) { @@ -450,5 +450,10 @@ OneSignalPlugin.prototype.isLocationShared = function(callback) { //------------------------------------------------------------------- var OneSignal = new OneSignalPlugin(); - module.exports = OneSignal; + +if(!window.plugins) + window.plugins = {}; + +if (!window.plugins.OneSignal) + window.plugins.OneSignal = OneSignal; \ No newline at end of file From a9c51655c0a206bcf856ead302f601968198fcc5 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 14 Jun 2021 16:51:14 -0300 Subject: [PATCH 43/55] Remove clear handler * Clear handlers is not a public method, remove it from TS file --- types/OneSignalPlugin.d.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/types/OneSignalPlugin.d.ts b/types/OneSignalPlugin.d.ts index f0d91609..a72dae02 100644 --- a/types/OneSignalPlugin.d.ts +++ b/types/OneSignalPlugin.d.ts @@ -305,12 +305,6 @@ export interface OneSignalPlugin { */ setLogLevel(nsLogLevel: LogLevel, visualLogLevel: LogLevel): void; - /** - * Clears all handlers and observers. - * @returns void - */ - clearHandlers(): void; - /** * Did the user provide privacy consent for GDPR purposes. * @returns Promise From 935dea48d7257955aeb73ca196841f9c81cfeccc Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 14 Jun 2021 16:55:14 -0300 Subject: [PATCH 44/55] Remove outcomes and tags from IAM TS * Remove not yet accessible data --- types/InAppMessage.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/InAppMessage.d.ts b/types/InAppMessage.d.ts index 9239858b..29877d2e 100644 --- a/types/InAppMessage.d.ts +++ b/types/InAppMessage.d.ts @@ -3,6 +3,4 @@ export interface InAppMessageAction { first_click : boolean; click_name ?: string; click_url ?: string; - outcomes ?: object[]; - tags ?: object; } From 0818e3b64a4371e0bd3efc8542fa8e36c7c7740e Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 14 Jun 2021 16:59:55 -0300 Subject: [PATCH 45/55] Update Subscription parsed data * Update TS data for Subscription models and update Subscription data to match TS keys --- types/Subscription.d.ts | 10 ++++------ www/Subscription.js | 6 +++--- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/types/Subscription.d.ts b/types/Subscription.d.ts index af7a6e1c..e432c020 100644 --- a/types/Subscription.d.ts +++ b/types/Subscription.d.ts @@ -1,5 +1,5 @@ // 0 = NotDetermined, 1 = Denied, 2 = Authorized, 3 = Provisional, 4 = Ephemeral -export type IosPermissionStatus = 0 | 1 | 2 | 3 | 4; +export type PermissionStatus = 0 | 1 | 2 | 3 | 4; /* D E V I C E */ export interface DeviceState { @@ -13,23 +13,21 @@ export interface DeviceState { isPushDisabled : boolean; isEmailSubscribed : boolean; isSMSSubscribed : boolean; - hasNotificationPermission ?: boolean; - notificationPermissionStatus ?: IosPermissionStatus; // ios only + hasNotificationPermission : boolean; + notificationPermissionStatus ?: PermissionStatus; // ios only // areNotificationsEnabled (android) not included since it is converted to hasNotificationPermission in bridge } export interface PermissionChange { - status ?: IosPermissionStatus; // ios + status : PermissionStatus; hasPrompted ?: boolean; // ios provisional ?: boolean; // ios - areNotificationsEnabled ?: boolean; // android } export interface SubscriptionChange { userId ?: string; pushToken ?: string; isSubscribed : boolean; - isPushDisabled : boolean; } export interface EmailSubscriptionChange { diff --git a/www/Subscription.js b/www/Subscription.js index fd7d61f2..c4ff7ad2 100644 --- a/www/Subscription.js +++ b/www/Subscription.js @@ -58,7 +58,7 @@ function OSSubscriptionState(json) { /// is subscribed to your app with OneSignal /// This is only true if the `userId`, `pushToken`, and /// `userSubscriptionSetting` parameters are defined/true. - this.subscribed = json.isSubscribed; + this.isSubscribed = json.isSubscribed; /// The current user's User ID (AKA playerID) with OneSignal this.userId = json.userId; @@ -81,7 +81,7 @@ function OSSubscriptionStateChanges(json) { /// Represents the user's OneSignal email subscription state, function OSEmailSubscriptionState(json) { - this.subscribed = json.isSubscribed; + this.isEmailSubscribed = json.isSubscribed; this.emailAddress = json.emailAddress; this.emailUserId = json.emailUserId; } @@ -99,7 +99,7 @@ function OSEmailSubscriptionStateChanges(json) { /// Represents the user's OneSignal SMS subscription state, function OSSMSSubscriptionState(json) { - this.subscribed = json.isSubscribed; + this.isSMSSubscribed = json.isSubscribed; this.smsNumber = json.smsNumber; this.smsUserId = json.smsUserId; } From c5c9cf4a80e44cc03f3b4e35caaf7d070e9b692d Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Thu, 17 Jun 2021 16:56:33 -0300 Subject: [PATCH 46/55] Release commit beta cut 2 --- package.json | 2 +- plugin.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 6d12ae11..d6d5fcd5 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "3.0.0-beta1", + "version": "3.0.0-beta2", "name": "onesignal-cordova-plugin", "cordova_name": "OneSignal Push Notifications", diff --git a/plugin.xml b/plugin.xml index 32aae165..8f91b228 100644 --- a/plugin.xml +++ b/plugin.xml @@ -2,7 +2,7 @@ + version="3.0.0-beta2"> OneSignal Push Notifications Josh Kasten, Bradley Hesse, Rodrigo Gomez-Palacio From 02d7e3b37237d03e080ec57cc13fb0edb4e3e88a Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Mon, 12 Jul 2021 12:36:22 -0300 Subject: [PATCH 47/55] Remove framework deprecated config * Replace framework type="podspec" with config --- plugin.xml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/plugin.xml b/plugin.xml index 8f91b228..4acd0d4b 100644 --- a/plugin.xml +++ b/plugin.xml @@ -72,7 +72,16 @@ production - + + + + + + + + + + From ae53e90d8ebd4e127251e2342a2015ba474e3ffa Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 13 Jul 2021 13:40:36 -0300 Subject: [PATCH 48/55] Standardize raw payload type to object * Android was returning raw payload as String meanwhile iOS returned an object, make both return an object --- types/Notification.d.ts | 2 +- www/NotificationReceived.js | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/types/Notification.d.ts b/types/Notification.d.ts index 959e5164..6d1a5799 100644 --- a/types/Notification.d.ts +++ b/types/Notification.d.ts @@ -7,7 +7,7 @@ export interface OSNotification { sound ?: string; title ?: string; launchURL ?: string; - rawPayload : object | string; // platform bridges return different types + rawPayload : object; actionButtons ?: object[]; additionalData : object; notificationId : string; diff --git a/www/NotificationReceived.js b/www/NotificationReceived.js index 84c459d3..ea5910fc 100644 --- a/www/NotificationReceived.js +++ b/www/NotificationReceived.js @@ -10,7 +10,11 @@ function OSNotification (receivedEvent) { this.additionalData = receivedEvent.additionalData; /// A hashmap object representing the raw key/value /// properties of the push notification - this.rawPayload = receivedEvent.rawPayload; + if (typeof receivedEvent.rawPayload === 'string' || receivedEvent.rawPayload instanceof String) { + this.rawPayload = JSON.parse(receivedEvent.rawPayload); + } else { + this.rawPayload = receivedEvent.rawPayload; + } /// If set, he launch URL will be opened when the user /// taps on your push notification. You can control /// whether or not it opens in an in-app webview or From 3ce0cc4a1d8083c19b68981f87119799f0416681 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 13 Jul 2021 14:33:43 -0300 Subject: [PATCH 49/55] Update Android version to 4.4.1 --- plugin.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin.xml b/plugin.xml index 4acd0d4b..b67fb55d 100644 --- a/plugin.xml +++ b/plugin.xml @@ -31,7 +31,7 @@ - + From aa68dbab4fea7b2c57ea18fbc143e1fe6fa87af4 Mon Sep 17 00:00:00 2001 From: Jeasmine Nahui Date: Tue, 13 Jul 2021 20:43:31 -0300 Subject: [PATCH 50/55] Release commit beta cut 3 --- package.json | 2 +- plugin.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index d6d5fcd5..4686efbe 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "3.0.0-beta2", + "version": "3.0.0-beta3", "name": "onesignal-cordova-plugin", "cordova_name": "OneSignal Push Notifications", diff --git a/plugin.xml b/plugin.xml index b67fb55d..faa7a383 100644 --- a/plugin.xml +++ b/plugin.xml @@ -2,7 +2,7 @@ + version="3.0.0-beta3"> OneSignal Push Notifications Josh Kasten, Bradley Hesse, Rodrigo Gomez-Palacio From 644bb47fbbd3176411a2a34b86072d2ff70c46d6 Mon Sep 17 00:00:00 2001 From: Josh Kasten Date: Mon, 2 Aug 2021 11:20:16 -0700 Subject: [PATCH 51/55] Switch to iOS OneSignalXCFramework * This supports M1 mac simulator builds * Tested on an x86 mac with Cordova CLI 10.0.0, Cordova iOS 6.2.0, and Xcode 12.5.1 on iOS 14.4.1 --- plugin.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin.xml b/plugin.xml index faa7a383..8ed84aaa 100644 --- a/plugin.xml +++ b/plugin.xml @@ -78,7 +78,7 @@ - + From a083caa4ebd94efd07d13d341f7c851acc62c12f Mon Sep 17 00:00:00 2001 From: Nan Date: Mon, 12 Jul 2021 11:03:29 -0700 Subject: [PATCH 52/55] Added methods for setLanguage feature --- .../com/onesignal/cordova/OneSignalController.java | 11 +++++++++++ src/android/com/onesignal/cordova/OneSignalPush.java | 6 ++++++ src/ios/OneSignalPush.h | 2 ++ src/ios/OneSignalPush.m | 4 ++++ types/OneSignalPlugin.d.ts | 7 +++++++ www/OneSignalPlugin.js | 4 ++++ 6 files changed, 34 insertions(+) diff --git a/src/android/com/onesignal/cordova/OneSignalController.java b/src/android/com/onesignal/cordova/OneSignalController.java index a3378472..877400dd 100644 --- a/src/android/com/onesignal/cordova/OneSignalController.java +++ b/src/android/com/onesignal/cordova/OneSignalController.java @@ -48,6 +48,17 @@ public static void setLogLevel(JSONArray data) { } } + public static boolean setLanguage(JSONArray data) { + try { + OneSignal.setLanguage(data.getString(0)); + return true; + } + catch (Throwable t) { + t.printStackTrace(); + return false; + } + } + /** * Tags */ diff --git a/src/android/com/onesignal/cordova/OneSignalPush.java b/src/android/com/onesignal/cordova/OneSignalPush.java index c66d7172..f5482151 100644 --- a/src/android/com/onesignal/cordova/OneSignalPush.java +++ b/src/android/com/onesignal/cordova/OneSignalPush.java @@ -53,6 +53,8 @@ public class OneSignalPush extends CordovaPlugin { private static final String GET_DEVICE_STATE = "getDeviceState"; + private static final String SET_LANGUAGE = "setLanguage"; + private static final String ADD_PERMISSION_OBSERVER = "addPermissionObserver"; private static final String ADD_SUBSCRIPTION_OBSERVER = "addSubscriptionObserver"; private static final String ADD_EMAIL_SUBSCRIPTION_OBSERVER = "addEmailSubscriptionObserver"; @@ -168,6 +170,10 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo result = OneSignalController.getDeviceState(callbackContext); break; + case SET_LANGUAGE: + result = OneSignalController.setLanguage(language); + break; + case ADD_PERMISSION_OBSERVER: result = OneSignalObserverController.addPermissionObserver(callbackContext); break; diff --git a/src/ios/OneSignalPush.h b/src/ios/OneSignalPush.h index 40a839d7..d48dfa46 100644 --- a/src/ios/OneSignalPush.h +++ b/src/ios/OneSignalPush.h @@ -100,4 +100,6 @@ - (void)setLocationShared:(CDVInvokedUrlCommand* _Nonnull)command; - (void)isLocationShared:(CDVInvokedUrlCommand* _Nonnull)command; +- (void)setLanguage:(CDVInvokedUrlCommand* _Nonnull)command; + @end diff --git a/src/ios/OneSignalPush.m b/src/ios/OneSignalPush.m index e5a1dc64..d4b6532b 100644 --- a/src/ios/OneSignalPush.m +++ b/src/ios/OneSignalPush.m @@ -235,6 +235,10 @@ - (void)getDeviceState:(CDVInvokedUrlCommand*)command { successCallback(command.callbackId, [[OneSignal getDeviceState] jsonRepresentation]); } +- (void)setLanguage:(CDVInvokedUrlCommand*)command { + [OneSignal setLanguage:command.arguments[0]]; +} + - (void)addPermissionObserver:(CDVInvokedUrlCommand*)command { bool first = permissionObserverCallbackId == nil; permissionObserverCallbackId = command.callbackId; diff --git a/types/OneSignalPlugin.d.ts b/types/OneSignalPlugin.d.ts index a72dae02..e5015785 100644 --- a/types/OneSignalPlugin.d.ts +++ b/types/OneSignalPlugin.d.ts @@ -112,6 +112,13 @@ export interface OneSignalPlugin { */ getDeviceState(): Promise; + /** + * Allows you to set the app defined language with the OneSignal SDK. + * @param {string} language + * @returns void + */ + setLanguage(language: string): void; + /** * Tag a user based on an app event of your choosing so they can be targeted later via segments. * @param {string} key diff --git a/www/OneSignalPlugin.js b/www/OneSignalPlugin.js index 103d0562..f5a4c4a9 100644 --- a/www/OneSignalPlugin.js +++ b/www/OneSignalPlugin.js @@ -106,6 +106,10 @@ OneSignalPlugin.prototype.getDeviceState = function(deviceStateReceivedCallBack) window.cordova.exec(deviceStateCallback, function(){}, "OneSignalPush", "getDeviceState", []); }; +OneSignalPlugin.prototype.setLanguage = function(language) { + window.cordova.exec(function(){}, function(){}, "OneSignalPush", "setLanguage", [language]); +} + OneSignalPlugin.prototype.addSubscriptionObserver = function(callback) { OneSignalPlugin._subscriptionObserverList.push(callback); var subscriptionCallBackProcessor = function(state) { From 8437d12de904d1fbbff365e2e4f0ec13f7648b7c Mon Sep 17 00:00:00 2001 From: Nan Date: Tue, 13 Jul 2021 11:00:03 -0700 Subject: [PATCH 53/55] Update variable 'language' to 'data' in OneSignalPush.java --- src/android/com/onesignal/cordova/OneSignalPush.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/android/com/onesignal/cordova/OneSignalPush.java b/src/android/com/onesignal/cordova/OneSignalPush.java index f5482151..e82edd20 100644 --- a/src/android/com/onesignal/cordova/OneSignalPush.java +++ b/src/android/com/onesignal/cordova/OneSignalPush.java @@ -171,7 +171,7 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo break; case SET_LANGUAGE: - result = OneSignalController.setLanguage(language); + result = OneSignalController.setLanguage(data); break; case ADD_PERMISSION_OBSERVER: From 59bf0cd0dbc4198717384e5c43a2319907a0b1a6 Mon Sep 17 00:00:00 2001 From: Josh Kasten Date: Fri, 6 Aug 2021 13:09:57 -0700 Subject: [PATCH 54/55] Remove -beta from 3.0.0 version --- package.json | 2 +- plugin.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 4686efbe..878ca787 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "3.0.0-beta3", + "version": "3.0.0", "name": "onesignal-cordova-plugin", "cordova_name": "OneSignal Push Notifications", diff --git a/plugin.xml b/plugin.xml index 8ed84aaa..ca1e1902 100644 --- a/plugin.xml +++ b/plugin.xml @@ -2,7 +2,7 @@ + version="3.0.0"> OneSignal Push Notifications Josh Kasten, Bradley Hesse, Rodrigo Gomez-Palacio From 74f641cf41abce8b8735bd4f72be0dc48ccefcb5 Mon Sep 17 00:00:00 2001 From: Josh Kasten Date: Fri, 6 Aug 2021 13:11:20 -0700 Subject: [PATCH 55/55] Bump OneSignal-Android-SDK to 4.4.2 --- plugin.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin.xml b/plugin.xml index ca1e1902..da35f1bb 100644 --- a/plugin.xml +++ b/plugin.xml @@ -31,7 +31,7 @@ - +