VLCDropboxController.m 11.5 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * VLCDropboxController.m
 * VLC for iOS
 *****************************************************************************
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>
 *          Jean-Baptiste Kempf <jb # videolan.org>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
13 14

#import "VLCDropboxController.h"
15
#import "NSString+SupportedMedia.h"
16
#import "VLCPlaybackController.h"
17
#import "VLCActivityManager.h"
18
#if !TARGET_OS_TV
19
#import "VLCMediaFileDiscoverer.h"
20
#endif
21
#import "DBKeychain.h"
22
#import "VLCDropboxConstants.h"
23 24 25 26 27 28

@interface VLCDropboxController ()
{
    DBRestClient *_restClient;
    NSArray *_currentFileList;

29 30 31
    NSMutableArray *_listOfDropboxFilesToDownload;
    BOOL _downloadInProgress;

32
    NSInteger _outstandingNetworkRequests;
33 34 35 36 37

    CGFloat _averageSpeed;
    CGFloat _fileSize;
    NSTimeInterval _startDL;
    NSTimeInterval _lastStatsUpdate;
38 39

    UINavigationController *_lastKnownNavigationController;
40 41 42 43 44 45 46 47
}

@end

@implementation VLCDropboxController

#pragma mark - session handling

48 49 50 51 52 53
+ (instancetype)sharedInstance
{
    static VLCDropboxController *sharedInstance = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
54
        sharedInstance = [VLCDropboxController new];
55
        [sharedInstance shareCredentials];
56 57 58 59

        DBSession* dbSession = [[DBSession alloc] initWithAppKey:kVLCDropboxAppKey appSecret:kVLCDropboxPrivateKey root:kDBRootDropbox];
        [DBSession setSharedSession:dbSession];
        [DBRequest setNetworkRequestDelegate:sharedInstance];
60 61 62 63 64
    });

    return sharedInstance;
}

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
- (void)shareCredentials
{
    /* share our credentials */
    NSDictionary *credentials = [DBKeychain credentials];
    if (credentials == nil)
        return;

    NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
    [ubiquitousStore setDictionary:credentials forKey:kVLCStoreDropboxCredentials];
    [ubiquitousStore synchronize];
}

- (BOOL)restoreFromSharedCredentials
{
    NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
    [ubiquitousStore synchronize];
    NSDictionary *credentials = [ubiquitousStore dictionaryForKey:kVLCStoreDropboxCredentials];
    if (!credentials)
        return NO;

    [DBKeychain setCredentials:credentials];
    return YES;
}

89 90
- (void)startSession
{
91
    [[DBSession sharedSession] isLinked];
92 93 94 95 96 97 98
}

- (void)logout
{
    [[DBSession sharedSession] unlinkAll];
}

99
- (BOOL)isAuthorized
100
{
101
    return [[DBSession sharedSession] isLinked];
102 103 104 105 106 107 108 109 110 111 112
}

- (DBRestClient *)restClient {
    if (!_restClient) {
        _restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
        _restClient.delegate = self;
    }
    return _restClient;
}

#pragma mark - file management
113 114 115 116 117 118

- (BOOL)canPlayAll
{
    return NO;
}

119 120
- (void)requestDirectoryListingAtPath:(NSString *)path
{
121
    if (self.isAuthorized)
122 123 124 125 126 127
        [[self restClient] loadMetadata:path];
}

