VLCAppDelegate.m 27.4 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"
Gleb Pinigin's avatar
Gleb Pinigin committed
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 "VLCPlaybackNavigationController.h"
25
#import "PAPasscodeViewController.h"
26
#import "VLCHTTPUploaderController.h"
27
#import "VLCMenuTableViewController.h"
Carola's avatar
Carola committed
28
#import "VLCMigrationViewController.h"
Carola's avatar
Carola committed
29
#import <BoxSDK/BoxSDK.h>
30
#import "VLCNotificationRelay.h"
31
#import "VLCPlaybackController.h"
32
#import "VLCNavigationController.h"
33
#import "VLCWatchMessage.h"
34
#import "VLCPlaybackController+MediaLibrary.h"
35
#import "VLCPlayerDisplayController.h"
Tobias's avatar
Tobias committed
36
#import <MediaPlayer/MediaPlayer.h>
37
#import <DropboxSDK/DropboxSDK.h>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
38
#import <HockeySDK/HockeySDK.h>
39
40

NSString *const VLCDropboxSessionWasAuthorized = @"VLCDropboxSessionWasAuthorized";
41

Felix Paul Kühne's avatar
Felix Paul Kühne committed
42
43
#define BETA_DISTRIBUTION 1

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

@end
Felix Paul Kühne's avatar
Felix Paul Kühne committed
55
56
57

@implementation VLCAppDelegate

58
59
60
61
+ (void)initialize
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

62
63
64
65
66
    NSNumber *skipLoopFilterDefaultValue;
    int deviceSpeedCategory = [[UIDevice currentDevice] speedCategory];
    if (deviceSpeedCategory < 3)
        skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonKey;
    else
67
        skipLoopFilterDefaultValue = kVLCSettingSkipLoopFilterNonRef;
68

Felix Paul Kühne's avatar
Felix Paul Kühne committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    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};
88
89
90
    [defaults registerDefaults:appDefaults];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
91
92
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
93
94
95
96
97
98
99
100
101
102
103
104
    BITHockeyManager *hockeyManager = [BITHockeyManager sharedHockeyManager];

    if (BETA_DISTRIBUTION) {
        APLog(@"Using HockeySDK beta key");
        [hockeyManager configureWithIdentifier:@"0114ca8e265244ce588d2ebd035c3577"];
    } else
        [hockeyManager configureWithIdentifier:@"c95f4227dff96c61f8b3a46a25edc584"];

    // Configure the SDK in here only!
    [hockeyManager startManager];
    [hockeyManager.authenticator authenticateInstallation];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
105
106
107
108
109
110
111
112
    // Change the keyboard for UISearchBar
    [[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];
    // 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]];
113

114
115
    [[UISwitch appearance] setOnTintColor:[UIColor VLCOrangeTintColor]];

116
    /* clean caches on launch (since those are used for wifi upload only) */
117
    [self cleanCache];
118

119
120
121
    // Init the HTTP Server
    self.uploadController = [[VLCHTTPUploaderController alloc] init];

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

        _revealController = [[GHRevealViewController alloc] initWithNibName:nil bundle:nil];
129
130
        _revealController.extendedLayoutIncludesOpaqueBars = YES;
        _revealController.edgesForExtendedLayout = UIRectEdgeAll;
Carola's avatar
Carola committed
131
132
133
134
        _menuViewController = [[VLCMenuTableViewController alloc] initWithNibName:nil bundle:nil];
        _revealController.sidebarViewController = _menuViewController;
        _revealController.contentViewController = navCon;

135
136
        _playerDisplayController = [[VLCPlayerDisplayController alloc] init];
        _playerDisplayController.childViewController = self.revealController;
137
138

        self.window.rootViewController = _playerDisplayController;
Carola's avatar
Carola committed
139
140
141
142
        // necessary to avoid navbar blinking in VLCOpenNetworkStreamViewController & VLCDownloadViewController
        _revealController.contentViewController.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
        [self.window makeKeyAndVisible];

143
144
145
146
        [self validatePasscode];

        [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];

Carola's avatar
Carola committed
147
148
149
150
151
152
        VLCMediaFileDiscoverer *discoverer = [VLCMediaFileDiscoverer sharedInstance];
        [discoverer addObserver:self];
        [discoverer startDiscovering:[self directoryPath]];
    };

    NSError *error = nil;
