VLCBoxController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. NSLog(@"%s", __PRETTY_FUNCTION__);
  90. [[NSNotificationCenter defaultCenter] postNotificationName:VLCBoxControllerSessionUpdated object:nil];
  91. }
  92. - (BOOL)isAuthorized
  93. {
  94. return [[BoxSDK sharedSDK].OAuth2Session isAuthorized];
  95. }
  96. #pragma mark - file management
  97. - (void)requestDirectoryListingAtPath:(NSString *)path
  98. {
  99. //we entered a different folder so discard all current files
  100. if (![path isEqualToString:_folderId])
  101. _currentFileList = nil;
  102. [self listFilesWithID:path];
  103. }
  104. - (BOOL)hasMoreFiles
  105. {
  106. return _offset < _maxOffset;
  107. }
  108. - (void)listFilesWithID:(NSString *)folderId
  109. {
  110. _fileList = nil;
  111. _folderId = folderId;
  112. if (_folderId == nil || [_folderId isEqualToString:@""]) {
  113. _folderId = BoxAPIFolderIDRoot;
  114. }
  115. BoxCollectionBlock success = ^(BoxCollection *collection)
  116. {
  117. _fileList = collection;
  118. [self _listOfGoodFilesAndFolders];
  119. };
  120. BoxAPIJSONFailureBlock failure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
  121. {
  122. 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");
  123. };
  124. [_operation cancel];
  125. _operation = [[BoxSDK sharedSDK].foldersManager folderItemsWithID:_folderId requestBuilder:nil success:success failure:failure];
  126. }
  127. #if TARGET_OS_IOS
  128. - (void)downloadFileToDocumentFolder:(BoxItem *)file
  129. {
  130. if (file != nil) {
  131. if ([file.type isEqualToString:BoxAPIItemTypeFolder]) return;
  132. if (!_listOfBoxFilesToDownload)
  133. _listOfBoxFilesToDownload = [NSMutableArray new];
  134. [_listOfBoxFilesToDownload addObject:file];
  135. }
  136. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  137. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  138. [self _triggerNextDownload];
  139. }
  140. - (void)_triggerNextDownload
  141. {
  142. if (_listOfBoxFilesToDownload.count > 0 && !_downloadInProgress) {
  143. [self _reallyDownloadFileToDocumentFolder:_listOfBoxFilesToDownload[0]];
  144. [_listOfBoxFilesToDownload removeObjectAtIndex:0];
  145. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  146. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  147. }
  148. }
  149. - (void)_reallyDownloadFileToDocumentFolder:(BoxFile *)file
  150. {
  151. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  152. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  153. [self loadFile:file intoPath:filePath];
  154. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  155. [self.delegate operationWithProgressInformationStarted];
  156. _downloadInProgress = YES;
  157. }
  158. #endif
  159. - (BOOL)_supportedFileExtension:(NSString *)filename
  160. {
  161. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  162. return YES;
  163. return NO;
  164. }
  165. //just pick out Directories and supported formats.
  166. //if the resulting list contains less than 10 items try to get more
  167. - (void)_listOfGoodFilesAndFolders
  168. {
  169. NSMutableArray *listOfGoodFilesAndFolders = [NSMutableArray new];
  170. _maxOffset = _fileList.totalCount.intValue;
  171. _offset += _fileList.numberOfEntries;
  172. NSUInteger numberOfEntries = _fileList.numberOfEntries;
  173. for (int i = 0; i < numberOfEntries; i++)
  174. {
  175. BoxModel *boxFile = [_fileList modelAtIndex:i];
  176. BOOL isDirectory = [boxFile.type isEqualToString:BoxAPIItemTypeFolder];
  177. BOOL supportedFile = NO;
  178. if (!isDirectory) {
  179. BoxFile * file = (BoxFile *)boxFile;
  180. supportedFile = [self _supportedFileExtension:[NSString stringWithFormat:@".%@",file.name.lastPathComponent]];
  181. }
  182. if (isDirectory || supportedFile)
  183. [listOfGoodFilesAndFolders addObject:boxFile];
  184. }
  185. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  186. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  187. [self listFilesWithID:_folderId];
  188. return;
  189. }
  190. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  191. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  192. [self.delegate mediaListUpdated];
  193. }
  194. #if TARGET_OS_IOS
  195. - (void)loadFile:(BoxFile *)file intoPath:(NSString*)destinationPath
  196. {
  197. NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
  198. _startDL = [NSDate timeIntervalSinceReferenceDate];
  199. BoxDownloadSuccessBlock successBlock = ^(NSString *downloadedFileID, long long expectedContentLength)
  200. {
  201. [self downloadSuccessful];
  202. };
  203. BoxDownloadFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error)
  204. {
  205. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  206. [self downloadFailedWithError:error];
  207. };
  208. BoxAPIDataProgressBlock progressBlock = ^(long long expectedTotalBytes, unsigned long long bytesReceived)
  209. {
  210. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  211. [self calculateRemainingTime:(CGFloat)bytesReceived expectedDownloadSize:(CGFloat)expectedTotalBytes];
  212. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  213. }
  214. CGFloat progress = (CGFloat)bytesReceived / (CGFloat)expectedTotalBytes;
  215. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  216. [self.delegate currentProgressInformation:progress];
  217. };
  218. [[BoxSDK sharedSDK].filesManager downloadFileWithID:file.modelID outputStream:outputStream requestBuilder:nil success:successBlock failure:failureBlock progress:progressBlock];
  219. }
  220. - (void)showAlert:(NSString *)title message:(NSString *)message
  221. {
  222. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:title
  223. message:message
  224. delegate:nil
  225. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  226. otherButtonTitles:nil];
  227. [alert show];
  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. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  248. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  249. [self.delegate operationWithProgressInformationStopped];
  250. _downloadInProgress = NO;
  251. [self _triggerNextDownload];
  252. }
  253. - (void)downloadFailedWithError:(NSError*)error
  254. {
  255. APLog(@"BoxFile download failed with error %li", (long)error.code);
  256. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  257. [self.delegate operationWithProgressInformationStopped];
  258. _downloadInProgress = NO;
  259. [self _triggerNextDownload];
  260. }
  261. #endif
  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