VLCDownloadViewController.m 16.9 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * VLCDownloadViewController.m
 * VLC for iOS
 *****************************************************************************
5
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
6 7 8 9 10 11 12 13
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *          Gleb Pinigin <gpinigin # gmail.com>
 *          Pierre Sagaspe <pierre.sagaspe # me.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
14

15
#import "VLCDownloadViewController.h"
16
#import "VLCHTTPFileDownloader.h"
17
#import "VLCActivityManager.h"
18
#import "WhiteRaccoon.h"
19
#import "NSString+SupportedMedia.h"
20
#import "VLCHTTPFileDownloader.h"
21

22 23 24 25 26
typedef NS_ENUM(NSUInteger, VLCDownloadScheme) {
    VLCDownloadSchemeNone,
    VLCDownloadSchemeHTTP,
    VLCDownloadSchemeFTP
};
27

Pierre SAGASPE's avatar
Pierre SAGASPE committed
28
@interface VLCDownloadViewController () <WRRequestDelegate, UITableViewDataSource, UITableViewDelegate, VLCHTTPFileDownloader, UITextFieldDelegate>
29 30
{
    NSMutableArray *_currentDownloads;
31
    VLCDownloadScheme _currentDownloadType;
32
    NSString *_humanReadableFilename;
Pierre SAGASPE's avatar
Pierre SAGASPE committed
33
    NSMutableArray *_currentDownloadFilename;
34 35
    NSTimeInterval _startDL;

36 37 38
    VLCHTTPFileDownloader *_httpDownloader;

    WRRequestDownload *_FTPDownloadRequest;
39
    NSTimeInterval _lastStatsUpdate;
40
    CGFloat _averageSpeed;
41 42

    UIBackgroundTaskIdentifier _backgroundTaskIdentifier;
43 44 45
}
@end

46
@implementation VLCDownloadViewController
47

48 49 50 51 52 53 54 55 56 57 58 59
+ (instancetype)sharedInstance
{
    static VLCDownloadViewController *sharedInstance = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
        sharedInstance = [[VLCDownloadViewController alloc] initWithNibName:@"VLCDownloadViewController" bundle:nil];
    });

    return sharedInstance;
}

60 61 62
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
63
    if (self){
64
        _currentDownloads = [[NSMutableArray alloc] init];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
65 66
        _currentDownloadFilename = [[NSMutableArray alloc] init];
    }
67 68 69
    return self;
}

70 71
- (void)viewDidLoad
{
72 73
    [super viewDidLoad];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
74 75
    NSAttributedString *coloredAttributedPlaceholder = [[NSAttributedString alloc] initWithString:@"http://myserver.com/file.mkv" attributes:@{NSForegroundColorAttributeName: [UIColor VLCLightTextColor]}];
    self.urlField.attributedPlaceholder = coloredAttributedPlaceholder;
76

77
    [self.downloadButton setTitle:NSLocalizedString(@"BUTTON_DOWNLOAD", nil) forState:UIControlStateNormal];
78
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
79 80
    self.title = NSLocalizedString(@"DOWNLOAD_FROM_HTTP", nil);
    self.whatToDownloadHelpLabel.text = [NSString stringWithFormat:NSLocalizedString(@"DOWNLOAD_FROM_HTTP_HELP", nil), [[UIDevice currentDevice] model]];
81
    self.urlField.delegate = self;
82
    self.urlField.keyboardType = UIKeyboardTypeURL;
83
    self.progressContainer.hidden = YES;
84
    self.downloadsTable.backgroundColor = [UIColor VLCDarkBackgroundColor];
85
    self.downloadsTable.hidden = YES;
86

Felix Paul Kühne's avatar
Felix Paul Kühne committed
87
    self.edgesForExtendedLayout = UIRectEdgeNone;
88 89 90 91
}

- (void)viewWillAppear:(BOOL)animated
{
92
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
93 94 95 96 97 98
    if ([pasteboard containsPasteboardTypes:@[@"public.url"]]) {
        id pasteboardValue = [pasteboard valueForPasteboardType:@"public.url"];
        if ([pasteboardValue respondsToSelector:@selector(absoluteString)]) {
            self.urlField.text = [pasteboardValue absoluteString];
        }
    }
99
    [self _updateUI];
100 101 102 103
    [super viewWillAppear:animated];
}