153
154

    if ([[MLMediaLibrary sharedMediaLibrary] libraryMigrationNeeded]){
Carola's avatar
Carola committed
155
156
157
158
        _isRunningMigration = YES;

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

Carola's avatar
Carola committed
160
161
162
163
164
165
            //migrate
            setupBlock();
            _isRunningMigration = NO;
            [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
            [self updateMediaList];
        };
Felix Paul Kühne's avatar
Felix Paul Kühne committed
166

Carola's avatar
Carola committed
167
168
        self.window.rootViewController = migrationController;
        [self.window makeKeyAndVisible];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
169

Carola's avatar
Carola committed
170
171
    } else {
        if (error != nil) {
172
            APLog(@"removed persistentStore since it was corrupt");
Carola's avatar
Carola committed
173
174
175
176
177
            NSURL *storeURL = ((MLMediaLibrary *)[MLMediaLibrary sharedMediaLibrary]).persistentStoreURL;
            [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
        }
        setupBlock();
    }
178

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

181
    [[VLCNotificationRelay sharedRelay] addRelayLocalName:VLCPlaybackControllerPlaybackMetadataDidChange toRemoteName:kVLCDarwinNotificationNowPlayingInfoUpdate];
182

Carola's avatar
Carola committed
183
184
    return YES;
}
185

Carola's avatar
Carola committed
186
187
#pragma mark - Handoff

188
189
- (BOOL)application:(UIApplication *)application willContinueUserActivityWithType:(NSString *)userActivityType
{
190
191
192
    if ([userActivityType isEqualToString:@"org.videolan.vlc-ios.librarymode"] ||
        [userActivityType isEqualToString:@"org.videolan.vlc-ios.playing"] ||
        [userActivityType isEqualToString:@"org.videolan.vlc-ios.libraryselection"])
Carola's avatar
Carola committed
193
        return YES;
194

Carola's avatar
Carola committed
195
196
197
    return NO;
}

198
199
200
201
202
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray *))restorationHandler
{
    NSString *userActivityType = userActivity.activityType;
Carola's avatar
Carola committed
203

204
205
    if([userActivityType isEqualToString:@"org.videolan.vlc-ios.librarymode"] ||
       [userActivityType isEqualToString:@"org.videolan.vlc-ios.libraryselection"]) {
Carola's avatar
Carola committed
206
        NSDictionary *dict = userActivity.userInfo;
207
208
209
210
211
212
        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];
        }
213

Carola's avatar
Carola committed
214
215
        [self.playlistViewController restoreUserActivityState:userActivity];
        _isComingFromHandoff = YES;
Carola's avatar
Carola committed
216
217
218
219
220
221
222
223
224
225
226
227
        return YES;
    }
    return NO;
}

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

228
229
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
230
    if ([[DBSession sharedSession] handleOpenURL:url]) {
231
        [[NSNotificationCenter defaultCenter] postNotificationName:VLCDropboxSessionWasAuthorized object:nil];
232
233
        return YES;
    }
234

235
236
    if (_playlistViewController && url != nil) {
        APLog(@"%@ requested %@ to be opened", sourceApplication, url);
237

238
        if (url.isFileURL) {
239
240
241
242
243
244
            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)
245
                APLog(@"saving the file failed (%li): %@", (long)theError.code, theError.localizedDescription);
246

247
            [self updateMediaList];
248
249
250
251
252
        } 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:@""];
