VLCLocalServerListViewController.m 15.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
//  VLCLocalServerListViewController.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 "VLCLocalServerListViewController.h"
#import "UIBarButtonItem+Theme.h"
#import "VLCAppDelegate.h"
#import "UPnPManager.h"
#import "VLCLocalNetworkListCell.h"
16
#import "VLCLocalServerFolderListViewController.h"
17 18
#import <QuartzCore/QuartzCore.h>
#import "GHRevealViewController.h"
19 20
#import "VLCNetworkLoginViewController.h"
#import "UINavigationController+Theme.h"
21
#import "VLCPlaylistViewController.h"
22

23
@interface VLCLocalServerListViewController () <UITableViewDataSource, UITableViewDelegate, NSNetServiceBrowserDelegate, VLCNetworkLoginViewController, NSNetServiceDelegate, VLCMediaListDelegate>
24 25
{
    UIBarButtonItem *_backToMenuButton;
26 27
    NSArray *_sectionHeaderTexts;

28
    NSNetServiceBrowser *_netServiceBrowser;
29
    NSMutableArray *_rawServices;
30 31
    NSMutableArray *_ftpServices;

32 33
    NSArray *_filteredUPNPDevices;
    NSArray *_UPNPdevices;
34

35 36
    VLCMediaDiscoverer * _sapDiscoverer;

37
    VLCNetworkLoginViewController *_loginViewController;
Pierre SAGASPE's avatar
Pierre SAGASPE committed
38 39

    UIRefreshControl *refreshControl;
40 41 42 43 44 45
}

@end

@implementation VLCLocalServerListViewController

46 47 48 49 50
- (void)dealloc
{
    [_netServiceBrowser stop];
}

51 52 53 54 55 56 57 58 59 60 61 62 63
- (void)loadView
{
    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.view = _tableView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

64
    _sectionHeaderTexts = @[@"Universal Plug'n'Play (UPNP)", @"File Transfer Protocol (FTP)", @"Network Streams (SAP)"];
65 66 67 68

    _backToMenuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
    self.navigationItem.leftBarButtonItem = _backToMenuButton;

69
    self.tableView.rowHeight = [VLCLocalNetworkListCell heightOfCell];
70 71 72 73 74
    self.tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
    self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];

    self.title = NSLocalizedString(@"LOCAL_NETWORK", @"");

75
    _ftpServices = [[NSMutableArray alloc] init];
76
    [_ftpServices addObject:NSLocalizedString(@"CONNECT_TO_SERVER", nil)];
77

78 79
    _rawServices = [[NSMutableArray alloc] init];

80 81
    _netServiceBrowser = [[NSNetServiceBrowser alloc] init];
    _netServiceBrowser.delegate = self;
Pierre SAGASPE's avatar
Pierre SAGASPE committed
82

83
    [self performSelectorInBackground:@selector(_startUPNPDiscovery) withObject:nil];
84
    [self performSelectorInBackground:@selector(_startSAPDiscovery) withObject:nil];
85

Pierre SAGASPE's avatar
Pierre SAGASPE committed
86 87 88
    refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:refreshControl];
89 90 91 92 93 94 95 96 97 98 99 100
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_netServiceBrowser stop];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self _triggerNetServiceBrowser];
101
    [self performSelectorInBackground:@selector(_startUPNPDiscovery) withObject:nil];
102
    [self performSelectorInBackground:@selector(_startSAPDiscovery) withObject:nil];
103 104 105 106 107
}

- (void)_triggerNetServiceBrowser
{
    [_netServiceBrowser searchForServicesOfType:@"_ftp._tcp." inDomain:@""];
108 109 110 111
}