#pragma mark - UI interaction
104 105

- (BOOL)shouldAutorotate
106
{
107
    UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
108 109 110 111 112
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        return NO;
    return YES;
}

113 114
- (IBAction)goBack:(id)sender
{
115
    [self.view endEditing:YES];
116
    [[VLCSidebarController sharedInstance] toggleSidebar];
117 118
}

119 120 121 122
- (IBAction)downloadAction:(id)sender
{
    if ([self.urlField.text length] > 0) {
        NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
123 124 125 126 127 128 129 130 131 132
        if (![URLtoSave.lastPathComponent isSupportedFormat] && ![URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
            VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
                                                              message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), URLtoSave.lastPathComponent]
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                    otherButtonTitles:nil];
            [alert show];
            return;
        }
        if (![URLtoSave.scheme isEqualToString:@"http"] & ![URLtoSave.scheme isEqualToString:@"https"] && ![URLtoSave.scheme isEqualToString:@"ftp"]) {
133 134 135 136 137
            VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"SCHEME_NOT_SUPPORTED", nil)
                                                              message:[NSString stringWithFormat:NSLocalizedString(@"SCHEME_NOT_SUPPORTED_LONG", nil), URLtoSave.scheme]
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                    otherButtonTitles:nil];
138
            [alert show];
139
            return;
140
        }
141 142 143 144 145 146 147

        [_currentDownloads addObject:URLtoSave];
        [_currentDownloadFilename addObject:@""];
        self.urlField.text = @"";
        [self.downloadsTable reloadData];
        [self _triggerNextDownload];

148 149 150
    }
}

151 152
- (void)_updateUI
{
153
    _currentDownloadType != VLCDownloadSchemeNone ? [self downloadStarted] : [self downloadEnded];
154 155 156
    [self.downloadsTable reloadData];
}

157
- (VLCHTTPFileDownloader *)httpDownloader
158
{
159 160 161 162 163 164
    if (!_httpDownloader) {
        _httpDownloader = [[VLCHTTPFileDownloader alloc] init];
        _httpDownloader.delegate = self;
    }
    return _httpDownloader;
}
165

166 167 168 169 170 171 172 173 174
#pragma mark - Download management

- (void)_startDownload
{
    [_currentDownloads removeObjectAtIndex:0];
    [_currentDownloadFilename removeObjectAtIndex:0];
    [self _beginBackgroundDownload];
    [self _updateUI];
}
175

176 177 178 179 180 181 182 183
- (void)_downloadSchemeHttp
{
    if (self.httpDownloader.downloadInProgress) {
        return;
    }
    _currentDownloadType = VLCDownloadSchemeHTTP;
    if (![_currentDownloadFilename.firstObject isEqualToString:@""]) {
        _humanReadableFilename = [[_currentDownloadFilename firstObject] stringByRemovingPercentEncoding];
184
        [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject withFileName:_humanReadableFilename];
185
    } else {
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 219 220 221 222
        [self.httpDownloader downloadFileFromURL:_currentDownloads.firstObject];
        _humanReadableFilename = self.httpDownloader.userReadableDownloadName;
    }
    [self _startDownload];
}

- (void)_downloadSchemeFtp
{
    if (_FTPDownloadRequest) {
        return;
    }
    _currentDownloadType = VLCDownloadSchemeFTP;
    [self _downloadFTPFile:_currentDownloads.firstObject];
    _humanReadableFilename = [_currentDownloads.firstObject lastPathComponent];
    [self _startDownload];
}

