VLCBoxController.m 12 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. #import "VLC_iOS-Swift.h"
  18. @interface VLCBoxController ()
  19. {
  20. BoxCollection *_fileList;
  21. BoxAPIJSONOperation *_operation;
  22. NSArray *_currentFileList;
  23. NSMutableArray *_listOfBoxFilesToDownload;
  24. BOOL _downloadInProgress;
  25. int _maxOffset;
  26. int _offset;
  27. NSString *_folderId;
  28. CGFloat _averageSpeed;
  29. NSTimeInterval _startDL;
  30. NSTimeInterval _lastStatsUpdate;
  31. }
  32. @end
  33. @implementation VLCBoxController
  34. #pragma mark - session handling
  35. + (VLCCloudStorageController *)sharedInstance
  36. {
  37. static VLCBoxController *sharedInstance = nil;
  38. static dispatch_once_t pred;
  39. dispatch_once(&pred, ^{
  40. sharedInstance = [VLCBoxController new];
  41. });
  42. return sharedInstance;
  43. }
  44. - (void)startSession
  45. {
  46. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  47. [defaultCenter addObserver:self
  48. selector:@selector(boxApiTokenDidRefresh)
  49. name:BoxOAuth2SessionDidRefreshTokensNotification
  50. object:[BoxSDK sharedSDK].OAuth2Session];
  51. [defaultCenter addObserver:self
  52. selector:@selector(boxApiTokenDidRefresh)
  53. name:BoxOAuth2SessionDidBecomeAuthenticatedNotification
  54. object:[BoxSDK sharedSDK].OAuth2Session];
  55. [BoxSDK sharedSDK].OAuth2Session.clientID = kVLCBoxClientID;
  56. [BoxSDK sharedSDK].OAuth2Session.clientSecret = kVLCBoxClientSecret;
  57. NSString *token = [XKKeychainGenericPasswordItem itemForService:kVLCBoxService account:kVLCBoxAccount error:nil].secret.stringValue;
  58. if (!token) {
  59. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  60. [ubiquitousStore synchronize];
  61. token = [ubiquitousStore stringForKey:kVLCStoreBoxCredentials];
  62. }
  63. if (token != nil) {
  64. [BoxSDK sharedSDK].OAuth2Session.refreshToken = token;
  65. }
  66. }
  67. - (void)stopSession
  68. {
  69. [_operation cancel];
  70. _offset = 0;
  71. _currentFileList = nil;
  72. }
  73. - (void)logout
  74. {
  75. XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
  76. keychainItem.service = kVLCBoxService;
  77. keychainItem.account = kVLCBoxAccount;
  78. [keychainItem deleteWithError:nil];
  79. [[BoxSDK sharedSDK].OAuth2Session logout];
  80. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  81. [ubiquitousStore setString:nil forKey:kVLCStoreBoxCredentials];
  82. [ubiquitousStore synchronize];
  83. [self stopSession];
  84. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  85. [self.delegate mediaListUpdated];
  86. }
  87. - (void)boxApiTokenDidRefresh
  88. {
  89. [[NSNotificationCenter defaultCenter] postNotificationName:VLCBoxControllerSessionUpdated object:nil];
  90. }
  91. - (BOOL)isAuthorized
  92. {
  93. return [[BoxSDK sharedSDK].OAuth2Session isAuthorized];
  94. }
  95. #pragma mark - file management
  96. - (BOOL)canPlayAll
  97. {
  98. return NO;
  99. }
  100. - (void)requestDirectoryListingAtPath:(NSString *)path
  101. {
  102. //we entered a different folder so discard all current files
  103. if (![path isEqualToString:_folderId])
  104. _currentFileList = nil;
  105. [self listFilesWithID:path];
  106. }
  107. - (BOOL)hasMoreFiles
  108. {
  109. return _offset < _maxOffset;
  110. }
  111. - (void)listFilesWithID:(NSString *)folderId
  112. {
  113. _fileList = nil;
  114. _folderId = folderId;
  115. if (_folderId == nil || [_folderId isEqualToString:@""]) {
  116. _folderId = BoxAPIFolderIDRoot;
  117. }
  118. BoxCollectionBlock success = ^(BoxCollection *collection)
  119. {
  120. self->_fileList = collection;
  121. [self _listOfGoodFilesAndFolders];
  122. };
  123. BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
  124. {
  125. 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");
  126. };
  127. [_operation cancel];
  128. _operation = [[BoxSDK sharedSDK].foldersManager folderItemsWithID:_folderId requestBuilder:nil success:success failure:failure];
  129. }
  130. #if TARGET_OS_IOS
  131. - (void)downloadFileToDocumentFolder:(BoxItem *)file
  132. {
  133. if (file != nil) {
  134. if ([file.type isEqualToString:BoxAPIItemTypeFolder]) return;
  135. if (!_listOfBoxFilesToDownload)
  136. _listOfBoxFilesToDownload = [NSMutableArray new];
  137. [_listOfBoxFilesToDownload addObject:file];
  138. }
  139. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  140. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  141. [self _triggerNextDownload];
  142. }
  143. - (void)_triggerNextDownload
  144. {
  145. if (_listOfBoxFilesToDownload.count > 0 && !_downloadInProgress) {
  146. [self _reallyDownloadFileToDocumentFolder:_listOfBoxFilesToDownload[0]];
  147. [_listOfBoxFilesToDownload removeObjectAtIndex:0];
  148. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  149. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  150. }
  151. }
  152. - (void)_reallyDownloadFileToDocumentFolder:(BoxFile *)file
  153. {
  154. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  155. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  156. [self loadFile:file intoPath:filePath];
  157. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  158. [self.delegate operationWithProgressInformationStarted];
  159. _downloadInProgress = YES;
  160. }
  161. #endif
  162. //just pick out Directories and supported formats.
  163. //if the resulting list contains less than 10 items try to get more
  164. - (void)_listOfGoodFilesAndFolders
  165. {
  166. NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
  167. _maxOffset = _fileList.totalCount.intValue;
  168. _offset += _fileList.numberOfEntries;
  169. NSUInteger numberOfEntries = _fileList.numberOfEntries;
  170. for (int i = 0; i < numberOfEntries; i++)
  171. {
  172. BoxModel *boxFile = [_fileList modelAtIndex:i];
  173. BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
  174. BOOL supportedFile = NO;
  175. if (!isDirectory) {
  176. BoxFile * file = (BoxFile *)boxFile;
  177. supportedFile = [[NSString stringWithFormat:@".%@",file.name.lastPathComponent] isSupportedFormat];
  178. }
  179. if (isDirectory || supportedFile)
  180. [listOfGoodFilesAndFolders addObject:boxFile];
  181. }
  182. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  183. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  184. [self listFilesWithID:_folderId];
  185. return;
  186. }
  187. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  188. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  189. [self.delegate mediaListUpdated];
  190. }
  191. #if TARGET_OS_IOS
  192. - (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
  193. {
  194. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
  195. _startDL = [NSDate timeIntervalSinceReferenceDate];
  196. BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
  197. {
  198. [self downloadSuccessful];
  199. };
  200. BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
  201. {
  202. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  203. [self downloadFailedWithError:error];
  204. };
  205. BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
  206. {
  207. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  208. [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
  209. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  210. }
  211. CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
  212. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  213. [self.delegate currentProgressInformation:progress];
  214. };
  215. [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
  216. }
  217. - (void)showAlert:(NSString *)title message:(NSString *)message
  218. {
  219. [VLCAlertViewController alertViewManagerWithTitle:title
  220. errorMessage:message
  221. viewController:[UIApplication sharedApplication].keyWindow.rootViewController
  222. buttonsAction:@[[[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_OK", nil)
  223. action: ^(UIAlertAction* action){}]]];
  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