- (void)_startUPNPDiscovery
{
112
    UPnPManager *managerInstance = [UPnPManager GetInstance];
113

114 115
    _UPNPdevices = [[managerInstance DB] rootDevices];

116 117 118
    if (_UPNPdevices.count > 0)
        [self UPnPDBUpdated:nil];

119
    [[managerInstance DB] addObserver:(UPnPDBObserver*)self];
120 121

    //Optional; set User Agent
122
    [[managerInstance SSDP] setUserAgentProduct:[NSString stringWithFormat:@"VLC for iOS/%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]] andOS:@"iOS"];
123 124

    //Search for UPnP Devices
125 126 127
    [[managerInstance SSDP] startSSDP];
    [[managerInstance SSDP] searchSSDP];
    [[managerInstance SSDP] SSDPDBUpdate];
128 129 130 131
}

- (IBAction)goBack:(id)sender
{
132 133 134
    UPnPManager *managerInstance = [UPnPManager GetInstance];
    [[managerInstance DB] removeObserver:(UPnPDBObserver*)self];
    [[managerInstance SSDP] stopSSDP];
135
    [self _stopSAPDiscovery];
136

137 138 139
    [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}

140
- (BOOL)shouldAutorotate
141
{
142
    UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
143 144 145 146 147
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        return NO;
    return YES;
}

148 149
#pragma mark - table view handling

150 151
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
152
    return _sectionHeaderTexts.count;
153 154 155 156
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
157 158
    if (section == 0)
        return _filteredUPNPDevices.count;
159 160
    else if (section == 1)
        return _ftpServices.count;
161 162
    else if (section == 2)
        return _sapDiscoverer.discoveredMedia.count;
163 164

    return 0;
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
}

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

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

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

180 181 182 183
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;

    [cell setIsDirectory:YES];
184
    [cell setIcon:nil];
185 186 187

    if (section == 0) {
        BasicUPnPDevice *device = _filteredUPNPDevices[row];
188 189
        [cell setTitle:[device friendlyName]];
        [cell setIcon:[device smallIcon]];
190 191 192 193 194
    } else if (section == 1) {
        if (row == 0)
            [cell setTitle:_ftpServices[row]];
        else
            [cell setTitle:[_ftpServices[row] name]];
195 196
    } else if (section == 2)
        [cell setTitle:[[_sapDiscoverer.discoveredMedia mediaAtIndex:row] metadataForKey: VLCMetaInformationTitle]];
197 198 199 200 201 202

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
203 204
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

205 206 207 208 209
    NSUInteger row = indexPath.row;
    NSUInteger section = indexPath.section;

    if (section == 0) {
        BasicUPnPDevice *device = _filteredUPNPDevices[row];
210 211
        if ([[device urn] isEqualToString:@"urn:schemas-upnp-org:device:MediaServer:1"]) {
            MediaServer1Device *server = (MediaServer1Device*)device;
212
            VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithUPNPDevice:server header:[device friendlyName] andRootID:@"0"];
213
            [self.navigationController pushViewController:targetViewController animated:YES];
214
        }
215
    } else if (section == 1) {
216 217 218 219 220 221 222 223 224 225 226
        if (_loginViewController == nil) {
            _loginViewController = [[VLCNetworkLoginViewController alloc] initWithNibName:nil bundle:nil];
            _loginViewController.delegate = self;
        }

        UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_loginViewController];
        [navCon loadTheme];
        navCon.navigationBarHidden = NO;

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            navCon.modalPresentationStyle = UIModalPresentationFormSheet;
227
            [self presentViewController:navCon animated:YES completion:nil];
228 229

            if (_loginViewController.navigationItem.leftBarButtonItem == nil) {
230
                UIBarButtonItem *doneButton = [UIBarButtonItem themedDoneButtonWithTarget:_loginViewController andSelector:@selector(dismissWithAnimation:)];
231 232 233

                _loginViewController.navigationItem.leftBarButtonItem = doneButton;
            }
234
        } else
235
            [self.navigationController pushViewController:_loginViewController animated:YES];
236

237 238 239
        if (row != 0) { // FTP Connect To Server Special Item
            if ([_ftpServices[row] hostName].length > 0)
                _loginViewController.serverAddressField.text = [NSString stringWithFormat:@"ftp://%@", [_ftpServices[row] hostName]];
240 241
        } else
            _loginViewController.serverAddressField.text = @"";
242 243
    } else if (section == 2) {
        VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
244
        [appDelegate openMovieFromURL:[[_sapDiscoverer.discoveredMedia mediaAtIndex:row] url]];
245
    }
246 247
}

Pierre SAGASPE's avatar
Pierre SAGASPE committed
248 249 250 251
#pragma mark - Refresh

-(void)handleRefresh
{
Pierre SAGASPE's avatar
Pierre SAGASPE committed
252 253 254 255
    UPnPManager *managerInstance = [UPnPManager GetInstance];
    [[managerInstance DB] removeObserver:(UPnPDBObserver*)self];
    [[managerInstance SSDP] stopSSDP];

Pierre SAGASPE's avatar
Pierre SAGASPE committed
256 257 258 259 260 261 262 263 264 265 266 267 268
    //set the title while refreshing
    refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"Refresh"];
    //set the date and time of refreshing
    NSDateFormatter *formattedDate = [[NSDateFormatter alloc]init];
    [formattedDate setDateFormat:@"MMM d, h:mm a"];
    NSString *lastupdated = [NSString stringWithFormat:@"Last Updated on %@",[formattedDate stringFromDate:[NSDate date]]];
    refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:lastupdated];
    //end the refreshing
    [refreshControl endRefreshing];

    [self.tableView reloadData];

    [self performSelectorInBackground:@selector(_startUPNPDiscovery) withObject:nil];
269
    [self performSelectorInBackground:@selector(_startSAPDiscovery) withObject:nil];
Pierre SAGASPE's avatar
Pierre SAGASPE committed
270 271
}

272 273
#pragma mark - login panel protocol

274
- (void)loginToURL:(NSURL *)url confirmedWithUsername:(NSString *)username andPassword:(NSString *)password
275 276
{
    _loginViewController = nil;
277 278 279 280 281 282 283
    if ([url.scheme isEqualToString:@"ftp"]) {
        if (url.host.length > 0) {
            VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithFTPServer:url.host userName:username andPassword:password atPath:@"/"];
            [self.navigationController pushViewController:targetViewController animated:YES];
        }
    } else
        APLog(@"Unsupported URL Scheme requested %@", url.scheme);
