VLCBoxTableViewController.m 12 KB

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