VLCAppDelegate.m 19 KB

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