- (void)_beginBackgroundDownload
{
    if (!_backgroundTaskIdentifier || _backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
        dispatch_block_t expirationHandler = ^{
            APLog(@"Downloads were interrupted after being in background too long, time remaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
            [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
            _backgroundTaskIdentifier = 0;
        };

        _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCDownloader" expirationHandler:expirationHandler];
        if (_backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
            APLog(@"Unable to download");
        }
    }
}

- (void)_triggerNextDownload
{
    if ([_currentDownloads count] == 0) {
        _currentDownloadType = VLCDownloadSchemeNone;
223 224 225 226 227

        if (_backgroundTaskIdentifier && _backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
            _backgroundTaskIdentifier = 0;
        }
228 229 230 231 232 233 234 235 236 237 238 239 240 241
        return;
    }

    [self.activityIndicator startAnimating];
    NSString *downloadScheme = [_currentDownloads.firstObject scheme];

    if ([downloadScheme isEqualToString:@"http"] || [downloadScheme isEqualToString:@"https"]) {
        [self _downloadSchemeHttp];
    } else if ([downloadScheme isEqualToString:@"ftp"]) {
        [self _downloadSchemeFtp];
    } else {
        APLog(@"Unknown download scheme '%@'", downloadScheme);
        [_currentDownloads removeObjectAtIndex:0];
        _currentDownloadType = VLCDownloadSchemeNone;
242
    }
243 244 245 246
}

- (IBAction)cancelDownload:(id)sender
{
247 248 249 250 251 252 253 254
    if (_currentDownloadType == VLCDownloadSchemeHTTP && self.httpDownloader.downloadInProgress) {
        [self.httpDownloader cancelDownload];
    } else if (_currentDownloadType == VLCDownloadSchemeFTP && _FTPDownloadRequest) {
        NSURL *target = _FTPDownloadRequest.downloadLocation;
        [_FTPDownloadRequest destroy];
        [self requestCompleted:_FTPDownloadRequest];

        /* remove partially downloaded content */
255
        [[NSFileManager defaultManager] removeItemAtPath:target.path error:nil];
256
    }
257 258 259 260 261 262 263
}

#pragma mark - VLC HTTP Downloader delegate

- (void)downloadStarted
{
    [self.activityIndicator stopAnimating];
264 265 266 267 268

    VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
    [activityManager networkActivityStopped];
    [activityManager networkActivityStarted];

269
    self.currentDownloadLabel.text = _humanReadableFilename;
270
    self.progressView.progress = 0.;
271
    [self.progressPercent setText:@"0%%"];
272 273 274
    [self.speedRate setText:@"0 Kb/s"];
    [self.timeDL setText:@"00:00:00"];
    _startDL = [NSDate timeIntervalSinceReferenceDate];
275
    self.progressContainer.hidden = NO;
276

277 278 279 280 281
    APLog(@"download started");
}

- (void)downloadEnded
{
282
    [[VLCActivityManager defaultManager] networkActivityStopped];
283
    _currentDownloadType = VLCDownloadSchemeNone;
284
    APLog(@"download ended");
285
    self.progressContainer.hidden = YES;
286 287 288 289 290 291

    [self _triggerNextDownload];
}

- (void)downloadFailedWithErrorDescription:(NSString *)description
{
292 293 294 295 296
    VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", nil)
                                                      message:description
                                                     delegate:self
                                            cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                            otherButtonTitles:nil];
297
    [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
298 299
}

300
- (void)progressUpdatedTo:(CGFloat)percentage receivedDataSize:(CGFloat)receivedDataSize  expectedDownloadSize:(CGFloat)expectedDownloadSize
301
{
302 303 304 305 306 307
    if ((_lastStatsUpdate > 0 && ([NSDate timeIntervalSinceReferenceDate] - _lastStatsUpdate > .5)) || _lastStatsUpdate <= 0) {
        [self.progressPercent setText:[NSString stringWithFormat:@"%.1f%%", percentage*100]];
        [self.timeDL setText:[self calculateRemainingTime:receivedDataSize expectedDownloadSize:expectedDownloadSize]];
        [self.speedRate setText:[self calculateSpeedString:receivedDataSize]];
            _lastStatsUpdate = [NSDate timeIntervalSinceReferenceDate];
    }
308

309 310 311
    [self.progressView setProgress:percentage animated:YES];
}

312
- (NSString*)calculateRemainingTime:(CGFloat)receivedDataSize expectedDownloadSize:(CGFloat)expectedDownloadSize
313
{
314 315 316 317
    CGFloat lastSpeed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
    CGFloat smoothingFactor = 0.005;
    _averageSpeed = isnan(_averageSpeed) ? lastSpeed : smoothingFactor * lastSpeed + (1 - smoothingFactor) * _averageSpeed;
    CGFloat RemainingInSeconds = (expectedDownloadSize - receivedDataSize)/_averageSpeed;
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:RemainingInSeconds];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSString  *remaingTime = [formatter stringFromDate:date];
    return remaingTime;
}

- (NSString*)calculateSpeedString:(CGFloat)receivedDataSize
{
    CGFloat speed = receivedDataSize / ([NSDate timeIntervalSinceReferenceDate] - _startDL);
    NSString *string = [NSByteCountFormatter stringFromByteCount:speed countStyle:NSByteCountFormatterCountStyleDecimal];
    string = [string stringByAppendingString:@"/s"];
    return string;
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
#pragma mark - ftp networking

- (void)_downloadFTPFile:(NSURL *)URLToFile
{
    if (_FTPDownloadRequest)
        return;

    _FTPDownloadRequest = [[WRRequestDownload alloc] init];
    _FTPDownloadRequest.delegate = self;
    _FTPDownloadRequest.passive = YES;

    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *directoryPath = searchPaths[0];
    NSURL *destinationURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directoryPath, URLToFile.lastPathComponent]];
    _FTPDownloadRequest.downloadLocation = destinationURL;

    [_FTPDownloadRequest startWithFullURL:URLToFile];
}

