VLCAppDelegate.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
  124. url = [NSURL URLWithString:parsedString];
  125. }
  126. }
  127. [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
  128. NSString *scheme = url.scheme;
  129. if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"]) {
  130. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"BUTTON_PLAY", nil)]];
  131. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  132. if (cancelled)
  133. [[self downloadViewController] addURLToDownloadList:url fileNameOfMedia:nil];
  134. else
  135. [self openMovieFromURL:url];
  136. };
  137. [alert show];
  138. } else
  139. [self openMovieFromURL:url];
  140. }
  141. return YES;
  142. }
  143. return NO;
  144. }
  145. - (void)applicationWillEnterForeground:(UIApplication *)application
  146. {
  147. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  148. }
  149. - (void)applicationWillResignActive:(UIApplication *)application
  150. {
  151. _passcodeValidated = NO;
  152. [self validatePasscode];
  153. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  154. }
  155. - (void)applicationDidBecomeActive:(UIApplication *)application
  156. {
  157. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  158. [self updateMediaList];
  159. }
  160. - (void)applicationWillTerminate:(UIApplication *)application
  161. {
  162. _passcodeValidated = NO;
  163. [[NSUserDefaults standardUserDefaults] synchronize];
  164. }
  165. #pragma mark - properties
  166. - (VLCDropboxTableViewController *)dropboxTableViewController
  167. {
  168. if (_dropboxTableViewController == nil)
  169. _dropboxTableViewController = [[VLCDropboxTableViewController alloc] initWithNibName:@"VLCCloudStorageTableViewController" bundle:nil];
  170. return _dropboxTableViewController;
  171. }
  172. - (VLCGoogleDriveTableViewController *)googleDriveTableViewController
  173. {
  174. if (_googleDriveTableViewController == nil)
  175. _googleDriveTableViewController = [[VLCGoogleDriveTableViewController alloc] initWithNibName:@"VLCCloudStorageTableViewController" bundle:nil];
  176. return _googleDriveTableViewController;
  177. }
  178. - (VLCDownloadViewController *)downloadViewController
  179. {
  180. if (_downloadViewController == nil) {
  181. if (SYSTEM_RUNS_IOS7_OR_LATER)
  182. _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCFutureDownloadViewController" bundle:nil];
  183. else
  184. _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
  185. }
  186. return _downloadViewController;
  187. }
  188. #pragma mark - media discovering
  189. - (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
  190. {
  191. if (!isLoading) {
  192. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  193. [sharedLibrary addFilePaths:@[fileName]];
  194. /* exclude media files from backup (QA1719) */
  195. NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
  196. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  197. // TODO Should we update media db after adding new files?
  198. [sharedLibrary updateMediaDatabase];
  199. [_playlistViewController updateViewContents];
  200. }
  201. }
  202. - (void)mediaFileDeleted:(NSString *)name
  203. {
  204. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  205. [_playlistViewController updateViewContents];
  206. }
  207. - (void)cleanCache
  208. {
  209. if ([self haveNetworkActivity])
  210. return;
  211. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  212. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  213. NSFileManager *fileManager = [NSFileManager defaultManager];
  214. if ([fileManager fileExistsAtPath:uploadDirPath])
  215. [fileManager removeItemAtPath:uploadDirPath error:nil];
  216. }
  217. #pragma mark - media list methods
  218. - (NSString *)directoryPath
  219. {
  220. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  221. NSString *directoryPath = searchPaths[0];
  222. return directoryPath;
  223. }
  224. - (void)updateMediaList
  225. {
  226. NSString *directoryPath = [self directoryPath];
  227. NSArray *foundFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
  228. NSMutableArray *filePaths = [NSMutableArray arrayWithCapacity:[foundFiles count]];
  229. NSURL *fileURL;
  230. for (NSString *fileName in foundFiles) {
  231. if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
  232. [filePaths addObject:[directoryPath stringByAppendingPathComponent:fileName]];
  233. /* exclude media files from backup (QA1719) */
  234. fileURL = [NSURL fileURLWithPath:[directoryPath stringByAppendingPathComponent:fileName]];
  235. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  236. }
  237. }
  238. [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
  239. [_playlistViewController updateViewContents];
  240. }
  241. #pragma mark - pass code validation
  242. - (void)validatePasscode
  243. {
  244. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  245. NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
  246. if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  247. _passcodeValidated = YES;
  248. return;
  249. }
  250. if (!_passcodeValidated) {
  251. _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
  252. _passcodeLockController.delegate = self;
  253. _passcodeLockController.passcode = passcode;
  254. if (self.window.rootViewController.presentedViewController)
  255. [self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];
  256. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_passcodeLockController];
  257. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  258. [self.window.rootViewController presentViewController:navCon animated:NO completion:nil];
  259. }
  260. }
  261. - (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
  262. {
  263. [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
  264. }
  265. - (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
  266. {
  267. // FIXME: handle countless failed passcode attempts
  268. }
  269. #pragma mark - idle timer preventer
  270. - (void)disableIdleTimer
  271. {
  272. _idleCounter++;
  273. if ([UIApplication sharedApplication].idleTimerDisabled == NO)
  274. [UIApplication sharedApplication].idleTimerDisabled = YES;
  275. }
  276. - (void)activateIdleTimer
  277. {
  278. _idleCounter--;
  279. if (_idleCounter < 1)
  280. [UIApplication sharedApplication].idleTimerDisabled = NO;
  281. }
  282. - (void)networkActivityStarted
  283. {
  284. _networkActivityCounter++;
  285. if ([UIApplication sharedApplication].networkActivityIndicatorVisible == NO)
  286. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  287. }
  288. - (BOOL)haveNetworkActivity
  289. {
  290. return _networkActivityCounter >= 1;
  291. }
  292. - (void)networkActivityStopped
  293. {
  294. _networkActivityCounter--;
  295. if (_networkActivityCounter < 1)
  296. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  297. }
  298. #pragma mark - playback view handling
  299. - (void)openMediaFromManagedObject:(NSManagedObject *)mediaObject
  300. {
  301. if (!_movieViewController)
  302. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  303. if ([mediaObject isKindOfClass:[MLFile class]])
  304. _movieViewController.fileFromMediaLibrary = (MLFile *)mediaObject;
  305. else if ([mediaObject isKindOfClass:[MLAlbumTrack class]])
  306. _movieViewController.fileFromMediaLibrary = [(MLAlbumTrack*)mediaObject files].anyObject;
  307. else if ([mediaObject isKindOfClass:[MLShowEpisode class]])
  308. _movieViewController.fileFromMediaLibrary = [(MLShowEpisode*)mediaObject files].anyObject;
  309. [(MLFile *)_movieViewController.fileFromMediaLibrary setUnread:@(NO)];
  310. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  311. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  312. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  313. }
  314. - (void)openMovieFromURL:(NSURL *)url
  315. {
  316. if (!_movieViewController)
  317. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  318. _movieViewController.url = url;
  319. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  320. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  321. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  322. }
  323. - (void)openMediaList:(VLCMediaList *)list atIndex:(int)index
  324. {
  325. if (!_movieViewController)
  326. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  327. _movieViewController.mediaList = list;
  328. _movieViewController.itemInMediaListToBePlayedFirst = index;
  329. _movieViewController.pathToExternalSubtitlesFile = nil;
  330. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  331. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  332. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  333. }
  334. - (void)openMovieWithExternalSubtitleFromURL:(NSURL *)url externalSubURL:(NSString *)SubtitlePath
  335. {
  336. if (!_movieViewController)
  337. _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
  338. _movieViewController.url = url;
  339. _movieViewController.pathToExternalSubtitlesFile = SubtitlePath;
  340. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_movieViewController];
  341. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  342. [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
  343. }
  344. @end