forked from microsoft/react-native-code-push
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodePush.m
More file actions
495 lines (432 loc) · 17.7 KB
/
CodePush.m
File metadata and controls
495 lines (432 loc) · 17.7 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
#import "RCTBridgeModule.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTRootView.h"
#import "RCTUtils.h"
#import "CodePush.h"
@implementation CodePush {
BOOL _hasResumeListener;
BOOL _isFirstRunAfterUpdate;
}
RCT_EXPORT_MODULE()
static BOOL testConfigurationFlag = NO;
// These keys represent the names we use to store data in NSUserDefaults
static NSString *const FailedUpdatesKey = @"CODE_PUSH_FAILED_UPDATES";
static NSString *const PendingUpdateKey = @"CODE_PUSH_PENDING_UPDATE";
// These keys are already "namespaced" by the PendingUpdateKey, so
// their values don't need to be obfuscated to prevent collision with app data
static NSString *const PendingUpdateHashKey = @"hash";
static NSString *const PendingUpdateIsLoadingKey = @"isLoading";
// These keys are used to inspect/augment the metadata
// that is associated with an update's package.
static NSString *const PackageHashKey = @"packageHash";
static NSString *const PackageIsPendingKey = @"isPending";
@synthesize bridge = _bridge;
// Public Obj-C API (see header for method comments)
+ (NSURL *)bundleURL
{
return [self bundleURLForResource:@"main"];
}
+ (NSURL *)bundleURLForResource:(NSString *)resourceName
{
return [self bundleURLForResource:resourceName
withExtension:@"jsbundle"];
}
+ (NSURL *)bundleURLForResource:(NSString *)resourceName
withExtension:(NSString *)resourceExtension
{
NSError *error;
NSString *packageFile = [CodePushPackage getCurrentPackageBundlePath:&error];
NSURL *binaryJsBundleUrl = [[NSBundle mainBundle] URLForResource:resourceName withExtension:resourceExtension];
NSString *logMessageFormat = @"Loading JS bundle from %@";
if (error || !packageFile) {
NSLog(logMessageFormat, binaryJsBundleUrl);
return binaryJsBundleUrl;
}
NSDictionary *binaryFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[binaryJsBundleUrl path] error:nil];
NSDictionary *appFileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:packageFile error:nil];
NSDate *binaryDate = [binaryFileAttributes objectForKey:NSFileModificationDate];
NSDate *packageDate = [appFileAttribs objectForKey:NSFileModificationDate];
NSString *binaryAppVersion = [[CodePushConfig current] appVersion];
NSDictionary *currentPackageMetadata = [CodePushPackage getCurrentPackage:&error];
if (error || !currentPackageMetadata) {
NSLog(logMessageFormat, binaryJsBundleUrl);
return binaryJsBundleUrl;
}
NSString *packageAppVersion = [currentPackageMetadata objectForKey:@"appVersion"];
if ([binaryDate compare:packageDate] == NSOrderedAscending && [binaryAppVersion isEqualToString:packageAppVersion]) {
// Return package file because it is newer than the app store binary's JS bundle
NSURL *packageUrl = [[NSURL alloc] initFileURLWithPath:packageFile];
NSLog(logMessageFormat, packageUrl);
return packageUrl;
} else {
#ifndef DEBUG
[CodePush clearUpdates];
#endif
NSLog(logMessageFormat, binaryJsBundleUrl);
return binaryJsBundleUrl;
}
}
+ (NSString *)getApplicationSupportDirectory
{
NSString *applicationSupportDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return applicationSupportDirectory;
}
/*
* This returns a boolean value indicating whether CodePush has
* been set to run under a test configuration.
*/
+ (BOOL)isUsingTestConfiguration
{
return testConfigurationFlag;
}
/*
* This is used to enable an environment in which tests can be run.
* Specifically, it flips a boolean flag that causes bundles to be
* saved to a test folder and enables the ability to modify
* installed bundles on the fly from JavaScript.
*/
+ (void)setUsingTestConfiguration:(BOOL)shouldUseTestConfiguration
{
testConfigurationFlag = shouldUseTestConfiguration;
}
/*
* WARNING: This cleans up all downloaded and pending updates.
*/
+ (void)clearUpdates
{
[CodePushPackage clearUpdates];
[self removePendingUpdate];
[self removeFailedUpdates];
}
// Private API methods
/*
* This method is used by the React Native bridge to allow
* our plugin to expose constants to the JS-side. In our case
* we're simply exporting enum values so that the JS and Native
* sides of the plugin can be in sync.
*/
- (NSDictionary *)constantsToExport
{
// Export the values of the CodePushInstallMode enum
// so that the script-side can easily stay in sync
return @{
@"codePushInstallModeOnNextRestart":@(CodePushInstallModeOnNextRestart),
@"codePushInstallModeImmediate": @(CodePushInstallModeImmediate),
@"codePushInstallModeOnNextResume": @(CodePushInstallModeOnNextResume)
};
};
- (void)dealloc
{
// Ensure the global resume handler is cleared, so that
// this object isn't kept alive unnecessarily
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)init
{
self = [super init];
if (self) {
[self initializeUpdateAfterRestart];
}
return self;
}
/*
* This method is used when the app is started to either
* initialize a pending update or rollback a faulty update
* to the previous version.
*/
- (void)initializeUpdateAfterRestart
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSDictionary *pendingUpdate = [preferences objectForKey:PendingUpdateKey];
if (pendingUpdate) {
_isFirstRunAfterUpdate = YES;
BOOL updateIsLoading = [pendingUpdate[PendingUpdateIsLoadingKey] boolValue];
if (updateIsLoading) {
// Pending update was initialized, but notifyApplicationReady was not called.
// Therefore, deduce that it is a broken update and rollback.
NSLog(@"Update did not finish loading the last time, rolling back to a previous version.");
[self rollbackPackage];
} else {
// 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.
[self savePendingUpdate:pendingUpdate[PendingUpdateHashKey]
isLoading:YES];
}
}
}
/*
* This method checks to see whether a specific package hash
* has previously failed installation.
*/
- (BOOL)isFailedHash:(NSString*)packageHash
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSMutableArray *failedUpdates = [preferences objectForKey:FailedUpdatesKey];
return (failedUpdates != nil && [failedUpdates containsObject:packageHash]);
}
/*
* This method checks to see whether a specific package hash
* represents a downloaded and installed update, that hasn't
* been applied yet via an app restart.
*/
- (BOOL)isPendingUpdate:(NSString*)packageHash
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSDictionary *pendingUpdate = [preferences objectForKey:PendingUpdateKey];
// If there is a pending update whose "state" isn't loading, then we consider it "pending".
// Additionally, if a specific hash was provided, we ensure it matches that of the pending update.
BOOL updateIsPending = pendingUpdate &&
[pendingUpdate[PendingUpdateIsLoadingKey] boolValue] == NO &&
(!packageHash || [pendingUpdate[PendingUpdateHashKey] isEqualToString:packageHash]);
return updateIsPending;
}
/*
* This method updates the React Native bridge's bundle URL
* to point at the latest CodePush update, and then restarts
* the bridge. This isn't meant to be called directly.
*/
- (void)loadBundle
{
// This needs to be async dispatched because the _bridge is not set on init
// when the app first starts, therefore rollbacks will not take effect.
dispatch_async(dispatch_get_main_queue(), ^{
// If the current bundle URL is using http(s), then assume the dev
// is debugging and therefore, shouldn't be redirected to a local
// file (since Chrome wouldn't support it). Otherwise, update
// the current bundle URL to point at the latest update
if ([CodePush isUsingTestConfiguration] || ![_bridge.bundleURL.scheme hasPrefix:@"http"]) {
[_bridge setValue:[CodePush bundleURL] forKey:@"bundleURL"];
}
[_bridge reload];
});
}
/*
* This method is used when an update has failed installation
* and the app needs to be rolled back to the previous bundle.
* This method is automatically called when the rollback timer
* expires without the app indicating whether the update succeeded,
* and therefore, it shouldn't be called directly.
*/
- (void)rollbackPackage
{
NSError *error;
NSString *packageHash = [CodePushPackage getCurrentPackageHash:&error];
// Write the current package's hash to the "failed list"
[self saveFailedUpdate:packageHash];
// Rollback to the previous version and de-register the new update
[CodePushPackage rollbackPackage];
[CodePush removePendingUpdate];
[self loadBundle];
}
/*
* When an update failed to apply, this method can be called
* to store its hash so that it can be ignored on future
* attempts to check the server for an update.
*/
- (void)saveFailedUpdate:(NSString *)packageHash
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSMutableArray *failedUpdates = [preferences objectForKey:FailedUpdatesKey];
if (failedUpdates == nil) {
failedUpdates = [[NSMutableArray alloc] init];
} else {
// The NSUserDefaults sytem always returns immutable
// objects, regardless if you stored something mutable.
failedUpdates = [failedUpdates mutableCopy];
}
[failedUpdates addObject:packageHash];
[preferences setObject:failedUpdates forKey:FailedUpdatesKey];
[preferences synchronize];
}
/*
* This method is used to clear away failed updates in the event that
* a new app store binary is installed.
*/
+ (void)removeFailedUpdates
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences removeObjectForKey:FailedUpdatesKey];
[preferences synchronize];
}
/*
* This method is used to register the fact that a pending
* update succeeded and therefore can be removed.
*/
+ (void)removePendingUpdate
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences removeObjectForKey:PendingUpdateKey];
[preferences synchronize];
}
/*
* When an update is installed whose mode isn't IMMEDIATE, this method
* can be called to store the pending update's metadata (e.g. packageHash)
* so that it can be used when the actual update application occurs at a later point.
*/
- (void)savePendingUpdate:(NSString *)packageHash
isLoading:(BOOL)isLoading
{
// Since we're not restarting, we need to store the fact that the update
// was installed, but hasn't yet become "active".
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSDictionary *pendingUpdate = [[NSDictionary alloc] initWithObjectsAndKeys:
packageHash,PendingUpdateHashKey,
[NSNumber numberWithBool:isLoading],PendingUpdateIsLoadingKey, nil];
[preferences setObject:pendingUpdate forKey:PendingUpdateKey];
[preferences synchronize];
}
// JavaScript-exported module methods
/*
* This is native-side of the RemotePackage.download method
*/
RCT_EXPORT_METHOD(downloadUpdate:(NSDictionary*)updatePackage
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
[CodePushPackage downloadPackage:updatePackage
// The download is progressing forward
progressCallback:^(long long expectedContentLength, long long receivedContentLength) {
// Notify the script-side about the progress
[self.bridge.eventDispatcher
sendDeviceEventWithName:@"CodePushDownloadProgress"
body:@{
@"totalBytes":[NSNumber numberWithLongLong:expectedContentLength],
@"receivedBytes":[NSNumber numberWithLongLong:receivedContentLength]
}];
}
// The download completed
doneCallback:^{
NSError *err;
NSDictionary *newPackage = [CodePushPackage getPackage:updatePackage[PackageHashKey] error:&err];
if (err) {
return reject(err);
}
resolve(newPackage);
}
// The download failed
failCallback:^(NSError *err) {
reject(err);
}];
}
/*
* This is the native side of the CodePush.getConfiguration method. It isn't
* currently exposed via the "react-native-code-push" module, and is used
* internally only by the CodePush.checkForUpdate method in order to get the
* app version, as well as the deployment key that was configured in the Info.plist file.
*/
RCT_EXPORT_METHOD(getConfiguration:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
resolve([[CodePushConfig current] configuration]);
}
/*
* This method is the native side of the CodePush.getCurrentPackage method.
*/
RCT_EXPORT_METHOD(getCurrentPackage:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error;
NSMutableDictionary *package = [[CodePushPackage getCurrentPackage:&error] mutableCopy];
if (error) {
reject(error);
}
// Add the "isPending" virtual property to the package at this point, so that
// the script-side doesn't need to immediately call back into native to populate it.
BOOL isPendingUpdate = [self isPendingUpdate:[package objectForKey:PackageHashKey]];
[package setObject:@(isPendingUpdate) forKey:PackageIsPendingKey];
resolve(package);
});
}
/*
* This method is the native side of the LocalPackage.install method.
*/
RCT_EXPORT_METHOD(installUpdate:(NSDictionary*)updatePackage
installMode:(CodePushInstallMode)installMode
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *error;
[CodePushPackage installPackage:updatePackage
error:&error];
if (error) {
reject(error);
} else {
[self savePendingUpdate:updatePackage[PackageHashKey]
isLoading:NO];
if (installMode == CodePushInstallModeOnNextResume && !_hasResumeListener) {
// Ensure we do not add the listener twice.
// Register for app resume notifications so that we
// can check for pending updates which support "restart on resume"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(loadBundle)
name:UIApplicationWillEnterForegroundNotification
object:[UIApplication sharedApplication]];
_hasResumeListener = YES;
}
// Signal to JS that the update has been applied.
resolve(nil);
}
});
}
/*
* This method isn't publicly exposed via the "react-native-code-push"
* module, and is only used internally to populate the RemotePackage.failedInstall property.
*/
RCT_EXPORT_METHOD(isFailedUpdate:(NSString *)packageHash
resolve:(RCTPromiseResolveBlock)resolve
reject:(RCTPromiseRejectBlock)reject)
{
BOOL isFailedHash = [self isFailedHash:packageHash];
resolve(@(isFailedHash));
}
/*
* This method isn't publicly exposed via the "react-native-code-push"
* module, and is only used internally to populate the LocalPackage.isFirstRun property.
*/
RCT_EXPORT_METHOD(isFirstRun:(NSString *)packageHash
resolve:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSError *error;
BOOL isFirstRun = _isFirstRunAfterUpdate
&& nil != packageHash
&& [packageHash length] > 0
&& [packageHash isEqualToString:[CodePushPackage getCurrentPackageHash:&error]];
resolve(@(isFirstRun));
}
/*
* This method is the native side of the CodePush.notifyApplicationReady() method.
*/
RCT_EXPORT_METHOD(notifyApplicationReady:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
[CodePush removePendingUpdate];
resolve([NSNull null]);
}
/*
* This method is the native side of the CodePush.restartApp() method.
*/
RCT_EXPORT_METHOD(restartApp:(BOOL)onlyIfUpdateIsPending)
{
// If this is an unconditional restart request, or there
// is current pending update, then reload the app.
if (!onlyIfUpdateIsPending || [self isPendingUpdate:nil]) {
[self loadBundle];
}
}
/*
* This method is the native side of the CodePush.downloadAndReplaceCurrentBundle()
* method, which replaces the current bundle with the one downloaded from
* removeBundleUrl. It is only to be used during tests and no-ops if the test
* configuration flag is not set.
*/
RCT_EXPORT_METHOD(downloadAndReplaceCurrentBundle:(NSString *)remoteBundleUrl)
{
if ([CodePush isUsingTestConfiguration]) {
[CodePushPackage downloadAndReplaceCurrentBundle:remoteBundleUrl];
}
}
@end