253
254
255
256
            NSURL *movieURL;
            NSURL *successCallback;
            NSURL *errorCallback;
            NSString *fileName;
257
258
259
260
261
            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];
262
263

                if ([key isEqualToString:@"url"])
264
                    movieURL = [NSURL URLWithString:value];
265
                else if ([key isEqualToString:@"filename"])
266
                    fileName = value;
267
                else if ([key isEqualToString:@"x-success"])
268
                    successCallback = [NSURL URLWithString:value];
269
270
                else if ([key isEqualToString:@"x-error"])
                    errorCallback = [NSURL URLWithString:value];
271
272
            }
            if ([action isEqualToString:@"stream"] && movieURL) {
273
                [self openMovieFromURL:movieURL successCallback:successCallback errorCallback:errorCallback];
274
            }
275
276
277
            else if ([action isEqualToString:@"download"] && movieURL) {
                [self downloadMovieFromURL:movieURL fileNameOfMedia:fileName];
            }
Luis's avatar
Luis committed
278
        } else {
279
280
281
282
283
284
285
286
287
288
            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]];
289
290
291
292
293
294
                    } else {
                        parsedString = [receivedUrl substringFromIndex:6];
                        if (![parsedString hasPrefix:@"http://"] && ![parsedString hasPrefix:@"https://"] && ![parsedString hasPrefix:@"ftp://"]) {
                            parsedString = [@"http://" stringByAppendingString:[receivedUrl substringFromIndex:6]];
                        }
                    }
295
296
297
                    url = [NSURL URLWithString:parsedString];
                }
            }
298
            [self.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
299
300
301

            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
302
                VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"OPEN_STREAM_OR_DOWNLOAD", nil) message:url.absoluteString cancelButtonTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) otherButtonTitles:@[NSLocalizedString(@"PLAY_BUTTON", nil)]];
303
304
                alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
                    if (cancelled)
305
                        [self downloadMovieFromURL:url fileNameOfMedia:nil];
306
307
308
309
310
311
                    else
                        [self openMovieFromURL:url];
                };
                [alert show];
            } else
                [self openMovieFromURL:url];
Luis's avatar
Luis committed
312
        }
313
314
315
316
317
        return YES;
    }
    return NO;
}

