VLCGoogleDriveController.m 11 KB

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