VLCAppDelegate.m 28.7 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * VLCAppDelegate.m
 * VLC for iOS
 *****************************************************************************
Felix Paul Kühne's avatar
Felix Paul Kühne committed
5
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
6 7 8 9 10 11 12
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *          Gleb Pinigin <gpinigin # gmail.com>
 *          Jean-Romain Prévost <jr # 3on.fr>
 *          Luis Fernandes <zipleen # gmail.com>
 *          Carola Nitz <nitz.carola # googlemail.com>
13
 *          Tamas Timar <ttimar.vlc # gmail.com>
Tobias's avatar
Tobias committed
14
 *          Tobias Conradi <videolan # tobias-conradi.de>
15 16 17
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
Felix Paul Kühne's avatar
Felix Paul Kühne committed
18 19

#import "VLCAppDelegate.h"
20
#import "VLCMediaFileDiscoverer.h"
21
#import "NSString+SupportedMedia.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
22
#import "UIDevice+VLC.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
23
#import "VLCPlaylistViewController.h"
24
#import "VLCMovieViewController.h"
25
#import "VLCPlaybackNavigationController.h"
26
#import "PAPasscodeViewController.h"
27
#import "VLCHTTPUploaderController.h"
28
#import "VLCMenuTableViewController.h"
29
#import "VLCMigrationViewController.h"
30
#import "VLCAlertView.h"
Carola Nitz's avatar
Carola Nitz committed
31
#import <BoxSDK/BoxSDK.h>
32
#import "VLCNotificationRelay.h"
33
#import "VLCPlaybackController.h"
34
#import "VLCNavigationController.h"
35
#import "VLCWatchMessage.h"
36
#import "VLCPlaybackController+MediaLibrary.h"
37

38 39 40
#define HAVE_FABRIC 0

#if HAVE_FABRIC
41 42
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
43
#endif
44

Tobias's avatar
Tobias committed
45
@interface VLCAppDelegate () <PAPasscodeViewControllerDelegate, VLCMediaFileDiscovererDelegate> {
Gleb Pinigin's avatar
Gleb Pinigin committed
46
    PAPasscodeViewController *_passcodeLockController;
47
    VLCDownloadViewController *_downloadViewController;
48
    VLCDropboxTableViewController *_dropboxTableViewController;
49
    int _idleCounter;
50
    int _networkActivityCounter;
51
    BOOL _passcodeValidated;
52
    BOOL _isRunningMigration;
Carola Nitz's avatar
Carola Nitz committed
53
    BOOL _isComingFromHandoff;
Gleb Pinigin's avatar
Gleb Pinigin committed
54
}
55

56 57
@property (nonatomic, strong) VLCMovieViewController *movieViewController;

58
@end
Felix Paul Kühne's avatar
Felix Paul Kühne committed
59 60 61

@implementation VLCAppDelegate

62 63 64 65
+ (void)initialize
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

66 67 68 69 70
    NSNumber *skipLoopFilterDefaultValue;
    int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
    if (deviceSpeedCategory < 3)
        skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
    else