- (void)requestStarted:(WRRequest *)request
{
    [self downloadStarted];
}

- (void)requestCompleted:(WRRequest *)request
{
    _FTPDownloadRequest = nil;
    [self downloadEnded];
}

- (void)requestFailed:(WRRequest *)request
{
    _FTPDownloadRequest = nil;
    [self downloadEnded];
370

371
    VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", nil), request.error.errorCode]
372 373 374 375
                                                       message:request.error.message
                                                      delegate:self
                                             cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                             otherButtonTitles:nil];
376
    [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];
377 378
}

379 380 381 382 383 384 385 386
#pragma mark - table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
387 388
    NSUInteger count = _currentDownloads.count;
    self.downloadsTable.hidden = count > 0 ? NO : YES;
389 390 391 392 393 394 395 396 397 398 399
    return _currentDownloads.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ScheduledDownloadsCell";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.textLabel.textColor = [UIColor whiteColor];
400
        cell.detailTextLabel.textColor = [UIColor VLCLightTextColor];
401 402 403
    }

    NSInteger row = indexPath.row;
Pierre SAGASPE's avatar
Pierre SAGASPE committed
404
    if ([_currentDownloadFilename[row] isEqualToString:@""])
405
        cell.textLabel.text = [[_currentDownloads[row] lastPathComponent] stringByRemovingPercentEncoding];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
406
    else
407
        cell.textLabel.text = [[_currentDownloadFilename[row] lastPathComponent] stringByRemovingPercentEncoding];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
408

409
    cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
410 411 412 413 414 415 416 417

    return cell;
}

#pragma mark - table view delegate

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
418
    cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
419 420 421 422 423 424 425 426 427 428 429
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_currentDownloads removeObjectAtIndex:indexPath.row];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
430
        [_currentDownloadFilename removeObjectAtIndex:indexPath.row];
431 432 433 434
        [tableView reloadData];
    }
}

435
#pragma mark - communication with other VLC objects
Pierre SAGASPE's avatar
Pierre SAGASPE committed
436
- (void)addURLToDownloadList:(NSURL *)aURL fileNameOfMedia:(NSString*) fileName
437 438
{
    [_currentDownloads addObject:aURL];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
439 440 441
    if (!fileName)
        fileName = @"";
    [_currentDownloadFilename addObject:fileName];
442
    [self.downloadsTable reloadData];
443 444 445
    [self _triggerNextDownload];
}

446
#pragma mark - text view delegate
447 448
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
449 450 451 452
    [self.urlField resignFirstResponder];
    return NO;
}

453
@end