VLCBoxController.m 11.7 KB
Newer Older
Carola Nitz's avatar
Carola Nitz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*****************************************************************************
 * VLCBoxController.m
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2014 VideoLAN. All rights reserved.
 * $Id$
 *
 * Authors: Carola Nitz <nitz.carola # googlemail.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

#import "VLCBoxController.h"
#import "NSString+SupportedMedia.h"
15
#import "VLCPlaybackController.h"
16
#import "VLCMediaFileDiscoverer.h"
17
#import <XKKeychain/XKKeychainGenericPasswordItem.h>
18
#if TARGET_OS_IOS
19
#import "VLC-Swift.h"
20
#endif
Carola Nitz's avatar
Carola Nitz committed
21

22
@interface VLCBoxController ()
Carola Nitz's avatar
Carola Nitz committed
23 24 25 26 27 28 29 30 31
{
    BoxCollection *_fileList;
    BoxAPIJSONOperation *_operation;

    NSArray *_currentFileList;

    NSMutableArray *_listOfBoxFilesToDownload;
    BOOL _downloadInProgress;

32 33
    int _maxOffset;
    int _offset;
Carola Nitz's avatar
Carola Nitz committed
34 35 36 37 38 39 40 41 42 43 44 45 46
    NSString *_folderId;

    CGFloat _averageSpeed;
    NSTimeInterval _startDL;
    NSTimeInterval _lastStatsUpdate;
}

@end

@implementation VLCBoxController

#pragma mark - session handling

47
+ (VLCCloudStorageController *)sharedInstance
Carola Nitz's avatar
Carola Nitz committed
48 49 50 51 52
{
    static VLCBoxController *sharedInstance = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
53
        sharedInstance = [VLCBoxController new];
Carola Nitz's avatar
Carola Nitz committed
54 55 56 57 58 59 60
    });

    return sharedInstance;
}

- (void)startSession
{
61 62 63 64 65 66 67 68 69 70 71
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(boxApiTokenDidRefresh)
                          name:BoxOAuth2SessionDidRefreshTokensNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];

    [defaultCenter addObserver:self
                      selector:@selector(boxApiTokenDidRefresh)
                          name:BoxOAuth2SessionDidBecomeAuthenticatedNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];

Carola Nitz's avatar
Carola Nitz committed
72 73
    [BoxSDK sharedSDK].OAuth2Session.clientID = kVLCBoxClientID;
    [BoxSDK sharedSDK].OAuth2Session.clientSecret = kVLCBoxClientSecret;
74 75

    NSString *token = [XKKeychainGenericPasswordItem itemForService:kVLCBoxService account:kVLCBoxAccount error:nil].secret.stringValue;
76 77 78 79 80
    if (!token) {
        NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
        [ubiquitousStore synchronize];
        token = [ubiquitousStore stringForKey:kVLCStoreBoxCredentials];
    }
Carola Nitz's avatar
Carola Nitz committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94
    if (token != nil) {
        [BoxSDK sharedSDK].OAuth2Session.refreshToken = token;
    }
}

- (void)stopSession
{
    [_operation cancel];
    _offset = 0;
    _currentFileList = nil;
}

- (void)logout
{
95 96 97 98 99
    XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
    keychainItem.service = kVLCBoxService;
    keychainItem.account = kVLCBoxAccount;
    [keychainItem deleteWithError:nil];

Carola Nitz's avatar
Carola Nitz committed
100
    [[BoxSDK sharedSDK].OAuth2Session logout];
101 102 103
    NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
    [ubiquitousStore setString:nil forKey:kVLCStoreBoxCredentials];
    [ubiquitousStore synchronize];
Carola Nitz's avatar
Carola Nitz committed
104 105
    [self stopSession];
    if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
106
        [self.delegate mediaListUpdated];
Carola Nitz's avatar
Carola Nitz committed
107 108
}

109 110 111 112 113
- (void)boxApiTokenDidRefresh
{
    [[NSNotificationCenter defaultCenter] postNotificationName:VLCBoxControllerSessionUpdated object:nil];
}

Carola Nitz's avatar
Carola Nitz committed
114 115 116 117 118 119
- (BOOL)isAuthorized
{
    return [[BoxSDK sharedSDK].OAuth2Session isAuthorized];
}

#pragma mark - file management
120 121 122 123 124 125

- (BOOL)canPlayAll
{
    return NO;
}

126
- (void)requestDirectoryListingAtPath:(NSString *)path
Carola Nitz's avatar
Carola Nitz committed
127 128
{
    //we entered a different folder so discard all current files
129
    if (![path isEqualToString:_folderId])
Carola Nitz's avatar
Carola Nitz committed
130
        _currentFileList = nil;
131
    [self listFilesWithID:path];
Carola Nitz's avatar
Carola Nitz committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
}

- (BOOL)hasMoreFiles
{
    return _offset < _maxOffset;
}