71
        skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    NSDictionary *appDefaults = @{kVLCSettingPasscodeKey : @"",
                                  kVLCSettingPasscodeOnKey : @(NO),
                                  kVLCSettingContinueAudioInBackgroundKey : @(YES),
                                  kVLCSettingStretchAudio : @(NO),
                                  kVLCSettingTextEncoding : kVLCSettingTextEncodingDefaultValue,
                                  kVLCSettingSkipLoopFilter : skipLoopFilterDefaultValue,
                                  kVLCSettingSubtitlesFont : kVLCSettingSubtitlesFontDefaultValue,
                                  kVLCSettingSubtitlesFontColor : kVLCSettingSubtitlesFontColorDefaultValue,
                                  kVLCSettingSubtitlesFontSize : kVLCSettingSubtitlesFontSizeDefaultValue,
                                  kVLCSettingSubtitlesBoldFont: kVLCSettingSubtitlesBoldFontDefaultValue,
                                  kVLCSettingDeinterlace : kVLCSettingDeinterlaceDefaultValue,
                                  kVLCSettingNetworkCaching : kVLCSettingNetworkCachingDefaultValue,
                                  kVLCSettingPlaybackGestures : [NSNumber numberWithBool:YES],
                                  kVLCSettingFTPTextEncoding : kVLCSettingFTPTextEncodingDefaultValue,
                                  kVLCSettingWiFiSharingIPv6 : kVLCSettingWiFiSharingIPv6DefaultValue,
                                  kVLCSettingEqualizerProfile : kVLCSettingEqualizerProfileDefaultValue,
                                  kVLCSettingPlaybackForwardSkipLength : kVLCSettingPlaybackForwardSkipLengthDefaultValue,
                                  kVLCSettingPlaybackBackwardSkipLength : kVLCSettingPlaybackBackwardSkipLengthDefaultValue,
                                  kVLCSettingOpenAppForPlayback : kVLCSettingOpenAppForPlaybackDefaultValue};
92 93 94
    [defaults registerDefaults:appDefaults];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
95 96
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
97
    if (SYSTEM_RUNS_IOS7_OR_LATER) {
98
        // Change the keyboard for UISearchBar
99
        [[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];
100 101 102 103 104 105
        // For the cursor
        [[UITextField appearance] setTintColor:[UIColor VLCOrangeTintColor]];
        // Don't override the 'Cancel' button color in the search bar with the previous UITextField call. Use the default blue color
        [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]} forState:UIControlStateNormal];
        // For the edit selection indicators
        [[UITableView appearance] setTintColor:[UIColor VLCOrangeTintColor]];
106 107
    }

108 109
    [[UISwitch appearance] setOnTintColor:[UIColor VLCOrangeTintColor]];

110
    /* clean caches on launch (since those are used for wifi upload only) */
111
    [self cleanCache];
112

113 114 115
    // Init the HTTP Server
    self.uploadController = [[VLCHTTPUploaderController alloc] init];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
116
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
117
    // enable crash preventer
118 119
     void (^setupBlock)() = ^{
         _playlistViewController = [[VLCPlaylistViewController alloc] init];
120
        UINavigationController *navCon = [[VLCNavigationController alloc] initWithRootViewController:_playlistViewController];
121 122 123 124 125 126 127 128 129 130 131 132

        _revealController = [[GHRevealViewController alloc] initWithNibName:nil bundle:nil];
        _revealController.wantsFullScreenLayout = YES;
        _menuViewController = [[VLCMenuTableViewController alloc] initWithNibName:nil bundle:nil];
        _revealController.sidebarViewController = _menuViewController;
        _revealController.contentViewController = navCon;

        self.window.rootViewController = self.revealController;
        // necessary to avoid navbar blinking in VLCOpenNetworkStreamViewController & VLCDownloadViewController
        _revealController.contentViewController.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
        [self.window makeKeyAndVisible];

133 134 135 136
        [self validatePasscode];

        [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];

137 138 139 140 141 142
        VLCMediaFileDiscoverer *discoverer = [VLCMediaFileDiscoverer sharedInstance];
        [discoverer addObserver:self];
        [discoverer startDiscovering:[self directoryPath]];
    };

    NSError *error = nil;
