VLCAppDelegate.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // VLCAppDelegate.m
  3. // AspenProject
  4. //
  5. // Created by Felix Paul Kühne on 27.02.13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCAppDelegate.h"
  11. #import "DirectoryWatcher.h"
  12. #import "NSString+SupportedMedia.h"
  13. #import "UIDevice+SpeedCategory.h"
  14. #import "VLCPlaylistViewController.h"
  15. #import "VLCMovieViewController.h"
  16. #import "PAPasscodeViewController.h"
  17. #import "UINavigationController+Theme.h"
  18. @interface VLCAppDelegate () <PAPasscodeViewControllerDelegate, DirectoryWatcherDelegate> {
  19. NSURL *_tempURL;
  20. PAPasscodeViewController *_passcodeLockController;
  21. VLCDropboxTableViewController *_dropboxTableViewController;
  22. DirectoryWatcher *_directoryWatcher;
  23. NSTimer *_addMediaTimer;
  24. NSMutableDictionary *_addedFiles;
  25. }
  26. @property (nonatomic) BOOL passcodeValidated;
  27. @end
  28. @implementation VLCAppDelegate
  29. + (void)initialize
  30. {
  31. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  32. NSNumber *skipLoopFilterDefaultValue;
  33. int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
  34. if (deviceSpeedCategory < 3)
  35. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
  36. else
  37. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
  38. NSDictionary *appDefaults = @{kVLCSettingPasscodeKey : @"", kVLCSettingPasscodeOnKey : @(NO), kVLCSettingContinueAudioInBackgroundKey : @(YES), kVLCSettingStretchAudio : @(NO), kVLCSettingTextEncoding : kVLCSettingTextEncodingDefaultValue, kVLCSettingSkipLoopFilter : skipLoopFilterDefaultValue};
  39. [defaults registerDefaults:appDefaults];
  40. }
  41. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  42. {
  43. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  44. _playlistViewController = [[VLCPlaylistViewController alloc] init];
  45. self.navigationController = [[UINavigationController alloc] initWithRootViewController:_playlistViewController];
  46. [self.navigationController loadTheme];
  47. self.window.rootViewController = self.navigationController;
  48. [self.window makeKeyAndVisible];
  49. _directoryWatcher = [DirectoryWatcher watchFolderWithPath:[self directoryPath] delegate:self];
  50. [self validatePasscode];
  51. return YES;
  52. }
  53. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  54. {
  55. if ([[DBSession sharedSession] handleOpenURL:url]) {
  56. [self.dropboxTableViewController updateViewAfterSessionChange];
  57. return YES;
  58. }
  59. if (_playlistViewController && url != nil) {
  60. APLog(@"%@ requested %@ to be opened", sourceApplication, url);
  61. if (url.isFileURL) {
  62. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"SAVE_FILE", @"") message:[NSString stringWithFormat:NSLocalizedString(@"SAVE_FILE_LONG", @""), url.lastPathComponent] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:NSLocalizedString(@"BUTTON_SAVE", @""), nil];
  63. _tempURL = url;
  64. [alert show];
  65. } else {
  66. NSURL *parsedUrl = [self parseOpenURL:url];
  67. [_playlistViewController openMovieFromURL:parsedUrl];
  68. }
  69. return YES;
  70. }
  71. return NO;
  72. }
  73. - (NSURL *)parseOpenURL:(NSURL *)url
  74. {
  75. NSString *receivedUrl = [url absoluteString];
  76. if ([receivedUrl length] > 6) {
  77. NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
  78. if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
  79. NSString *parsedString = [receivedUrl substringFromIndex:6];
  80. // "url decode" so we can parse http:// links
  81. parsedString = [parsedString stringByReplacingOccurrencesOfString:@"+"withString:@" "];
  82. parsedString = [parsedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  83. // add http:// if nothing is there
  84. NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeLink error:nil];
  85. NSUInteger parsedStringLength = [parsedString length];
  86. NSUInteger numberOfUrlMatches = [detector numberOfMatchesInString:parsedString options:0 range:NSMakeRange(0, parsedStringLength)];
  87. if (numberOfUrlMatches == 0) {
  88. parsedString = [@"http://" stringByAppendingString:parsedString];
  89. }
  90. NSURL *targetUrl = [NSURL URLWithString:parsedString];
  91. return targetUrl;
  92. }
  93. }
  94. return url;
  95. }
  96. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  97. {
  98. if (buttonIndex == 1) {
  99. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  100. NSString *directoryPath = searchPaths[0];
  101. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, _tempURL.lastPathComponent]];
  102. NSError *theError;
  103. [[NSFileManager defaultManager] copyItemAtURL:_tempURL toURL:destinationURL error:&theError];
  104. if (theError.code != noErr)
  105. APLog(@"saving the file failed (%i): %@", theError.code, theError.localizedDescription);
  106. [self updateMediaList];
  107. } else
  108. [_playlistViewController openMovieFromURL:_tempURL];
  109. }
  110. - (void)applicationWillResignActive:(UIApplication *)application
  111. {
  112. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  113. }
  114. - (void)applicationDidBecomeActive:(UIApplication *)application
  115. {
  116. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  117. [self updateMediaList];
  118. }
  119. - (void)applicationDidEnterBackground:(UIApplication *)application
  120. {
  121. [self validatePasscode]; // Lock library when going to background
  122. }
  123. #pragma mark - properties
  124. - (VLCDropboxTableViewController *)dropboxTableViewController
  125. {
  126. if (_dropboxTableViewController == nil) {
  127. _dropboxTableViewController = [[VLCDropboxTableViewController alloc] initWithNibName:nil bundle:nil];
  128. }
  129. return _dropboxTableViewController;
  130. }
  131. #pragma mark - directory watcher delegate
  132. - (void)addFileTimerFired
  133. {
  134. NSArray *allKeys = [_addedFiles allKeys];
  135. NSFileManager *fileManager = [NSFileManager defaultManager];
  136. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  137. for (NSString *fileURL in allKeys) {
  138. if (![fileManager fileExistsAtPath:fileURL])
  139. continue;
  140. NSDictionary *attribs = [fileManager attributesOfItemAtPath:fileURL error:nil];
  141. NSNumber *prevFetchedSize = [_addedFiles objectForKey:fileURL];
  142. NSNumber *updatedSize = [attribs objectForKey:NSFileSize];
  143. if (!updatedSize)
  144. continue;
  145. if ([prevFetchedSize compare:updatedSize] == NSOrderedSame) {
  146. [_addedFiles removeObjectForKey:fileURL];
  147. [sharedLibrary addFilePaths:@[fileURL]];
  148. /* exclude media files from backup (QA1719) */
  149. NSURL *excludeURL = [NSURL fileURLWithPath:fileURL];
  150. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  151. // TODO Should we update media db after adding new files?
  152. [sharedLibrary updateMediaDatabase];
  153. [_playlistViewController updateViewContents];
  154. } else
  155. [_addedFiles setObject:updatedSize forKey:fileURL];
  156. }
  157. if (_addedFiles.count == 0) {
  158. [_addMediaTimer invalidate];
  159. _addMediaTimer = nil;
  160. }
  161. }
  162. - (void)directoryDidChange:(DirectoryWatcher *)folderWatcher
  163. {
  164. NSArray *foundFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self directoryPath] error:nil];
  165. NSMutableArray *matchedFiles = [NSMutableArray arrayWithCapacity:foundFiles.count];
  166. for (NSString *fileName in foundFiles) {
  167. if ([fileName isSupportedMediaFormat])
  168. [matchedFiles addObject:[[self directoryPath] stringByAppendingPathComponent:fileName]];
  169. }
  170. NSArray *mediaFiles = [MLFile allFiles];
  171. if (mediaFiles.count > matchedFiles.count) { // File was deleted
  172. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  173. [_playlistViewController updateViewContents];
  174. } else if (mediaFiles.count < matchedFiles.count) { // File was added
  175. NSMutableArray *addedFiles = [NSMutableArray array];
  176. for (NSString *fileName in matchedFiles) {
  177. NSURL *fileURL = [NSURL fileURLWithPath:fileName];
  178. BOOL found = NO;
  179. for (MLFile *mediaFile in mediaFiles) {
  180. if ([mediaFile.url isEqualToString:fileURL.absoluteString])
  181. found = YES;
  182. }
  183. if (!found)
  184. [addedFiles addObject:fileName];
  185. }
  186. _addedFiles = [NSMutableDictionary dictionaryWithCapacity:[addedFiles count]];
  187. for (NSString *fileURL in addedFiles)
  188. [_addedFiles setObject:@(0) forKey:fileURL];
  189. _addMediaTimer = [NSTimer scheduledTimerWithTimeInterval:2. target:self
  190. selector:@selector(addFileTimerFired)
  191. userInfo:nil repeats:YES];
  192. }
  193. }
  194. #pragma mark - media list methods
  195. - (NSString *)directoryPath
  196. {
  197. #define LOCAL_PLAYBACK_HACK 0
  198. #if LOCAL_PLAYBACK_HACK && TARGET_IPHONE_SIMULATOR
  199. NSString *directoryPath = @"/Users/fkuehne/Desktop/VideoLAN docs/Clips/sel/";
  200. #else
  201. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  202. NSString *directoryPath = searchPaths[0];
  203. #endif
  204. return directoryPath;
  205. }
  206. - (void)updateMediaList
  207. {
  208. NSString *directoryPath = [self directoryPath];
  209. NSArray *foundFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
  210. NSMutableArray *filePaths = [NSMutableArray arrayWithCapacity:[foundFiles count]];
  211. NSURL *fileURL;
  212. for (NSString *fileName in foundFiles) {
  213. if ([fileName isSupportedMediaFormat]) {
  214. [filePaths addObject:[directoryPath stringByAppendingPathComponent:fileName]];
  215. /* exclude media files from backup (QA1719) */
  216. fileURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:fileName]];
  217. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  218. }
  219. }
  220. [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
  221. [_playlistViewController updateViewContents];
  222. }
  223. #pragma mark - pass code validation
  224. - (void)validatePasscode
  225. {
  226. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  227. NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
  228. if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  229. self.passcodeValidated = YES;
  230. return;
  231. }
  232. if (!self.passcodeValidated) {
  233. if ([self.nextPasscodeCheckDate earlierDate:[NSDate date]] == self.nextPasscodeCheckDate) {
  234. _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
  235. _passcodeLockController.delegate = self;
  236. _passcodeLockController.passcode = passcode;
  237. self.window.rootViewController = _passcodeLockController;
  238. } else
  239. self.passcodeValidated = YES;
  240. }
  241. }
  242. - (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
  243. {
  244. // TODO add transition animation, i.e. fade
  245. self.nextPasscodeCheckDate = [NSDate dateWithTimeIntervalSinceNow:300];
  246. self.window.rootViewController = self.navigationController;
  247. }
  248. - (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
  249. {
  250. // TODO handle error attempts
  251. }
  252. @end