VLCBoxController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 <SSKeychain/SSKeychain.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)dealloc
  44. {
  45. [[NSNotificationCenter defaultCenter] removeObserver:self];
  46. }
  47. - (void)startSession
  48. {
  49. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  50. [defaultCenter addObserver:self
  51. selector:@selector(boxApiTokenDidRefresh)
  52. name:BoxOAuth2SessionDidRefreshTokensNotification
  53. object:[BoxSDK sharedSDK].OAuth2Session];
  54. [defaultCenter addObserver:self
  55. selector:@selector(boxApiTokenDidRefresh)
  56. name:BoxOAuth2SessionDidBecomeAuthenticatedNotification
  57. object:[BoxSDK sharedSDK].OAuth2Session];
  58. [BoxSDK sharedSDK].OAuth2Session.clientID = kVLCBoxClientID;
  59. [BoxSDK sharedSDK].OAuth2Session.clientSecret = kVLCBoxClientSecret;
  60. NSString *token = [SSKeychain passwordForService:kVLCBoxService account:kVLCBoxAccount];
  61. if (!token) {
  62. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  63. [ubiquitousStore synchronize];
  64. token = [ubiquitousStore stringForKey:kVLCStoreBoxCredentials];
  65. }
  66. if (token != nil) {
  67. [BoxSDK sharedSDK].OAuth2Session.refreshToken = token;
  68. }
  69. }
  70. - (void)stopSession
  71. {
  72. [_operation cancel];
  73. _offset = 0;
  74. _currentFileList = nil;
  75. }
  76. - (void)logout
  77. {
  78. [SSKeychain deletePasswordForService:kVLCBoxService account:kVLCBoxAccount];
  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. _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. - (BOOL)_supportedFileExtension:(NSString *)filename
  163. {
  164. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  165. return YES;
  166. return NO;
  167. }
  168. //just pick out Directories and supported formats.
  169. //if the resulting list contains less than 10 items try to get more
  170. - (void)_listOfGoodFilesAndFolders
  171. {
  172. NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
  173. _maxOffset = _fileList.totalCount.intValue;
  174. _offset += _fileList.numberOfEntries;
  175. NSUInteger numberOfEntries = _fileList.numberOfEntries;
  176. for (int i = 0; i < numberOfEntries; i++)
  177. {
  178. BoxModel *boxFile = [_fileList modelAtIndex:i];
  179. BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
  180. BOOL supportedFile = NO;
  181. if (!isDirectory) {
  182. BoxFile * file = (BoxFile *)boxFile;
  183. supportedFile = [self _supportedFileExtension:[NSString stringWithFormat:@".%@",file.name.lastPathComponent]];
  184. }
  185. if (isDirectory || supportedFile)
  186. [listOfGoodFilesAndFolders addObject:boxFile];
  187. }
  188. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  189. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  190. [self listFilesWithID:_folderId];
  191. return;
  192. }
  193. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  194. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  195. [self.delegate mediaListUpdated];
  196. }
  197. #if TARGET_OS_IOS
  198. - (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
  199. {
  200. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
  201. _startDL = [NSDate timeIntervalSinceReferenceDate];
  202. BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
  203. {
  204. [self downloadSuccessful];
  205. };
  206. BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
  207. {
  208. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  209. [self downloadFailedWithError:error];
  210. };
  211. BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
  212. {
  213. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  214. [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
  215. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  216. }
  217. CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
  218. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  219. [self.delegate currentProgressInformation:progress];
  220. };
  221. [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
  222. }
  223. - (void)showAlert:(NSString *)title message:(NSString *)message
  224. {
  225. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:title
  226. message:message
  227. delegate:nil
  228. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  229. otherButtonTitles:nil];
  230. [alert show];
  231. }
  232. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  233. {
  234. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  235. CGFloat smoothingFactor = 0.005;
  236. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  237. CGFloat remainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  238. NSDate *date = [NSDate dateWithTimeIntervalSince1970:remainingInSeconds];
  239. NSDateFormatter *formatter = [NSDateFormatter new];
  240. [formatter setDateFormat:@"HH:mm:ss"];
  241. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  242. NSString *remainingTime = [formatter stringFromDate:date];
  243. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  244. [self.delegate updateRemainingTime:remainingTime];
  245. }
  246. - (void)downloadSuccessful
  247. {
  248. /* update library now that we got a file */
  249. APLog(@"BoxFile download was successful");
  250. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  251. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  252. [self.delegate operationWithProgressInformationStopped];
  253. _downloadInProgress = NO;
  254. [self _triggerNextDownload];
  255. }
  256. - (void)downloadFailedWithError:(NSError*)error
  257. {
  258. APLog(@"BoxFile download failed with error %li", (long)error.code);
  259. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  260. [self.delegate operationWithProgressInformationStopped];
  261. _downloadInProgress = NO;
  262. [self _triggerNextDownload];
  263. }
  264. #endif
  265. #pragma mark - VLC internal communication and delegate
  266. - (NSArray *)currentListFiles
  267. {
  268. return _currentFileList;
  269. }
  270. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  271. {
  272. if (_listOfBoxFilesToDownload)
  273. return _listOfBoxFilesToDownload.count;
  274. return 0;
  275. }
  276. @end