VLCGoogleDriveController.m 12 KB

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