VLCBoxController.m 12 KB

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