Repository navigation
Expand file tree
/
Copy pathSMBundle.m
More file actions
477 lines (422 loc) · 15.8 KB
/
Copy pathSMBundle.m
File metadata and controls
477 lines (422 loc) · 15.8 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
/*
* Copyright 2015-present wequick.net
*
* 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.
*/
#import "SMBundle.h"
#import "SMFileManager.h"
#import "ZipArchive.h"
#import "Small.h"
#import "SMBundleFetcher.h"
#import "SMBundleLauncher.h"
NSString *const SMBundleManifestName = @"bundle.json";
NSString *const SMBundleLoaderErrorDomain = @"SMBundleLoaderError";
NSString *const SMBundlesKey = @"bundles";
NSInteger const SMBundleLoaderMissingFileError = 1;
NSInteger const SMBundleLoaderFormatError = 2;
NSInteger const SMBundleLoaderUnknownVersionError = 3;
static NSMutableArray *kBundleLaunchers;
static NSMutableArray *kLaunchableBundles;
static void (^kLoadingComplection)(void);
static NSMutableDictionary *kBundleDownloadPaths;
static NSString *kBaseUrl;
static NSArray *kRegisteredBundles;
static NSArray *kDownloadBundles;
@interface SMBundle ()
{
SMBundleLauncher *_applicableLauncher;
}
@end
@implementation SMBundle
+ (instancetype)bundleForName:(NSString *)name
{
if (kLaunchableBundles == nil) return nil;
for (SMBundle *bundle in kLaunchableBundles) {
if ([bundle.pkg isEqualToString:name]) return bundle;
}
return nil;
}
+ (void)setBaseUrl:(NSString *)url
{
kBaseUrl = url;
}
+ (void)loadLaunchableBundlesWithComplection:(void (^)(void))complection
{
kLoadingComplection = complection;
NSError *error = nil;
[self loadManifestWithPath:[SMFileManager documentBundlesPath] error:&error];
if (error) {
[self loadManifestWithPath:[SMFileManager mainBundlesPath] error:&error];
}
}
+ (NSArray *)allLaunchableBundles
{
return kLaunchableBundles;
}
+ (instancetype)launchableBundleForURL:(NSURL *)url
{
for (SMBundle *bundle in kLaunchableBundles) {
// Look up the matched bundle
NSString *target;
NSString *query;
if ([bundle matchesRuleForURL:url target:&target query:&query]) {
[bundle setTarget:target];
[bundle setQuery:query];
return bundle;
}
}
NSString *scheme = url.scheme;
if ([scheme isEqualToString:@"http"] ||
[scheme isEqualToString:@"https"] ||
[scheme isEqualToString:@"file"]) {
// Downgrade to launch remote web page
SMBundle *bundle = [[SMBundle alloc] init];
[bundle setURL:url];
[bundle prepareForLaunch];
return bundle;
}
return nil;
}
+ (void)registerLauncher:(SMBundleLauncher *)launcher
{
if (kBundleLaunchers == nil) {
kBundleLaunchers = [[NSMutableArray alloc] init];
}
[kBundleLaunchers addObject:launcher];
}
+ (void)removeExternalBundles
{
NSString *documentBundlesPath = [SMFileManager documentBundlesPath];
if ([[SMFileManager defaultManager] fileExistsAtPath:documentBundlesPath]) {
[[SMFileManager defaultManager] removeItemAtPath:documentBundlesPath error:nil];
}
NSString *documentTempPath = [SMFileManager documentTempPath];
if ([[SMFileManager defaultManager] fileExistsAtPath:documentTempPath]) {
[[SMFileManager defaultManager] removeItemAtPath:documentTempPath error:nil];
}
}
- (BOOL)upgrade {
if (_applicableLauncher == nil) return NO;
// return [_applicableLauncher upgradeBundle:self];
if ([self isLoaded]) [self unload];
// Unzip the patch file
ZipArchive *zipArchive = [[ZipArchive alloc] init];
[zipArchive UnzipOpenFile:self.patchFile];
[zipArchive UnzipFileTo:[SMFileManager documentBundlesPath] overWrite:YES];
[zipArchive UnzipCloseFile];
[[NSFileManager defaultManager] removeItemAtPath:self.patchFile error:nil];
SMBundle *bundle = [[SMBundle alloc] initWithPath:self.patchPath];
NSDictionary *info = bundle.infoDictionary;
bundle.pkg = self.pkg;
bundle.uri = self.uri;
bundle.rules = self.rules;
bundle.type = self.type;
bundle.patchPath = self.patchPath;
bundle.patchFile = self.patchFile;
bundle.versionName = info[@"CFBundleShortVersionString"];
bundle.versionCode = info[@"CFBundleVersion"];
bundle->_applicableLauncher = _applicableLauncher;
[kLaunchableBundles removeObject:self];
[kLaunchableBundles addObject:bundle];
// UIViewController *v = [UIApplication sharedApplication].delegate.window.rootViewController;
// UITabBarController *tc = (id) v.presentedViewController;
// UINavigationController *nc = (id) tc.childViewControllers[0];
// UIViewController *v0 = nc.childViewControllers[0];
//
// Class cls = v0.class;
// NSString *name = NSStringFromClass(cls);
//
// // Hot swap
// [self unload];
// NSMutableArray *bundles = (NSMutableArray *)[NSBundle allFrameworks];
// [bundles removeObject:self];
//
// NSError *error;
// BOOL succeed = [bundle loadAndReturnError:&error];
// if (!succeed) {
// return NO;
// }
//
// Class cls2 = NSClassFromString(name); //cls;//[bundle classNamed:name];
//
// UIViewController *v0_ = [[cls2 alloc] initWithNibName:name bundle:bundle];
// v0_.tabBarItem = v0.tabBarItem;
//// [nc popToRootViewControllerAnimated:NO];
// dispatch_async(dispatch_get_main_queue(), ^{
// nc.viewControllers = @[v0_];
//// [nc popToRootViewControllerAnimated:NO];
//// [nc pushViewController:v0_ animated:YES];
// });
return YES;
}
- (BOOL)matchesRuleForURL:(NSURL *)url target:(NSString * __autoreleasing*)outTarget query:(NSString * __autoreleasing*)outQuery {
/* e.g.
* input
* - url: http://host/path/abc.html
* - self.uri: http://host/path
* - self.rules: abc.html -> AbcController
* output
* - target => AbcController
*/
NSString *query = [url query];
NSString *urlString = [url absoluteString];
NSRange range = [urlString rangeOfString:self.uri];
if (range.length == 0) return NO;
NSString *from = [urlString substringFromIndex:range.length];
NSString *excludedQueryFrom = nil;
if (query != nil) {
excludedQueryFrom = [from substringToIndex:[from length] - [query length] - 1];
}
for (NSString *key in self.rules) {
// TODO: regex match and replace
NSString *matchingTarget = nil;
if ([key isEqualToString:from]) {
matchingTarget = [self.rules objectForKey:key];
} else if (excludedQueryFrom != nil && [key isEqualToString:excludedQueryFrom]) {
matchingTarget = [self.rules objectForKey:key];
}
if (matchingTarget == nil) continue;
NSRange range = [matchingTarget rangeOfString:@"?"];
if (range.length != 0) {
*outTarget = [matchingTarget substringToIndex:range.location];
if (query != nil) {
*outQuery = [NSString stringWithFormat:@"%@&%@", query, [matchingTarget substringFromIndex:range.location + 1]];
} else {
*outQuery = [matchingTarget substringFromIndex:range.location + 1];
}
} else {
*outTarget = matchingTarget;
*outQuery = query;
}
return YES;
}
return NO;
}
- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
NSString *pkg = [dictionary objectForKey:@"pkg"];
if (pkg == nil || [pkg isEqualToString:@"main"]) {
if (self = [super initWithPath:[[NSBundle mainBundle] bundlePath]]) {
self.type = SMBundleTypeHost;
}
return self;
}
NSString *bundlePath = nil;
NSString *bundleSuffix = @"bundle";
SMBundleType bundleType = SMBundleTypeAssets;
if ([pkg rangeOfString:@".app."].location != NSNotFound
|| [pkg rangeOfString:@".lib."].location != NSNotFound) {
bundleSuffix = @"framework";
bundleType = SMBundleTypeApplication;
}
NSString *bundleName = [pkg stringByReplacingOccurrencesOfString:@"." withString:@"_"];
bundleName = [bundleName stringByAppendingFormat:@".%@", bundleSuffix];
NSString *documentBundlesPath = [SMFileManager documentBundlesPath];
NSString *patchFilePath = [SMFileManager tempBundlePathForName:bundleName];
if ([[NSFileManager defaultManager] fileExistsAtPath:patchFilePath]) {
// Unzip
NSString *unzipPath = documentBundlesPath;
ZipArchive *zipArchive = [[ZipArchive alloc] init];
[zipArchive UnzipOpenFile:patchFilePath];
[zipArchive UnzipFileTo:unzipPath overWrite:YES];
[zipArchive UnzipCloseFile];
[[NSFileManager defaultManager] removeItemAtPath:patchFilePath error:nil];
}
NSString *patchPath = [documentBundlesPath stringByAppendingPathComponent:bundleName];
NSString *builtinPath = [[SMFileManager mainBundlesPath] stringByAppendingPathComponent:bundleName];
NSArray *bundlePaths = @[patchPath, builtinPath];
for (NSString *aBundlePath in bundlePaths) {
if ([[NSFileManager defaultManager] fileExistsAtPath:aBundlePath]) {
bundlePath = aBundlePath;
break;
}
}
if (self = [super initWithPath:bundlePath]) {
NSDictionary *info = self.infoDictionary;
self.versionName = info[@"CFBundleShortVersionString"];
self.versionCode = info[@"CFBundleVersion"];
self.pkg = pkg;
self.type = bundleType;
_patchFile = patchFilePath;
_patchPath = patchPath;
// NSLog(@"-- %@: %@ %@", self.pkg, self.versionName, bundlePath);
[self initValuesWithDictionary:dictionary];
}
return self;
}
- (void)initValuesWithDictionary:(NSDictionary *)dictionary {
NSString *uri = [dictionary objectForKey:@"uri"];
self.uri = [Small absoluteUriFromUri:uri];
// UI routes to principal page
NSString *defaultTarget = @"";
NSMutableDictionary *rules = [[NSMutableDictionary alloc] init];
rules[@""] = defaultTarget;
rules[@".html"] = defaultTarget;
rules[@"/index"] = defaultTarget;
rules[@"/index.html"] = defaultTarget;
// UI routes to other pages
NSDictionary *userRules = [dictionary objectForKey:@"rules"];
if (userRules != nil) {
[rules setValuesForKeysWithDictionary:userRules];
}
self.rules = rules;
}
- (void)prepareForLaunch
{
for (SMBundleLauncher *launcher in kBundleLaunchers) {
if ([launcher resolveBundle:self]) {
_applicableLauncher = launcher;
if (self.versionCode != nil) {
[Small setBundleVersion:self.versionCode forBundleName:self.pkg];
}
break;
}
}
}
- (void)launchFromController:(UIViewController *)controller
{
if (_applicableLauncher == nil) {
[self prepareForLaunch];
}
if (_applicableLauncher != nil) {
[_applicableLauncher launchBundle:self fromController:controller];
}
}
- (UIViewController *)launcherController
{
if (_applicableLauncher == nil) {
[self prepareForLaunch];
}
if (_applicableLauncher != nil) {
return [_applicableLauncher controllerForBundle:self];
}
return nil;
}
- (NSURL *)URL
{
if (_URL == nil) {
NSURL *url = [self URLForResource:@"index" withExtension:@"html"];
if (_query != nil) {
url = [NSURL URLWithString:[NSString stringWithFormat:@"?%@", _query] relativeToURL:url];
}
return url;
}
return _URL;
}
- (UIImage *)icon
{
NSString *iconName = [[[self infoDictionary] objectForKey:@"CFBundleIconFiles"] objectAtIndex:0] ?: @"icon";
return SMBundleImage(self, iconName);
}
- (void)setQuery:(NSString *)query
{
_query = query;
if (query == nil) {
_queryParams = nil;
} else {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
NSArray *components = [query componentsSeparatedByString:@"&"];
for (NSString *component in components) {
NSRange range = [component rangeOfString:@"="];
if (range.length == 0) {
continue;
}
NSString *key = [component substringToIndex:range.location];
NSString *value = [component substringFromIndex:range.location + 1];
[params setObject:value forKey:key];
}
_queryParams = params;
}
}
//___________________________________________________________________________________________________
// Private
+ (BOOL)loadManifestWithPath:(NSString *)manifestPath error:(NSError *__autoreleasing*)error
{
NSString *manifestFile = [manifestPath stringByAppendingPathComponent:SMBundleManifestName];
NSData *manifestData = [NSData dataWithContentsOfFile:manifestFile];
if (manifestData == nil) {
if (error != nil) {
*error = [[NSError alloc] initWithDomain:SMBundleLoaderErrorDomain code:SMBundleLoaderMissingFileError userInfo:nil];
}
return NO;
}
NSDictionary *manifest = [NSJSONSerialization JSONObjectWithData:manifestData options:NSJSONReadingMutableLeaves error:error];
if (manifest == nil) {
if (error != nil) {
*error = [[NSError alloc] initWithDomain:SMBundleLoaderErrorDomain code:SMBundleLoaderFormatError userInfo:nil];
}
return NO;
}
// TODO: CRC
//...
NSString *version = [manifest objectForKey:@"version"];
return [self loadManifest:manifest forVersion:version error:error];
}
+ (BOOL)loadManifest:(NSDictionary *)manifest forVersion:(NSString *)version error:(NSError * __autoreleasing*)error
{
if ([version isEqualToString:@"1.0.0"]) {
NSArray *bundles = [manifest objectForKey:SMBundlesKey];
[self loadBundles:bundles];
return YES;
}
if (error != nil) {
*error = [[NSError alloc] initWithDomain:SMBundleLoaderErrorDomain code:SMBundleLoaderUnknownVersionError userInfo:nil];
}
return NO;
}
+ (void)loadBundles:(NSArray *)bundles {
if (kLoadingComplection == nil) {
[self syncLoadBundles:bundles];
} else {
dispatch_queue_t queue = dispatch_queue_create("net.wequick.small.BundleLoader", NULL);
dispatch_async(queue, ^{
[self syncLoadBundles:bundles];
dispatch_sync(dispatch_get_main_queue(), ^{
kLoadingComplection();
kLoadingComplection = nil;
});
});
}
}
+ (void)syncLoadBundles:(NSArray *)bundles {
// Treat all bundles as local
for (NSDictionary *desc in bundles) {
SMBundle *bundle = [[SMBundle alloc] initWithDictionary:desc];
if (bundle == nil) continue;
[bundle prepareForLaunch];
if (kLaunchableBundles == nil) {
kLaunchableBundles = [[NSMutableArray alloc] init];
}
[kLaunchableBundles addObject:bundle];
}
}
+ (long long)fileSizeWithURL:(NSURL *)url {
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"Head"];
NSURLResponse *res = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];
if (error != nil || res == nil) {
return 0;
}
return res.expectedContentLength;
}
+ (NSString *)zipPathForName:(NSString *)name {
NSString *basePath = [SMFileManager documentTempPath]; // NSTemporaryDirectory()
NSString *zipPath = [[basePath stringByAppendingPathComponent:name] stringByAppendingString:@".zip"];
return zipPath;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
NSLog(@"-- SMBundle setValue:%@ forUndefinedKey:%@", value, key);
}
@end