VLCSharedLibraryListViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*****************************************************************************
  2. * VLCSharedLibraryListViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2015 VideoLAN. All rights reserved.
  6. *
  7. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  8. * Pierre SAGASPE <pierre.sagaspe # me.com>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. #import "VLCSharedLibraryListViewController.h"
  13. #import "VLCSharedLibraryParser.h"
  14. #import "VLCNetworkListCell.h"
  15. #import "VLCPlaybackController.h"
  16. #import "VLCLibraryViewController.h"
  17. #import "VLCDownloadViewController.h"
  18. #import "NSString+SupportedMedia.h"
  19. #import "VLCStatusLabel.h"
  20. #import "UIDevice+VLC.h"
  21. @interface VLCSharedLibraryListViewController () <UITableViewDataSource, UITableViewDelegate, VLCNetworkListCellDelegate, UISearchBarDelegate, UISearchDisplayDelegate, VLCSharedLibraryParserDelegate>
  22. {
  23. NSArray *_serverDataArray;
  24. NSCache *_imageCache;
  25. NSString *_httpServerName;
  26. NSString *_httpServerAddress;
  27. NSString *_httpServerPort;
  28. VLCSharedLibraryParser *_httpParser;
  29. NSMutableArray *_searchData;
  30. UISearchBar *_searchBar;
  31. UISearchDisplayController *_searchDisplayController;
  32. UIRefreshControl *_refreshControl;
  33. UIBarButtonItem *_menuButton;
  34. UITapGestureRecognizer *_tapTwiceGestureRecognizer;
  35. }
  36. @end
  37. @implementation VLCSharedLibraryListViewController
  38. - (void)dealloc
  39. {
  40. [_tapTwiceGestureRecognizer removeTarget:self action:NULL];
  41. }
  42. - (void)loadView
  43. {
  44. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  45. _tableView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  46. _tableView.delegate = self;
  47. _tableView.dataSource = self;
  48. _tableView.rowHeight = [VLCNetworkListCell heightOfCell];
  49. _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  50. _tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  51. self.view = _tableView;
  52. }
  53. - (id)initWithHttpServer:(NSString *)serverName serverAddress:(NSString *)serverAddress portNumber:(NSString *)portNumber
  54. {
  55. self = [super init];
  56. if (self) {
  57. _httpServerName = serverName;
  58. _httpServerAddress = serverAddress;
  59. _httpServerPort = portNumber;
  60. _imageCache = [[NSCache alloc] init];
  61. [_imageCache setCountLimit:50];
  62. _httpParser = [[VLCSharedLibraryParser alloc] init];
  63. _httpParser.delegate = self;
  64. }
  65. return self;
  66. }
  67. - (void)viewWillAppear:(BOOL)animated
  68. {
  69. [super viewWillAppear:animated];
  70. [_httpParser fetchDataFromServer:_httpServerAddress port:_httpServerPort.longLongValue];
  71. }
  72. - (void)viewDidLoad
  73. {
  74. [super viewDidLoad];
  75. self.tableView.separatorColor = [UIColor VLCDarkBackgroundColor];
  76. self.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
  77. self.title = _httpServerAddress;
  78. _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
  79. UINavigationBar *navBar = self.navigationController.navigationBar;
  80. _searchBar.barTintColor = navBar.barTintColor;
  81. _searchBar.tintColor = navBar.tintColor;
  82. _searchBar.translucent = navBar.translucent;
  83. _searchBar.opaque = navBar.opaque;
  84. _searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
  85. _searchDisplayController.delegate = self;
  86. _searchDisplayController.searchResultsDataSource = self;
  87. _searchDisplayController.searchResultsDelegate = self;
  88. _searchDisplayController.searchBar.searchBarStyle = UIBarStyleBlack;
  89. _searchDisplayController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  90. _searchDisplayController.searchResultsTableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  91. _searchBar.delegate = self;
  92. _searchBar.hidden = YES;
  93. _tapTwiceGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwiceGestureAction:)];
  94. [_tapTwiceGestureRecognizer setNumberOfTapsRequired:2];
  95. [self.navigationController.navigationBar addGestureRecognizer:_tapTwiceGestureRecognizer];
  96. // Active le Pull down to refresh
  97. _refreshControl = [[UIRefreshControl alloc] init];
  98. _refreshControl.backgroundColor = [UIColor VLCDarkBackgroundColor];
  99. _refreshControl.tintColor = [UIColor whiteColor];
  100. // Call the refresh function
  101. [_refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];
  102. [self.tableView addSubview:_refreshControl];
  103. _searchData = [[NSMutableArray alloc] init];
  104. [_searchData removeAllObjects];
  105. }
  106. - (BOOL)shouldAutorotate
  107. {
  108. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  109. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  110. return NO;
  111. return YES;
  112. }
  113. #pragma mark - Table view data source
  114. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  115. {
  116. return 1;
  117. }
  118. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  119. {
  120. @synchronized(self) {
  121. if (tableView == self.searchDisplayController.searchResultsTableView)
  122. return _searchData.count;
  123. else
  124. return _serverDataArray.count;
  125. }
  126. }
  127. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  128. {
  129. static NSString *CellIdentifier = @"libraryVLCCellDetail";
  130. VLCNetworkListCell *cell = (VLCNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  131. if (cell == nil)
  132. cell = [VLCNetworkListCell cellWithReuseIdentifier:CellIdentifier];
  133. NSDictionary *cellObject;
  134. @synchronized(self) {
  135. if (tableView == self.searchDisplayController.searchResultsTableView)
  136. cellObject = _searchData[indexPath.row];
  137. else
  138. cellObject = _serverDataArray[indexPath.row];
  139. }
  140. [cell setTitle:[cellObject objectForKey:@"title"]];
  141. [cell setIcon:[UIImage imageNamed:@"blank"]];
  142. NSString *thumbPath = [cellObject objectForKey:@"thumb"];
  143. if (thumbPath) {
  144. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
  145. dispatch_async(queue, ^{
  146. UIImage *img = [self getCachedImage:thumbPath];
  147. dispatch_async(dispatch_get_main_queue(), ^{
  148. if (!img)
  149. [cell setIcon:[UIImage imageNamed:@"blank"]];
  150. else
  151. [cell setIcon:img];
  152. });
  153. });
  154. }
  155. NSInteger size = [[cellObject objectForKey:@"size"] integerValue];
  156. NSString *mediaSize = [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
  157. NSString *duration = [cellObject objectForKey:@"duration"];
  158. [cell setIsDirectory:NO];
  159. [cell setSubtitle:[NSString stringWithFormat:@"%@ (%@)", mediaSize, duration]];
  160. [cell setIsDownloadable:YES];
  161. [cell setDelegate:self];
  162. return cell;
  163. }
  164. - (UIImage *)getCachedImage:(NSString *)url
  165. {
  166. UIImage *image = [_imageCache objectForKey:url];
  167. if ((image != nil) && [image isKindOfClass:[UIImage class]]) {
  168. return image;
  169. } else {
  170. NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
  171. if (imageData) {
  172. image = [[UIImage alloc] initWithData:imageData];
  173. [_imageCache setObject:image forKey:url];
  174. }
  175. return image;
  176. }
  177. }
  178. #pragma mark - Table view delegate
  179. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  180. {
  181. UIColor *color = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  182. cell.contentView.backgroundColor = cell.titleLabel.backgroundColor = cell.folderTitleLabel.backgroundColor = cell.subtitleLabel.backgroundColor = color;
  183. }
  184. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  185. {
  186. NSDictionary *selectedObject;
  187. @synchronized(self) {
  188. if (tableView == self.searchDisplayController.searchResultsTableView)
  189. selectedObject = _searchData[indexPath.row];
  190. else
  191. selectedObject = _serverDataArray[indexPath.row];
  192. }
  193. NSString *URLofSubtitle = nil;
  194. if (![[selectedObject objectForKey:@"pathSubtitle"] isEqualToString:@""]) {
  195. NSURL *url = [NSURL URLWithString:[[selectedObject objectForKey:@"pathSubtitle"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  196. URLofSubtitle = [self _getFileSubtitleFromServer:url modeStream:YES];
  197. }
  198. NSURL *itemURL = [NSURL URLWithString:[selectedObject objectForKey:@"pathfile"]];
  199. if (itemURL) {
  200. VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
  201. [vpc playURL:itemURL subtitlesFilePath:URLofSubtitle];
  202. }
  203. [tableView deselectRowAtIndexPath:indexPath animated:NO];
  204. }
  205. #pragma mark - Specifics
  206. - (void)sharedLibraryDataProcessings:(NSArray *)result
  207. {
  208. @synchronized(self) {
  209. _serverDataArray = result;
  210. self.title = [_serverDataArray.firstObject objectForKey:@"libTitle"];
  211. }
  212. [self.tableView reloadData];
  213. }
  214. - (void)_downloadFileFromMediaItem:(NSURL *)itemURL
  215. {
  216. APLog(@"trying to download %@", [itemURL absoluteString]);
  217. if (![[itemURL absoluteString] isSupportedFormat]) {
  218. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  219. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [itemURL absoluteString]]
  220. delegate:self
  221. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  222. otherButtonTitles:nil];
  223. [alert show];
  224. } else if (itemURL) {
  225. [[VLCDownloadViewController sharedInstance] addURLToDownloadList:itemURL fileNameOfMedia:nil];
  226. }
  227. }
  228. - (NSString *)_getFileSubtitleFromServer:(NSURL *)url modeStream:(BOOL)modeStream
  229. {
  230. NSString *FileSubtitlePath = nil;
  231. NSString *fileName = [[url path] lastPathComponent];
  232. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  233. if (receivedSub.length < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  234. NSArray *searchPaths = nil;
  235. if (modeStream)
  236. searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  237. else
  238. searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  239. NSString *directoryPath = [searchPaths objectAtIndex:0];
  240. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  241. NSFileManager *fileManager = [NSFileManager defaultManager];
  242. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  243. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  244. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  245. APLog(@"file creation failed, no data was saved");
  246. }
  247. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  248. } else {
  249. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  250. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]]
  251. delegate:self
  252. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  253. otherButtonTitles:nil];
  254. [alert show];
  255. }
  256. return FileSubtitlePath;
  257. }
  258. #pragma mark - VLCNetworkListCell delegation
  259. - (void)triggerDownloadForCell:(VLCNetworkListCell *)cell
  260. {
  261. NSDictionary *dataItem;
  262. @synchronized(self) {
  263. if ([self.searchDisplayController isActive])
  264. dataItem = _searchData[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row];
  265. else
  266. dataItem = _serverDataArray[[self.tableView indexPathForCell:cell].row];
  267. }
  268. NSURL *itemURL = [NSURL URLWithString:[dataItem objectForKey:@"pathfile"]];
  269. NSInteger size = [[dataItem objectForKey:@"size"] integerValue];
  270. if (size < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  271. NSString *URLofSubtitle = nil;
  272. if (![[dataItem objectForKey:@"pathSubtitle"] isEqualToString:@""]) {
  273. NSURL *url = [NSURL URLWithString:[[dataItem objectForKey:@"pathSubtitle"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  274. URLofSubtitle = [self _getFileSubtitleFromServer:url modeStream:NO];
  275. }
  276. [self _downloadFileFromMediaItem:itemURL];
  277. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", nil)];
  278. } else {
  279. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  280. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), [dataItem objectForKey:@"title"], [[UIDevice currentDevice] model]]
  281. delegate:self
  282. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  283. otherButtonTitles:nil];
  284. [alert show];
  285. }
  286. }
  287. #pragma mark - Search Display Controller Delegate
  288. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  289. {
  290. @synchronized (self) {
  291. [_searchData removeAllObjects];
  292. NSUInteger count = _serverDataArray.count;
  293. for (NSUInteger i = 0; i < count; i++) {
  294. NSRange nameRange;
  295. nameRange = [[_serverDataArray[i] objectForKey:@"title"] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  296. if (nameRange.location != NSNotFound)
  297. [_searchData addObject:_serverDataArray[i]];
  298. }
  299. }
  300. return YES;
  301. }
  302. - (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
  303. {
  304. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  305. tableView.rowHeight = 80.0f;
  306. else
  307. tableView.rowHeight = 68.0f;
  308. tableView.backgroundColor = [UIColor blackColor];
  309. }
  310. #pragma mark - Refresh
  311. -(void)handleRefresh
  312. {
  313. //set the title while refreshing
  314. _refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"LOCAL_SERVER_REFRESH", nil)];
  315. //set the date and time of refreshing
  316. NSDateFormatter *formattedDate = [[NSDateFormatter alloc]init];
  317. [formattedDate setDateFormat:@"MMM d, h:mm a"];
  318. NSString *lastupdated = [NSString stringWithFormat:NSLocalizedString(@"LOCAL_SERVER_LAST_UPDATE", nil),[formattedDate stringFromDate:[NSDate date]]];
  319. NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
  320. _refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastupdated attributes:attrsDictionary];
  321. //end the refreshing
  322. [_refreshControl endRefreshing];
  323. @synchronized(self) {
  324. _serverDataArray = nil;
  325. }
  326. [_httpParser fetchDataFromServer:_httpServerAddress port:_httpServerPort.longLongValue];
  327. }
  328. #pragma mark - Gesture Action
  329. - (void)tapTwiceGestureAction:(UIGestureRecognizer *)recognizer
  330. {
  331. _searchBar.hidden = !_searchBar.hidden;
  332. if (_searchBar.hidden)
  333. self.tableView.tableHeaderView = nil;
  334. else
  335. self.tableView.tableHeaderView = _searchBar;
  336. [self.tableView setContentOffset:CGPointMake(0.0f, -self.tableView.contentInset.top) animated:NO];
  337. }
  338. @end