VLCDropboxController.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*****************************************************************************
  2. * VLCDropboxController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Jean-Baptiste Kempf <jb # videolan.org>
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCDropboxController.h"
  14. #import "NSString+SupportedMedia.h"
  15. #import "VLCPlaybackController.h"
  16. #if TARGET_OS_TV
  17. #import "VLCPlayerDisplayController.h"
  18. #else
  19. #import "VLCActivityManager.h"
  20. #import "VLCMediaFileDiscoverer.h"
  21. #endif
  22. @interface VLCDropboxController ()
  23. {
  24. DBRestClient *_restClient;
  25. NSArray *_currentFileList;
  26. NSMutableArray *_listOfDropboxFilesToDownload;
  27. BOOL _downloadInProgress;
  28. NSInteger _outstandingNetworkRequests;
  29. CGFloat _averageSpeed;
  30. CGFloat _fileSize;
  31. NSTimeInterval _startDL;
  32. NSTimeInterval _lastStatsUpdate;
  33. }
  34. @end
  35. @implementation VLCDropboxController
  36. #pragma mark - session handling
  37. + (instancetype)sharedInstance
  38. {
  39. static VLCDropboxController *sharedInstance = nil;
  40. static dispatch_once_t pred;
  41. dispatch_once(&pred, ^{
  42. sharedInstance = [VLCDropboxController new];
  43. });
  44. return sharedInstance;
  45. }
  46. - (void)startSession
  47. {
  48. [[DBSession sharedSession] isLinked];
  49. }
  50. - (void)logout
  51. {
  52. [[DBSession sharedSession] unlinkAll];
  53. }
  54. - (BOOL)isAuthorized
  55. {
  56. return [[DBSession sharedSession] isLinked];
  57. }
  58. - (DBRestClient *)restClient {
  59. if (!_restClient) {
  60. _restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
  61. _restClient.delegate = self;
  62. }
  63. return _restClient;
  64. }
  65. #pragma mark - file management
  66. - (void)requestDirectoryListingAtPath:(NSString *)path
  67. {
  68. if (self.isAuthorized)
  69. [[self restClient] loadMetadata:path];
  70. }
  71. - (void)downloadFileToDocumentFolder:(DBMetadata *)file
  72. {
  73. if (!file.isDirectory) {
  74. if (!_listOfDropboxFilesToDownload)
  75. _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
  76. [_listOfDropboxFilesToDownload addObject:file];
  77. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  78. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  79. [self _triggerNextDownload];
  80. }
  81. }
  82. - (void)streamFile:(DBMetadata *)file
  83. {
  84. if (!file.isDirectory)
  85. [[self restClient] loadStreamableURLForFile:file.path];
  86. }
  87. - (void)_triggerNextDownload
  88. {
  89. if (_listOfDropboxFilesToDownload.count > 0 && !_downloadInProgress) {
  90. [self _reallyDownloadFileToDocumentFolder:_listOfDropboxFilesToDownload[0]];
  91. [_listOfDropboxFilesToDownload removeObjectAtIndex:0];
  92. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  93. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  94. }
  95. }
  96. - (void)_reallyDownloadFileToDocumentFolder:(DBMetadata *)file
  97. {
  98. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  99. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.filename];
  100. _startDL = [NSDate timeIntervalSinceReferenceDate];
  101. _fileSize = file.totalBytes;
  102. [[self restClient] loadFile:file.path intoPath:filePath];
  103. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  104. [self.delegate operationWithProgressInformationStarted];
  105. _downloadInProgress = YES;
  106. }
  107. #pragma mark - restClient delegate
  108. - (BOOL)_supportedFileExtension:(NSString *)filename
  109. {
  110. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  111. return YES;
  112. return NO;
  113. }
  114. - (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata {
  115. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  116. if (metadata.isDirectory) {
  117. NSArray *contents = metadata.contents;
  118. NSUInteger metaDataCount = metadata.contents.count;
  119. for (NSUInteger x = 0; x < metaDataCount; x++) {
  120. DBMetadata *file = contents[x];
  121. if ([file isDirectory] || [self _supportedFileExtension:file.filename])
  122. [listOfGoodFilesAndFolders addObject:file];
  123. }
  124. }
  125. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  126. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  127. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  128. [self.delegate mediaListUpdated];
  129. }
  130. - (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
  131. {
  132. APLog(@"DBMetadata download failed with error %li", (long)error.code);
  133. [self _handleError:error];
  134. }
  135. - (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
  136. {
  137. #if TARGET_OS_IOS
  138. /* update library now that we got a file */
  139. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  140. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  141. [self.delegate operationWithProgressInformationStopped];
  142. _downloadInProgress = NO;
  143. [self _triggerNextDownload];
  144. #endif
  145. }
  146. - (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
  147. {
  148. APLog(@"DBFile download failed with error %li", (long)error.code);
  149. [self _handleError:error];
  150. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  151. [self.delegate operationWithProgressInformationStopped];
  152. _downloadInProgress = NO;
  153. [self _triggerNextDownload];
  154. }
  155. - (void)restClient:(DBRestClient*)client loadProgress:(CGFloat)progress forFile:(NSString*)destPath
  156. {
  157. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  158. [self calculateRemainingTime:progress * _fileSize expectedDownloadSize:_fileSize];
  159. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  160. }
  161. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  162. [self.delegate currentProgressInformation:progress];
  163. }
  164. - (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
  165. {
  166. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  167. [vpc playURL:url successCallback:nil errorCallback:nil];
  168. }
  169. - (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
  170. {
  171. APLog(@"loadStreamableURL failed with error %li", (long)error.code);
  172. [self _handleError:error];
  173. }
  174. #pragma mark - DBSession delegate
  175. - (void)sessionDidReceiveAuthorizationFailure:(DBSession *)session userId:(NSString *)userId
  176. {
  177. APLog(@"DBSession received authorization failure with user ID %@", userId);
  178. }
  179. #pragma mark - DBNetworkRequest delegate
  180. - (void)networkRequestStarted
  181. {
  182. _outstandingNetworkRequests++;
  183. #if TARGET_OS_IOS
  184. if (_outstandingNetworkRequests == 1) {
  185. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  186. [activityManager networkActivityStarted];
  187. [activityManager disableIdleTimer];
  188. }
  189. #endif
  190. }
  191. - (void)networkRequestStopped
  192. {
  193. _outstandingNetworkRequests--;
  194. #if TARGET_OS_IOS
  195. if (_outstandingNetworkRequests == 0) {
  196. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  197. [activityManager networkActivityStopped];
  198. [activityManager activateIdleTimer];
  199. }
  200. #endif
  201. }
  202. #pragma mark - VLC internal communication and delegate
  203. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  204. {
  205. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  206. CGFloat smoothingFactor = 0.005;
  207. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  208. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  209. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  210. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  211. [formatter setDateFormat:@"HH:mm:ss"];
  212. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  213. NSString *remaingTime = [formatter stringFromDate:date];
  214. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  215. [self.delegate updateRemainingTime:remaingTime];
  216. }
  217. - (NSArray *)currentListFiles
  218. {
  219. return _currentFileList;
  220. }
  221. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  222. {
  223. if (_listOfDropboxFilesToDownload)
  224. return _listOfDropboxFilesToDownload.count;
  225. return 0;
  226. }
  227. #pragma mark - user feedback
  228. - (void)_handleError:(NSError *)error
  229. {
  230. #if TARGET_OS_IOS
  231. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  232. message:error.localizedDescription
  233. delegate:self
  234. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  235. otherButtonTitles:nil];
  236. [alert show];
  237. #else
  238. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  239. message:error.localizedDescription
  240. preferredStyle:UIAlertControllerStyleAlert];
  241. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  242. style:UIAlertActionStyleDestructive
  243. handler:^(UIAlertAction *action) {
  244. }];
  245. [alert addAction:defaultAction];
  246. [[[VLCPlayerDisplayController sharedInstance] childViewController] presentViewController:alert animated:YES completion:nil];
  247. #endif
  248. }
  249. @end