VLCGoogleDriveController.m 9.1 KB

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