VLCGoogleDriveController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCGoogleDriveController.h"
  14. #import "NSString+SupportedMedia.h"
  15. #import "VLCPlaybackController.h"
  16. #import "VLCMediaFileDiscoverer.h"
  17. #import <XKKeychain/XKKeychain.h>
  18. #import "GTMOAuth2ViewControllerTouch.h"
  19. #import "GTMOAuth2SignIn.h"
  20. @interface VLCGoogleDriveController ()
  21. {
  22. GTLDriveFileList *_fileList;
  23. GTLServiceTicket *_fileListTicket;
  24. NSArray *_currentFileList;
  25. NSMutableArray *_listOfGoogleDriveFilesToDownload;
  26. BOOL _downloadInProgress;
  27. NSString *_nextPageToken;
  28. NSString *_folderId;
  29. CGFloat _averageSpeed;
  30. NSTimeInterval _startDL;
  31. NSTimeInterval _lastStatsUpdate;
  32. }
  33. @end
  34. @implementation VLCGoogleDriveController
  35. #pragma mark - session handling
  36. + (instancetype)sharedInstance
  37. {
  38. static VLCGoogleDriveController *sharedInstance = nil;
  39. static dispatch_once_t pred;
  40. dispatch_once(&pred, ^{
  41. sharedInstance = [VLCGoogleDriveController new];
  42. });
  43. return sharedInstance;
  44. }
  45. - (void)startSession
  46. {
  47. [self restoreFromSharedCredentials];
  48. self.driveService = [GTLServiceDrive new];
  49. self.driveService.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kVLCGoogleDriveClientID clientSecret:kVLCGoogleDriveClientSecret];
  50. }
  51. - (void)stopSession
  52. {
  53. [_fileListTicket cancelTicket];
  54. _nextPageToken = nil;
  55. _currentFileList = nil;
  56. }
  57. - (void)logout
  58. {
  59. [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemName];
  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 = [((GTMOAuth2Authentication *)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. query = [GTLQueryDrive queryForFilesList];
  149. query.pageToken = _nextPageToken;
  150. //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.
  151. //query.pageSize = 1000;
  152. query.includeDeleted = NO;
  153. query.includeRemoved = NO;
  154. query.restrictToMyDrive = YES;
  155. if (![_folderId isEqualToString:@""]) {
  156. query.q = [NSString stringWithFormat:@"'%@' in parents", [_folderId lastPathComponent]];
  157. }
  158. _fileListTicket = [self.driveService executeQuery:query
  159. completionHandler:^(GTLServiceTicket *ticket,
  160. GTLDriveFileList *fileList,
  161. NSError *error) {
  162. if (error == nil) {
  163. _fileList = fileList;
  164. _nextPageToken = fileList.nextPageToken;
  165. _fileListTicket = nil;
  166. [self _listOfGoodFilesAndFolders];
  167. } else {
  168. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  169. }
  170. }];
  171. }
  172. - (void)streamFile:(GTLDriveFile *)file
  173. {
  174. NSString *token = ((GTMOAuth2Authentication *)self.driveService.authorizer).accessToken;
  175. NSString *urlString = [NSString stringWithFormat:@"https://www.googleapis.com/drive/v3/files/%@?alt=media&access_token=%@",
  176. file.identifier, token];
  177. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  178. [vpc playURL:[NSURL URLWithString:urlString] successCallback:nil errorCallback:nil];
  179. }
  180. - (void)_triggerNextDownload
  181. {
  182. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  183. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  184. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  185. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  186. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  187. }
  188. }
  189. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  190. {
  191. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  192. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  193. [self loadFile:file intoPath:filePath];
  194. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  195. [self.delegate operationWithProgressInformationStarted];
  196. _downloadInProgress = YES;
  197. }
  198. - (BOOL)_supportedFileExtension:(NSString *)filename
  199. {
  200. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  201. return YES;
  202. return NO;
  203. }
  204. - (void)_listOfGoodFilesAndFolders
  205. {
  206. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  207. for (GTLDriveFile *iter in _fileList.files) {
  208. BOOL isDirectory = [iter.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  209. BOOL inDirectory = NO;
  210. if (iter.parents.count > 0) {
  211. GTLDriveFile *parent = [iter.parents firstObject];
  212. //since there is no rootfolder display the files right away
  213. if (parent.parents == nil)
  214. inDirectory = ![parent.identifier isEqualToString:[_folderId lastPathComponent]];
  215. }
  216. BOOL supportedFile = [self _supportedFileExtension:iter.name];
  217. if ((isDirectory || supportedFile) && !inDirectory)
  218. [listOfGoodFilesAndFolders addObject:iter];
  219. }
  220. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [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 ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  252. [self calculateRemainingTime:totalBytesWritten expectedDownloadSize:totalBytesExpectedToWrite];
  253. _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. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  290. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  291. [self.delegate operationWithProgressInformationStopped];
  292. _downloadInProgress = NO;
  293. [self _triggerNextDownload];
  294. }
  295. - (void)downloadFailedWithError:(NSError*)error
  296. {
  297. APLog(@"DriveFile download failed with error %li", (long)error.code);
  298. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  299. [self.delegate operationWithProgressInformationStopped];
  300. _downloadInProgress = NO;
  301. [self _triggerNextDownload];
  302. }
  303. #pragma mark - VLC internal communication and delegate
  304. - (NSArray *)currentListFiles
  305. {
  306. return _currentFileList;
  307. }
  308. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  309. {
  310. if (_listOfGoogleDriveFilesToDownload)
  311. return _listOfGoogleDriveFilesToDownload.count;
  312. return 0;
  313. }
  314. @end