VLCDropboxController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. #if !TARGET_OS_TV
  18. #import "VLCMediaFileDiscoverer.h"
  19. #endif
  20. #import "DBKeychain.h"
  21. #import "VLCDropboxConstants.h"
  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. UINavigationController *_lastKnownNavigationController;
  34. }
  35. @end
  36. @implementation VLCDropboxController
  37. #pragma mark - session handling
  38. + (instancetype)sharedInstance
  39. {
  40. static VLCDropboxController *sharedInstance = nil;
  41. static dispatch_once_t pred;
  42. dispatch_once(&pred, ^{
  43. sharedInstance = [VLCDropboxController new];
  44. [sharedInstance shareCredentials];
  45. DBSession* dbSession = [[DBSession alloc] initWithAppKey:kVLCDropboxAppKey appSecret:kVLCDropboxPrivateKey root:kDBRootDropbox];
  46. [DBSession setSharedSession:dbSession];
  47. [DBRequest setNetworkRequestDelegate:sharedInstance];
  48. });
  49. return sharedInstance;
  50. }
  51. - (void)shareCredentials
  52. {
  53. /* share our credentials */
  54. NSDictionary *credentials = [DBKeychain credentials];
  55. if (credentials == nil)
  56. return;
  57. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  58. [ubiquitousStore setDictionary:credentials forKey:kVLCStoreDropboxCredentials];
  59. [ubiquitousStore synchronize];
  60. }
  61. - (BOOL)restoreFromSharedCredentials
  62. {
  63. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  64. [ubiquitousStore synchronize];
  65. NSDictionary *credentials = [ubiquitousStore dictionaryForKey:kVLCStoreDropboxCredentials];
  66. if (!credentials)
  67. return NO;
  68. [DBKeychain setCredentials:credentials];
  69. return YES;
  70. }
  71. - (void)startSession
  72. {
  73. [[DBSession sharedSession] isLinked];
  74. }
  75. - (void)logout
  76. {
  77. [[DBSession sharedSession] unlinkAll];
  78. }
  79. - (BOOL)isAuthorized
  80. {
  81. return [[DBSession sharedSession] isLinked];
  82. }
  83. - (DBRestClient *)restClient {
  84. if (!_restClient) {
  85. _restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
  86. _restClient.delegate = self;
  87. }
  88. return _restClient;
  89. }
  90. #pragma mark - file management
  91. - (void)requestDirectoryListingAtPath:(NSString *)path
  92. {
  93. if (self.isAuthorized)
  94. [[self restClient] loadMetadata:path];
  95. }
  96. - (void)downloadFileToDocumentFolder:(DBMetadata *)file
  97. {
  98. if (!file.isDirectory) {
  99. if (!_listOfDropboxFilesToDownload)
  100. _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
  101. [_listOfDropboxFilesToDownload addObject:file];
  102. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  103. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  104. [self _triggerNextDownload];
  105. }
  106. }
  107. - (void)streamFile:(DBMetadata *)file currentNavigationController:(UINavigationController *)navigationController
  108. {
  109. if (!file.isDirectory) {
  110. _lastKnownNavigationController = navigationController;
  111. [[self restClient] loadStreamableURLForFile:file.path];
  112. }
  113. }
  114. - (void)_triggerNextDownload
  115. {
  116. if (_listOfDropboxFilesToDownload.count > 0 && !_downloadInProgress) {
  117. [self _reallyDownloadFileToDocumentFolder:_listOfDropboxFilesToDownload[0]];
  118. [_listOfDropboxFilesToDownload removeObjectAtIndex:0];
  119. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  120. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  121. }
  122. }
  123. - (void)_reallyDownloadFileToDocumentFolder:(DBMetadata *)file
  124. {
  125. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  126. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.filename];
  127. _startDL = [NSDate timeIntervalSinceReferenceDate];
  128. _fileSize = file.totalBytes;
  129. [[self restClient] loadFile:file.path intoPath:filePath];
  130. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  131. [self.delegate operationWithProgressInformationStarted];
  132. _downloadInProgress = YES;
  133. }
  134. #pragma mark - restClient delegate
  135. - (BOOL)_supportedFileExtension:(NSString *)filename
  136. {
  137. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  138. return YES;
  139. return NO;
  140. }
  141. - (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata
  142. {
  143. _currentFileList = [NSArray arrayWithArray:metadata.contents];
  144. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  145. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  146. [self.delegate mediaListUpdated];
  147. }
  148. - (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
  149. {
  150. APLog(@"DBMetadata download failed with error %li", (long)error.code);
  151. [self _handleError:error];
  152. }
  153. - (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
  154. {
  155. #if TARGET_OS_IOS
  156. /* update library now that we got a file */
  157. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  158. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  159. [self.delegate operationWithProgressInformationStopped];
  160. _downloadInProgress = NO;
  161. [self _triggerNextDownload];
  162. #endif
  163. }
  164. - (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
  165. {
  166. APLog(@"DBFile download failed with error %li", (long)error.code);
  167. [self _handleError:error];
  168. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  169. [self.delegate operationWithProgressInformationStopped];
  170. _downloadInProgress = NO;
  171. [self _triggerNextDownload];
  172. }
  173. - (void)restClient:(DBRestClient*)client loadProgress:(CGFloat)progress forFile:(NSString*)destPath
  174. {
  175. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  176. [self calculateRemainingTime:progress * _fileSize expectedDownloadSize:_fileSize];
  177. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  178. }
  179. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  180. [self.delegate currentProgressInformation:progress];
  181. }
  182. - (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
  183. {
  184. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  185. [vpc playURL:url successCallback:nil errorCallback:nil];
  186. #if TARGET_OS_TV
  187. if (_lastKnownNavigationController) {
  188. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  189. [_lastKnownNavigationController presentViewController:movieVC
  190. animated:YES
  191. completion:nil];
  192. }
  193. #endif
  194. }
  195. - (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
  196. {
  197. APLog(@"loadStreamableURL failed with error %li", (long)error.code);
  198. [self _handleError:error];
  199. }
  200. #pragma mark - DBSession delegate
  201. - (void)sessionDidReceiveAuthorizationFailure:(DBSession *)session userId:(NSString *)userId
  202. {
  203. APLog(@"DBSession received authorization failure with user ID %@", userId);
  204. }
  205. #pragma mark - DBNetworkRequest delegate
  206. - (void)networkRequestStarted
  207. {
  208. _outstandingNetworkRequests++;
  209. if (_outstandingNetworkRequests == 1) {
  210. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  211. [activityManager networkActivityStarted];
  212. [activityManager disableIdleTimer];
  213. }
  214. }
  215. - (void)networkRequestStopped
  216. {
  217. _outstandingNetworkRequests--;
  218. if (_outstandingNetworkRequests == 0) {
  219. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  220. [activityManager networkActivityStopped];
  221. [activityManager activateIdleTimer];
  222. }
  223. }
  224. #pragma mark - VLC internal communication and delegate
  225. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  226. {
  227. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  228. CGFloat smoothingFactor = 0.005;
  229. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  230. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  231. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  232. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  233. [formatter setDateFormat:@"HH:mm:ss"];
  234. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  235. NSString *remaingTime = [formatter stringFromDate:date];
  236. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  237. [self.delegate updateRemainingTime:remaingTime];
  238. }
  239. - (NSArray *)currentListFiles
  240. {
  241. return _currentFileList;
  242. }
  243. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  244. {
  245. if (_listOfDropboxFilesToDownload)
  246. return _listOfDropboxFilesToDownload.count;
  247. return 0;
  248. }
  249. #pragma mark - user feedback
  250. - (void)_handleError:(NSError *)error
  251. {
  252. #if TARGET_OS_IOS
  253. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  254. message:error.localizedDescription
  255. delegate:self
  256. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  257. otherButtonTitles:nil];
  258. [alert show];
  259. #else
  260. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  261. message:error.localizedDescription
  262. preferredStyle:UIAlertControllerStyleAlert];
  263. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  264. style:UIAlertActionStyleDestructive
  265. handler:^(UIAlertAction *action) {
  266. }];
  267. [alert addAction:defaultAction];
  268. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  269. #endif
  270. }
  271. - (void)reset
  272. {
  273. [_restClient cancelAllRequests];
  274. _currentFileList = nil;
  275. }
  276. @end