forked from bobeast/PushPlugin-deprecated
-
Notifications
You must be signed in to change notification settings - Fork 989
/
Copy pathPushPlugin.java
429 lines (385 loc) · 15.1 KB
/
PushPlugin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
* Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazon.cordova.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.LOG;
import org.json.JSONArray;
import org.json.JSONException;
import com.amazon.device.messaging.ADM;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import java.util.Iterator;
import org.json.JSONObject;
public class PushPlugin extends CordovaPlugin {
private static String TAG = "PushPlugin";
/**
* @uml.property name="adm"
* @uml.associationEnd
*/
private ADM adm = null;
/**
* @uml.property name="activity"
* @uml.associationEnd
*/
private Activity activity = null;
private static CordovaWebView webview = null;
private static String notificationHandlerCallBack;
private static boolean isForeground = false;
private static Bundle gCachedExtras = null;
public static final String REGISTER = "register";
public static final String UNREGISTER = "unregister";
public static final String REGISTER_EVENT = "registered";
public static final String UNREGISTER_EVENT = "unregistered";
public static final String MESSAGE = "message";
public static final String ECB = "ecb";
public static final String EVENT = "event";
public static final String PAYLOAD = "payload";
public static final String FOREGROUND = "foreground";
public static final String REG_ID = "regid";
public static final String COLDSTART = "coldstart";
private static final String NON_AMAZON_DEVICE_ERROR = "PushNotifications using Amazon Device Messaging is only supported on Kindle Fire devices (2nd Generation and Later only).";
private static final String ADM_NOT_SUPPORTED_ERROR = "Amazon Device Messaging is not supported on this device.";
private static final String REGISTER_OPTIONS_NULL = "Register options are not specified.";
private static final String ECB_NOT_SPECIFIED = "ecb(eventcallback) option is not specified in register().";
private static final String ECB_NAME_NOT_SPECIFIED = "ecb(eventcallback) value is missing in options for register().";
private static final String REGISTRATION_SUCCESS_RESPONSE = "Registration started...";
private static final String UNREGISTRATION_SUCCESS_RESPONSE = "Unregistration started...";
private static final String MODEL_FIRST_GEN = "Kindle Fire";
public enum ADMReadiness {
INITIALIZED, NON_AMAZON_DEVICE, ADM_NOT_SUPPORTED
}
/**
* Sets the context of the Command. This can then be used to do things like get file paths associated with the
* Activity.
*
* @param cordova
* The context of the main Activity.
* @param webView
* The associated CordovaWebView.
*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
// Initialize only for Amazon devices 2nd Generation and later
if (this.isAmazonDevice() && !isFirstGenKindleFireDevice()) {
adm = new ADM(cordova.getActivity());
activity = (CordovaActivity) cordova.getActivity();
webview = this.webView;
isForeground = true;
ADMMessageHandler.saveConfigOptions(activity);
} else {
LOG.e(TAG, NON_AMAZON_DEVICE_ERROR);
}
}
/**
* Checks if current device manufacturer is Amazon by using android.os.Build.MANUFACTURER property
*
* @return returns true for all Kindle Fire OS devices.
*/
private boolean isAmazonDevice() {
String deviceMaker = android.os.Build.MANUFACTURER;
return deviceMaker.equalsIgnoreCase("Amazon");
}
/**
* Check if device is First generation Kindle
*
* @return if device is First generation Kindle
*/
private static boolean isFirstGenKindleFireDevice() {
return android.os.Build.MODEL.equals(MODEL_FIRST_GEN);
}
/**
* Checks if ADM is available and supported - could be one of three 1. Non Amazon device, hence no ADM support 2.
* ADM is not supported on this Kindle device (1st generation) 3. ADM is successfully initialized and ready to be
* used
*
* @return returns true for all Kindle Fire OS devices.
*/
public ADMReadiness isPushPluginReady() {
if (adm == null) {
return ADMReadiness.NON_AMAZON_DEVICE;
} else if (!adm.isSupported()) {
return ADMReadiness.ADM_NOT_SUPPORTED;
}
return ADMReadiness.INITIALIZED;
}
/**
* @see Plugin#execute(String, JSONArray, String)
*/
@Override
public boolean execute(final String request, final JSONArray args,
CallbackContext callbackContext) throws JSONException {
try {
// check ADM readiness
ADMReadiness ready = isPushPluginReady();
if (ready == ADMReadiness.NON_AMAZON_DEVICE) {
callbackContext.error(NON_AMAZON_DEVICE_ERROR);
return false;
} else if (ready == ADMReadiness.ADM_NOT_SUPPORTED) {
callbackContext.error(ADM_NOT_SUPPORTED_ERROR);
return false;
} else if (callbackContext == null) {
LOG.e(TAG,
"CallbackConext is null. Notification to WebView is not possible. Can not proceed.");
return false;
}
// Process the request here
if (REGISTER.equals(request)) {
if (args == null) {
LOG.e(TAG, REGISTER_OPTIONS_NULL);
callbackContext.error(REGISTER_OPTIONS_NULL);
return false;
}
// parse args to get eventcallback name
if (args.isNull(0)) {
LOG.e(TAG, ECB_NOT_SPECIFIED);
callbackContext.error(ECB_NOT_SPECIFIED);
return false;
}
JSONObject jo = args.getJSONObject(0);
if (jo.getString("ecb").isEmpty()) {
LOG.e(TAG, ECB_NAME_NOT_SPECIFIED);
callbackContext.error(ECB_NAME_NOT_SPECIFIED);
return false;
}
callbackContext.success(REGISTRATION_SUCCESS_RESPONSE);
notificationHandlerCallBack = jo.getString(ECB);
String regId = adm.getRegistrationId();
LOG.d(TAG, "regId = " + regId);
if (regId == null) {
adm.startRegister();
} else {
sendRegistrationIdWithEvent(REGISTER_EVENT, regId);
}
// see if there are any messages while app was in background and
// launched via app icon
LOG.d(TAG,"checking for offline message..");
deliverPendingMessageAndCancelNotifiation();
return true;
} else if (UNREGISTER.equals(request)) {
adm.startUnregister();
callbackContext.success(UNREGISTRATION_SUCCESS_RESPONSE);
return true;
} else {
LOG.e(TAG, "Invalid action : " + request);
callbackContext.error("Invalid action : " + request);
return false;
}
} catch (final Exception e) {
callbackContext.error(e.getMessage());
}
return false;
}
/**
* Checks if any bundle extras were cached while app was not running
*
* @return returns tru if cached Bundle is not null otherwise true.
*/
public boolean cachedExtrasAvailable() {
return (gCachedExtras != null);
}
/**
* Checks if offline message was pending to be delivered from notificationIntent. Sends it to webView(JS) if it is
* and also clears notification from the NotificaitonCenter.
*/
private boolean deliverOfflineMessages() {
LOG.d(TAG,"deliverOfflineMessages()");
Bundle pushBundle = ADMMessageHandler.getOfflineMessage();
if (pushBundle != null) {
LOG.d(TAG,"Sending offline message...");
sendExtras(pushBundle);
ADMMessageHandler.cleanupNotificationIntent();
return true;
}
return false;
}
// lifecyle callback to set the isForeground
@Override
public void onPause(boolean multitasking) {
LOG.d(TAG, "onPause");
super.onPause(multitasking);
isForeground = false;
}
@Override
public void onResume(boolean multitasking) {
LOG.d(TAG, "onResume");
super.onResume(multitasking);
isForeground = true;
//Check if there are any offline messages?
deliverPendingMessageAndCancelNotifiation();
}
@Override
public void onDestroy() {
LOG.d(TAG, "onDestroy");
super.onDestroy();
isForeground = false;
webview = null;
notificationHandlerCallBack = null;
}
/**
* Indicates if app is in foreground or not.
*
* @return returns true if app is running otherwise false.
*/
public static boolean isInForeground() {
return isForeground;
}
/**
* Indicates if app is killed or not
*
* @return returns true if app is killed otherwise false.
*/
public static boolean isActive() {
return webview != null;
}
/**
* Delivers pending/offline messages if any
*
* @return returns true if there were any pending messages otherwise false.
*/
public boolean deliverPendingMessageAndCancelNotifiation() {
boolean delivered = false;
LOG.d(TAG,"deliverPendingMessages()");
if (cachedExtrasAvailable()) {
LOG.v(TAG, "sending cached extras");
sendExtras(gCachedExtras);
gCachedExtras = null;
delivered = true;
} else {
delivered = deliverOfflineMessages();
}
// Clear the notification if any exists
ADMMessageHandler.cancelNotification(activity);
return delivered;
}
/**
* Sends register/unregiste events to JS
*
* @param String
* - eventName - "register", "unregister"
* @param String
* - valid registrationId
*/
public static void sendRegistrationIdWithEvent(String event,
String registrationId) {
if (TextUtils.isEmpty(event) || TextUtils.isEmpty(registrationId)) {
return;
}
try {
JSONObject json;
json = new JSONObject().put(EVENT, event);
json.put(REG_ID, registrationId);
sendJavascript(json);
} catch (Exception e) {
Log.getStackTraceString(e);
}
}
/**
* Sends events to JS using cordova nativeToJS bridge.
*
* @param JSONObject
*/
public static boolean sendJavascript(JSONObject json) {
if (json == null) {
LOG.i(TAG, "JSON object is empty. Nothing to send to JS.");
return true;
}
if (notificationHandlerCallBack != null && webview != null) {
String jsToSend = "javascript:" + notificationHandlerCallBack + "("
+ json.toString() + ")";
LOG.v(TAG, "sendJavascript: " + jsToSend);
webview.sendJavascript(jsToSend);
return true;
}
return false;
}
/*
* Sends the pushbundle extras to the client application. If the client application isn't currently active, it is
* cached for later processing.
*/
public static void sendExtras(Bundle extras) {
if (extras != null) {
if (!sendJavascript(convertBundleToJson(extras))) {
LOG.v(TAG,
"sendExtras: could not send to JS. Caching extras to send at a later time.");
gCachedExtras = extras;
}
}
}
// serializes a bundle to JSON.
private static JSONObject convertBundleToJson(Bundle extras) {
if (extras == null) {
return null;
}
try {
JSONObject json;
json = new JSONObject().put(EVENT, MESSAGE);
JSONObject jsondata = new JSONObject();
Iterator<String> it = extras.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Object value = extras.get(key);
// System data from Android
if (key.equals(FOREGROUND)) {
json.put(key, extras.getBoolean(FOREGROUND));
} else if (key.equals(COLDSTART)) {
json.put(key, extras.getBoolean(COLDSTART));
} else {
// we encourage put the message content into message value
// when server send out notification
if (key.equals(MESSAGE)) {
json.put(key, value);
}
if (value instanceof String) {
// Try to figure out if the value is another JSON object
String strValue = (String) value;
if (strValue.startsWith("{")) {
try {
JSONObject json2 = new JSONObject(strValue);
jsondata.put(key, json2);
} catch (Exception e) {
jsondata.put(key, value);
}
// Try to figure out if the value is another JSON
// array
} else if (strValue.startsWith("[")) {
try {
JSONArray json2 = new JSONArray(strValue);
jsondata.put(key, json2);
} catch (Exception e) {
jsondata.put(key, value);
}
} else {
jsondata.put(key, value);
}
}
} // while
}
json.put(PAYLOAD, jsondata);
LOG.v(TAG, "extrasToJSON: " + json.toString());
return json;
} catch (JSONException e) {
LOG.e(TAG, "extrasToJSON: JSON exception");
}
return null;
}
}