forked from microsoft/react-native-code-push
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodePush.m
336 lines (287 loc) · 11.8 KB
/
CodePush.m
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
#import "RCTBridgeModule.h"
#import "RCTEventDispatcher.h"
#import "RCTConvert.h"
#import "RCTRootView.h"
#import "RCTUtils.h"
#import "CodePush.h"
@implementation CodePush {
BOOL _resumablePendingUpdateAvailable;
}
RCT_EXPORT_MODULE()
BOOL didUpdate = NO;
NSTimer *_timer;
BOOL usingTestFolder = NO;
NSString * const FailedUpdatesKey = @"CODE_PUSH_FAILED_UPDATES";
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
NSString * const PendingUpdateHashKey = @"hash";
NSString * const PendingUpdateRollbackTimeoutKey = @"rollbackTimeout";
@synthesize bridge = _bridge;
// Public Obj-C API
+ (NSString *)getDocumentsDirectory
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return documentsDirectory;
}
+ (NSURL *)getBundleUrl
{
NSError *error;
NSString *packageFile = [CodePushPackage getCurrentPackageBundlePath:&error];
NSURL *binaryJsBundleUrl = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
if (error || !packageFile)
{
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];
if ([binaryDate compare:packageDate] == NSOrderedAscending) {
// Return package file because it is newer than the app store binary's JS bundle
return [[NSURL alloc] initFileURLWithPath:packageFile];
} else {
return binaryJsBundleUrl;
}
}
// Internal API methods
- (void)cancelRollbackTimer
{
dispatch_async(dispatch_get_main_queue(), ^{
[_timer invalidate];
});
}
- (void)checkForPendingUpdate:(BOOL)needsRestart
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSDictionary *pendingUpdate = [preferences objectForKey:PendingUpdateKey];
if (pendingUpdate) {
NSError *error;
NSString *pendingHash = pendingUpdate[PendingUpdateHashKey];
NSString *currentHash = [CodePushPackage getCurrentPackageHash:&error];
// If the current hash is equivalent to the pending hash, then the app
// restart "picked up" the new update, but we need to kick off the
// rollback timer and ensure that the necessary state is setup.
if ([pendingHash isEqualToString:currentHash]) {
int rollbackTimeout = [pendingUpdate[PendingUpdateRollbackTimeoutKey] intValue];
[self initializeUpdateWithRollbackTimeout:rollbackTimeout needsRestart:needsRestart];
// Clear the pending update and sync
[preferences removeObjectForKey:PendingUpdateKey];
[preferences synchronize];
}
}
});
}
- (void)checkForPendingUpdateDuringResume
{
// In order to ensure that CodePush doesn't impact the app's
// resume experience, we're using a simple boolean check to
// check whether we need to restart, before reading the defaults store
if (_resumablePendingUpdateAvailable) {
[self checkForPendingUpdate:YES];
}
}
- (NSDictionary *)constantsToExport
{
// Export the values of the CodePushRestartMode enum
// so that the script-side can easily stay in sync
return @{ @"codePushRestartModeNone": @(CodePushRestartModeNone),
@"codePushRestartModeImmediate": @(CodePushRestartModeImmediate),
@"codePushRestartModeOnNextResume": @(CodePushRestartModeOnNextResume)
};
};
- (void)dealloc
{
// Ensure the global resume handler is cleared, so that
// this object isn't kept alive unnecessarily
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (CodePush *)init
{
self = [super init];
if (self) {
// Do an async check to see whether
// we need to start the rollback timer
// due to a pending update being applied at start
[self checkForPendingUpdate:NO];
// Register for app resume notifications so that we
// can check for pending updates which support "restart on resume"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(checkForPendingUpdateDuringResume)
name:UIApplicationWillEnterForegroundNotification
object:[UIApplication sharedApplication]];
}
return self;
}
- (void)initializeUpdateWithRollbackTimeout:(int)rollbackTimeout
needsRestart:(BOOL)needsRestart
{
didUpdate = YES;
if (needsRestart) {
[self loadBundle];
}
if (0 != rollbackTimeout) {
dispatch_async(dispatch_get_main_queue(), ^{
[self startRollbackTimer:rollbackTimeout];
});
}
}
- (BOOL)isFailedHash:(NSString*)packageHash
{
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSMutableArray *failedUpdates = [preferences objectForKey:FailedUpdatesKey];
return (failedUpdates != nil && [failedUpdates containsObject:packageHash]);
}
- (void)loadBundle
{
// Reset the runtime's bundle to be
// the latest URL, and then force a refresh
_bridge.bundleURL = [CodePush getBundleUrl];
[_bridge reload];
}
- (void)rollbackPackage
{
NSError *error;
NSString *packageHash = [CodePushPackage getCurrentPackageHash:&error];
// Write the current package's hash to the "failed list"
[self saveFailedUpdate:packageHash];
// Do the actual rollback and then
// refresh the app with the previous package
[CodePushPackage rollbackPackage];
[self loadBundle];
}
- (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];
}
- (void)savePendingUpdate:(NSString *)packageHash
rollbackTimeout:(int)rollbackTimeout
{
// Since we're not restarting, we need to store the fact that the update
// was applied, but hasn't yet become "active".
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSDictionary *pendingUpdate = [[NSDictionary alloc] initWithObjectsAndKeys:
packageHash,PendingUpdateHashKey,
[NSNumber numberWithInt:rollbackTimeout],PendingUpdateRollbackTimeoutKey, nil];
[preferences setObject:pendingUpdate forKey:PendingUpdateKey];
[preferences synchronize];
}
- (void)startRollbackTimer:(int)rollbackTimeout
{
double timeoutInSeconds = rollbackTimeout / 1000;
_timer = [NSTimer scheduledTimerWithTimeInterval:timeoutInSeconds
target:self
selector:@selector(rollbackPackage)
userInfo:nil
repeats:NO];
}
// JavaScript-exported module methods
RCT_EXPORT_METHOD(applyUpdate:(NSDictionary*)updatePackage
rollbackTimeout:(int)rollbackTimeout
restartMode:(CodePushRestartMode)restartMode
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *error;
[CodePushPackage applyPackage:updatePackage
error:&error];
if (error) {
reject(error);
} else {
if (restartMode == CodePushRestartModeImmediate) {
[self initializeUpdateWithRollbackTimeout:rollbackTimeout needsRestart:YES];
} else {
_resumablePendingUpdateAvailable = (restartMode == CodePushRestartModeOnNextResume);
[self savePendingUpdate:updatePackage[@"packageHash"]
rollbackTimeout:rollbackTimeout];
}
}
});
}
RCT_EXPORT_METHOD(downloadUpdate:(NSDictionary*)updatePackage
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
[CodePushPackage downloadPackage:updatePackage
progressCallback:^(long expectedContentLength, long receivedContentLength) {
[self.bridge.eventDispatcher
sendAppEventWithName:@"CodePushDownloadProgress"
body:@{
@"totalBytes":[NSNumber numberWithLong:expectedContentLength],
@"receivedBytes":[NSNumber numberWithLong:receivedContentLength]
}];
}
doneCallback:^{
NSError *err;
NSDictionary *newPackage = [CodePushPackage
getPackage:updatePackage[@"packageHash"]
error:&err];
if (err) {
return reject(err);
}
resolve(newPackage);
}
failCallback:^(NSError *err) {
reject(err);
}];
}
RCT_EXPORT_METHOD(getConfiguration:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
resolve([CodePushConfig getConfiguration]);
}
RCT_EXPORT_METHOD(getCurrentPackage:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error;
NSDictionary *package = [CodePushPackage getCurrentPackage:&error];
if (error) {
reject(error);
} else {
resolve(package);
}
});
}
RCT_EXPORT_METHOD(isFailedUpdate:(NSString *)packageHash
resolve:(RCTPromiseResolveBlock)resolve
reject:(RCTPromiseRejectBlock)reject)
{
BOOL isFailedHash = [self isFailedHash:packageHash];
resolve(@(isFailedHash));
}
RCT_EXPORT_METHOD(isFirstRun:(NSString *)packageHash
resolve:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSError *error;
BOOL isFirstRun = didUpdate
&& nil != packageHash
&& [packageHash length] > 0
&& [packageHash isEqualToString:[CodePushPackage getCurrentPackageHash:&error]];
resolve(@(isFirstRun));
}
RCT_EXPORT_METHOD(notifyApplicationReady:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
[self cancelRollbackTimer];
resolve([NSNull null]);
}
RCT_EXPORT_METHOD(setUsingTestFolder:(BOOL)shouldUseTestFolder)
{
usingTestFolder = shouldUseTestFolder;
}
@end