143 144

    if ([[MLMediaLibrary sharedMediaLibrary] libraryMigrationNeeded]){
145 146 147 148
        _isRunningMigration = YES;

        VLCMigrationViewController *migrationController = [[VLCMigrationViewController alloc] initWithNibName:@"VLCMigrationViewController" bundle:nil];
        migrationController.completionHandler = ^{
149

150 151 152 153 154 155
            //migrate
            setupBlock();
            _isRunningMigration = NO;
            [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
            [self updateMediaList];
        };
Felix Paul Kühne's avatar
Felix Paul Kühne committed
156

157 158
        self.window.rootViewController = migrationController;
        [self.window makeKeyAndVisible];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
159

160 161
    } else {
        if (error != nil) {
162
            APLog(@"removed persistentStore since it was corrupt");
163 164 165 166 167
            NSURL *storeURL = ((MLMediaLibrary *)[MLMediaLibrary sharedMediaLibrary]).persistentStoreURL;
            [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
        }
        setupBlock();
    }
168

169 170
    [[VLCNotificationRelay sharedRelay] addRelayLocalName:NSManagedObjectContextDidSaveNotification toRemoteName:@"org.videolan.ios-app.dbupdate"];

171
    [[VLCNotificationRelay sharedRelay] addRelayLocalName:kVLCNotificationNowPlayingInfoUpdate toRemoteName:kVLCDarwinNotificationNowPlayingInfoUpdate];
172

173
#if HAVE_FABRIC
174
    [Fabric with:@[CrashlyticsKit]];
175
#endif
176

177 178
    return YES;
}
179

Carola Nitz's avatar
Carola Nitz committed
180 181
#pragma mark - Handoff

182 183
- (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType
{
184 185 186
    if ([userActivityType isEqualToString:@"org.videolan.vlc-ios.librarymode"] ||
        [userActivityType isEqualToString:@"org.videolan.vlc-ios.playing"] ||
        [userActivityType isEqualToString:@"org.videolan.vlc-ios.libraryselection"])
Carola Nitz's avatar
Carola Nitz committed
187
        return YES;
188

Carola Nitz's avatar
Carola Nitz committed
189 190 191
    return NO;
}

192 193 194 195 196
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray *))restorationHandler
{
    NSString *userActivityType = userActivity.activityType;
Carola Nitz's avatar
Carola Nitz committed
197

198 199
    if([userActivityType isEqualToString:@"org.videolan.vlc-ios.librarymode"] ||
       [userActivityType isEqualToString:@"org.videolan.vlc-ios.libraryselection"]) {
Carola Nitz's avatar
Carola Nitz committed
200
        NSDictionary *dict = userActivity.userInfo;
201 202 203 204 205 206
        VLCLibraryMode libraryMode = (VLCLibraryMode)[(NSNumber *)dict[@"state"] integerValue];

        if (libraryMode <= VLCLibraryModeAllSeries) {
            [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:libraryMode inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
            [self.playlistViewController setLibraryMode:(VLCLibraryMode)libraryMode];
        }
207

Carola Nitz's avatar
Carola Nitz committed
208 209
        [self.playlistViewController restoreUserActivityState:userActivity];
        _isComingFromHandoff = YES;
Carola Nitz's avatar
Carola Nitz committed
210 211 212 213 214 215 216 217 218 219 220 221
        return YES;
    }
    return NO;
}

- (void)application:(UIApplication *)application didFailToContinueUserActivityWithType:(NSString *)userActivityType error:(NSError *)error
{
    if (error.code != NSUserCancelledError){
        //TODO: present alert
    }
}

222 223
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
224 225 226 227
    if ([[DBSession sharedSession] handleOpenURL:url]) {
        [self.dropboxTableViewController updateViewAfterSessionChange];
        return YES;
    }
228

229 230
    if (_playlistViewController && url != nil) {
        APLog(@"%@ requested %@ to be opened", sourceApplication, url);
231

232
        if (url.isFileURL) {
233 234 235 236 237 238
            NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *directoryPath = searchPaths[0];
            NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, url.lastPathComponent]];
            NSError *theError;
            [[NSFileManager defaultManager] moveItemAtURL:url toURL:destinationURL error:&theError];
            if (theError.code != noErr)
239
                APLog(@"saving the file failed (%li): %@", (long)theError.code, theError.localizedDescription);
240

241
            [self updateMediaList];
242 243 244 245 246
        } else if ([url.scheme isEqualToString:@"vlc-x-callback"] || [url.host isEqualToString:@"x-callback-url"]) {
            // URL confirmes to the x-callback-url specification
            // vlc-x-callback://x-callback-url/action?param=value&x-success=callback
            APLog(@"x-callback-url with host '%@' path '%@' parameters '%@'", url.host, url.path, url.query);
            NSString *action = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
247 248 249 250
            NSURL *movieURL;
            NSURL *successCallback;
            NSURL *errorCallback;
            NSString *fileName;
251 252 253 254 255
            for (NSString *entry in [url.query componentsSeparatedByString:@"&"]) {
                NSArray *keyvalue = [entry componentsSeparatedByString:@"="];
                if (keyvalue.count < 2) continue;
                NSString *key = keyvalue[0];
                NSString *value = [keyvalue[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
256 257

                if ([key isEqualToString:@"url"])
258
                    movieURL = [NSURL URLWithString:value];
259
                else if ([key isEqualToString:@"filename"])
260
                    fileName = value;
261
                else if ([key isEqualToString:@"x-success"])
262
                    successCallback = [NSURL URLWithString:value];
263 264
                else if ([key isEqualToString:@"x-error"])
                    errorCallback = [NSURL URLWithString:value];
265 266
            }
            if ([action isEqualToString:@"stream"] && movieURL) {
267
                [self openMovieFromURL:movieURL successCallback:successCallback errorCallback:errorCallback];
268
            }
269 270 271
            else if ([action isEqualToString:@"download"] && movieURL) {
                [self downloadMovieFromURL:movieURL fileNameOfMedia:fileName];
            }
Luis's avatar
Luis committed
272
        } else {
273 274 275 276 277 278 279 280 281 282
            NSString *receivedUrl = [url absoluteString];
            if ([receivedUrl length] > 6) {
                NSString *verifyVlcUrl = [receivedUrl substringToIndex:6];
                if ([verifyVlcUrl isEqualToString:@"vlc://"]) {
                    NSString *parsedString = [receivedUrl substringFromIndex:6];
                    NSUInteger location = [parsedString rangeOfString:@"//"].location;

                    /* Safari & al mangle vlc://http:// so fix this */
                    if (location != NSNotFound && [parsedString characterAtIndex:location - 1] != 0x3a) { // :
                            parsedString = [NSString stringWithFormat:@"%@://%@", [parsedString substringToIndex:location], [parsedString substringFromIndex:location+2]];
283 284 285 286 287 288
                    } else {
                        parsedString = [receivedUrl substringFromIndex:6];
                        if (![parsedString hasPrefix:@"http://"] && ![parsedString hasPrefix:@"https://"] && ![parsedString hasPrefix:@"ftp://"]) {
                            parsedString = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
                        }
                    }
289 290 291
                    url = [NSURL URLWithString:parsedString];
                }
            }
292
            [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
293 294 295

            NSString *scheme = url.scheme;
            if ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"ftp"]) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
296
                VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"PLAY_BUTTON", nil)]];
