VLCLocalPlexFolderListViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*****************************************************************************
  2. * VLCLocalPlexFolderListViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2014 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 "VLCLocalPlexFolderListViewController.h"
  13. #import "VLCPlexParser.h"
  14. #import "VLCLocalNetworkListCell.h"
  15. #import "VLCAppDelegate.h"
  16. #import "VLCPlaylistViewController.h"
  17. #import "UINavigationController+Theme.h"
  18. #import "VLCDownloadViewController.h"
  19. #import "NSString+SupportedMedia.h"
  20. #import "VLCStatusLabel.h"
  21. @interface VLCLocalPlexFolderListViewController () <UITableViewDataSource, UITableViewDelegate, VLCLocalNetworkListCell, UISearchBarDelegate, UISearchDisplayDelegate>
  22. {
  23. UIBarButtonItem *_backButton;
  24. NSMutableArray *_mutableObjectList;
  25. NSCache *_imageCache;
  26. NSString *_PlexServerName;
  27. NSString *_PlexServerAddress;
  28. NSString *_PlexServerPort;
  29. NSString *_PlexServerPath;
  30. VLCPlexParser *_PlexParser;
  31. NSMutableArray *_searchData;
  32. UISearchBar *_searchBar;
  33. UISearchDisplayController *_searchDisplayController;
  34. UIRefreshControl *_refreshControl;
  35. }
  36. @end
  37. @implementation VLCLocalPlexFolderListViewController
  38. - (void)loadView
  39. {
  40. _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
  41. _tableView.backgroundColor = [UIColor VLCDarkBackgroundColor];
  42. _tableView.delegate = self;
  43. _tableView.dataSource = self;
  44. _tableView.rowHeight = [VLCLocalNetworkListCell heightOfCell];
  45. _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  46. _tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  47. self.view = _tableView;
  48. }
  49. - (id)initWithPlexServer:(NSString *)serverName serverAddress:(NSString *)serverAddress portNumber:(NSString *)portNumber atPath:(NSString *)path
  50. {
  51. self = [super init];
  52. if (self) {
  53. _PlexServerName = serverName;
  54. _PlexServerAddress = serverAddress;
  55. _PlexServerPort = portNumber;
  56. _PlexServerPath = path;
  57. _mutableObjectList = [[NSMutableArray alloc] init];
  58. _imageCache = [[NSCache alloc] init];
  59. [_imageCache setCountLimit:50];
  60. _PlexParser = [[VLCPlexParser alloc] init];
  61. }
  62. return self;
  63. }
  64. - (void)viewDidLoad
  65. {
  66. [super viewDidLoad];
  67. [_mutableObjectList removeAllObjects];
  68. _mutableObjectList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:_PlexServerPath];
  69. self.tableView.separatorColor = [UIColor VLCDarkBackgroundColor];
  70. self.view.backgroundColor = [UIColor VLCDarkBackgroundColor];
  71. NSString *titleValue;
  72. if ([_PlexServerPath isEqualToString:@""])
  73. titleValue = _PlexServerName;
  74. else
  75. titleValue = [_mutableObjectList[0] objectForKey:@"libTitle"];
  76. self.title = titleValue;
  77. _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
  78. UINavigationBar *navBar = self.navigationController.navigationBar;
  79. if (SYSTEM_RUNS_IOS7_OR_LATER)
  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. if (SYSTEM_RUNS_IOS7_OR_LATER)
  89. _searchDisplayController.searchBar.searchBarStyle = UIBarStyleBlack;
  90. _searchDisplayController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  91. _searchDisplayController.searchResultsTableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
  92. _searchBar.delegate = self;
  93. _searchBar.hidden = YES;
  94. //self.tableView.tableHeaderView = _searchBar;
  95. //self.tableView.contentOffset = CGPointMake(0, CGRectGetHeight(_searchBar.frame)); // -> hide search bar to load
  96. UITapGestureRecognizer *tapTwiceGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwiceGestureAction:)];
  97. [tapTwiceGesture setNumberOfTapsRequired:2];
  98. [self.navigationController.navigationBar addGestureRecognizer:tapTwiceGesture];
  99. // Active le Pull down to refresh
  100. _refreshControl = [[UIRefreshControl alloc] init];
  101. _refreshControl.backgroundColor = [UIColor VLCDarkBackgroundColor];
  102. _refreshControl.tintColor = [UIColor whiteColor];
  103. // Call the refresh function
  104. [_refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];
  105. [self.tableView addSubview:_refreshControl];
  106. _searchData = [[NSMutableArray alloc] init];
  107. [_searchData removeAllObjects];
  108. }
  109. - (BOOL)shouldAutorotate
  110. {
  111. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  112. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  113. return NO;
  114. return YES;
  115. }
  116. #pragma mark - Table view data source
  117. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  118. {
  119. return 1;
  120. }
  121. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  122. {
  123. if (tableView == self.searchDisplayController.searchResultsTableView)
  124. return _searchData.count;
  125. else
  126. return _mutableObjectList.count;
  127. }
  128. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  129. {
  130. static NSString *CellIdentifier = @"PlexCellDetail";
  131. VLCLocalNetworkListCell *cell = (VLCLocalNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  132. if (cell == nil)
  133. cell = [VLCLocalNetworkListCell cellWithReuseIdentifier:CellIdentifier];
  134. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  135. [ObjList removeAllObjects];
  136. if (tableView == self.searchDisplayController.searchResultsTableView)
  137. [ObjList addObjectsFromArray:_searchData];
  138. else
  139. [ObjList addObjectsFromArray:_mutableObjectList];
  140. [cell setTitle:[[ObjList objectAtIndex:indexPath.row] objectForKey:@"title"]];
  141. [cell setIcon:[UIImage imageNamed:@"blank"]];
  142. NSString *thumbPath = [[ObjList objectAtIndex:indexPath.row] 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. if ([[[ObjList objectAtIndex:indexPath.row] objectForKey:@"container"] isEqualToString:@"item"]) {
  156. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGestureAction:)];
  157. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  158. [cell addGestureRecognizer:swipeRight];
  159. NSInteger size = [[[ObjList objectAtIndex:indexPath.row] objectForKey:@"size"] integerValue];
  160. NSString *mediaSize = [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
  161. NSString *durationInSeconds = [[ObjList objectAtIndex:indexPath.row] objectForKey:@"duration"];
  162. [cell setIsDirectory:NO];
  163. [cell setSubtitle:[NSString stringWithFormat:@"%@ (%@)", mediaSize, durationInSeconds]];
  164. [cell setIsDownloadable:YES];
  165. [cell setDelegate:self];
  166. } else {
  167. [cell setIsDirectory:YES];
  168. if (!thumbPath)
  169. [cell setIcon:[UIImage imageNamed:@"folder"]];
  170. }
  171. return cell;
  172. }
  173. - (UIImage *)getCachedImage:(NSString *)url
  174. {
  175. UIImage *image = [_imageCache objectForKey:url];
  176. if ((image != nil) && [image isKindOfClass:[UIImage class]]) {
  177. return image;
  178. } else {
  179. NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
  180. if (imageData) {
  181. image = [[UIImage alloc] initWithData:imageData];
  182. [_imageCache setObject:image forKey:url];
  183. }
  184. return image;
  185. }
  186. }
  187. #pragma mark - Table view delegate
  188. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCLocalNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  189. {
  190. UIColor *color = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  191. cell.contentView.backgroundColor = cell.titleLabel.backgroundColor = cell.folderTitleLabel.backgroundColor = cell.subtitleLabel.backgroundColor = color;
  192. }
  193. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  194. {
  195. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  196. [ObjList removeAllObjects];
  197. NSString *newPath = nil;
  198. if (tableView == self.searchDisplayController.searchResultsTableView)
  199. [ObjList addObjectsFromArray:_searchData];
  200. else
  201. [ObjList addObjectsFromArray:_mutableObjectList];
  202. NSString *keyValue = [[ObjList objectAtIndex:indexPath.row] objectForKey:@"key"];
  203. if ([keyValue rangeOfString:@"library"].location == NSNotFound)
  204. newPath = [_PlexServerPath stringByAppendingPathComponent:keyValue];
  205. else
  206. newPath = keyValue;
  207. if ([[[ObjList objectAtIndex:indexPath.row] objectForKey:@"container"] isEqualToString:@"item"]) {
  208. [ObjList removeAllObjects];
  209. ObjList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:newPath];
  210. NSString *URLofSubtitle = nil;
  211. if ([[ObjList objectAtIndex:0] objectForKey:@"keySubtitle"])
  212. URLofSubtitle = [self _getFileSubtitleFromPlexServer:ObjList modeStream:YES];
  213. NSURL *itemURL = [NSURL URLWithString:[[ObjList objectAtIndex:0] objectForKey:@"keyMedia"]];
  214. if (itemURL) {
  215. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  216. [appDelegate openMovieWithExternalSubtitleFromURL:itemURL externalSubURL:URLofSubtitle];
  217. }
  218. } else {
  219. VLCLocalPlexFolderListViewController *targetViewController = [[VLCLocalPlexFolderListViewController alloc] initWithPlexServer:_PlexServerName serverAddress:_PlexServerAddress portNumber:_PlexServerPort atPath:newPath];
  220. [[self navigationController] pushViewController:targetViewController animated:YES];
  221. }
  222. [tableView deselectRowAtIndexPath:indexPath animated:NO];
  223. }
  224. #pragma mark - Specifics
  225. - (void)_downloadFileFromMediaItem:(NSMutableArray *)mutableMediaObject
  226. {
  227. NSURL *itemURL = [NSURL URLWithString:[[mutableMediaObject objectAtIndex:0] objectForKey:@"keyMedia"]];
  228. if (![[itemURL absoluteString] isSupportedFormat]) {
  229. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil) message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [itemURL absoluteString]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil) otherButtonTitles:nil];
  230. [alert show];
  231. } else if (itemURL) {
  232. NSString *fileName = [[mutableMediaObject objectAtIndex:0] objectForKey:@"namefile"];
  233. [[(VLCAppDelegate *)[UIApplication sharedApplication].delegate downloadViewController] addURLToDownloadList:itemURL fileNameOfMedia:fileName];
  234. }
  235. }
  236. - (NSString *)_getFileSubtitleFromPlexServer:(NSMutableArray *)mutableMediaObject modeStream:(BOOL)modeStream
  237. {
  238. NSURL *url = [NSURL URLWithString:[[mutableMediaObject objectAtIndex:0] objectForKey:@"keySubtitle"]];
  239. NSString *receivedSub = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
  240. NSArray *searchPaths = nil;
  241. if (modeStream)
  242. searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  243. else
  244. searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  245. NSString *directoryPath = [searchPaths objectAtIndex:0];
  246. NSString *FileSubtitlePath = [[directoryPath stringByAppendingPathComponent:[[[mutableMediaObject objectAtIndex:0] objectForKey:@"namefile"] stringByDeletingPathExtension]] stringByAppendingPathExtension:[[mutableMediaObject objectAtIndex:0] objectForKey:@"codecSubtitle"]];
  247. NSFileManager *fileManager = [NSFileManager defaultManager];
  248. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  249. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  250. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  251. APLog(@"file creation failed, no data was saved");
  252. }
  253. [receivedSub writeToFile:FileSubtitlePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  254. return FileSubtitlePath;
  255. }
  256. - (void)swipeRightGestureAction:(UIGestureRecognizer *)recognizer
  257. {
  258. NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:[recognizer locationInView:self.tableView]];
  259. UITableViewCell *swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
  260. VLCLocalNetworkListCell *cell = (VLCLocalNetworkListCell *)[[self tableView] cellForRowAtIndexPath:swipedIndexPath];
  261. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  262. [ObjList removeAllObjects];
  263. [ObjList addObject:_mutableObjectList[[self.tableView indexPathForCell:swipedCell].row]];
  264. NSString *ratingKey = [[ObjList objectAtIndex:0] objectForKey:@"ratingKey"];
  265. NSString *tag = [[ObjList objectAtIndex:0] objectForKey:@"state"];
  266. NSString *cellStatusLbl = nil;
  267. NSInteger status = [_PlexParser MarkWatchedUnwatchedMedia:_PlexServerAddress port:_PlexServerPort videoRatingKey:ratingKey state:tag];
  268. if (status == 200) {
  269. if ([tag isEqualToString:@"watched"]) {
  270. tag = @"unwatched";
  271. cellStatusLbl = NSLocalizedString(@"PLEX_UNWATCHED", nil);
  272. } else if ([tag isEqualToString:@"unwatched"]) {
  273. tag = @"watched";
  274. cellStatusLbl = NSLocalizedString(@"PLEX_WATCHED", nil);
  275. }
  276. } else
  277. cellStatusLbl = NSLocalizedString(@"PLEX_ERROR_MARK", nil);
  278. [cell.statusLabel showStatusMessage:cellStatusLbl];
  279. [[_mutableObjectList objectAtIndex:[self.tableView indexPathForCell:swipedCell].row] setObject:tag forKey:@"state"];
  280. }
  281. - (void)reloadTableViewPlex
  282. {
  283. [_mutableObjectList removeAllObjects];
  284. _mutableObjectList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:_PlexServerPath];
  285. [self.tableView reloadData];
  286. }
  287. #pragma mark - VLCLocalNetworkListCell delegation
  288. - (void)triggerDownloadForCell:(VLCLocalNetworkListCell *)cell
  289. {
  290. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  291. [ObjList removeAllObjects];
  292. if ([self.searchDisplayController isActive])
  293. [ObjList addObject:_searchData[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row]];
  294. else
  295. [ObjList addObject:_mutableObjectList[[self.tableView indexPathForCell:cell].row]];
  296. NSString *path = [[ObjList objectAtIndex:0] objectForKey:@"key"];
  297. [ObjList removeAllObjects];
  298. ObjList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:path];
  299. if ([[ObjList objectAtIndex:0] objectForKey:@"keySubtitle"])
  300. [self _getFileSubtitleFromPlexServer:ObjList modeStream:NO];
  301. [self _downloadFileFromMediaItem:ObjList];
  302. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", nil)];
  303. }
  304. #pragma mark - Search Display Controller Delegate
  305. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  306. {
  307. [_searchData removeAllObjects];
  308. for (int i = 0; i < [_mutableObjectList count]; i++) {
  309. NSRange nameRange;
  310. nameRange = [[[_mutableObjectList objectAtIndex:i] objectForKey:@"title"] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  311. if (nameRange.location != NSNotFound)
  312. [_searchData addObject:_mutableObjectList[i]];
  313. }
  314. return YES;
  315. }
  316. - (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
  317. {
  318. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  319. tableView.rowHeight = 80.0f;
  320. else
  321. tableView.rowHeight = 68.0f;
  322. tableView.backgroundColor = [UIColor blackColor];
  323. }
  324. #pragma mark - Refresh
  325. -(void)handleRefresh
  326. {
  327. //set the title while refreshing
  328. _refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:NSLocalizedString(@"LOCAL_SERVER_REFRESH",nil)];
  329. //set the date and time of refreshing
  330. NSDateFormatter *formattedDate = [[NSDateFormatter alloc]init];
  331. [formattedDate setDateFormat:@"MMM d, h:mm a"];
  332. NSString *lastupdated = [NSString stringWithFormat:NSLocalizedString(@"LOCAL_SERVER_LAST_UPDATE",nil),[formattedDate stringFromDate:[NSDate date]]];
  333. NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
  334. _refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastupdated attributes:attrsDictionary];
  335. //end the refreshing
  336. [_refreshControl endRefreshing];
  337. [self performSelector:@selector(reloadTableViewPlex) withObject:nil];
  338. }
  339. #pragma mark - Gesture Action
  340. - (void)tapTwiceGestureAction:(UIGestureRecognizer *)recognizer
  341. {
  342. _searchBar.hidden = !_searchBar.hidden;
  343. if (_searchBar.hidden)
  344. self.tableView.tableHeaderView = nil;
  345. else
  346. self.tableView.tableHeaderView = _searchBar;
  347. [self.tableView setContentOffset:CGPointMake(0.0f, -self.tableView.contentInset.top) animated:NO];
  348. }
  349. @end