- (void)downloadFileToDocumentFolder:(DBMetadata *)file
{
    if (!file.isDirectory) {
128 129 130
        if (!_listOfDropboxFilesToDownload)
            _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
        [_listOfDropboxFilesToDownload addObject:file];
131

132 133
        if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
            [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
134

135
        [self _triggerNextDownload];
136 137 138
    }
}

139
- (void)streamFile:(DBMetadata *)file currentNavigationController:(UINavigationController *)navigationController
140
{
141 142
    if (!file.isDirectory) {
        _lastKnownNavigationController = navigationController;
143 144 145
        NSString *path = file.path;
        if (path != nil)
            [[self restClient] loadStreamableURLForFile:path];
146
    }
147 148
}

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
- (void)_triggerNextDownload
{
    if (_listOfDropboxFilesToDownload.count > 0 && !_downloadInProgress) {
        [self _reallyDownloadFileToDocumentFolder:_listOfDropboxFilesToDownload[0]];
        [_listOfDropboxFilesToDownload removeObjectAtIndex:0];

        if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
            [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
    }
}

- (void)_reallyDownloadFileToDocumentFolder:(DBMetadata *)file
{
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.filename];
164 165
    _startDL = [NSDate timeIntervalSinceReferenceDate];
    _fileSize = file.totalBytes;
166 167 168 169 170 171 172 173
    [[self restClient] loadFile:file.path intoPath:filePath];

    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
        [self.delegate operationWithProgressInformationStarted];

    _downloadInProgress = YES;
}

174 175 176
#pragma mark - restClient delegate
- (BOOL)_supportedFileExtension:(NSString *)filename
{
177
    if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
178 179 180 181 182
        return YES;

    return NO;
}

183 184
- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata
{
185
    _currentFileList = [NSArray arrayWithArray:metadata.contents];
186

Felix Paul Kühne's avatar
Felix Paul Kühne committed
187
    APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
188 189 190 191 192 193
    if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
        [self.delegate mediaListUpdated];
}

- (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
{
194
    APLog(@"DBMetadata download failed with error %li", (long)error.code);
195
    [self _handleError:error];
196 197 198 199
}

- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
200
#if TARGET_OS_IOS
201
    /* update library now that we got a file */
202
    [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
203 204 205

    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
206 207 208
    _downloadInProgress = NO;

    [self _triggerNextDownload];
209
#endif
210 211 212 213
}

- (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
{
214
    APLog(@"DBFile download failed with error %li", (long)error.code);
215
    [self _handleError:error];
216 217
    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
218 219
    _downloadInProgress = NO;
    [self _triggerNextDownload];
220 221 222 223
}

- (void)restClient:(DBRestClient*)client loadProgress:(CGFloat)progress forFile:(NSString*)destPath
{
224
    if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
Carola Nitz's avatar
Carola Nitz committed
225
        [self calculateRemainingTime:progress * _fileSize expectedDownloadSize:_fileSize];
226 227 228
        _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
    }

229 230
    if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
        [self.delegate currentProgressInformation:progress];
231 232
}

233 234
- (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
{
235 236
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    [vpc playURL:url successCallback:nil errorCallback:nil];
237 238 239 240 241 242 243 244
#if TARGET_OS_TV
    if (_lastKnownNavigationController) {
        VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
        [_lastKnownNavigationController presentViewController:movieVC
                                                     animated:YES
                                                   completion:nil];
    }
#endif
245 246 247 248
}

- (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
{
249
    APLog(@"loadStreamableURL failed with error %li", (long)error.code);
250
    [self _handleError:error];
251 252
}

253 254 255 256 257 258 259 260 261 262
#pragma mark - DBSession delegate

- (void)sessionDidReceiveAuthorizationFailure:(DBSession *)session userId:(NSString *)userId
{
    APLog(@"DBSession received authorization failure with user ID %@", userId);
}

#pragma mark - DBNetworkRequest delegate
- (void)networkRequestStarted
{
263
    _outstandingNetworkRequests++;
264
    if (_outstandingNetworkRequests == 1) {
265 266 267
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStarted];
        [activityManager disableIdleTimer];
268
    }
269 270 271 272
}

- (void)networkRequestStopped
{
273
    _outstandingNetworkRequests--;
274
    if (_outstandingNetworkRequests == 0) {
275 276 277
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStopped];
        [activityManager activateIdleTimer];
278
    }
279 280 281 282
}

#pragma mark - VLC internal communication and delegate

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
- (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
{
    CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
    CGFloat smoothingFactor = 0.005;
    _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;

    CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSString  *remaingTime = [formatter stringFromDate:date];
    if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
        [self.delegate updateRemainingTime:remaingTime];
}

301 302 303 304 305
- (NSArray *)currentListFiles
{
    return _currentFileList;
}

306 307 308 309 310 311 312 313
- (NSInteger)numberOfFilesWaitingToBeDownloaded
{
    if (_listOfDropboxFilesToDownload)
        return _listOfDropboxFilesToDownload.count;

    return 0;
}

314 315 316
#pragma mark - user feedback
- (void)_handleError:(NSError *)error
{
317
#if TARGET_OS_IOS
318 319 320 321 322
    VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
                                                      message:error.localizedDescription
                                                     delegate:self
                                            cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                            otherButtonTitles:nil];
323
    [alert show];
324 325 326 327 328 329 330 331 332 333 334 335
#else
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
                                                                   message:error.localizedDescription
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                            style:UIAlertActionStyleDestructive
                                                          handler:^(UIAlertAction *action) {
                                                          }];

    [alert addAction:defaultAction];

336
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
337
#endif
338 339
}

340 341 342 343 344 345
- (void)reset
{
    [_restClient cancelAllRequests];
    _currentFileList = nil;
}

346
@end