VLCLocalServerFolderListViewController.m 15.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
//  VLCLocalServerFolderListViewController.m
//  VLC for iOS
//
//  Created by Felix Paul Kühne on 10.08.13.
//  Copyright (c) 2013 VideoLAN. All rights reserved.
//
//  Refer to the COPYING file of the official project for license.
//

#import "VLCLocalServerFolderListViewController.h"
#import "MediaServerBasicObjectParser.h"
#import "MediaServer1ItemObject.h"
#import "MediaServer1ContainerObject.h"
#import "MediaServer1Device.h"
#import "VLCLocalNetworkListCell.h"
17 18 19
#import "VLCAppDelegate.h"
#import "VLCPlaylistViewController.h"
#import "UINavigationController+Theme.h"
20
#import "VLCDownloadViewController.h"
21
#import "WhiteRaccoon.h"
22
#import "NSString+SupportedMedia.h"
23
#import "VLCStatusLabel.h"
24

25 26
#define kVLCServerTypeUPNP 0
#define kVLCServerTypeFTP 1
27

28
@interface VLCLocalServerFolderListViewController () <UITableViewDataSource, UITableViewDelegate, WRRequestDelegate, VLCLocalNetworkListCell>
29
{
30
    /* UI */
31 32
    UIBarButtonItem *_backButton;

33
    /* generic data storage */
34
    NSString *_listTitle;
35
    NSArray *_objectList;
36
    NSMutableArray *_mutableObjectList;
37 38
    NSUInteger _serverType;

39
    /* UPNP specifics */
40 41
    MediaServer1Device *_UPNPdevice;
    NSString *_UPNProotID;
42 43 44 45 46 47

    /* FTP specifics */
    NSString *_ftpServerAddress;
    NSString *_ftpServerUserName;
    NSString *_ftpServerPassword;
    NSString *_ftpServerPath;
48
    WRRequestListDirectory *_FTPListDirRequest;
49 50 51 52 53 54 55 56 57 58 59 60
}

@end

@implementation VLCLocalServerFolderListViewController

- (void)loadView
{
    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
    _tableView.delegate = self;
    _tableView.dataSource = self;
61
    _tableView.rowHeight = [VLCLocalNetworkListCell heightOfCell];
62 63 64
    self.view = _tableView;
}

65
- (id)initWithUPNPDevice:(MediaServer1Device*)device header:(NSString*)header andRootID:(NSString*)rootID
66 67 68 69
{
    self = [super init];

    if (self) {
70 71 72
        _UPNPdevice = device;
        _listTitle = header;
        _UPNProotID = rootID;
73
        _serverType = kVLCServerTypeUPNP;
74
        _mutableObjectList = [[NSMutableArray alloc] init];
75 76 77 78 79 80 81 82
    }

    return self;
}

- (id)initWithFTPServer:(NSString *)serverAddress userName:(NSString *)username andPassword:(NSString *)password atPath:(NSString *)path
{
    self = [super init];
83

84 85 86 87 88
    if (self) {
        _ftpServerAddress = serverAddress;
        _ftpServerUserName = username;
        _ftpServerPassword = password;
        _ftpServerPath = path;
89
        _serverType = kVLCServerTypeFTP;
90 91 92 93 94 95 96 97 98
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

99
    if (_serverType == kVLCServerTypeUPNP) {
100 101 102 103
        NSMutableString *outResult = [[NSMutableString alloc] init];
        NSMutableString *outNumberReturned = [[NSMutableString alloc] init];
        NSMutableString *outTotalMatches = [[NSMutableString alloc] init];
        NSMutableString *outUpdateID = [[NSMutableString alloc] init];
104

105
        [[_UPNPdevice contentDirectory] BrowseWithObjectID:_UPNProotID BrowseFlag:@"BrowseDirectChildren" Filter:@"*" StartingIndex:@"0" RequestedCount:@"0" SortCriteria:@"+dc:title" OutResult:outResult OutNumberReturned:outNumberReturned OutTotalMatches:outTotalMatches OutUpdateID:outUpdateID];
106

107
        [_mutableObjectList removeAllObjects];
108
        NSData *didl = [outResult dataUsingEncoding:NSUTF8StringEncoding];
109
        MediaServerBasicObjectParser *parser = [[MediaServerBasicObjectParser alloc] initWithMediaObjectArray:_mutableObjectList itemsOnly:NO];
110
        [parser parseFromData:didl];
111
    } else if (_serverType == kVLCServerTypeFTP) {
112 113 114 115 116
        if ([_ftpServerPath isEqualToString:@"/"])
            _listTitle = _ftpServerAddress;
        else
            _listTitle = [_ftpServerPath lastPathComponent];
        [self _listFTPDirectory];
117
    }
118 119 120 121

    self.tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
    self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];

122
    self.title = _listTitle;
123 124
}

125
- (BOOL)shouldAutorotate
126
{
127
    UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
128 129 130 131 132 133 134 135 136 137 138 139 140 141
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        return NO;
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
142
    if (_serverType == kVLCServerTypeUPNP)
143 144
        return _mutableObjectList.count;

145 146 147 148 149 150 151 152 153 154 155
    return _objectList.count;
}

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

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

