VLCGoogleDriveController.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //
  2. // VLCGoogleDriveController.m
  3. // VLC for iOS
  4. //
  5. // Created by Carola Nitz on 21.09.13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCGoogleDriveController.h"
  11. #import "NSString+SupportedMedia.h"
  12. #import "VLCAppDelegate.h"
  13. #import "HTTPMessage.h"
  14. @interface VLCGoogleDriveController ()
  15. {
  16. GTLDriveFileList *_fileList;
  17. GTLServiceTicket *_fileListTicket;
  18. NSError *_fileListFetchError;
  19. NSArray *_currentFileList;
  20. NSMutableArray *_listOfGoogleDriveFilesToDownload;
  21. BOOL _downloadInProgress;
  22. NSInteger _outstandingNetworkRequests;
  23. }
  24. @end
  25. @implementation VLCGoogleDriveController
  26. #pragma mark - session handling
  27. - (void)startSession
  28. {
  29. self.driveService = [[GTLServiceDrive alloc] init];
  30. self.driveService.authorizer = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kVLCGoogleDriveClientID clientSecret:kVLCGoogleDriveClientSecret];
  31. }
  32. - (void)logout
  33. {
  34. [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:kKeychainItemName];
  35. self.driveService.authorizer = nil;
  36. }
  37. - (BOOL)isAuthorized
  38. {
  39. return [((GTMOAuth2Authentication *)self.driveService.authorizer) canAuthorize];;
  40. }
  41. - (void)showAlert:(NSString *)title message:(NSString *)message
  42. {
  43. UIAlertView *alert;
  44. alert = [[UIAlertView alloc] initWithTitle: title
  45. message: message
  46. delegate: nil
  47. cancelButtonTitle: @"OK"
  48. otherButtonTitles: nil];
  49. [alert show];
  50. }
  51. #pragma mark - file management
  52. - (void)requestDirectoryListingAtPath:(NSString *)path
  53. {
  54. if (self.isAuthorized)
  55. [self listFiles];
  56. }
  57. - (void)downloadFileToDocumentFolder:(GTLDriveFile *)file
  58. {
  59. if (![file.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) {
  60. if (!_listOfGoogleDriveFilesToDownload)
  61. _listOfGoogleDriveFilesToDownload = [[NSMutableArray alloc] init];
  62. [_listOfGoogleDriveFilesToDownload addObject:file];
  63. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  64. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  65. [self _triggerNextDownload];
  66. }
  67. }
  68. - (void)listFiles
  69. {
  70. _fileList = nil;
  71. _fileListFetchError = nil;
  72. GTLServiceDrive *service = self.driveService;
  73. GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
  74. query.maxResults = 150;
  75. query.fields = @"items(originalFilename,title,mimeType,fileExtension,fileSize,iconLink)";
  76. //+ (id)queryForChildrenListWithFolderId:(NSString *)folderId;
  77. _fileListTicket = [service executeQuery:query
  78. completionHandler:^(GTLServiceTicket *ticket,
  79. GTLDriveFileList *fileList,
  80. NSError *error) {
  81. // Callback
  82. _fileList = fileList;
  83. _fileListFetchError = error;
  84. _fileListTicket = nil;
  85. [self listOfGoodFilesAndFolders];
  86. }];
  87. }
  88. - (void)_triggerNextDownload
  89. {
  90. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  91. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  92. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  93. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  94. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  95. }
  96. }
  97. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  98. {
  99. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  100. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  101. [self loadFile:file intoPath:filePath];
  102. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  103. [self.delegate operationWithProgressInformationStarted];
  104. _downloadInProgress = YES;
  105. }
  106. - (BOOL)_supportedFileExtension:(NSString *)filename
  107. {
  108. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  109. return YES;
  110. return NO;
  111. }
  112. - (void)listOfGoodFilesAndFolders
  113. {
  114. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  115. for (GTLDriveFile *driveFile in _fileList.items)
  116. {
  117. BOOL isDirectory = [driveFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  118. if (isDirectory || [self _supportedFileExtension:[NSString stringWithFormat:@".%@",driveFile.fileExtension ]]) {
  119. [listOfGoodFilesAndFolders addObject:driveFile];
  120. }
  121. }
  122. _currentFileList = [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  123. APLog(@"found filtered metadata for %i files", _currentFileList.count);
  124. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  125. [self.delegate mediaListUpdated];
  126. }
  127. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  128. {
  129. NSString *exportURLStr = file.downloadUrl;
  130. if ([exportURLStr length] > 0) {
  131. NSString *suggestedName = file.originalFilename;
  132. if ([suggestedName length] == 0) {
  133. suggestedName = file.title;
  134. }
  135. NSURL *url = [NSURL URLWithString:exportURLStr];
  136. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  137. GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
  138. // Requests of user data from Google services must be authorized.
  139. fetcher.authorizer = self.driveService.authorizer;
  140. // The fetcher can save data directly to a file.
  141. fetcher.downloadPath = destinationPath;
  142. // Fetcher logging can include comments.
  143. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.title];
  144. __weak GTMHTTPFetcher *weakFetcher = fetcher;
  145. fetcher.receivedDataBlock = ^(NSData *receivedData) {
  146. float progress = (float)weakFetcher.downloadedLength / (float)[file.fileSize longLongValue];
  147. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  148. [self.delegate currentProgressInformation:progress];
  149. };
  150. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  151. // Callback
  152. //TODO:localize Strings
  153. if (error == nil) {
  154. UIAlertView *alert;
  155. alert = [[UIAlertView alloc] initWithTitle: @"Downloaded"
  156. message: @"your file has been sucessfully downloaded"
  157. delegate: nil
  158. cancelButtonTitle: @"OK"
  159. otherButtonTitles: nil];
  160. [alert show];
  161. [self downloadSucessfull];
  162. } else {
  163. UIAlertView *alert;
  164. alert = [[UIAlertView alloc] initWithTitle: @"Error"
  165. message: @"AN Error occured while downloading"
  166. delegate: nil
  167. cancelButtonTitle: @"OK"
  168. otherButtonTitles: nil];
  169. [alert show];
  170. [self downloadFailedWithError:error];
  171. }
  172. }];
  173. }
  174. }
  175. - (void)downloadSucessfull
  176. {
  177. /* update library now that we got a file */
  178. APLog(@"DriveFile download was sucessful");
  179. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  180. [appDelegate updateMediaList];
  181. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  182. [self.delegate operationWithProgressInformationStopped];
  183. _downloadInProgress = NO;
  184. [self _triggerNextDownload];
  185. }
  186. - (void)downloadFailedWithError:(NSError*)error
  187. {
  188. APLog(@"DriveFile download failed with error %i", error.code);
  189. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  190. [self.delegate operationWithProgressInformationStopped];
  191. _downloadInProgress = NO;
  192. [self _triggerNextDownload];
  193. }
  194. #pragma mark - VLC internal communication and delegate
  195. - (NSArray *)currentListFiles
  196. {
  197. return _currentFileList;
  198. }
  199. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  200. {
  201. if (_listOfGoogleDriveFilesToDownload)
  202. return _listOfGoogleDriveFilesToDownload.count;
  203. return 0;
  204. }
  205. @end