318
319
320
321
322
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[MLMediaLibrary sharedMediaLibrary] applicationWillStart];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
323
324
- (void)applicationWillResignActive:(UIApplication *)application
{
325
    _passcodeValidated = NO;
326
    [self.playlistViewController setEditing:NO animated:NO];
327
    [self validatePasscode];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
328
329
330
331
332
    [[MLMediaLibrary sharedMediaLibrary] applicationWillExit];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
Carola's avatar
Carola committed
333
    if (!_isRunningMigration && !_isComingFromHandoff) {
Carola's avatar
Carola committed
334
335
        [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
        [self updateMediaList];
Carola's avatar
Carola committed
336
337
    } else if(_isComingFromHandoff) {
        _isComingFromHandoff = NO;
Carola's avatar
Carola committed
338
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
339
340
}

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

Gleb Pinigin's avatar
Gleb Pinigin committed
347
348
#pragma mark - properties

349
350
- (VLCDownloadViewController *)downloadViewController
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
351
352
    if (_downloadViewController == nil)
        _downloadViewController = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
353
354
355
356

    return _downloadViewController;
}

357

Gleb Pinigin's avatar
Gleb Pinigin committed
358
#pragma mark - media discovering
359

360
361
- (void)mediaFileAdded:(NSString *)fileName loading:(BOOL)isLoading
{
Gleb Pinigin's avatar
Gleb Pinigin committed
362
363
364
    if (!isLoading) {
        MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
        [sharedLibrary addFilePaths:@[fileName]];
365

Gleb Pinigin's avatar
Gleb Pinigin committed
366
367
368
        /* exclude media files from backup (QA1719) */
        NSURL *excludeURL = [NSURL fileURLWithPath:fileName];
        [excludeURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
369

Gleb Pinigin's avatar
Gleb Pinigin committed
370
371
        // TODO Should we update media db after adding new files?
        [sharedLibrary updateMediaDatabase];
372
        [_playlistViewController updateViewContents];
373
374
375
    }
}

376
377
- (void)mediaFileDeleted:(NSString *)name
{
Gleb Pinigin's avatar
Gleb Pinigin committed
378
379
380
381
    [[MLMediaLibrary sharedMediaLibrary] updateMediaDatabase];
    [_playlistViewController updateViewContents];
}

382
383
- (void)cleanCache
{
384
385
386
    if ([self haveNetworkActivity])
        return;

387
388
389
390
391
392
393
    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];
}

394
395
396
#pragma mark - media list methods

- (NSString *)directoryPath
Felix Paul Kühne's avatar
Felix Paul Kühne committed
397
{
398
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
399
    NSString *directoryPath = searchPaths[0];
400
401
402
403
404
405
    return directoryPath;
}

- (void)updateMediaList
{
    NSString *directoryPath = [self directoryPath];
406
    NSMutableArray *foundFiles = [NSMutableArray arrayWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil]];
407
    NSMutableArray *filePaths = [NSMutableArray array];
408
    NSURL *fileURL;
409
410
411
412
413
    while (foundFiles.count) {
        NSString *fileName = foundFiles.firstObject;
        NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
        [foundFiles removeObject:fileName];

414
        if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
415
            [filePaths addObject:filePath];
416
417

            /* exclude media files from backup (QA1719) */
418
            fileURL = [NSURL fileURLWithPath:filePath];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
419
            [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
420
421
422
        } else {
            BOOL isDirectory = NO;
            BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
423

424
425
            // add folders
            if (exists && isDirectory) {
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
                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];
                    }
                }
441
            }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
442
443
444
        }
    }
    [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
445
    [_playlistViewController updateViewContents];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
446
447
}

448
449
#pragma mark - pass code validation

450
451
452
453
454
- (BOOL)passcodeValidated
{
    return _passcodeValidated;
}

455
456
457
458
- (void)validatePasscode
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *passcode = [defaults objectForKey:kVLCSettingPasscodeKey];
459
    if ([passcode isEqualToString:@""] || ![[defaults objectForKey:kVLCSettingPasscodeOnKey] boolValue]) {
460
        _passcodeValidated = YES;
461
462
        return;
    }
463

464
    if (!_passcodeValidated) {
465
466
467
        _passcodeLockController = [[PAPasscodeViewController alloc] initForAction:PasscodeActionEnter];
        _passcodeLockController.delegate = self;
        _passcodeLockController.passcode = passcode;
468
469
470
471
472
473
474

        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];
475
476
477
478
479
    }
}

- (void)PAPasscodeViewControllerDidEnterPasscode:(PAPasscodeViewController *)controller
{
480
481
    _passcodeValidated = YES;
    [self.playlistViewController updateViewContents];
482
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
483
484
485
486
}

- (void)PAPasscodeViewController:(PAPasscodeViewController *)controller didFailToEnterPasscode:(NSInteger)attempts
{
487
    // FIXME: handle countless failed passcode attempts
488
489
}

490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#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;
}

505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
- (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;
}

524
525
526
527
528
529
530
531
532
533
534
#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];
}

535
536
#pragma mark - playback view handling

537
538
- (void)openMediaFromManagedObject:(NSManagedObject *)mediaObject
{
539
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
540
    [vpc playMediaLibraryObject:mediaObject];
541
542
543
}

- (void)openMovieFromURL:(NSURL *)url
544
         successCallback:(NSURL *)successCallback
545
           errorCallback:(NSURL *)errorCallback
546
{
547
548
549
550
551
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

    vpc.url = url;
    vpc.successCallback = successCallback;
    vpc.errorCallback = errorCallback;
552

553
    [vpc startPlayback];
554
555
}

