VLCDropboxController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. - (BOOL)canPlayAll
  93. {
  94. return NO;
  95. }
  96. - (void)requestDirectoryListingAtPath:(NSString *)path
  97. {
  98. if (self.isAuthorized) {
  99. [self listFiles:path];
  100. }
  101. }
  102. - (void)downloadFileToDocumentFolder:(DBFILESMetadata *)file
  103. {
  104. if (![file isKindOfClass:[DBFILESFolderMetadata class]]) {
  105. if (!self.listOfDropboxFilesToDownload) {
  106. self.listOfDropboxFilesToDownload = [[NSMutableArray alloc] init];
  107. }
  108. [self.listOfDropboxFilesToDownload addObject:file];
  109. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)]) {
  110. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  111. }
  112. [self _triggerNextDownload];
  113. }
  114. }
  115. - (void)_triggerNextDownload
  116. {
  117. if (self.listOfDropboxFilesToDownload.count > 0 && !self.downloadInProgress) {
  118. [self _reallyDownloadFileToDocumentFolder:self.listOfDropboxFilesToDownload[0]];
  119. [self.listOfDropboxFilesToDownload removeObjectAtIndex:0];
  120. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)]) {
  121. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  122. }
  123. }
  124. }
  125. - (void)_reallyDownloadFileToDocumentFolder:(DBFILESFileMetadata *)file
  126. {
  127. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  128. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.name];
  129. self.startDL = [NSDate timeIntervalSinceReferenceDate];
  130. [self downloadFileFrom:file.pathDisplay to:filePath];
  131. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)]) {
  132. [self.delegate operationWithProgressInformationStarted];
  133. }
  134. self.downloadInProgress = YES;
  135. }
  136. - (void)streamFile:(DBFILESMetadata *)file currentNavigationController:(UINavigationController *)navigationController
  137. {
  138. if (![file isKindOfClass:[DBFILESFolderMetadata class]]) {
  139. _lastKnownNavigationController = navigationController;
  140. [self loadStreamFrom:file.pathLower];
  141. }
  142. }
  143. # pragma mark - Dropbox API Request
  144. - (void)listFiles:(NSString *)path
  145. {
  146. // DropBox API prefers an empty path than a '/'
  147. if (!path || [path isEqualToString:@"/"]) {
  148. path = @"";
  149. }
  150. [[[self client].filesRoutes listFolder:path] setResponseBlock:^(DBFILESListFolderResult * _Nullable result, DBFILESListFolderError * _Nullable routeError, DBRequestError * _Nullable networkError) {
  151. if (result) {
  152. self.currentFileList = [result.entries sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  153. NSString *first = [(DBFILESMetadata*)a name];
  154. NSString *second = [(DBFILESMetadata*)b name];
  155. return [first caseInsensitiveCompare:second];
  156. }];
  157. APLog(@"found filtered metadata for %lu files", (unsigned long)self.currentFileList.count);
  158. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  159. [self.delegate mediaListUpdated];
  160. } else {
  161. APLog(@"listFiles failed with network error %li and error tag %li", (long)networkError.statusCode, (long)networkError.tag);
  162. [self _handleError:[NSError errorWithDomain:networkError.description code:networkError.statusCode.integerValue userInfo:nil]];
  163. }
  164. }];
  165. }
  166. - (NSArray *)currentListFiles
  167. {
  168. return _currentFileList;
  169. }
  170. - (void)downloadFileFrom:(NSString *)path to:(NSString *)destination
  171. {
  172. if (![self _supportedFileExtension:[path lastPathComponent]]) {
  173. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) code:415 userInfo:nil]];
  174. return;
  175. }
  176. if (!destination) {
  177. [self _handleError:[NSError errorWithDomain:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE", nil) code:415 userInfo:nil]];
  178. return;
  179. }
  180. // Need to replace all ' ' by '_' because it causes a `NSInvalidArgumentException ... destination path is nil` in the dropbox library.
  181. destination = [destination stringByReplacingOccurrencesOfString:@" " withString:@"_"];
  182. destination = [self createPotentialPathFrom:destination];
  183. destination = [destination
  184. stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  185. URLPathAllowedCharacterSet]];
  186. [[[self.client.filesRoutes downloadUrl:path overwrite:YES destination:[NSURL URLWithString:destination]]
  187. setResponseBlock:^(DBFILESFileMetadata * _Nullable result, DBFILESDownloadError * _Nullable routeError, DBRequestError * _Nullable networkError, NSURL * _Nonnull destination) {
  188. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)]) {
  189. [self.delegate operationWithProgressInformationStopped];
  190. }
  191. #if TARGET_OS_IOS
  192. // FIXME: Replace notifications by cleaner observers
  193. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  194. object:self];
  195. #endif
  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. [[self.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 (self.lastKnownNavigationController) {
  228. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  229. [self.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] - self.startDL);
  244. CGFloat smoothingFactor = 0.005;
  245. self.averageSpeed = isnan(self.averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * self.averageSpeed;
  246. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/self.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. }
  256. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  257. {
  258. if (self.listOfDropboxFilesToDownload) {
  259. return self.listOfDropboxFilesToDownload.count;
  260. }
  261. return 0;
  262. }
  263. #pragma mark - user feedback
  264. - (void)_handleError:(NSError *)error
  265. {
  266. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), error.code]
  267. message:error.localizedDescription
  268. preferredStyle:UIAlertControllerStyleAlert];
  269. UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_OK", nil)
  270. style:UIAlertActionStyleDestructive
  271. handler:^(UIAlertAction *action) {
  272. }];
  273. [alert addAction:defaultAction];
  274. [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
  275. }
  276. - (void)reset
  277. {
  278. self.currentFileList = nil;
  279. }
  280. @end