VLCGoogleDriveController.m 14 KB

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