VLCBoxController.m 13 KB

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