VLCLocalServerListViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*****************************************************************************
  2. * VLCLocalServerListViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Pierre SAGASPE <pierre.sagaspe # me.com>
  10. * Gleb Pinigin <gpinigin # gmail.com>
  11. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCLocalServerListViewController.h"
  15. #import "UIBarButtonItem+Theme.h"
  16. #import "VLCAppDelegate.h"
  17. #import "UPnPManager.h"
  18. #import "VLCLocalNetworkListCell.h"
  19. #import "VLCLocalServerFolderListViewController.h"
  20. #import <QuartzCore/QuartzCore.h>
  21. #import "GHRevealViewController.h"
  22. #import "VLCNetworkLoginViewController.h"
  23. #import "UINavigationController+Theme.h"
  24. #import "VLCPlaylistViewController.h"
  25. #import "Reachability.h"
  26. @interface VLCLocalServerListViewController () <UITableViewDataSource, UITableViewDelegate, NSNetServiceBrowserDelegate, VLCNetworkLoginViewController, NSNetServiceDelegate, VLCMediaListDelegate>
  27. {
  28. UIBarButtonItem *_backToMenuButton;
  29. NSArray *_sectionHeaderTexts;
  30. NSNetServiceBrowser *_ftpNetServiceBrowser;
  31. NSMutableArray *_rawNetServices;
  32. NSMutableArray *_ftpServices;
  33. NSArray *_filteredUPNPDevices;
  34. NSArray *_UPNPdevices;
  35. VLCMediaDiscoverer * _sapDiscoverer;
  36. VLCNetworkLoginViewController *_loginViewController;
  37. UIRefreshControl *_refreshControl;
  38. UIActivityIndicatorView *_activityIndicator;
  39. Reachability *_reachability;
  40. BOOL _udnpDiscoveryRunning;
  41. }
  42. @end
  43. @implementation VLCLocalServerListViewController
  44. - (void)dealloc
  45. {
  46. [_reachability stopNotifier];
  47. [_ftpNetServiceBrowser stop];
  48. }
  49. - (void)loadView
  50. {
  51. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  52. _tableView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  53. _tableView.delegate = self;
  54. _tableView.dataSource = self;
  55. self.view = _tableView;
  56. _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
  57. _activityIndicator.center = _tableView.center;
  58. _activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
  59. _activityIndicator.hidesWhenStopped = YES;
  60. [self.view addSubview:_activityIndicator];
  61. }
  62. - (void)viewDidLoad
  63. {
  64. [super viewDidLoad];
  65. if (SYSTEM_RUNS_IOS7_OR_LATER)
  66. _sectionHeaderTexts = @[@"Universal Plug'n'Play (UPNP)", @"File Transfer Protocol (FTP)", @"Network Streams (SAP)"];
  67. else
  68. _sectionHeaderTexts = @[@"Universal Plug'n'Play (UPNP)", @"File Transfer Protocol (FTP)"];
  69. _backToMenuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
  70. self.navigationItem.leftBarButtonItem = _backToMenuButton;
  71. self.tableView.rowHeight = [VLCLocalNetworkListCell heightOfCell];
  72. self.tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
  73. self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  74. self.title = NSLocalizedString(@"LOCAL_NETWORK", @"");
  75. _ftpServices = [[NSMutableArray alloc] init];
  76. [_ftpServices addObject:NSLocalizedString(@"CONNECT_TO_SERVER", nil)];
  77. _rawNetServices = [[NSMutableArray alloc] init];
  78. _ftpNetServiceBrowser = [[NSNetServiceBrowser alloc] init];
  79. _ftpNetServiceBrowser.delegate = self;
  80. [self _triggerNetServiceBrowser];
  81. _refreshControl = [[UIRefreshControl alloc] init];
  82. [_refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];
  83. [self.tableView addSubview:_refreshControl];
  84. if (SYSTEM_RUNS_IOS7_OR_LATER)
  85. _loginViewController = [[VLCNetworkLoginViewController alloc] initWithNibName:@"VLCFutureNetworkLoginViewController" bundle:nil];
  86. else
  87. _loginViewController = [[VLCNetworkLoginViewController alloc] initWithNibName:@"VLCNetworkLoginViewController" bundle:nil];
  88. _loginViewController.delegate = self;
  89. _reachability = [Reachability reachabilityForLocalWiFi];
  90. [_reachability startNotifier];
  91. [self netReachabilityChanged:nil];
  92. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netReachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  93. }
  94. - (void)viewWillDisappear:(BOOL)animated
  95. {
  96. [super viewWillDisappear:animated];
  97. [_activityIndicator stopAnimating];
  98. [_ftpNetServiceBrowser stop];
  99. }
  100. - (void)viewWillAppear:(BOOL)animated
  101. {
  102. [_activityIndicator stopAnimating];
  103. [super viewWillAppear:animated];
  104. [self netReachabilityChanged:nil];
  105. }
  106. - (void)netReachabilityChanged:(NSNotification *)notification
  107. {
  108. if (_reachability.currentReachabilityStatus == ReachableViaWiFi) {
  109. [self _triggerNetServiceBrowser];
  110. [self performSelectorInBackground:@selector(_startUPNPDiscovery) withObject:nil];
  111. [self performSelectorInBackground:@selector(_startSAPDiscovery) withObject:nil];
  112. } else {
  113. [_ftpNetServiceBrowser stop];
  114. [self _stopUPNPDiscovery];
  115. [self _stopSAPDiscovery];
  116. }
  117. }
  118. - (void)_triggerNetServiceBrowser
  119. {
  120. [_ftpNetServiceBrowser searchForServicesOfType:@"_ftp._tcp." inDomain:@""];
  121. }
  122. - (void)_startUPNPDiscovery
  123. {
  124. if (_reachability.currentReachabilityStatus != ReachableViaWiFi)
  125. return;
  126. UPnPManager *managerInstance = [UPnPManager GetInstance];
  127. _UPNPdevices = [[managerInstance DB] rootDevices];
  128. if (_UPNPdevices.count > 0)
  129. [self UPnPDBUpdated:nil];
  130. [[managerInstance DB] addObserver:(UPnPDBObserver*)self];
  131. //Optional; set User Agent
  132. [[managerInstance SSDP] setUserAgentProduct:[NSString stringWithFormat:@"VLC for iOS/%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]] andOS:@"iOS"];
  133. //Search for UPnP Devices
  134. [[managerInstance SSDP] startSSDP];
  135. [[managerInstance SSDP] searchSSDP];
  136. [[managerInstance SSDP] SSDPDBUpdate];
  137. _udnpDiscoveryRunning = YES;
  138. }
  139. - (void)_stopUPNPDiscovery
  140. {
  141. if (_udnpDiscoveryRunning) {
  142. UPnPManager *managerInstance = [UPnPManager GetInstance];
  143. [[managerInstance DB] removeObserver:(UPnPDBObserver*)self];
  144. [[managerInstance SSDP] stopSSDP];
  145. _udnpDiscoveryRunning = NO;
  146. }
  147. }
  148. - (IBAction)goBack:(id)sender
  149. {
  150. [self _stopUPNPDiscovery];
  151. [self _stopSAPDiscovery];
  152. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  153. }
  154. - (BOOL)shouldAutorotate
  155. {
  156. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  157. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  158. return NO;
  159. return YES;
  160. }
  161. #pragma mark - table view handling
  162. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  163. {
  164. return _sectionHeaderTexts.count;
  165. }
  166. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  167. {
  168. if (section == 0)
  169. return _filteredUPNPDevices.count;
  170. else if (section == 1)
  171. return _ftpServices.count;
  172. else if (section == 2)
  173. return _sapDiscoverer.discoveredMedia.count;
  174. return 0;
  175. }
  176. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCLocalNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  177. {
  178. UIColor *color = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  179. cell.contentView.backgroundColor = cell.titleLabel.backgroundColor = cell.folderTitleLabel.backgroundColor = cell.subtitleLabel.backgroundColor = color;
  180. }
  181. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  182. {
  183. static NSString *CellIdentifier = @"LocalNetworkCell";
  184. VLCLocalNetworkListCell *cell = (VLCLocalNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  185. if (cell == nil)
  186. cell = [VLCLocalNetworkListCell cellWithReuseIdentifier:CellIdentifier];
  187. NSUInteger row = indexPath.row;
  188. NSUInteger section = indexPath.section;
  189. [cell setIsDirectory:YES];
  190. [cell setIcon:nil];
  191. if (section == 0) {
  192. BasicUPnPDevice *device = _filteredUPNPDevices[row];
  193. [cell setTitle:[device friendlyName]];
  194. UIImage *icon = [device smallIcon];
  195. [cell setIcon:icon != nil ? icon : [UIImage imageNamed:@"serverIcon"]];
  196. } else if (section == 1) {
  197. if (row == 0)
  198. [cell setTitle:_ftpServices[row]];
  199. else {
  200. [cell setTitle:[_ftpServices[row] name]];
  201. [cell setIcon:[UIImage imageNamed:@"serverIcon"]];
  202. }
  203. } else if (section == 2)
  204. [cell setTitle:[[_sapDiscoverer.discoveredMedia mediaAtIndex:row] metadataForKey: VLCMetaInformationTitle]];
  205. return cell;
  206. }
  207. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  208. {
  209. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  210. NSUInteger row = indexPath.row;
  211. NSUInteger section = indexPath.section;
  212. if (section == 0) {
  213. [_activityIndicator startAnimating];
  214. BasicUPnPDevice *device = _filteredUPNPDevices[row];
  215. if ([[device urn] isEqualToString:@"urn:schemas-upnp-org:device:MediaServer:1"]) {
  216. MediaServer1Device *server = (MediaServer1Device*)device;
  217. VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithUPNPDevice:server header:[device friendlyName] andRootID:@"0"];
  218. [self.navigationController pushViewController:targetViewController animated:YES];
  219. }
  220. } else if (section == 1) {
  221. UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:_loginViewController];
  222. [navCon loadTheme];
  223. navCon.navigationBarHidden = NO;
  224. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  225. navCon.modalPresentationStyle = UIModalPresentationFormSheet;
  226. [self presentViewController:navCon animated:YES completion:nil];
  227. if (_loginViewController.navigationItem.leftBarButtonItem == nil) {
  228. UIBarButtonItem *doneButton = [UIBarButtonItem themedDoneButtonWithTarget:_loginViewController andSelector:@selector(dismissWithAnimation:)];
  229. _loginViewController.navigationItem.leftBarButtonItem = doneButton;
  230. }
  231. } else
  232. [self.navigationController pushViewController:_loginViewController animated:YES];
  233. if (row != 0 && [_ftpServices[row] hostName].length > 0) // FTP Connect To Server Special Item and hostname is long enough
  234. _loginViewController.hostname = [_ftpServices[row] hostName];
  235. else
  236. _loginViewController.hostname = @"";
  237. } else if (section == 2) {
  238. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  239. [appDelegate openMovieFromURL:[[_sapDiscoverer.discoveredMedia mediaAtIndex:row] url]];
  240. }
  241. }
  242. #pragma mark - Refresh
  243. -(void)handleRefresh
  244. {
  245. UPnPManager *managerInstance = [UPnPManager GetInstance];
  246. [[managerInstance DB] removeObserver:(UPnPDBObserver*)self];
  247. [[managerInstance SSDP] stopSSDP];
  248. //set the title while refreshing
  249. _refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"LOCAL_SERVER_REFRESH",nil)];
  250. //set the date and time of refreshing
  251. NSDateFormatter *formattedDate = [[NSDateFormatter alloc]init];
  252. [formattedDate setDateFormat:@"MMM d, h:mm a"];
  253. NSString *lastupdated = [NSString stringWithFormat:NSLocalizedString(@"LOCAL_SERVER_LAST_UPDATE",nil),[formattedDate stringFromDate:[NSDate date]]];
  254. _refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:lastupdated];
  255. //end the refreshing
  256. [_refreshControl endRefreshing];
  257. [self.tableView reloadData];
  258. [self performSelectorInBackground:@selector(_startUPNPDiscovery) withObject:nil];
  259. [self performSelectorInBackground:@selector(_startSAPDiscovery) withObject:nil];
  260. }
  261. #pragma mark - login panel protocol
  262. - (void)loginToURL:(NSURL *)url confirmedWithUsername:(NSString *)username andPassword:(NSString *)password
  263. {
  264. if ([url.scheme isEqualToString:@"ftp"]) {
  265. if (url.host.length > 0) {
  266. VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithFTPServer:url.host userName:username andPassword:password atPath:@"/"];
  267. [self.navigationController pushViewController:targetViewController animated:YES];
  268. }
  269. } else
  270. APLog(@"Unsupported URL Scheme requested %@", url.scheme);
  271. }
  272. #pragma mark - custom table view appearance
  273. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  274. return 21.f;
  275. }
  276. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  277. NSObject *headerText = NSLocalizedString(_sectionHeaderTexts[section], @"");
  278. UIView *headerView = nil;
  279. if (headerText != [NSNull null]) {
  280. headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.height, 21.0f)];
  281. if (!SYSTEM_RUNS_IOS7_OR_LATER) {
  282. CAGradientLayer *gradient = [CAGradientLayer layer];
  283. gradient.frame = headerView.bounds;
  284. gradient.colors = @[
  285. (id)[UIColor colorWithRed:(66.0f/255.0f) green:(66.0f/255.0f) blue:(66.0f/255.0f) alpha:1.0f].CGColor,
  286. (id)[UIColor colorWithRed:(56.0f/255.0f) green:(56.0f/255.0f) blue:(56.0f/255.0f) alpha:1.0f].CGColor,
  287. ];
  288. [headerView.layer insertSublayer:gradient atIndex:0];
  289. } else
  290. headerView.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  291. UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectInset(headerView.bounds, 12.0f, 5.0f)];
  292. textLabel.text = (NSString *) headerText;
  293. textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:([UIFont systemFontSize] * 0.8f)];
  294. textLabel.shadowOffset = CGSizeMake(0.0f, 1.0f);
  295. textLabel.shadowColor = [UIColor colorWithWhite:0.0f alpha:0.25f];
  296. textLabel.textColor = [UIColor colorWithRed:(118.0f/255.0f) green:(118.0f/255.0f) blue:(118.0f/255.0f) alpha:1.0f];
  297. textLabel.backgroundColor = [UIColor clearColor];
  298. [headerView addSubview:textLabel];
  299. UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [UIScreen mainScreen].bounds.size.height, 1.0f)];
  300. topLine.backgroundColor = [UIColor colorWithRed:(95.0f/255.0f) green:(95.0f/255.0f) blue:(95.0f/255.0f) alpha:1.0f];
  301. [headerView addSubview:topLine];
  302. UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 21.0f, [UIScreen mainScreen].bounds.size.height, 1.0f)];
  303. bottomLine.backgroundColor = [UIColor colorWithRed:(16.0f/255.0f) green:(16.0f/255.0f) blue:(16.0f/255.0f) alpha:1.0f];
  304. [headerView addSubview:bottomLine];
  305. }
  306. return headerView;
  307. }
  308. #pragma mark - bonjour discovery
  309. - (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
  310. {
  311. APLog(@"found bonjour service: %@ (%@)", aNetService.name, aNetService.type);
  312. [_rawNetServices addObject:aNetService];
  313. aNetService.delegate = self;
  314. [aNetService resolveWithTimeout:5.];
  315. }
  316. - (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)moreComing
  317. {
  318. APLog(@"bonjour service disappeared: %@ (%i)", aNetService.name, moreComing);
  319. if ([_rawNetServices containsObject:aNetService])
  320. [_rawNetServices removeObject:aNetService];
  321. if ([aNetService.type isEqualToString:@"_ftp._tcp."])
  322. [_ftpServices removeObject:aNetService];
  323. if (!moreComing)
  324. [self.tableView reloadData];
  325. }
  326. - (void)netServiceDidResolveAddress:(NSNetService *)aNetService
  327. {
  328. if ([aNetService.type isEqualToString:@"_ftp._tcp."]) {
  329. if (![_ftpServices containsObject:aNetService])
  330. [_ftpServices addObject:aNetService];
  331. }
  332. [_rawNetServices removeObject:aNetService];
  333. [self.tableView reloadData];
  334. }
  335. - (void)netService:(NSNetService *)aNetService didNotResolve:(NSDictionary *)errorDict
  336. {
  337. APLog(@"failed to resolve: %@", aNetService.name);
  338. [_rawNetServices removeObject:aNetService];
  339. }
  340. #pragma mark - UPNP details
  341. //protocol UPnPDBObserver
  342. - (void)UPnPDBWillUpdate:(UPnPDB*)sender{
  343. }
  344. - (void)UPnPDBUpdated:(UPnPDB*)sender{
  345. NSUInteger count = _UPNPdevices.count;
  346. BasicUPnPDevice *device;
  347. NSMutableArray *mutArray = [[NSMutableArray alloc] init];
  348. for (NSUInteger x = 0; x < count; x++) {
  349. device = _UPNPdevices[x];
  350. if ([[device urn] isEqualToString:@"urn:schemas-upnp-org:device:MediaServer:1"])
  351. [mutArray addObject:device];
  352. else
  353. APLog(@"found device '%@' with unsupported urn '%@'", [device friendlyName], [device urn]);
  354. }
  355. _filteredUPNPDevices = nil;
  356. _filteredUPNPDevices = [NSArray arrayWithArray:mutArray];
  357. [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
  358. }
  359. #pragma mark SAP discovery
  360. - (void)_startSAPDiscovery
  361. {
  362. if (!SYSTEM_RUNS_IOS7_OR_LATER)
  363. return;
  364. if (_reachability.currentReachabilityStatus != ReachableViaWiFi)
  365. return;
  366. _sapDiscoverer = [[VLCMediaDiscoverer alloc] initWithName:@"sap"];
  367. _sapDiscoverer.discoveredMedia.delegate = self;
  368. }
  369. - (void)_stopSAPDiscovery
  370. {
  371. if (!SYSTEM_RUNS_IOS7_OR_LATER)
  372. return;
  373. _sapDiscoverer = nil;
  374. }
  375. - (void)mediaList:(VLCMediaList *)aMediaList mediaAdded:(VLCMedia *)media atIndex:(NSInteger)index
  376. {
  377. [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  378. }
  379. - (void)mediaList:(VLCMediaList *)aMediaList mediaRemovedAtIndex:(NSInteger)index
  380. {
  381. [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  382. }
  383. @end