VLCAppDelegate.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*****************************************************************************
  2. * VLCAppDelegate.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Jean-Romain Prévost <jr # 3on.fr>
  11. * Luis Fernandes <zipleen # gmail.com>
  12. * Carola Nitz <nitz.carola # googlemail.com>
  13. *
  14. * Refer to the COPYING file of the official project for license.
  15. *****************************************************************************/
  16. #import "VLCAppDelegate.h"
  17. #import "VLCMediaFileDiscoverer.h"
  18. #import "NSString+SupportedMedia.h"
  19. #import "UIDevice+SpeedCategory.h"
  20. #import "VLCPlaylistViewController.h"
  21. #import "VLCMovieViewController.h"
  22. #import "PAPasscodeViewController.h"
  23. #import "UINavigationController+Theme.h"
  24. #import "VLCHTTPUploaderController.h"
  25. #import "VLCMenuTableViewController.h"
  26. #define PASSCODE_CHECK_INTERVAL 300
  27. @interface VLCAppDelegate () <PAPasscodeViewControllerDelegate, VLCMediaFileDiscovererDelegate> {
  28. PAPasscodeViewController *_passcodeLockController;
  29. VLCDropboxTableViewController *_dropboxTableViewController;
  30. VLCGoogleDriveTableViewController *_googleDriveTableViewController;
  31. VLCDownloadViewController *_downloadViewController;
  32. int _idleCounter;
  33. VLCMovieViewController *_movieViewController;
  34. }
  35. @property (nonatomic) BOOL passcodeValidated;
  36. @end
  37. @implementation VLCAppDelegate
  38. + (void)initialize
  39. {
  40. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  41. NSNumber *skipLoopFilterDefaultValue;
  42. int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
  43. if (deviceSpeedCategory < 3)
  44. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
  45. else
  46. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
  47. NSDictionary *appDefaults = @{kVLCSettingPasscodeKey : @"", kVLCSettingPasscodeOnKey : @(NO), kVLCSettingContinueAudioInBackgroundKey : @(YES), kVLCSettingStretchAudio : @(NO), kVLCSettingTextEncoding : kVLCSettingTextEncodingDefaultValue, kVLCSettingSkipLoopFilter : skipLoopFilterDefaultValue, kVLCSettingSubtitlesFont : kVLCSettingSubtitlesFontDefaultValue, kVLCSettingSubtitlesFontColor : kVLCSettingSubtitlesFontColorDefaultValue, kVLCSettingSubtitlesFontSize : kVLCSettingSubtitlesFontSizeDefaultValue, kVLCSettingDeinterlace : kVLCSettingDeinterlaceDefaultValue};
  48. [defaults registerDefaults:appDefaults];
  49. }
  50. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  51. {
  52. // Init the HTTP Server
  53. self.uploadController = [[VLCHTTPUploaderController alloc] init];
  54. // enable crash preventer
  55. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  56. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  57. _playlistViewController = [[VLCPlaylistViewController alloc] init];
  58. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_playlistViewController];
  59. [navCon loadTheme];
  60. _revealController = [[GHRevealViewController alloc] initWithNibName:nil bundle:nil];
  61. _revealController.wantsFullScreenLayout = YES;
  62. _menuViewController = [[VLCMenuTableViewController alloc] initWithNibName:nil bundle:nil];
  63. _revealController.sidebarViewController = _menuViewController;
  64. _revealController.contentViewController = navCon;
  65. self.window.rootViewController = self.revealController;
  66. // necessary to avoid navbar blinking in VLCOpenNetworkStreamViewController & VLCDownloadViewController
  67. _revealController.contentViewController.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  68. [self.window makeKeyAndVisible];
  69. VLCMediaFileDiscoverer *discoverer = [VLCMediaFileDiscoverer sharedInstance];
  70. [discoverer addObserver:self];
  71. [discoverer startDiscovering:[self directoryPath]];
  72. [self validatePasscode];
  73. return YES;
  74. }
  75. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  76. {
  77. if ([[DBSession sharedSession] handleOpenURL:url]) {
  78. [self.dropboxTableViewController updateViewAfterSessionChange];
  79. return YES;
  80. }
  81. if (_playlistViewController && url != nil) {
  82. APLog(@"%@ requested %@ to be opened", sourceApplication, url);
  83. if (url.isFileURL) {
  84. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  85. NSString *directoryPath = searchPaths[0];
  86. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, url.lastPathComponent]];
  87. NSError *theError;
  88. [[NSFileManager defaultManager] moveItemAtURL:url toURL:destinationURL error:&theError];
  89. if (theError.code != noErr)
  90. APLog(@"saving the file failed (%i): %@", theError.code, theError.localizedDescription);
  91. [self updateMediaList];
  92. } else {
  93. NSURL *parsedUrl = [self parseOpenURL:url];
  94. [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
  95. [self.playlistViewController performSelector:@selector(openMovieFromURL:) withObject:parsedUrl afterDelay:kGHRevealSidebarDefaultAnimationDuration];
  96. }
  97. return YES;
  98. }
  99. return NO;
  100. }
  101. - (NSURL *)parseOpenURL:(NSURL *)url
  102. {
  103. NSString *receivedUrl = [url absoluteString];
  104. if ([receivedUrl length] > 6) {
  105. NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
  106. if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
  107. NSString *parsedString = [receivedUrl substringFromIndex:6];
  108. // "url decode" so we can parse http:// links
  109. parsedString = [parsedString stringByReplacingOccurrencesOfString:@"+"withString:@" "];
  110. parsedString = [parsedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  111. // add http:// if nothing is there
  112. NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeLink error:nil];
  113. NSUInteger parsedStringLength = [parsedString length];
  114. NSUInteger numberOfUrlMatches = [detector numberOfMatchesInString:parsedString options:0 range:NSMakeRange(0, parsedStringLength)];
  115. if (numberOfUrlMatches == 0) {
  116. parsedString = [@"http://" stringByAppendingString:parsedString];
  117. }
  118. NSURL *targetUrl = [NSURL URLWithString:parsedString];
  119. return targetUrl;
  120. }
  121. }
  122. return url;
  123. }
  124. - (void)applicationWillEnterForeground:(UIApplication *)application
  125. {
  126. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  127. [self validatePasscode];
  128. }
  129. - (void)applicationWillResignActive:(UIApplication *)application
  130. {
  131. self.nextPasscodeCheckDate = [NSDate dateWithTimeIntervalSinceNow:PASSCODE_CHECK_INTERVAL];
  132. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  133. }
  134. - (void)applicationDidBecomeActive:(UIApplication *)application
  135. {
  136. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  137. [self updateMediaList];
  138. }
  139. - (void)applicationWillTerminate:(UIApplication *)application
  140. {
  141. [[NSUserDefaults standardUserDefaults] synchronize];
  142. }
  143. #pragma mark - properties
  144. - (VLCDropboxTableViewController *)dropboxTableViewController
  145. {
  146. if (_dropboxTableViewController == nil) {
  147. _dropboxTableViewController = [[VLCDropboxTableViewController alloc] initWithNibName:nil bundle:nil];
  148. }
  149. return _dropboxTableViewController;
  150. }
  151. - (VLCGoogleDriveTableViewController *)googleDriveTableViewController
  152. {
  153. if (_googleDriveTableViewController == nil) {
  154. _googleDriveTableViewController = [[VLCGoogleDriveTableViewController alloc] initWithNibName:nil bundle:nil];
  155. }
  156. return _googleDriveTableViewController;
  157. }
  158. - (VLCDownloadViewController *)downloadViewController
  159. {
  160. if (_downloadViewController == nil) {
  161. _downloadViewController = [[VLCDownloadViewController alloc] init];
  162. }
  163. return _downloadViewController;
  164. }
  165. #pragma mark - media discovering
  166. - (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading {
  167. if (!isLoading) {
  168. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  169. [sharedLibrary addFilePaths:@[fileName]];
  170. /* exclude media files from backup (QA1719) */
  171. NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
  172. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  173. // TODO Should we update media db after adding new files?
  174. [sharedLibrary updateMediaDatabase];
  175. [_playlistViewController updateViewContents];
  176. }
  177. }
  178. - (void)mediaFileDeleted:(NSString *)name {
  179. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  180. [_playlistViewController updateViewContents];
  181. }
  182. #pragma mark - media list methods
  183. - (NSString *)directoryPath
  184. {
  185. #define LOCAL_PLAYBACK_HACK 0
  186. #if LOCAL_PLAYBACK_HACK && TARGET_IPHONE_SIMULATOR
  187. NSString *directoryPath = @"/Users/fkuehne/Desktop/VideoLAN docs/Clips/sel/";
  188. #else
  189. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  190. NSString *directoryPath = searchPaths[0];
  191. #endif
  192. return directoryPath;
  193. }
  194. - (void)updateMediaList
  195. {
  196. NSString *directoryPath = [self directoryPath];
  197. NSArray *foundFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
  198. NSMutableArray *filePaths = [NSMutableArray arrayWithCapacity:[foundFiles count]];
  199. NSURL *fileURL;
  200. for (NSString *fileName in foundFiles) {
  201. if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
  202. [filePaths addObject:[directoryPath stringByAppendingPathComponent:fileName]];
  203. /* exclude media files from backup (QA1719) */
  204. fileURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:fileName]];
  205. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  206. }
  207. }
  208. [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
  209. [_playlistViewController updateViewContents];
  210. }
  211. #pragma mark - pass code validation
  212. - (void)validatePasscode
  213. {
  214. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  215. NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
  216. if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  217. self.passcodeValidated = YES;
  218. return;
  219. }
  220. if (!self.passcodeValidated) {
  221. if ([self.nextPasscodeCheckDate earlierDate:[NSDate date]] == self.nextPasscodeCheckDate) {
  222. _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
  223. _passcodeLockController.delegate = self;
  224. _passcodeLockController.passcode = passcode;
  225. self.window.rootViewController = _passcodeLockController;
  226. } else
  227. self.passcodeValidated = YES;
  228. }
  229. }
  230. - (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
  231. {
  232. // TODO add transition animation, i.e. fade
  233. self.nextPasscodeCheckDate = [NSDate dateWithTimeIntervalSinceNow:PASSCODE_CHECK_INTERVAL];
  234. self.window.rootViewController = self.revealController;
  235. }
  236. - (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
  237. {
  238. // TODO handle error attempts
  239. }
  240. #pragma mark - idle timer preventer
  241. - (void)disableIdleTimer
  242. {
  243. _idleCounter++;
  244. if ([UIApplication sharedApplication].idleTimerDisabled == NO)
  245. [UIApplication sharedApplication].idleTimerDisabled = YES;
  246. }
  247. - (void)activateIdleTimer
  248. {
  249. _idleCounter--;
  250. if (_idleCounter < 1)
  251. [UIApplication sharedApplication].idleTimerDisabled = NO;
  252. }
  253. #pragma mark - playback view handling
  254. - (void)openMediaFromManagedObject:(NSManagedObject *)mediaObject
  255. {
  256. if (!_movieViewController)
  257. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  258. if ([mediaObject isKindOfClass:[MLFile class]])
  259. _movieViewController.mediaItem = (MLFile *)mediaObject;
  260. else if ([mediaObject isKindOfClass:[MLAlbumTrack class]])
  261. _movieViewController.mediaItem = [(MLAlbumTrack*)mediaObject files].anyObject;
  262. else if ([mediaObject isKindOfClass:[MLShowEpisode class]])
  263. _movieViewController.mediaItem = [(MLShowEpisode*)mediaObject files].anyObject;
  264. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  265. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  266. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  267. }
  268. - (void)openMovieFromURL:(NSURL *)url
  269. {
  270. if (!_movieViewController)
  271. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  272. _movieViewController.url = url;
  273. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  274. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  275. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  276. }
  277. @end