VLCBoxController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*****************************************************************************
  2. * VLCBoxController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <nitz.carola # googlemail.com>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. #import "VLCBoxController.h"
  13. #import "NSString+SupportedMedia.h"
  14. #import "VLCPlaybackController.h"
  15. #import "VLCMediaFileDiscoverer.h"
  16. #import <XKKeychain/XKKeychainGenericPasswordItem.h>
  17. #if TARGET_OS_IOS
  18. #import "VLC-Swift.h"
  19. #endif
  20. @interface VLCBoxController ()
  21. {
  22. BoxCollection *_fileList;
  23. BoxAPIJSONOperation *_operation;
  24. NSArray *_currentFileList;
  25. NSMutableArray *_listOfBoxFilesToDownload;
  26. BOOL _downloadInProgress;
  27. int _maxOffset;
  28. int _offset;
  29. NSString *_folderId;
  30. CGFloat _averageSpeed;
  31. NSTimeInterval _startDL;
  32. NSTimeInterval _lastStatsUpdate;
  33. }
  34. @end
  35. @implementation VLCBoxController
  36. #pragma mark - session handling
  37. + (VLCCloudStorageController *)sharedInstance
  38. {
  39. static VLCBoxController *sharedInstance = nil;
  40. static dispatch_once_t pred;
  41. dispatch_once(&pred, ^{
  42. sharedInstance = [VLCBoxController new];
  43. });
  44. return sharedInstance;
  45. }
  46. - (void)startSession
  47. {
  48. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  49. [defaultCenter addObserver:self
  50. selector:@selector(boxApiTokenDidRefresh)
  51. name:BoxOAuth2SessionDidRefreshTokensNotification
  52. object:[BoxSDK sharedSDK].OAuth2Session];
  53. [defaultCenter addObserver:self
  54. selector:@selector(boxApiTokenDidRefresh)
  55. name:BoxOAuth2SessionDidBecomeAuthenticatedNotification
  56. object:[BoxSDK sharedSDK].OAuth2Session];
  57. [BoxSDK sharedSDK].OAuth2Session.clientID = kVLCBoxClientID;
  58. [BoxSDK sharedSDK].OAuth2Session.clientSecret = kVLCBoxClientSecret;
  59. NSString *token = [XKKeychainGenericPasswordItem itemForService:kVLCBoxService account:kVLCBoxAccount error:nil].secret.stringValue;
  60. if (!token) {
  61. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  62. [ubiquitousStore synchronize];
  63. token = [ubiquitousStore stringForKey:kVLCStoreBoxCredentials];
  64. }
  65. if (token != nil) {
  66. [BoxSDK sharedSDK].OAuth2Session.refreshToken = token;
  67. }
  68. }
  69. - (void)stopSession
  70. {
  71. [_operation cancel];
  72. _offset = 0;
  73. _currentFileList = nil;
  74. }
  75. - (void)logout
  76. {
  77. XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
  78. keychainItem.service = kVLCBoxService;
  79. keychainItem.account = kVLCBoxAccount;
  80. [keychainItem deleteWithError:nil];
  81. [[BoxSDK sharedSDK].OAuth2Session logout];
  82. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  83. [ubiquitousStore setString:nil forKey:kVLCStoreBoxCredentials];
  84. [ubiquitousStore synchronize];
  85. [self stopSession];
  86. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  87. [self.delegate mediaListUpdated];
  88. }
  89. - (void)boxApiTokenDidRefresh
  90. {
  91. [[NSNotificationCenter defaultCenter] postNotificationName:VLCBoxControllerSessionUpdated object:nil];
  92. }
  93. - (BOOL)isAuthorized
  94. {
  95. return [[BoxSDK sharedSDK].OAuth2Session isAuthorized];
  96. }
  97. #pragma mark - file management
  98. - (BOOL)canPlayAll
  99. {
  100. return NO;
  101. }
  102. - (void)requestDirectoryListingAtPath:(NSString *)path
  103. {
  104. //we entered a different folder so discard all current files
  105. if (![path isEqualToString:_folderId])
  106. _currentFileList = nil;
  107. [self listFilesWithID:path];
  108. }
  109. - (BOOL)hasMoreFiles
  110. {
  111. return _offset < _maxOffset;
  112. }
  113. - (void)listFilesWithID:(NSString *)folderId
  114. {
  115. _fileList = nil;
  116. _folderId = folderId;
  117. if (_folderId == nil || [_folderId isEqualToString:@""]) {
  118. _folderId = BoxAPIFolderIDRoot;
  119. }
  120. BoxCollectionBlock success = ^(BoxCollection *collection)
  121. {
  122. self->_fileList = collection;
  123. [self _listOfGoodFilesAndFolders];
  124. };
  125. BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
  126. {
  127. 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");
  128. };
  129. [_operation cancel];
  130. _operation = [[BoxSDK sharedSDK].foldersManager folderItemsWithID:_folderId requestBuilder:nil success:success failure:failure];
  131. }
  132. #if TARGET_OS_IOS
  133. - (void)downloadFileToDocumentFolder:(BoxItem *)file
  134. {
  135. if (file != nil) {
  136. if ([file.type isEqualToString:BoxAPIItemTypeFolder]) return;
  137. if (!_listOfBoxFilesToDownload)
  138. _listOfBoxFilesToDownload = [NSMutableArray new];
  139. [_listOfBoxFilesToDownload addObject:file];
  140. }
  141. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  142. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  143. [self _triggerNextDownload];
  144. }
  145. - (void)_triggerNextDownload
  146. {
  147. if (_listOfBoxFilesToDownload.count > 0 && !_downloadInProgress) {
  148. [self _reallyDownloadFileToDocumentFolder:_listOfBoxFilesToDownload[0]];
  149. [_listOfBoxFilesToDownload removeObjectAtIndex:0];
  150. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  151. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  152. }
  153. }
  154. - (void)_reallyDownloadFileToDocumentFolder:(BoxFile *)file
  155. {
  156. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  157. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  158. [self loadFile:file intoPath:filePath];
  159. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  160. [self.delegate operationWithProgressInformationStarted];
  161. _downloadInProgress = YES;
  162. }
  163. #endif
  164. //just pick out Directories and supported formats.
  165. //if the resulting list contains less than 10 items try to get more
  166. - (void)_listOfGoodFilesAndFolders
  167. {
  168. NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
  169. _maxOffset = _fileList.totalCount.intValue;
  170. _offset += _fileList.numberOfEntries;
  171. NSUInteger numberOfEntries = _fileList.numberOfEntries;
  172. for (int i = 0; i < numberOfEntries; i++)
  173. {
  174. BoxModel *boxFile = [_fileList modelAtIndex:i];
  175. BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
  176. BOOL supportedFile = NO;
  177. if (!isDirectory) {
  178. BoxFile * file = (BoxFile *)boxFile;
  179. supportedFile = [[NSString stringWithFormat:@".%@",file.name.lastPathComponent] isSupportedFormat];
  180. }
  181. if (isDirectory || supportedFile)
  182. [listOfGoodFilesAndFolders addObject:boxFile];
  183. }
  184. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  185. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  186. [self listFilesWithID:_folderId];
  187. return;
  188. }
  189. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  190. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  191. [self.delegate mediaListUpdated];
  192. }
  193. #if TARGET_OS_IOS
  194. - (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
  195. {
  196. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
  197. _startDL = [NSDate timeIntervalSinceReferenceDate];
  198. BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
  199. {
  200. [self downloadSuccessful];
  201. };
  202. BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
  203. {
  204. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  205. [self downloadFailedWithError:error];
  206. };
  207. BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
  208. {
  209. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  210. [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
  211. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  212. }
  213. CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
  214. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  215. [self.delegate currentProgressInformation:progress];
  216. };
  217. [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
  218. }
  219. - (void)showAlert:(NSString *)title message:(NSString *)message
  220. {
  221. [VLCAlertViewController alertViewManagerWithTitle:title
  222. errorMessage:message
  223. viewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  224. }
  225. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  226. {
  227. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  228. CGFloat smoothingFactor = 0.005;
  229. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  230. CGFloat remainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  231. NSDate *date = [NSDate dateWithTimeIntervalSince1970:remainingInSeconds];
  232. NSDateFormatter *formatter = [NSDateFormatter new];
  233. [formatter setDateFormat:@"HH:mm:ss"];
  234. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  235. NSString *remainingTime = [formatter stringFromDate:date];
  236. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  237. [self.delegate updateRemainingTime:remainingTime];
  238. }
  239. - (void)downloadSuccessful
  240. {
  241. /* update library now that we got a file */
  242. APLog(@"BoxFile download was successful");
  243. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  244. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  245. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  246. [self.delegate operationWithProgressInformationStopped];
  247. _downloadInProgress = NO;
  248. [self _triggerNextDownload];
  249. }
  250. - (void)downloadFailedWithError:(NSError*)error
  251. {
  252. APLog(@"BoxFile download failed with error %li", (long)error.code);
  253. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  254. [self.delegate operationWithProgressInformationStopped];
  255. _downloadInProgress = NO;
  256. [self _triggerNextDownload];
  257. }
  258. #endif
  259. #pragma mark - VLC internal communication and delegate
  260. - (NSArray *)currentListFiles
  261. {
  262. return _currentFileList;
  263. }
  264. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  265. {
  266. if (_listOfBoxFilesToDownload)
  267. return _listOfBoxFilesToDownload.count;
  268. return 0;
  269. }
  270. @end