VLCDropboxController.m 8.7 KB

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