VLCBoxController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 "VLCAppDelegate.h"
  15. #import <SSKeychain/SSKeychain.h>
  16. @interface VLCBoxController ()
  17. {
  18. BoxCollection *_fileList;
  19. BoxAPIJSONOperation *_operation;
  20. NSArray *_currentFileList;
  21. NSMutableArray *_listOfBoxFilesToDownload;
  22. BOOL _downloadInProgress;
  23. int _maxOffset;
  24. int _offset;
  25. NSString *_folderId;
  26. CGFloat _averageSpeed;
  27. NSTimeInterval _startDL;
  28. NSTimeInterval _lastStatsUpdate;
  29. }
  30. @end
  31. @implementation VLCBoxController
  32. #pragma mark - session handling
  33. + (VLCCloudStorageController *)sharedInstance
  34. {
  35. static VLCBoxController *sharedInstance = nil;
  36. static dispatch_once_t pred;
  37. dispatch_once(&pred, ^{
  38. sharedInstance = [self new];
  39. });
  40. return sharedInstance;
  41. }
  42. - (void)startSession
  43. {
  44. [BoxSDK sharedSDK].OAuth2Session.clientID = kVLCBoxClientID;
  45. [BoxSDK sharedSDK].OAuth2Session.clientSecret = kVLCBoxClientSecret;
  46. NSString *token = [SSKeychain passwordForService:kVLCBoxService account:kVLCBoxAccount];
  47. if (token != nil) {
  48. [BoxSDK sharedSDK].OAuth2Session.refreshToken = token;
  49. }
  50. }
  51. - (void)stopSession
  52. {
  53. [_operation cancel];
  54. _offset = 0;
  55. _currentFileList = nil;
  56. }
  57. - (void)logout
  58. {
  59. [SSKeychain deletePasswordForService:kVLCBoxService account:kVLCBoxAccount];
  60. [[BoxSDK sharedSDK].OAuth2Session logout];
  61. [self stopSession];
  62. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  63. [self.delegate mediaListUpdated];
  64. }
  65. - (BOOL)isAuthorized
  66. {
  67. return [[BoxSDK sharedSDK].OAuth2Session isAuthorized];
  68. }
  69. - (void)showAlert:(NSString *)title message:(NSString *)message
  70. {
  71. UIAlertView *alert;
  72. alert = [[UIAlertView alloc] initWithTitle: title
  73. message: message
  74. delegate: nil
  75. cancelButtonTitle: NSLocalizedString(@"BUTTON_OK", nil)
  76. otherButtonTitles: nil];
  77. [alert show];
  78. }
  79. #pragma mark - file management
  80. - (void)requestDirectoryListingAtPath:(NSString *)path
  81. {
  82. //we entered a different folder so discard all current files
  83. if (![path isEqualToString:_folderId])
  84. _currentFileList = nil;
  85. [self listFilesWithID:path];
  86. }
  87. - (BOOL)hasMoreFiles
  88. {
  89. return _offset < _maxOffset;
  90. }
  91. - (void)downloadFileToDocumentFolder:(BoxItem *)file
  92. {
  93. if ([file.type isEqualToString:BoxAPIItemTypeFolder]) return;
  94. if (!_listOfBoxFilesToDownload)
  95. _listOfBoxFilesToDownload = [NSMutableArray new];
  96. [_listOfBoxFilesToDownload addObject:file];
  97. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  98. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  99. [self _triggerNextDownload];
  100. }
  101. - (void)listFilesWithID:(NSString *)folderId
  102. {
  103. _fileList = nil;
  104. _folderId = folderId;
  105. if (_folderId == nil || [_folderId isEqualToString:@""]) {
  106. _folderId = BoxAPIFolderIDRoot;
  107. }
  108. BoxCollectionBlock success = ^(BoxCollection *collection)
  109. {
  110. _fileList = collection;
  111. [self _listOfGoodFilesAndFolders];
  112. };
  113. BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
  114. {
  115. NSLog(@"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");
  116. };
  117. [_operation cancel];
  118. _operation = [[BoxSDK sharedSDK].foldersManager folderItemsWithID:_folderId requestBuilder:nil success:success failure:failure];
  119. }
  120. - (void)streamFile:(BoxFile *)file
  121. {
  122. // VLCAppDelegate *appDelegate = (VLCAppDelegate *)[UIApplication sharedApplication].delegate;
  123. // NSString *token = [BoxSDK sharedSDK].OAuth2Session.accessToken;
  124. // NSString *downloadString = [@"https://api.box.com/2.0/files/"stringByAppendingString:[NSString stringWithFormat:@"%@&access_token=%@",file.modelID, token]];
  125. // [appDelegate openMovieFromURL:[NSURL URLWithString:downloadString]];
  126. }
  127. - (void)_triggerNextDownload
  128. {
  129. if (_listOfBoxFilesToDownload.count > 0 && !_downloadInProgress) {
  130. [self _reallyDownloadFileToDocumentFolder:_listOfBoxFilesToDownload[0]];
  131. [_listOfBoxFilesToDownload removeObjectAtIndex:0];
  132. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  133. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  134. }
  135. }
  136. - (void)_reallyDownloadFileToDocumentFolder:(BoxFile *)file
  137. {
  138. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  139. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  140. [self loadFile:file intoPath:filePath];
  141. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  142. [self.delegate operationWithProgressInformationStarted];
  143. _downloadInProgress = YES;
  144. }
  145. - (BOOL)_supportedFileExtension:(NSString *)filename
  146. {
  147. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  148. return YES;
  149. return NO;
  150. }
  151. //just pick out Directories and supported formats.
  152. //if the resulting list contains less than 10 items try to get more
  153. - (void)_listOfGoodFilesAndFolders
  154. {
  155. NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
  156. _maxOffset = _fileList.totalCount.intValue;
  157. _offset += _fileList.numberOfEntries;
  158. NSUInteger numberOfEntries = _fileList.numberOfEntries;
  159. for (int i = 0; i < numberOfEntries; i++)
  160. {
  161. BoxModel *boxFile = [_fileList modelAtIndex:i];
  162. BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
  163. BOOL supportedFile = NO;
  164. if (!isDirectory) {
  165. BoxFile * file = (BoxFile *)boxFile;
  166. supportedFile = [self _supportedFileExtension:[NSString stringWithFormat:@".%@",file.name.lastPathComponent]];
  167. }
  168. if (isDirectory || supportedFile)
  169. [listOfGoodFilesAndFolders addObject:boxFile];
  170. }
  171. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  172. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  173. [self listFilesWithID:_folderId];
  174. return;
  175. }
  176. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  177. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  178. [self.delegate mediaListUpdated];
  179. }
  180. - (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
  181. {
  182. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
  183. _startDL = [NSDate timeIntervalSinceReferenceDate];
  184. BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
  185. {
  186. [self downloadSuccessful];
  187. };
  188. BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
  189. {
  190. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  191. [self downloadFailedWithError:error];
  192. };
  193. BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
  194. {
  195. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  196. [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
  197. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  198. }
  199. CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
  200. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  201. [self.delegate currentProgressInformation:progress];
  202. };
  203. [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
  204. }
  205. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  206. {
  207. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  208. CGFloat smoothingFactor = 0.005;
  209. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  210. CGFloat remainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  211. NSDate *date = [NSDate dateWithTimeIntervalSince1970:remainingInSeconds];
  212. NSDateFormatter *formatter = [NSDateFormatter new];
  213. [formatter setDateFormat:@"HH:mm:ss"];
  214. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  215. NSString *remainingTime = [formatter stringFromDate:date];
  216. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  217. [self.delegate updateRemainingTime:remainingTime];
  218. }
  219. - (void)downloadSuccessful
  220. {
  221. /* update library now that we got a file */
  222. APLog(@"BoxFile download was successful");
  223. VLCAppDelegate *appDelegate = (VLCAppDelegate *) [UIApplication sharedApplication].delegate;
  224. [appDelegate performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  225. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  226. [self.delegate operationWithProgressInformationStopped];
  227. _downloadInProgress = NO;
  228. [self _triggerNextDownload];
  229. }
  230. - (void)downloadFailedWithError:(NSError*)error
  231. {
  232. APLog(@"BoxFile download failed with error %li", (long)error.code);
  233. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  234. [self.delegate operationWithProgressInformationStopped];
  235. _downloadInProgress = NO;
  236. [self _triggerNextDownload];
  237. }
  238. #pragma mark - VLC internal communication and delegate
  239. - (NSArray *)currentListFiles
  240. {
  241. return _currentFileList;
  242. }
  243. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  244. {
  245. if (_listOfBoxFilesToDownload)
  246. return _listOfBoxFilesToDownload.count;
  247. return 0;
  248. }
  249. @end