- (void)listFilesWithID:(NSString *)folderId
{
    _fileList = nil;
    _folderId = folderId;
    if (_folderId == nil || [_folderId isEqualToString:@""]) {
        _folderId = BoxAPIFolderIDRoot;
    }

    BoxCollectionBlock success = ^(BoxCollection *collection)
    {
149
        self->_fileList = collection;
Carola Nitz's avatar
Carola Nitz committed
150 151 152 153 154
        [self _listOfGoodFilesAndFolders];
    };

    BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
    {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
155
        APLog(@"there was an error getting the files but we don't show an error. this request is used to check if we need to refresh the token");
Carola Nitz's avatar
Carola Nitz committed
156 157 158 159 160 161
    };

    [_operation cancel];
    _operation = [[BoxSDK sharedSDK].foldersManager folderItemsWithID:_folderId requestBuilder:nil success:success failure:failure];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
#if TARGET_OS_IOS

- (void)downloadFileToDocumentFolder:(BoxItem *)file
{
    if (file != nil) {
        if ([file.type isEqualToString:BoxAPIItemTypeFolder]) return;

        if (!_listOfBoxFilesToDownload)
            _listOfBoxFilesToDownload = [NSMutableArray new];

        [_listOfBoxFilesToDownload addObject:file];
    }

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

    [self _triggerNextDownload];
}

Carola Nitz's avatar
Carola Nitz committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
- (void)_triggerNextDownload
{
    if (_listOfBoxFilesToDownload.count > 0 && !_downloadInProgress) {
        [self _reallyDownloadFileToDocumentFolder:_listOfBoxFilesToDownload[0]];
        [_listOfBoxFilesToDownload removeObjectAtIndex:0];

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

- (void)_reallyDownloadFileToDocumentFolder:(BoxFile *)file
{
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];

    [self loadFile:file intoPath:filePath];

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

    _downloadInProgress = YES;
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
204
#endif
Carola Nitz's avatar
Carola Nitz committed
205

206
//just pick out Directories and supported formats.
Carola Nitz's avatar
Carola Nitz committed
207 208 209 210 211
//if the resulting list contains less than 10 items try to get more

- (void)_listOfGoodFilesAndFolders
{
    NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
212 213
    _maxOffset = _fileList.totalCount.intValue;
    _offset += _fileList.numberOfEntries;
214

215 216
    NSUInteger numberOfEntries = _fileList.numberOfEntries;
    for (int i = 0; i < numberOfEntries; i++)
Carola Nitz's avatar
Carola Nitz committed
217 218 219 220 221 222
    {
        BoxModel *boxFile = [_fileList modelAtIndex:i];
        BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
        BOOL supportedFile = NO;
        if (!isDirectory) {
            BoxFile * file = (BoxFile *)boxFile;
223
            supportedFile = [[NSString stringWithFormat:@".%@",file.name.lastPathComponent] isSupportedFormat];
Carola Nitz's avatar
Carola Nitz committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        }

       if (isDirectory || supportedFile)
            [listOfGoodFilesAndFolders addObject:boxFile];
    }
    _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];

    if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
        [self listFilesWithID:_folderId];
        return;
    }

    APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);

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

Felix Paul Kühne's avatar
Felix Paul Kühne committed
242
#if TARGET_OS_IOS
Carola Nitz's avatar
Carola Nitz committed
243 244 245 246 247 248 249 250 251 252 253
- (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
{
    NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
    _startDL = [NSDate timeIntervalSinceReferenceDate];
    BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
    {
        [self downloadSuccessful];
    };

    BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
    {
254
        [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
Carola Nitz's avatar
Carola Nitz committed
255 256 257 258 259
        [self downloadFailedWithError:error];
    };

    BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
    {
260
        if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
Carola Nitz's avatar
Carola Nitz committed
261
            [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
262
            self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
Carola Nitz's avatar
Carola Nitz committed
263 264 265 266 267 268 269 270 271 272
        }

        CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
        if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
            [self.delegate currentProgressInformation:progress];
    };

    [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
273 274
- (void)showAlert:(NSString *)title message:(NSString *)message
{
275 276
    [VLCAlertViewController alertViewManagerWithTitle:title
                                         errorMessage:message
277
                                       viewController:[UIApplication sharedApplication].keyWindow.rootViewController];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
278 279
}

Carola Nitz's avatar
Carola Nitz committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
- (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 new];
    [formatter setDateFormat:@"HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

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

- (void)downloadSuccessful
{
    /* update library now that we got a file */
    APLog(@"BoxFile download was successful");
303
    UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
304
    [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
305
#if TARGET_OS_IOS
306 307 308
    // FIXME: Replace notifications by cleaner observers
    [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
                                                        object:self];
309
#endif
Carola Nitz's avatar
Carola Nitz committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
    _downloadInProgress = NO;

    [self _triggerNextDownload];
}

- (void)downloadFailedWithError:(NSError*)error
{
    APLog(@"BoxFile download failed with error %li", (long)error.code);
    if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
        [self.delegate operationWithProgressInformationStopped];
    _downloadInProgress = NO;

    [self _triggerNextDownload];
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
326
#endif
Carola Nitz's avatar
Carola Nitz committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

#pragma mark - VLC internal communication and delegate

- (NSArray *)currentListFiles
{
    return _currentFileList;
}

- (NSInteger)numberOfFilesWaitingToBeDownloaded
{
    if (_listOfBoxFilesToDownload)
        return _listOfBoxFilesToDownload.count;

    return 0;
}

@end