297 298
                alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
                    if (cancelled)
299
                        [self downloadMovieFromURL:url fileNameOfMedia:nil];
300 301 302 303 304 305
                    else
                        [self openMovieFromURL:url];
                };
                [alert show];
            } else
                [self openMovieFromURL:url];
Luis's avatar
Luis committed
306
        }
307 308 309 310 311
        return YES;
    }
    return NO;
}

312 313 314 315 316
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
317 318
- (void)applicationWillResignActive:(UIApplication *)application
{
319
    _passcodeValidated = NO;
320
    [self validatePasscode];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
321 322 323 324 325
    [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
Carola Nitz's avatar
Carola Nitz committed
326
    if (!_isRunningMigration && !_isComingFromHandoff) {
327 328
        [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
        [self updateMediaList];
Carola Nitz's avatar
Carola Nitz committed
329 330
    } else if(_isComingFromHandoff) {
        _isComingFromHandoff = NO;
331
    }
332

333 334 335 336 337 338 339
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

    if (!vpc.audioOnlyPlaybackSession) {
        if (vpc.isPlaying && !self.movieViewController.presentingViewController)
            [self presentMovieViewController];
    } else
        [self.playlistViewController displayMiniPlaybackViewIfNeeded];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
340 341
}

342 343
- (void)applicationWillTerminate:(UIApplication *)application
{
344
    _passcodeValidated = NO;
345 346 347
    [[NSUserDefaults standardUserDefaults] synchronize];
}

348 349 350
#pragma mark - properties
- (VLCDropboxTableViewController *)dropboxTableViewController
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
351
    if (_dropboxTableViewController == nil)
352
        _dropboxTableViewController = [[VLCDropboxTableViewController alloc] initWithNibName:@"VLCCloudStorageTableViewController" bundle:nil];
353 354 355 356

    return _dropboxTableViewController;
}

357 358
- (VLCDownloadViewController *)downloadViewController
{
359 360 361 362 363 364
    if (_downloadViewController == nil) {
        if (SYSTEM_RUNS_IOS7_OR_LATER)
            _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCFutureDownloadViewController" bundle:nil];
        else
            _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
    }
365 366 367 368

    return _downloadViewController;
}

369 370 371 372 373 374 375 376 377
- (VLCMovieViewController *)movieViewController
{
    if (!_movieViewController) {
        _movieViewController = [[VLCMovieViewController alloc] initWithNibName:nil bundle:nil];
        [VLCPlaybackController sharedInstance].delegate = _movieViewController;
    }
    return _movieViewController;
}

378
#pragma mark - media discovering
379

380 381
- (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
{
382 383 384
    if (!isLoading) {
        MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
        [sharedLibrary addFilePaths:@[fileName]];
385

386 387 388
        /* exclude media files from backup (QA1719) */
        NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
        [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
389

390 391
        // TODO Should we update media db after adding new files?
        [sharedLibrary updateMediaDatabase];
392
        [_playlistViewController updateViewContents];
393 394 395
    }
}

396 397
- (void)mediaFileDeleted:(NSString *)name
{
398 399 400 401
    [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
    [_playlistViewController updateViewContents];
}

402 403
- (void)cleanCache
{
404 405 406
    if ([self haveNetworkActivity])
        return;

407 408 409 410 411 412 413
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:uploadDirPath])
        [fileManager removeItemAtPath:uploadDirPath error:nil];
}

414 415 416
#pragma mark - media list methods

- (NSString *)directoryPath
Felix Paul Kühne's avatar
Felix Paul Kühne committed
417
{
418
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
419
    NSString *directoryPath = searchPaths[0];
420 421 422 423 424 425
    return directoryPath;
}

- (void)updateMediaList
{
    NSString *directoryPath = [self directoryPath];
426
    NSMutableArray *foundFiles = [NSMutableArray arrayWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil]];
427
    NSMutableArray *filePaths = [NSMutableArray array];
428
    NSURL *fileURL;
429 430 431 432 433
    while (foundFiles.count) {
        NSString *fileName = foundFiles.firstObject;
        NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
        [foundFiles removeObject:fileName];

434
        if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
435
            [filePaths addObject:filePath];
436 437

            /* exclude media files from backup (QA1719) */
438
            fileURL = [NSURL fileURLWithPath:filePath];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
439
            [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
440 441 442
        } else {
            BOOL isDirectory = NO;
            BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
443

444 445
            // add folders
            if (exists && isDirectory) {
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
                NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
                for (NSString* file in files) {
                    NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:file];
                    isDirectory = NO;
                    exists = [[NSFileManager defaultManager] fileExistsAtPath:fullFilePath isDirectory:&isDirectory];
                    //only add folders or files in folders
                    if ((exists && isDirectory) || ![filePath.lastPathComponent isEqualToString:@"Documents"]) {
                        NSString *folderpath = [filePath stringByReplacingOccurrencesOfString:directoryPath withString:@""];
                        if (![folderpath isEqualToString:@""]) {
                            folderpath = [folderpath stringByAppendingString:@"/"];
                        }
                        NSString *path = [folderpath stringByAppendingString:file];
                        [foundFiles addObject:path];
                    }
                }
461
            }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
462 463 464
        }
    }
    [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
465
    [_playlistViewController updateViewContents];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
466 467
}

468 469
#pragma mark - pass code validation

470 471 472 473 474
- (BOOL)passcodeValidated
{
    return _passcodeValidated;
}

475 476 477 478
- (void)validatePasscode
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
479
    if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
480
        _passcodeValidated = YES;
481 482
        return;
    }
