VLCSharedLibraryListViewController.m 16 KB

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