VLCDownloadViewController.m 10.2 KB
Newer Older
1
//
2
//  VLCDownloadViewController.m
3 4 5 6 7 8 9 10
//  VLC for iOS
//
//  Created by Felix Paul Kühne on 16.06.13.
//  Copyright (c) 2013 VideoLAN. All rights reserved.
//
//  Refer to the COPYING file of the official project for license.
//

11
#import "VLCDownloadViewController.h"
12
#import "VLCHTTPFileDownloader.h"
13
#import "VLCAppDelegate.h"
14
#import "UIBarButtonItem+Theme.h"
15
#import "WhiteRaccoon.h"
16
#import "NSString+SupportedMedia.h"
17
#import "VLCHTTPFileDownloader.h"
18

19 20 21
#define kVLCDownloadViaHTTP 1
#define kVLCDownloadViaFTP 2

22 23
@interface VLCDownloadViewController () <WRRequestDelegate, UITableViewDataSource, UITableViewDelegate,
                                        VLCHTTPFileDownloader>
24 25
{
    NSMutableArray *_currentDownloads;
26
    NSUInteger _currentDownloadType;
27 28 29 30 31
    NSString *_humanReadableFilename;

    VLCHTTPFileDownloader *_httpDownloader;

    WRRequestDownload *_FTPDownloadRequest;
32 33 34
}
@end

35
@implementation VLCDownloadViewController
36

37 38 39 40 41 42 43 44 45
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
        _currentDownloads = [[NSMutableArray alloc] init];

    return self;
}

46 47
- (void)viewDidLoad
{
48
    [self.downloadButton setTitle:NSLocalizedString(@"BUTTON_DOWNLOAD",@"") forState:UIControlStateNormal];
49
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
50
    self.title = NSLocalizedString(@"DOWNLOAD_FROM_HTTP", @"");
51
    self.whatToDownloadHelpLabel.text = [NSString stringWithFormat:NSLocalizedString(@"DOWNLOAD_FROM_HTTP_HELP", @""), [[UIDevice currentDevice] model]];
52 53 54 55 56
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
57 58
    self.navigationController.navigationBar.translucent = NO;

59 60 61 62 63 64 65 66 67 68 69 70 71 72
    if ([[UIPasteboard generalPasteboard] containsPasteboardTypes:@[@"public.url", @"public.text"]]) {
        NSURL *pasteURL = [[UIPasteboard generalPasteboard] valueForPasteboardType:@"public.url"];
        if (!pasteURL || [[pasteURL absoluteString] isEqualToString:@""]) {
            NSString *pasteString = [[UIPasteboard generalPasteboard] valueForPasteboardType:@"public.text"];
            pasteURL = [NSURL URLWithString:pasteString];
        }

        if (pasteURL && ![[pasteURL scheme] isEqualToString:@""] && ![[pasteURL absoluteString] isEqualToString:@""])
            self.urlField.text = [pasteURL absoluteString];
    }

    [super viewWillAppear:animated];
}

73 74 75 76 77 78 79
- (void)viewWillDisappear:(BOOL)animated
{
    if (SYSTEM_RUNS_IN_THE_FUTURE)
        self.navigationController.navigationBar.translucent = YES;
    [super viewWillDisappear:animated];
}

80
#pragma mark - UI interaction
81 82 83 84 85 86 87
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        return NO;
    return YES;
}

88 89
- (IBAction)goBack:(id)sender
{
90
    [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
91 92
}

93 94 95 96
- (IBAction)downloadAction:(id)sender
{
    if ([self.urlField.text length] > 0) {
        NSURL *URLtoSave = [NSURL URLWithString:self.urlField.text];
97
        if (([URLtoSave.scheme isEqualToString:@"http"] || [URLtoSave.scheme isEqualToString:@"https"] || [URLtoSave.scheme isEqualToString:@"ftp"]) && ![URLtoSave.lastPathComponent.pathExtension isEqualToString:@""]) {
98 99 100 101
            if ([URLtoSave.lastPathComponent isSupportedFormat]) {
                [_currentDownloads addObject:URLtoSave];
                self.urlField.text = @"";
                [self.downloadsTable reloadData];
102

103 104
                [self _triggerNextDownload];
            } else {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
105
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", @"") message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", @""), URLtoSave.lastPathComponent] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
106 107
                [alert show];
            }
108 109 110 111 112 113 114
        }
    }
}