483

484
    if (!_passcodeValidated) {
485 486 487
        _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
        _passcodeLockController.delegate = self;
        _passcodeLockController.passcode = passcode;
488 489 490 491 492 493 494

        if (self.window.rootViewController.presentedViewController)
            [self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];

        UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_passcodeLockController];
        navCon.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.window.rootViewController presentViewController:navCon animated:NO completion:nil];
495 496 497 498 499
    }
}

- (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
{
500 501
    _passcodeValidated = YES;
    [self.playlistViewController updateViewContents];
502
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
503 504 505 506
}

- (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
{
507
    // FIXME: handle countless failed passcode attempts
508 509
}

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
#pragma mark - idle timer preventer
- (void)disableIdleTimer
{
    _idleCounter++;
    if ([UIApplication sharedApplication].idleTimerDisabled == NO)
        [UIApplication sharedApplication].idleTimerDisabled = YES;
}

- (void)activateIdleTimer
{
    _idleCounter--;
    if (_idleCounter < 1)
        [UIApplication sharedApplication].idleTimerDisabled = NO;
}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
- (void)networkActivityStarted
{
    _networkActivityCounter++;
    if ([UIApplication sharedApplication].networkActivityIndicatorVisible == NO)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (BOOL)haveNetworkActivity
{
    return _networkActivityCounter >= 1;
}

- (void)networkActivityStopped
{
    _networkActivityCounter--;
    if (_networkActivityCounter < 1)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

544 545 546 547 548 549 550 551 552 553 554
#pragma mark - download handling

- (void)downloadMovieFromURL:(NSURL *)url
             fileNameOfMedia:(NSString *)fileName
{
    [self.downloadViewController addURLToDownloadList:url fileNameOfMedia:fileName];

    // select Downloads menu item and reveal corresponding viewcontroller
    [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1] animated:NO scrollPosition:UITableViewScrollPositionNone];
}

555 556
#pragma mark - playback view handling

557
- (void)presentMovieViewController
558
{
559 560 561 562 563
    if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) {
        return;
    }

    UINavigationController *navCon = [[VLCPlaybackNavigationController alloc] initWithRootViewController:self.movieViewController];
564
    [self.movieViewController prepareForMediaPlayback:[VLCPlaybackController sharedInstance]];
565 566 567
    navCon.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.window.rootViewController presentViewController:navCon animated:YES completion:nil];
}
568

569 570
- (void)openMediaFromManagedObject:(NSManagedObject *)mediaObject
{
571 572
    BOOL retainFullscreenPlayback = false;

573
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
574

575 576 577
    if (vpc.presentingMovieViewController)
        retainFullscreenPlayback = YES;

578
    [vpc playMediaLibraryObject:mediaObject];
579

580 581
    if (retainFullscreenPlayback)
        [self presentMovieViewController];
582 583 584
}

- (void)openMovieFromURL:(NSURL *)url
585
         successCallback:(NSURL *)successCallback
586
           errorCallback:(NSURL *)errorCallback
587
{
588 589 590 591 592
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

    vpc.url = url;
    vpc.successCallback = successCallback;
    vpc.errorCallback = errorCallback;
593

594
    [vpc startPlayback];
595 596
}

597 598
- (void)openMovieFromURL:(NSURL *)url
{
599
    [self openMovieFromURL:url successCallback:nil errorCallback:nil];
600 601
}

602 603
- (void)openMovieWithExternalSubtitleFromURL:(NSURL *)url externalSubURL:(NSString *)SubtitlePath
{
604 605 606 607
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

    vpc.url = url;
    vpc.pathToExternalSubtitlesFile = SubtitlePath;
608

609
    [vpc startPlayback];
610 611
}

612
#pragma mark - watch struff
613 614 615 616 617 618 619 620 621
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
    /* dispatch background task */
    __block UIBackgroundTaskIdentifier taskIdentifier = [application beginBackgroundTaskWithName:nil
                                                                               expirationHandler:^{
                                                                                   [application endBackgroundTask:taskIdentifier];
                                                                                   taskIdentifier = UIBackgroundTaskInvalid;
    }];

622 623
    VLCWatchMessage *message = [[VLCWatchMessage alloc] initWithDictionary:userInfo];
    NSString *name = message.name;
624
    NSDictionary *responseDict = nil;
625
    if ([name isEqualToString:VLCWatchMessageNameGetNowPlayingInfo]) {
626
        responseDict = [self nowPlayingResponseDict];
627
    } else if ([name isEqualToString:VLCWatchMessageNamePlayPause]) {
628 629
        [[VLCPlaybackController sharedInstance] playPause];
        responseDict = @{@"playing": @([VLCPlaybackController sharedInstance].isPlaying)};
630
    } else if ([name isEqualToString:VLCWatchMessageNameSkipForward]) {
631
        [[VLCPlaybackController sharedInstance] forward];
632
    } else if ([name isEqualToString:VLCWatchMessageNameSkipBackward]) {
633
        [[VLCPlaybackController sharedInstance] backward];
634 635 636 637
    } else if ([name isEqualToString:VLCWatchMessageNamePlayFile]) {
        [self playFileFromWatch:message];
    } else if ([name isEqualToString:VLCWatchMessageNameSetVolume]) {
        [self setVolumeFromWatch:message];
638
    } else {
639
        APLog(@"Did not handle request from WatchKit Extension: %@",userInfo);
640
    }
641
    reply(responseDict);
642
}
643

