VLCAppDelegate.m 21 KB

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