VLCDropboxController.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. - (BOOL)canPlayAll
  92. {
  93. return NO;
  94. }
  95. - (void)requestDirectoryListingAtPath:(NSString *)path
  96. {
  97. if (self.isAuthorized)
  98. [[self restClient] loadMetadata:path];
  99. }
  100. - (void)downloadFileToDocumentFolder:(DBMetadata *)file
  101. {
  102. if (!file.isDirectory) {
  103. if (!_listOfDropboxFilesToDownload)
  104. _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
  105. [_listOfDropboxFilesToDownload addObject:file];
  106. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  107. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  108. [self _triggerNextDownload];
  109. }
  110. }
  111. - (void)streamFile:(DBMetadata *)file currentNavigationController:(UINavigationController *)navigationController
  112. {
  113. if (!file.isDirectory) {
  114. _lastKnownNavigationController = navigationController;
  115. [[self restClient] loadStreamableURLForFile:file.path];
  116. }
  117. }
  118. - (void)_triggerNextDownload
  119. {
  120. if (_listOfDropboxFilesToDownload.count > 0 && !_downloadInProgress) {
  121. [self _reallyDownloadFileToDocumentFolder:_listOfDropboxFilesToDownload[0]];
  122. [_listOfDropboxFilesToDownload removeObjectAtIndex:0];
  123. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  124. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  125. }
  126. }
  127. - (void)_reallyDownloadFileToDocumentFolder:(DBMetadata *)file
  128. {
  129. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  130. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.filename];
  131. _startDL = [NSDate timeIntervalSinceReferenceDate];
  132. _fileSize = file.totalBytes;
  133. [[self restClient] loadFile:file.path intoPath:filePath];
  134. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  135. [self.delegate operationWithProgressInformationStarted];
  136. _downloadInProgress = YES;
  137. }
  138. #pragma mark - restClient delegate
  139. - (BOOL)_supportedFileExtension:(NSString *)filename
  140. {
  141. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  142. return YES;
  143. return NO;
  144. }
  145. - (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata
  146. {
  147. _currentFileList = [NSArray arrayWithArray:metadata.contents];
  148. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  149. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  150. [self.delegate mediaListUpdated];
  151. }
  152. - (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
  153. {
  154. APLog(@"DBMetadata download failed with error %li", (long)error.code);
  155. [self _handleError:error];
  156. }
  157. - (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
  158. {
  159. #if TARGET_OS_IOS
  160. /* update library now that we got a file */
  161. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  162. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  163. [self.delegate operationWithProgressInformationStopped];
  164. _downloadInProgress = NO;
  165. [self _triggerNextDownload];
  166. #endif
  167. }
  168. - (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
  169. {
  170. APLog(@"DBFile download failed with error %li", (long)error.code);
  171. [self _handleError:error];
  172. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  173. [self.delegate operationWithProgressInformationStopped];
  174. _downloadInProgress = NO;
  175. [self _triggerNextDownload];
  176. }
  177. - (void)restClient:(DBRestClient*)client loadProgress:(CGFloat)progress forFile:(NSString*)destPath
  178. {
  179. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  180. [self calculateRemainingTime:progress * _fileSize expectedDownloadSize:_fileSize];
  181. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  182. }
  183. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  184. [self.delegate currentProgressInformation:progress];
  185. }
  186. - (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
  187. {
  188. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  189. [vpc playURL:url successCallback:nil errorCallback:nil];
  190. #if TARGET_OS_TV
  191. if (_lastKnownNavigationController) {
  192. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  193. [_lastKnownNavigationController presentViewController:movieVC
  194. animated:YES
  195. completion:nil];
  196. }
  197. #endif
  198. }
  199. - (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
  200. {
  201. APLog(@"loadStreamableURL failed with error %li", (long)error.code);
  202. [self _handleError:error];
  203. }
  204. #pragma mark - DBSession delegate
  205. - (void)sessionDidReceiveAuthorizationFailure:(DBSession *)session userId:(NSString *)userId
  206. {
  207. APLog(@"DBSession received authorization failure with user ID %@", userId);
  208. }
  209. #pragma mark - DBNetworkRequest delegate
  210. - (void)networkRequestStarted
  211. {
  212. _outstandingNetworkRequests++;
  213. if (_outstandingNetworkRequests == 1) {
  214. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  215. [activityManager networkActivityStarted];
  216. [activityManager disableIdleTimer];
  217. }
  218. }
  219. - (void)networkRequestStopped
  220. {
  221. _outstandingNetworkRequests--;
  222. if (_outstandingNetworkRequests == 0) {
  223. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  224. [activityManager networkActivityStopped];
  225. [activityManager activateIdleTimer];
  226. }
  227. }
  228. #pragma mark - VLC internal communication and delegate
  229. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  230. {
  231. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  232. CGFloat smoothingFactor = 0.005;
  233. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  234. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  235. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  236. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  237. [formatter setDateFormat:@"HH:mm:ss"];
  238. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  239. NSString *remaingTime = [formatter stringFromDate:date];
  240. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  241. [self.delegate updateRemainingTime:remaingTime];
  242. }
  243. - (NSArray *)currentListFiles
  244. {
  245. return _currentFileList;
  246. }
  247. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  248. {
  249. if (_listOfDropboxFilesToDownload)
  250. return _listOfDropboxFilesToDownload.count;
  251. return 0;
  252. }
  253. #pragma mark - user feedback
  254. - (void)_handleError:(NSError *)error
  255. {
  256. #if TARGET_OS_IOS
  257. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  258. message:error.localizedDescription
  259. delegate:self
  260. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  261. otherButtonTitles:nil];
  262. [alert show];
  263. #else
  264. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  265. message:error.localizedDescription
  266. preferredStyle:UIAlertControllerStyleAlert];
  267. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  268. style:UIAlertActionStyleDestructive
  269. handler:^(UIAlertAction *action) {
  270. }];
  271. [alert addAction:defaultAction];
  272. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  273. #endif
  274. }
  275. - (void)reset
  276. {
  277. [_restClient cancelAllRequests];
  278. _currentFileList = nil;
  279. }
  280. @end