644
- (void)playFileFromWatch:(VLCWatchMessage *)message
645
{
646
    NSManagedObject *managedObject = nil;
647 648
    NSString *uriString = (id)message.payload;
    if ([uriString isKindOfClass:[NSString class]]) {
649 650 651
        NSURL *uriRepresentation = [NSURL URLWithString:uriString];
        managedObject = [[MLMediaLibrary sharedMediaLibrary] objectForURIRepresentation:uriRepresentation];
    }
652
    if (managedObject == nil) {
653
        APLog(@"%s file not found: %@",__PRETTY_FUNCTION__,message);
654 655 656 657
        return;
    }

    [self openMediaFromManagedObject:managedObject];
658 659
}

660
- (void)setVolumeFromWatch:(VLCWatchMessage *)message
661
{
662
    NSNumber *volume = (id)message.payload;
663 664 665 666 667 668 669 670 671
    if ([volume isKindOfClass:[NSNumber class]]) {
        /*
         * Since WatchKit doen't provide something like MPVolumeView we use deprecated API.
         * rdar://20783803 Feature Request: WatchKit equivalent for MPVolumeView
         */
        [MPMusicPlayerController applicationMusicPlayer].volume = volume.floatValue;
    }
}

672 673
- (NSDictionary *)nowPlayingResponseDict {
    NSMutableDictionary *response = [NSMutableDictionary new];
674
    NSMutableDictionary *nowPlayingInfo = [[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo mutableCopy];
675
    NSNumber *playbackTime = [VLCPlaybackController sharedInstance].mediaPlayer.time.numberValue;
676 677 678
    if (playbackTime) {
        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(playbackTime.floatValue/1000);
    }
679 680 681
    if (nowPlayingInfo) {
        response[@"nowPlayingInfo"] = nowPlayingInfo;
    }
682
    MLFile *currentFile = [VLCPlaybackController sharedInstance].currentlyPlayingMediaFile;
683 684 685
    NSString *URIString = currentFile.objectID.URIRepresentation.absoluteString;
    if (URIString) {
        response[@"URIRepresentation"] = URIString;
686
    }
687 688 689

    response[@"volume"] = @([MPMusicPlayerController applicationMusicPlayer].volume);

690
    return response;
691 692
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
693
@end