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