VLCDropboxController.m 13 KB

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