VLCLocalServerFolderListViewController.m 34 KB

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