VLCGoogleDriveController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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_iOS-Swift.h"
  19. #import <XKKeychain/XKKeychain.h>
  20. #import <AppAuth/AppAuth.h>
  21. #import <GTMAppAuth/GTMAppAuth.h>
  22. @interface VLCGoogleDriveController ()
  23. {
  24. GTLDriveFileList *_fileList;
  25. GTLServiceTicket *_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 = [GTLServiceDrive 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. NSMutableArray<ButtonAction *> *buttonsAction = [[NSMutableArray alloc] init];
  108. ButtonAction *cancelAction = [[ButtonAction alloc] initWithButtonTitle: NSLocalizedString(@"BUTTON_OK", nil)
  109. buttonAction: ^(UIAlertAction* action){}];
  110. [buttonsAction addObject: cancelAction];
  111. [VLCAlertViewController alertViewManagerWithTitle:title
  112. errorMessage:message
  113. viewController:[UIApplication sharedApplication].keyWindow.rootViewController
  114. buttonsAction:buttonsAction];
  115. }
  116. #pragma mark - file management
  117. - (BOOL)canPlayAll
  118. {
  119. return NO;
  120. }
  121. - (void)requestDirectoryListingAtPath:(NSString *)path
  122. {
  123. if (self.isAuthorized) {
  124. //we entered a different folder so discard all current files
  125. if (![path isEqualToString:_folderId])
  126. _currentFileList = nil;
  127. [self listFilesWithID:path];
  128. }
  129. }
  130. - (BOOL)hasMoreFiles
  131. {
  132. return _nextPageToken != nil;
  133. }
  134. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  135. {
  136. if (file == nil)
  137. return;
  138. if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) return;
  139. if (!_listOfGoogleDriveFilesToDownload)
  140. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  141. [_listOfGoogleDriveFilesToDownload addObject:file];
  142. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  143. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  144. [self _triggerNextDownload];
  145. }
  146. - (void)listFilesWithID:(NSString *)folderId
  147. {
  148. _fileList = nil;
  149. _folderId = folderId;
  150. GTLQueryDrive *query;
  151. NSString *parentName = @"root";
  152. query = [GTLQueryDrive queryForFilesList];
  153. query.pageToken = _nextPageToken;
  154. //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.
  155. //query.pageSize = 1000;
  156. query.includeDeleted = NO;
  157. query.includeRemoved = NO;
  158. query.restrictToMyDrive = YES;
  159. query.fields = @"files(*)";
  160. if (![_folderId isEqualToString:@""]) {
  161. parentName = [_folderId lastPathComponent];
  162. }
  163. query.q = [NSString stringWithFormat:@"'%@' in parents", parentName];
  164. _fileListTicket = [self.driveService executeQuery:query
  165. completionHandler:^(GTLServiceTicket *ticket,
  166. GTLDriveFileList *fileList,
  167. NSError *error) {
  168. if (error == nil) {
  169. self->_fileList = fileList;
  170. self->_nextPageToken = fileList.nextPageToken;
  171. self->_fileListTicket = nil;
  172. [self _listOfGoodFilesAndFolders];
  173. } else {
  174. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  175. }
  176. }];
  177. }
  178. - (void)streamFile:(GTLDriveFile *)file
  179. {
  180. NSString *token = [((GTMAppAuthFetcherAuthorization *)self.driveService.authorizer).authState.lastTokenResponse accessToken];
  181. NSString *urlString = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media&access_token=%@",
  182. file.identifier, token];
  183. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  184. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:urlString]];
  185. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  186. [medialist addMedia:media];
  187. [vpc playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
  188. }
  189. - (void)_triggerNextDownload
  190. {
  191. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  192. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  193. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  194. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  195. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  196. }
  197. }
  198. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  199. {
  200. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  201. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  202. [self loadFile:file intoPath:filePath];
  203. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  204. [self.delegate operationWithProgressInformationStarted];
  205. _downloadInProgress = YES;
  206. }
  207. - (BOOL)_supportedFileExtension:(NSString *)filename
  208. {
  209. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  210. return YES;
  211. return NO;
  212. }
  213. - (void)_listOfGoodFilesAndFolders
  214. {
  215. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  216. for (GTLDriveFile *iter in _fileList.files) {
  217. if (iter.trashed.boolValue) {
  218. continue;
  219. }
  220. BOOL isDirectory = [iter.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  221. BOOL supportedFile = [self _supportedFileExtension:iter.name];
  222. if (isDirectory || supportedFile)
  223. [listOfGoodFilesAndFolders addObject:iter];
  224. }
  225. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  226. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  227. [self listFilesWithID:_folderId];
  228. return;
  229. }
  230. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  231. //the files come in a chaotic order so we order alphabetically
  232. NSArray *sortedArray = [_currentFileList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  233. NSString *first = [(GTLDriveFile *)a name];
  234. NSString *second = [(GTLDriveFile *)b name];
  235. return [first compare:second];
  236. }];
  237. _currentFileList = sortedArray;
  238. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  239. [self.delegate mediaListUpdated];
  240. }
  241. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  242. {
  243. NSString *exportURLStr = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media",
  244. file.identifier];
  245. if ([exportURLStr length] > 0) {
  246. GTMSessionFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:exportURLStr];
  247. fetcher.authorizer = self.driveService.authorizer;
  248. fetcher.destinationFileURL = [NSURL fileURLWithPath:destinationPath isDirectory:YES];
  249. // Fetcher logging can include comments.
  250. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.name];
  251. __weak GTMSessionFetcher *weakFetcher = fetcher;
  252. _startDL = [NSDate timeIntervalSinceReferenceDate];
  253. fetcher.downloadProgressBlock = ^(int64_t bytesWritten,
  254. int64_t totalBytesWritten,
  255. int64_t totalBytesExpectedToWrite) {
  256. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  257. [self calculateRemainingTime:totalBytesWritten expectedDownloadSize:totalBytesExpectedToWrite];
  258. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  259. }
  260. CGFloat progress = (CGFloat)weakFetcher.downloadedLength / (CGFloat)[file.size unsignedLongValue];
  261. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  262. [self.delegate currentProgressInformation:progress];
  263. };
  264. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  265. if (error == nil) {
  266. //TODO: show something nice than an annoying alert
  267. //[self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  268. [self downloadSuccessful];
  269. } else {
  270. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  271. [self downloadFailedWithError:error];
  272. }
  273. }];
  274. }
  275. }
  276. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  277. {
  278. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  279. CGFloat smoothingFactor = 0.005;
  280. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  281. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  282. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  283. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  284. [formatter setDateFormat:@"HH:mm:ss"];
  285. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  286. NSString *remainingTime = [formatter stringFromDate:date];
  287. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  288. [self.delegate updateRemainingTime:remainingTime];
  289. }
  290. - (void)downloadSuccessful
  291. {
  292. /* update library now that we got a file */
  293. APLog(@"DriveFile download was successful");
  294. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  295. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  296. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  297. [self.delegate operationWithProgressInformationStopped];
  298. _downloadInProgress = NO;
  299. [self _triggerNextDownload];
  300. }
  301. - (void)downloadFailedWithError:(NSError*)error
  302. {
  303. APLog(@"DriveFile download failed with error %li", (long)error.code);
  304. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  305. [self.delegate operationWithProgressInformationStopped];
  306. _downloadInProgress = NO;
  307. [self _triggerNextDownload];
  308. }
  309. #pragma mark - VLC internal communication and delegate
  310. - (NSArray *)currentListFiles
  311. {
  312. return _currentFileList;
  313. }
  314. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  315. {
  316. if (_listOfGoogleDriveFilesToDownload)
  317. return _listOfGoogleDriveFilesToDownload.count;
  318. return 0;
  319. }
  320. @end