VLCGoogleDriveController.m 12 KB

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