VLCDropboxController.m 13 KB

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