VLCDropboxController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. #import "VLCMediaFileDiscoverer.h"
  18. #import "VLCDropboxConstants.h"
  19. #import "VLC_iOS-Swift.h"
  20. @interface VLCDropboxController ()
  21. {
  22. DBUserClient *_client;
  23. NSArray *_currentFileList;
  24. NSMutableArray *_listOfDropboxFilesToDownload;
  25. BOOL _downloadInProgress;
  26. CGFloat _averageSpeed;
  27. NSTimeInterval _startDL;
  28. NSTimeInterval _lastStatsUpdate;
  29. UINavigationController *_lastKnownNavigationController;
  30. }
  31. @end
  32. @implementation VLCDropboxController
  33. #pragma mark - session handling
  34. + (instancetype)sharedInstance
  35. {
  36. static VLCDropboxController *sharedInstance = nil;
  37. static dispatch_once_t pred;
  38. dispatch_once(&pred, ^{
  39. sharedInstance = [VLCDropboxController new];
  40. [sharedInstance shareCredentials];
  41. });
  42. return sharedInstance;
  43. }
  44. - (void)shareCredentials
  45. {
  46. /* share our credentials */
  47. NSArray *credentials = [DBSDKKeychain retrieveAllTokenIds];
  48. if (credentials == nil)
  49. return;
  50. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  51. [ubiquitousStore setArray:credentials forKey:kVLCStoreDropboxCredentials];
  52. [ubiquitousStore synchronize];
  53. }
  54. - (BOOL)restoreFromSharedCredentials
  55. {
  56. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  57. [ubiquitousStore synchronize];
  58. NSArray *credentials = [ubiquitousStore arrayForKey:kVLCStoreDropboxCredentials];
  59. if (!credentials)
  60. return NO;
  61. for (NSString *tmp in credentials) {
  62. [DBSDKKeychain storeValueWithKey:kVLCStoreDropboxCredentials value:tmp];
  63. }
  64. return YES;
  65. }
  66. - (void)startSession
  67. {
  68. [DBClientsManager authorizedClient];
  69. }
  70. - (void)logout
  71. {
  72. [DBClientsManager unlinkAndResetClients];
  73. }
  74. - (BOOL)isAuthorized
  75. {
  76. return [DBClientsManager authorizedClient];
  77. }
  78. - (DBUserClient *)client {
  79. if (!_client) {
  80. _client = [DBClientsManager authorizedClient];
  81. }
  82. return _client;
  83. }
  84. #pragma mark - file management
  85. - (BOOL)_supportedFileExtension:(NSString *)filename
  86. {
  87. return [filename isSupportedMediaFormat]
  88. || [filename isSupportedAudioMediaFormat]
  89. || [filename isSupportedSubtitleFormat];
  90. }
  91. - (NSString *)_createPotentialNameFrom:(NSString *)path
  92. {
  93. NSFileManager *fileManager = [NSFileManager defaultManager];
  94. NSString *fileName = [path lastPathComponent];
  95. NSString *finalFilePath = [path stringByDeletingLastPathComponent];
  96. if ([fileManager fileExistsAtPath:path]) {
  97. NSString *potentialFilename;
  98. NSString *fileExtension = [fileName pathExtension];
  99. NSString *rawFileName = [fileName stringByDeletingPathExtension];
  100. for (NSUInteger x = 1; x < 100; x++) {
  101. potentialFilename = [NSString stringWithFormat:@"%@_%lu.%@", rawFileName, (unsigned long)x, fileExtension];
  102. if (![fileManager fileExistsAtPath:[finalFilePath stringByAppendingPathComponent:potentialFilename]])
  103. break;
  104. }
  105. return [finalFilePath stringByAppendingPathComponent:potentialFilename];
  106. }
  107. return path;
  108. }
  109. - (BOOL)canPlayAll
  110. {
  111. return NO;
  112. }
  113. - (void)requestDirectoryListingAtPath:(NSString *)path
  114. {
  115. if (self.isAuthorized)
  116. [self listFiles:path];
  117. }
  118. - (void)downloadFileToDocumentFolder:(DBFILESMetadata *)file
  119. {
  120. if (![file isKindOfClass:[DBFILESFolderMetadata class]]) {
  121. if (!_listOfDropboxFilesToDownload)
  122. _listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
  123. [_listOfDropboxFilesToDownload addObject:file];
  124. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  125. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  126. [self _triggerNextDownload];
  127. }
  128. }
  129. - (void)_triggerNextDownload
  130. {
  131. if (_listOfDropboxFilesToDownload.count > 0 && !_downloadInProgress) {
  132. [self _reallyDownloadFileToDocumentFolder:_listOfDropboxFilesToDownload[0]];
  133. [_listOfDropboxFilesToDownload removeObjectAtIndex:0];
  134. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  135. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  136. }
  137. }
  138. - (void)_reallyDownloadFileToDocumentFolder:(DBFILESFileMetadata *)file
  139. {
  140. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  141. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  142. _startDL = [NSDate timeIntervalSinceReferenceDate];
  143. [self downloadFileFrom:file.pathDisplay to:filePath];
  144. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  145. [self.delegate operationWithProgressInformationStarted];
  146. _downloadInProgress = YES;
  147. }
  148. - (void)streamFile:(DBFILESMetadata *)file currentNavigationController:(UINavigationController *)navigationController
  149. {
  150. if (![file isKindOfClass:[DBFILESFolderMetadata class]]) {
  151. _lastKnownNavigationController = navigationController;
  152. [self loadStreamFrom:file.pathLower];
  153. }
  154. }
  155. # pragma mark - Dropbox API Request
  156. - (void)listFiles:(NSString *)path
  157. {
  158. // DropBox API prefers an empty path than a '/'
  159. if (!path || [path isEqualToString:@"/"]) {
  160. path = @"";
  161. }
  162. [[[self client].filesRoutes listFolder:path] setResponseBlock:^(DBFILESListFolderResult * _Nullable result, DBFILESListFolderError * _Nullable routeError, DBRequestError * _Nullable networkError) {
  163. if (result) {
  164. self->_currentFileList = [result.entries sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  165. NSString *first = [(DBFILESMetadata*)a name];
  166. NSString *second = [(DBFILESMetadata*)b name];
  167. return [first caseInsensitiveCompare:second];
  168. }];
  169. APLog(@"found filtered metadata for %lu files", (unsigned long)self->_currentFileList.count);
  170. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  171. [self.delegate mediaListUpdated];
  172. } else {
  173. APLog(@"listFiles failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  174. [self _handleError:[NSError errorWithDomain:networkError.description code:networkError.statusCode.integerValue userInfo:nil]];
  175. }
  176. }];
  177. }
  178. - (void)downloadFileFrom:(NSString *)path to:(NSString *)destination
  179. {
  180. if (![self _supportedFileExtension:[path lastPathComponent]]) {
  181. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) code:415 userInfo:nil]];
  182. return;
  183. }
  184. if (!destination) {
  185. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE", nil) code:415 userInfo:nil]];
  186. return;
  187. }
  188. // Need to replace all ' ' by '_' because it causes a `NSInvalidArgumentException ... destination path is nil` in the dropbox library.
  189. destination = [destination stringByReplacingOccurrencesOfString:@" " withString:@"_"];
  190. destination = [self _createPotentialNameFrom:destination];
  191. [[[_client.filesRoutes downloadUrl:path overwrite:YES destination:[NSURL URLWithString:destination]]
  192. setResponseBlock:^(DBFILESFileMetadata * _Nullable result, DBFILESDownloadError * _Nullable routeError, DBRequestError * _Nullable networkError, NSURL * _Nonnull destination) {
  193. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)]) {
  194. [self.delegate operationWithProgressInformationStopped];
  195. }
  196. self->_downloadInProgress = NO;
  197. [self _triggerNextDownload];
  198. if (networkError) {
  199. APLog(@"downloadFile failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  200. [self _handleError:networkError.nsError];
  201. }
  202. }] setProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  203. if (totalBytesWritten == totalBytesExpectedToWrite) {
  204. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  205. }
  206. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  207. [self calculateRemainingTime:(CGFloat)totalBytesWritten expectedDownloadSize:(CGFloat)totalBytesExpectedToWrite];
  208. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  209. }
  210. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  211. [self.delegate currentProgressInformation:(CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite];
  212. }];
  213. }
  214. - (void)loadStreamFrom:(NSString *)path
  215. {
  216. if (!path || ![self _supportedFileExtension:[path lastPathComponent]]) {
  217. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) code:415 userInfo:nil]];
  218. return;
  219. }
  220. [[_client.filesRoutes getTemporaryLink:path] setResponseBlock:^(DBFILESGetTemporaryLinkResult * _Nullable result, DBFILESGetTemporaryLinkError * _Nullable routeError, DBRequestError * _Nullable networkError) {
  221. if (result) {
  222. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:result.link]];
  223. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  224. [medialist addMedia:media];
  225. [[VLCPlaybackController sharedInstance] playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
  226. #if TARGET_OS_TV
  227. if (_lastKnownNavigationController) {
  228. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  229. [_lastKnownNavigationController presentViewController:movieVC
  230. animated:YES
  231. completion:nil];
  232. }
  233. #endif
  234. } else {
  235. APLog(@"loadStream failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  236. [self _handleError:[NSError errorWithDomain:networkError.description code:networkError.statusCode.integerValue userInfo:nil]];
  237. }
  238. }];
  239. }
  240. #pragma mark - VLC internal communication and delegate
  241. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  242. {
  243. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  244. CGFloat smoothingFactor = 0.005;
  245. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  246. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
  247. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  248. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  249. [formatter setDateFormat:@"HH:mm:ss"];
  250. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  251. NSString *remaingTime = [formatter stringFromDate:date];
  252. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  253. [self.delegate updateRemainingTime:remaingTime];
  254. }
  255. - (NSArray *)currentListFiles
  256. {
  257. return _currentFileList;
  258. }
  259. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  260. {
  261. if (_listOfDropboxFilesToDownload)
  262. return _listOfDropboxFilesToDownload.count;
  263. return 0;
  264. }
  265. #pragma mark - user feedback
  266. - (void)_handleError:(NSError *)error
  267. {
  268. #if TARGET_OS_IOS
  269. [VLCAlertViewController alertViewManagerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  270. errorMessage:error.localizedDescription
  271. viewController:[UIApplication sharedApplication].keyWindow.rootViewController
  272. buttonsAction:@[[[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_CANCEL", nil)
  273. action: ^(UIAlertAction* action){}]
  274. ]];
  275. #else
  276. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  277. message:error.localizedDescription
  278. preferredStyle:UIAlertControllerStyleAlert];
  279. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  280. style:UIAlertActionStyleDestructive
  281. handler:^(UIAlertAction *action) {
  282. }];
  283. [alert addAction:defaultAction];
  284. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  285. #endif
  286. }
  287. - (void)reset
  288. {
  289. _currentFileList = nil;
  290. }
  291. @end