VLCGoogleDriveController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. - (void)requestDirectoryListingAtPath:(NSString *)path
  108. {
  109. if (self.isAuthorized) {
  110. //we entered a different folder so discard all current files
  111. if (![path isEqualToString:_folderId])
  112. _currentFileList = nil;
  113. [self listFilesWithID:path];
  114. }
  115. }
  116. - (BOOL)hasMoreFiles
  117. {
  118. return _nextPageToken != nil;
  119. }
  120. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  121. {
  122. if (file == nil)
  123. return;
  124. if ([file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) return;
  125. if (!_listOfGoogleDriveFilesToDownload)
  126. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  127. [_listOfGoogleDriveFilesToDownload addObject:file];
  128. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  129. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  130. [self _triggerNextDownload];
  131. }
  132. - (void)listFilesWithID:(NSString *)folderId
  133. {
  134. _fileList = nil;
  135. _folderId = folderId;
  136. GTLQueryDrive *query;
  137. query = [GTLQueryDrive queryForFilesList];
  138. query.pageToken = _nextPageToken;
  139. //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.
  140. query.maxResults = INT_MAX;
  141. if (![_folderId isEqualToString:@""]) {
  142. query.q = [NSString stringWithFormat:@"'%@' in parents", [_folderId lastPathComponent]];
  143. }
  144. _fileListTicket = [self.driveService executeQuery:query
  145. completionHandler:^(GTLServiceTicket *ticket,
  146. GTLDriveFileList *fileList,
  147. NSError *error) {
  148. if (error == nil) {
  149. _fileList = fileList;
  150. _nextPageToken = fileList.nextPageToken;
  151. _fileListTicket = nil;
  152. [self _listOfGoodFilesAndFolders];
  153. } else {
  154. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  155. }
  156. }];
  157. }
  158. - (void)streamFile:(GTLDriveFile *)file
  159. {
  160. NSString *token = ((GTMOAuth2Authentication *)self.driveService.authorizer).accessToken;
  161. NSString *downloadString = [file.downloadUrl stringByAppendingString:[NSString stringWithFormat:@"&access_token=%@",token]];
  162. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  163. [vpc playURL:[NSURL URLWithString:downloadString] successCallback:nil errorCallback:nil];
  164. }
  165. - (void)_triggerNextDownload
  166. {
  167. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  168. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  169. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  170. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  171. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  172. }
  173. }
  174. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  175. {
  176. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  177. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  178. [self loadFile:file intoPath:filePath];
  179. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  180. [self.delegate operationWithProgressInformationStarted];
  181. _downloadInProgress = YES;
  182. }
  183. - (BOOL)_supportedFileExtension:(NSString *)filename
  184. {
  185. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  186. return YES;
  187. return NO;
  188. }
  189. - (void)_listOfGoodFilesAndFolders
  190. {
  191. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  192. for (GTLDriveFile *driveFile in _fileList.items)
  193. {
  194. BOOL isDirectory = [driveFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  195. BOOL inDirectory = NO;
  196. if (driveFile.parents.count > 0) {
  197. GTLDriveParentReference *parent = (GTLDriveParentReference *)driveFile.parents[0];
  198. //since there is no rootfolder display the files right away
  199. if (![parent.isRoot boolValue])
  200. inDirectory = ![parent.identifier isEqualToString:[_folderId lastPathComponent]];
  201. }
  202. BOOL supportedFile = [self _supportedFileExtension:[NSString stringWithFormat:@".%@",driveFile.fileExtension]];
  203. if ((isDirectory || supportedFile) && !inDirectory)
  204. [listOfGoodFilesAndFolders addObject:driveFile];
  205. }
  206. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  207. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  208. [self listFilesWithID:_folderId];
  209. return;
  210. }
  211. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  212. //the files come in a chaotic order so we order alphabetically
  213. NSArray *sortedArray = [_currentFileList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
  214. NSString *first = [(GTLDriveFile *)a title];
  215. NSString *second = [(GTLDriveFile *)b title];
  216. return [first compare:second];
  217. }];
  218. _currentFileList = sortedArray;
  219. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  220. [self.delegate mediaListUpdated];
  221. }
  222. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  223. {
  224. NSString *exportURLStr = file.downloadUrl;
  225. if ([exportURLStr length] > 0) {
  226. NSURL *url = [NSURL URLWithString:exportURLStr];
  227. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  228. GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
  229. fetcher.authorizer = self.driveService.authorizer;
  230. fetcher.downloadPath = destinationPath;
  231. // Fetcher logging can include comments.
  232. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.title];
  233. __weak GTMHTTPFetcher *weakFetcher = fetcher;
  234. _startDL = [NSDate timeIntervalSinceReferenceDate];
  235. fetcher.receivedDataBlock = ^(NSData *receivedData) {
  236. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  237. [self calculateRemainingTime:weakFetcher.downloadedLength expectedDownloadSize:[file.fileSize floatValue]];
  238. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  239. }
  240. CGFloat progress = (CGFloat)weakFetcher.downloadedLength / (CGFloat)[file.fileSize unsignedLongValue];
  241. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  242. [self.delegate currentProgressInformation:progress];
  243. };
  244. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  245. if (error == nil) {
  246. //TODO: show something nice than an annoying alert
  247. //[self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  248. [self downloadSuccessful];
  249. } else {
  250. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  251. [self downloadFailedWithError:error];
  252. }
  253. }];
  254. }
  255. }
  256. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  257. {
  258. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  259. CGFloat smoothingFactor = 0.005;
  260. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  261. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  262. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  263. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  264. [formatter setDateFormat:@"HH:mm:ss"];
  265. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  266. NSString *remainingTime = [formatter stringFromDate:date];
  267. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  268. [self.delegate updateRemainingTime:remainingTime];
  269. }
  270. - (void)downloadSuccessful
  271. {
  272. /* update library now that we got a file */
  273. APLog(@"DriveFile download was successful");
  274. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  275. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  276. [self.delegate operationWithProgressInformationStopped];
  277. _downloadInProgress = NO;
  278. [self _triggerNextDownload];
  279. }
  280. - (void)downloadFailedWithError:(NSError*)error
  281. {
  282. APLog(@"DriveFile download failed with error %li", (long)error.code);
  283. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  284. [self.delegate operationWithProgressInformationStopped];
  285. _downloadInProgress = NO;
  286. [self _triggerNextDownload];
  287. }
  288. #pragma mark - VLC internal communication and delegate
  289. - (NSArray *)currentListFiles
  290. {
  291. return _currentFileList;
  292. }
  293. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  294. {
  295. if (_listOfGoogleDriveFilesToDownload)
  296. return _listOfGoogleDriveFilesToDownload.count;
  297. return 0;
  298. }
  299. @end