VLCGoogleDriveController.m 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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)streamFile:(GTLDriveFile *)file
  114. {
  115. VLCAppDelegate *appDelegate = (VLCAppDelegate *)[UIApplication sharedApplication].delegate;
  116. [appDelegate openMovieFromURL:[NSURL URLWithString:file.webContentLink]];
  117. }
  118. - (void)_triggerNextDownload
  119. {
  120. if (_listOfGoogleDriveFilesToDownload.count > 0 && !_downloadInProgress) {
  121. [self _reallyDownloadFileToDocumentFolder:_listOfGoogleDriveFilesToDownload[0]];
  122. [_listOfGoogleDriveFilesToDownload removeObjectAtIndex:0];
  123. if ([self.delegate respondsToSelector:@selector(numberOfFilesWaitingToBeDownloadedChanged)])
  124. [self.delegate numberOfFilesWaitingToBeDownloadedChanged];
  125. }
  126. }
  127. - (void)_reallyDownloadFileToDocumentFolder:(GTLDriveFile *)file
  128. {
  129. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  130. NSString *filePath = [searchPaths[0] stringByAppendingFormat:@"/%@", file.originalFilename];
  131. [self loadFile:file intoPath:filePath];
  132. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStarted)])
  133. [self.delegate operationWithProgressInformationStarted];
  134. _downloadInProgress = YES;
  135. }
  136. - (BOOL)_supportedFileExtension:(NSString *)filename
  137. {
  138. if ([filename isSupportedMediaFormat] || [filename isSupportedAudioMediaFormat] || [filename isSupportedSubtitleFormat])
  139. return YES;
  140. return NO;
  141. }
  142. - (void)_listOfGoodFiles
  143. {
  144. NSMutableArray *listOfGoodFilesAndFolders = [[NSMutableArray alloc] init];
  145. for (GTLDriveFile *driveFile in _fileList.items)
  146. {
  147. BOOL isDirectory = [driveFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"];
  148. if (!isDirectory && [self _supportedFileExtension:[NSString stringWithFormat:@".%@",driveFile.fileExtension ]]) {
  149. [listOfGoodFilesAndFolders addObject:driveFile];
  150. }
  151. }
  152. _currentFileList = [_currentFileList count] ? [_currentFileList arrayByAddingObjectsFromArray:listOfGoodFilesAndFolders] : [NSArray arrayWithArray:listOfGoodFilesAndFolders];
  153. if ([_currentFileList count] <= 10 && [self hasMoreFiles]) {
  154. [self requestFileListing];
  155. return;
  156. }
  157. APLog(@"found filtered metadata for %i files", _currentFileList.count);
  158. if ([self.delegate respondsToSelector:@selector(mediaListUpdated)])
  159. [self.delegate mediaListUpdated];
  160. }
  161. - (void)loadFile:(GTLDriveFile*)file intoPath:(NSString*)destinationPath
  162. {
  163. NSString *exportURLStr = file.downloadUrl;
  164. if ([exportURLStr length] > 0) {
  165. NSString *suggestedName = file.originalFilename;
  166. if ([suggestedName length] == 0) {
  167. suggestedName = file.title;
  168. }
  169. NSURL *url = [NSURL URLWithString:exportURLStr];
  170. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  171. GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
  172. fetcher.authorizer = self.driveService.authorizer;
  173. fetcher.downloadPath = destinationPath;
  174. // Fetcher logging can include comments.
  175. [fetcher setCommentWithFormat:@"Downloading \"%@\"", file.title];
  176. __weak GTMHTTPFetcher *weakFetcher = fetcher;
  177. fetcher.receivedDataBlock = ^(NSData *receivedData) {
  178. float progress = (float)weakFetcher.downloadedLength / (float)[file.fileSize longLongValue];
  179. if ([self.delegate respondsToSelector:@selector(currentProgressInformation:)])
  180. [self.delegate currentProgressInformation:progress];
  181. };
  182. [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
  183. if (error == nil) {
  184. [self showAlert:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL_TITLE",nil) message:NSLocalizedString(@"GDRIVE_DOWNLOAD_SUCCESSFUL",nil)];
  185. [self downloadSucessfull];
  186. } else {
  187. [self showAlert:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE_TITLE",nil) message:NSLocalizedString(@"GDRIVE_ERROR_DOWNLOADING_FILE",nil)];
  188. [self downloadFailedWithError:error];
  189. }
  190. }];
  191. }
  192. }
  193. - (void)downloadSucessfull
  194. {
  195. /* update library now that we got a file */
  196. APLog(@"DriveFile download was successful");
  197. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  198. [appDelegate updateMediaList];
  199. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  200. [self.delegate operationWithProgressInformationStopped];
  201. _downloadInProgress = NO;
  202. [self _triggerNextDownload];
  203. }
  204. - (void)downloadFailedWithError:(NSError*)error
  205. {
  206. APLog(@"DriveFile download failed with error %i", error.code);
  207. if ([self.delegate respondsToSelector:@selector(operationWithProgressInformationStopped)])
  208. [self.delegate operationWithProgressInformationStopped];
  209. _downloadInProgress = NO;
  210. [self _triggerNextDownload];
  211. }
  212. #pragma mark - VLC internal communication and delegate
  213. - (NSArray *)currentListFiles
  214. {
  215. return _currentFileList;
  216. }
  217. - (NSInteger)numberOfFilesWaitingToBeDownloaded
  218. {
  219. if (_listOfGoogleDriveFilesToDownload)
  220. return _listOfGoogleDriveFilesToDownload.count;
  221. return 0;
  222. }
  223. @end