VLCDropboxController.m 9.2 KB

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