VLCDropboxController.m 9.2 KB

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