VLCBoxTableViewController.m 13.2 KB
Newer Older
Carola Nitz's avatar
Carola Nitz committed
1 2 3 4
/*****************************************************************************
 * VLCBoxTableViewController.m
 * VLC for iOS
 *****************************************************************************
5
 * Copyright (c) 2014-2015 VideoLAN. All rights reserved.
Carola Nitz's avatar
Carola Nitz committed
6 7 8 9 10 11 12 13
 * $Id$
 *
 * Authors: Carola Nitz <nitz.carola # googlemail.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

#import "VLCBoxTableViewController.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
14
#import "VLCCloudStorageTableViewCell.h"
Carola Nitz's avatar
Carola Nitz committed
15
#import "VLCBoxController.h"
16
#import <XKKeychain/XKKeychainGenericPasswordItem.h>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
17
#import "UIDevice+VLC.h"
18
#import "VLCPlaybackController.h"
19
#import "VLC-Swift.h"
Carola Nitz's avatar
Carola Nitz committed
20

Felix Paul Kühne's avatar
Felix Paul Kühne committed
21
#if TARGET_OS_IOS
22
@interface VLCBoxTableViewController () <VLCCloudStorageTableViewCell, BoxAuthorizationViewControllerDelegate, VLCCloudStorageDelegate, NSURLConnectionDataDelegate>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
23
#else
24
@interface VLCBoxTableViewController () <VLCCloudStorageTableViewCell, VLCCloudStorageDelegate, NSURLConnectionDataDelegate>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
25
#endif
Carola Nitz's avatar
Carola Nitz committed
26 27 28
{
    BoxFile *_selectedFile;
    VLCBoxController *_boxController;
29
    NSArray *_listOfFiles;
Carola Nitz's avatar
Carola Nitz committed
30 31 32 33 34 35
}

@end

@implementation VLCBoxTableViewController

36 37 38 39 40 41 42 43 44
- (instancetype)initWithPath:(NSString *)path
{
    self = [super init];
    if (self) {
        self.currentPath = path;
    }
    return self;
}

Carola Nitz's avatar
Carola Nitz committed
45 46 47 48
- (void)viewDidLoad
{
    [super viewDidLoad];

49
    _boxController = [VLCBoxController sharedInstance];
50 51
    self.controller = _boxController;
    self.controller.delegate = self;
Carola Nitz's avatar
Carola Nitz committed
52

53
#if TARGET_OS_IOS
54
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Box"]];
Carola Nitz's avatar
Carola Nitz committed
55

56
    [self.cloudStorageLogo setImage:[UIImage imageNamed:@"Box"]];
Carola Nitz's avatar
Carola Nitz committed
57

58 59
    [self.cloudStorageLogo sizeToFit];
    self.cloudStorageLogo.center = self.view.center;
60 61
#else
    self.title = @"Box";
62 63
#endif

Carola Nitz's avatar
Carola Nitz committed
64
    // Handle logged in
Felix Paul Kühne's avatar
Felix Paul Kühne committed
65 66 67 68 69
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(boxApiTokenDidRefresh)
                          name:BoxOAuth2SessionDidRefreshTokensNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];
Carola Nitz's avatar
Carola Nitz committed
70

Felix Paul Kühne's avatar
Felix Paul Kühne committed
71 72 73 74
    [defaultCenter addObserver:self
                      selector:@selector(boxApiTokenDidRefresh)
                          name:BoxOAuth2SessionDidBecomeAuthenticatedNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];
75 76

#if TARGET_OS_IOS
Carola Nitz's avatar
Carola Nitz committed
77
    // Handle logout
Felix Paul Kühne's avatar
Felix Paul Kühne committed
78 79 80 81 82 83 84 85
    [defaultCenter addObserver:self
                      selector:@selector(boxDidGetLoggedOut)
                          name:BoxOAuth2SessionDidReceiveAuthenticationErrorNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];
    [defaultCenter addObserver:self
                      selector:@selector(boxDidGetLoggedOut)
                          name:BoxOAuth2SessionDidReceiveRefreshErrorNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];
Carola Nitz's avatar
Carola Nitz committed
86

Felix Paul Kühne's avatar
Felix Paul Kühne committed
87 88 89 90 91 92 93 94
    [defaultCenter addObserver:self
                      selector:@selector(boxAPIAuthenticationDidFail)
                          name:BoxOAuth2SessionDidReceiveAuthenticationErrorNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];
    [defaultCenter addObserver:self
                      selector:@selector(boxAPIInitiateLogin)
                          name:BoxOAuth2SessionDidReceiveRefreshErrorNotification
                        object:[BoxSDK sharedSDK].OAuth2Session];
95
#endif
Carola Nitz's avatar
Carola Nitz committed
96 97
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
98
#if TARGET_OS_IOS
Carola Nitz's avatar
Carola Nitz committed
99 100 101
- (UIViewController *)createAuthController
{
    NSURL *authorizationURL = [[BoxSDK sharedSDK].OAuth2Session authorizeURL];
102 103
    NSString *redirectURLString = [[BoxSDK sharedSDK].OAuth2Session redirectURIString];
    BoxAuthorizationViewController *authorizationController = [[BoxAuthorizationViewController alloc] initWithAuthorizationURL:authorizationURL redirectURI:redirectURLString];
Carola Nitz's avatar
Carola Nitz committed
104 105 106
    authorizationController.delegate = self;
    return authorizationController;
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
107
#endif
Carola Nitz's avatar
Carola Nitz committed
108 109 110

- (void)viewWillAppear:(BOOL)animated
{
111
    [super viewWillAppear:animated];
112 113 114 115 116 117

    _boxController = [VLCBoxController sharedInstance];
    self.controller = _boxController;
    self.controller.delegate = self;

    if (!_listOfFiles || _listOfFiles.count == 0)
118
        [self requestInformationForCurrentPath];
Carola Nitz's avatar
Carola Nitz committed
119 120 121 122
}

- (void)viewWillDisappear:(BOOL)animated
{
123
    [super viewWillDisappear:animated];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
124
    if ([UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController == nil) {
Carola Nitz's avatar
Carola Nitz committed
125 126 127 128 129 130 131
        [_boxController stopSession];
        [self.tableView reloadData];
    }
}

#pragma mark - Table view data source

132 133 134 135 136 137
- (void)mediaListUpdated
{
    _listOfFiles = [[VLCBoxController sharedInstance].currentListFiles copy];
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}

138
- (VLCCloudStorageTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Carola Nitz's avatar
Carola Nitz committed
139 140 141 142 143 144 145
{
    static NSString *CellIdentifier = @"BoxCell";

    VLCCloudStorageTableViewCell *cell = (VLCCloudStorageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [VLCCloudStorageTableViewCell cellWithReuseIdentifier:CellIdentifier];

146 147 148 149 150 151 152
    NSUInteger index = indexPath.row;
    if (_listOfFiles) {
        if (index < _listOfFiles.count) {
            cell.boxFile = _listOfFiles[index];
            cell.delegate = self;
        }
    }
Carola Nitz's avatar
Carola Nitz committed
153 154 155 156

    return cell;
}

157 158 159 160 161
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _listOfFiles.count;
}

Carola Nitz's avatar
Carola Nitz committed
162 163
#pragma mark - Table view delegate

164

Carola Nitz's avatar
Carola Nitz committed
165 166
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
167
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
168
    if (indexPath.row >= _listOfFiles.count)
169 170
        return;

171
    _selectedFile = _listOfFiles[indexPath.row];
172
    if (![_selectedFile.type isEqualToString:@"folder"])
173
        [self streamFile:(BoxFile *)_selectedFile];
174
    else {
Carola Nitz's avatar
Carola Nitz committed
175
        /* dive into subdirectory */
