VLCGoogleDriveController.m 12 KB

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