This repository was archived by the owner on May 18, 2024. It is now read-only.
forked from microsoft/react-native-code-push
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodePushNativeModule.java
More file actions
707 lines (616 loc) · 31.5 KB
/
CodePushNativeModule.java
File metadata and controls
707 lines (616 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
package com.microsoft.codepush.react;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.ChoreographerCompat;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.ReactChoreographer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CodePushNativeModule extends ReactContextBaseJavaModule {
private String mBinaryContentsHash = null;
private String mClientUniqueId = null;
private LifecycleEventListener mLifecycleEventListener = null;
private int mMinimumBackgroundDuration = 0;
private CodePush mCodePush;
private SettingsManager mSettingsManager;
private CodePushTelemetryManager mTelemetryManager;
private CodePushUpdateManager mUpdateManager;
private boolean _allowed = true;
private boolean _restartInProgress = false;
private ArrayList<Boolean> _restartQueue = new ArrayList<>();
public CodePushNativeModule(ReactApplicationContext reactContext, CodePush codePush, CodePushUpdateManager codePushUpdateManager, CodePushTelemetryManager codePushTelemetryManager, SettingsManager settingsManager) {
super(reactContext);
mCodePush = codePush;
mSettingsManager = settingsManager;
mTelemetryManager = codePushTelemetryManager;
mUpdateManager = codePushUpdateManager;
// Initialize module state while we have a reference to the current context.
mBinaryContentsHash = CodePushUpdateUtils.getHashForBinaryContents(reactContext, mCodePush.isDebugMode());
mClientUniqueId = Settings.Secure.getString(reactContext.getContentResolver(), Settings.Secure.ANDROID_ID);
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("codePushInstallModeImmediate", CodePushInstallMode.IMMEDIATE.getValue());
constants.put("codePushInstallModeOnNextRestart", CodePushInstallMode.ON_NEXT_RESTART.getValue());
constants.put("codePushInstallModeOnNextResume", CodePushInstallMode.ON_NEXT_RESUME.getValue());
constants.put("codePushInstallModeOnNextSuspend", CodePushInstallMode.ON_NEXT_SUSPEND.getValue());
constants.put("codePushUpdateStateRunning", CodePushUpdateState.RUNNING.getValue());
constants.put("codePushUpdateStatePending", CodePushUpdateState.PENDING.getValue());
constants.put("codePushUpdateStateLatest", CodePushUpdateState.LATEST.getValue());
return constants;
}
@Override
public String getName() {
return "CodePush";
}
private void loadBundleLegacy() {
final Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
// The currentActivity can be null if it is backgrounded / destroyed, so we simply
// no-op to prevent any null pointer exceptions.
return;
}
mCodePush.invalidateCurrentInstance();
currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
currentActivity.recreate();
}
});
}
// Use reflection to find and set the appropriate fields on ReactInstanceManager. See #556 for a proposal for a less brittle way
// to approach this.
private void setJSBundle(ReactInstanceManager instanceManager, String latestJSBundleFile) throws IllegalAccessException {
try {
JSBundleLoader latestJSBundleLoader;
if (latestJSBundleFile.toLowerCase().startsWith("assets://")) {
latestJSBundleLoader = JSBundleLoader.createAssetLoader(getReactApplicationContext(), latestJSBundleFile, false);
} else {
latestJSBundleLoader = JSBundleLoader.createFileLoader(latestJSBundleFile);
}
Field bundleLoaderField = instanceManager.getClass().getDeclaredField("mBundleLoader");
bundleLoaderField.setAccessible(true);
bundleLoaderField.set(instanceManager, latestJSBundleLoader);
} catch (Exception e) {
CodePushUtils.log("Unable to set JSBundle - CodePush may not support this version of React Native");
throw new IllegalAccessException("Could not setJSBundle");
}
}
private void loadBundle() {
clearLifecycleEventListener();
try {
mCodePush.clearDebugCacheIfNeeded(resolveInstanceManager());
} catch(Exception e) {
// If we got error in out reflection we should clear debug cache anyway.
mCodePush.clearDebugCacheIfNeeded(null);
}
try {
// #1) Get the ReactInstanceManager instance, which is what includes the
// logic to reload the current React context.
final ReactInstanceManager instanceManager = resolveInstanceManager();
if (instanceManager == null) {
return;
}
String latestJSBundleFile = mCodePush.getJSBundleFileInternal(mCodePush.getAssetsBundleFileName());
// #2) Update the locally stored JS bundle file path
setJSBundle(instanceManager, latestJSBundleFile);
// #3) Get the context creation method and fire it on the UI thread (which RN enforces)
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
try {
// We don't need to resetReactRootViews anymore
// due the issue https://github.com/facebook/react-native/issues/14533
// has been fixed in RN 0.46.0
//resetReactRootViews(instanceManager);
instanceManager.recreateReactContextInBackground();
mCodePush.initializeUpdateAfterRestart();
} catch (Exception e) {
// The recreation method threw an unknown exception
// so just simply fallback to restarting the Activity (if it exists)
loadBundleLegacy();
}
}
});
} catch (Exception e) {
// Our reflection logic failed somewhere
// so fall back to restarting the Activity (if it exists)
CodePushUtils.log("Failed to load the bundle, falling back to restarting the Activity (if it exists). " + e.getMessage());
loadBundleLegacy();
}
}
// This workaround has been implemented in order to fix https://github.com/facebook/react-native/issues/14533
// resetReactRootViews allows to call recreateReactContextInBackground without any exceptions
// This fix also relates to https://github.com/microsoft/react-native-code-push/issues/878
private void resetReactRootViews(ReactInstanceManager instanceManager) throws NoSuchFieldException, IllegalAccessException {
Field mAttachedRootViewsField = instanceManager.getClass().getDeclaredField("mAttachedRootViews");
mAttachedRootViewsField.setAccessible(true);
List<ReactRootView> mAttachedRootViews = (List<ReactRootView>)mAttachedRootViewsField.get(instanceManager);
for (ReactRootView reactRootView : mAttachedRootViews) {
reactRootView.removeAllViews();
reactRootView.setId(View.NO_ID);
}
mAttachedRootViewsField.set(instanceManager, mAttachedRootViews);
}
private void clearLifecycleEventListener() {
// Remove LifecycleEventListener to prevent infinite restart loop
if (mLifecycleEventListener != null) {
getReactApplicationContext().removeLifecycleEventListener(mLifecycleEventListener);
mLifecycleEventListener = null;
}
}
// Use reflection to find the ReactInstanceManager. See #556 for a proposal for a less brittle way to approach this.
private ReactInstanceManager resolveInstanceManager() throws NoSuchFieldException, IllegalAccessException {
ReactInstanceManager instanceManager = mCodePush.getReactInstanceManager();
if (instanceManager != null) {
return instanceManager;
}
final Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
return null;
}
ReactApplication reactApplication = (ReactApplication) currentActivity.getApplication();
instanceManager = reactApplication.getReactNativeHost().getReactInstanceManager();
return instanceManager;
}
private void restartAppInternal(boolean onlyIfUpdateIsPending) {
if (this._restartInProgress) {
CodePushUtils.log("Restart request queued until the current restart is completed");
this._restartQueue.add(onlyIfUpdateIsPending);
return;
} else if (!this._allowed) {
CodePushUtils.log("Restart request queued until restarts are re-allowed");
this._restartQueue.add(onlyIfUpdateIsPending);
return;
}
this._restartInProgress = true;
if (!onlyIfUpdateIsPending || mSettingsManager.isPendingUpdate(null)) {
loadBundle();
CodePushUtils.log("Restarting app");
return;
}
this._restartInProgress = false;
if (this._restartQueue.size() > 0) {
boolean buf = this._restartQueue.get(0);
this._restartQueue.remove(0);
this.restartAppInternal(buf);
}
}
@ReactMethod
public void allow(Promise promise) {
CodePushUtils.log("Re-allowing restarts");
this._allowed = true;
if (_restartQueue.size() > 0) {
CodePushUtils.log("Executing pending restart");
boolean buf = this._restartQueue.get(0);
this._restartQueue.remove(0);
this.restartAppInternal(buf);
}
promise.resolve(null);
return;
}
@ReactMethod
public void clearPendingRestart(Promise promise) {
this._restartQueue.clear();
promise.resolve(null);
return;
}
@ReactMethod
public void disallow(Promise promise) {
CodePushUtils.log("Disallowing restarts");
this._allowed = false;
promise.resolve(null);
return;
}
@ReactMethod
public void restartApp(boolean onlyIfUpdateIsPending, Promise promise) {
try {
restartAppInternal(onlyIfUpdateIsPending);
promise.resolve(null);
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void downloadUpdate(final ReadableMap updatePackage, final boolean notifyProgress, final Promise promise) {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
CodePushUtils.log("Update Package - " + updatePackage);
JSONObject mutableUpdatePackage = CodePushUtils.convertReadableToJsonObject(updatePackage);
CodePushUtils.setJSONValueForKey(mutableUpdatePackage, CodePushConstants.BINARY_MODIFIED_TIME_KEY, "" + mCodePush.getBinaryResourcesModifiedTime());
mUpdateManager.downloadPackage(mutableUpdatePackage, mCodePush.getAssetsBundleFileName(), new DownloadProgressCallback() {
private boolean hasScheduledNextFrame = false;
private DownloadProgress latestDownloadProgress = null;
@Override
public void call(DownloadProgress downloadProgress) {
if (!notifyProgress) {
return;
}
latestDownloadProgress = downloadProgress;
// If the download is completed, synchronously send the last event.
if (latestDownloadProgress.isCompleted()) {
dispatchDownloadProgressEvent();
return;
}
if (hasScheduledNextFrame) {
return;
}
hasScheduledNextFrame = true;
getReactApplicationContext().runOnUiQueueThread(new Runnable() {
@Override
public void run() {
ReactChoreographer.getInstance().postFrameCallback(ReactChoreographer.CallbackType.TIMERS_EVENTS, new ChoreographerCompat.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
if (!latestDownloadProgress.isCompleted()) {
dispatchDownloadProgressEvent();
}
hasScheduledNextFrame = false;
}
});
}
});
}
public void dispatchDownloadProgressEvent() {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(CodePushConstants.DOWNLOAD_PROGRESS_EVENT_NAME, latestDownloadProgress.createWritableMap());
}
}, mCodePush.getPublicKey());
JSONObject newPackage = mUpdateManager.getPackage(CodePushUtils.tryGetString(updatePackage, CodePushConstants.PACKAGE_HASH_KEY));
promise.resolve(CodePushUtils.convertJsonObjectToWritable(newPackage));
} catch (CodePushInvalidUpdateException e) {
CodePushUtils.log(e);
mSettingsManager.saveFailedUpdate(CodePushUtils.convertReadableToJsonObject(updatePackage));
promise.reject(e);
} catch (IOException | CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
return null;
}
};
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@ReactMethod
public void getConfiguration(Promise promise) {
try {
WritableMap configMap = Arguments.createMap();
configMap.putString("appVersion", mCodePush.getAppVersion());
configMap.putString("clientUniqueId", mClientUniqueId);
configMap.putString("deploymentKey", mCodePush.getDeploymentKey());
configMap.putString("serverUrl", mCodePush.getServerUrl());
// The binary hash may be null in debug builds
if (mBinaryContentsHash != null) {
configMap.putString(CodePushConstants.PACKAGE_HASH_KEY, mBinaryContentsHash);
}
promise.resolve(configMap);
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void getUpdateMetadata(final int updateState, final Promise promise) {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
JSONObject currentPackage = mUpdateManager.getCurrentPackage();
if (currentPackage == null) {
promise.resolve(null);
return null;
}
Boolean currentUpdateIsPending = false;
if (currentPackage.has(CodePushConstants.PACKAGE_HASH_KEY)) {
String currentHash = currentPackage.optString(CodePushConstants.PACKAGE_HASH_KEY, null);
currentUpdateIsPending = mSettingsManager.isPendingUpdate(currentHash);
}
if (updateState == CodePushUpdateState.PENDING.getValue() && !currentUpdateIsPending) {
// The caller wanted a pending update
// but there isn't currently one.
promise.resolve(null);
} else if (updateState == CodePushUpdateState.RUNNING.getValue() && currentUpdateIsPending) {
// The caller wants the running update, but the current
// one is pending, so we need to grab the previous.
JSONObject previousPackage = mUpdateManager.getPreviousPackage();
if (previousPackage == null) {
promise.resolve(null);
return null;
}
promise.resolve(CodePushUtils.convertJsonObjectToWritable(previousPackage));
} else {
// The current package satisfies the request:
// 1) Caller wanted a pending, and there is a pending update
// 2) Caller wanted the running update, and there isn't a pending
// 3) Caller wants the latest update, regardless if it's pending or not
if (mCodePush.isRunningBinaryVersion()) {
// This only matters in Debug builds. Since we do not clear "outdated" updates,
// we need to indicate to the JS side that somehow we have a current update on
// disk that is not actually running.
CodePushUtils.setJSONValueForKey(currentPackage, "_isDebugOnly", true);
}
// Enable differentiating pending vs. non-pending updates
CodePushUtils.setJSONValueForKey(currentPackage, "isPending", currentUpdateIsPending);
promise.resolve(CodePushUtils.convertJsonObjectToWritable(currentPackage));
}
} catch (CodePushMalformedDataException e) {
// We need to recover the app in case 'codepush.json' is corrupted
CodePushUtils.log(e.getMessage());
clearUpdates();
promise.resolve(null);
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
return null;
}
};
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@ReactMethod
public void getNewStatusReport(final Promise promise) {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
if (mCodePush.needToReportRollback()) {
mCodePush.setNeedToReportRollback(false);
JSONArray failedUpdates = mSettingsManager.getFailedUpdates();
if (failedUpdates != null && failedUpdates.length() > 0) {
try {
JSONObject lastFailedPackageJSON = failedUpdates.getJSONObject(failedUpdates.length() - 1);
WritableMap lastFailedPackage = CodePushUtils.convertJsonObjectToWritable(lastFailedPackageJSON);
WritableMap failedStatusReport = mTelemetryManager.getRollbackReport(lastFailedPackage);
if (failedStatusReport != null) {
promise.resolve(failedStatusReport);
return null;
}
} catch (JSONException e) {
throw new CodePushUnknownException("Unable to read failed updates information stored in SharedPreferences.", e);
}
}
} else if (mCodePush.didUpdate()) {
JSONObject currentPackage = mUpdateManager.getCurrentPackage();
if (currentPackage != null) {
WritableMap newPackageStatusReport = mTelemetryManager.getUpdateReport(CodePushUtils.convertJsonObjectToWritable(currentPackage));
if (newPackageStatusReport != null) {
promise.resolve(newPackageStatusReport);
return null;
}
}
} else if (mCodePush.isRunningBinaryVersion()) {
WritableMap newAppVersionStatusReport = mTelemetryManager.getBinaryUpdateReport(mCodePush.getAppVersion());
if (newAppVersionStatusReport != null) {
promise.resolve(newAppVersionStatusReport);
return null;
}
} else {
WritableMap retryStatusReport = mTelemetryManager.getRetryStatusReport();
if (retryStatusReport != null) {
promise.resolve(retryStatusReport);
return null;
}
}
promise.resolve("");
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
return null;
}
};
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@ReactMethod
public void installUpdate(final ReadableMap updatePackage, final int installMode, final int minimumBackgroundDuration, final Promise promise) {
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
mUpdateManager.installPackage(CodePushUtils.convertReadableToJsonObject(updatePackage), mSettingsManager.isPendingUpdate(null));
String pendingHash = CodePushUtils.tryGetString(updatePackage, CodePushConstants.PACKAGE_HASH_KEY);
if (pendingHash == null) {
throw new CodePushUnknownException("Update package to be installed has no hash.");
} else {
mSettingsManager.savePendingUpdate(pendingHash, /* isLoading */false);
}
if (installMode == CodePushInstallMode.ON_NEXT_RESUME.getValue() ||
// We also add the resume listener if the installMode is IMMEDIATE, because
// if the current activity is backgrounded, we want to reload the bundle when
// it comes back into the foreground.
installMode == CodePushInstallMode.IMMEDIATE.getValue() ||
installMode == CodePushInstallMode.ON_NEXT_SUSPEND.getValue()) {
// Store the minimum duration on the native module as an instance
// variable instead of relying on a closure below, so that any
// subsequent resume-based installs could override it.
CodePushNativeModule.this.mMinimumBackgroundDuration = minimumBackgroundDuration;
if (mLifecycleEventListener == null) {
// Ensure we do not add the listener twice.
mLifecycleEventListener = new LifecycleEventListener() {
private Date lastPausedDate = null;
private Handler appSuspendHandler = new Handler(Looper.getMainLooper());
private Runnable loadBundleRunnable = new Runnable() {
@Override
public void run() {
CodePushUtils.log("Loading bundle on suspend");
restartAppInternal(false);
}
};
@Override
public void onHostResume() {
appSuspendHandler.removeCallbacks(loadBundleRunnable);
// As of RN 36, the resume handler fires immediately if the app is in
// the foreground, so explicitly wait for it to be backgrounded first
if (lastPausedDate != null) {
long durationInBackground = (new Date().getTime() - lastPausedDate.getTime()) / 1000;
if (installMode == CodePushInstallMode.IMMEDIATE.getValue()
|| durationInBackground >= CodePushNativeModule.this.mMinimumBackgroundDuration) {
CodePushUtils.log("Loading bundle on resume");
restartAppInternal(false);
}
}
}
@Override
public void onHostPause() {
// Save the current time so that when the app is later
// resumed, we can detect how long it was in the background.
lastPausedDate = new Date();
if (installMode == CodePushInstallMode.ON_NEXT_SUSPEND.getValue() && mSettingsManager.isPendingUpdate(null)) {
appSuspendHandler.postDelayed(loadBundleRunnable, minimumBackgroundDuration * 1000);
}
}
@Override
public void onHostDestroy() {
}
};
getReactApplicationContext().addLifecycleEventListener(mLifecycleEventListener);
}
}
promise.resolve("");
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
return null;
}
};
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@ReactMethod
public void isFailedUpdate(String packageHash, Promise promise) {
try {
promise.resolve(mSettingsManager.isFailedHash(packageHash));
} catch (CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void getLatestRollbackInfo(Promise promise) {
try {
JSONObject latestRollbackInfo = mSettingsManager.getLatestRollbackInfo();
if (latestRollbackInfo != null) {
promise.resolve(CodePushUtils.convertJsonObjectToWritable(latestRollbackInfo));
} else {
promise.resolve(null);
}
} catch (CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void setLatestRollbackInfo(String packageHash, Promise promise) {
try {
mSettingsManager.setLatestRollbackInfo(packageHash);
promise.resolve(null);
} catch (CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void isFirstRun(String packageHash, Promise promise) {
try {
boolean isFirstRun = mCodePush.didUpdate()
&& packageHash != null
&& packageHash.length() > 0
&& packageHash.equals(mUpdateManager.getCurrentPackageHash());
promise.resolve(isFirstRun);
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void notifyApplicationReady(Promise promise) {
try {
mSettingsManager.removePendingUpdate();
promise.resolve("");
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
promise.reject(e);
}
}
@ReactMethod
public void recordStatusReported(ReadableMap statusReport) {
try {
mTelemetryManager.recordStatusReported(statusReport);
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
}
}
@ReactMethod
public void saveStatusReportForRetry(ReadableMap statusReport) {
try {
mTelemetryManager.saveStatusReportForRetry(statusReport);
} catch(CodePushUnknownException e) {
CodePushUtils.log(e);
}
}
@ReactMethod
// Replaces the current bundle with the one downloaded from removeBundleUrl.
// It is only to be used during tests. No-ops if the test configuration flag is not set.
public void downloadAndReplaceCurrentBundle(String remoteBundleUrl) {
try {
if (mCodePush.isUsingTestConfiguration()) {
try {
mUpdateManager.downloadAndReplaceCurrentBundle(remoteBundleUrl, mCodePush.getAssetsBundleFileName());
} catch (IOException e) {
throw new CodePushUnknownException("Unable to replace current bundle", e);
}
}
} catch(CodePushUnknownException | CodePushMalformedDataException e) {
CodePushUtils.log(e);
}
}
/**
* This method clears CodePush's downloaded updates.
* It is needed to switch to a different deployment if the current deployment is more recent.
* Note: we don’t recommend to use this method in scenarios other than that (CodePush will call
* this method automatically when needed in other cases) as it could lead to unpredictable
* behavior.
*/
@ReactMethod
public void clearUpdates() {
CodePushUtils.log("Clearing updates.");
mCodePush.clearUpdates();
}
@ReactMethod
public void addListener(String eventName) {
// Set up any upstream listeners or background tasks as necessary
}
@ReactMethod
public void removeListeners(Integer count) {
// Remove upstream listeners, stop unnecessary background tasks
}
}