176 177 178 179 180 181
        NSString *path = self.currentPath;
        if (![path isEqualToString:@""])
            path = [path stringByAppendingString:@"/"];
        path = [path stringByAppendingString:_selectedFile.modelID];

        self.currentPath = path;
182
        [self requestInformationForCurrentPath];
Carola Nitz's avatar
Carola Nitz committed
183 184 185
    }
}

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
- (void)streamFile:(BoxFile *)file
{
    /* the Box API requires us to set an HTTP header to get the actual URL:
     * curl -L https://api.box.com/2.0/files/FILE_ID/content -H "Authorization: Bearer ACCESS_TOKEN"
     *
     * ... however, libvlc does not support setting custom HTTP headers, so we are resolving the redirect ourselves with a NSURLConnection
     * and pass the final location to libvlc, which does not require a custom HTTP header */

    NSURL *baseURL = [[[BoxSDK sharedSDK] filesManager] URLWithResource:@"files"
                                                                     ID:file.modelID
                                                            subresource:@"content"
                                                                  subID:nil];

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:baseURL
                                                              cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                          timeoutInterval:60];

    [urlRequest setValue:[NSString stringWithFormat:@"Bearer %@", [BoxSDK sharedSDK].OAuth2Session.accessToken] forHTTPHeaderField:@"Authorization"];

    NSURLConnection *theTestConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    [theTestConnection start];
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    if (response != nil) {
        /* we have 1 redirect from the original URL, so as soon as we'd do that,
         * we grab the URL and cancel the connection */
        NSURL *theActualURL = request.URL;

        [connection cancel];

        /* now ask VLC to stream the URL we were just passed */
219 220 221 222
        VLCMedia *media = [VLCMedia mediaWithURL:theActualURL];
        VLCMediaList *medialist = [[VLCMediaList alloc] init];
        [medialist addMedia:media];
        [[VLCPlaybackController sharedInstance] playMediaList:medialist firstIndex:0 subtitlesFilePath:nil];
223 224 225 226 227
    }

    return request;
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
228
#if TARGET_OS_IOS
Carola Nitz's avatar
Carola Nitz committed
229 230
- (void)triggerDownloadForCell:(VLCCloudStorageTableViewCell *)cell
{
231
    _selectedFile = _listOfFiles[[self.tableView indexPathForCell:cell].row];
Carola Nitz's avatar
Carola Nitz committed
232

233
    if (_selectedFile.size.longLongValue < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
234
        /* selected item is a proper file, ask the user if s/he wants to download it */
235
        NSArray<VLCAlertButton *> *buttonsAction = @[[[VLCAlertButton alloc] initWithTitle: NSLocalizedString(@"BUTTON_CANCEL", nil)
236
                                                                                     style: UIAlertActionStyleCancel
237
                                                                                    action: ^(UIAlertAction *action) {
238 239
                                                                                        self->_selectedFile = nil;
                                                                                    }],
240
                                                     [[VLCAlertButton alloc] initWithTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil)
241
                                                                                    action:^(UIAlertAction *action) {
242 243 244
                                                                                        [self->_boxController downloadFileToDocumentFolder:self->_selectedFile];
                                                                                        self->_selectedFile = nil;
                                                                                    }]];
245 246 247 248
        [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DROPBOX_DOWNLOAD", nil)
                                             errorMessage:[NSString stringWithFormat:NSLocalizedString(@"DROPBOX_DL_LONG", nil), _selectedFile.name, [[UIDevice currentDevice] model]]
                                           viewController:self
                                            buttonsAction:buttonsAction];
249
    } else {
250 251
        [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
                                             errorMessage:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _selectedFile.name, [[UIDevice currentDevice] model]]
252
                                           viewController:self];
