PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/platforms/ios/CordovaLib/Classes/Private/Plugins/CDVLocalStorage/CDVLocalStorage.m

https://gitlab.com/blocknotary/IonicInterviews
Objective C | 487 lines | 336 code | 98 blank | 53 comment | 58 complexity | 983e546cf9cafce697d48345b8ba63ec MD5 | raw file
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. #import "CDVLocalStorage.h"
  18. #import "CDV.h"
  19. @interface CDVLocalStorage ()
  20. @property (nonatomic, readwrite, strong) NSMutableArray* backupInfo; // array of CDVBackupInfo objects
  21. @property (nonatomic, readwrite, weak) id <UIWebViewDelegate> webviewDelegate;
  22. @end
  23. @implementation CDVLocalStorage
  24. @synthesize backupInfo, webviewDelegate;
  25. - (void)pluginInitialize
  26. {
  27. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResignActive)
  28. name:UIApplicationWillResignActiveNotification object:nil];
  29. BOOL cloudBackup = [@"cloud" isEqualToString : self.commandDelegate.settings[[@"BackupWebStorage" lowercaseString]]];
  30. self.backupInfo = [[self class] createBackupInfoWithCloudBackup:cloudBackup];
  31. }
  32. #pragma mark -
  33. #pragma mark Plugin interface methods
  34. + (NSMutableArray*)createBackupInfoWithTargetDir:(NSString*)targetDir backupDir:(NSString*)backupDir targetDirNests:(BOOL)targetDirNests backupDirNests:(BOOL)backupDirNests rename:(BOOL)rename
  35. {
  36. /*
  37. This "helper" does so much work and has so many options it would probably be clearer to refactor the whole thing.
  38. Basically, there are three database locations:
  39. 1. "Normal" dir -- LIB/<nested dires WebKit/LocalStorage etc>/<normal filenames>
  40. 2. "Caches" dir -- LIB/Caches/<normal filenames>
  41. 3. "Backup" dir -- DOC/Backups/<renamed filenames>
  42. And between these three, there are various migration paths, most of which only consider 2 of the 3, which is why this helper is based on 2 locations and has a notion of "direction".
  43. */
  44. NSMutableArray* backupInfo = [NSMutableArray arrayWithCapacity:3];
  45. NSString* original;
  46. NSString* backup;
  47. CDVBackupInfo* backupItem;
  48. // ////////// LOCALSTORAGE
  49. original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/file__0.localstorage":@"file__0.localstorage"];
  50. backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];
  51. backup = [backup stringByAppendingPathComponent:(rename ? @"localstorage.appdata.db" : @"file__0.localstorage")];
  52. backupItem = [[CDVBackupInfo alloc] init];
  53. backupItem.backup = backup;
  54. backupItem.original = original;
  55. backupItem.label = @"localStorage database";
  56. [backupInfo addObject:backupItem];
  57. // ////////// WEBSQL MAIN DB
  58. original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/Databases.db":@"Databases.db"];
  59. backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];
  60. backup = [backup stringByAppendingPathComponent:(rename ? @"websqlmain.appdata.db" : @"Databases.db")];
  61. backupItem = [[CDVBackupInfo alloc] init];
  62. backupItem.backup = backup;
  63. backupItem.original = original;
  64. backupItem.label = @"websql main database";
  65. [backupInfo addObject:backupItem];
  66. // ////////// WEBSQL DATABASES
  67. original = [targetDir stringByAppendingPathComponent:targetDirNests ? @"WebKit/LocalStorage/file__0":@"file__0"];
  68. backup = [backupDir stringByAppendingPathComponent:(backupDirNests ? @"WebKit/LocalStorage" : @"")];
  69. backup = [backup stringByAppendingPathComponent:(rename ? @"websqldbs.appdata.db" : @"file__0")];
  70. backupItem = [[CDVBackupInfo alloc] init];
  71. backupItem.backup = backup;
  72. backupItem.original = original;
  73. backupItem.label = @"websql databases";
  74. [backupInfo addObject:backupItem];
  75. return backupInfo;
  76. }
  77. + (NSMutableArray*)createBackupInfoWithCloudBackup:(BOOL)cloudBackup
  78. {
  79. // create backup info from backup folder to caches folder
  80. NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  81. NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  82. NSString* cacheFolder = [appLibraryFolder stringByAppendingPathComponent:@"Caches"];
  83. NSString* backupsFolder = [appDocumentsFolder stringByAppendingPathComponent:@"Backups"];
  84. // create the backups folder, if needed
  85. [[NSFileManager defaultManager] createDirectoryAtPath:backupsFolder withIntermediateDirectories:YES attributes:nil error:nil];
  86. [self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:backupsFolder] skip:!cloudBackup];
  87. return [self createBackupInfoWithTargetDir:cacheFolder backupDir:backupsFolder targetDirNests:NO backupDirNests:NO rename:YES];
  88. }
  89. + (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL*)URL skip:(BOOL)skip
  90. {
  91. NSError* error = nil;
  92. BOOL success = [URL setResourceValue:[NSNumber numberWithBool:skip] forKey:NSURLIsExcludedFromBackupKey error:&error];
  93. if (!success) {
  94. NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
  95. }
  96. return success;
  97. }
  98. + (BOOL)copyFrom:(NSString*)src to:(NSString*)dest error:(NSError* __autoreleasing*)error
  99. {
  100. NSFileManager* fileManager = [NSFileManager defaultManager];
  101. if (![fileManager fileExistsAtPath:src]) {
  102. NSString* errorString = [NSString stringWithFormat:@"%@ file does not exist.", src];
  103. if (error != NULL) {
  104. (*error) = [NSError errorWithDomain:kCDVLocalStorageErrorDomain
  105. code:kCDVLocalStorageFileOperationError
  106. userInfo:[NSDictionary dictionaryWithObject:errorString
  107. forKey:NSLocalizedDescriptionKey]];
  108. }
  109. return NO;
  110. }
  111. // generate unique filepath in temp directory
  112. CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
  113. CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);
  114. NSString* tempBackup = [[NSTemporaryDirectory() stringByAppendingPathComponent:(__bridge NSString*)uuidString] stringByAppendingPathExtension:@"bak"];
  115. CFRelease(uuidString);
  116. CFRelease(uuidRef);
  117. BOOL destExists = [fileManager fileExistsAtPath:dest];
  118. // backup the dest
  119. if (destExists && ![fileManager copyItemAtPath:dest toPath:tempBackup error:error]) {
  120. return NO;
  121. }
  122. // remove the dest
  123. if (destExists && ![fileManager removeItemAtPath:dest error:error]) {
  124. return NO;
  125. }
  126. // create path to dest
  127. if (!destExists && ![fileManager createDirectoryAtPath:[dest stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:error]) {
  128. return NO;
  129. }
  130. // copy src to dest
  131. if ([fileManager copyItemAtPath:src toPath:dest error:error]) {
  132. // success - cleanup - delete the backup to the dest
  133. if ([fileManager fileExistsAtPath:tempBackup]) {
  134. [fileManager removeItemAtPath:tempBackup error:error];
  135. }
  136. return YES;
  137. } else {
  138. // failure - we restore the temp backup file to dest
  139. [fileManager copyItemAtPath:tempBackup toPath:dest error:error];
  140. // cleanup - delete the backup to the dest
  141. if ([fileManager fileExistsAtPath:tempBackup]) {
  142. [fileManager removeItemAtPath:tempBackup error:error];
  143. }
  144. return NO;
  145. }
  146. }
  147. - (BOOL)shouldBackup
  148. {
  149. for (CDVBackupInfo* info in self.backupInfo) {
  150. if ([info shouldBackup]) {
  151. return YES;
  152. }
  153. }
  154. return NO;
  155. }
  156. - (BOOL)shouldRestore
  157. {
  158. for (CDVBackupInfo* info in self.backupInfo) {
  159. if ([info shouldRestore]) {
  160. return YES;
  161. }
  162. }
  163. return NO;
  164. }
  165. /* copy from webkitDbLocation to persistentDbLocation */
  166. - (void)backup:(CDVInvokedUrlCommand*)command
  167. {
  168. NSString* callbackId = command.callbackId;
  169. NSError* __autoreleasing error = nil;
  170. CDVPluginResult* result = nil;
  171. NSString* message = nil;
  172. for (CDVBackupInfo* info in self.backupInfo) {
  173. if ([info shouldBackup]) {
  174. [[self class] copyFrom:info.original to:info.backup error:&error];
  175. if (callbackId) {
  176. if (error == nil) {
  177. message = [NSString stringWithFormat:@"Backed up: %@", info.label];
  178. NSLog(@"%@", message);
  179. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
  180. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  181. } else {
  182. message = [NSString stringWithFormat:@"Error in CDVLocalStorage (%@) backup: %@", info.label, [error localizedDescription]];
  183. NSLog(@"%@", message);
  184. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
  185. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  186. }
  187. }
  188. }
  189. }
  190. }
  191. /* copy from persistentDbLocation to webkitDbLocation */
  192. - (void)restore:(CDVInvokedUrlCommand*)command
  193. {
  194. NSError* __autoreleasing error = nil;
  195. CDVPluginResult* result = nil;
  196. NSString* message = nil;
  197. for (CDVBackupInfo* info in self.backupInfo) {
  198. if ([info shouldRestore]) {
  199. [[self class] copyFrom:info.backup to:info.original error:&error];
  200. if (error == nil) {
  201. message = [NSString stringWithFormat:@"Restored: %@", info.label];
  202. NSLog(@"%@", message);
  203. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
  204. [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  205. } else {
  206. message = [NSString stringWithFormat:@"Error in CDVLocalStorage (%@) restore: %@", info.label, [error localizedDescription]];
  207. NSLog(@"%@", message);
  208. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
  209. [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  210. }
  211. }
  212. }
  213. }
  214. + (void)__fixupDatabaseLocationsWithBackupType:(NSString*)backupType
  215. {
  216. [self __verifyAndFixDatabaseLocations];
  217. [self __restoreLegacyDatabaseLocationsWithBackupType:backupType];
  218. }
  219. + (void)__verifyAndFixDatabaseLocations
  220. {
  221. NSBundle* mainBundle = [NSBundle mainBundle];
  222. NSString* bundlePath = [[mainBundle bundlePath] stringByDeletingLastPathComponent];
  223. NSString* bundleIdentifier = [[mainBundle infoDictionary] objectForKey:@"CFBundleIdentifier"];
  224. NSString* appPlistPath = [bundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"Library/Preferences/%@.plist", bundleIdentifier]];
  225. NSMutableDictionary* appPlistDict = [NSMutableDictionary dictionaryWithContentsOfFile:appPlistPath];
  226. BOOL modified = [[self class] __verifyAndFixDatabaseLocationsWithAppPlistDict:appPlistDict
  227. bundlePath:bundlePath
  228. fileManager:[NSFileManager defaultManager]];
  229. if (modified) {
  230. BOOL ok = [appPlistDict writeToFile:appPlistPath atomically:YES];
  231. [[NSUserDefaults standardUserDefaults] synchronize];
  232. NSLog(@"Fix applied for database locations?: %@", ok ? @"YES" : @"NO");
  233. }
  234. }
  235. + (BOOL)__verifyAndFixDatabaseLocationsWithAppPlistDict:(NSMutableDictionary*)appPlistDict
  236. bundlePath:(NSString*)bundlePath
  237. fileManager:(NSFileManager*)fileManager
  238. {
  239. NSString* libraryCaches = @"Library/Caches";
  240. NSString* libraryWebKit = @"Library/WebKit";
  241. NSArray* keysToCheck = [NSArray arrayWithObjects:
  242. @"WebKitLocalStorageDatabasePathPreferenceKey",
  243. @"WebDatabaseDirectory",
  244. nil];
  245. BOOL dirty = NO;
  246. for (NSString* key in keysToCheck) {
  247. NSString* value = [appPlistDict objectForKey:key];
  248. // verify key exists, and path is in app bundle, if not - fix
  249. if ((value != nil) && ![value hasPrefix:bundlePath]) {
  250. // the pathSuffix to use may be wrong - OTA upgrades from < 5.1 to 5.1 do keep the old path Library/WebKit,
  251. // while Xcode synced ones do change the storage location to Library/Caches
  252. NSString* newBundlePath = [bundlePath stringByAppendingPathComponent:libraryCaches];
  253. if (![fileManager fileExistsAtPath:newBundlePath]) {
  254. newBundlePath = [bundlePath stringByAppendingPathComponent:libraryWebKit];
  255. }
  256. [appPlistDict setValue:newBundlePath forKey:key];
  257. dirty = YES;
  258. }
  259. }
  260. return dirty;
  261. }
  262. + (void)__restoreLegacyDatabaseLocationsWithBackupType:(NSString*)backupType
  263. {
  264. // on iOS 6, if you toggle between cloud/local backup, you must move database locations. Default upgrade from iOS5.1 to iOS6 is like a toggle from local to cloud.
  265. NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  266. NSString* appDocumentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  267. NSMutableArray* backupInfo = [NSMutableArray arrayWithCapacity:0];
  268. if ([backupType isEqualToString:@"cloud"]) {
  269. #ifdef DEBUG
  270. NSLog(@"\n\nStarted backup to iCloud! Please be careful."
  271. "\nYour application might be rejected by Apple if you store too much data."
  272. "\nFor more information please read \"iOS Data Storage Guidelines\" at:"
  273. "\nhttps://developer.apple.com/icloud/documentation/data-storage/"
  274. "\nTo disable web storage backup to iCloud, set the BackupWebStorage preference to \"local\" in the Cordova config.xml file\n\n");
  275. #endif
  276. // We would like to restore old backups/caches databases to the new destination (nested in lib folder)
  277. [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:appLibraryFolder backupDir:[appDocumentsFolder stringByAppendingPathComponent:@"Backups"] targetDirNests:YES backupDirNests:NO rename:YES]];
  278. [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:appLibraryFolder backupDir:[appLibraryFolder stringByAppendingPathComponent:@"Caches"] targetDirNests:YES backupDirNests:NO rename:NO]];
  279. } else {
  280. // For ios6 local backups we also want to restore from Backups dir -- but we don't need to do that here, since the plugin will do that itself.
  281. [backupInfo addObjectsFromArray:[self createBackupInfoWithTargetDir:[appLibraryFolder stringByAppendingPathComponent:@"Caches"] backupDir:appLibraryFolder targetDirNests:NO backupDirNests:YES rename:NO]];
  282. }
  283. NSFileManager* manager = [NSFileManager defaultManager];
  284. for (CDVBackupInfo* info in backupInfo) {
  285. if ([manager fileExistsAtPath:info.backup]) {
  286. if ([info shouldRestore]) {
  287. NSLog(@"Restoring old webstorage backup. From: '%@' To: '%@'.", info.backup, info.original);
  288. [self copyFrom:info.backup to:info.original error:nil];
  289. }
  290. NSLog(@"Removing old webstorage backup: '%@'.", info.backup);
  291. [manager removeItemAtPath:info.backup error:nil];
  292. }
  293. }
  294. [[NSUserDefaults standardUserDefaults] setBool:[backupType isEqualToString:@"cloud"] forKey:@"WebKitStoreWebDataForBackup"];
  295. }
  296. #pragma mark -
  297. #pragma mark Notification handlers
  298. - (void)onResignActive
  299. {
  300. UIDevice* device = [UIDevice currentDevice];
  301. NSNumber* exitsOnSuspend = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIApplicationExitsOnSuspend"];
  302. BOOL isMultitaskingSupported = [device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported];
  303. if (exitsOnSuspend == nil) { // if it's missing, it should be NO (i.e. multi-tasking on by default)
  304. exitsOnSuspend = [NSNumber numberWithBool:NO];
  305. }
  306. if (exitsOnSuspend) {
  307. [self backup:nil];
  308. } else if (isMultitaskingSupported) {
  309. __block UIBackgroundTaskIdentifier backgroundTaskID = UIBackgroundTaskInvalid;
  310. backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  311. [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
  312. backgroundTaskID = UIBackgroundTaskInvalid;
  313. NSLog(@"Background task to backup WebSQL/LocalStorage expired.");
  314. }];
  315. CDVLocalStorage __weak* weakSelf = self;
  316. [self.commandDelegate runInBackground:^{
  317. [weakSelf backup:nil];
  318. [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
  319. backgroundTaskID = UIBackgroundTaskInvalid;
  320. }];
  321. }
  322. }
  323. - (void)onAppTerminate
  324. {
  325. [self onResignActive];
  326. }
  327. - (void)onReset
  328. {
  329. [self restore:nil];
  330. }
  331. @end
  332. #pragma mark -
  333. #pragma mark CDVBackupInfo implementation
  334. @implementation CDVBackupInfo
  335. @synthesize original, backup, label;
  336. - (BOOL)file:(NSString*)aPath isNewerThanFile:(NSString*)bPath
  337. {
  338. NSFileManager* fileManager = [NSFileManager defaultManager];
  339. NSError* __autoreleasing error = nil;
  340. NSDictionary* aPathAttribs = [fileManager attributesOfItemAtPath:aPath error:&error];
  341. NSDictionary* bPathAttribs = [fileManager attributesOfItemAtPath:bPath error:&error];
  342. NSDate* aPathModDate = [aPathAttribs objectForKey:NSFileModificationDate];
  343. NSDate* bPathModDate = [bPathAttribs objectForKey:NSFileModificationDate];
  344. if ((nil == aPathModDate) && (nil == bPathModDate)) {
  345. return NO;
  346. }
  347. return [aPathModDate compare:bPathModDate] == NSOrderedDescending || bPathModDate == nil;
  348. }
  349. - (BOOL)item:(NSString*)aPath isNewerThanItem:(NSString*)bPath
  350. {
  351. NSFileManager* fileManager = [NSFileManager defaultManager];
  352. BOOL aPathIsDir = NO, bPathIsDir = NO;
  353. BOOL aPathExists = [fileManager fileExistsAtPath:aPath isDirectory:&aPathIsDir];
  354. [fileManager fileExistsAtPath:bPath isDirectory:&bPathIsDir];
  355. if (!aPathExists) {
  356. return NO;
  357. }
  358. if (!(aPathIsDir && bPathIsDir)) { // just a file
  359. return [self file:aPath isNewerThanFile:bPath];
  360. }
  361. // essentially we want rsync here, but have to settle for our poor man's implementation
  362. // we get the files in aPath, and see if it is newer than the file in bPath
  363. // (it is newer if it doesn't exist in bPath) if we encounter the FIRST file that is newer,
  364. // we return YES
  365. NSDirectoryEnumerator* directoryEnumerator = [fileManager enumeratorAtPath:aPath];
  366. NSString* path;
  367. while ((path = [directoryEnumerator nextObject])) {
  368. NSString* aPathFile = [aPath stringByAppendingPathComponent:path];
  369. NSString* bPathFile = [bPath stringByAppendingPathComponent:path];
  370. BOOL isNewer = [self file:aPathFile isNewerThanFile:bPathFile];
  371. if (isNewer) {
  372. return YES;
  373. }
  374. }
  375. return NO;
  376. }
  377. - (BOOL)shouldBackup
  378. {
  379. return [self item:self.original isNewerThanItem:self.backup];
  380. }
  381. - (BOOL)shouldRestore
  382. {
  383. return [self item:self.backup isNewerThanItem:self.original];
  384. }
  385. @end