VLCNetworkServerBrowserViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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)_streamFileForItem:(id<VLCNetworkServerBrowserItem>)item
  121. {
  122. NSString *URLofSubtitle = nil;
  123. NSURL *remoteSubtitleURL = nil;
  124. if ([item respondsToSelector:@selector(subtitleURL)]) {
  125. remoteSubtitleURL = [item subtitleURL];
  126. }
  127. if (!remoteSubtitleURL) {
  128. NSArray *SubtitlesList = [self _searchSubtitle:item.URL.lastPathComponent];
  129. remoteSubtitleURL = SubtitlesList.firstObject;
  130. }
  131. if(remoteSubtitleURL)
  132. URLofSubtitle = [self _getFileSubtitleFromServer:remoteSubtitleURL];
  133. NSURL *URLToPlay = item.URL;
  134. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  135. [vpc playURL:URLToPlay subtitlesFilePath:URLofSubtitle];
  136. }
  137. - (NSArray<NSURL*> *)_searchSubtitle:(NSString *)url
  138. {
  139. NSString *urlTemp = [[url lastPathComponent] stringByDeletingPathExtension];
  140. NSMutableArray<NSURL*> *urls = [NSMutableArray arrayWithArray:[self.serverBrowser.items valueForKey:@"URL"]];
  141. NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF.path contains[c] %@", urlTemp];
  142. [urls filterUsingPredicate:namePredicate];
  143. NSPredicate *formatPrediate = [NSPredicate predicateWithBlock:^BOOL(NSURL *_Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
  144. return [evaluatedObject.path isSupportedSubtitleFormat];
  145. }];
  146. [urls filterUsingPredicate:formatPrediate];
  147. return [NSArray arrayWithArray:urls];
  148. }
  149. - (NSString *)_getFileSubtitleFromServer:(NSURL *)subtitleURL
  150. {
  151. NSString *FileSubtitlePath = nil;
  152. NSData *receivedSub = [NSData dataWithContentsOfURL:subtitleURL]; // TODO: fix synchronous load
  153. if (receivedSub.length < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  154. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  155. NSString *directoryPath = searchPaths[0];
  156. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:[subtitleURL lastPathComponent]];
  157. NSFileManager *fileManager = [NSFileManager defaultManager];
  158. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  159. //create local subtitle file
  160. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  161. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  162. APLog(@"file creation failed, no data was saved");
  163. }
  164. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  165. } else {
  166. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  167. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), [subtitleURL lastPathComponent], [[UIDevice currentDevice] model]]
  168. delegate:self
  169. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  170. otherButtonTitles:nil];
  171. [alert show];
  172. }
  173. return FileSubtitlePath;
  174. }
  175. - (UIImage *)getCachedImage:(NSURL *)url
  176. {
  177. UIImage *image = [self.imageCache objectForKey:url];
  178. if ((image != nil) && [image isKindOfClass:[UIImage class]]) {
  179. return image;
  180. } else {
  181. NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
  182. if (imageData) {
  183. image = [[UIImage alloc] initWithData:imageData];
  184. [self.imageCache setObject:image forKey:url];
  185. }
  186. return image;
  187. }
  188. }
  189. #pragma mark - table view data source, for more see super
  190. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  191. {
  192. if (tableView == self.searchDisplayController.searchResultsTableView)
  193. return _searchArray.count;
  194. return self.serverBrowser.items.count;
  195. }
  196. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  197. {
  198. VLCNetworkListCell *cell = (VLCNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:VLCNetworkListCellIdentifier];
  199. if (cell == nil)
  200. cell = [VLCNetworkListCell cellWithReuseIdentifier:VLCNetworkListCellIdentifier];
  201. id<VLCNetworkServerBrowserItem> item;
  202. if (tableView == self.searchDisplayController.searchResultsTableView) {
  203. item = _searchArray[indexPath.row];
  204. } else {
  205. item = self.serverBrowser.items[indexPath.row];
  206. }
  207. cell.title = item.name;
  208. if (item.isContainer) {
  209. cell.isDirectory = YES;
  210. cell.icon = [UIImage imageNamed:@"folder"];
  211. } else {
  212. cell.isDirectory = NO;
  213. cell.icon = [UIImage imageNamed:@"blank"];
  214. NSString *sizeString = item.fileSizeBytes ? [self.byteCounterFormatter stringFromByteCount:item.fileSizeBytes.longLongValue] : nil;
  215. NSString *duration = nil;
  216. if ([item respondsToSelector:@selector(duration)]) {
  217. duration = item.duration;
  218. }
  219. NSString *subtitle = nil;
  220. if (sizeString && duration) {
  221. subtitle = [NSString stringWithFormat:@"%@ (%@)",sizeString, duration];
  222. } else if (sizeString) {
  223. subtitle = sizeString;
  224. } else if (duration) {
  225. subtitle = duration;
  226. }
  227. cell.subtitle = sizeString;
  228. cell.isDownloadable = YES;
  229. cell.delegate = self;
  230. NSURL *thumbnailURL = nil;
  231. if ([item respondsToSelector:@selector(thumbnailURL)]) {
  232. thumbnailURL = item.thumbnailURL;
  233. }
  234. if (thumbnailURL) {
  235. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
  236. dispatch_async(queue, ^{
  237. UIImage *img = [self getCachedImage:thumbnailURL];
  238. dispatch_async(dispatch_get_main_queue(), ^{
  239. if (img) {
  240. [cell setIcon:img];
  241. }
  242. });
  243. });
  244. }
  245. }
  246. return cell;
  247. }
  248. #pragma mark - table view delegate, for more see super
  249. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  250. {
  251. [super tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath];
  252. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row)
  253. [[VLCActivityManager defaultManager] networkActivityStopped];
  254. }
  255. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  256. {
  257. id<VLCNetworkServerBrowserItem> item;
  258. if (tableView == self.searchDisplayController.searchResultsTableView) {
  259. item = _searchArray[indexPath.row];
  260. } else {
  261. item = self.serverBrowser.items[indexPath.row];
  262. }
  263. if (item.isContainer) {
  264. VLCNetworkServerBrowserViewController *targetViewController = [[VLCNetworkServerBrowserViewController alloc] initWithServerBrowser:item.containerBrowser];
  265. [self.navigationController pushViewController:targetViewController animated:YES];
  266. } else {
  267. if (![self isSupportedItem:item]) {
  268. [self showUnsupportedFileAlertForItem:item];
  269. } else
  270. [self _streamFileForItem:item];
  271. }
  272. [tableView deselectRowAtIndexPath:indexPath animated:NO];
  273. }
  274. #pragma mark - VLCNetworkListCell delegation
  275. - (void)triggerDownloadForCell:(VLCNetworkListCell *)cell
  276. {
  277. id<VLCNetworkServerBrowserItem> item;
  278. if ([self.searchDisplayController isActive])
  279. item = _searchArray[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row];
  280. else
  281. item = self.serverBrowser.items[[self.tableView indexPathForCell:cell].row];
  282. if (![self isSupportedItem:item]) {
  283. [self showUnsupportedFileAlertForItem:item];
  284. } else {
  285. if (item.fileSizeBytes.longLongValue < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  286. [self _downloadItem:item];
  287. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", nil)];
  288. } else {
  289. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  290. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), item.name, [[UIDevice currentDevice] model]]
  291. delegate:self
  292. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  293. otherButtonTitles:nil];
  294. [alert show];
  295. }
  296. }
  297. }
  298. #pragma mark - search
  299. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  300. {
  301. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@",searchString];
  302. self.searchArray = [self.serverBrowser.items filteredArrayUsingPredicate:predicate];
  303. return YES;
  304. }
  305. @end