VLCAppDelegate.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /*****************************************************************************
  2. * VLCAppDelegate.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2014 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. #import "BWQuincyManager.h"
  27. #import "VLCAlertView.h"
  28. @interface VLCAppDelegate () <PAPasscodeViewControllerDelegate, VLCMediaFileDiscovererDelegate, BWQuincyManagerDelegate> {
  29. PAPasscodeViewController *_passcodeLockController;
  30. VLCDropboxTableViewController *_dropboxTableViewController;
  31. VLCGoogleDriveTableViewController *_googleDriveTableViewController;
  32. VLCDownloadViewController *_downloadViewController;
  33. int _idleCounter;
  34. int _networkActivityCounter;
  35. VLCMovieViewController *_movieViewController;
  36. BOOL _passcodeValidated;
  37. }
  38. @end
  39. @implementation VLCAppDelegate
  40. + (void)initialize
  41. {
  42. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  43. NSNumber *skipLoopFilterDefaultValue;
  44. int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
  45. if (deviceSpeedCategory < 3)
  46. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
  47. else
  48. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
  49. NSDictionary *appDefaults = @{kVLCSettingPasscodeKey : @"", kVLCSettingPasscodeOnKey : @(NO), kVLCSettingContinueAudioInBackgroundKey : @(YES), kVLCSettingStretchAudio : @(NO), kVLCSettingTextEncoding : kVLCSettingTextEncodingDefaultValue, kVLCSettingSkipLoopFilter : skipLoopFilterDefaultValue, kVLCSettingSubtitlesFont : kVLCSettingSubtitlesFontDefaultValue, kVLCSettingSubtitlesFontColor : kVLCSettingSubtitlesFontColorDefaultValue, kVLCSettingSubtitlesFontSize : kVLCSettingSubtitlesFontSizeDefaultValue, kVLCSettingSubtitlesBoldFont: kVLCSettingSubtitlesBoldFontDefaulValue, kVLCSettingDeinterlace : kVLCSettingDeinterlaceDefaultValue, kVLCSettingNetworkCaching : kVLCSettingNetworkCachingDefaultValue, kVLCSettingPlaybackGestures : [NSNumber numberWithBool:YES], kVLCSettingFTPTextEncoding : kVLCSettingFTPTextEncodingDefaultValue };
  50. [defaults registerDefaults:appDefaults];
  51. }
  52. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  53. {
  54. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  55. // Change the keyboard for UISearchBar
  56. [[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];
  57. // For the cursor
  58. [[UITextField appearance] setTintColor:[UIColor VLCOrangeTintColor]];
  59. // Don't override the 'Cancel' button color in the search bar with the previous UITextField call. Use the default blue color
  60. [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]} forState:UIControlStateNormal];
  61. // For the edit selection indicators
  62. [[UITableView appearance] setTintColor:[UIColor VLCOrangeTintColor]];
  63. }
  64. [[UISwitch appearance] setOnTintColor:[UIColor VLCOrangeTintColor]];
  65. BWQuincyManager *quincyManager = [BWQuincyManager sharedQuincyManager];
  66. [quincyManager setSubmissionURL:@"http://crash.videolan.org/crash_v200.php"];
  67. [quincyManager setDelegate:self];
  68. [quincyManager setShowAlwaysButton:YES];
  69. [quincyManager startManager];
  70. /* clean caches on launch (since those are used for wifi upload only) */
  71. [self cleanCache];
  72. // Init the HTTP Server
  73. self.uploadController = [[VLCHTTPUploaderController alloc] init];
  74. // enable crash preventer
  75. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  76. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  77. _playlistViewController = [[VLCPlaylistViewController alloc] init];
  78. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_playlistViewController];
  79. [navCon loadTheme];
  80. _revealController = [[GHRevealViewController alloc] initWithNibName:nil bundle:nil];
  81. _revealController.wantsFullScreenLayout = YES;
  82. _menuViewController = [[VLCMenuTableViewController alloc] initWithNibName:nil bundle:nil];
  83. _revealController.sidebarViewController = _menuViewController;
  84. _revealController.contentViewController = navCon;
  85. self.window.rootViewController = self.revealController;
  86. // necessary to avoid navbar blinking in VLCOpenNetworkStreamViewController & VLCDownloadViewController
  87. _revealController.contentViewController.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
  88. [self.window makeKeyAndVisible];
  89. VLCMediaFileDiscoverer *discoverer = [VLCMediaFileDiscoverer sharedInstance];
  90. [discoverer addObserver:self];
  91. [discoverer startDiscovering:[self directoryPath]];
  92. [self validatePasscode];
  93. return YES;
  94. }
  95. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  96. {
  97. if ([[DBSession sharedSession] handleOpenURL:url]) {
  98. [self.dropboxTableViewController updateViewAfterSessionChange];
  99. return YES;
  100. }
  101. if (_playlistViewController && url != nil) {
  102. APLog(@"%@ requested %@ to be opened", sourceApplication, url);
  103. if (url.isFileURL) {
  104. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  105. NSString *directoryPath = searchPaths[0];
  106. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, url.lastPathComponent]];
  107. NSError *theError;
  108. [[NSFileManager defaultManager] moveItemAtURL:url toURL:destinationURL error:&theError];
  109. if (theError.code != noErr)
  110. APLog(@"saving the file failed (%li): %@", (long)theError.code, theError.localizedDescription);
  111. [self updateMediaList];
  112. } else {
  113. NSString *receivedUrl = [url absoluteString];
  114. if ([receivedUrl length] > 6) {
  115. NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
  116. if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
  117. NSString *parsedString = [receivedUrl substringFromIndex:6];
  118. NSUInteger location = [parsedString rangeOfString:@"//"].location;
  119. /* Safari & al mangle vlc://http:// so fix this */
  120. if (location != NSNotFound && [parsedString characterAtIndex:location - 1] != 0x3a) { // :
  121. parsedString = [NSString stringWithFormat:@"%@://%@", [parsedString substringToIndex:location], [parsedString substringFromIndex:location+2]];
  122. } else {
  123. parsedString = [receivedUrl substringFromIndex:6];
  124. if (![parsedString hasPrefix:@"http://"] && ![parsedString hasPrefix:@"https://"] && ![parsedString hasPrefix:@"ftp://"]) {
  125. parsedString = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
  126. }
  127. }
  128. url = [NSURL URLWithString:parsedString];
  129. }
  130. }
  131. [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
  132. NSString *scheme = url.scheme;
  133. if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"]) {
  134. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"BUTTON_PLAY", nil)]];
  135. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  136. if (cancelled)
  137. [[self downloadViewController] addURLToDownloadList:url fileNameOfMedia:nil];
  138. else
  139. [self openMovieFromURL:url];
  140. };
  141. [alert show];
  142. } else
  143. [self openMovieFromURL:url];
  144. }
  145. return YES;
  146. }
  147. return NO;
  148. }
  149. - (void)applicationWillEnterForeground:(UIApplication *)application
  150. {
  151. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  152. }
  153. - (void)applicationWillResignActive:(UIApplication *)application
  154. {
  155. _passcodeValidated = NO;
  156. [self validatePasscode];
  157. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  158. }
  159. - (void)applicationDidBecomeActive:(UIApplication *)application
  160. {
  161. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  162. [self updateMediaList];
  163. }
  164. - (void)applicationWillTerminate:(UIApplication *)application
  165. {
  166. _passcodeValidated = NO;
  167. [[NSUserDefaults standardUserDefaults] synchronize];
  168. }
  169. #pragma mark - properties
  170. - (VLCDropboxTableViewController *)dropboxTableViewController
  171. {
  172. if (_dropboxTableViewController == nil)
  173. _dropboxTableViewController = [[VLCDropboxTableViewController alloc] initWithNibName:@"VLCCloudStorageTableViewController" bundle:nil];
  174. return _dropboxTableViewController;
  175. }
  176. - (VLCGoogleDriveTableViewController *)googleDriveTableViewController
  177. {
  178. if (_googleDriveTableViewController == nil)
  179. _googleDriveTableViewController = [[VLCGoogleDriveTableViewController alloc] initWithNibName:@"VLCCloudStorageTableViewController" bundle:nil];
  180. return _googleDriveTableViewController;
  181. }
  182. - (VLCDownloadViewController *)downloadViewController
  183. {
  184. if (_downloadViewController == nil) {
  185. if (SYSTEM_RUNS_IOS7_OR_LATER)
  186. _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCFutureDownloadViewController" bundle:nil];
  187. else
  188. _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
  189. }
  190. return _downloadViewController;
  191. }
  192. #pragma mark - media discovering
  193. - (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
  194. {
  195. if (!isLoading) {
  196. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  197. [sharedLibrary addFilePaths:@[fileName]];
  198. /* exclude media files from backup (QA1719) */
  199. NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
  200. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  201. // TODO Should we update media db after adding new files?
  202. [sharedLibrary updateMediaDatabase];
  203. [_playlistViewController updateViewContents];
  204. }
  205. }
  206. - (void)mediaFileDeleted:(NSString *)name
  207. {
  208. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  209. [_playlistViewController updateViewContents];
  210. }
  211. - (void)cleanCache
  212. {
  213. if ([self haveNetworkActivity])
  214. return;
  215. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  216. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  217. NSFileManager *fileManager = [NSFileManager defaultManager];
  218. if ([fileManager fileExistsAtPath:uploadDirPath])
  219. [fileManager removeItemAtPath:uploadDirPath error:nil];
  220. }
  221. #pragma mark - media list methods
  222. - (NSString *)directoryPath
  223. {
  224. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  225. NSString *directoryPath = searchPaths[0];
  226. return directoryPath;
  227. }
  228. - (void)updateMediaList
  229. {
  230. NSString *directoryPath = [self directoryPath];
  231. NSArray *foundFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
  232. NSMutableArray *filePaths = [NSMutableArray arrayWithCapacity:[foundFiles count]];
  233. NSURL *fileURL;
  234. for (NSString *fileName in foundFiles) {
  235. if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
  236. [filePaths addObject:[directoryPath stringByAppendingPathComponent:fileName]];
  237. /* exclude media files from backup (QA1719) */
  238. fileURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:fileName]];
  239. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  240. }
  241. }
  242. [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
  243. [_playlistViewController updateViewContents];
  244. }
  245. #pragma mark - pass code validation
  246. - (void)validatePasscode
  247. {
  248. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  249. NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
  250. if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  251. _passcodeValidated = YES;
  252. return;
  253. }
  254. if (!_passcodeValidated) {
  255. _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
  256. _passcodeLockController.delegate = self;
  257. _passcodeLockController.passcode = passcode;
  258. if (self.window.rootViewController.presentedViewController)
  259. [self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];
  260. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_passcodeLockController];
  261. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  262. [self.window.rootViewController presentViewController:navCon animated:NO completion:nil];
  263. }
  264. }
  265. - (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
  266. {
  267. [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
  268. }
  269. - (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
  270. {
  271. // FIXME: handle countless failed passcode attempts
  272. }
  273. #pragma mark - idle timer preventer
  274. - (void)disableIdleTimer
  275. {
  276. _idleCounter++;
  277. if ([UIApplication sharedApplication].idleTimerDisabled == NO)
  278. [UIApplication sharedApplication].idleTimerDisabled = YES;
  279. }
  280. - (void)activateIdleTimer
  281. {
  282. _idleCounter--;
  283. if (_idleCounter < 1)
  284. [UIApplication sharedApplication].idleTimerDisabled = NO;
  285. }
  286. - (void)networkActivityStarted
  287. {
  288. _networkActivityCounter++;
  289. if ([UIApplication sharedApplication].networkActivityIndicatorVisible == NO)
  290. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  291. }
  292. - (BOOL)haveNetworkActivity
  293. {
  294. return _networkActivityCounter >= 1;
  295. }
  296. - (void)networkActivityStopped
  297. {
  298. _networkActivityCounter--;
  299. if (_networkActivityCounter < 1)
  300. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  301. }
  302. #pragma mark - playback view handling
  303. - (void)openMediaFromManagedObject:(NSManagedObject *)mediaObject
  304. {
  305. if (!_movieViewController)
  306. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  307. if ([mediaObject isKindOfClass:[MLFile class]])
  308. _movieViewController.fileFromMediaLibrary = (MLFile *)mediaObject;
  309. else if ([mediaObject isKindOfClass:[MLAlbumTrack class]])
  310. _movieViewController.fileFromMediaLibrary = [(MLAlbumTrack*)mediaObject files].anyObject;
  311. else if ([mediaObject isKindOfClass:[MLShowEpisode class]])
  312. _movieViewController.fileFromMediaLibrary = [(MLShowEpisode*)mediaObject files].anyObject;
  313. [(MLFile *)_movieViewController.fileFromMediaLibrary setUnread:@(NO)];
  314. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  315. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  316. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  317. }
  318. - (void)openMovieFromURL:(NSURL *)url
  319. {
  320. if (!_movieViewController)
  321. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  322. _movieViewController.url = url;
  323. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  324. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  325. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  326. }
  327. - (void)openMediaList:(VLCMediaList *)list atIndex:(int)index
  328. {
  329. if (!_movieViewController)
  330. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  331. _movieViewController.mediaList = list;
  332. _movieViewController.itemInMediaListToBePlayedFirst = index;
  333. _movieViewController.pathToExternalSubtitlesFile = nil;
  334. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  335. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  336. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  337. }
  338. - (void)openMovieWithExternalSubtitleFromURL:(NSURL *)url externalSubURL:(NSString *)SubtitlePath
  339. {
  340. if (!_movieViewController)
  341. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  342. _movieViewController.url = url;
  343. _movieViewController.pathToExternalSubtitlesFile = SubtitlePath;
  344. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  345. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  346. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  347. }
  348. @end