VLCAppDelegate.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  126. discoverer.directoryPath = [searchPaths firstObject];
  127. [discoverer addObserver:self];
  128. [discoverer startDiscovering];
  129. };
  130. NSError *error = nil;
  131. if ([[MLMediaLibrary sharedMediaLibrary] libraryMigrationNeeded]){
  132. _isRunningMigration = YES;
  133. VLCMigrationViewController *migrationController = [[VLCMigrationViewController alloc] initWithNibName:@"VLCMigrationViewController" bundle:nil];
  134. migrationController.completionHandler = ^{
  135. //migrate
  136. setupBlock();
  137. _isRunningMigration = NO;
  138. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  139. [[VLCMediaFileDiscoverer sharedInstance] updateMediaList];
  140. };
  141. self.window.rootViewController = migrationController;
  142. [self.window makeKeyAndVisible];
  143. } else {
  144. if (error != nil) {
  145. APLog(@"removed persistentStore since it was corrupt");
  146. NSURL *storeURL = ((MLMediaLibrary *)[MLMediaLibrary sharedMediaLibrary]).persistentStoreURL;
  147. [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
  148. }
  149. setupBlock();
  150. }
  151. if ([VLCWatchCommunication isSupported]) {
  152. _watchCommunication = [VLCWatchCommunication sharedInstance];
  153. // TODO: push DB changes instead
  154. // [_watchCommunication startRelayingNotificationName:NSManagedObjectContextDidSaveNotification object:nil];
  155. [_watchCommunication startRelayingNotificationName:VLCPlaybackControllerPlaybackMetadataDidChange object:nil];
  156. }
  157. return YES;
  158. }
  159. - (void)dealloc
  160. {
  161. [[NSNotificationCenter defaultCenter] removeObserver:self];
  162. }
  163. #pragma mark - Handoff
  164. - (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType
  165. {
  166. if ([userActivityType isEqualToString:kVLCUserActivityLibraryMode] ||
  167. [userActivityType isEqualToString:kVLCUserActivityPlaying] ||
  168. [userActivityType isEqualToString:kVLCUserActivityLibrarySelection])
  169. return YES;
  170. return NO;
  171. }
  172. - (BOOL)application:(UIApplication *)application
  173. continueUserActivity:(NSUserActivity *)userActivity
  174. restorationHandler:(void (^)(NSArray *))restorationHandler
  175. {
  176. NSString *userActivityType = userActivity.activityType;
  177. NSDictionary *dict = userActivity.userInfo;
  178. if([userActivityType isEqualToString:kVLCUserActivityLibraryMode] ||
  179. [userActivityType isEqualToString:kVLCUserActivityLibrarySelection]) {
  180. VLCLibraryMode libraryMode = (VLCLibraryMode)[(NSNumber *)dict[@"state"] integerValue];
  181. if (libraryMode <= VLCLibraryModeAllSeries) {
  182. [[VLCSidebarController sharedInstance] selectRowAtIndexPath:[NSIndexPath indexPathForRow:libraryMode inSection:0]
  183. scrollPosition:UITableViewScrollPositionTop];
  184. [self.libraryViewController setLibraryMode:libraryMode];
  185. }
  186. [self.libraryViewController restoreUserActivityState:userActivity];
  187. _isComingFromHandoff = YES;
  188. return YES;
  189. } else {
  190. NSURL *uriRepresentation = nil;
  191. if ([userActivityType isEqualToString:CSSearchableItemActionType]) {
  192. uriRepresentation = [NSURL URLWithString:dict[CSSearchableItemActivityIdentifier]];
  193. } else {
  194. uriRepresentation = dict[@"playingmedia"];
  195. }
  196. if (!uriRepresentation) {
  197. return NO;
  198. }
  199. NSManagedObject *managedObject = [[MLMediaLibrary sharedMediaLibrary] objectForURIRepresentation:uriRepresentation];
  200. if (managedObject == nil) {
  201. APLog(@"%s file not found: %@",__PRETTY_FUNCTION__,userActivity);
  202. return NO;
  203. }
  204. [[VLCPlaybackController sharedInstance] openMediaLibraryObject:managedObject];
  205. return YES;
  206. }
  207. return NO;
  208. }
  209. - (void)application:(UIApplication *)application
  210. didFailToContinueUserActivityWithType:(NSString *)userActivityType
  211. error:(NSError *)error
  212. {
  213. if (error.code != NSUserCancelledError){
  214. //TODO: present alert
  215. }
  216. }
  217. - (BOOL)application:(UIApplication *)application
  218. openURL:(NSURL *)url
  219. sourceApplication:(NSString *)sourceApplication
  220. annotation:(id)annotation
  221. {
  222. if ([[DBSession sharedSession] handleOpenURL:url]) {
  223. [[NSNotificationCenter defaultCenter] postNotificationName:VLCDropboxSessionWasAuthorized object:nil];
  224. return YES;
  225. }
  226. if (_libraryViewController && url != nil) {
  227. APLog(@"%@ requested %@ to be opened", sourceApplication, url);
  228. if (url.isFileURL) {
  229. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  230. NSString *directoryPath = searchPaths[0];
  231. NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, url.lastPathComponent]];
  232. NSError *theError;
  233. [[NSFileManager defaultManager] moveItemAtURL:url toURL:destinationURL error:&theError];
  234. if (theError.code != noErr)
  235. APLog(@"saving the file failed (%li): %@", (long)theError.code, theError.localizedDescription);
  236. [[VLCMediaFileDiscoverer sharedInstance] updateMediaList];
  237. } else if ([url.scheme isEqualToString:@"vlc-x-callback"] || [url.host isEqualToString:@"x-callback-url"]) {
  238. // URL confirmes to the x-callback-url specification
  239. // vlc-x-callback://x-callback-url/action?param=value&x-success=callback
  240. APLog(@"x-callback-url with host '%@' path '%@' parameters '%@'", url.host, url.path, url.query);
  241. NSString *action = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
  242. NSURL *movieURL;
  243. NSURL *successCallback;
  244. NSURL *errorCallback;
  245. NSString *fileName;
  246. for (NSString *entry in [url.query componentsSeparatedByString:@"&"]) {
  247. NSArray *keyvalue = [entry componentsSeparatedByString:@"="];
  248. if (keyvalue.count < 2) continue;
  249. NSString *key = keyvalue[0];
  250. NSString *value = [keyvalue[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  251. if ([key isEqualToString:@"url"])
  252. movieURL = [NSURL URLWithString:value];
  253. else if ([key isEqualToString:@"filename"])
  254. fileName = value;
  255. else if ([key isEqualToString:@"x-success"])
  256. successCallback = [NSURL URLWithString:value];
  257. else if ([key isEqualToString:@"x-error"])
  258. errorCallback = [NSURL URLWithString:value];
  259. }
  260. if ([action isEqualToString:@"stream"] && movieURL) {
  261. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  262. vpc.fullscreenSessionRequested = YES;
  263. [vpc playURL:movieURL successCallback:successCallback errorCallback:errorCallback];
  264. }
  265. else if ([action isEqualToString:@"download"] && movieURL) {
  266. [self downloadMovieFromURL:movieURL fileNameOfMedia:fileName];
  267. }
  268. } else {
  269. NSString *receivedUrl = [url absoluteString];
  270. if ([receivedUrl length] > 6) {
  271. NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
  272. if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
  273. NSString *parsedString = [receivedUrl substringFromIndex:6];
  274. NSUInteger location = [parsedString rangeOfString:@"//"].location;
  275. /* Safari & al mangle vlc://http:// so fix this */
  276. if (location != NSNotFound && [parsedString characterAtIndex:location - 1] != 0x3a) { // :
  277. parsedString = [NSString stringWithFormat:@"%@://%@", [parsedString substringToIndex:location], [parsedString substringFromIndex:location+2]];
  278. } else {
  279. parsedString = [receivedUrl substringFromIndex:6];
  280. if (![parsedString hasPrefix:@"http://"] && ![parsedString hasPrefix:@"https://"] && ![parsedString hasPrefix:@"ftp://"]) {
  281. parsedString = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
  282. }
  283. }
  284. url = [NSURL URLWithString:parsedString];
  285. }
  286. }
  287. [[VLCSidebarController sharedInstance] selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
  288. scrollPosition:UITableViewScrollPositionNone];
  289. NSString *scheme = url.scheme;
  290. if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"]) {
  291. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"PLAY_BUTTON", nil)]];
  292. alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
  293. if (cancelled)
  294. [self downloadMovieFromURL:url fileNameOfMedia:nil];
  295. else {
  296. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  297. [vpc playURL:url successCallback:nil errorCallback:nil];
  298. }
  299. };
  300. [alert show];
  301. } else {
  302. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  303. vpc.fullscreenSessionRequested = YES;
  304. [vpc playURL:url successCallback:nil errorCallback:nil];
  305. }
  306. }
  307. return YES;
  308. }
  309. return NO;
  310. }
  311. - (void)applicationWillEnterForeground:(UIApplication *)application
  312. {
  313. [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
  314. }
  315. - (void)applicationWillResignActive:(UIApplication *)application
  316. {
  317. _passcodeValidated = NO;
  318. [self.libraryViewController setEditing:NO animated:NO];
  319. [self validatePasscode];
  320. [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
  321. }
  322. - (void)applicationDidBecomeActive:(UIApplication *)application
  323. {
  324. if (!_isRunningMigration && !_isComingFromHandoff) {
  325. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  326. [[VLCMediaFileDiscoverer sharedInstance] updateMediaList];
  327. } else if(_isComingFromHandoff) {
  328. _isComingFromHandoff = NO;
  329. }
  330. }
  331. - (void)applicationWillTerminate:(UIApplication *)application
  332. {
  333. _passcodeValidated = NO;
  334. [[NSUserDefaults standardUserDefaults] synchronize];
  335. }
  336. #pragma mark - media discovering
  337. - (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
  338. {
  339. if (!isLoading) {
  340. MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
  341. [sharedLibrary addFilePaths:@[fileName]];
  342. /* exclude media files from backup (QA1719) */
  343. NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
  344. [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  345. // TODO Should we update media db after adding new files?
  346. [sharedLibrary updateMediaDatabase];
  347. [_libraryViewController updateViewContents];
  348. }
  349. }
  350. - (void)mediaFileDeleted:(NSString *)name
  351. {
  352. [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
  353. [_libraryViewController updateViewContents];
  354. }
  355. - (void)mediaFilesFoundRequiringAdditionToStorageBackend:(NSArray<NSString *> *)foundFiles
  356. {
  357. [[MLMediaLibrary sharedMediaLibrary] addFilePaths:foundFiles];
  358. [[(VLCAppDelegate *)[UIApplication sharedApplication].delegate libraryViewController] updateViewContents];
  359. }
  360. #pragma mark - pass code validation
  361. - (void)passcodeWasValidated:(NSNotification *)aNotifcation
  362. {
  363. _passcodeValidated = YES;
  364. [self.libraryViewController updateViewContents];
  365. if ([VLCPlaybackController sharedInstance].isPlaying)
  366. [[VLCPlayerDisplayController sharedInstance] pushPlaybackView];
  367. }
  368. - (BOOL)passcodeValidated
  369. {
  370. return _passcodeValidated;
  371. }
  372. - (void)validatePasscode
  373. {
  374. VLCKeychainCoordinator *keychainCoordinator = [VLCKeychainCoordinator defaultCoordinator];
  375. if (!_passcodeValidated && [keychainCoordinator passcodeLockEnabled]) {
  376. [[VLCPlayerDisplayController sharedInstance] dismissPlaybackView];
  377. [keychainCoordinator validatePasscode];
  378. } else
  379. _passcodeValidated = YES;
  380. }
  381. #pragma mark - download handling
  382. - (void)downloadMovieFromURL:(NSURL *)url
  383. fileNameOfMedia:(NSString *)fileName
  384. {
  385. [[VLCDownloadViewController sharedInstance] addURLToDownloadList:url fileNameOfMedia:fileName];
  386. [[VLCSidebarController sharedInstance] selectRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]
  387. scrollPosition:UITableViewScrollPositionNone];
  388. }
  389. #pragma mark - remote events pre 7.1
  390. - (void)remoteControlReceivedWithEvent:(UIEvent *)event {
  391. [[VLCPlaybackController sharedInstance] remoteControlReceivedWithEvent:event];
  392. }
  393. #pragma mark - watch stuff
  394. - (void)application:(UIApplication *)application
  395. handleWatchKitExtensionRequest:(NSDictionary *)userInfo
  396. reply:(void (^)(NSDictionary *))reply
  397. {
  398. if ([VLCWatchCommunication isSupported]) {
  399. [self.watchCommunication session:[WCSession defaultSession] didReceiveMessage:userInfo replyHandler:reply];
  400. }
  401. }
  402. @end