VLCDropboxController.m 14 KB

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