VLCBoxTableViewController.m 13 KB

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