VLCAppDelegate.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 "VLCLibraryViewController.h"
  23. #import "VLCHTTPUploaderController.h"
  24. #import "VLCMigrationViewController.h"
  25. #import <BoxSDK/BoxSDK.h>
  26. #import "VLCPlaybackController.h"
  27. #import "VLCPlaybackController+MediaLibrary.h"
  28. #import "VLCPlayerDisplayController.h"
  29. #import <MediaPlayer/MediaPlayer.h>
  30. #import <DropboxSDK/DropboxSDK.h>
  31. #import <HockeySDK/HockeySDK.h>
  32. #import "VLCSidebarController.h"
  33. #import "VLCKeychainCoordinator.h"
  34. #import "VLCActivityManager.h"
  35. NSString *const VLCDropboxSessionWasAuthorized = @"VLCDropboxSessionWasAuthorized";
  36. #define BETA_DISTRIBUTION 1
  37. @interface VLCAppDelegate () <VLCMediaFileDiscovererDelegate>
  38. {
  39. BOOL _passcodeValidated;
  40. BOOL _isRunningMigration;
  41. BOOL _isComingFromHandoff;
  42. VLCWatchCommunication *_watchCommunication;
  43. }
  44. @end
  45. @implementation VLCAppDelegate
  46. + (void)initialize
  47. {
  48. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  49. NSNumber *skipLoopFilterDefaultValue;
  50. int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
  51. if (deviceSpeedCategory < 3)
  52. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
  53. else
  54. skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
  55. NSDictionary *appDefaults = @{kVLCSettingPasscodeKey : @"",
  56. kVLCSettingContinueAudioInBackgroundKey : @(YES),
  57. kVLCSettingStretchAudio : @(NO),
  58. kVLCSettingTextEncoding : kVLCSettingTextEncodingDefaultValue,
  59. kVLCSettingSkipLoopFilter : skipLoopFilterDefaultValue,
  60. kVLCSettingSubtitlesFont : kVLCSettingSubtitlesFontDefaultValue,
  61. kVLCSettingSubtitlesFontColor : kVLCSettingSubtitlesFontColorDefaultValue,
  62. kVLCSettingSubtitlesFontSize : kVLCSettingSubtitlesFontSizeDefaultValue,
  63. kVLCSettingSubtitlesBoldFont: kVLCSettingSubtitlesBoldFontDefaultValue,
  64. kVLCSettingDeinterlace : kVLCSettingDeinterlaceDefaultValue,
  65. kVLCSettingNetworkCaching : kVLCSettingNetworkCachingDefaultValue,
  66. kVLCSettingPlaybackGestures : @(YES),
  67. kVLCSettingVideoFullscreenPlayback : @(YES),
  68. kVLCSettingFTPTextEncoding : kVLCSettingFTPTextEncodingDefaultValue,
  69. kVLCSettingWiFiSharingIPv6 : kVLCSettingWiFiSharingIPv6DefaultValue,
  70. kVLCSettingEqualizerProfile : kVLCSettingEqualizerProfileDefaultValue,
  71. kVLCSettingPlaybackForwardSkipLength : kVLCSettingPlaybackForwardSkipLengthDefaultValue,
  72. kVLCSettingPlaybackBackwardSkipLength : kVLCSettingPlaybackBackwardSkipLengthDefaultValue,
  73. kVLCSettingOpenAppForPlayback : kVLCSettingOpenAppForPlaybackDefaultValue};
  74. [defaults registerDefaults:appDefaults];
  75. }
  76. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  77. {
  78. BITHockeyManager *hockeyManager = [BITHockeyManager sharedHockeyManager];
  79. if (BETA_DISTRIBUTION) {
  80. APLog(@"Using HockeySDK beta key");
  81. [hockeyManager configureWithIdentifier:@"0114ca8e265244ce588d2ebd035c3577"];
  82. } else
  83. [hockeyManager configureWithIdentifier:@"c95f4227dff96c61f8b3a46a25edc584"];
  84. // Configure the SDK in here only!
  85. [hockeyManager startManager];
  86. [hockeyManager.authenticator authenticateInstallation];
  87. /* listen to validation notification */
  88. [[NSNotificationCenter defaultCenter] addObserver:self
  89. selector:@selector(passcodeWasValidated:)
  90. name:VLCPasscodeValidated
  91. object:nil];
  92. // Change the keyboard for UISearchBar
  93. [[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];
  94. // For the cursor
  95. [[UITextField appearance] setTintColor:[UIColor VLCOrangeTintColor]];
  96. // Don't override the 'Cancel' button color in the search bar with the previous UITextField call. Use the default blue color
  97. [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]} forState:UIControlStateNormal];
  98. // For the edit selection indicators
  99. [[UITableView appearance] setTintColor:[UIColor VLCOrangeTintColor]];
  100. [[UISwitch appearance] setOnTintColor:[UIColor VLCOrangeTintColor]];
  101. // Init the HTTP Server and clean its cache
  102. [[VLCHTTPUploaderController sharedInstance] cleanCache];
  103. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  104. // enable crash preventer
  105. void (^setupBlock)() = ^{
  106. _libraryViewController = [[VLCLibraryViewController alloc] init];
  107. VLCSidebarController *sidebarVC = [VLCSidebarController sharedInstance];
  108. VLCNavigationController *navCon = [[VLCNavigationController alloc] initWithRootViewController:_libraryViewController];
  109. sidebarVC.contentViewController = navCon;
  110. _playerDisplayController = [[VLCPlayerDisplayController alloc] init];
  111. _playerDisplayController.childViewController = sidebarVC.fullViewController;
  112. self.window.rootViewController = _playerDisplayController;
  113. [self.window makeKeyAndVisible];
  114. [self validatePasscode];
  115. BOOL spotlightEnabled = ![[VLCKeychainCoordinator defaultCoordinator] passcodeLockEnabled];
  116. [[MLMediaLibrary sharedMediaLibrary] setSpotlightIndexingEnabled:spotlightEnabled];
  117. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  118. VLCMediaFileDiscoverer *discoverer = [VLCMediaFileDiscoverer sharedInstance];
  119. [discoverer addObserver:self];
  120. [discoverer startDiscovering];
  121. };
  122. NSError *error = nil;
  123. if ([[MLMediaLibrary sharedMediaLibrary] libraryMigrationNeeded]){
  124. _isRunningMigration = YES;
  125. VLCMigrationViewController *migrationController = [[VLCMigrationViewController alloc] initWithNibName:@"VLCMigrationViewController" bundle:nil];
  126. migrationController.completionHandler = ^{
  127. //migrate
  128. setupBlock();
  129. _isRunningMigration = NO;
  130. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  131. [[VLCMediaFileDiscoverer sharedInstance] updateMediaList];
  132. };
  133. self.window.rootViewController = migrationController;
  134. [self.window makeKeyAndVisible];
  135. } else {
  136. if (error != nil) {
  137. APLog(@"removed persistentStore since it was corrupt");
  138. NSURL *storeURL = ((MLMediaLibrary *)[MLMediaLibrary sharedMediaLibrary]).persistentStoreURL;
  139. [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
  140. }
  141. setupBlock();
  142. }
  143. if ([VLCWatchCommunication isSupported]) {
  144. _watchCommunication = [VLCWatchCommunication sharedInstance];
  145. // TODO: push DB changes instead
  146. // [_watchCommunication startRelayingNotificationName:NSManagedObjectContextDidSaveNotification object:nil];
  147. [_watchCommunication startRelayingNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:nil];
  148. }
  149. return YES;
  150. }
  151. - (void)dealloc
  152. {
  153. [[NSNotificationCenter defaultCenter] removeObserver:self];
  154. }
  155. #pragma mark - Handoff
  156. - (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType
  157. {
  158. if ([userActivityType isEqualToString:kVLCUserActivityLibraryMode] ||
  159. [userActivityType isEqualToString:kVLCUserActivityPlaying] ||
  160. [userActivityType isEqualToString:kVLCUserActivityLibrarySelection])
  161. return YES;
  162. return NO;
  163. }
  164. - (BOOL)application:(UIApplication *)application
  165. continueUserActivity:(NSUserActivity *)userActivity
  166. restorationHandler:(void (^)(NSArray *))restorationHandler
  167. {
  168. NSString *userActivityType = userActivity.activityType;
  169. NSDictionary *dict = userActivity.userInfo;
  170. if([userActivityType isEqualToString:kVLCUserActivityLibraryMode] ||
  171. [userActivityType isEqualToString:kVLCUserActivityLibrarySelection]) {
  172. VLCLibraryMode libraryMode = (VLCLibraryMode)[(NSNumber *)dict[@"state"] integerValue];
  173. if (libraryMode <= VLCLibraryModeAllSeries) {
  174. [[VLCSidebarController sharedInstance] selectRowAtIndexPath:[NSIndexPath indexPathForRow:libraryMode inSection:0]
  175. scrollPosition:UITableViewScrollPositionTop];
  176. [self.libraryViewController setLibraryMode:libraryMode];
  177. }
  178. [self.libraryViewController restoreUserActivityState:userActivity];
  179. _isComingFromHandoff = YES;
  180. return YES;
  181. } else {
  182. NSURL *uriRepresentation = nil;
  183. if ([userActivityType isEqualToString:CSSearchableItemActionType]) {
  184. uriRepresentation = [NSURL URLWithString:dict[CSSearchableItemActivityIdentifier]];
  185. } else {
  186. uriRepresentation = dict[@"playingmedia"];
  187. }
  188. if (!uriRepresentation) {
  189. return NO;
  190. }
  191. NSManagedObject *managedObject = [[MLMediaLibrary sharedMediaLibrary] objectForURIRepresentation:uriRepresentation];
  192. if (managedObject == nil) {
  193. APLog(@"%s file not found: %@",__PRETTY_FUNCTION__,userActivity);
  194. return NO;
  195. }
  196. [[VLCPlaybackController sharedInstance] openMediaLibraryObject:managedObject];
  197. return YES;
  198. }
  199. return NO;
  200. }
  201. - (void)application:(UIApplication *)application
  202. didFailToContinueUserActivityWithType:(NSString *)userActivityType
  203. error:(NSError *)error
  204. {
  205. if (error.code != NSUserCancelledError){
  206. //TODO: present alert
  207. }
  208. }
  209. - (BOOL)application:(UIApplication *)application
  210. openURL:(NSURL *)url
  211. sourceApplication:(NSString *)sourceApplication
  212. annotation:(id)annotation
  213. {
  214. if ([[DBSession sharedSession] handleOpenURL:url]) {
  215. [[NSNotificationCenter defaultCenter] postNotificationName:VLCDropboxSessionWasAuthorized object:nil];
  216. return YES;
  217. }
  218. if (_libraryViewController && url != nil) {
  219. APLog(@"%@ requested %@ to be opened", sourceApplication, url);
  220. if (url.isFileURL) {
  221. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  222. NSString *directoryPath = searchPaths[0];
  223. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, url.lastPathComponent]];
  224. NSError *theError;
  225. [[NSFileManager defaultManager] moveItemAtURL:url toURL:destinationURL error:&theError];
  226. if (theError.code != noErr)
  227. APLog(@"saving the file failed (%li): %@", (long)theError.code, theError.localizedDescription);
  228. [[VLCMediaFileDiscoverer sharedInstance] updateMediaList];
  229. } else if ([url.scheme isEqualToString:@"vlc-x-callback"] || [url.host isEqualToString:@"x-callback-url"]) {
  230. // URL confirmes to the x-callback-url specification
  231. // vlc-x-callback://x-callback-url/action?param=value&x-success=callback
  232. APLog(@"x-callback-url with host '%@' path '%@' parameters '%@'", url.host, url.path, url.query);
  233. NSString *action = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
  234. NSURL *movieURL;
  235. NSURL *successCallback;
  236. NSURL *errorCallback;
  237. NSString *fileName;
  238. for (NSString *entry in [url.query componentsSeparatedByString:@"&"]) {
  239. NSArray *keyvalue = [entry componentsSeparatedByString:@"="];
  240. if (keyvalue.count < 2) continue;
  241. NSString *key = keyvalue[0];
  242. NSString *value = [keyvalue[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  243. if ([key isEqualToString:@"url"])
  244. movieURL = [NSURL URLWithString:value];
  245. else if ([key isEqualToString:@"filename"])
  246. fileName = value;
  247. else if ([key isEqualToString:@"x-success"])
  248. successCallback = [NSURL URLWithString:value];
  249. else if ([key isEqualToString:@"x-error"])
  250. errorCallback = [NSURL URLWithString:value];
  251. }
  252. if ([action isEqualToString:@"stream"] && movieURL) {
  253. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  254. vpc.fullscreenSessionRequested = YES;
  255. [vpc playURL:movieURL successCallback:successCallback errorCallback:errorCallback];
  256. }
  257. else if ([action isEqualToString:@"download"] && movieURL) {
  258. [self downloadMovieFromURL:movieURL fileNameOfMedia:fileName];
  259. }
  260. } else {
  261. NSString *receivedUrl = [url absoluteString];
  262. if ([receivedUrl length] > 6) {
  263. NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
  264. if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
  265. NSString *parsedString = [receivedUrl substringFromIndex:6];
  266. NSUInteger location = [parsedString rangeOfString:@"//"].location;
  267. /* Safari & al mangle vlc://http:// so fix this */
  268. if (location != NSNotFound && [parsedString characterAtIndex:location - 1] != 0x3a) { // :
  269. parsedString = [NSString stringWithFormat:@"%@://%@", [parsedString substringToIndex:location], [parsedString substringFromIndex:location+2]];
  270. } else {
  271. parsedString = [receivedUrl substringFromIndex:6];
  272. if (![parsedString hasPrefix:@"http://"] && ![parsedString hasPrefix:@"https://"] && ![parsedString hasPrefix:@"ftp://"]) {
  273. parsedString = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
  274. }
  275. }
  276. url = [NSURL URLWithString:parsedString];
  277. }
  278. }
  279. [[VLCSidebarController sharedInstance] selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
  280. scrollPosition:UITableViewScrollPositionNone];
  281. NSString *scheme = url.scheme;
  282. if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"]) {
  283. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"PLAY_BUTTON", nil)]];
  284. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  285. if (cancelled)
  286. [self downloadMovieFromURL:url fileNameOfMedia:nil];
  287. else {
  288. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  289. [vpc playURL:url successCallback:nil errorCallback:nil];
  290. }
  291. };
  292. [alert show];
  293. } else {
  294. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  295. vpc.fullscreenSessionRequested = YES;
  296. [vpc playURL:url successCallback:nil errorCallback:nil];
  297. }
  298. }
  299. return YES;
  300. }
  301. return NO;
  302. }
  303. - (void)applicationWillEnterForeground:(UIApplication *)application
  304. {
  305. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  306. }
  307. - (void)applicationWillResignActive:(UIApplication *)application
  308. {
  309. _passcodeValidated = NO;
  310. [self.libraryViewController setEditing:NO animated:NO];
  311. [self validatePasscode];
  312. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  313. }
  314. - (void)applicationDidBecomeActive:(UIApplication *)application
  315. {
  316. if (!_isRunningMigration && !_isComingFromHandoff) {
  317. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  318. [[VLCMediaFileDiscoverer sharedInstance] updateMediaList];
  319. } else if(_isComingFromHandoff) {
  320. _isComingFromHandoff = NO;
  321. }
  322. }
  323. - (void)applicationWillTerminate:(UIApplication *)application
  324. {
  325. _passcodeValidated = NO;
  326. [[NSUserDefaults standardUserDefaults] synchronize];
  327. }
  328. #pragma mark - media discovering
  329. - (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
  330. {
  331. if (!isLoading) {
  332. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  333. [sharedLibrary addFilePaths:@[fileName]];
  334. /* exclude media files from backup (QA1719) */
  335. NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
  336. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  337. // TODO Should we update media db after adding new files?
  338. [sharedLibrary updateMediaDatabase];
  339. [_libraryViewController updateViewContents];
  340. }
  341. }
  342. - (void)mediaFileDeleted:(NSString *)name
  343. {
  344. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  345. [_libraryViewController updateViewContents];
  346. }
  347. #pragma mark - pass code validation
  348. - (void)passcodeWasValidated:(NSNotification *)aNotifcation
  349. {
  350. _passcodeValidated = YES;
  351. [self.libraryViewController updateViewContents];
  352. if ([VLCPlaybackController sharedInstance].isPlaying)
  353. [_playerDisplayController pushPlaybackView];
  354. }
  355. - (BOOL)passcodeValidated
  356. {
  357. return _passcodeValidated;
  358. }
  359. - (void)validatePasscode
  360. {
  361. VLCKeychainCoordinator *keychainCoordinator = [VLCKeychainCoordinator defaultCoordinator];
  362. if (!_passcodeValidated && [keychainCoordinator passcodeLockEnabled]) {
  363. [_playerDisplayController dismissPlaybackView];
  364. [keychainCoordinator validatePasscode];
  365. } else
  366. _passcodeValidated = YES;
  367. }
  368. #pragma mark - download handling
  369. - (void)downloadMovieFromURL:(NSURL *)url
  370. fileNameOfMedia:(NSString *)fileName
  371. {
  372. [[VLCDownloadViewController sharedInstance] addURLToDownloadList:url fileNameOfMedia:fileName];
  373. [[VLCSidebarController sharedInstance] selectRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]
  374. scrollPosition:UITableViewScrollPositionNone];
  375. }
  376. #pragma mark - remote events pre 7.1
  377. - (void)remoteControlReceivedWithEvent:(UIEvent *)event {
  378. [[VLCPlaybackController sharedInstance] remoteControlReceivedWithEvent:event];
  379. }
  380. #pragma mark - watch stuff
  381. - (void)application:(UIApplication *)application
  382. handleWatchKitExtensionRequest:(NSDictionary *)userInfo
  383. reply:(void (^)(NSDictionary *))reply
  384. {
  385. if ([VLCWatchCommunication isSupported]) {
  386. [self.watchCommunication session:[WCSession defaultSession] didReceiveMessage:userInfo replyHandler:reply];
  387. }
  388. }
  389. @end