#pragma mark - download management
- (void)_triggerNextDownload
{
115 116 117 118 119 120 121 122 123 124 125
    if (_currentDownloads.count > 0) {
        NSString *downloadScheme = [_currentDownloads[0] scheme];
        if ([downloadScheme isEqualToString:@"http"] || [downloadScheme isEqualToString:@"https"]) {
            if (!_httpDownloader) {
                _httpDownloader = [[VLCHTTPFileDownloader alloc] init];
                _httpDownloader.delegate = self;
            }

            if (!_httpDownloader.downloadInProgress) {
                _currentDownloadType = kVLCDownloadViaHTTP;
                [_httpDownloader downloadFileFromURL:_currentDownloads[0]];
126
                _humanReadableFilename = _httpDownloader.userReadableDownloadName;
127 128 129
            }
        } else if ([downloadScheme isEqualToString:@"ftp"]) {
            _currentDownloadType = kVLCDownloadViaFTP;
130 131
            [self _downloadFTPFile:_currentDownloads[0]];
            _humanReadableFilename = [_currentDownloads[0] lastPathComponent];
132 133
        } else
            APLog(@"Unknown download scheme '%@'", downloadScheme);
134 135 136 137

        [self.activityIndicator startAnimating];
        [_currentDownloads removeObjectAtIndex:0];
        [self.downloadsTable reloadData];
138 139
    } else
        _currentDownloadType = 0;
140 141 142 143
}

- (IBAction)cancelDownload:(id)sender
{
144 145 146
    if (_currentDownloadType == kVLCDownloadViaHTTP) {
        if (_httpDownloader.downloadInProgress)
            [_httpDownloader cancelDownload];
147 148 149 150 151 152 153 154 155 156 157
    } else if (_currentDownloadType == kVLCDownloadViaFTP) {
        if (_FTPDownloadRequest) {
            NSURL *target = _FTPDownloadRequest.downloadLocation;
            [_FTPDownloadRequest destroy];
            [self requestCompleted:_FTPDownloadRequest];

            /* remove partially downloaded content */
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:target.path])
                [fileManager removeItemAtPath:target.path error:nil];
        }
158
    }
159 160 161 162 163 164 165
}

#pragma mark - VLC HTTP Downloader delegate

- (void)downloadStarted
{
    [self.activityIndicator stopAnimating];
166
    self.currentDownloadLabel.text = _humanReadableFilename;
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    self.progressView.progress = 0.;
    self.currentDownloadLabel.hidden = NO;
    self.progressView.hidden = NO;
    self.cancelButton.hidden = NO;
    APLog(@"download started");
}

- (void)downloadEnded
{
    self.currentDownloadLabel.hidden = YES;
    self.progressView.hidden = YES;
    self.cancelButton.hidden = YES;
    APLog(@"download ended");

    [self _triggerNextDownload];
}

- (void)downloadFailedWithErrorDescription:(NSString *)description
{
186 187
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DOWNLOAD_FAILED", @"") message:description delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
    [alert show];
188 189 190 191 192 193 194
}

- (void)progressUpdatedTo:(CGFloat)percentage
{
    [self.progressView setProgress:percentage animated:YES];
}

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 223 224 225 226 227 228
#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];
229 230 231

    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:NSLocalizedString(@"ERROR_NUMBER", @""), request.error.errorCode] message:request.error.message delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
    [alert show];
232 233
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
#pragma mark - table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    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];
        cell.detailTextLabel.textColor = [UIColor colorWithWhite:.72 alpha:1.];
    }

    NSInteger row = indexPath.row;
    cell.textLabel.text = [_currentDownloads[row] lastPathComponent];
258
    cell.detailTextLabel.text = [_currentDownloads[row] absoluteString];
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

    return cell;
}

#pragma mark - table view delegate

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
}

- (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];
        [tableView reloadData];
    }
}

283 284 285 286
#pragma mark - communication with other VLC objects
- (void)addURLToDownloadList:(NSURL *)aURL
{
    [_currentDownloads addObject:aURL];
287
    [self.downloadsTable reloadData];
288 289 290
    [self _triggerNextDownload];
}

291
@end