VLCGoogleDriveController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 "VLCPlaybackService.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. sharedInstance.sortBy = VLCCloudSortingCriteriaName; //Default sort by file names
  45. });
  46. return sharedInstance;
  47. }
  48. - (void)startSession
  49. {
  50. [self restoreFromSharedCredentials];
  51. self.driveService = [GTLRDriveService new];
  52. self.driveService.authorizer = [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kKeychainItemName];
  53. }
  54. - (void)stopSession
  55. {
  56. [_fileListTicket cancelTicket];
  57. _nextPageToken = nil;
  58. _currentFileList = nil;
  59. }
  60. - (void)logout
  61. {
  62. self.driveService.authorizer = nil;
  63. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  64. [ubiquitousStore setString:nil forKey:kVLCStoreGDriveCredentials];
  65. [ubiquitousStore synchronize];
  66. [self stopSession];
  67. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  68. [self.delegate mediaListUpdated];
  69. }
  70. - (BOOL)isAuthorized
  71. {
  72. if (!self.driveService) {
  73. [self startSession];
  74. }
  75. BOOL ret = [(GTMAppAuthFetcherAuthorization *)self.driveService.authorizer canAuthorize];
  76. if (ret) {
  77. [self shareCredentials];
  78. }
  79. return ret;
  80. }
  81. - (void)shareCredentials
  82. {
  83. /* share our credentials */
  84. XKKeychainGenericPasswordItem *item = [XKKeychainGenericPasswordItem itemForService:kKeychainItemName account:@"OAuth" error:nil]; // kGTMOAuth2AccountName
  85. NSString *credentials = item.secret.stringValue;
  86. if (credentials == nil)
  87. return;
  88. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  89. [ubiquitousStore setString:credentials forKey:kVLCStoreGDriveCredentials];
  90. [ubiquitousStore synchronize];
  91. }
  92. - (BOOL)restoreFromSharedCredentials
  93. {
  94. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  95. [ubiquitousStore synchronize];
  96. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreGDriveCredentials];
  97. if (!credentials)
  98. return NO;
  99. XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
  100. keychainItem.service = kKeychainItemName;
  101. keychainItem.account = @"OAuth"; // kGTMOAuth2AccountName
  102. keychainItem.secret.stringValue = credentials;
  103. [keychainItem saveWithError:nil];
  104. return YES;
  105. }
  106. - (void)showAlert:(NSString *)title message:(NSString *)message
  107. {
  108. [VLCAlertViewController alertViewManagerWithTitle:title
  109. errorMessage:message
  110. viewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  111. }
  112. #pragma mark - file management
  113. - (BOOL)canPlayAll
  114. {
  115. return NO;
  116. }
  117. - (BOOL)supportSorting
  118. {
  119. return YES; //Google drive controller implemented sorting
  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:(GTLRDrive_File *)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. GTLRDriveQuery_FilesList *query;
  151. NSString *parentName = @"root";
  152. query = [GTLRDriveQuery_FilesList query];
  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.fields = @"files(*)";
  157. //Set orderBy parameter based on sortBy
  158. if (self.sortBy == VLCCloudSortingCriteriaName)
  159. query.orderBy = @"folder,name,modifiedTime desc";
  160. else
  161. query.orderBy = @"modifiedTime desc,folder,name";
  162. if (![_folderId isEqualToString:@""]) {
  163. parentName = [_folderId lastPathComponent];
  164. }
  165. query.q = [NSString stringWithFormat:@"'%@' in parents", parentName];
  166. _fileListTicket = [self.driveService executeQuery:query
  167. completionHandler:^(GTLRServiceTicket *ticket,
  168. GTLRDrive_FileList *fileList,
  169. NSError *error) {
  170. if (error == nil) {
  171. self->_fileList = fileList;
  172. self->_nextPageToken = fileList.nextPageToken;
  173. self->_fileListTicket = nil;
  174. [self _listOfGoodFilesAndFolders];
  175. } else {
  176. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  177. }
  178. }];
  179. }
  180. - (void)streamFile:(GTLRDrive_File *)file
  181. {
  182. NSString *token = [((GTMAppAuthFetcherAuthorization *)self.driveService.authorizer).authState.lastTokenResponse accessToken];
  183. NSString *urlString = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media&access_token=%@",
  184. file.identifier, token];
  185. VLCPlaybackService *vpc = [VLCPlaybackService sharedInstance];
  186. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:urlString]];
  187. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  188. [medialist addMedia:media];
  189. [vpc playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
  190. }
  191. - (void)_triggerNextDownload
  192. {
  193. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  194. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  195. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  196. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  197. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  198. }
  199. }
  200. - (void)_reallyDownloadFileToDocumentFolder:(GTLRDrive_File *)file
  201. {
  202. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  203. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  204. [self loadFile:file intoPath:filePath];
  205. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  206. [self.delegate operationWithProgressInformationStarted];
  207. _downloadInProgress = YES;
  208. }
  209. - (BOOL)_supportedFileExtension:(NSString *)filename
  210. {
  211. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  212. return YES;
  213. return NO;
  214. }
  215. - (void)_listOfGoodFilesAndFolders
  216. {
  217. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  218. for (GTLRDrive_File *iter in _fileList.files) {
  219. if (iter.trashed.boolValue) {
  220. continue;
  221. }
  222. BOOL isDirectory = [iter.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  223. BOOL supportedFile = [self _supportedFileExtension:iter.name];
  224. if (isDirectory || supportedFile)
  225. [listOfGoodFilesAndFolders addObject:iter];
  226. }
  227. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  228. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  229. [self listFilesWithID:_folderId];
  230. return;
  231. }
  232. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  233. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  234. [self.delegate mediaListUpdated];
  235. }
  236. - (void)loadFile:(GTLRDrive_File*)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. _startDL = [NSDate timeIntervalSinceReferenceDate];
  247. fetcher.downloadProgressBlock = ^(int64_t bytesWritten,
  248. int64_t totalBytesWritten,
  249. int64_t totalBytesExpectedToWrite) {
  250. if ((self->_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - self->_lastStatsUpdate > .5)) || self->_lastStatsUpdate <= 0) {
  251. [self calculateRemainingTime:totalBytesWritten expectedDownloadSize:totalBytesExpectedToWrite];
  252. self->_lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  253. }
  254. CGFloat progress = (CGFloat)totalBytesWritten / (CGFloat)[file.size unsignedLongValue];
  255. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  256. [self.delegate currentProgressInformation:progress];
  257. };
  258. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  259. if (error == nil) {
  260. //TODO: show something nice than an annoying alert
  261. //[self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  262. [self downloadSuccessful];
  263. } else {
  264. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  265. [self downloadFailedWithError:error];
  266. }
  267. }];
  268. }
  269. }
  270. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  271. {
  272. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  273. CGFloat smoothingFactor = 0.005;
  274. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  275. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  276. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  277. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  278. [formatter setDateFormat:@"HH:mm:ss"];
  279. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  280. NSString *remainingTime = [formatter stringFromDate:date];
  281. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  282. [self.delegate updateRemainingTime:remainingTime];
  283. }
  284. - (void)downloadSuccessful
  285. {
  286. /* update library now that we got a file */
  287. APLog(@"DriveFile download was successful");
  288. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL", nil));
  289. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  290. #if TARGET_OS_IOS
  291. // FIXME: Replace notifications by cleaner observers
  292. [[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.VLCNewFileAddedNotification
  293. object:self];
  294. #endif
  295. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  296. [self.delegate operationWithProgressInformationStopped];
  297. _downloadInProgress = NO;
  298. [self _triggerNextDownload];
  299. }
  300. - (void)downloadFailedWithError:(NSError*)error
  301. {
  302. APLog(@"DriveFile download failed with error %li", (long)error.code);
  303. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  304. [self.delegate operationWithProgressInformationStopped];
  305. _downloadInProgress = NO;
  306. [self _triggerNextDownload];
  307. }
  308. #pragma mark - VLC internal communication and delegate
  309. - (NSArray *)currentListFiles
  310. {
  311. return _currentFileList;
  312. }
  313. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  314. {
  315. if (_listOfGoogleDriveFilesToDownload)
  316. return _listOfGoogleDriveFilesToDownload.count;
  317. return 0;
  318. }
  319. @end