VLCDropboxController.m 11 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
#if !TARGET_OS_TV
Felix Paul Kühne's avatar
Felix Paul Kühne committed
18 19
#import "VLCActivityManager.h"
#import "VLCMediaFileDiscoverer.h"
20
#endif
21
#import "DBKeychain.h"
22 23 24 25 26 27

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

28 29 30
    NSMutableArray *_listOfDropboxFilesToDownload;
    BOOL _downloadInProgress;

31
    NSInteger _outstandingNetworkRequests;
32 33 34 35 36

    CGFloat _averageSpeed;
    CGFloat _fileSize;
    NSTimeInterval _startDL;
    NSTimeInterval _lastStatsUpdate;
37 38 39 40 41 42 43 44
}

@end

@implementation VLCDropboxController

#pragma mark - session handling

45 46 47 48 49 50
+ (instancetype)sharedInstance
{
    static VLCDropboxController *sharedInstance = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
51
        sharedInstance = [VLCDropboxController new];
52
        [sharedInstance shareCredentials];
53 54 55 56 57
    });

    return sharedInstance;
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
- (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;
}

82 83
- (void)startSession
{
84
    [[DBSession sharedSession] isLinked];
85 86 87 88 89 90 91
}

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

92
- (BOOL)isAuthorized
93
{
94
    return [[DBSession sharedSession] isLinked];
95 96 97 98 99 100 101 102 103 104 105 106 107
}

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

#pragma mark - file management
- (void)requestDirectoryListingAtPath:(NSString *)path
{
108
    if (self.isAuthorized)
109 110 111 112 113 114
        [[self restClient] loadMetadata:path];
}

- (void)downloadFileToDocumentFolder:(DBMetadata *)file
{
    if (!file.isDirectory) {
115 116 117
        if (!_listOfDropboxFilesToDownload)
            _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
        [_listOfDropboxFilesToDownload addObject:file];
118

119 120
        if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
            [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
121

122
        [self _triggerNextDownload];
123 124 125
    }
}

126 127 128 129 130 131
- (void)streamFile:(DBMetadata *)file
{
    if (!file.isDirectory)
        [[self restClient] loadStreamableURLForFile:file.path];
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
- (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];
147 148
    _startDL = [NSDate timeIntervalSinceReferenceDate];
    _fileSize = file.totalBytes;
149 150 151 152 153 154 155 156
    [[self restClient] loadFile:file.path intoPath:filePath];

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

    _downloadInProgress = YES;
}

157 158 159
#pragma mark - restClient delegate
- (BOOL)_supportedFileExtension:(NSString *)filename
{
160
    if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
161 162 163 164 165
        return YES;

    return NO;
}

166 167
- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata
{
168 169 170 171 172 173 174 175 176 177 178 179 180 181
    NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];

    if (metadata.isDirectory) {
        NSArray *contents = metadata.contents;
        NSUInteger metaDataCount = metadata.contents.count;
        for (NSUInteger x = 0; x < metaDataCount; x++) {
            DBMetadata *file = contents[x];
            if ([file isDirectory] || [self _supportedFileExtension:file.filename])
                [listOfGoodFilesAndFolders addObject:file];
        }
    }

    _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];

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

- (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
{
189
    APLog(@"DBMetadata download failed with error %li", (long)error.code);
190
    [self _handleError:error];
191 192 193 194
}

- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
195
#if TARGET_OS_IOS
196
    /* update library now that we got a file */
Felix Paul Kühne's avatar
Felix Paul Kühne committed
197
    [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
198 199 200

    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
201 202 203
    _downloadInProgress = NO;

    [self _triggerNextDownload];
204
#endif
205 206 207 208
}

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

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

224 225
    if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
        [self.delegate currentProgressInformation:progress];
226 227
}

228 229
- (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
{
230 231
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    [vpc playURL:url successCallback:nil errorCallback:nil];
232 233 234 235
}

- (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
{
236
    APLog(@"loadStreamableURL failed with error %li", (long)error.code);
237
    [self _handleError:error];
238 239
}

240 241 242 243 244 245 246 247 248 249
#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
{
250
    _outstandingNetworkRequests++;
251
#if TARGET_OS_IOS
252
    if (_outstandingNetworkRequests == 1) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
253 254 255
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStarted];
        [activityManager disableIdleTimer];
256
    }
257
#endif
258 259 260 261
}

- (void)networkRequestStopped
{
262
    _outstandingNetworkRequests--;
263
#if TARGET_OS_IOS
264
    if (_outstandingNetworkRequests == 0) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
265 266 267
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStopped];
        [activityManager activateIdleTimer];
268
    }
269
#endif
270 271 272 273
}

#pragma mark - VLC internal communication and delegate

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
- (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];
}

292 293 294 295 296
- (NSArray *)currentListFiles
{
    return _currentFileList;
}

297 298 299 300 301 302 303 304
- (NSInteger)numberOfFilesWaitingToBeDownloaded
{
    if (_listOfDropboxFilesToDownload)
        return _listOfDropboxFilesToDownload.count;

    return 0;
}

305 306 307
#pragma mark - user feedback
- (void)_handleError:(NSError *)error
{
308
#if TARGET_OS_IOS
309 310 311 312 313
    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];
314
    [alert show];
315 316 317 318 319 320 321 322 323 324 325 326
#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];

327
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
328
#endif
329 330
}

331
@end