VLCGoogleDriveController.m 12 KB

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