VLCGoogleDriveController.m 12 KB

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