556
557
- (void)openMovieFromURL:(NSURL *)url
{
558
    [self openMovieFromURL:url successCallback:nil errorCallback:nil];
559
560
}

561
562
- (void)openMovieWithExternalSubtitleFromURL:(NSURL *)url externalSubURL:(NSString *)SubtitlePath
{
563
564
565
566
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];

    vpc.url = url;
    vpc.pathToExternalSubtitlesFile = SubtitlePath;
567

568
    [vpc startPlayback];
569
570
}

571
#pragma mark - watch struff
572
573
574
575
576
577
578
579
580
- (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;
    }];

581
582
    VLCWatchMessage *message = [[VLCWatchMessage alloc] initWithDictionary:userInfo];
    NSString *name = message.name;
583
    NSDictionary *responseDict = nil;
584
    if ([name isEqualToString:VLCWatchMessageNameGetNowPlayingInfo]) {
585
        responseDict = [self nowPlayingResponseDict];
586
    } else if ([name isEqualToString:VLCWatchMessageNamePlayPause]) {
587
588
        [[VLCPlaybackController sharedInstance] playPause];
        responseDict = @{@"playing": @([VLCPlaybackController sharedInstance].isPlaying)};
589
    } else if ([name isEqualToString:VLCWatchMessageNameSkipForward]) {
590
        [[VLCPlaybackController sharedInstance] forward];
591
    } else if ([name isEqualToString:VLCWatchMessageNameSkipBackward]) {
592
        [[VLCPlaybackController sharedInstance] backward];
593
594
595
596
    } else if ([name isEqualToString:VLCWatchMessageNamePlayFile]) {
        [self playFileFromWatch:message];
    } else if ([name isEqualToString:VLCWatchMessageNameSetVolume]) {
        [self setVolumeFromWatch:message];
597
    } else {
598
        APLog(@"Did not handle request from WatchKit Extension: %@",userInfo);
599
    }
600
    reply(responseDict);
601
}
602

603
- (void)playFileFromWatch:(VLCWatchMessage *)message
604
{
605
    NSManagedObject *managedObject = nil;
606
607
    NSString *uriString = (id)message.payload;
    if ([uriString isKindOfClass:[NSString class]]) {
608
609
610
        NSURL *uriRepresentation = [NSURL URLWithString:uriString];
        managedObject = [[MLMediaLibrary sharedMediaLibrary] objectForURIRepresentation:uriRepresentation];
    }
611
    if (managedObject == nil) {
612
        APLog(@"%s file not found: %@",__PRETTY_FUNCTION__,message);
613
614
615
616
        return;
    }

    [self openMediaFromManagedObject:managedObject];
617
618
}

619
- (void)setVolumeFromWatch:(VLCWatchMessage *)message
620
{
621
    NSNumber *volume = (id)message.payload;
622
623
624
625
626
627
628
629
630
    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;
    }
}

631
632
- (NSDictionary *)nowPlayingResponseDict {
    NSMutableDictionary *response = [NSMutableDictionary new];
633
    NSMutableDictionary *nowPlayingInfo = [[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo mutableCopy];
634
    NSNumber *playbackTime = [VLCPlaybackController sharedInstance].mediaPlayer.time.numberValue;
635
636
637
    if (playbackTime) {
        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(playbackTime.floatValue/1000);
    }
638
639
640
    if (nowPlayingInfo) {
        response[@"nowPlayingInfo"] = nowPlayingInfo;
    }
641
    MLFile *currentFile = [VLCPlaybackController sharedInstance].currentlyPlayingMediaFile;
642
643
644
    NSString *URIString = currentFile.objectID.URIRepresentation.absoluteString;
    if (URIString) {
        response[@"URIRepresentation"] = URIString;
645
    }
646
647
648

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

649
    return response;
650
651
}

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