VLCLocalServerFolderListViewController.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. /*****************************************************************************
  2. * VLCLocalServerFolderListViewController.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. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCLocalServerFolderListViewController.h"
  14. #import "MediaServerBasicObjectParser.h"
  15. #import "MediaServer1ItemObject.h"
  16. #import "MediaServer1ContainerObject.h"
  17. #import "MediaServer1Device.h"
  18. #import "VLCLocalNetworkListCell.h"
  19. #import "VLCAppDelegate.h"
  20. #import "VLCPlaylistViewController.h"
  21. #import "UINavigationController+Theme.h"
  22. #import "VLCDownloadViewController.h"
  23. #import "WhiteRaccoon.h"
  24. #import "NSString+SupportedMedia.h"
  25. #import "VLCStatusLabel.h"
  26. #import "BasicUPnPDevice+VLC.h"
  27. #import "UIBarButtonItem+Theme.h"
  28. #define kVLCServerTypeUPNP 0
  29. #define kVLCServerTypeFTP 1
  30. @interface VLCLocalServerFolderListViewController () <UITableViewDataSource, UITableViewDelegate, WRRequestDelegate, VLCLocalNetworkListCell, UISearchBarDelegate, UISearchDisplayDelegate, UIActionSheetDelegate>
  31. {
  32. /* UI */
  33. UIBarButtonItem *_menuButton;
  34. /* generic data storage */
  35. NSString *_listTitle;
  36. NSArray *_objectList;
  37. NSMutableArray *_mutableObjectList;
  38. NSUInteger _serverType;
  39. /* UPNP specifics */
  40. MediaServer1Device *_UPNPdevice;
  41. NSString *_UPNProotID;
  42. /* FTP specifics */
  43. NSString *_ftpServerAddress;
  44. NSString *_ftpServerUserName;
  45. NSString *_ftpServerPassword;
  46. NSString *_ftpServerPath;
  47. WRRequestListDirectory *_FTPListDirRequest;
  48. NSMutableArray *_searchData;
  49. UISearchBar *_searchBar;
  50. UISearchDisplayController *_searchDisplayController;
  51. /* UPnP items with multiple resources specifics */
  52. MediaServer1ItemObject *_lastSelectedMediaItem;
  53. UIView *_resourceSelectionActionSheetAnchorView;
  54. }
  55. @end
  56. @implementation VLCLocalServerFolderListViewController
  57. - (void)loadView
  58. {
  59. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  60. _tableView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  61. _tableView.delegate = self;
  62. _tableView.dataSource = self;
  63. _tableView.rowHeight = [VLCLocalNetworkListCell heightOfCell];
  64. _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  65. _tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  66. self.view = _tableView;
  67. }
  68. - (id)initWithUPNPDevice:(MediaServer1Device*)device header:(NSString*)header andRootID:(NSString*)rootID
  69. {
  70. self = [super init];
  71. if (self) {
  72. _UPNPdevice = device;
  73. _listTitle = header;
  74. _UPNProotID = rootID;
  75. _serverType = kVLCServerTypeUPNP;
  76. _mutableObjectList = [[NSMutableArray alloc] init];
  77. }
  78. return self;
  79. }
  80. - (id)initWithFTPServer:(NSString *)serverAddress userName:(NSString *)username andPassword:(NSString *)password atPath:(NSString *)path
  81. {
  82. self = [super init];
  83. if (self) {
  84. _ftpServerAddress = serverAddress;
  85. _ftpServerUserName = username;
  86. _ftpServerPassword = password;
  87. _ftpServerPath = path;
  88. _serverType = kVLCServerTypeFTP;
  89. }
  90. return self;
  91. }
  92. - (void)viewDidLoad
  93. {
  94. [super viewDidLoad];
  95. if (_serverType == kVLCServerTypeUPNP) {
  96. NSString *sortCriteria = @"";
  97. NSMutableString *outSortCaps = [[NSMutableString alloc] init];
  98. [[_UPNPdevice contentDirectory] GetSortCapabilitiesWithOutSortCaps:outSortCaps];
  99. if ([outSortCaps rangeOfString:@"dc:title"].location != NSNotFound)
  100. {
  101. sortCriteria = @"+dc:title";
  102. }
  103. NSMutableString *outResult = [[NSMutableString alloc] init];
  104. NSMutableString *outNumberReturned = [[NSMutableString alloc] init];
  105. NSMutableString *outTotalMatches = [[NSMutableString alloc] init];
  106. NSMutableString *outUpdateID = [[NSMutableString alloc] init];
  107. [[_UPNPdevice contentDirectory] BrowseWithObjectID:_UPNProotID BrowseFlag:@"BrowseDirectChildren" Filter:@"*" StartingIndex:@"0" RequestedCount:@"0" SortCriteria:sortCriteria OutResult:outResult OutNumberReturned:outNumberReturned OutTotalMatches:outTotalMatches OutUpdateID:outUpdateID];
  108. [_mutableObjectList removeAllObjects];
  109. NSData *didl = [outResult dataUsingEncoding:NSUTF8StringEncoding];
  110. MediaServerBasicObjectParser *parser = [[MediaServerBasicObjectParser alloc] initWithMediaObjectArray:_mutableObjectList itemsOnly:NO];
  111. [parser parseFromData:didl];
  112. } else if (_serverType == kVLCServerTypeFTP) {
  113. if ([_ftpServerPath isEqualToString:@"/"])
  114. _listTitle = _ftpServerAddress;
  115. else
  116. _listTitle = [_ftpServerPath lastPathComponent];
  117. [self _listFTPDirectory];
  118. }
  119. self.tableView.separatorColor = [UIColor VLCDarkBackgroundColor];
  120. self.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
  121. self.title = _listTitle;
  122. _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
  123. UINavigationBar *navBar = self.navigationController.navigationBar;
  124. if (SYSTEM_RUNS_IOS7_OR_LATER)
  125. _searchBar.barTintColor = navBar.barTintColor;
  126. _searchBar.tintColor = navBar.tintColor;
  127. _searchBar.translucent = navBar.translucent;
  128. _searchBar.opaque = navBar.opaque;
  129. _searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
  130. _searchDisplayController.delegate = self;
  131. _searchDisplayController.searchResultsDataSource = self;
  132. _searchDisplayController.searchResultsDelegate = self;
  133. _searchDisplayController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  134. _searchDisplayController.searchResultsTableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  135. if (SYSTEM_RUNS_IOS7_OR_LATER)
  136. _searchDisplayController.searchBar.searchBarStyle = UIBarStyleBlack;
  137. _searchBar.delegate = self;
  138. _searchBar.hidden = YES;
  139. UITapGestureRecognizer *tapTwiceGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwiceGestureAction:)];
  140. [tapTwiceGesture setNumberOfTapsRequired:2];
  141. [self.navigationController.navigationBar addGestureRecognizer:tapTwiceGesture];
  142. _menuButton = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(menuButtonAction:)];
  143. self.navigationItem.rightBarButtonItem = _menuButton;
  144. _searchData = [[NSMutableArray alloc] init];
  145. [_searchData removeAllObjects];
  146. }
  147. - (BOOL)shouldAutorotate
  148. {
  149. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  150. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  151. return NO;
  152. return YES;
  153. }
  154. - (IBAction)menuButtonAction:(id)sender
  155. {
  156. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  157. if (self.isEditing)
  158. [self setEditing:NO animated:YES];
  159. }
  160. #pragma mark - Table view data source
  161. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  162. {
  163. return 1;
  164. }
  165. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  166. {
  167. if (tableView == self.searchDisplayController.searchResultsTableView)
  168. return _searchData.count;
  169. else {
  170. if (_serverType == kVLCServerTypeUPNP)
  171. return _mutableObjectList.count;
  172. return _objectList.count;
  173. }
  174. }
  175. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  176. {
  177. static NSString *CellIdentifier = @"LocalNetworkCellDetail";
  178. VLCLocalNetworkListCell *cell = (VLCLocalNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  179. if (cell == nil)
  180. cell = [VLCLocalNetworkListCell cellWithReuseIdentifier:CellIdentifier];
  181. if (_serverType == kVLCServerTypeUPNP) {
  182. MediaServer1BasicObject *item;
  183. if (tableView == self.searchDisplayController.searchResultsTableView)
  184. item = _searchData[indexPath.row];
  185. else
  186. item = _mutableObjectList[indexPath.row];
  187. if (![item isContainer]) {
  188. MediaServer1ItemObject *mediaItem;
  189. long long mediaSize = 0;
  190. unsigned int durationInSeconds = 0;
  191. unsigned int bitrate = 0;
  192. if (tableView == self.searchDisplayController.searchResultsTableView)
  193. mediaItem = _searchData[indexPath.row];
  194. else
  195. mediaItem = _mutableObjectList[indexPath.row];
  196. MediaServer1ItemRes *resource = nil;
  197. NSEnumerator *e = [[mediaItem resources] objectEnumerator];
  198. while((resource = (MediaServer1ItemRes*)[e nextObject])){
  199. if (resource.bitrate > 0 && resource.durationInSeconds > 0) {
  200. mediaSize = resource.size;
  201. durationInSeconds = resource.durationInSeconds;
  202. bitrate = resource.bitrate;
  203. }
  204. }
  205. if (mediaSize < 1)
  206. mediaSize = [mediaItem.size longLongValue];
  207. if (mediaSize < 1)
  208. mediaSize = (bitrate * durationInSeconds);
  209. // object.item.videoItem.videoBroadcast items (like the HDHomeRun) may not have this information. Center the title (this makes channel names look better for the HDHomeRun)
  210. if (mediaSize > 0 && durationInSeconds > 0) {
  211. [cell setSubtitle: [NSString stringWithFormat:@"%@ (%@)", [NSByteCountFormatter stringFromByteCount:mediaSize countStyle:NSByteCountFormatterCountStyleFile], [VLCTime timeWithInt:durationInSeconds * 1000].stringValue]];
  212. } else {
  213. cell.titleLabelCentered = YES;
  214. }
  215. // Custom TV icon for video broadcasts
  216. if ([[mediaItem objectClass] isEqualToString:@"object.item.videoItem.videoBroadcast"]) {
  217. UIImage *broadcastImage;
  218. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  219. broadcastImage = [UIImage imageNamed:@"TVBroadcastIcon"];
  220. } else {
  221. broadcastImage = [UIImage imageNamed:@"TVBroadcastIcon~ipad"];
  222. }
  223. [cell setIcon:broadcastImage];
  224. } else {
  225. [cell setIcon:[UIImage imageNamed:@"blank"]];
  226. }
  227. [cell setIsDirectory:NO];
  228. if (mediaItem.albumArt != nil)
  229. [cell setIconURL:[NSURL URLWithString:mediaItem.albumArt]];
  230. // Disable downloading for the HDHomeRun for now to avoid infinite downloads (URI needs a duration parameter, otherwise you are just downloading a live stream). VLC also needs an extension in the file name for this to work.
  231. if (![_UPNPdevice VLC_isHDHomeRunMediaServer]) {
  232. cell.isDownloadable = YES;
  233. }
  234. cell.delegate = self;
  235. } else {
  236. [cell setIsDirectory:YES];
  237. if (item.albumArt != nil)
  238. [cell setIconURL:[NSURL URLWithString:item.albumArt]];
  239. [cell setIcon:[UIImage imageNamed:@"folder"]];
  240. }
  241. [cell setTitle:[item title]];
  242. } else if (_serverType == kVLCServerTypeFTP) {
  243. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  244. [ObjList removeAllObjects];
  245. if (tableView == self.searchDisplayController.searchResultsTableView)
  246. [ObjList addObjectsFromArray:_searchData];
  247. else
  248. [ObjList addObjectsFromArray:_objectList];
  249. NSString *rawFileName = [ObjList[indexPath.row] objectForKey:(id)kCFFTPResourceName];
  250. NSData *flippedData = [rawFileName dataUsingEncoding:[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingFTPTextEncoding] intValue] allowLossyConversion:YES];
  251. cell.title = [[NSString alloc] initWithData:flippedData encoding:NSUTF8StringEncoding];
  252. if ([[ObjList[indexPath.row] objectForKey:(id)kCFFTPResourceType] intValue] == 4) {
  253. cell.isDirectory = YES;
  254. cell.icon = [UIImage imageNamed:@"folder"];
  255. } else {
  256. cell.isDirectory = NO;
  257. cell.icon = [UIImage imageNamed:@"blank"];
  258. cell.subtitle = [NSString stringWithFormat:@"%0.2f MB", (float)([[ObjList[indexPath.row] objectForKey:(id)kCFFTPResourceSize] intValue] / 1e6)];
  259. cell.isDownloadable = YES;
  260. cell.delegate = self;
  261. }
  262. }
  263. return cell;
  264. }
  265. #pragma mark - Table view delegate
  266. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCLocalNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  267. {
  268. UIColor *color = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  269. cell.contentView.backgroundColor = cell.titleLabel.backgroundColor = cell.folderTitleLabel.backgroundColor = cell.subtitleLabel.backgroundColor = color;
  270. if (_serverType == kVLCServerTypeFTP)
  271. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row)
  272. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStopped];
  273. }
  274. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  275. {
  276. if (_serverType == kVLCServerTypeUPNP) {
  277. MediaServer1BasicObject *item;
  278. if (tableView == self.searchDisplayController.searchResultsTableView)
  279. item = _searchData[indexPath.row];
  280. else
  281. item = _mutableObjectList[indexPath.row];
  282. if ([item isContainer]) {
  283. MediaServer1ContainerObject *container;
  284. if (tableView == self.searchDisplayController.searchResultsTableView)
  285. container = _searchData[indexPath.row];
  286. else
  287. container = _mutableObjectList[indexPath.row];
  288. VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithUPNPDevice:_UPNPdevice header:[container title] andRootID:[container objectID]];
  289. [[self navigationController] pushViewController:targetViewController animated:YES];
  290. } else {
  291. MediaServer1ItemObject *mediaItem;
  292. if (tableView == self.searchDisplayController.searchResultsTableView)
  293. mediaItem = _searchData[indexPath.row];
  294. else
  295. mediaItem = _mutableObjectList[indexPath.row];
  296. NSURL *itemURL;
  297. NSArray *uriCollectionKeys = [[mediaItem uriCollection] allKeys];
  298. NSUInteger count = uriCollectionKeys.count;
  299. NSRange position;
  300. NSUInteger correctIndex = 0;
  301. NSUInteger numberOfDownloadableResources = 0;
  302. for (NSUInteger i = 0; i < count; i++) {
  303. position = [uriCollectionKeys[i] rangeOfString:@"http-get:*:video/"];
  304. if (position.location != NSNotFound) {
  305. correctIndex = i;
  306. numberOfDownloadableResources++;
  307. }
  308. }
  309. NSArray *uriCollectionObjects = [[mediaItem uriCollection] allValues];
  310. // Present an action sheet for the user to choose which URI to download. Do not deselect the cell to provide visual feedback to the user
  311. if (numberOfDownloadableResources > 1) {
  312. _resourceSelectionActionSheetAnchorView = [tableView cellForRowAtIndexPath:indexPath];
  313. [self presentResourceSelectionActionSheetForUPnPMediaItem:mediaItem forDownloading:NO];
  314. } else {
  315. if (uriCollectionObjects.count > 0) {
  316. itemURL = [NSURL URLWithString:uriCollectionObjects[correctIndex]];
  317. }
  318. if (itemURL) {
  319. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  320. [appDelegate openMovieFromURL:itemURL];
  321. }
  322. }
  323. }
  324. } else if (_serverType == kVLCServerTypeFTP) {
  325. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  326. [ObjList removeAllObjects];
  327. if (tableView == self.searchDisplayController.searchResultsTableView)
  328. [ObjList addObjectsFromArray:_searchData];
  329. else
  330. [ObjList addObjectsFromArray:_objectList];
  331. if ([[ObjList[indexPath.row] objectForKey:(id)kCFFTPResourceType] intValue] == 4) {
  332. NSString *newPath = [NSString stringWithFormat:@"%@/%@", _ftpServerPath, [ObjList[indexPath.row] objectForKey:(id)kCFFTPResourceName]];
  333. VLCLocalServerFolderListViewController *targetViewController = [[VLCLocalServerFolderListViewController alloc] initWithFTPServer:_ftpServerAddress userName:_ftpServerUserName andPassword:_ftpServerPassword atPath:newPath];
  334. [self.navigationController pushViewController:targetViewController animated:YES];
  335. } else {
  336. NSString *rawObjectName = [ObjList[indexPath.row] objectForKey:(id)kCFFTPResourceName];
  337. NSData *flippedData = [rawObjectName dataUsingEncoding:[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingFTPTextEncoding] intValue] allowLossyConversion:YES];
  338. NSString *properObjectName = [[NSString alloc] initWithData:flippedData encoding:NSUTF8StringEncoding];
  339. if (![properObjectName isSupportedFormat]) {
  340. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), properObjectName] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:nil];
  341. [alert show];
  342. } else
  343. [self _streamFTPFile:properObjectName];
  344. }
  345. }
  346. [tableView deselectRowAtIndexPath:indexPath animated:NO];
  347. }
  348. #pragma mark - UPnP Multiple Resources
  349. /// Presents an UIActionSheet for the user to choose which <res> resource to play or download. Contains some display code specific to the HDHomeRun devices. Also parses "DLNA.ORG_PN" protocolInfo.
  350. - (void)presentResourceSelectionActionSheetForUPnPMediaItem:(MediaServer1ItemObject *)mediaItem forDownloading:(BOOL)forDownloading {
  351. NSParameterAssert(mediaItem);
  352. if (!mediaItem) {
  353. return;
  354. }
  355. // Store it so we can act on the action sheet callback.
  356. _lastSelectedMediaItem = mediaItem;
  357. NSArray *uriCollectionKeys = [[_lastSelectedMediaItem uriCollection] allKeys];
  358. NSArray *uriCollectionObjects = [[_lastSelectedMediaItem uriCollection] allValues];
  359. NSUInteger count = uriCollectionKeys.count;
  360. NSRange position;
  361. NSString *titleString;
  362. if (!forDownloading) {
  363. titleString = NSLocalizedString(@"SELECT_RESOURCE_TO_PLAY", nil);
  364. } else {
  365. titleString = NSLocalizedString(@"SELECT_RESOURCE_TO_DOWNLOAD", nil);
  366. }
  367. UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:titleString
  368. delegate:self
  369. cancelButtonTitle:nil
  370. destructiveButtonTitle:nil
  371. otherButtonTitles:nil];
  372. // Provide users with a descriptive action sheet for them to choose based on the multiple resources advertised by DLNA devices (HDHomeRun for example)
  373. for (NSUInteger i = 0; i < count; i++) {
  374. position = [uriCollectionKeys[i] rangeOfString:@"http-get:*:video/"];
  375. if (position.location != NSNotFound) {
  376. NSString *orgPNValue;
  377. NSString *transcodeValue;
  378. // Attempt to parse DLNA.ORG_PN first
  379. NSString *protocolInfo = uriCollectionKeys[i];
  380. NSArray *components = [protocolInfo componentsSeparatedByString:@";"];
  381. NSArray *nonFlagsComponents = [components[0] componentsSeparatedByString:@":"];
  382. NSString *orgPN = [nonFlagsComponents lastObject];
  383. // Check to see if we are where we should be
  384. NSRange orgPNRange = [orgPN rangeOfString:@"DLNA.ORG_PN="];
  385. if (orgPNRange.location == 0) {
  386. orgPNValue = [orgPN substringFromIndex:orgPNRange.length];
  387. }
  388. // HDHomeRun: Get the transcode profile from the HTTP API if possible
  389. if ([_UPNPdevice VLC_isHDHomeRunMediaServer]) {
  390. NSRange transcodeRange = [uriCollectionObjects[i] rangeOfString:@"transcode="];
  391. if (transcodeRange.location != NSNotFound) {
  392. transcodeValue = [uriCollectionObjects[i] substringFromIndex:transcodeRange.location + transcodeRange.length];
  393. // Check that there are no more parameters
  394. NSRange ampersandRange = [transcodeValue rangeOfString:@"&"];
  395. if (ampersandRange.location != NSNotFound) {
  396. transcodeValue = [transcodeValue substringToIndex:transcodeRange.location];
  397. }
  398. transcodeValue = [transcodeValue capitalizedString];
  399. }
  400. }
  401. // Fallbacks to get the most descriptive resource title
  402. NSString *profileTitle;
  403. if ([transcodeValue length] && [orgPNValue length]) {
  404. profileTitle = [NSString stringWithFormat:@"%@ (%@)", transcodeValue, orgPNValue];
  405. // The extra whitespace is to get UIActionSheet to render the text better (this bug has been fixed in iOS 8)
  406. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  407. if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
  408. profileTitle = [NSString stringWithFormat:@" %@ ", profileTitle];
  409. }
  410. }
  411. } else if ([transcodeValue length]) {
  412. profileTitle = transcodeValue;
  413. } else if ([orgPNValue length]) {
  414. profileTitle = orgPNValue;
  415. } else if ([uriCollectionKeys[i] length]) {
  416. profileTitle = uriCollectionKeys[i];
  417. } else if ([uriCollectionObjects[i] length]) {
  418. profileTitle = uriCollectionObjects[i];
  419. } else {
  420. profileTitle = NSLocalizedString(@"UNKNOWN", nil);
  421. }
  422. [actionSheet addButtonWithTitle:profileTitle];
  423. }
  424. }
  425. // If no resources are found, an empty action sheet will be presented, but the fact that we got here implies that we have playable resources, so no special handling for this case is included
  426. actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)];
  427. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  428. // Attach it to a specific view (a cell, a download button, etc)
  429. if (_resourceSelectionActionSheetAnchorView) {
  430. CGRect presentationRect = [self.view convertRect:_resourceSelectionActionSheetAnchorView.frame fromView:_resourceSelectionActionSheetAnchorView.superview];
  431. [actionSheet showFromRect:presentationRect inView:self.view animated:YES];
  432. } else {
  433. [actionSheet showInView:self.view];
  434. }
  435. } else {
  436. [actionSheet showInView:self.view];
  437. }
  438. }
  439. #pragma mark - UIActionSheetDelegate
  440. - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
  441. {
  442. // Act on the selected resource that the user selected
  443. if (_lastSelectedMediaItem) {
  444. if (buttonIndex != actionSheet.cancelButtonIndex) {
  445. // Check again through our raw list which items are playable, since this same code was used to build the action sheet. Make sure we choose the right object based on the action sheet button index.
  446. NSArray *uriCollectionKeys = [[_lastSelectedMediaItem uriCollection] allKeys];
  447. NSArray *uriCollectionObjects = [[_lastSelectedMediaItem uriCollection] allValues];
  448. if (uriCollectionObjects.count > 0) {
  449. NSUInteger count = uriCollectionKeys.count;
  450. NSMutableArray *possibleCollectionObjects = [[NSMutableArray alloc] initWithCapacity:[uriCollectionObjects count]];
  451. for (NSUInteger i = 0; i < count; i++) {
  452. if ([uriCollectionKeys[i] rangeOfString:@"http-get:*:video/"].location != NSNotFound) {
  453. [possibleCollectionObjects addObject:uriCollectionObjects[i]];
  454. }
  455. }
  456. NSString *itemURLString = uriCollectionObjects[buttonIndex];
  457. if ([itemURLString length]) {
  458. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  459. [appDelegate openMovieFromURL:[NSURL URLWithString:itemURLString]];
  460. }
  461. }
  462. }
  463. _lastSelectedMediaItem = nil;
  464. _resourceSelectionActionSheetAnchorView = nil;
  465. UITableView *activeTableView;
  466. if ([self.searchDisplayController isActive]) {
  467. activeTableView = self.searchDisplayController.searchResultsTableView;
  468. } else {
  469. activeTableView = self.tableView;
  470. }
  471. [activeTableView deselectRowAtIndexPath:[activeTableView indexPathForSelectedRow] animated:NO];
  472. }
  473. }
  474. #pragma mark - FTP specifics
  475. - (void)_listFTPDirectory
  476. {
  477. if (_FTPListDirRequest)
  478. return;
  479. _FTPListDirRequest = [[WRRequestListDirectory alloc] init];
  480. _FTPListDirRequest.delegate = self;
  481. _FTPListDirRequest.hostname = _ftpServerAddress;
  482. _FTPListDirRequest.username = _ftpServerUserName;
  483. _FTPListDirRequest.password = _ftpServerPassword;
  484. _FTPListDirRequest.path = _ftpServerPath;
  485. _FTPListDirRequest.passive = YES;
  486. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  487. [_FTPListDirRequest start];
  488. }
  489. - (NSString *)_credentials
  490. {
  491. NSString * cred;
  492. if (_ftpServerUserName.length > 0) {
  493. if (_ftpServerPassword.length > 0)
  494. cred = [NSString stringWithFormat:@"%@:%@@", _ftpServerUserName, _ftpServerPassword];
  495. else
  496. cred = [NSString stringWithFormat:@"%@@", _ftpServerPassword];
  497. } else
  498. cred = @"";
  499. return [cred stringByStandardizingPath];
  500. }
  501. - (void)_downloadFTPFile:(NSString *)fileName
  502. {
  503. NSURL *URLToQueue = [NSURL URLWithString:[[@"ftp" stringByAppendingFormat:@"://%@%@/%@/%@", [self _credentials], _ftpServerAddress, _ftpServerPath, fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  504. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate downloadViewController] addURLToDownloadList:URLToQueue fileNameOfMedia:nil];
  505. }
  506. - (void)_downloadUPNPFileFromMediaItem:(MediaServer1ItemObject *)mediaItem
  507. {
  508. NSURL *itemURL;
  509. NSArray *uriCollectionKeys = [[mediaItem uriCollection] allKeys];
  510. NSUInteger count = uriCollectionKeys.count;
  511. NSRange position;
  512. NSUInteger correctIndex = 0;
  513. for (NSUInteger i = 0; i < count; i++) {
  514. position = [uriCollectionKeys[i] rangeOfString:@"http-get:*:video/"];
  515. if (position.location != NSNotFound)
  516. correctIndex = i;
  517. }
  518. NSArray *uriCollectionObjects = [[mediaItem uriCollection] allValues];
  519. if (uriCollectionObjects.count > 0)
  520. itemURL = [NSURL URLWithString:uriCollectionObjects[correctIndex]];
  521. if (![itemURL.absoluteString isSupportedFormat]) {
  522. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [mediaItem uri]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:nil];
  523. [alert show];
  524. } else if (itemURL) {
  525. NSString *fileName = [[mediaItem.title stringByAppendingString:@"."] stringByAppendingString:[[itemURL absoluteString] pathExtension]];
  526. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate downloadViewController] addURLToDownloadList:itemURL fileNameOfMedia:fileName];
  527. }
  528. }
  529. - (void)requestCompleted:(WRRequest *)request
  530. {
  531. if (request == _FTPListDirRequest) {
  532. NSMutableArray *filteredList = [[NSMutableArray alloc] init];
  533. NSArray *rawList = [(WRRequestListDirectory*)request filesInfo];
  534. NSUInteger count = rawList.count;
  535. for (NSUInteger x = 0; x < count; x++) {
  536. if (![[rawList[x] objectForKey:(id)kCFFTPResourceName] hasPrefix:@"."])
  537. [filteredList addObject:rawList[x]];
  538. }
  539. _objectList = [NSArray arrayWithArray:filteredList];
  540. [self.tableView reloadData];
  541. } else
  542. APLog(@"unknown request %@ completed", request);
  543. }
  544. - (void)requestFailed:(WRRequest *)request
  545. {
  546. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"LOCAL_SERVER_CONNECTION_FAILED_TITLE", nil) message:NSLocalizedString(@"LOCAL_SERVER_CONNECTION_FAILED_MESSAGE", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:nil];
  547. [alert show];
  548. APLog(@"request %@ failed with error %i", request, request.error.errorCode);
  549. }
  550. #pragma mark - VLCLocalNetworkListCell delegation
  551. - (void)triggerDownloadForCell:(VLCLocalNetworkListCell *)cell
  552. {
  553. if (_serverType == kVLCServerTypeUPNP) {
  554. MediaServer1ItemObject *item;
  555. if ([self.searchDisplayController isActive])
  556. item = _searchData[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row];
  557. else
  558. item = _mutableObjectList[[self.tableView indexPathForCell:cell].row];
  559. [self _downloadUPNPFileFromMediaItem:item];
  560. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", nil)];
  561. }else if (_serverType == kVLCServerTypeFTP) {
  562. NSString *rawObjectName;
  563. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  564. [ObjList removeAllObjects];
  565. if ([self.searchDisplayController isActive]) {
  566. [ObjList addObjectsFromArray:_searchData];
  567. rawObjectName = [ObjList[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row] objectForKey:(id)kCFFTPResourceName];
  568. } else {
  569. [ObjList addObjectsFromArray:_objectList];
  570. rawObjectName = [ObjList[[self.tableView indexPathForCell:cell].row] objectForKey:(id)kCFFTPResourceName];
  571. }
  572. NSData *flippedData = [rawObjectName dataUsingEncoding:[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingFTPTextEncoding] intValue] allowLossyConversion:YES];
  573. NSString *properObjectName = [[NSString alloc] initWithData:flippedData encoding:NSUTF8StringEncoding];
  574. if (![properObjectName isSupportedFormat]) {
  575. UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), properObjectName] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:nil];
  576. [alert show];
  577. } else {
  578. [self _downloadFTPFile:properObjectName];
  579. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", nil)];
  580. }
  581. }
  582. }
  583. #pragma mark - communication with playback engine
  584. - (void)_streamFTPFile:(NSString *)fileName
  585. {
  586. NSString *URLofSubtitle = nil;
  587. NSMutableArray *SubtitlesList = [[NSMutableArray alloc] init];
  588. [SubtitlesList removeAllObjects];
  589. SubtitlesList = [self _searchSubtitle:fileName];
  590. if(SubtitlesList.count > 0)
  591. URLofSubtitle = [self _getFileSubtitleFromFtpServer:SubtitlesList[0]];
  592. NSURL *URLToPlay = [NSURL URLWithString:[[@"ftp" stringByAppendingFormat:@"://%@%@/%@/%@", [self _credentials], _ftpServerAddress, _ftpServerPath, fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  593. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  594. [appDelegate openMovieWithExternalSubtitleFromURL:URLToPlay externalSubURL:URLofSubtitle];
  595. }
  596. - (NSMutableArray *)_searchSubtitle:(NSString *)url
  597. {
  598. NSString *urlTemp = [[url lastPathComponent] stringByDeletingPathExtension];
  599. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  600. [ObjList removeAllObjects];
  601. for (int loop = 0; loop < _objectList.count; loop++)
  602. [ObjList addObject:[_objectList[loop] objectForKey:(id)kCFFTPResourceName]];
  603. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", urlTemp];
  604. NSArray *results = [ObjList filteredArrayUsingPredicate:predicate];
  605. [ObjList removeAllObjects];
  606. for (int cnt = 0; cnt < results.count; cnt++) {
  607. if ([results[cnt] isSupportedSubtitleFormat])
  608. [ObjList addObject:results[cnt]];
  609. }
  610. return ObjList;
  611. }
  612. - (NSString *)_getFileSubtitleFromFtpServer:(NSString *)fileName
  613. {
  614. NSURL *url = [NSURL URLWithString:[[@"ftp" stringByAppendingFormat:@"://%@%@/%@/%@", [self _credentials], _ftpServerAddress, _ftpServerPath, fileName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  615. NSString *receivedSub = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
  616. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  617. NSString *directoryPath = searchPaths[0];
  618. NSString *FileSubtitlePath = [directoryPath stringByAppendingPathComponent:[fileName lastPathComponent]];
  619. NSFileManager *fileManager = [NSFileManager defaultManager];
  620. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  621. //create local subtitle file
  622. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  623. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  624. APLog(@"file creation failed, no data was saved");
  625. }
  626. [receivedSub writeToFile:FileSubtitlePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  627. return FileSubtitlePath;
  628. }
  629. #pragma mark - Search Display Controller Delegate
  630. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  631. {
  632. MediaServer1BasicObject *item;
  633. NSInteger listCount = 0;
  634. [_searchData removeAllObjects];
  635. if (_serverType == kVLCServerTypeUPNP)
  636. listCount = _mutableObjectList.count;
  637. else if (_serverType == kVLCServerTypeFTP)
  638. listCount = _objectList.count;
  639. for (int i = 0; i < listCount; i++) {
  640. NSRange nameRange;
  641. if (_serverType == kVLCServerTypeUPNP) {
  642. item = _mutableObjectList[i];
  643. nameRange = [[item title] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  644. } else if (_serverType == kVLCServerTypeFTP) {
  645. NSString *rawObjectName = [_objectList[i] objectForKey:(id)kCFFTPResourceName];
  646. NSData *flippedData = [rawObjectName dataUsingEncoding:[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingFTPTextEncoding] intValue] allowLossyConversion:YES];
  647. NSString *properObjectName = [[NSString alloc] initWithData:flippedData encoding:NSUTF8StringEncoding];
  648. nameRange = [properObjectName rangeOfString:searchString options:NSCaseInsensitiveSearch];
  649. }
  650. if (nameRange.location != NSNotFound) {
  651. if (_serverType == kVLCServerTypeUPNP)
  652. [_searchData addObject:_mutableObjectList[i]];
  653. else
  654. [_searchData addObject:_objectList[i]];
  655. }
  656. }
  657. return YES;
  658. }
  659. - (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
  660. {
  661. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  662. tableView.rowHeight = 80.0f;
  663. else
  664. tableView.rowHeight = 68.0f;
  665. tableView.backgroundColor = [UIColor blackColor];
  666. }
  667. #pragma mark - Gesture Action
  668. - (void)tapTwiceGestureAction:(UIGestureRecognizer *)recognizer
  669. {
  670. _searchBar.hidden = !_searchBar.hidden;
  671. if (_searchBar.hidden)
  672. self.tableView.tableHeaderView = nil;
  673. else
  674. self.tableView.tableHeaderView = _searchBar;
  675. [self.tableView setContentOffset:CGPointMake(0.0f, -self.tableView.contentInset.top) animated:NO];
  676. }
  677. @end