VLCGoogleDriveController.m 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. }
  26. @end
  27. @implementation VLCGoogleDriveController
  28. #pragma mark - session handling
  29. + (VLCGoogleDriveController *)sharedInstance
  30. {
  31. static VLCGoogleDriveController *sharedInstance = nil;
  32. static dispatch_once_t pred;
  33. dispatch_once(&pred, ^{
  34. sharedInstance = [[self alloc] init];
  35. });
  36. return sharedInstance;
  37. }
  38. - (void)startSession
  39. {
  40. self.driveService = [[GTLServiceDrive alloc] init];
  41. self.driveService.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kVLCGoogleDriveClientID clientSecret:kVLCGoogleDriveClientSecret];
  42. }
  43. - (void)stopSession
  44. {
  45. [_fileListTicket cancelTicket];
  46. _nextPageToken = nil;
  47. _currentFileList = nil;
  48. }
  49. - (void)logout
  50. {
  51. [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemName];
  52. self.driveService.authorizer = nil;
  53. _currentFileList = nil;
  54. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  55. [self.delegate mediaListUpdated];
  56. }
  57. - (BOOL)isAuthorized
  58. {
  59. return [((GTMOAuth2Authentication *)self.driveService.authorizer) canAuthorize];;
  60. }
  61. - (void)showAlert:(NSString *)title message:(NSString *)message
  62. {
  63. UIAlertView *alert;
  64. alert = [[UIAlertView alloc] initWithTitle: title
  65. message: message
  66. delegate: nil
  67. cancelButtonTitle: @"OK"
  68. otherButtonTitles: nil];
  69. [alert show];
  70. }
  71. #pragma mark - file management
  72. - (void)requestFileListing
  73. {
  74. if (self.isAuthorized)
  75. [self listFiles];
  76. }
  77. - (BOOL)hasMoreFiles
  78. {
  79. return _nextPageToken != nil;
  80. }
  81. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  82. {
  83. if (!_listOfGoogleDriveFilesToDownload)
  84. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  85. [_listOfGoogleDriveFilesToDownload addObject:file];
  86. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  87. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  88. [self _triggerNextDownload];
  89. }
  90. - (void)listFiles
  91. {
  92. _fileList = nil;
  93. GTLQueryDrive *query;
  94. query = [GTLQueryDrive queryForFilesList];
  95. query.fields = @"items(originalFilename,title,mimeType,fileExtension,fileSize,iconLink,downloadUrl,webContentLink),nextPageToken";
  96. query.pageToken = _nextPageToken;
  97. query.maxResults = 100;
  98. APLog(@"fetching files with following queryfields:%@", query.fields);
  99. _fileListTicket = [self.driveService executeQuery:query
  100. completionHandler:^(GTLServiceTicket *ticket,
  101. GTLDriveFileList *fileList,
  102. NSError *error) {
  103. if (error == nil) {
  104. _fileList = fileList;
  105. _nextPageToken = fileList.nextPageToken;
  106. _fileListTicket = nil;
  107. [self _listOfGoodFiles];
  108. } else {
  109. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_FETCHING_FILES",nil) message:error.localizedDescription];
  110. }
  111. }];
  112. }
  113. - (void)_triggerNextDownload
  114. {
  115. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  116. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  117. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  118. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  119. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  120. }
  121. }
  122. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  123. {
  124. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  125. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  126. [self loadFile:file intoPath:filePath];
  127. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  128. [self.delegate operationWithProgressInformationStarted];
  129. _downloadInProgress = YES;
  130. }
  131. - (BOOL)_supportedFileExtension:(NSString *)filename
  132. {
  133. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  134. return YES;
  135. return NO;
  136. }
  137. - (void)_listOfGoodFiles
  138. {
  139. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  140. for (GTLDriveFile *driveFile in _fileList.items)
  141. {
  142. BOOL isDirectory = [driveFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  143. if (!isDirectory && [self _supportedFileExtension:[NSString stringWithFormat:@".%@",driveFile.fileExtension ]]) {
  144. [listOfGoodFilesAndFolders addObject:driveFile];
  145. }
  146. }
  147. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  148. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  149. [self requestFileListing];
  150. return;
  151. }
  152. APLog(@"found filtered metadata for %i files", _currentFileList.count);
  153. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  154. [self.delegate mediaListUpdated];
  155. }
  156. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  157. {
  158. NSString *exportURLStr = file.downloadUrl;
  159. if ([exportURLStr length] > 0) {
  160. NSString *suggestedName = file.originalFilename;
  161. if ([suggestedName length] == 0) {
  162. suggestedName = file.title;
  163. }
  164. NSURL *url = [NSURL URLWithString:exportURLStr];
  165. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  166. GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
  167. fetcher.authorizer = self.driveService.authorizer;
  168. fetcher.downloadPath = destinationPath;
  169. // Fetcher logging can include comments.
  170. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.title];
  171. __weak GTMHTTPFetcher *weakFetcher = fetcher;
  172. fetcher.receivedDataBlock = ^(NSData *receivedData) {
  173. float progress = (float)weakFetcher.downloadedLength / (float)[file.fileSize longLongValue];
  174. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  175. [self.delegate currentProgressInformation:progress];
  176. };
  177. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  178. if (error == nil) {
  179. [self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  180. [self downloadSucessfull];
  181. } else {
  182. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  183. [self downloadFailedWithError:error];
  184. }
  185. }];
  186. }
  187. }
  188. - (void)downloadSucessfull
  189. {
  190. /* update library now that we got a file */
  191. APLog(@"DriveFile download was successful");
  192. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  193. [appDelegate updateMediaList];
  194. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  195. [self.delegate operationWithProgressInformationStopped];
  196. _downloadInProgress = NO;
  197. [self _triggerNextDownload];
  198. }
  199. - (void)downloadFailedWithError:(NSError*)error
  200. {
  201. APLog(@"DriveFile download failed with error %i", error.code);
  202. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  203. [self.delegate operationWithProgressInformationStopped];
  204. _downloadInProgress = NO;
  205. [self _triggerNextDownload];
  206. }
  207. #pragma mark - VLC internal communication and delegate
  208. - (NSArray *)currentListFiles
  209. {
  210. return _currentFileList;
  211. }
  212. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  213. {
  214. if (_listOfGoogleDriveFilesToDownload)
  215. return _listOfGoogleDriveFilesToDownload.count;
  216. return 0;
  217. }
  218. @end