VLCDropboxController.m 11 KB

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