VLCGoogleDriveController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 "SSKeychain.h"
  18. @interface VLCGoogleDriveController ()
  19. {
  20. GTLDriveFileList *_fileList;
  21. GTLServiceTicket *_fileListTicket;
  22. NSArray *_currentFileList;
  23. NSMutableArray *_listOfGoogleDriveFilesToDownload;
  24. BOOL _downloadInProgress;
  25. NSString *_nextPageToken;
  26. NSString *_folderId;
  27. CGFloat _averageSpeed;
  28. NSTimeInterval _startDL;
  29. NSTimeInterval _lastStatsUpdate;
  30. }
  31. @end
  32. @implementation VLCGoogleDriveController
  33. #pragma mark - session handling
  34. + (instancetype)sharedInstance
  35. {
  36. static VLCGoogleDriveController *sharedInstance = nil;
  37. static dispatch_once_t pred;
  38. dispatch_once(&pred, ^{
  39. sharedInstance = [VLCGoogleDriveController new];
  40. });
  41. return sharedInstance;
  42. }
  43. - (void)startSession
  44. {
  45. [self restoreFromSharedCredentials];
  46. self.driveService = [GTLServiceDrive new];
  47. self.driveService.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kVLCGoogleDriveClientID clientSecret:kVLCGoogleDriveClientSecret];
  48. }
  49. - (void)stopSession
  50. {
  51. [_fileListTicket cancelTicket];
  52. _nextPageToken = nil;
  53. _currentFileList = nil;
  54. }
  55. - (void)logout
  56. {
  57. [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemName];
  58. self.driveService.authorizer = nil;
  59. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  60. [ubiquitousStore setString:nil forKey:kVLCStoreGDriveCredentials];
  61. [ubiquitousStore synchronize];
  62. [self stopSession];
  63. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  64. [self.delegate mediaListUpdated];
  65. }
  66. - (BOOL)isAuthorized
  67. {
  68. if (!self.driveService) {
  69. [self startSession];
  70. }
  71. BOOL ret = [((GTMOAuth2Authentication *)self.driveService.authorizer) canAuthorize];
  72. if (ret) {
  73. [self shareCredentials];
  74. }
  75. return ret;
  76. }
  77. - (void)shareCredentials
  78. {
  79. /* share our credentials */
  80. NSString *credentials = [SSKeychain passwordForService:kKeychainItemName account:@"OAuth"]; // kGTMOAuth2AccountName
  81. if (credentials == nil)
  82. return;
  83. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  84. [ubiquitousStore setString:credentials forKey:kVLCStoreGDriveCredentials];
  85. [ubiquitousStore synchronize];
  86. }
  87. - (BOOL)restoreFromSharedCredentials
  88. {
  89. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  90. [ubiquitousStore synchronize];
  91. NSString *credentials = [ubiquitousStore stringForKey:kVLCStoreGDriveCredentials];
  92. if (!credentials)
  93. return NO;
  94. [SSKeychain setPassword:credentials forService:kKeychainItemName account:@"OAuth"]; // kGTMOAuth2AccountName
  95. return YES;
  96. }
  97. - (void)showAlert:(NSString *)title message:(NSString *)message
  98. {
  99. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle: title
  100. message: message
  101. delegate: nil
  102. cancelButtonTitle: @"OK"
  103. otherButtonTitles: nil];
  104. [alert show];
  105. }
  106. #pragma mark - file management
  107. - (BOOL)canPlayAll
  108. {
  109. return NO;
  110. }
  111. - (void)requestDirectoryListingAtPath:(NSString *)path
  112. {
  113. if (self.isAuthorized) {
  114. //we entered a different folder so discard all current files
  115. if (![path isEqualToString:_folderId])
  116. _currentFileList = nil;
  117. [self listFilesWithID:path];
  118. }
  119. }
  120. - (BOOL)hasMoreFiles
  121. {
  122. return _nextPageToken != nil;
  123. }
  124. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  125. {
  126. if (file == nil)
  127. return;
  128. if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) return;
  129. if (!_listOfGoogleDriveFilesToDownload)
  130. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  131. [_listOfGoogleDriveFilesToDownload addObject:file];
  132. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  133. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  134. [self _triggerNextDownload];
  135. }
  136. - (void)listFilesWithID:(NSString *)folderId
  137. {
  138. _fileList = nil;
  139. _folderId = folderId;
  140. GTLQueryDrive *query;
  141. query = [GTLQueryDrive queryForFilesList];
  142. query.pageToken = _nextPageToken;
  143. //the results don't come in alphabetical order when paging. So the maxresult (default 100) is set to INT_max in order to get all files at once.
  144. query.maxResults = INT_MAX;
  145. if (![_folderId isEqualToString:@""]) {
  146. query.q = [NSString stringWithFormat:@"'%@' in parents", [_folderId lastPathComponent]];
  147. }
  148. _fileListTicket = [self.driveService executeQuery:query
  149. completionHandler:^(GTLServiceTicket *ticket,
  150. GTLDriveFileList *fileList,
  151. NSError *error) {
  152. if (error == nil) {
  153. _fileList = fileList;
  154. _nextPageToken = fileList.nextPageToken;
  155. _fileListTicket = nil;
  156. [self _listOfGoodFilesAndFolders];
  157. } else {
  158. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  159. }
  160. }];
  161. }
  162. - (void)streamFile:(GTLDriveFile *)file
  163. {
  164. NSString *token = ((GTMOAuth2Authentication *)self.driveService.authorizer).accessToken;
  165. NSString *downloadString = [file.downloadUrl stringByAppendingString:[NSString stringWithFormat:@"&access_token=%@",token]];
  166. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  167. [vpc playURL:[NSURL URLWithString:downloadString] successCallback:nil errorCallback:nil];
  168. }
  169. - (void)_triggerNextDownload
  170. {
  171. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  172. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  173. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  174. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  175. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  176. }
  177. }
  178. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  179. {
  180. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  181. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  182. [self loadFile:file intoPath:filePath];
  183. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  184. [self.delegate operationWithProgressInformationStarted];
  185. _downloadInProgress = YES;
  186. }
  187. - (BOOL)_supportedFileExtension:(NSString *)filename
  188. {
  189. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  190. return YES;
  191. return NO;
  192. }
  193. - (void)_listOfGoodFilesAndFolders
  194. {
  195. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  196. for (GTLDriveFile *driveFile in _fileList.items)
  197. {
  198. BOOL isDirectory = [driveFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  199. BOOL inDirectory = NO;
  200. if (driveFile.parents.count > 0) {
  201. GTLDriveParentReference *parent = (GTLDriveParentReference *)driveFile.parents[0];
  202. //since there is no rootfolder display the files right away
  203. if (![parent.isRoot boolValue])
  204. inDirectory = ![parent.identifier isEqualToString:[_folderId lastPathComponent]];
  205. }
  206. BOOL supportedFile = [self _supportedFileExtension:[NSString stringWithFormat:@".%@",driveFile.fileExtension]];
  207. if ((isDirectory || supportedFile) && !inDirectory)
  208. [listOfGoodFilesAndFolders addObject:driveFile];
  209. }
  210. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  211. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  212. [self listFilesWithID:_folderId];
  213. return;
  214. }
  215. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  216. //the files come in a chaotic order so we order alphabetically
  217. NSArray *sortedArray = [_currentFileList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  218. NSString *first = [(GTLDriveFile *)a title];
  219. NSString *second = [(GTLDriveFile *)b title];
  220. return [first compare:second];
  221. }];
  222. _currentFileList = sortedArray;
  223. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  224. [self.delegate mediaListUpdated];
  225. }
  226. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  227. {
  228. NSString *exportURLStr = file.downloadUrl;
  229. if ([exportURLStr length] > 0) {
  230. NSURL *url = [NSURL URLWithString:exportURLStr];
  231. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  232. GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
  233. fetcher.authorizer = self.driveService.authorizer;
  234. fetcher.downloadPath = destinationPath;
  235. // Fetcher logging can include comments.
  236. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.title];
  237. __weak GTMHTTPFetcher *weakFetcher = fetcher;
  238. _startDL = [NSDate timeIntervalSinceReferenceDate];
  239. fetcher.receivedDataBlock = ^(NSData *receivedData) {
  240. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  241. [self calculateRemainingTime:weakFetcher.downloadedLength expectedDownloadSize:[file.fileSize floatValue]];
  242. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  243. }
  244. CGFloat progress = (CGFloat)weakFetcher.downloadedLength / (CGFloat)[file.fileSize unsignedLongValue];
  245. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  246. [self.delegate currentProgressInformation:progress];
  247. };
  248. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  249. if (error == nil) {
  250. //TODO: show something nice than an annoying alert
  251. //[self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  252. [self downloadSuccessful];
  253. } else {
  254. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  255. [self downloadFailedWithError:error];
  256. }
  257. }];
  258. }
  259. }
  260. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  261. {
  262. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  263. CGFloat smoothingFactor = 0.005;
  264. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  265. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  266. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  267. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  268. [formatter setDateFormat:@"HH:mm:ss"];
  269. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  270. NSString *remainingTime = [formatter stringFromDate:date];
  271. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  272. [self.delegate updateRemainingTime:remainingTime];
  273. }
  274. - (void)downloadSuccessful
  275. {
  276. /* update library now that we got a file */
  277. APLog(@"DriveFile download was successful");
  278. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  279. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  280. [self.delegate operationWithProgressInformationStopped];
  281. _downloadInProgress = NO;
  282. [self _triggerNextDownload];
  283. }
  284. - (void)downloadFailedWithError:(NSError*)error
  285. {
  286. APLog(@"DriveFile download failed with error %li", (long)error.code);
  287. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  288. [self.delegate operationWithProgressInformationStopped];
  289. _downloadInProgress = NO;
  290. [self _triggerNextDownload];
  291. }
  292. #pragma mark - VLC internal communication and delegate
  293. - (NSArray *)currentListFiles
  294. {
  295. return _currentFileList;
  296. }
  297. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  298. {
  299. if (_listOfGoogleDriveFilesToDownload)
  300. return _listOfGoogleDriveFilesToDownload.count;
  301. return 0;
  302. }
  303. @end