VLCAppDelegate.m 19 KB

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