253
    }
Carola Nitz's avatar
Carola Nitz committed
254 255
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
256
#endif
Carola Nitz's avatar
Carola Nitz committed
257

258
#pragma mark - box controller delegate
Carola Nitz's avatar
Carola Nitz committed
259 260 261

#pragma mark - BoxAuthorizationViewControllerDelegate

Felix Paul Kühne's avatar
Felix Paul Kühne committed
262 263 264
- (void)boxApiTokenDidRefresh
{
    NSString *token = [BoxSDK sharedSDK].OAuth2Session.refreshToken;
265 266 267 268 269 270 271

    XKKeychainGenericPasswordItem *keychainItem = [[XKKeychainGenericPasswordItem alloc] init];
    keychainItem.service = kVLCBoxService;
    keychainItem.account = kVLCBoxAccount;
    keychainItem.secret.stringValue = token;
    [keychainItem saveWithError:nil];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
272 273 274 275 276 277 278 279
    NSUbiquitousKeyValueStore *ubiquitousStore = [NSUbiquitousKeyValueStore defaultStore];
    [ubiquitousStore setString:token forKey:kVLCStoreBoxCredentials];
    [ubiquitousStore synchronize];
    self.authorizationInProgress = YES;
    [self updateViewAfterSessionChange];
    self.authorizationInProgress = NO;
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
280
#if TARGET_OS_IOS
Carola Nitz's avatar
Carola Nitz committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
- (BOOL)authorizationViewController:(BoxAuthorizationViewController *)authorizationViewController shouldLoadReceivedOAuth2RedirectRequest:(NSURLRequest *)request
{
    [[BoxSDK sharedSDK].OAuth2Session performAuthorizationCodeGrantWithReceivedURL:request.URL];
    [self.navigationController popViewControllerAnimated:YES];
    return NO;
}

- (void)authorizationViewControllerDidStartLoading:(BoxAuthorizationViewController *)authorizationViewController
{
    //needs to be implemented
}

- (void)authorizationViewControllerDidFinishLoading:(BoxAuthorizationViewController *)authorizationViewController
{
    //needs to be implemented
}

- (void)boxDidGetLoggedOut
{
300
    [self performSelectorOnMainThread:@selector(showLoginPanel) withObject:nil waitUntilDone:NO];
Carola Nitz's avatar
Carola Nitz committed
301 302 303 304 305 306 307 308 309
}

- (void)boxAPIAuthenticationDidFail
{
    //needs to be implemented
}

- (void)boxAPIInitiateLogin
{
310
    [self performSelectorOnMainThread:@selector(showLoginPanel) withObject:nil waitUntilDone:NO];
Carola Nitz's avatar
Carola Nitz committed
311 312 313 314 315 316
}

- (void)authorizationViewControllerDidCancel:(BoxAuthorizationViewController *)authorizationViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
317
#endif
318

319
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
320
{
321 322 323 324 325
    NSInteger currentOffset = scrollView.contentOffset.y;
    NSInteger maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;

    if (maximumOffset - currentOffset <= - self.tableView.rowHeight) {
        if (_boxController.hasMoreFiles && !self.activityIndicator.isAnimating) {
326
            [self requestInformationForCurrentPath];
327 328 329
        }
    }
}
Carola Nitz's avatar
Carola Nitz committed
330 331
#pragma mark - login dialog

Felix Paul Kühne's avatar
Felix Paul Kühne committed
332
#if TARGET_OS_IOS
Carola Nitz's avatar
Carola Nitz committed
333 334 335
- (IBAction)loginAction:(id)sender
{
    if (![_boxController isAuthorized]) {
336
        self.authorizationInProgress = YES;
Carola Nitz's avatar
Carola Nitz committed
337 338 339 340 341
        [self.navigationController pushViewController:[self createAuthController] animated:YES];
    } else {
        [_boxController logout];
    }
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
342
#endif
Carola Nitz's avatar
Carola Nitz committed
343 344

@end