VLCDropboxController.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  144. if (metadata.isDirectory) {
  145. NSArray *contents = metadata.contents;
  146. NSUInteger metaDataCount = metadata.contents.count;
  147. for (NSUInteger x = 0; x < metaDataCount; x++) {
  148. DBMetadata *file = contents[x];
  149. if ([file isDirectory] || [self _supportedFileExtension:file.filename])
  150. [listOfGoodFilesAndFolders addObject:file];
  151. }
  152. }
  153. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  154. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  155. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  156. [self.delegate mediaListUpdated];
  157. }
  158. - (void)restClient:(DBRestClient *)client loadMetadataFailedWithError:(NSError *)error
  159. {
  160. APLog(@"DBMetadata download failed with error %li", (long)error.code);
  161. [self _handleError:error];
  162. }
  163. - (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
  164. {
  165. #if TARGET_OS_IOS
  166. /* update library now that we got a file */
  167. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  168. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  169. [self.delegate operationWithProgressInformationStopped];
  170. _downloadInProgress = NO;
  171. [self _triggerNextDownload];
  172. #endif
  173. }
  174. - (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error
  175. {
  176. APLog(@"DBFile download failed with error %li", (long)error.code);
  177. [self _handleError:error];
  178. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  179. [self.delegate operationWithProgressInformationStopped];
  180. _downloadInProgress = NO;
  181. [self _triggerNextDownload];
  182. }
  183. - (void)restClient:(DBRestClient*)client loadProgress:(CGFloat)progress forFile:(NSString*)destPath
  184. {
  185. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  186. [self calculateRemainingTime:progress * _fileSize expectedDownloadSize:_fileSize];
  187. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  188. }
  189. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  190. [self.delegate currentProgressInformation:progress];
  191. }
  192. - (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path
  193. {
  194. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  195. [vpc playURL:url successCallback:nil errorCallback:nil];
  196. #if TARGET_OS_TV
  197. if (_lastKnownNavigationController) {
  198. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  199. [_lastKnownNavigationController presentViewController:movieVC
  200. animated:YES
  201. completion:nil];
  202. }
  203. #endif
  204. }
  205. - (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error
  206. {
  207. APLog(@"loadStreamableURL failed with error %li", (long)error.code);
  208. [self _handleError:error];
  209. }
  210. #pragma mark - DBSession delegate
  211. - (void)sessionDidReceiveAuthorizationFailure:(DBSession *)session userId:(NSString *)userId
  212. {
  213. APLog(@"DBSession received authorization failure with user ID %@", userId);
  214. }
  215. #pragma mark - DBNetworkRequest delegate
  216. - (void)networkRequestStarted
  217. {
  218. _outstandingNetworkRequests++;
  219. if (_outstandingNetworkRequests == 1) {
  220. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  221. [activityManager networkActivityStarted];
  222. [activityManager disableIdleTimer];
  223. }
  224. }
  225. - (void)networkRequestStopped
  226. {
  227. _outstandingNetworkRequests--;
  228. if (_outstandingNetworkRequests == 0) {
  229. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  230. [activityManager networkActivityStopped];
  231. [activityManager activateIdleTimer];
  232. }
  233. }
  234. #pragma mark - VLC internal communication and delegate
  235. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  236. {
  237. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  238. CGFloat smoothingFactor = 0.005;
  239. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  240. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  241. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  242. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  243. [formatter setDateFormat:@"HH:mm:ss"];
  244. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  245. NSString *remaingTime = [formatter stringFromDate:date];
  246. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  247. [self.delegate updateRemainingTime:remaingTime];
  248. }
  249. - (NSArray *)currentListFiles
  250. {
  251. return _currentFileList;
  252. }
  253. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  254. {
  255. if (_listOfDropboxFilesToDownload)
  256. return _listOfDropboxFilesToDownload.count;
  257. return 0;
  258. }
  259. #pragma mark - user feedback
  260. - (void)_handleError:(NSError *)error
  261. {
  262. #if TARGET_OS_IOS
  263. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  264. message:error.localizedDescription
  265. delegate:self
  266. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  267. otherButtonTitles:nil];
  268. [alert show];
  269. #else
  270. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  271. message:error.localizedDescription
  272. preferredStyle:UIAlertControllerStyleAlert];
  273. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  274. style:UIAlertActionStyleDestructive
  275. handler:^(UIAlertAction *action) {
  276. }];
  277. [alert addAction:defaultAction];
  278. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  279. #endif
  280. }
  281. - (void)reset
  282. {
  283. [_restClient cancelAllRequests];
  284. _currentFileList = nil;
  285. }
  286. @end