VLCAppDelegate.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. /*****************************************************************************
  2. * VLCAppDelegate.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 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. * Tamas Timar <ttimar.vlc # gmail.com>
  14. * Tobias Conradi <videolan # tobias-conradi.de>
  15. *
  16. * Refer to the COPYING file of the official project for license.
  17. *****************************************************************************/
  18. #import "VLCAppDelegate.h"
  19. #import "VLCMediaFileDiscoverer.h"
  20. #import "NSString+SupportedMedia.h"
  21. #import "UIDevice+VLC.h"
  22. #import "VLCPlaylistViewController.h"
  23. #import "VLCPlaybackNavigationController.h"
  24. #import "PAPasscodeViewController.h"
  25. #import "VLCHTTPUploaderController.h"
  26. #import "VLCMenuTableViewController.h"
  27. #import "VLCMigrationViewController.h"
  28. #import "VLCAlertView.h"
  29. #import <BoxSDK/BoxSDK.h>
  30. #import "VLCNotificationRelay.h"
  31. #import "VLCPlaybackController.h"
  32. #import "VLCNavigationController.h"
  33. #import "VLCWatchMessage.h"
  34. #import "VLCPlaybackController+MediaLibrary.h"
  35. #import "VLCPlayerDisplayController.h"
  36. #import <MediaPlayer/MediaPlayer.h>
  37. #define HAVE_FABRIC 0
  38. #if HAVE_FABRIC
  39. #import <Fabric/Fabric.h>
  40. #import <Crashlytics/Crashlytics.h>
  41. #endif
  42. @interface VLCAppDelegate () <PAPasscodeViewControllerDelegate, VLCMediaFileDiscovererDelegate> {
  43. PAPasscodeViewController *_passcodeLockController;
  44. VLCDownloadViewController *_downloadViewController;
  45. VLCDropboxTableViewController *_dropboxTableViewController;
  46. int _idleCounter;
  47. int _networkActivityCounter;
  48. BOOL _passcodeValidated;
  49. BOOL _isRunningMigration;
  50. BOOL _isComingFromHandoff;
  51. }
  52. @end
  53. @implementation VLCAppDelegate
  54. + (void)initialize
  55. {
  56. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  57. NSNumber *skipLoopFilterDefaultValue;
  58. int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
  59. if (deviceSpeedCategory < 3)
  60. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
  61. else
  62. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
  63. NSDictionary *appDefaults = @{kVLCSettingPasscodeKey : @"",
  64. kVLCSettingPasscodeOnKey : @(NO),
  65. kVLCSettingContinueAudioInBackgroundKey : @(YES),
  66. kVLCSettingStretchAudio : @(NO),
  67. kVLCSettingTextEncoding : kVLCSettingTextEncodingDefaultValue,
  68. kVLCSettingSkipLoopFilter : skipLoopFilterDefaultValue,
  69. kVLCSettingSubtitlesFont : kVLCSettingSubtitlesFontDefaultValue,
  70. kVLCSettingSubtitlesFontColor : kVLCSettingSubtitlesFontColorDefaultValue,
  71. kVLCSettingSubtitlesFontSize : kVLCSettingSubtitlesFontSizeDefaultValue,
  72. kVLCSettingSubtitlesBoldFont: kVLCSettingSubtitlesBoldFontDefaultValue,
  73. kVLCSettingDeinterlace : kVLCSettingDeinterlaceDefaultValue,
  74. kVLCSettingNetworkCaching : kVLCSettingNetworkCachingDefaultValue,
  75. kVLCSettingPlaybackGestures : [NSNumber numberWithBool:YES],
  76. kVLCSettingFTPTextEncoding : kVLCSettingFTPTextEncodingDefaultValue,
  77. kVLCSettingWiFiSharingIPv6 : kVLCSettingWiFiSharingIPv6DefaultValue,
  78. kVLCSettingEqualizerProfile : kVLCSettingEqualizerProfileDefaultValue,
  79. kVLCSettingPlaybackForwardSkipLength : kVLCSettingPlaybackForwardSkipLengthDefaultValue,
  80. kVLCSettingPlaybackBackwardSkipLength : kVLCSettingPlaybackBackwardSkipLengthDefaultValue,
  81. kVLCSettingOpenAppForPlayback : kVLCSettingOpenAppForPlaybackDefaultValue};
  82. [defaults registerDefaults:appDefaults];
  83. }
  84. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  85. {
  86. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  87. // Change the keyboard for UISearchBar
  88. [[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];
  89. // For the cursor
  90. [[UITextField appearance] setTintColor:[UIColor VLCOrangeTintColor]];
  91. // Don't override the 'Cancel' button color in the search bar with the previous UITextField call. Use the default blue color
  92. [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]} forState:UIControlStateNormal];
  93. // For the edit selection indicators
  94. [[UITableView appearance] setTintColor:[UIColor VLCOrangeTintColor]];
  95. }
  96. [[UISwitch appearance] setOnTintColor:[UIColor VLCOrangeTintColor]];
  97. /* clean caches on launch (since those are used for wifi upload only) */
  98. [self cleanCache];
  99. // Init the HTTP Server
  100. self.uploadController = [[VLCHTTPUploaderController alloc] init];
  101. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  102. // enable crash preventer
  103. void (^setupBlock)() = ^{
  104. _playlistViewController = [[VLCPlaylistViewController alloc] init];
  105. UINavigationController *navCon = [[VLCNavigationController alloc] initWithRootViewController:_playlistViewController];
  106. _revealController = [[GHRevealViewController alloc] initWithNibName:nil bundle:nil];
  107. _revealController.wantsFullScreenLayout = YES;
  108. _menuViewController = [[VLCMenuTableViewController alloc] initWithNibName:nil bundle:nil];
  109. _revealController.sidebarViewController = _menuViewController;
  110. _revealController.contentViewController = navCon;
  111. _playerDisplayController = [[VLCPlayerDisplayController alloc] init];
  112. _playerDisplayController.childViewController = self.revealController;
  113. self.window.rootViewController = _playerDisplayController;
  114. // necessary to avoid navbar blinking in VLCOpenNetworkStreamViewController & VLCDownloadViewController
  115. _revealController.contentViewController.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
  116. [self.window makeKeyAndVisible];
  117. [self validatePasscode];
  118. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  119. VLCMediaFileDiscoverer *discoverer = [VLCMediaFileDiscoverer sharedInstance];
  120. [discoverer addObserver:self];
  121. [discoverer startDiscovering:[self directoryPath]];
  122. };
  123. NSError *error = nil;
  124. if ([[MLMediaLibrary sharedMediaLibrary] libraryMigrationNeeded]){
  125. _isRunningMigration = YES;
  126. VLCMigrationViewController *migrationController = [[VLCMigrationViewController alloc] initWithNibName:@"VLCMigrationViewController" bundle:nil];
  127. migrationController.completionHandler = ^{
  128. //migrate
  129. setupBlock();
  130. _isRunningMigration = NO;
  131. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  132. [self updateMediaList];
  133. };
  134. self.window.rootViewController = migrationController;
  135. [self.window makeKeyAndVisible];
  136. } else {
  137. if (error != nil) {
  138. APLog(@"removed persistentStore since it was corrupt");
  139. NSURL *storeURL = ((MLMediaLibrary *)[MLMediaLibrary sharedMediaLibrary]).persistentStoreURL;
  140. [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
  141. }
  142. setupBlock();
  143. }
  144. [[VLCNotificationRelay sharedRelay] addRelayLocalName:NSManagedObjectContextDidSaveNotification toRemoteName:@"org.videolan.ios-app.dbupdate"];
  145. [[VLCNotificationRelay sharedRelay] addRelayLocalName:VLCPlaybackControllerPlaybackMetadataDidChange toRemoteName:kVLCDarwinNotificationNowPlayingInfoUpdate];
  146. #if HAVE_FABRIC
  147. [Fabric with:@[CrashlyticsKit]];
  148. #endif
  149. return YES;
  150. }
  151. #pragma mark - Handoff
  152. - (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType
  153. {
  154. if ([userActivityType isEqualToString:@"org.videolan.vlc-ios.librarymode"] ||
  155. [userActivityType isEqualToString:@"org.videolan.vlc-ios.playing"] ||
  156. [userActivityType isEqualToString:@"org.videolan.vlc-ios.libraryselection"])
  157. return YES;
  158. return NO;
  159. }
  160. - (BOOL)application:(UIApplication *)application
  161. continueUserActivity:(NSUserActivity *)userActivity
  162. restorationHandler:(void (^)(NSArray *))restorationHandler
  163. {
  164. NSString *userActivityType = userActivity.activityType;
  165. if([userActivityType isEqualToString:@"org.videolan.vlc-ios.librarymode"] ||
  166. [userActivityType isEqualToString:@"org.videolan.vlc-ios.libraryselection"]) {
  167. NSDictionary *dict = userActivity.userInfo;
  168. VLCLibraryMode libraryMode = (VLCLibraryMode)[(NSNumber *)dict[@"state"] integerValue];
  169. if (libraryMode <= VLCLibraryModeAllSeries) {
  170. [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:libraryMode inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
  171. [self.playlistViewController setLibraryMode:(VLCLibraryMode)libraryMode];
  172. }
  173. [self.playlistViewController restoreUserActivityState:userActivity];
  174. _isComingFromHandoff = YES;
  175. return YES;
  176. }
  177. return NO;
  178. }
  179. - (void)application:(UIApplication *)application didFailToContinueUserActivityWithType:(NSString *)userActivityType error:(NSError *)error
  180. {
  181. if (error.code != NSUserCancelledError){
  182. //TODO: present alert
  183. }
  184. }
  185. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  186. {
  187. if ([[DBSession sharedSession] handleOpenURL:url]) {
  188. [self.dropboxTableViewController updateViewAfterSessionChange];
  189. return YES;
  190. }
  191. if (_playlistViewController && url != nil) {
  192. APLog(@"%@ requested %@ to be opened", sourceApplication, url);
  193. if (url.isFileURL) {
  194. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  195. NSString *directoryPath = searchPaths[0];
  196. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, url.lastPathComponent]];
  197. NSError *theError;
  198. [[NSFileManager defaultManager] moveItemAtURL:url toURL:destinationURL error:&theError];
  199. if (theError.code != noErr)
  200. APLog(@"saving the file failed (%li): %@", (long)theError.code, theError.localizedDescription);
  201. [self updateMediaList];
  202. } else if ([url.scheme isEqualToString:@"vlc-x-callback"] || [url.host isEqualToString:@"x-callback-url"]) {
  203. // URL confirmes to the x-callback-url specification
  204. // vlc-x-callback://x-callback-url/action?param=value&x-success=callback
  205. APLog(@"x-callback-url with host '%@' path '%@' parameters '%@'", url.host, url.path, url.query);
  206. NSString *action = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
  207. NSURL *movieURL;
  208. NSURL *successCallback;
  209. NSURL *errorCallback;
  210. NSString *fileName;
  211. for (NSString *entry in [url.query componentsSeparatedByString:@"&"]) {
  212. NSArray *keyvalue = [entry componentsSeparatedByString:@"="];
  213. if (keyvalue.count < 2) continue;
  214. NSString *key = keyvalue[0];
  215. NSString *value = [keyvalue[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  216. if ([key isEqualToString:@"url"])
  217. movieURL = [NSURL URLWithString:value];
  218. else if ([key isEqualToString:@"filename"])
  219. fileName = value;
  220. else if ([key isEqualToString:@"x-success"])
  221. successCallback = [NSURL URLWithString:value];
  222. else if ([key isEqualToString:@"x-error"])
  223. errorCallback = [NSURL URLWithString:value];
  224. }
  225. if ([action isEqualToString:@"stream"] && movieURL) {
  226. [self openMovieFromURL:movieURL successCallback:successCallback errorCallback:errorCallback];
  227. }
  228. else if ([action isEqualToString:@"download"] && movieURL) {
  229. [self downloadMovieFromURL:movieURL fileNameOfMedia:fileName];
  230. }
  231. } else {
  232. NSString *receivedUrl = [url absoluteString];
  233. if ([receivedUrl length] > 6) {
  234. NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
  235. if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
  236. NSString *parsedString = [receivedUrl substringFromIndex:6];
  237. NSUInteger location = [parsedString rangeOfString:@"//"].location;
  238. /* Safari & al mangle vlc://http:// so fix this */
  239. if (location != NSNotFound && [parsedString characterAtIndex:location - 1] != 0x3a) { // :
  240. parsedString = [NSString stringWithFormat:@"%@://%@", [parsedString substringToIndex:location], [parsedString substringFromIndex:location+2]];
  241. } else {
  242. parsedString = [receivedUrl substringFromIndex:6];
  243. if (![parsedString hasPrefix:@"http://"] && ![parsedString hasPrefix:@"https://"] && ![parsedString hasPrefix:@"ftp://"]) {
  244. parsedString = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
  245. }
  246. }
  247. url = [NSURL URLWithString:parsedString];
  248. }
  249. }
  250. [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
  251. NSString *scheme = url.scheme;
  252. if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"]) {
  253. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"PLAY_BUTTON", nil)]];
  254. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  255. if (cancelled)
  256. [self downloadMovieFromURL:url fileNameOfMedia:nil];
  257. else
  258. [self openMovieFromURL:url];
  259. };
  260. [alert show];
  261. } else
  262. [self openMovieFromURL:url];
  263. }
  264. return YES;
  265. }
  266. return NO;
  267. }
  268. - (void)applicationWillEnterForeground:(UIApplication *)application
  269. {
  270. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  271. }
  272. - (void)applicationWillResignActive:(UIApplication *)application
  273. {
  274. _passcodeValidated = NO;
  275. [self validatePasscode];
  276. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  277. }
  278. - (void)applicationDidBecomeActive:(UIApplication *)application
  279. {
  280. if (!_isRunningMigration && !_isComingFromHandoff) {
  281. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  282. [self updateMediaList];
  283. } else if(_isComingFromHandoff) {
  284. _isComingFromHandoff = NO;
  285. }
  286. }
  287. - (void)applicationWillTerminate:(UIApplication *)application
  288. {
  289. _passcodeValidated = NO;
  290. [[NSUserDefaults standardUserDefaults] synchronize];
  291. }
  292. #pragma mark - properties
  293. - (VLCDropboxTableViewController *)dropboxTableViewController
  294. {
  295. if (_dropboxTableViewController == nil)
  296. _dropboxTableViewController = [[VLCDropboxTableViewController alloc] initWithNibName:@"VLCCloudStorageTableViewController" bundle:nil];
  297. return _dropboxTableViewController;
  298. }
  299. - (VLCDownloadViewController *)downloadViewController
  300. {
  301. if (_downloadViewController == nil) {
  302. if (SYSTEM_RUNS_IOS7_OR_LATER)
  303. _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCFutureDownloadViewController" bundle:nil];
  304. else
  305. _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
  306. }
  307. return _downloadViewController;
  308. }
  309. #pragma mark - media discovering
  310. - (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
  311. {
  312. if (!isLoading) {
  313. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  314. [sharedLibrary addFilePaths:@[fileName]];
  315. /* exclude media files from backup (QA1719) */
  316. NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
  317. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  318. // TODO Should we update media db after adding new files?
  319. [sharedLibrary updateMediaDatabase];
  320. [_playlistViewController updateViewContents];
  321. }
  322. }
  323. - (void)mediaFileDeleted:(NSString *)name
  324. {
  325. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  326. [_playlistViewController updateViewContents];
  327. }
  328. - (void)cleanCache
  329. {
  330. if ([self haveNetworkActivity])
  331. return;
  332. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  333. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  334. NSFileManager *fileManager = [NSFileManager defaultManager];
  335. if ([fileManager fileExistsAtPath:uploadDirPath])
  336. [fileManager removeItemAtPath:uploadDirPath error:nil];
  337. }
  338. #pragma mark - media list methods
  339. - (NSString *)directoryPath
  340. {
  341. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  342. NSString *directoryPath = searchPaths[0];
  343. return directoryPath;
  344. }
  345. - (void)updateMediaList
  346. {
  347. NSString *directoryPath = [self directoryPath];
  348. NSMutableArray *foundFiles = [NSMutableArray arrayWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil]];
  349. NSMutableArray *filePaths = [NSMutableArray array];
  350. NSURL *fileURL;
  351. while (foundFiles.count) {
  352. NSString *fileName = foundFiles.firstObject;
  353. NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
  354. [foundFiles removeObject:fileName];
  355. if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
  356. [filePaths addObject:filePath];
  357. /* exclude media files from backup (QA1719) */
  358. fileURL = [NSURL fileURLWithPath:filePath];
  359. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  360. } else {
  361. BOOL isDirectory = NO;
  362. BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
  363. // add folders
  364. if (exists && isDirectory) {
  365. NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
  366. for (NSString* file in files) {
  367. NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:file];
  368. isDirectory = NO;
  369. exists = [[NSFileManager defaultManager] fileExistsAtPath:fullFilePath isDirectory:&isDirectory];
  370. //only add folders or files in folders
  371. if ((exists && isDirectory) || ![filePath.lastPathComponent isEqualToString:@"Documents"]) {
  372. NSString *folderpath = [filePath stringByReplacingOccurrencesOfString:directoryPath withString:@""];
  373. if (![folderpath isEqualToString:@""]) {
  374. folderpath = [folderpath stringByAppendingString:@"/"];
  375. }
  376. NSString *path = [folderpath stringByAppendingString:file];
  377. [foundFiles addObject:path];
  378. }
  379. }
  380. }
  381. }
  382. }
  383. [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
  384. [_playlistViewController updateViewContents];
  385. }
  386. #pragma mark - pass code validation
  387. - (BOOL)passcodeValidated
  388. {
  389. return _passcodeValidated;
  390. }
  391. - (void)validatePasscode
  392. {
  393. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  394. NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
  395. if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
  396. _passcodeValidated = YES;
  397. return;
  398. }
  399. if (!_passcodeValidated) {
  400. _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
  401. _passcodeLockController.delegate = self;
  402. _passcodeLockController.passcode = passcode;
  403. if (self.window.rootViewController.presentedViewController)
  404. [self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];
  405. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_passcodeLockController];
  406. navCon.modalPresentationStyle = UIModalPresentationFullScreen;
  407. [self.window.rootViewController presentViewController:navCon animated:NO completion:nil];
  408. }
  409. }
  410. - (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
  411. {
  412. _passcodeValidated = YES;
  413. [self.playlistViewController updateViewContents];
  414. [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
  415. }
  416. - (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
  417. {
  418. // FIXME: handle countless failed passcode attempts
  419. }
  420. #pragma mark - idle timer preventer
  421. - (void)disableIdleTimer
  422. {
  423. _idleCounter++;
  424. if ([UIApplication sharedApplication].idleTimerDisabled == NO)
  425. [UIApplication sharedApplication].idleTimerDisabled = YES;
  426. }
  427. - (void)activateIdleTimer
  428. {
  429. _idleCounter--;
  430. if (_idleCounter < 1)
  431. [UIApplication sharedApplication].idleTimerDisabled = NO;
  432. }
  433. - (void)networkActivityStarted
  434. {
  435. _networkActivityCounter++;
  436. if ([UIApplication sharedApplication].networkActivityIndicatorVisible == NO)
  437. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  438. }
  439. - (BOOL)haveNetworkActivity
  440. {
  441. return _networkActivityCounter >= 1;
  442. }
  443. - (void)networkActivityStopped
  444. {
  445. _networkActivityCounter--;
  446. if (_networkActivityCounter < 1)
  447. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  448. }
  449. #pragma mark - download handling
  450. - (void)downloadMovieFromURL:(NSURL *)url
  451. fileNameOfMedia:(NSString *)fileName
  452. {
  453. [self.downloadViewController addURLToDownloadList:url fileNameOfMedia:fileName];
  454. // select Downloads menu item and reveal corresponding viewcontroller
  455. [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1] animated:NO scrollPosition:UITableViewScrollPositionNone];
  456. }
  457. #pragma mark - playback view handling
  458. - (void)openMediaFromManagedObject:(NSManagedObject *)mediaObject
  459. {
  460. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  461. [vpc playMediaLibraryObject:mediaObject];
  462. }
  463. - (void)openMovieFromURL:(NSURL *)url
  464. successCallback:(NSURL *)successCallback
  465. errorCallback:(NSURL *)errorCallback
  466. {
  467. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  468. vpc.url = url;
  469. vpc.successCallback = successCallback;
  470. vpc.errorCallback = errorCallback;
  471. [vpc startPlayback];
  472. }
  473. - (void)openMovieFromURL:(NSURL *)url
  474. {
  475. [self openMovieFromURL:url successCallback:nil errorCallback:nil];
  476. }
  477. - (void)openMovieWithExternalSubtitleFromURL:(NSURL *)url externalSubURL:(NSString *)SubtitlePath
  478. {
  479. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  480. vpc.url = url;
  481. vpc.pathToExternalSubtitlesFile = SubtitlePath;
  482. [vpc startPlayback];
  483. }
  484. #pragma mark - watch struff
  485. - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
  486. {
  487. /* dispatch background task */
  488. __block UIBackgroundTaskIdentifier taskIdentifier = [application beginBackgroundTaskWithName:nil
  489. expirationHandler:^{
  490. [application endBackgroundTask:taskIdentifier];
  491. taskIdentifier = UIBackgroundTaskInvalid;
  492. }];
  493. VLCWatchMessage *message = [[VLCWatchMessage alloc] initWithDictionary:userInfo];
  494. NSString *name = message.name;
  495. NSDictionary *responseDict = nil;
  496. if ([name isEqualToString:VLCWatchMessageNameGetNowPlayingInfo]) {
  497. responseDict = [self nowPlayingResponseDict];
  498. } else if ([name isEqualToString:VLCWatchMessageNamePlayPause]) {
  499. [[VLCPlaybackController sharedInstance] playPause];
  500. responseDict = @{@"playing": @([VLCPlaybackController sharedInstance].isPlaying)};
  501. } else if ([name isEqualToString:VLCWatchMessageNameSkipForward]) {
  502. [[VLCPlaybackController sharedInstance] forward];
  503. } else if ([name isEqualToString:VLCWatchMessageNameSkipBackward]) {
  504. [[VLCPlaybackController sharedInstance] backward];
  505. } else if ([name isEqualToString:VLCWatchMessageNamePlayFile]) {
  506. [self playFileFromWatch:message];
  507. } else if ([name isEqualToString:VLCWatchMessageNameSetVolume]) {
  508. [self setVolumeFromWatch:message];
  509. } else {
  510. APLog(@"Did not handle request from WatchKit Extension: %@",userInfo);
  511. }
  512. reply(responseDict);
  513. }
  514. - (void)playFileFromWatch:(VLCWatchMessage *)message
  515. {
  516. NSManagedObject *managedObject = nil;
  517. NSString *uriString = (id)message.payload;
  518. if ([uriString isKindOfClass:[NSString class]]) {
  519. NSURL *uriRepresentation = [NSURL URLWithString:uriString];
  520. managedObject = [[MLMediaLibrary sharedMediaLibrary] objectForURIRepresentation:uriRepresentation];
  521. }
  522. if (managedObject == nil) {
  523. APLog(@"%s file not found: %@",__PRETTY_FUNCTION__,message);
  524. return;
  525. }
  526. [self openMediaFromManagedObject:managedObject];
  527. }
  528. - (void)setVolumeFromWatch:(VLCWatchMessage *)message
  529. {
  530. NSNumber *volume = (id)message.payload;
  531. if ([volume isKindOfClass:[NSNumber class]]) {
  532. /*
  533. * Since WatchKit doen't provide something like MPVolumeView we use deprecated API.
  534. * rdar://20783803 Feature Request: WatchKit equivalent for MPVolumeView
  535. */
  536. [MPMusicPlayerController applicationMusicPlayer].volume = volume.floatValue;
  537. }
  538. }
  539. - (NSDictionary *)nowPlayingResponseDict {
  540. NSMutableDictionary *response = [NSMutableDictionary new];
  541. NSMutableDictionary *nowPlayingInfo = [[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo mutableCopy];
  542. NSNumber *playbackTime = [VLCPlaybackController sharedInstance].mediaPlayer.time.numberValue;
  543. if (playbackTime) {
  544. nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(playbackTime.floatValue/1000);
  545. }
  546. if (nowPlayingInfo) {
  547. response[@"nowPlayingInfo"] = nowPlayingInfo;
  548. }
  549. MLFile *currentFile = [VLCPlaybackController sharedInstance].currentlyPlayingMediaFile;
  550. NSString *URIString = currentFile.objectID.URIRepresentation.absoluteString;
  551. if (URIString) {
  552. response[@"URIRepresentation"] = URIString;
  553. }
  554. response[@"volume"] = @([MPMusicPlayerController applicationMusicPlayer].volume);
  555. return response;
  556. }
  557. @end