VLCNetworkServerBrowserViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /*****************************************************************************
  2. * VLCNetworkServerBrowserViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Pierre SAGASPE <pierre.sagaspe # me.com>
  10. * Tobias Conradi <videolan # tobias-conradi.de>
  11. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCNetworkServerBrowserViewController.h"
  15. #import "VLCNetworkListCell.h"
  16. #import "VLCActivityManager.h"
  17. #import "NSString+SupportedMedia.h"
  18. #import "UIDevice+VLC.h"
  19. #import "VLCStatusLabel.h"
  20. #import "VLCPlaybackController.h"
  21. #import "VLCDownloadViewController.h"
  22. #import "WhiteRaccoon.h"
  23. #import "VLCNetworkServerBrowser-Protocol.h"
  24. @interface VLCNetworkServerBrowserViewController () <VLCNetworkServerBrowserDelegate,VLCNetworkListCellDelegate, UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate>
  25. {
  26. UIRefreshControl *_refreshControl;
  27. }
  28. @property (nonatomic) id<VLCNetworkServerBrowser> serverBrowser;
  29. @property (nonatomic) NSByteCountFormatter *byteCounterFormatter;
  30. @property (nonatomic) NSArray<id<VLCNetworkServerBrowserItem>> *searchArray;
  31. @property (nonatomic, readonly) NSCache *imageCache;
  32. @end
  33. @implementation VLCNetworkServerBrowserViewController
  34. - (instancetype)initWithServerBrowser:(id<VLCNetworkServerBrowser>)browser
  35. {
  36. self = [super init];
  37. if (self) {
  38. _serverBrowser = browser;
  39. browser.delegate = self;
  40. _imageCache = [[NSCache alloc] init];
  41. [_imageCache setCountLimit:50];
  42. }
  43. return self;
  44. }
  45. - (void)viewDidLoad
  46. {
  47. [super viewDidLoad];
  48. _refreshControl = [[UIRefreshControl alloc] init];
  49. _refreshControl.backgroundColor = [UIColor VLCDarkBackgroundColor];
  50. _refreshControl.tintColor = [UIColor whiteColor];
  51. [_refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];
  52. [self.tableView addSubview:_refreshControl];
  53. self.title = self.serverBrowser.title;
  54. [self update];
  55. }
  56. - (void)networkServerBrowserDidUpdate:(id<VLCNetworkServerBrowser>)networkBrowser {
  57. [self.tableView reloadData];
  58. [[VLCActivityManager defaultManager] networkActivityStopped];
  59. [_refreshControl endRefreshing];
  60. }
  61. - (void)networkServerBrowser:(id<VLCNetworkServerBrowser>)networkBrowser requestDidFailWithError:(NSError *)error {
  62. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"LOCAL_SERVER_CONNECTION_FAILED_TITLE", nil)
  63. message:NSLocalizedString(@"LOCAL_SERVER_CONNECTION_FAILED_MESSAGE", nil)
  64. delegate:self
  65. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  66. otherButtonTitles:nil];
  67. [alert show];
  68. }
  69. - (void)update
  70. {
  71. [self.serverBrowser update];
  72. [[VLCActivityManager defaultManager] networkActivityStarted];
  73. }
  74. -(void)handleRefresh
  75. {
  76. //set the title while refreshing
  77. _refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"LOCAL_SERVER_REFRESH",nil)];
  78. //set the date and time of refreshing
  79. NSDateFormatter *formattedDate = [[NSDateFormatter alloc]init];
  80. [formattedDate setDateFormat:@"MMM d, h:mm a"];
  81. NSString *lastupdated = [NSString stringWithFormat:NSLocalizedString(@"LOCAL_SERVER_LAST_UPDATE",nil),[formattedDate stringFromDate:[NSDate date]]];
  82. NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
  83. _refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastupdated attributes:attrsDictionary];
  84. //end the refreshing
  85. [self update];
  86. }
  87. #pragma mark -
  88. - (NSByteCountFormatter *)byteCounterFormatter {
  89. if (!_byteCounterFormatter) {
  90. _byteCounterFormatter = [[NSByteCountFormatter alloc] init];
  91. }
  92. return _byteCounterFormatter;
  93. }
  94. - (BOOL)isSupportedItem:(id<VLCNetworkServerBrowserItem>)item {
  95. NSString *properObjectName = item.name;
  96. NSString *itemURLName = item.URL.lastPathComponent;
  97. return [properObjectName isSupportedFormat] || [itemURLName isSupportedFormat];
  98. }
  99. - (void)showUnsupportedFileAlertForItem:(id<VLCNetworkServerBrowserItem>)item {
  100. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  101. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), item.name]
  102. delegate:self
  103. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  104. otherButtonTitles:nil];
  105. [alert show];
  106. }
  107. #pragma mark - server browser item specifics
  108. - (void)_downloadItem:(id<VLCNetworkServerBrowserItem>)item
  109. {
  110. NSString *filename = item.name;
  111. if (filename.pathExtension.length == 0) {
  112. /* there are few crappy UPnP servers who don't reveal the correct file extension, so we use a generic fake (#11123) */
  113. NSString *urlExtension = item.URL.pathExtension;
  114. NSString *extension = urlExtension.length != 0 ? urlExtension : @"vlc";
  115. filename = [filename stringByAppendingPathExtension:extension];
  116. }
  117. [[VLCDownloadViewController sharedInstance] addURLToDownloadList:item.URL
  118. fileNameOfMedia:filename];
  119. }
  120. - (void)_streamMediaList:(VLCMediaList *)mediaList startingAtIndex:(NSInteger)startIndex
  121. {
  122. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  123. [vpc playMediaList:mediaList firstIndex:startIndex];
  124. }
  125. - (void)_streamFileForItem:(id<VLCNetworkServerBrowserItem>)item
  126. {
  127. NSString *URLofSubtitle = nil;
  128. NSURL *remoteSubtitleURL = nil;
  129. if ([item respondsToSelector:@selector(subtitleURL)]) {
  130. remoteSubtitleURL = [item subtitleURL];
  131. }
  132. if (!remoteSubtitleURL) {
  133. NSArray *SubtitlesList = [self _searchSubtitle:item.URL.lastPathComponent];
  134. remoteSubtitleURL = SubtitlesList.firstObject;
  135. }
  136. if(remoteSubtitleURL)
  137. URLofSubtitle = [self _getFileSubtitleFromServer:remoteSubtitleURL];
  138. NSURL *URLToPlay = item.URL;
  139. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  140. [vpc playURL:URLToPlay subtitlesFilePath:URLofSubtitle];
  141. }
  142. - (NSArray<NSURL*> *)_searchSubtitle:(NSString *)url
  143. {
  144. NSString *urlTemp = [[url lastPathComponent] stringByDeletingPathExtension];
  145. NSMutableArray<NSURL*> *urls = [NSMutableArray arrayWithArray:[self.serverBrowser.items valueForKey:@"URL"]];
  146. NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF.path contains[c] %@", urlTemp];
  147. [urls filterUsingPredicate:namePredicate];
  148. NSPredicate *formatPrediate = [NSPredicate predicateWithBlock:^BOOL(NSURL *_Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
  149. return [evaluatedObject.path isSupportedSubtitleFormat];
  150. }];
  151. [urls filterUsingPredicate:formatPrediate];
  152. return [NSArray arrayWithArray:urls];
  153. }
  154. - (NSString *)_getFileSubtitleFromServer:(NSURL *)subtitleURL
  155. {
  156. NSString *FileSubtitlePath = nil;
  157. NSData *receivedSub = [NSData dataWithContentsOfURL:subtitleURL]; // TODO: fix synchronous load
  158. if (receivedSub.length < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  159. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  160. NSString *directoryPath = searchPaths[0];
  161. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:[subtitleURL lastPathComponent]];
  162. NSFileManager *fileManager = [NSFileManager defaultManager];
  163. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  164. //create local subtitle file
  165. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  166. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  167. APLog(@"file creation failed, no data was saved");
  168. return nil;
  169. }
  170. }
  171. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  172. } else {
  173. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  174. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), [subtitleURL lastPathComponent], [[UIDevice currentDevice] model]]
  175. delegate:self
  176. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  177. otherButtonTitles:nil];
  178. [alert show];
  179. }
  180. return FileSubtitlePath;
  181. }
  182. - (UIImage *)getCachedImage:(NSURL *)url
  183. {
  184. UIImage *image = [self.imageCache objectForKey:url];
  185. if ((image != nil) && [image isKindOfClass:[UIImage class]]) {
  186. return image;
  187. } else {
  188. NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
  189. if (imageData) {
  190. image = [[UIImage alloc] initWithData:imageData];
  191. [self.imageCache setObject:image forKey:url];
  192. }
  193. return image;
  194. }
  195. }
  196. #pragma mark - table view data source, for more see super
  197. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  198. {
  199. if (tableView == self.searchDisplayController.searchResultsTableView)
  200. return _searchArray.count;
  201. return self.serverBrowser.items.count;
  202. }
  203. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  204. {
  205. VLCNetworkListCell *cell = (VLCNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:VLCNetworkListCellIdentifier];
  206. if (cell == nil)
  207. cell = [VLCNetworkListCell cellWithReuseIdentifier:VLCNetworkListCellIdentifier];
  208. id<VLCNetworkServerBrowserItem> item;
  209. if (tableView == self.searchDisplayController.searchResultsTableView) {
  210. item = _searchArray[indexPath.row];
  211. } else {
  212. item = self.serverBrowser.items[indexPath.row];
  213. }
  214. cell.title = item.name;
  215. if (item.isContainer) {
  216. cell.isDirectory = YES;
  217. cell.icon = [UIImage imageNamed:@"folder"];
  218. } else {
  219. cell.isDirectory = NO;
  220. cell.icon = [UIImage imageNamed:@"blank"];
  221. NSString *sizeString = item.fileSizeBytes ? [self.byteCounterFormatter stringFromByteCount:item.fileSizeBytes.longLongValue] : nil;
  222. NSString *duration = nil;
  223. if ([item respondsToSelector:@selector(duration)]) {
  224. duration = item.duration;
  225. }
  226. NSString *subtitle = nil;
  227. if (sizeString && duration) {
  228. subtitle = [NSString stringWithFormat:@"%@ (%@)",sizeString, duration];
  229. } else if (sizeString) {
  230. subtitle = sizeString;
  231. } else if (duration) {
  232. subtitle = duration;
  233. }
  234. cell.subtitle = sizeString;
  235. cell.isDownloadable = YES;
  236. cell.delegate = self;
  237. NSURL *thumbnailURL = nil;
  238. if ([item respondsToSelector:@selector(thumbnailURL)]) {
  239. thumbnailURL = item.thumbnailURL;
  240. }
  241. if (thumbnailURL) {
  242. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
  243. dispatch_async(queue, ^{
  244. UIImage *img = [self getCachedImage:thumbnailURL];
  245. dispatch_async(dispatch_get_main_queue(), ^{
  246. if (img) {
  247. [cell setIcon:img];
  248. }
  249. });
  250. });
  251. }
  252. }
  253. return cell;
  254. }
  255. #pragma mark - table view delegate, for more see super
  256. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  257. {
  258. [super tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath];
  259. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row)
  260. [[VLCActivityManager defaultManager] networkActivityStopped];
  261. }
  262. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  263. {
  264. id<VLCNetworkServerBrowserItem> item;
  265. NSInteger row = indexPath.row;
  266. BOOL searchResult = NO;
  267. if (tableView == self.searchDisplayController.searchResultsTableView) {
  268. item = _searchArray[row];
  269. searchResult = YES;
  270. } else {
  271. item = self.serverBrowser.items[row];
  272. }
  273. if (item.isContainer) {
  274. VLCNetworkServerBrowserViewController *targetViewController = [[VLCNetworkServerBrowserViewController alloc] initWithServerBrowser:item.containerBrowser];
  275. [self.navigationController pushViewController:targetViewController animated:YES];
  276. } else {
  277. if (![self isSupportedItem:item]) {
  278. [self showUnsupportedFileAlertForItem:item];
  279. } else {
  280. if (searchResult) {
  281. [self _streamFileForItem:item];
  282. } else {
  283. VLCMediaList *mediaList = self.serverBrowser.mediaList;
  284. if ([item respondsToSelector:@selector(subtitleURL)]) {
  285. NSArray *items = self.serverBrowser.items;
  286. id<VLCNetworkServerBrowserItem> loopItem;
  287. [mediaList lock];
  288. NSUInteger count = mediaList.count;
  289. for (NSUInteger i = 0; i < count; i++) {
  290. loopItem = items[i];
  291. NSString *URLofSubtitle = nil;
  292. NSURL *remoteSubtitleURL = [loopItem subtitleURL];
  293. if (remoteSubtitleURL == nil) {
  294. NSArray *SubtitlesList = [self _searchSubtitle:loopItem.URL.lastPathComponent];
  295. remoteSubtitleURL = SubtitlesList.firstObject;
  296. }
  297. if(remoteSubtitleURL != nil) {
  298. URLofSubtitle = [self _getFileSubtitleFromServer:remoteSubtitleURL];
  299. if (URLofSubtitle != nil)
  300. [[mediaList mediaAtIndex:i] addOptions:@{ kVLCSettingSubtitlesFilePath : URLofSubtitle }];
  301. }
  302. }
  303. [mediaList unlock];
  304. }
  305. [self _streamMediaList:mediaList startingAtIndex:row];
  306. }
  307. }
  308. }
  309. [tableView deselectRowAtIndexPath:indexPath animated:NO];
  310. }
  311. #pragma mark - VLCNetworkListCell delegation
  312. - (void)triggerDownloadForCell:(VLCNetworkListCell *)cell
  313. {
  314. id<VLCNetworkServerBrowserItem> item;
  315. if ([self.searchDisplayController isActive])
  316. item = _searchArray[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row];
  317. else
  318. item = self.serverBrowser.items[[self.tableView indexPathForCell:cell].row];
  319. if (![self isSupportedItem:item]) {
  320. [self showUnsupportedFileAlertForItem:item];
  321. } else {
  322. if (item.fileSizeBytes.longLongValue < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  323. [self _downloadItem:item];
  324. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", nil)];
  325. } else {
  326. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  327. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), item.name, [[UIDevice currentDevice] model]]
  328. delegate:self
  329. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  330. otherButtonTitles:nil];
  331. [alert show];
  332. }
  333. }
  334. }
  335. #pragma mark - search
  336. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  337. {
  338. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@",searchString];
  339. self.searchArray = [self.serverBrowser.items filteredArrayUsingPredicate:predicate];
  340. return YES;
  341. }
  342. @end