VLCAppDelegate.m 20 KB

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