VLCNetworkServerBrowserViewController.m 15 KB

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