VLCDropboxController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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-Swift.h"
  20. @interface VLCDropboxController ()
  21. @property (strong, nonatomic) DBUserClient *client;
  22. @property (strong, nonatomic) NSArray *currentFileList;
  23. @property (strong, nonatomic) NSMutableArray *listOfDropboxFilesToDownload;
  24. @property (assign, nonatomic) BOOL downloadInProgress;
  25. @property (assign, nonatomic) CGFloat averageSpeed;
  26. @property (assign, nonatomic) NSTimeInterval startDL;
  27. @property (assign, nonatomic) NSTimeInterval lastStatsUpdate;
  28. @property (strong, nonatomic) UINavigationController *lastKnownNavigationController;
  29. @end
  30. @implementation VLCDropboxController
  31. #pragma mark - session handling
  32. + (instancetype)sharedInstance
  33. {
  34. static VLCDropboxController *sharedInstance = nil;
  35. static dispatch_once_t pred;
  36. dispatch_once(&pred, ^{
  37. sharedInstance = [VLCDropboxController new];
  38. [sharedInstance shareCredentials];
  39. });
  40. return sharedInstance;
  41. }
  42. - (void)shareCredentials
  43. {
  44. /* share our credentials */
  45. NSArray *credentials = [DBSDKKeychain retrieveAllTokenIds];
  46. if (credentials == nil)
  47. return;
  48. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  49. [ubiquitousStore setArray:credentials forKey:kVLCStoreDropboxCredentials];
  50. [ubiquitousStore synchronize];
  51. }
  52. - (BOOL)restoreFromSharedCredentials
  53. {
  54. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  55. [ubiquitousStore synchronize];
  56. NSArray *credentials = [ubiquitousStore arrayForKey:kVLCStoreDropboxCredentials];
  57. if (!credentials) {
  58. return NO;
  59. }
  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. }
  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. }
  119. - (void)downloadFileToDocumentFolder:(DBFILESMetadata *)file
  120. {
  121. if (![file isKindOfClass:[DBFILESFolderMetadata class]]) {
  122. if (!self.listOfDropboxFilesToDownload) {
  123. self.listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
  124. }
  125. [self.listOfDropboxFilesToDownload addObject:file];
  126. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)]) {
  127. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  128. }
  129. [self _triggerNextDownload];
  130. }
  131. }
  132. - (void)_triggerNextDownload
  133. {
  134. if (self.listOfDropboxFilesToDownload.count > 0 && !self.downloadInProgress) {
  135. [self _reallyDownloadFileToDocumentFolder:self.listOfDropboxFilesToDownload[0]];
  136. [self.listOfDropboxFilesToDownload removeObjectAtIndex:0];
  137. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)]) {
  138. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  139. }
  140. }
  141. }
  142. - (void)_reallyDownloadFileToDocumentFolder:(DBFILESFileMetadata *)file
  143. {
  144. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  145. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  146. self.startDL = [NSDate timeIntervalSinceReferenceDate];
  147. [self downloadFileFrom:file.pathDisplay to:filePath];
  148. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)]) {
  149. [self.delegate operationWithProgressInformationStarted];
  150. }
  151. self.downloadInProgress = YES;
  152. }
  153. - (void)streamFile:(DBFILESMetadata *)file currentNavigationController:(UINavigationController *)navigationController
  154. {
  155. if (![file isKindOfClass:[DBFILESFolderMetadata class]]) {
  156. _lastKnownNavigationController = navigationController;
  157. [self loadStreamFrom:file.pathLower];
  158. }
  159. }
  160. # pragma mark - Dropbox API Request
  161. - (void)listFiles:(NSString *)path
  162. {
  163. // DropBox API prefers an empty path than a '/'
  164. if (!path || [path isEqualToString:@"/"]) {
  165. path = @"";
  166. }
  167. [[[self client].filesRoutes listFolder:path] setResponseBlock:^(DBFILESListFolderResult * _Nullable result, DBFILESListFolderError * _Nullable routeError, DBRequestError * _Nullable networkError) {
  168. if (result) {
  169. self.currentFileList = [result.entries sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  170. NSString *first = [(DBFILESMetadata*)a name];
  171. NSString *second = [(DBFILESMetadata*)b name];
  172. return [first caseInsensitiveCompare:second];
  173. }];
  174. APLog(@"found filtered metadata for %lu files", (unsigned long)self.currentFileList.count);
  175. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  176. [self.delegate mediaListUpdated];
  177. } else {
  178. APLog(@"listFiles failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  179. [self _handleError:[NSError errorWithDomain:networkError.description code:networkError.statusCode.integerValue userInfo:nil]];
  180. }
  181. }];
  182. }
  183. - (void)downloadFileFrom:(NSString *)path to:(NSString *)destination
  184. {
  185. if (![self _supportedFileExtension:[path lastPathComponent]]) {
  186. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) code:415 userInfo:nil]];
  187. return;
  188. }
  189. if (!destination) {
  190. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE", nil) code:415 userInfo:nil]];
  191. return;
  192. }
  193. // Need to replace all ' ' by '_' because it causes a `NSInvalidArgumentException ... destination path is nil` in the dropbox library.
  194. destination = [destination stringByReplacingOccurrencesOfString:@" " withString:@"_"];
  195. destination = [self _createPotentialNameFrom:destination];
  196. [[[self.client.filesRoutes downloadUrl:path overwrite:YES destination:[NSURL URLWithString:destination]]
  197. setResponseBlock:^(DBFILESFileMetadata * _Nullable result, DBFILESDownloadError * _Nullable routeError, DBRequestError * _Nullable networkError, NSURL * _Nonnull destination) {
  198. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)]) {
  199. [self.delegate operationWithProgressInformationStopped];
  200. }
  201. // FIXME: Replace notifications by cleaner observers
  202. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  203. object:self];
  204. self.downloadInProgress = NO;
  205. [self _triggerNextDownload];
  206. if (networkError) {
  207. APLog(@"downloadFile failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  208. [self _handleError:networkError.nsError];
  209. }
  210. }] setProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  211. if (totalBytesWritten == totalBytesExpectedToWrite) {
  212. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  213. }
  214. if ((self.lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self.lastStatsUpdate > .5)) || self.lastStatsUpdate <= 0) {
  215. [self calculateRemainingTime:(CGFloat)totalBytesWritten expectedDownloadSize:(CGFloat)totalBytesExpectedToWrite];
  216. self.lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  217. }
  218. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  219. [self.delegate currentProgressInformation:(CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite];
  220. }];
  221. }
  222. - (void)loadStreamFrom:(NSString *)path
  223. {
  224. if (!path || ![self _supportedFileExtension:[path lastPathComponent]]) {
  225. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) code:415 userInfo:nil]];
  226. return;
  227. }
  228. [[self.client.filesRoutes getTemporaryLink:path] setResponseBlock:^(DBFILESGetTemporaryLinkResult * _Nullable result, DBFILESGetTemporaryLinkError * _Nullable routeError, DBRequestError * _Nullable networkError) {
  229. if (result) {
  230. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:result.link]];
  231. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  232. [medialist addMedia:media];
  233. [[VLCPlaybackController sharedInstance] playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
  234. #if TARGET_OS_TV
  235. if (self.lastKnownNavigationController) {
  236. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  237. [self.lastKnownNavigationController presentViewController:movieVC
  238. animated:YES
  239. completion:nil];
  240. }
  241. #endif
  242. } else {
  243. APLog(@"loadStream failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  244. [self _handleError:[NSError errorWithDomain:networkError.description code:networkError.statusCode.integerValue userInfo:nil]];
  245. }
  246. }];
  247. }
  248. #pragma mark - VLC internal communication and delegate
  249. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  250. {
  251. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - self.startDL);
  252. CGFloat smoothingFactor = 0.005;
  253. self.averageSpeed = isnan(self.averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * self.averageSpeed;
  254. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/self.averageSpeed;
  255. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  256. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  257. [formatter setDateFormat:@"HH:mm:ss"];
  258. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  259. NSString *remaingTime = [formatter stringFromDate:date];
  260. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)]) {
  261. [self.delegate updateRemainingTime:remaingTime];
  262. }
  263. }
  264. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  265. {
  266. if (self.listOfDropboxFilesToDownload) {
  267. return self.listOfDropboxFilesToDownload.count;
  268. }
  269. return 0;
  270. }
  271. #pragma mark - user feedback
  272. - (void)_handleError:(NSError *)error
  273. {
  274. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  275. message:error.localizedDescription
  276. preferredStyle:UIAlertControllerStyleAlert];
  277. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil)
  278. style:UIAlertActionStyleDestructive
  279. handler:^(UIAlertAction *action) {
  280. }];
  281. [alert addAction:defaultAction];
  282. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  283. }
  284. - (void)reset
  285. {
  286. self.currentFileList = nil;
  287. }
  288. @end