VLCBoxTableViewController.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*****************************************************************************
  2. * VLCBoxTableViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <nitz.carola # googlemail.com>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. #import "VLCBoxTableViewController.h"
  13. #import "VLCCloudStorageTableViewCell.h"
  14. #import "VLCBoxController.h"
  15. #import <SSKeychain/SSKeychain.h>
  16. #import "UIDevice+VLC.h"
  17. #import "VLCPlaybackController.h"
  18. #if TARGET_OS_IOS
  19. @interface VLCBoxTableViewController () <VLCCloudStorageTableViewCell, BoxAuthorizationViewControllerDelegate, VLCCloudStorageDelegate, NSURLConnectionDataDelegate>
  20. #else
  21. @interface VLCBoxTableViewController () <VLCCloudStorageTableViewCell, VLCCloudStorageDelegate, NSURLConnectionDataDelegate>
  22. #endif
  23. {
  24. BoxFile *_selectedFile;
  25. VLCBoxController *_boxController;
  26. NSArray *_listOfFiles;
  27. }
  28. @end
  29. @implementation VLCBoxTableViewController
  30. - (instancetype)initWithPath:(NSString *)path
  31. {
  32. self = [super init];
  33. if (self) {
  34. self.currentPath = path;
  35. }
  36. return self;
  37. }
  38. - (void)viewDidLoad
  39. {
  40. [super viewDidLoad];
  41. _boxController = [VLCBoxController sharedInstance];
  42. self.controller = _boxController;
  43. self.controller.delegate = self;
  44. #if TARGET_OS_IOS
  45. self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Box"]];
  46. [self.cloudStorageLogo setImage:[UIImage imageNamed:@"Box"]];
  47. [self.cloudStorageLogo sizeToFit];
  48. self.cloudStorageLogo.center = self.view.center;
  49. #else
  50. self.title = @"Box";
  51. #endif
  52. // Handle logged in
  53. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  54. [defaultCenter addObserver:self
  55. selector:@selector(boxApiTokenDidRefresh)
  56. name:BoxOAuth2SessionDidRefreshTokensNotification
  57. object:[BoxSDK sharedSDK].OAuth2Session];
  58. [defaultCenter addObserver:self
  59. selector:@selector(boxApiTokenDidRefresh)
  60. name:BoxOAuth2SessionDidBecomeAuthenticatedNotification
  61. object:[BoxSDK sharedSDK].OAuth2Session];
  62. #if TARGET_OS_IOS
  63. // Handle logout
  64. [defaultCenter addObserver:self
  65. selector:@selector(boxDidGetLoggedOut)
  66. name:BoxOAuth2SessionDidReceiveAuthenticationErrorNotification
  67. object:[BoxSDK sharedSDK].OAuth2Session];
  68. [defaultCenter addObserver:self
  69. selector:@selector(boxDidGetLoggedOut)
  70. name:BoxOAuth2SessionDidReceiveRefreshErrorNotification
  71. object:[BoxSDK sharedSDK].OAuth2Session];
  72. [defaultCenter addObserver:self
  73. selector:@selector(boxAPIAuthenticationDidFail)
  74. name:BoxOAuth2SessionDidReceiveAuthenticationErrorNotification
  75. object:[BoxSDK sharedSDK].OAuth2Session];
  76. [defaultCenter addObserver:self
  77. selector:@selector(boxAPIInitiateLogin)
  78. name:BoxOAuth2SessionDidReceiveRefreshErrorNotification
  79. object:[BoxSDK sharedSDK].OAuth2Session];
  80. #endif
  81. }
  82. #if TARGET_OS_IOS
  83. - (UIViewController *)createAuthController
  84. {
  85. NSURL *authorizationURL = [[BoxSDK sharedSDK].OAuth2Session authorizeURL];
  86. NSString *redirectURLString = [[BoxSDK sharedSDK].OAuth2Session redirectURIString];
  87. BoxAuthorizationViewController *authorizationController = [[BoxAuthorizationViewController alloc] initWithAuthorizationURL:authorizationURL redirectURI:redirectURLString];
  88. authorizationController.delegate = self;
  89. return authorizationController;
  90. }
  91. #endif
  92. - (void)viewWillAppear:(BOOL)animated
  93. {
  94. [super viewWillAppear:animated];
  95. _boxController = [VLCBoxController sharedInstance];
  96. self.controller = _boxController;
  97. self.controller.delegate = self;
  98. if (!_listOfFiles || _listOfFiles.count == 0)
  99. [self requestInformationForCurrentPath];
  100. }
  101. - (void)viewWillDisappear:(BOOL)animated
  102. {
  103. [super viewWillDisappear:animated];
  104. if ([UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController == nil) {
  105. [_boxController stopSession];
  106. [self.tableView reloadData];
  107. }
  108. }
  109. #pragma mark - Table view data source
  110. - (void)mediaListUpdated
  111. {
  112. _listOfFiles = [[VLCBoxController sharedInstance].currentListFiles copy];
  113. [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  114. }
  115. - (VLCCloudStorageTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  116. {
  117. static NSString *CellIdentifier = @"BoxCell";
  118. VLCCloudStorageTableViewCell *cell = (VLCCloudStorageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  119. if (cell == nil)
  120. cell = [VLCCloudStorageTableViewCell cellWithReuseIdentifier:CellIdentifier];
  121. NSUInteger index = indexPath.row;
  122. if (_listOfFiles) {
  123. if (index < _listOfFiles.count) {
  124. cell.boxFile = _listOfFiles[index];
  125. cell.delegate = self;
  126. }
  127. }
  128. return cell;
  129. }
  130. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  131. {
  132. return _listOfFiles.count;
  133. }
  134. #pragma mark - Table view delegate
  135. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  136. {
  137. [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
  138. if (indexPath.row >= _listOfFiles.count)
  139. return;
  140. _selectedFile = _listOfFiles[indexPath.row];
  141. if (![_selectedFile.type isEqualToString:@"folder"])
  142. [self streamFile:(BoxFile *)_selectedFile];
  143. else {
  144. /* dive into subdirectory */
  145. NSString *path = self.currentPath;
  146. if (![path isEqualToString:@""])
  147. path = [path stringByAppendingString:@"/"];
  148. path = [path stringByAppendingString:_selectedFile.modelID];
  149. #if TARGET_OS_TV
  150. VLCBoxTableViewController *targetViewController = [[VLCBoxTableViewController alloc] initWithPath:path];
  151. [self.navigationController pushViewController:targetViewController animated:YES];
  152. #else
  153. self.currentPath = path;
  154. [self requestInformationForCurrentPath];
  155. #endif
  156. }
  157. }
  158. - (void)streamFile:(BoxFile *)file
  159. {
  160. /* the Box API requires us to set an HTTP header to get the actual URL:
  161. * curl -L https://api.box.com/2.0/files/FILE_ID/content -H "Authorization: Bearer ACCESS_TOKEN"
  162. *
  163. * ... however, libvlc does not support setting custom HTTP headers, so we are resolving the redirect ourselves with a NSURLConnection
  164. * and pass the final location to libvlc, which does not require a custom HTTP header */
  165. NSURL *baseURL = [[[BoxSDK sharedSDK] filesManager] URLWithResource:@"files"
  166. ID:file.modelID
  167. subresource:@"content"
  168. subID:nil];
  169. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:baseURL
  170. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  171. timeoutInterval:60];
  172. [urlRequest setValue:[NSString stringWithFormat:@"Bearer %@", [BoxSDK sharedSDK].OAuth2Session.accessToken] forHTTPHeaderField:@"Authorization"];
  173. NSURLConnection *theTestConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
  174. [theTestConnection start];
  175. }
  176. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
  177. {
  178. if (response != nil) {
  179. /* we have 1 redirect from the original URL, so as soon as we'd do that,
  180. * we grab the URL and cancel the connection */
  181. NSURL *theActualURL = request.URL;
  182. [connection cancel];
  183. /* now ask VLC to stream the URL we were just passed */
  184. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  185. [vpc playURL:theActualURL successCallback:nil errorCallback:nil];
  186. #if TARGET_OS_TV
  187. VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];
  188. [self presentViewController:movieVC
  189. animated:YES
  190. completion:nil];
  191. #endif
  192. }
  193. return request;
  194. }
  195. #if TARGET_OS_IOS
  196. - (void)triggerDownloadForCell:(VLCCloudStorageTableViewCell *)cell
  197. {
  198. _selectedFile = _listOfFiles[[self.tableView indexPathForCell:cell].row];
  199. if (_selectedFile.size.longLongValue < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  200. /* selected item is a proper file, ask the user if s/he wants to download it */
  201. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DROPBOX_DOWNLOAD", nil) message:[NSString stringWithFormat:NSLocalizedString(@"DROPBOX_DL_LONG", nil), _selectedFile.name, [[UIDevice currentDevice] model]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:NSLocalizedString(@"BUTTON_DOWNLOAD", nil), nil];
  202. [alert show];
  203. } else {
  204. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil) message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _selectedFile.name, [[UIDevice currentDevice] model]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil) otherButtonTitles:nil];
  205. [alert show];
  206. }
  207. }
  208. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  209. {
  210. if (buttonIndex == 1)
  211. [_boxController downloadFileToDocumentFolder:_selectedFile];
  212. _selectedFile = nil;
  213. }
  214. #endif
  215. #pragma mark - box controller delegate
  216. #pragma mark - BoxAuthorizationViewControllerDelegate
  217. - (void)boxApiTokenDidRefresh
  218. {
  219. NSString *token = [BoxSDK sharedSDK].OAuth2Session.refreshToken;
  220. [SSKeychain setPassword:token forService:kVLCBoxService account:kVLCBoxAccount];
  221. NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
  222. [ubiquitousStore setString:token forKey:kVLCStoreBoxCredentials];
  223. [ubiquitousStore synchronize];
  224. self.authorizationInProgress = YES;
  225. [self updateViewAfterSessionChange];
  226. self.authorizationInProgress = NO;
  227. }
  228. #if TARGET_OS_IOS
  229. - (BOOL)authorizationViewController:(BoxAuthorizationViewController *)authorizationViewController shouldLoadReceivedOAuth2RedirectRequest:(NSURLRequest *)request
  230. {
  231. [[BoxSDK sharedSDK].OAuth2Session performAuthorizationCodeGrantWithReceivedURL:request.URL];
  232. [self.navigationController popViewControllerAnimated:YES];
  233. return NO;
  234. }
  235. - (void)authorizationViewControllerDidStartLoading:(BoxAuthorizationViewController *)authorizationViewController
  236. {
  237. //needs to be implemented
  238. }
  239. - (void)authorizationViewControllerDidFinishLoading:(BoxAuthorizationViewController *)authorizationViewController
  240. {
  241. //needs to be implemented
  242. }
  243. - (void)boxDidGetLoggedOut
  244. {
  245. [self performSelectorOnMainThread:@selector(showLoginPanel) withObject:nil waitUntilDone:NO];
  246. }
  247. - (void)boxAPIAuthenticationDidFail
  248. {
  249. //needs to be implemented
  250. }
  251. - (void)boxAPIInitiateLogin
  252. {
  253. [self performSelectorOnMainThread:@selector(showLoginPanel) withObject:nil waitUntilDone:NO];
  254. }
  255. - (void)authorizationViewControllerDidCancel:(BoxAuthorizationViewController *)authorizationViewController
  256. {
  257. [self.navigationController popViewControllerAnimated:YES];
  258. }
  259. #endif
  260. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  261. {
  262. NSInteger currentOffset = scrollView.contentOffset.y;
  263. NSInteger maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  264. if (maximumOffset - currentOffset <= - self.tableView.rowHeight) {
  265. if (_boxController.hasMoreFiles && !self.activityIndicator.isAnimating) {
  266. [self requestInformationForCurrentPath];
  267. }
  268. }
  269. }
  270. #pragma mark - login dialog
  271. #if TARGET_OS_IOS
  272. - (IBAction)loginAction:(id)sender
  273. {
  274. if (![_boxController isAuthorized]) {
  275. self.authorizationInProgress = YES;
  276. [self.navigationController pushViewController:[self createAuthController] animated:YES];
  277. } else {
  278. [_boxController logout];
  279. }
  280. }
  281. #endif
  282. @end