VLCGoogleDriveController.m 9.5 KB

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