VLCDropboxController.m 9.2 KB

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