VLCLocalServerFolderListViewController.m 35 KB

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