VLCGoogleDriveController.m 8.6 KB

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