VLCGoogleDriveController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 <XKKeychain/XKKeychain.h>
  19. #import <AppAuth/AppAuth.h>
  20. #import <GTMAppAuth/GTMAppAuth.h>
  21. @interface VLCGoogleDriveController ()
  22. {
  23. GTLDriveFileList *_fileList;
  24. GTLServiceTicket *_fileListTicket;
  25. NSArray *_currentFileList;
  26. NSMutableArray *_listOfGoogleDriveFilesToDownload;
  27. BOOL _downloadInProgress;
  28. NSString *_nextPageToken;
  29. NSString *_folderId;
  30. CGFloat _averageSpeed;
  31. NSTimeInterval _startDL;
  32. NSTimeInterval _lastStatsUpdate;
  33. }
  34. @end
  35. @implementation VLCGoogleDriveController
  36. #pragma mark - session handling
  37. + (instancetype)sharedInstance
  38. {
  39. static VLCGoogleDriveController *sharedInstance = nil;
  40. static dispatch_once_t pred;
  41. dispatch_once(&pred, ^{
  42. sharedInstance = [VLCGoogleDriveController new];
  43. });
  44. return sharedInstance;
  45. }
  46. - (void)startSession
  47. {
  48. [self restoreFromSharedCredentials];
  49. self.driveService = [GTLServiceDrive new];
  50. self.driveService.authorizer = [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kKeychainItemName];
  51. }
  52. - (void)stopSession
  53. {
  54. [_fileListTicket cancelTicket];
  55. _nextPageToken = nil;
  56. _currentFileList = nil;
  57. }
  58. - (void)logout
  59. {
  60. self.driveService.authorizer = nil;
  61. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  62. [ubiquitousStore setString:nil forKey:kVLCStoreGDriveCredentials];
  63. [ubiquitousStore synchronize];
  64. [self stopSession];
  65. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  66. [self.delegate mediaListUpdated];
  67. }
  68. - (BOOL)isAuthorized
  69. {
  70. if (!self.driveService) {
  71. [self startSession];
  72. }
  73. BOOL ret = [(GTMAppAuthFetcherAuthorization *)self.driveService.authorizer canAuthorize];
  74. if (ret) {
  75. [self shareCredentials];
  76. }
  77. return ret;
  78. }
  79. - (void)shareCredentials
  80. {
  81. /* share our credentials */
  82. XKKeychainGenericPasswordItem *item = [XKKeychainGenericPasswordItem itemForService:kKeychainItemName account:@"OAuth" error:nil]; // kGTMOAuth2AccountName
  83. NSString *credentials = item.secret.stringValue;
  84. if (credentials == nil)
  85. return;
  86. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  87. [ubiquitousStore setString:credentials forKey:kVLCStoreGDriveCredentials];
  88. [ubiquitousStore synchronize];
  89. }
  90. - (BOOL)restoreFromSharedCredentials
  91. {
  92. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  93. [ubiquitousStore synchronize];
  94. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreGDriveCredentials];
  95. if (!credentials)
  96. return NO;
  97. XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
  98. keychainItem.service = kKeychainItemName;
  99. keychainItem.account = @"OAuth"; // kGTMOAuth2AccountName
  100. keychainItem.secret.stringValue = credentials;
  101. [keychainItem saveWithError:nil];
  102. return YES;
  103. }
  104. - (void)showAlert:(NSString *)title message:(NSString *)message
  105. {
  106. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle: title
  107. message: message
  108. delegate: nil
  109. cancelButtonTitle: @"OK"
  110. otherButtonTitles: nil];
  111. [alert show];
  112. }
  113. #pragma mark - file management
  114. - (BOOL)canPlayAll
  115. {
  116. return NO;
  117. }
  118. - (void)requestDirectoryListingAtPath:(NSString *)path
  119. {
  120. if (self.isAuthorized) {
  121. //we entered a different folder so discard all current files
  122. if (![path isEqualToString:_folderId])
  123. _currentFileList = nil;
  124. [self listFilesWithID:path];
  125. }
  126. }
  127. - (BOOL)hasMoreFiles
  128. {
  129. return _nextPageToken != nil;
  130. }
  131. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  132. {
  133. if (file == nil)
  134. return;
  135. if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) return;
  136. if (!_listOfGoogleDriveFilesToDownload)
  137. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  138. [_listOfGoogleDriveFilesToDownload addObject:file];
  139. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  140. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  141. [self _triggerNextDownload];
  142. }
  143. - (void)listFilesWithID:(NSString *)folderId
  144. {
  145. _fileList = nil;
  146. _folderId = folderId;
  147. GTLQueryDrive *query;
  148. NSString *parentName = @"root";
  149. query = [GTLQueryDrive queryForFilesList];
  150. query.pageToken = _nextPageToken;
  151. //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.
  152. //query.pageSize = 1000;
  153. query.includeDeleted = NO;
  154. query.includeRemoved = NO;
  155. query.restrictToMyDrive = YES;
  156. query.fields = @"files(*)";
  157. if (![_folderId isEqualToString:@""]) {
  158. parentName = [_folderId lastPathComponent];
  159. }
  160. query.q = [NSString stringWithFormat:@"'%@' in parents", parentName];
  161. _fileListTicket = [self.driveService executeQuery:query
  162. completionHandler:^(GTLServiceTicket *ticket,
  163. GTLDriveFileList *fileList,
  164. NSError *error) {
  165. if (error == nil) {
  166. self->_fileList = fileList;
  167. self->_nextPageToken = fileList.nextPageToken;
  168. self->_fileListTicket = nil;
  169. [self _listOfGoodFilesAndFolders];
  170. } else {
  171. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  172. }
  173. }];
  174. }
  175. - (void)streamFile:(GTLDriveFile *)file
  176. {
  177. NSString *token = [((GTMAppAuthFetcherAuthorization *)self.driveService.authorizer).authState.lastTokenResponse accessToken];
  178. NSString *urlString = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media&access_token=%@",
  179. file.identifier, token];
  180. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  181. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:urlString]];
  182. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  183. [medialist addMedia:media];
  184. [vpc playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
  185. }
  186. - (void)_triggerNextDownload
  187. {
  188. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  189. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  190. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  191. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  192. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  193. }
  194. }
  195. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  196. {
  197. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  198. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  199. [self loadFile:file intoPath:filePath];
  200. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  201. [self.delegate operationWithProgressInformationStarted];
  202. _downloadInProgress = YES;
  203. }
  204. - (BOOL)_supportedFileExtension:(NSString *)filename
  205. {
  206. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  207. return YES;
  208. return NO;
  209. }
  210. - (void)_listOfGoodFilesAndFolders
  211. {
  212. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  213. for (GTLDriveFile *iter in _fileList.files) {
  214. if (iter.trashed.boolValue) {
  215. continue;
  216. }
  217. BOOL isDirectory = [iter.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  218. BOOL supportedFile = [self _supportedFileExtension:iter.name];
  219. if (isDirectory || supportedFile)
  220. [listOfGoodFilesAndFolders addObject:iter];
  221. }
  222. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  223. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  224. [self listFilesWithID:_folderId];
  225. return;
  226. }
  227. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  228. //the files come in a chaotic order so we order alphabetically
  229. NSArray *sortedArray = [_currentFileList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  230. NSString *first = [(GTLDriveFile *)a name];
  231. NSString *second = [(GTLDriveFile *)b name];
  232. return [first compare:second];
  233. }];
  234. _currentFileList = sortedArray;
  235. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  236. [self.delegate mediaListUpdated];
  237. }
  238. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  239. {
  240. NSString *exportURLStr = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media",
  241. file.identifier];
  242. if ([exportURLStr length] > 0) {
  243. GTMSessionFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:exportURLStr];
  244. fetcher.authorizer = self.driveService.authorizer;
  245. fetcher.destinationFileURL = [NSURL fileURLWithPath:destinationPath isDirectory:YES];
  246. // Fetcher logging can include comments.
  247. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.name];
  248. __weak GTMSessionFetcher *weakFetcher = fetcher;
  249. _startDL = [NSDate timeIntervalSinceReferenceDate];
  250. fetcher.downloadProgressBlock = ^(int64_t bytesWritten,
  251. int64_t totalBytesWritten,
  252. int64_t totalBytesExpectedToWrite) {
  253. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  254. [self calculateRemainingTime:totalBytesWritten expectedDownloadSize:totalBytesExpectedToWrite];
  255. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  256. }
  257. CGFloat progress = (CGFloat)weakFetcher.downloadedLength / (CGFloat)[file.size unsignedLongValue];
  258. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  259. [self.delegate currentProgressInformation:progress];
  260. };
  261. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  262. if (error == nil) {
  263. //TODO: show something nice than an annoying alert
  264. //[self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  265. [self downloadSuccessful];
  266. } else {
  267. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  268. [self downloadFailedWithError:error];
  269. }
  270. }];
  271. }
  272. }
  273. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  274. {
  275. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  276. CGFloat smoothingFactor = 0.005;
  277. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  278. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  279. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  280. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  281. [formatter setDateFormat:@"HH:mm:ss"];
  282. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  283. NSString *remainingTime = [formatter stringFromDate:date];
  284. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  285. [self.delegate updateRemainingTime:remainingTime];
  286. }
  287. - (void)downloadSuccessful
  288. {
  289. /* update library now that we got a file */
  290. APLog(@"DriveFile download was successful");
  291. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  292. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  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