VLCDropboxController.m 13 KB

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