284 285
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299
#pragma mark - custom table view appearance

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 21.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	NSObject *headerText = NSLocalizedString(_sectionHeaderTexts[section], @"");
	UIView *headerView = nil;
	if (headerText != [NSNull null]) {
		headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.height, 21.0f)];
		CAGradientLayer *gradient = [CAGradientLayer layer];
		gradient.frame = headerView.bounds;
		gradient.colors = @[
300 301
                      (id)[UIColor colorWithRed:(66.0f/255.0f) green:(66.0f/255.0f) blue:(66.0f/255.0f) alpha:1.0f].CGColor,
                      (id)[UIColor colorWithRed:(56.0f/255.0f) green:(56.0f/255.0f) blue:(56.0f/255.0f) alpha:1.0f].CGColor,
302 303 304 305 306 307 308 309
                      ];
		[headerView.layer insertSublayer:gradient atIndex:0];

		UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 12.0f, 5.0f)];
		textLabel.text = (NSString *) headerText;
		textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:([UIFont systemFontSize] * 0.8f)];
		textLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
		textLabel.shadowColor = [UIColor colorWithWhite:0.0f alpha:0.25f];
310
		textLabel.textColor = [UIColor colorWithRed:(118.0f/255.0f) green:(118.0f/255.0f) blue:(118.0f/255.0f) alpha:1.0f];
311 312 313 314
		textLabel.backgroundColor = [UIColor clearColor];
		[headerView addSubview:textLabel];

		UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.height, 1.0f)];
315
		topLine.backgroundColor = [UIColor colorWithRed:(95.0f/255.0f) green:(95.0f/255.0f) blue:(95.0f/255.0f) alpha:1.0f];
316 317 318
		[headerView addSubview:topLine];

		UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 21.0f, [UIScreen mainScreen].bounds.size.height, 1.0f)];
319
		bottomLine.backgroundColor = [UIColor colorWithRed:(16.0f/255.0f) green:(16.0f/255.0f) blue:(16.0f/255.0f) alpha:1.0f];
320 321 322 323 324
		[headerView addSubview:bottomLine];
	}
	return headerView;
}

325 326 327
#pragma mark - bonjour discovery
- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
328 329 330
    APLog(@"found bonjour service: %@ (%@)", aNetService.name, aNetService.type);
    [_rawServices addObject:aNetService];
    aNetService.delegate = self;
331
    [aNetService resolveWithTimeout:5.];
332 333 334 335
}

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
{
336 337 338 339 340
    APLog(@"bonjour service disappeared: %@ (%i)", aNetService.name, moreComing);
    if ([_rawServices containsObject:aNetService])
        [_rawServices removeObject:aNetService];
    if ([aNetService.type isEqualToString:@"_ftp._tcp."])
        [_ftpServices removeObject:aNetService];
341 342 343 344
    if (!moreComing)
        [self.tableView reloadData];
}

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
- (void)netServiceDidResolveAddress:(NSNetService *)aNetService
{
    if ([aNetService.type isEqualToString:@"_ftp._tcp."]) {
        if (![_ftpServices containsObject:aNetService])
            [_ftpServices addObject:aNetService];
    }
    [_rawServices removeObject:aNetService];
    [self.tableView reloadData];
}

- (void)netService:(NSNetService *)aNetService didNotResolve:(NSDictionary *)errorDict
{
    APLog(@"failed to resolve: %@", aNetService.name);
    [_rawServices removeObject:aNetService];
}

361
#pragma mark - UPNP details
362
//protocol UPnPDBObserver
363
- (void)UPnPDBWillUpdate:(UPnPDB*)sender{
364 365
}

366
- (void)UPnPDBUpdated:(UPnPDB*)sender{
367
    NSUInteger count = _UPNPdevices.count;
368 369 370
    BasicUPnPDevice *device;
    NSMutableArray *mutArray = [[NSMutableArray alloc] init];
    for (NSUInteger x = 0; x < count; x++) {
371
        device = _UPNPdevices[x];
372 373 374
        if ([[device urn] isEqualToString:@"urn:schemas-upnp-org:device:MediaServer:1"])
            [mutArray addObject:device];
    }
375 376
    _filteredUPNPDevices = nil;
    _filteredUPNPDevices = [NSArray arrayWithArray:mutArray];
377

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
}

#pragma mark SAP discovery

- (void)_startSAPDiscovery
{
    _sapDiscoverer = [[VLCMediaDiscoverer alloc] initWithName:@"sap"];
    _sapDiscoverer.discoveredMedia.delegate = self;
}

- (void)_stopSAPDiscovery
{
    _sapDiscoverer = nil;
}

- (void)mediaList:(VLCMediaList *)aMediaList mediaAdded:(VLCMedia *)media atIndex:(NSInteger)index
{
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}

- (void)mediaList:(VLCMediaList *)aMediaList mediaRemovedAtIndex:(NSInteger)index
{
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
402 403 404
}

@end