VLCAppDelegate.m 25 KB

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