VLCDropboxController.m 9.17 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"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
17 18
#import "VLCActivityManager.h"
#import "VLCMediaFileDiscoverer.h"
19 20 21 22 23 24

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

25 26 27
    NSMutableArray *_listOfDropboxFilesToDownload;
    BOOL _downloadInProgress;

28
    NSInteger _outstandingNetworkRequests;
29 30 31 32 33

    CGFloat _averageSpeed;
    CGFloat _fileSize;
    NSTimeInterval _startDL;
    NSTimeInterval _lastStatsUpdate;
34 35 36 37 38 39 40 41
}

@end

@implementation VLCDropboxController

#pragma mark - session handling

42 43 44 45 46 47
+ (instancetype)sharedInstance
{
    static VLCDropboxController *sharedInstance = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
48
        sharedInstance = [VLCDropboxController new];
49 50 51 52 53
    });

    return sharedInstance;
}

54 55
- (void)startSession
{
56
    [[DBSession sharedSession] isLinked];
57 58 59 60 61 62 63
}

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

64
- (BOOL)isAuthorized
65
{
66
    return [[DBSession sharedSession] isLinked];
67 68 69 70 71 72 73 74 75 76 77 78 79
}

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

#pragma mark - file management
- (void)requestDirectoryListingAtPath:(NSString *)path
{
80
    if (self.isAuthorized)
81 82 83 84 85 86
        [[self restClient] loadMetadata:path];
}

- (void)downloadFileToDocumentFolder:(DBMetadata *)file
{
    if (!file.isDirectory) {
87 88 89
        if (!_listOfDropboxFilesToDownload)
            _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
        [_listOfDropboxFilesToDownload addObject:file];
90

91 92
        if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
            [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
93

94
        [self _triggerNextDownload];
95 96 97
    }
}

98 99 100 101 102 103
- (void)streamFile:(DBMetadata *)file
{
    if (!file.isDirectory)
        [[self restClient] loadStreamableURLForFile:file.path];
}

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
- (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];
119 120
    _startDL = [NSDate timeIntervalSinceReferenceDate];
    _fileSize = file.totalBytes;
121 122 123 124 125 126 127 128
    [[self restClient] loadFile:file.path intoPath:filePath];

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

    _downloadInProgress = YES;
}

129 130 131
#pragma mark - restClient delegate
- (BOOL)_supportedFileExtension:(NSString *)filename
{
132
    if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        return YES;

    return NO;
}

- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata {
    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
153
    APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
154 155 156 157 158 159
    if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
        [self.delegate mediaListUpdated];
}

- (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
{
160
    APLog(@"DBMetadata download failed with error %li", (long)error.code);
161
    [self _handleError:error];
162 163 164 165 166
}

- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
    /* update library now that we got a file */
Felix Paul Kühne's avatar
Felix Paul Kühne committed
167
    [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
168 169 170

    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
171 172 173
    _downloadInProgress = NO;

    [self _triggerNextDownload];
174 175 176 177
}

- (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
{
178
    APLog(@"DBFile download failed with error %li", (long)error.code);
179
    [self _handleError:error];
180 181
    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
182 183
    _downloadInProgress = NO;
    [self _triggerNextDownload];
184 185 186 187
}

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

193 194
    if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
        [self.delegate currentProgressInformation:progress];
195 196
}

197 198
- (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
{
199 200
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    [vpc playURL:url successCallback:nil errorCallback:nil];
201 202 203 204
}

- (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
{
205
    APLog(@"loadStreamableURL failed with error %li", (long)error.code);
206
    [self _handleError:error];
207 208
}

209 210 211 212 213 214 215 216 217 218
#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
{
219
    _outstandingNetworkRequests++;
220
    if (_outstandingNetworkRequests == 1) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
221 222 223
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStarted];
        [activityManager disableIdleTimer];
224
    }
225 226 227 228
}

- (void)networkRequestStopped
{
229
    _outstandingNetworkRequests--;
230
    if (_outstandingNetworkRequests == 0) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
231 232 233
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStopped];
        [activityManager activateIdleTimer];
234
    }
235 236 237 238
}

#pragma mark - VLC internal communication and delegate

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
- (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];
}

257 258 259 260 261
- (NSArray *)currentListFiles
{
    return _currentFileList;
}

262 263 264 265 266 267 268 269
- (NSInteger)numberOfFilesWaitingToBeDownloaded
{
    if (_listOfDropboxFilesToDownload)
        return _listOfDropboxFilesToDownload.count;

    return 0;
}

270 271 272
#pragma mark - user feedback
- (void)_handleError:(NSError *)error
{
273 274 275 276 277
    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];
278 279 280
    [alert show];
}

281
@end