VLCGoogleDriveController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /*****************************************************************************
  2. * VLCGoogleDriveController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <nitz.carola # googlemail.com>
  9. * Felix Paul Kühne <fkuehne # videolan.org>
  10. * Soomin Lee <TheHungryBu # gmail.com>
  11. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCGoogleDriveController.h"
  15. #import "NSString+SupportedMedia.h"
  16. #import "VLCPlaybackController.h"
  17. #import "VLCMediaFileDiscoverer.h"
  18. #import "VLC-Swift.h"
  19. #import <XKKeychain/XKKeychain.h>
  20. #import <GTMAppAuth/GTMAppAuth.h>
  21. #import <GTMSessionFetcher/GTMSessionFetcherService.h>
  22. @interface VLCGoogleDriveController ()
  23. {
  24. GTLRDrive_FileList *_fileList;
  25. GTLRServiceTicket *_fileListTicket;
  26. NSArray *_currentFileList;
  27. NSMutableArray *_listOfGoogleDriveFilesToDownload;
  28. BOOL _downloadInProgress;
  29. NSString *_nextPageToken;
  30. NSString *_folderId;
  31. CGFloat _averageSpeed;
  32. NSTimeInterval _startDL;
  33. NSTimeInterval _lastStatsUpdate;
  34. }
  35. @end
  36. @implementation VLCGoogleDriveController
  37. #pragma mark - session handling
  38. + (instancetype)sharedInstance
  39. {
  40. static VLCGoogleDriveController *sharedInstance = nil;
  41. static dispatch_once_t pred;
  42. dispatch_once(&pred, ^{
  43. sharedInstance = [VLCGoogleDriveController new];
  44. });
  45. return sharedInstance;
  46. }
  47. - (void)startSession
  48. {
  49. [self restoreFromSharedCredentials];
  50. self.driveService = [GTLRDriveService new];
  51. self.driveService.authorizer = [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kKeychainItemName];
  52. }
  53. - (void)stopSession
  54. {
  55. [_fileListTicket cancelTicket];
  56. _nextPageToken = nil;
  57. _currentFileList = nil;
  58. }
  59. - (void)logout
  60. {
  61. self.driveService.authorizer = nil;
  62. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  63. [ubiquitousStore setString:nil forKey:kVLCStoreGDriveCredentials];
  64. [ubiquitousStore synchronize];
  65. [self stopSession];
  66. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  67. [self.delegate mediaListUpdated];
  68. }
  69. - (BOOL)isAuthorized
  70. {
  71. if (!self.driveService) {
  72. [self startSession];
  73. }
  74. BOOL ret = [(GTMAppAuthFetcherAuthorization *)self.driveService.authorizer canAuthorize];
  75. if (ret) {
  76. [self shareCredentials];
  77. }
  78. return ret;
  79. }
  80. - (void)shareCredentials
  81. {
  82. /* share our credentials */
  83. XKKeychainGenericPasswordItem *item = [XKKeychainGenericPasswordItem itemForService:kKeychainItemName account:@"OAuth" error:nil]; // kGTMOAuth2AccountName
  84. NSString *credentials = item.secret.stringValue;
  85. if (credentials == nil)
  86. return;
  87. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  88. [ubiquitousStore setString:credentials forKey:kVLCStoreGDriveCredentials];
  89. [ubiquitousStore synchronize];
  90. }
  91. - (BOOL)restoreFromSharedCredentials
  92. {
  93. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  94. [ubiquitousStore synchronize];
  95. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreGDriveCredentials];
  96. if (!credentials)
  97. return NO;
  98. XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
  99. keychainItem.service = kKeychainItemName;
  100. keychainItem.account = @"OAuth"; // kGTMOAuth2AccountName
  101. keychainItem.secret.stringValue = credentials;
  102. [keychainItem saveWithError:nil];
  103. return YES;
  104. }
  105. - (void)showAlert:(NSString *)title message:(NSString *)message
  106. {
  107. [VLCAlertViewController alertViewManagerWithTitle:title
  108. errorMessage:message
  109. viewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  110. }
  111. #pragma mark - file management
  112. - (BOOL)canPlayAll
  113. {
  114. return NO;
  115. }
  116. - (void)requestDirectoryListingAtPath:(NSString *)path
  117. {
  118. if (self.isAuthorized) {
  119. //we entered a different folder so discard all current files
  120. if (![path isEqualToString:_folderId])
  121. _currentFileList = nil;
  122. [self listFilesWithID:path];
  123. }
  124. }
  125. - (BOOL)hasMoreFiles
  126. {
  127. return _nextPageToken != nil;
  128. }
  129. - (void)downloadFileToDocumentFolder:(GTLRDrive_File *)file
  130. {
  131. if (file == nil)
  132. return;
  133. if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) return;
  134. if (!_listOfGoogleDriveFilesToDownload)
  135. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  136. [_listOfGoogleDriveFilesToDownload addObject:file];
  137. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  138. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  139. [self _triggerNextDownload];
  140. }
  141. - (void)listFilesWithID:(NSString *)folderId
  142. {
  143. _fileList = nil;
  144. _folderId = folderId;
  145. GTLRDriveQuery_FilesList *query;
  146. NSString *parentName = @"root";
  147. query = [GTLRDriveQuery_FilesList query];
  148. query.pageToken = _nextPageToken;
  149. //the results don't come in alphabetical order when paging. So the maxresult (default 100) is set to 1000 in order to get a few more files at once.
  150. //query.pageSize = 1000;
  151. query.fields = @"files(*)";
  152. if (![_folderId isEqualToString:@""]) {
  153. parentName = [_folderId lastPathComponent];
  154. }
  155. query.q = [NSString stringWithFormat:@"'%@' in parents", parentName];
  156. _fileListTicket = [self.driveService executeQuery:query
  157. completionHandler:^(GTLRServiceTicket *ticket,
  158. GTLRDrive_FileList *fileList,
  159. NSError *error) {
  160. if (error == nil) {
  161. self->_fileList = fileList;
  162. self->_nextPageToken = fileList.nextPageToken;
  163. self->_fileListTicket = nil;
  164. [self _listOfGoodFilesAndFolders];
  165. } else {
  166. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  167. }
  168. }];
  169. }
  170. - (void)streamFile:(GTLRDrive_File *)file
  171. {
  172. NSString *token = [((GTMAppAuthFetcherAuthorization *)self.driveService.authorizer).authState.lastTokenResponse accessToken];
  173. NSString *urlString = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media&access_token=%@",
  174. file.identifier, token];
  175. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  176. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:urlString]];
  177. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  178. [medialist addMedia:media];
  179. [vpc playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
  180. }
  181. - (void)_triggerNextDownload
  182. {
  183. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  184. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  185. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  186. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  187. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  188. }
  189. }
  190. - (void)_reallyDownloadFileToDocumentFolder:(GTLRDrive_File *)file
  191. {
  192. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  193. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  194. [self loadFile:file intoPath:filePath];
  195. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  196. [self.delegate operationWithProgressInformationStarted];
  197. _downloadInProgress = YES;
  198. }
  199. - (BOOL)_supportedFileExtension:(NSString *)filename
  200. {
  201. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  202. return YES;
  203. return NO;
  204. }
  205. - (void)_listOfGoodFilesAndFolders
  206. {
  207. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  208. for (GTLRDrive_File *iter in _fileList.files) {
  209. if (iter.trashed.boolValue) {
  210. continue;
  211. }
  212. BOOL isDirectory = [iter.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  213. BOOL supportedFile = [self _supportedFileExtension:iter.name];
  214. if (isDirectory || supportedFile)
  215. [listOfGoodFilesAndFolders addObject:iter];
  216. }
  217. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  218. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  219. [self listFilesWithID:_folderId];
  220. return;
  221. }
  222. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  223. //the files come in a chaotic order so we order alphabetically
  224. NSArray *sortedArray = [_currentFileList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  225. NSString *first = [(GTLRDrive_File *)a name];
  226. NSString *second = [(GTLRDrive_File *)b name];
  227. return [first compare:second];
  228. }];
  229. _currentFileList = sortedArray;
  230. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  231. [self.delegate mediaListUpdated];
  232. }
  233. - (void)loadFile:(GTLRDrive_File*)file intoPath:(NSString*)destinationPath
  234. {
  235. NSString *exportURLStr = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media",
  236. file.identifier];
  237. if ([exportURLStr length] > 0) {
  238. GTMSessionFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:exportURLStr];
  239. fetcher.authorizer = self.driveService.authorizer;
  240. fetcher.destinationFileURL = [NSURL fileURLWithPath:destinationPath isDirectory:YES];
  241. // Fetcher logging can include comments.
  242. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.name];
  243. __weak GTMSessionFetcher *weakFetcher = fetcher;
  244. _startDL = [NSDate timeIntervalSinceReferenceDate];
  245. fetcher.downloadProgressBlock = ^(int64_t bytesWritten,
  246. int64_t totalBytesWritten,
  247. int64_t totalBytesExpectedToWrite) {
  248. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  249. [self calculateRemainingTime:totalBytesWritten expectedDownloadSize:totalBytesExpectedToWrite];
  250. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  251. }
  252. CGFloat progress = (CGFloat)weakFetcher.downloadedLength / (CGFloat)[file.size unsignedLongValue];
  253. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  254. [self.delegate currentProgressInformation:progress];
  255. };
  256. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  257. if (error == nil) {
  258. //TODO: show something nice than an annoying alert
  259. //[self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  260. [self downloadSuccessful];
  261. } else {
  262. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  263. [self downloadFailedWithError:error];
  264. }
  265. }];
  266. }
  267. }
  268. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  269. {
  270. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  271. CGFloat smoothingFactor = 0.005;
  272. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  273. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  274. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  275. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  276. [formatter setDateFormat:@"HH:mm:ss"];
  277. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  278. NSString *remainingTime = [formatter stringFromDate:date];
  279. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  280. [self.delegate updateRemainingTime:remainingTime];
  281. }
  282. - (void)downloadSuccessful
  283. {
  284. /* update library now that we got a file */
  285. APLog(@"DriveFile download was successful");
  286. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  287. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  288. #if TARGET_OS_IOS
  289. // FIXME: Replace notifications by cleaner observers
  290. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  291. object:self];
  292. #endif
  293. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  294. [self.delegate operationWithProgressInformationStopped];
  295. _downloadInProgress = NO;
  296. [self _triggerNextDownload];
  297. }
  298. - (void)downloadFailedWithError:(NSError*)error
  299. {
  300. APLog(@"DriveFile download failed with error %li", (long)error.code);
  301. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  302. [self.delegate operationWithProgressInformationStopped];
  303. _downloadInProgress = NO;
  304. [self _triggerNextDownload];
  305. }
  306. #pragma mark - VLC internal communication and delegate
  307. - (NSArray *)currentListFiles
  308. {
  309. return _currentFileList;
  310. }
  311. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  312. {
  313. if (_listOfGoogleDriveFilesToDownload)
  314. return _listOfGoogleDriveFilesToDownload.count;
  315. return 0;
  316. }
  317. @end