156
    if (_serverType == kVLCServerTypeUPNP) {
157
        MediaServer1BasicObject *item = _mutableObjectList[indexPath.row];
158
        if (![item isContainer]) {
159
            MediaServer1ItemObject *mediaItem = _mutableObjectList[indexPath.row];
160
            [cell setSubtitle: [NSString stringWithFormat:@"%0.2f MB  (%@)", (float)([mediaItem.size intValue] / 1e6), mediaItem.duration]];
161
            [cell setIsDirectory:NO];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
162
            cell.isDownloadable = YES;
163 164 165 166 167 168 169
            if (![mediaItem.albumArt isEqualToString:NULL]) {
                NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaItem.albumArt]];
                UIImage* image = [[UIImage alloc] initWithData:imageData];
                [cell setIcon:image];
            }
            else
                [cell setIcon:[UIImage imageNamed:@"blank"]];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
170
            cell.delegate = self;
171 172 173 174 175
        } else {
            [cell setIsDirectory:YES];
            [cell setIcon:[UIImage imageNamed:@"folder"]];
        }
        [cell setTitle:[item title]];
176
    } else if (_serverType == kVLCServerTypeFTP) {
177 178 179 180 181 182 183
        cell.title = [_objectList[indexPath.row] objectForKey:(id)kCFFTPResourceName];
        if ([[_objectList[indexPath.row] objectForKey:(id)kCFFTPResourceType] intValue] == 4) {
            cell.isDirectory = YES;
            cell.icon = [UIImage imageNamed:@"folder"];
        } else {
            cell.isDirectory = NO;
            cell.icon = [UIImage imageNamed:@"blank"];
184
            cell.subtitle = [NSString stringWithFormat:@"%0.2f MB", (float)([[_objectList[indexPath.row] objectForKey:(id)kCFFTPResourceSize] intValue] / 1e6)];
185 186
            cell.isDownloadable = YES;
            cell.delegate = self;
187
        }
188
    }
189 190 191 192 193
    return cell;
}

#pragma mark - Table view delegate

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

199 200
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
201
    if (_serverType == kVLCServerTypeUPNP) {
202
        MediaServer1BasicObject *item = _mutableObjectList[indexPath.row];
203
        if ([item isContainer]) {
204
            MediaServer1ContainerObject *container = _mutableObjectList[indexPath.row];
205 206 207
            VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithUPNPDevice:_UPNPdevice header:[container title] andRootID:[container objectID]];
            [[self navigationController] pushViewController:targetViewController animated:YES];
        } else {
208
            MediaServer1ItemObject *item = _mutableObjectList[indexPath.row];
209 210 211 212 213

            MediaServer1ItemRes *resource = nil;
            NSEnumerator *e = [[item resources] objectEnumerator];
            NSURL *itemURL;
            while((resource = (MediaServer1ItemRes*)[e nextObject])){
214
                APLog(@"%@ - %d, %@, %d, %lld, %d, %@ (%@)", [item title], [resource bitrate], [resource duration], [resource nrAudioChannels], [resource size],  [resource durationInSeconds],  [resource protocolInfo], [item uri]);
215 216 217 218 219 220 221 222 223 224 225 226 227 228
                itemURL = [NSURL URLWithString:[item uri]];
            }

            if (itemURL && ([itemURL.scheme isEqualToString:@"http"] || [itemURL.scheme isEqualToString:@"rtsp"] || [itemURL.scheme isEqualToString:@"rtp"] || [itemURL.scheme isEqualToString:@"mms"] || [itemURL.scheme isEqualToString:@"mmsh"])) {
                VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;

                UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:appDelegate.playlistViewController];
                [navController loadTheme];

                appDelegate.revealController.contentViewController = navController;
                [appDelegate.revealController toggleSidebar:NO duration:kGHRevealSidebarDefaultAnimationDuration];

                [appDelegate.playlistViewController performSelector:@selector(openMovieFromURL:) withObject:itemURL afterDelay:kGHRevealSidebarDefaultAnimationDuration];
            }
229
        }
230
    } else if (_serverType == kVLCServerTypeFTP) {
231
        if ([[_objectList[indexPath.row] objectForKey:(id)kCFFTPResourceType] intValue] == 4) {
232
            NSString *newPath = [NSString stringWithFormat:@"%@/%@", _ftpServerPath, [_objectList[indexPath.row] objectForKey:(id)kCFFTPResourceName]];
233 234 235 236

            VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithFTPServer:_ftpServerAddress userName:_ftpServerUserName andPassword:_ftpServerPassword atPath:newPath];
            [self.navigationController pushViewController:targetViewController animated:YES];
        } else {
237 238
            NSString *objectName = [_objectList[indexPath.row] objectForKey:(id)kCFFTPResourceName];
            if (![objectName isSupportedFormat]) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
239
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", @"") message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", @""), objectName] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
240 241
                [alert show];
            } else
