forked from microsoft/react-native-code-push
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathCodePush.java
More file actions
444 lines (361 loc) · 16.6 KB
/
CodePush.java
File metadata and controls
444 lines (361 loc) · 16.6 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
package com.microsoft.codepush.react;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import com.facebook.react.ReactHost;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class CodePush implements ReactPackage {
private static final Object LOCK = new Object();
private static volatile CodePush mCurrentInstance;
public static CodePush getInstance(String deploymentKey, Context context, boolean isDebugMode) {
if (mCurrentInstance == null) {
synchronized (LOCK) {
if (mCurrentInstance == null) {
mCurrentInstance = new CodePush(deploymentKey, context, isDebugMode);
}
}
}
return mCurrentInstance;
}
private static boolean sIsRunningBinaryVersion = false;
private static boolean sNeedToReportRollback = false;
private static boolean sTestConfigurationFlag = false;
private static String sAppVersion = null;
private boolean mDidUpdate = false;
private String mAssetsBundleFileName;
// Helper classes.
private CodePushUpdateManager mUpdateManager;
private CodePushTelemetryManager mTelemetryManager;
private SettingsManager mSettingsManager;
// Config properties.
private String mDeploymentKey;
private static String mServerUrl = "https://codepush.appcenter.ms/";
private Context mContext;
private final boolean mIsDebugMode;
private static String mPublicKey;
private static ReactInstanceHolder mReactInstanceHolder;
private static ReactHostHolder mReactHostHolder;
public CodePush(String deploymentKey, Context context) {
this(deploymentKey, context, false);
}
public static String getServiceUrl() {
return mServerUrl;
}
private CodePush(String deploymentKey, Context context, boolean isDebugMode) {
mContext = context.getApplicationContext();
mUpdateManager = new CodePushUpdateManager(context.getFilesDir().getAbsolutePath());
mTelemetryManager = new CodePushTelemetryManager(mContext);
mDeploymentKey = deploymentKey;
mIsDebugMode = isDebugMode;
mSettingsManager = new SettingsManager(mContext);
if (sAppVersion == null) {
try {
PackageInfo pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
sAppVersion = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
throw new CodePushUnknownException("Unable to get package info for " + mContext.getPackageName(), e);
}
}
mCurrentInstance = this;
String publicKeyFromStrings = getCustomPropertyFromStringsIfExist("PublicKey");
if (publicKeyFromStrings != null) mPublicKey = publicKeyFromStrings;
String serverUrlFromStrings = getCustomPropertyFromStringsIfExist("ServerUrl");
if (serverUrlFromStrings != null) mServerUrl = serverUrlFromStrings;
// ignore liveReload when CodePush is initializing so that unneccessary cache could be cleared
clearDebugCacheIfNeeded(false);
initializeUpdateAfterRestart();
}
private CodePush(String deploymentKey, Context context, boolean isDebugMode, String serverUrl) {
this(deploymentKey, context, isDebugMode);
mServerUrl = serverUrl;
}
private CodePush(String deploymentKey, Context context, boolean isDebugMode, int publicKeyResourceDescriptor) {
this(deploymentKey, context, isDebugMode);
mPublicKey = getPublicKeyByResourceDescriptor(publicKeyResourceDescriptor);
}
private CodePush(String deploymentKey, Context context, boolean isDebugMode, String serverUrl, Integer publicKeyResourceDescriptor) {
this(deploymentKey, context, isDebugMode);
if (publicKeyResourceDescriptor != null) {
mPublicKey = getPublicKeyByResourceDescriptor(publicKeyResourceDescriptor);
}
mServerUrl = serverUrl;
}
private String getPublicKeyByResourceDescriptor(int publicKeyResourceDescriptor){
String publicKey;
try {
publicKey = mContext.getString(publicKeyResourceDescriptor);
} catch (Resources.NotFoundException e) {
throw new CodePushInvalidPublicKeyException(
"Unable to get public key, related resource descriptor " +
publicKeyResourceDescriptor +
" can not be found", e
);
}
if (publicKey.isEmpty()) {
throw new CodePushInvalidPublicKeyException("Specified public key is empty");
}
return publicKey;
}
private String getCustomPropertyFromStringsIfExist(String propertyName) {
String property;
String packageName = mContext.getPackageName();
int resId = mContext.getResources().getIdentifier("CodePush" + propertyName, "string", packageName);
if (resId != 0) {
property = mContext.getString(resId);
if (!property.isEmpty()) {
return property;
} else {
CodePushUtils.log("Specified " + propertyName + " is empty");
}
}
return null;
}
public void clearDebugCacheIfNeeded(boolean isLiveReloadEnabled) {
// for checking if we use LiveReload mode. In this case we should not remove ReactNativeDevBundle.js file
// because we get error with trying to get this after reloading. Issue: https://github.com/microsoft/react-native-code-push/issues/1272
if (mIsDebugMode && mSettingsManager.isPendingUpdate(null) && !isLiveReloadEnabled) {
// This needs to be kept in sync with https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManager.java#L78
File cachedDevBundle = new File(mContext.getFilesDir(), "ReactNativeDevBundle.js");
if (cachedDevBundle.exists()) {
cachedDevBundle.delete();
}
}
}
public boolean didUpdate() {
return mDidUpdate;
}
public String getAppVersion() {
return sAppVersion;
}
public String getAssetsBundleFileName() {
return mAssetsBundleFileName;
}
public String getPublicKey() {
return mPublicKey;
}
long getBinaryResourcesModifiedTime() {
try {
String packageName = this.mContext.getPackageName();
int codePushApkBuildTimeId = this.mContext.getResources().getIdentifier(CodePushConstants.CODE_PUSH_APK_BUILD_TIME_KEY, "string", packageName);
// replace double quotes needed for correct restoration of long value from strings.xml
// https://github.com/microsoft/cordova-plugin-code-push/issues/264
String codePushApkBuildTime = this.mContext.getResources().getString(codePushApkBuildTimeId).replaceAll("\"","");
return Long.parseLong(codePushApkBuildTime);
} catch (Exception e) {
throw new CodePushUnknownException("Error in getting binary resources modified time", e);
}
}
public String getPackageFolder() {
JSONObject codePushLocalPackage = mUpdateManager.getCurrentPackage();
if (codePushLocalPackage == null) {
return null;
}
return mUpdateManager.getPackageFolderPath(codePushLocalPackage.optString("packageHash"));
}
@Deprecated
public static String getBundleUrl() {
return getJSBundleFile();
}
@Deprecated
public static String getBundleUrl(String assetsBundleFileName) {
return getJSBundleFile(assetsBundleFileName);
}
public Context getContext() {
return mContext;
}
public String getDeploymentKey() {
return mDeploymentKey;
}
public static String getJSBundleFile() {
return CodePush.getJSBundleFile(CodePushConstants.DEFAULT_JS_BUNDLE_NAME);
}
public static String getJSBundleFile(String assetsBundleFileName) {
if (mCurrentInstance == null) {
throw new CodePushNotInitializedException("A CodePush instance has not been created yet. Have you added it to your app's list of ReactPackages?");
}
return mCurrentInstance.getJSBundleFileInternal(assetsBundleFileName);
}
public String getJSBundleFileInternal(String assetsBundleFileName) {
this.mAssetsBundleFileName = assetsBundleFileName;
String binaryJsBundleUrl = CodePushConstants.ASSETS_BUNDLE_PREFIX + assetsBundleFileName;
String packageFilePath = null;
try {
packageFilePath = mUpdateManager.getCurrentPackageBundlePath(this.mAssetsBundleFileName);
} catch (CodePushMalformedDataException e) {
// We need to recover the app in case 'codepush.json' is corrupted
CodePushUtils.log(e.getMessage());
clearUpdates();
}
if (packageFilePath == null) {
// There has not been any downloaded updates.
CodePushUtils.logBundleUrl(binaryJsBundleUrl);
sIsRunningBinaryVersion = true;
return binaryJsBundleUrl;
}
JSONObject packageMetadata = this.mUpdateManager.getCurrentPackage();
if (isPackageBundleLatest(packageMetadata)) {
CodePushUtils.logBundleUrl(packageFilePath);
sIsRunningBinaryVersion = false;
return packageFilePath;
} else {
// The binary version is newer.
this.mDidUpdate = false;
if (!this.mIsDebugMode || hasBinaryVersionChanged(packageMetadata)) {
this.clearUpdates();
}
CodePushUtils.logBundleUrl(binaryJsBundleUrl);
sIsRunningBinaryVersion = true;
return binaryJsBundleUrl;
}
}
public String getServerUrl() {
return mServerUrl;
}
void initializeUpdateAfterRestart() {
// Reset the state which indicates that
// the app was just freshly updated.
mDidUpdate = false;
JSONObject pendingUpdate = mSettingsManager.getPendingUpdate();
if (pendingUpdate != null) {
JSONObject packageMetadata = null;
try {
packageMetadata = this.mUpdateManager.getCurrentPackage();
} catch (CodePushMalformedDataException e) {
// We need to recover the app in case 'codepush.json' is corrupted
CodePushUtils.log(e);
clearUpdates();
return;
}
if (packageMetadata == null || !isPackageBundleLatest(packageMetadata) && hasBinaryVersionChanged(packageMetadata)) {
CodePushUtils.log("Skipping initializeUpdateAfterRestart(), binary version is newer");
return;
}
try {
boolean updateIsLoading = pendingUpdate.getBoolean(CodePushConstants.PENDING_UPDATE_IS_LOADING_KEY);
if (updateIsLoading) {
// Pending update was initialized, but notifyApplicationReady was not called.
// Therefore, deduce that it is a broken update and rollback.
CodePushUtils.log("Update did not finish loading the last time, rolling back to a previous version.");
sNeedToReportRollback = true;
rollbackPackage();
} else {
// There is in fact a new update running for the first
// time, so update the local state to ensure the client knows.
mDidUpdate = true;
// Mark that we tried to initialize the new update, so that if it crashes,
// we will know that we need to rollback when the app next starts.
mSettingsManager.savePendingUpdate(pendingUpdate.getString(CodePushConstants.PENDING_UPDATE_HASH_KEY),
/* isLoading */true);
}
} catch (JSONException e) {
// Should not happen.
throw new CodePushUnknownException("Unable to read pending update metadata stored in SharedPreferences", e);
}
}
}
void invalidateCurrentInstance() {
mCurrentInstance = null;
}
boolean isDebugMode() {
return mIsDebugMode;
}
boolean isRunningBinaryVersion() {
return sIsRunningBinaryVersion;
}
private boolean isPackageBundleLatest(JSONObject packageMetadata) {
try {
Long binaryModifiedDateDuringPackageInstall = null;
String binaryModifiedDateDuringPackageInstallString = packageMetadata.optString(CodePushConstants.BINARY_MODIFIED_TIME_KEY, null);
if (binaryModifiedDateDuringPackageInstallString != null) {
binaryModifiedDateDuringPackageInstall = Long.parseLong(binaryModifiedDateDuringPackageInstallString);
}
String packageAppVersion = packageMetadata.optString("appVersion", null);
long binaryResourcesModifiedTime = this.getBinaryResourcesModifiedTime();
return binaryModifiedDateDuringPackageInstall != null &&
binaryModifiedDateDuringPackageInstall == binaryResourcesModifiedTime &&
(isUsingTestConfiguration() || sAppVersion.equals(packageAppVersion));
} catch (NumberFormatException e) {
throw new CodePushUnknownException("Error in reading binary modified date from package metadata", e);
}
}
private boolean hasBinaryVersionChanged(JSONObject packageMetadata) {
String packageAppVersion = packageMetadata.optString("appVersion", null);
return !sAppVersion.equals(packageAppVersion);
}
boolean needToReportRollback() {
return sNeedToReportRollback;
}
public static void overrideAppVersion(String appVersionOverride) {
sAppVersion = appVersionOverride;
}
private void rollbackPackage() {
JSONObject failedPackage = mUpdateManager.getCurrentPackage();
mSettingsManager.saveFailedUpdate(failedPackage);
mUpdateManager.rollbackPackage();
mSettingsManager.removePendingUpdate();
}
public void setNeedToReportRollback(boolean needToReportRollback) {
CodePush.sNeedToReportRollback = needToReportRollback;
}
/* The below 3 methods are used for running tests.*/
public static boolean isUsingTestConfiguration() {
return sTestConfigurationFlag;
}
public void setDeploymentKey(String deploymentKey) {
mDeploymentKey = deploymentKey;
}
public static void setUsingTestConfiguration(boolean shouldUseTestConfiguration) {
sTestConfigurationFlag = shouldUseTestConfiguration;
}
public void clearUpdates() {
mUpdateManager.clearUpdates();
mSettingsManager.removePendingUpdate();
mSettingsManager.removeFailedUpdates();
}
public static void setReactInstanceHolder(ReactInstanceHolder reactInstanceHolder) {
mReactInstanceHolder = reactInstanceHolder;
}
public static void setReactHost(ReactHostHolder reactHostHolder) {
mReactHostHolder = reactHostHolder;
}
static ReactInstanceManager getReactInstanceManager() {
if (mReactInstanceHolder == null) {
return null;
}
return mReactInstanceHolder.getReactInstanceManager();
}
static ReactHost getReactHost() {
if (mReactHostHolder == null) {
return null;
}
return mReactHostHolder.getReactHost();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) {
CodePushNativeModule codePushModule = new CodePushNativeModule(reactApplicationContext, this, mUpdateManager, mTelemetryManager, mSettingsManager);
CodePushDialog dialogModule = new CodePushDialog(reactApplicationContext);
List<NativeModule> nativeModules = new ArrayList<>();
nativeModules.add(codePushModule);
nativeModules.add(dialogModule);
return nativeModules;
}
// Deprecated in RN v0.47.
public List<Class<? extends JavaScriptModule>> createJSModules() {
return new ArrayList<>();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) {
return new ArrayList<>();
}
}