VLCGoogleDriveController.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. #import "HTTPMessage.h"
  17. @interface VLCGoogleDriveController ()
  18. {
  19. GTLDriveFileList *_fileList;
  20. GTLServiceTicket *_fileListTicket;
  21. NSArray *_currentFileList;
  22. NSMutableArray *_listOfGoogleDriveFilesToDownload;
  23. BOOL _downloadInProgress;
  24. NSString *_nextPageToken;
  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)requestFileListing
  76. {
  77. if (self.isAuthorized)
  78. [self listFiles];
  79. }
  80. - (BOOL)hasMoreFiles
  81. {
  82. return _nextPageToken != nil;
  83. }
  84. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  85. {
  86. if (!_listOfGoogleDriveFilesToDownload)
  87. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  88. [_listOfGoogleDriveFilesToDownload addObject:file];
  89. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  90. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  91. [self _triggerNextDownload];
  92. }
  93. - (void)listFiles
  94. {
  95. _fileList = nil;
  96. GTLQueryDrive *query;
  97. query = [GTLQueryDrive queryForFilesList];
  98. query.fields = @"items(originalFilename,title,mimeType,fileExtension,fileSize,iconLink,downloadUrl,webContentLink,thumbnailLink),nextPageToken";
  99. query.pageToken = _nextPageToken;
  100. query.maxResults = 100;
  101. APLog(@"fetching files with following queryfields:%@", query.fields);
  102. _fileListTicket = [self.driveService executeQuery:query
  103. completionHandler:^(GTLServiceTicket *ticket,
  104. GTLDriveFileList *fileList,
  105. NSError *error) {
  106. if (error == nil) {
  107. _fileList = fileList;
  108. _nextPageToken = fileList.nextPageToken;
  109. _fileListTicket = nil;
  110. [self _listOfGoodFiles];
  111. } else {
  112. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  113. }
  114. }];
  115. }
  116. - (void)_triggerNextDownload
  117. {
  118. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  119. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  120. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  121. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  122. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  123. }
  124. }
  125. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  126. {
  127. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  128. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  129. [self loadFile:file intoPath:filePath];
  130. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  131. [self.delegate operationWithProgressInformationStarted];
  132. _downloadInProgress = YES;
  133. }
  134. - (BOOL)_supportedFileExtension:(NSString *)filename
  135. {
  136. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  137. return YES;
  138. return NO;
  139. }
  140. - (void)_listOfGoodFiles
  141. {
  142. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  143. for (GTLDriveFile *driveFile in _fileList.items)
  144. {
  145. BOOL isDirectory = [driveFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  146. if (!isDirectory && [self _supportedFileExtension:[NSString stringWithFormat:@".%@",driveFile.fileExtension ]]) {
  147. [listOfGoodFilesAndFolders addObject:driveFile];
  148. }
  149. }
  150. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  151. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  152. [self requestFileListing];
  153. return;
  154. }
  155. APLog(@"found filtered metadata for %lu files", (unsigned long)_currentFileList.count);
  156. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  157. [self.delegate mediaListUpdated];
  158. }
  159. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  160. {
  161. NSString *exportURLStr = file.downloadUrl;
  162. if ([exportURLStr length] > 0) {
  163. NSString *suggestedName = file.originalFilename;
  164. if ([suggestedName length] == 0) {
  165. suggestedName = file.title;
  166. }
  167. NSURL *url = [NSURL URLWithString:exportURLStr];
  168. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  169. GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
  170. fetcher.authorizer = self.driveService.authorizer;
  171. fetcher.downloadPath = destinationPath;
  172. // Fetcher logging can include comments.
  173. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.title];
  174. __weak GTMHTTPFetcher *weakFetcher = fetcher;
  175. _startDL = [NSDate timeIntervalSinceReferenceDate];
  176. fetcher.receivedDataBlock = ^(NSData *receivedData) {
  177. if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
  178. [self calculateRemainingTime:weakFetcher.downloadedLength expectedDownloadSize:[file.fileSize floatValue]];
  179. _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
  180. }
  181. CGFloat progress = (CGFloat)weakFetcher.downloadedLength / (CGFloat)[file.fileSize unsignedLongValue];
  182. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  183. [self.delegate currentProgressInformation:progress];
  184. };
  185. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  186. if (error == nil) {
  187. [self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  188. [self downloadSucessfull];
  189. } else {
  190. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  191. [self downloadFailedWithError:error];
  192. }
  193. }];
  194. }
  195. }
  196. - (void)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
  197. {
  198. CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
  199. CGFloat smoothingFactor = 0.005;
  200. _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
  201. CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize) / _averageSpeed;
  202. NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
  203. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  204. [formatter setDateFormat:@"HH:mm:ss"];
  205. [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  206. NSString *remaingTime = [formatter stringFromDate:date];
  207. if ([self.delegate respondsToSelector:@selector(updateRemainingTime:)])
  208. [self.delegate updateRemainingTime:remaingTime];
  209. }
  210. - (void)downloadSucessfull
  211. {
  212. /* update library now that we got a file */
  213. APLog(@"DriveFile download was successful");
  214. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  215. [appDelegate performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  216. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  217. [self.delegate operationWithProgressInformationStopped];
  218. _downloadInProgress = NO;
  219. [self _triggerNextDownload];
  220. }
  221. - (void)downloadFailedWithError:(NSError*)error
  222. {
  223. APLog(@"DriveFile download failed with error %li", (long)error.code);
  224. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  225. [self.delegate operationWithProgressInformationStopped];
  226. _downloadInProgress = NO;
  227. [self _triggerNextDownload];
  228. }
  229. #pragma mark - VLC internal communication and delegate
  230. - (NSArray *)currentListFiles
  231. {
  232. return _currentFileList;
  233. }
  234. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  235. {
  236. if (_listOfGoogleDriveFilesToDownload)
  237. return _listOfGoogleDriveFilesToDownload.count;
  238. return 0;
  239. }
  240. @end