VLCAppDelegate.m 29 KB

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