242 243
                [self _openURLStringAndDismiss:[_FTPListDirRequest.fullURLString stringByAppendingString:objectName]];
      }
244
    }
245
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
246 247
}

248 249 250
#pragma mark - FTP specifics
- (void)_listFTPDirectory
{
251
    if (_FTPListDirRequest)
252 253
        return;

254 255 256 257 258 259 260
    _FTPListDirRequest = [[WRRequestListDirectory alloc] init];
    _FTPListDirRequest.delegate = self;
    _FTPListDirRequest.hostname = _ftpServerAddress;
    _FTPListDirRequest.username = _ftpServerUserName;
    _FTPListDirRequest.password = _ftpServerPassword;
    _FTPListDirRequest.path = _ftpServerPath;
    _FTPListDirRequest.passive = YES;
261

262 263 264
    [_FTPListDirRequest start];
}

265
- (NSString *)_credentials
266
{
267
    NSString * cred;
268

269 270 271 272 273 274 275
    if (_ftpServerUserName.length > 0) {
        if (_ftpServerPassword.length > 0)
            cred = [NSString stringWithFormat:@"%@:%@@", _ftpServerUserName, _ftpServerPassword];
        else
            cred = [NSString stringWithFormat:@"%@@", _ftpServerPassword];
    } else
        cred = @"";
276

277 278
    return [cred stringByStandardizingPath];
}
279

280 281
- (void)_downloadFTPFile:(NSString *)fileName
{
282
    NSURL *URLToQueue = [NSURL URLWithString:[[@"ftp" stringByAppendingFormat:@"://%@%@/%@/%@", [self _credentials], _ftpServerAddress, _ftpServerPath, fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
283

Pierre SAGASPE's avatar
Pierre SAGASPE committed
284 285 286 287 288 289 290
    [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate downloadViewController] addURLToDownloadList:URLToQueue fileNameOfMedia:nil];
}

- (void)_downloadUPNPFile:(NSURL *)url fileNameOfMedia:(NSString*) fileName;
{
    fileName = [[fileName stringByAppendingString:@"."] stringByAppendingString:[[url absoluteString] pathExtension]];
    [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate downloadViewController] addURLToDownloadList:url fileNameOfMedia:fileName];
291 292 293 294
}

- (void)requestCompleted:(WRRequest *)request
{
295
    if (request == _FTPListDirRequest) {
296 297 298 299 300 301 302 303 304 305 306
        NSMutableArray *filteredList = [[NSMutableArray alloc] init];
        NSArray *rawList = [(WRRequestListDirectory*)request filesInfo];
        NSUInteger count = rawList.count;

        for (NSUInteger x = 0; x < count; x++) {
            if (![[rawList[x] objectForKey:(id)kCFFTPResourceName] hasPrefix:@"."])
                [filteredList addObject:rawList[x]];
        }

        _objectList = [NSArray arrayWithArray:filteredList];
        [self.tableView reloadData];
307 308 309 310
    } else
        APLog(@"unknown request %@ completed", request);
}

311 312
- (void)requestFailed:(WRRequest *)request
{
313 314 315
    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];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
316
    APLog(@"request %@ failed with error %i", request, request.error.errorCode);
317 318
}

319 320 321
#pragma mark - VLCLocalNetworkListCell delegation
- (void)triggerDownloadForCell:(VLCLocalNetworkListCell *)cell
{
322
    if (_serverType == kVLCServerTypeUPNP) {
Pierre SAGASPE's avatar
Pierre SAGASPE committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336
        MediaServer1ItemObject *item = _mutableObjectList[[self.tableView indexPathForCell:cell].row];
        MediaServer1ItemRes *resource = nil;
        NSEnumerator *e = [[item resources] objectEnumerator];
        NSURL *itemURL;
        while((resource = (MediaServer1ItemRes*)[e nextObject])){
            itemURL = [NSURL URLWithString:[[item uri] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        }
        if (![[item uri] isSupportedFormat]) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", @"") message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", @""), [item uri]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
            [alert show];
        } else {
            [self _downloadUPNPFile:itemURL fileNameOfMedia:[item title]];
            [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", @"")];
        }
337
    }else if (_serverType == kVLCServerTypeFTP) {
338 339
        NSString *objectName = [_objectList[[self.tableView indexPathForCell:cell].row] objectForKey:(id)kCFFTPResourceName];
        if (![objectName isSupportedFormat]) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
340
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", @"") message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", @""), objectName] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
341
            [alert show];
342
        } else {
343
            [self _downloadFTPFile:objectName];
344 345
            [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", @"")];
        }
346 347 348 349 350 351 352 353 354 355 356
    }
}

#pragma mark - communication with playback engine
- (void)_openURLStringAndDismiss:(NSString *)url
{
    VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate.menuViewController selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    [appDelegate.playlistViewController performSelector:@selector(openMovieFromURL:) withObject:[NSURL URLWithString:url] afterDelay:kGHRevealSidebarDefaultAnimationDuration];
}

357
@end