VLCAppDelegate.m 21 KB

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