VLCPlexConnectServerViewController.m 11.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*****************************************************************************
 * VLCPlexConnectServerViewController.m
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2015 VideoLAN. All rights reserved.
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *          Pierre SAGASPE <pierre.sagaspe # me.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

#import "VLCPlexConnectServerViewController.h"
#import "VLCLocalPlexFolderListViewController.h"

#define kPlexMediaServerPortDefault @"32400"

@interface VLCPlexConnectServerViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    NSMutableArray *_bookmarkServer;
    NSMutableArray *_bookmarkPort;
22 23

    UIActivityIndicatorView *_activityIndicator;
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
}
@end

@implementation VLCPlexConnectServerViewController

+ (void)initialize
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *loginDefaults = @{kVLCPLEXServer : @[], kVLCPLEXPort : @[]};
    [defaults registerDefaults:loginDefaults];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Plex Media Server";
    [self.connectButton setTitle:NSLocalizedString(@"BUTTON_CONNECT", nil) forState:UIControlStateNormal];
    self.serverAddressHelpLabel.text = NSLocalizedString(@"ENTER_SERVER_ADDRESS_HELP", nil);
    self.serverAddressLabel.text = NSLocalizedString(@"SERVER", nil);
    self.portLabel.text = NSLocalizedString(@"SERVER_PORT", nil);
    self.bookmarkLabel.text = NSLocalizedString(@"BOOKMARK", nil);

    self.serverAddressField.delegate = self;
    self.serverAddressField.returnKeyType = UIReturnKeyNext;
    self.serverAddressField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.serverAddressField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.portField.delegate = self;
    self.portField.returnKeyType = UIReturnKeyDone;
    self.portField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.portField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;

    self.serverPlexBookmark.backgroundColor = [UIColor VLCDarkBackgroundColor];
57 58
    self.serverPlexBookmark.showsVerticalScrollIndicator = YES;
    self.serverPlexBookmark.indicatorStyle = UIScrollViewIndicatorStyleWhite;
59 60 61 62 63 64 65 66

    if (SYSTEM_RUNS_IOS7_OR_LATER) {
        UIColor *color = [UIColor VLCLightTextColor];
        self.serverAddressField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"192.168.0.0" attributes:@{NSForegroundColorAttributeName: color}];
        self.portField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:kPlexMediaServerPortDefault attributes:@{NSForegroundColorAttributeName: color}];

        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
67 68 69 70 71 72

    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityIndicator.center = self.view.center;
    _activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _activityIndicator.hidesWhenStopped = YES;
    [self.view addSubview:_activityIndicator];
73 74 75 76

    self.scrollView.contentSize = self.view.frame.size;
    [self.scrollView setBackgroundColor:[UIColor VLCDarkBackgroundColor]];
    [self.scrollView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
}

- (void)viewWillAppear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    _bookmarkServer = [NSMutableArray arrayWithArray:[defaults objectForKey:kVLCPLEXServer]];
    _bookmarkPort = [NSMutableArray arrayWithArray:[defaults objectForKey:kVLCPLEXPort]];

    [super viewWillAppear:animated];

    if ([defaults stringForKey:kVLCLastPLEXServer])
        self.serverAddressField.text = [defaults stringForKey:kVLCLastPLEXServer];
    if ([defaults stringForKey:kVLCLastPLEXPort])
        self.portField.text = [defaults stringForKey:kVLCLastPLEXPort];

    if (self.portField.text.length < 1)
        self.portField.text = kPlexMediaServerPortDefault;
}

- (void)viewWillDisappear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.serverAddressField.text forKey:kVLCLastPLEXServer];
    [defaults setObject:self.portField.text forKey:kVLCLastPLEXPort];

    [super viewWillDisappear:animated];
}

#pragma mark - IBAction

- (IBAction)connectToServer:(id)sender
108 109 110 111 112 113
{
    [_activityIndicator startAnimating];
    [self performSelector:@selector(connectToPlexMediaServer) withObject:nil afterDelay:0.1];
}

