VLCBoxController.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 () <NSURLConnectionDataDelegate>
  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. [BoxSDK sharedSDK].OAuth2Session.clientID = kVLCBoxClientID;
  46. [BoxSDK sharedSDK].OAuth2Session.clientSecret = kVLCBoxClientSecret;
  47. NSString *token = [SSKeychain passwordForService:kVLCBoxService account:kVLCBoxAccount];
  48. if (token != nil) {
  49. [BoxSDK sharedSDK].OAuth2Session.refreshToken = token;
  50. }
  51. }
  52. - (void)stopSession
  53. {
  54. [_operation cancel];
  55. _offset = 0;
  56. _currentFileList = nil;
  57. }
  58. - (void)logout
  59. {
  60. [SSKeychain deletePasswordForService:kVLCBoxService account:kVLCBoxAccount];
  61. [[BoxSDK sharedSDK].OAuth2Session logout];
  62. [self stopSession];
  63. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  64. [self.delegate mediaListUpdated];
  65. }
  66. - (BOOL)isAuthorized
  67. {
  68. return [[BoxSDK sharedSDK].OAuth2Session isAuthorized];
  69. }
  70. - (void)showAlert:(NSString *)title message:(NSString *)message
  71. {
  72. VLCAlertView *alert = [[VLCAlertView 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 != nil) {
  94. if ([file.type isEqualToString:BoxAPIItemTypeFolder]) return;
  95. if (!_listOfBoxFilesToDownload)
  96. _listOfBoxFilesToDownload = [NSMutableArray new];
  97. [_listOfBoxFilesToDownload addObject:file];
  98. }
  99. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  100. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  101. [self _triggerNextDownload];
  102. }
  103. - (void)listFilesWithID:(NSString *)folderId
  104. {
  105. _fileList = nil;
  106. _folderId = folderId;
  107. if (_folderId == nil || [_folderId isEqualToString:@""]) {
  108. _folderId = BoxAPIFolderIDRoot;
  109. }
  110. BoxCollectionBlock success = ^(BoxCollection *collection)
  111. {
  112. _fileList = collection;
  113. [self _listOfGoodFilesAndFolders];
  114. };
  115. BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
  116. {
  117. 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");
  118. };
  119. [_operation cancel];
  120. _operation = [[BoxSDK sharedSDK].foldersManager folderItemsWithID:_folderId requestBuilder:nil success:success failure:failure];
  121. }
  122. - (void)streamFile:(BoxFile *)file
  123. {
  124. /* the Box API requires us to set an HTTP header to get the actual URL:
  125. * curl -L https://api.box.com/2.0/files/FILE_ID/content -H "Authorization: Bearer ACCESS_TOKEN"
  126. *
  127. * ... however, libvlc does not support setting custom HTTP headers, so we are resolving the redirect ourselves with a NSURLConnection
  128. * and pass the final location to libvlc, which does not require a custom HTTP header */
  129. NSURL *baseURL = [[[BoxSDK sharedSDK] filesManager] URLWithResource:@"files"
  130. ID:file.modelID
  131. subresource:@"content"
  132. subID:nil];
  133. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:baseURL
  134. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  135. timeoutInterval:60];
  136. [urlRequest setValue:[NSString stringWithFormat:@"Bearer %@", [BoxSDK sharedSDK].OAuth2Session.accessToken] forHTTPHeaderField:@"Authorization"];
  137. NSURLConnection *theTestConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
  138. [theTestConnection start];
  139. }
  140. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
  141. {
  142. if (response != nil) {
  143. /* we have 1 redirect from the original URL, so as soon as we'd do that,
  144. * we grab the URL and cancel the connection */
  145. NSURL *theActualURL = request.URL;
  146. [connection cancel];
  147. /* now ask VLC to stream the URL we were just passed */
  148. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  149. [vpc playURL:theActualURL successCallback:nil errorCallback:nil];
  150. }
  151. return request;
  152. }
  153. - (void)_triggerNextDownload
  154. {
  155. if (_listOfBoxFilesToDownload.count > 0 && !_downloadInProgress) {
  156. [self _reallyDownloadFileToDocumentFolder:_listOfBoxFilesToDownload[0]];
  157. [_listOfBoxFilesToDownload removeObjectAtIndex:0];
  158. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  159. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  160. }
  161. }
  162. - (void)_reallyDownloadFileToDocumentFolder:(BoxFile *)file
  163. {
  164. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  165. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  166. [self loadFile:file intoPath:filePath];
  167. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  168. [self.delegate operationWithProgressInformationStarted];
  169. _downloadInProgress = YES;
  170. }
  171. - (BOOL)_supportedFileExtension:(NSString *)filename
  172. {
  173. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  174. return YES;
  175. return NO;
  176. }
  177. //just pick out Directories and supported formats.
  178. //if the resulting list contains less than 10 items try to get more
  179. - (void)_listOfGoodFilesAndFolders
  180. {
  181. NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
  182. _maxOffset = _fileList.totalCount.intValue;
  183. _offset += _fileList.numberOfEntries;
  184. NSUInteger numberOfEntries = _fileList.numberOfEntries;
  185. for (int i = 0; i < numberOfEntries; i++)
  186. {
  187. BoxModel *boxFile = [_fileList modelAtIndex:i];
  188. BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
  189. BOOL supportedFile = NO;
  190. if (!isDirectory) {
  191. BoxFile * file = (BoxFile *)boxFile;
  192. supportedFile = [self _supportedFileExtension:[NSString stringWithFormat:@".%@",file.name.lastPathComponent]];
  193. }
  194. if (isDirectory || supportedFile)
  195. [listOfGoodFilesAndFolders addObject:boxFile];
  196. }
  197. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  198. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  199. [self listFilesWithID:_folderId];
  200. return;
  201. }
  202. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  203. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  204. [self.delegate mediaListUpdated];
  205. }
  206. - (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
  207. {
  208. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
  209. _startDL = [NSDate timeIntervalSinceReferenceDate];
  210. BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
  211. {
  212. [self downloadSuccessful];
  213. };
  214. BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
  215. {
  216. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  217. [self downloadFailedWithError:error];
  218. };
  219. BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
  220. {
  221. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  222. [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
  223. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  224. }
  225. CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
  226. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  227. [self.delegate currentProgressInformation:progress];
  228. };
  229. [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
  230. }
  231. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  232. {
  233. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  234. CGFloat smoothingFactor = 0.005;
  235. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  236. CGFloat remainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  237. NSDate *date = [NSDate dateWithTimeIntervalSince1970:remainingInSeconds];
  238. NSDateFormatter *formatter = [NSDateFormatter new];
  239. [formatter setDateFormat:@"HH:mm:ss"];
  240. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  241. NSString *remainingTime = [formatter stringFromDate:date];
  242. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  243. [self.delegate updateRemainingTime:remainingTime];
  244. }
  245. - (void)downloadSuccessful
  246. {
  247. /* update library now that we got a file */
  248. APLog(@"BoxFile download was successful");
  249. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  250. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  251. [self.delegate operationWithProgressInformationStopped];
  252. _downloadInProgress = NO;
  253. [self _triggerNextDownload];
  254. }
  255. - (void)downloadFailedWithError:(NSError*)error
  256. {
  257. APLog(@"BoxFile download failed with error %li", (long)error.code);
  258. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  259. [self.delegate operationWithProgressInformationStopped];
  260. _downloadInProgress = NO;
  261. [self _triggerNextDownload];
  262. }
  263. #pragma mark - VLC internal communication and delegate
  264. - (NSArray *)currentListFiles
  265. {
  266. return _currentFileList;
  267. }
  268. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  269. {
  270. if (_listOfBoxFilesToDownload)
  271. return _listOfBoxFilesToDownload.count;
  272. return 0;
  273. }
  274. @end