VLCGoogleDriveController.m 12 KB

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