VLCLocalServerFolderListViewController.m 35 KB

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