VLCGoogleDriveTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*****************************************************************************
  2. * VLCGoogleDriveTableViewController.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 "VLCGoogleDriveTableViewController.h"
  14. #import "VLCCloudStorageTableViewCell.h"
  15. #import "VLCGoogleDriveController.h"
  16. #import "VLCAppDelegate.h"
  17. #import "UIBarButtonItem+Theme.h"
  18. @interface VLCGoogleDriveTableViewController () <VLCCloudStorageTableViewCell, VLCGoogleDriveController>
  19. {
  20. GTLDriveFile *_selectedFile;
  21. GTMOAuth2ViewControllerTouch *_authController;
  22. NSString *_currentFolderId;
  23. UIBarButtonItem *_backButton;
  24. UIBarButtonItem *_backToMenuButton;
  25. UIBarButtonItem *_numberOfFilesBarButtonItem;
  26. UIBarButtonItem *_progressBarButtonItem;
  27. UIProgressView *_progressBar;
  28. UILabel *_progressLabel;
  29. UIActivityIndicatorView *_activityIndicator;
  30. BOOL _authorizationInProgress;
  31. VLCGoogleDriveController *_googleDriveController;
  32. }
  33. @end
  34. @implementation VLCGoogleDriveTableViewController
  35. - (void)viewDidLoad
  36. {
  37. [super viewDidLoad];
  38. self.modalPresentationStyle = UIModalPresentationFormSheet;
  39. _googleDriveController = [VLCGoogleDriveController sharedInstance];
  40. _googleDriveController.delegate = self;
  41. [_googleDriveController startSession];
  42. _authorizationInProgress = NO;
  43. self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"DriveWhite"]];
  44. self.navigationItem.titleView.contentMode = UIViewContentModeScaleAspectFit;
  45. _backButton = [UIBarButtonItem themedBackButtonWithTarget:self andSelector:@selector(goBack:)];
  46. _backToMenuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
  47. self.navigationItem.leftBarButtonItem = _backToMenuButton;
  48. self.tableView.rowHeight = [VLCCloudStorageTableViewCell heightOfCell];
  49. self.tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
  50. self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  51. _numberOfFilesBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"NUM_OF_FILES", @""), 0] style:UIBarButtonItemStylePlain target:nil action:nil];
  52. [_numberOfFilesBarButtonItem setTitleTextAttributes:@{ UITextAttributeFont : [UIFont systemFontOfSize:11.] } forState:UIControlStateNormal];
  53. _progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
  54. _progressLabel = [[UILabel alloc] init];
  55. _progressLabel.textColor = [UIColor whiteColor];
  56. _progressLabel.backgroundColor = [UIColor clearColor];
  57. _progressLabel.font = [UIFont systemFontOfSize:11.];
  58. UIView *progressView = [[UIView alloc] init];
  59. [progressView addSubview:_progressBar];
  60. [progressView addSubview:_progressLabel];
  61. [progressView addConstraint:[NSLayoutConstraint constraintWithItem:progressView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_progressLabel attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];
  62. [progressView addConstraint:[NSLayoutConstraint constraintWithItem:_progressBar attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_progressLabel attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];
  63. [progressView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_progressBar]-[_progressLabel]-|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(_progressBar, _progressLabel)]];
  64. progressView.translatesAutoresizingMaskIntoConstraints = NO;
  65. _progressLabel.translatesAutoresizingMaskIntoConstraints = NO;
  66. _progressBar.translatesAutoresizingMaskIntoConstraints = NO;
  67. _progressBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:progressView];
  68. [self.cloudStorageLogo setImage:[UIImage imageNamed:@"DriveWhite"]];
  69. if (!SYSTEM_RUNS_IOS7_OR_LATER) {
  70. self.flatLoginButton.hidden = YES;
  71. [self.loginButton setTitle:NSLocalizedString(@"DROPBOX_LOGIN", @"") forState:UIControlStateNormal];
  72. } else {
  73. self.loginButton.hidden = YES;
  74. [self.flatLoginButton setTitle:NSLocalizedString(@"DROPBOX_LOGIN", @"") forState:UIControlStateNormal];
  75. }
  76. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"sudHeaderBg"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  77. [self _showProgressInToolbar:NO];
  78. _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  79. _activityIndicator.hidesWhenStopped = YES;
  80. [self.view addSubview:_activityIndicator];
  81. }
  82. - (GTMOAuth2ViewControllerTouch *)createAuthController
  83. {
  84. _authController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive
  85. clientID:kVLCGoogleDriveClientID
  86. clientSecret:kVLCGoogleDriveClientSecret
  87. keychainItemName:kKeychainItemName
  88. delegate:self
  89. finishedSelector:@selector(viewController:finishedWithAuth:error:)];
  90. return _authController;
  91. }
  92. - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)authResult error:(NSError *)error
  93. {
  94. _authorizationInProgress = NO;
  95. if (error != nil) {
  96. _googleDriveController.driveService.authorizer = nil;
  97. } else {
  98. _googleDriveController.driveService.authorizer = authResult;
  99. }
  100. [self updateViewAfterSessionChange];
  101. }
  102. - (void)viewWillAppear:(BOOL)animated
  103. {
  104. self.navigationController.toolbarHidden = NO;
  105. self.navigationController.toolbar.barStyle = UIBarStyleBlack;
  106. [self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"bottomBlackBar"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
  107. [self updateViewAfterSessionChange];
  108. [super viewWillAppear:animated];
  109. CGRect aiFrame = _activityIndicator.frame;
  110. CGSize tvSize = self.tableView.frame.size;
  111. aiFrame.origin.x = (tvSize.width - aiFrame.size.width) / 2.;
  112. aiFrame.origin.y = (tvSize.height - aiFrame.size.height) / 2.;
  113. _activityIndicator.frame = aiFrame;
  114. [self.cloudStorageLogo sizeToFit];
  115. self.cloudStorageLogo.center = self.view.center;
  116. }
  117. - (void)viewWillDisappear:(BOOL)animated
  118. {
  119. self.navigationController.toolbarHidden = YES;
  120. if ((VLCAppDelegate*)[UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController == nil) {
  121. [_googleDriveController stopSession];
  122. [self.tableView reloadData];
  123. }
  124. [super viewWillDisappear:animated];
  125. }
  126. - (void)_showProgressInToolbar:(BOOL)value
  127. {
  128. if (!value)
  129. [self setToolbarItems:@[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], _numberOfFilesBarButtonItem, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]] animated:YES];
  130. else {
  131. _progressBar.progress = 0.;
  132. [self setToolbarItems:@[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], _progressBarButtonItem, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]] animated:YES];
  133. }
  134. }
  135. - (void)_requestInformationForCurrentFolderId
  136. {
  137. [_activityIndicator startAnimating];
  138. [_googleDriveController requestDirectoryListingWithFolderId:_currentFolderId];
  139. self.navigationItem.leftBarButtonItem = ![_currentFolderId isEqualToString:@""] ? _backButton : _backToMenuButton;
  140. }
  141. #pragma mark - interface interaction
  142. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
  143. {
  144. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  145. return NO;
  146. return YES;
  147. }
  148. - (IBAction)goBack:(id)sender
  149. {
  150. if (![_currentFolderId isEqualToString:@""] && [_currentFolderId length] > 0) {
  151. _currentFolderId = [_currentFolderId stringByDeletingLastPathComponent];
  152. [self _requestInformationForCurrentFolderId];
  153. } else
  154. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  155. }
  156. #pragma mark - Table view data source
  157. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  158. {
  159. return 1;
  160. }
  161. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  162. {
  163. return _googleDriveController.currentListFiles.count;
  164. }
  165. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  166. {
  167. static NSString *CellIdentifier = @"GoogleDriveCell";
  168. VLCCloudStorageTableViewCell *cell = (VLCCloudStorageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  169. if (cell == nil)
  170. cell = [VLCCloudStorageTableViewCell cellWithReuseIdentifier:CellIdentifier];
  171. cell.driveFile = _googleDriveController.currentListFiles[indexPath.row];
  172. cell.delegate = self;
  173. return cell;
  174. }
  175. #pragma mark - Table view delegate
  176. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  177. {
  178. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  179. }
  180. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  181. {
  182. _selectedFile = _googleDriveController.currentListFiles[indexPath.row];
  183. if (![_selectedFile.mimeType isEqualToString:@"application/vnd.google-apps.folder"]) {
  184. [_googleDriveController streamFile:_selectedFile];
  185. } else {
  186. /* dive into subdirectory */
  187. if (![_currentFolderId isEqualToString:@""])
  188. _currentFolderId = [_currentFolderId stringByAppendingString:@"/"];
  189. _currentFolderId = [_currentFolderId stringByAppendingString:_selectedFile.identifier];
  190. [self _requestInformationForCurrentFolderId];
  191. }
  192. [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
  193. }
  194. - (void)triggerDownloadForCell:(VLCCloudStorageTableViewCell *)cell
  195. {
  196. _selectedFile = _googleDriveController.currentListFiles[[self.tableView indexPathForCell:cell].row];
  197. /* selected item is a proper file, ask the user if s/he wants to download it */
  198. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DROPBOX_DOWNLOAD", @"") message:[NSString stringWithFormat:NSLocalizedString(@"DROPBOX_DL_LONG", @""), _selectedFile.title, [[UIDevice currentDevice] model]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:NSLocalizedString(@"BUTTON_DOWNLOAD", @""), nil];
  199. [alert show];
  200. }
  201. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  202. {
  203. NSInteger currentOffset = scrollView.contentOffset.y;
  204. NSInteger maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  205. if (maximumOffset - currentOffset <= - self.tableView.rowHeight) {
  206. if (_googleDriveController.hasMoreFiles && !_activityIndicator.isAnimating) {
  207. [self _requestInformationForCurrentFolderId];
  208. }
  209. }
  210. }
  211. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  212. {
  213. if (buttonIndex == 1)
  214. [_googleDriveController downloadFileToDocumentFolder:_selectedFile];
  215. _selectedFile = nil;
  216. }
  217. #pragma mark - google drive controller delegate
  218. - (void)mediaListUpdated
  219. {
  220. [_activityIndicator stopAnimating];
  221. [self.tableView reloadData];
  222. NSUInteger count = _googleDriveController.currentListFiles.count;
  223. if (count == 0)
  224. _numberOfFilesBarButtonItem.title = NSLocalizedString(@"NO_FILES", @"");
  225. else if (count != 1)
  226. _numberOfFilesBarButtonItem.title = [NSString stringWithFormat:NSLocalizedString(@"NUM_OF_FILES", @""), count];
  227. else
  228. _numberOfFilesBarButtonItem.title = NSLocalizedString(@"ONE_FILE", @"");
  229. }
  230. - (void)operationWithProgressInformationStarted
  231. {
  232. [self _showProgressInToolbar:YES];
  233. }
  234. - (void)updateRemainingTime:(NSString *)time
  235. {
  236. [_progressLabel setText:[NSString stringWithFormat:NSLocalizedString(@"REMAINING_TIME", nil), time]];
  237. CGSize size = [_progressLabel.text sizeWithFont:_progressLabel.font];
  238. [_progressLabel setFrame:CGRectMake(_progressLabel.frame.origin.x, _progressLabel.frame.origin.y, size.width, size.height)];
  239. }
  240. - (void)currentProgressInformation:(float)progress {
  241. [_progressBar setProgress:progress animated:YES];
  242. }
  243. - (void)operationWithProgressInformationStopped
  244. {
  245. [self _showProgressInToolbar:NO];
  246. }
  247. #pragma mark - communication with app delegate
  248. - (void)updateViewAfterSessionChange
  249. {
  250. if(_authorizationInProgress) {
  251. if (self.loginToCloudStorageView.superview)
  252. [self.loginToCloudStorageView removeFromSuperview];
  253. return;
  254. }
  255. if (![_googleDriveController isAuthorized]) {
  256. [self _showLoginPanel];
  257. return;
  258. } else if (self.loginToCloudStorageView.superview)
  259. [self.loginToCloudStorageView removeFromSuperview];
  260. //reload if we didn't come back from streaming
  261. _currentFolderId = @"";
  262. if([_googleDriveController.currentListFiles count] == 0)
  263. [self _requestInformationForCurrentFolderId];
  264. }
  265. #pragma mark - login dialog
  266. - (void)_showLoginPanel
  267. {
  268. self.loginToCloudStorageView.frame = self.tableView.frame;
  269. [self.view addSubview:self.loginToCloudStorageView];
  270. }
  271. - (IBAction)loginAction:(id)sender
  272. {
  273. if (![_googleDriveController isAuthorized]) {
  274. _authorizationInProgress = YES;
  275. [self.navigationController pushViewController:[self createAuthController] animated:YES];
  276. } else {
  277. [_googleDriveController logout];
  278. }
  279. }
  280. @end