VLCDropboxController.m 10.2 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 18 19
#if TARGET_OS_TV
#import "VLCPlayerDisplayController.h"
#else
Felix Paul Kühne's avatar
Felix Paul Kühne committed
20 21
#import "VLCActivityManager.h"
#import "VLCMediaFileDiscoverer.h"
22
#endif
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 40 41 42 43 44 45
}

@end

@implementation VLCDropboxController

#pragma mark - session handling

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

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

    return sharedInstance;
}

58 59
- (void)startSession
{
60
    [[DBSession sharedSession] isLinked];
61 62 63 64 65 66 67
}

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

68
- (BOOL)isAuthorized
69
{
70
    return [[DBSession sharedSession] isLinked];
71 72 73 74 75 76 77 78 79 80 81 82 83
}

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

#pragma mark - file management
- (void)requestDirectoryListingAtPath:(NSString *)path
{
84
    if (self.isAuthorized)
85 86 87 88 89 90
        [[self restClient] loadMetadata:path];
}

- (void)downloadFileToDocumentFolder:(DBMetadata *)file
{
    if (!file.isDirectory) {
91 92 93
        if (!_listOfDropboxFilesToDownload)
            _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
        [_listOfDropboxFilesToDownload addObject:file];
94

95 96
        if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
            [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
97

98
        [self _triggerNextDownload];
99 100 101
    }
}

102 103 104 105 106 107
- (void)streamFile:(DBMetadata *)file
{
    if (!file.isDirectory)
        [[self restClient] loadStreamableURLForFile:file.path];
}

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

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

    _downloadInProgress = YES;
}

133 134 135
#pragma mark - restClient delegate
- (BOOL)_supportedFileExtension:(NSString *)filename
{
136
    if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        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
157
    APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
158 159 160 161 162 163
    if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
        [self.delegate mediaListUpdated];
}

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

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

    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
176 177 178
    _downloadInProgress = NO;

    [self _triggerNextDownload];
179
#endif
180 181 182 183
}

- (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
{
184
    APLog(@"DBFile download failed with error %li", (long)error.code);
185
    [self _handleError:error];
186 187
    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
188 189
    _downloadInProgress = NO;
    [self _triggerNextDownload];
190 191 192 193
}

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

199 200
    if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
        [self.delegate currentProgressInformation:progress];
201 202
}

203 204
- (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
{
205 206
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    [vpc playURL:url successCallback:nil errorCallback:nil];
207 208 209 210
}

- (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
{
211
    APLog(@"loadStreamableURL failed with error %li", (long)error.code);
212
    [self _handleError:error];
213 214
}

215 216 217 218 219 220 221 222 223 224
#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
{
225
    _outstandingNetworkRequests++;
226
#if TARGET_OS_IOS
227
    if (_outstandingNetworkRequests == 1) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
228 229 230
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStarted];
        [activityManager disableIdleTimer];
231
    }
232
#endif
233 234 235 236
}

- (void)networkRequestStopped
{
237
    _outstandingNetworkRequests--;
238
#if TARGET_OS_IOS
239
    if (_outstandingNetworkRequests == 0) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
240 241 242
        VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
        [activityManager networkActivityStopped];
        [activityManager activateIdleTimer];
243
    }
244
#endif
245 246 247 248
}

#pragma mark - VLC internal communication and delegate

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
- (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];
}

267 268 269 270 271
- (NSArray *)currentListFiles
{
    return _currentFileList;
}

272 273 274 275 276 277 278 279
- (NSInteger)numberOfFilesWaitingToBeDownloaded
{
    if (_listOfDropboxFilesToDownload)
        return _listOfDropboxFilesToDownload.count;

    return 0;
}

280 281 282
#pragma mark - user feedback
- (void)_handleError:(NSError *)error
{
283
#if TARGET_OS_IOS
284 285 286 287 288
    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];
289
    [alert show];
290 291 292 293 294 295 296 297 298 299 300 301 302 303
#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];

    [[[VLCPlayerDisplayController sharedInstance] childViewController] presentViewController:alert animated:YES completion:nil];
#endif
304 305
}

306
@end