- (void)connectToPlexMediaServer
114 115
{
    NSString *server = [NSString stringWithFormat:@"%@", self.serverAddressField.text];
116
    NSString *port = [NSString stringWithFormat:@"%@", self.portField.text];
117

118 119 120 121 122 123 124
    if ([port isEqualToString:@""]) {
        self.portField.text = kPlexMediaServerPortDefault;
        port = kPlexMediaServerPortDefault;
    }

    if ([self isValidPort:port] && [self isValidAddress:server]) {
        if ([self isValidURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@", server, port]]]) {
125
            VLCLocalPlexFolderListViewController *targetViewController = [[VLCLocalPlexFolderListViewController alloc] initWithPlexServer:server serverAddress:server portNumber:[NSString stringWithFormat:@":%@", port] atPath:@"" authentification:@""];
126 127
            [[self navigationController] pushViewController:targetViewController animated:YES];
        } else {
128 129 130 131 132
            VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:nil
                                                              message:NSLocalizedString(@"HTTP_UPLOAD_SERVER_OFF", nil)
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
                                                    otherButtonTitles:nil];
133 134
            [alert show];
        }
135
    } else {
136 137 138 139 140
        VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:nil
                                                          message:NSLocalizedString(@"INVALID_IP_PORT", nil)
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
                                                otherButtonTitles:nil];
141
        [alert show];
142 143 144

        if (![self isValidPort:port])
            self.portField.text = kPlexMediaServerPortDefault;
145
    }
146
    [_activityIndicator stopAnimating];
147 148 149 150
}

- (IBAction)savePlexServer:(id)sender
{
151 152 153 154
    NSString *server = [NSString stringWithFormat:@"%@", self.serverAddressField.text];
    NSString *port = [NSString stringWithFormat:@"%@", self.portField.text];

    if ([self isValidPort:port] && [self isValidAddress:server]) {
155 156 157 158 159 160 161 162
        [_bookmarkServer addObject:self.serverAddressField.text];
        [_bookmarkPort addObject:self.portField.text];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[NSArray arrayWithArray:_bookmarkServer] forKey:kVLCPLEXServer];
        [defaults setObject:[NSArray arrayWithArray:_bookmarkPort] forKey:kVLCPLEXPort];
        [defaults synchronize];
        [self.serverPlexBookmark reloadData];
    } else {
163 164 165 166 167
        VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:nil
                                                          message:NSLocalizedString(@"INVALID_IP_PORT", nil)
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
                                                otherButtonTitles:nil];
168 169 170 171 172
        [alert show];
    }
}

#pragma mark - text view delegate
173

174 175 176 177 178 179 180 181 182 183 184 185
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([self.serverAddressField isFirstResponder]) {
        [self.serverAddressField resignFirstResponder];
        [self.portField becomeFirstResponder];
    } else if ([self.portField isFirstResponder]) {
        [self.portField resignFirstResponder];
    }
    return NO;
}

#pragma mark - table view data source
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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _bookmarkServer.count;
}

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

    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 VLCLightTextColor];
    }

    NSInteger row = indexPath.row;
    cell.textLabel.text = _bookmarkServer[row];
    cell.detailTextLabel.text = _bookmarkPort[row];

    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 VLCDarkBackgroundColor];
}

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

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_bookmarkServer removeObjectAtIndex:indexPath.row];
        [_bookmarkPort removeObjectAtIndex:indexPath.row];
        [tableView reloadData];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[NSArray arrayWithArray:_bookmarkServer] forKey:kVLCPLEXServer];
        [defaults setObject:[NSArray arrayWithArray:_bookmarkPort] forKey:kVLCPLEXPort];
        [defaults synchronize];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.serverAddressField setText:_bookmarkServer[indexPath.row]];
    [self.portField setText:_bookmarkPort[indexPath.row]];

    [self.serverPlexBookmark deselectRowAtIndexPath:indexPath animated:NO];
}

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
#pragma mark - isValid

- (BOOL)isValidPort:(NSString *)port
{
    NSString *portRegex = @"^([0-9]{2,5})$";
    NSPredicate *portTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", portRegex];
    return [portTest evaluateWithObject:port];
}

- (BOOL)isValidAddress:(NSString *)address
{
    NSString *addressRegex = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
    NSPredicate *addressTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", addressRegex];
    if ([addressTest evaluateWithObject:address] || [[address pathExtension] isEqualToString:@"local"])
        return YES;
    else
        return NO;
}

- (BOOL)isValidURL:(NSURL*)url
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
270
    //[request setHTTPMethod:@"HEAD"];
271 272
    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
273 274 275
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (([response statusCode] == 200) || ([responseString rangeOfString:@"Unauthorized"].location != NSNotFound))
276 277 278 279 280
        return YES;
    else
        return NO;
}

281
@end