VLCLocalPlexFolderListViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. NSMutableDictionary *_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 colorWithWhite:.122 alpha:1.];
  42. _tableView.delegate = self;
  43. _tableView.dataSource = self;
  44. _tableView.rowHeight = [VLCLocalNetworkListCell heightOfCell];
  45. self.view = _tableView;
  46. }
  47. - (id)initWithPlexServer:(NSString *)serverName serverAddress:(NSString *)serverAddress portNumber:(NSString *)portNumber atPath:(NSString *)path
  48. {
  49. self = [super init];
  50. if (self) {
  51. _PlexServerName = serverName;
  52. _PlexServerAddress = serverAddress;
  53. _PlexServerPort = portNumber;
  54. _PlexServerPath = path;
  55. _mutableObjectList = [[NSMutableArray alloc] init];
  56. _imageCache = [[NSMutableDictionary alloc] init];
  57. _PlexParser = [[VLCPlexParser alloc] init];
  58. }
  59. return self;
  60. }
  61. - (void)viewDidLoad
  62. {
  63. [super viewDidLoad];
  64. [_mutableObjectList removeAllObjects];
  65. _mutableObjectList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:_PlexServerPath];
  66. self.tableView.separatorColor = [UIColor colorWithWhite:.122 alpha:1.];
  67. self.view.backgroundColor = [UIColor colorWithWhite:.122 alpha:1.];
  68. NSString *titleValue;
  69. if ([_PlexServerPath isEqualToString:@""])
  70. titleValue = _PlexServerName;
  71. else
  72. titleValue = [_PlexServerPath lastPathComponent];
  73. self.title = titleValue;
  74. _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
  75. _searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
  76. _searchDisplayController.delegate = self;
  77. _searchDisplayController.searchResultsDataSource = self;
  78. _searchDisplayController.searchResultsDelegate = self;
  79. if (SYSTEM_RUNS_IOS7_OR_LATER)
  80. _searchDisplayController.searchBar.searchBarStyle = UIBarStyleBlack;
  81. _searchBar.delegate = self;
  82. self.tableView.tableHeaderView = _searchBar;
  83. // Active le Pull down to refresh
  84. refreshControl = [[UIRefreshControl alloc] init];
  85. // Call the refresh function
  86. [refreshControl addTarget:self action:@selector(handleRefresh) forControlEvents:UIControlEventValueChanged];
  87. [self.tableView addSubview:refreshControl];
  88. _searchData = [[NSMutableArray alloc] init];
  89. [_searchData removeAllObjects];
  90. }
  91. - (BOOL)shouldAutorotate
  92. {
  93. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  94. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  95. return NO;
  96. return YES;
  97. }
  98. #pragma mark - Table view data source
  99. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  100. {
  101. return 1;
  102. }
  103. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  104. {
  105. if (tableView == self.searchDisplayController.searchResultsTableView)
  106. return _searchData.count;
  107. else
  108. return _mutableObjectList.count;
  109. }
  110. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  111. {
  112. static NSString *CellIdentifier = @"PlexCellDetail";
  113. VLCLocalNetworkListCell *cell = (VLCLocalNetworkListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  114. if (cell == nil)
  115. cell = [VLCLocalNetworkListCell cellWithReuseIdentifier:CellIdentifier];
  116. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  117. [ObjList removeAllObjects];
  118. if (tableView == self.searchDisplayController.searchResultsTableView)
  119. [ObjList addObjectsFromArray:_searchData];
  120. else
  121. [ObjList addObjectsFromArray:_mutableObjectList];
  122. [cell setTitle:[[ObjList objectAtIndex:indexPath.row] objectForKey:@"title"]];
  123. [cell setIcon:[UIImage imageNamed:@"blank"]];
  124. NSString *thumbPath = [[ObjList objectAtIndex:indexPath.row] objectForKey:@"thumb"];
  125. if (thumbPath) {
  126. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
  127. dispatch_async(queue, ^{
  128. UIImage *img = [self getCachedImage:thumbPath];
  129. dispatch_async(dispatch_get_main_queue(), ^{
  130. [cell setIcon:img];
  131. });
  132. });
  133. }
  134. if ([[[ObjList objectAtIndex:indexPath.row] objectForKey:@"container"] isEqualToString:@"item"]) {
  135. UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightGestureAction:)];
  136. [swipeRight setDirection:(UISwipeGestureRecognizerDirectionRight)];
  137. [cell addGestureRecognizer:swipeRight];
  138. NSInteger size = [[[ObjList objectAtIndex:indexPath.row] objectForKey:@"size"] integerValue];
  139. NSString *mediaSize = [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
  140. NSString *durationInSeconds = [[ObjList objectAtIndex:indexPath.row] objectForKey:@"duration"];
  141. [cell setIsDirectory:NO];
  142. [cell setSubtitle:[NSString stringWithFormat:@"%@ (%@)", mediaSize, durationInSeconds]];
  143. [cell setIsDownloadable:YES];
  144. [cell setDelegate:self];
  145. } else {
  146. [cell setIsDirectory:YES];
  147. if (!thumbPath)
  148. [cell setIcon:[UIImage imageNamed:@"folder"]];
  149. }
  150. return cell;
  151. }
  152. - (UIImage *)getCachedImage:(NSString*)url
  153. {
  154. if (_imageCache.count > 50)
  155. [_imageCache removeAllObjects];
  156. UIImage *image = [_imageCache objectForKey:url];
  157. if ((image != nil) && [image isKindOfClass:[UIImage class]]) {
  158. return image;
  159. } else {
  160. NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
  161. image = [[UIImage alloc] initWithData:imageData];
  162. [_imageCache setObject:image forKey:url];
  163. return image;
  164. }
  165. }
  166. #pragma mark - Table view delegate
  167. - (void)tableView:(UITableView *)tableView willDisplayCell:(VLCLocalNetworkListCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  168. {
  169. UIColor *color = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor colorWithWhite:.122 alpha:1.];
  170. cell.contentView.backgroundColor = cell.titleLabel.backgroundColor = cell.folderTitleLabel.backgroundColor = cell.subtitleLabel.backgroundColor = color;
  171. }
  172. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  173. {
  174. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  175. [ObjList removeAllObjects];
  176. NSString *newPath = nil;
  177. if (tableView == self.searchDisplayController.searchResultsTableView)
  178. [ObjList addObjectsFromArray:_searchData];
  179. else
  180. [ObjList addObjectsFromArray:_mutableObjectList];
  181. NSString *keyValue = [[ObjList objectAtIndex:indexPath.row] objectForKey:@"key"];
  182. if ([keyValue rangeOfString:@"library"].location == NSNotFound)
  183. newPath = [_PlexServerPath stringByAppendingPathComponent:keyValue];
  184. else
  185. newPath = keyValue;
  186. if ([[[ObjList objectAtIndex:indexPath.row] objectForKey:@"container"] isEqualToString:@"item"]) {
  187. [ObjList removeAllObjects];
  188. ObjList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:newPath];
  189. NSString *URLofSubtitle = nil;
  190. if ([[ObjList objectAtIndex:0] objectForKey:@"keySubtitle"])
  191. URLofSubtitle = [self _getFileSubtitleFromPlexServer:ObjList modeStream:YES];
  192. NSURL *itemURL = [NSURL URLWithString:[[ObjList objectAtIndex:0] objectForKey:@"keyMedia"]];
  193. if (itemURL) {
  194. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  195. [appDelegate openMovieWithExternalSubtitleFromURL:itemURL externalSubURL:URLofSubtitle];
  196. }
  197. } else {
  198. VLCLocalPlexFolderListViewController *targetViewController = [[VLCLocalPlexFolderListViewController alloc] initWithPlexServer:_PlexServerName serverAddress:_PlexServerAddress portNumber:_PlexServerPort atPath:newPath];
  199. [[self navigationController] pushViewController:targetViewController animated:YES];
  200. }
  201. [tableView deselectRowAtIndexPath:indexPath animated:NO];
  202. }
  203. #pragma mark - Specifics
  204. - (void)_downloadFileFromMediaItem:(NSMutableArray *)mutableMediaObject
  205. {
  206. NSURL *itemURL = [NSURL URLWithString:[[mutableMediaObject objectAtIndex:0] objectForKey:@"keyMedia"]];
  207. if (![[itemURL absoluteString] isSupportedFormat]) {
  208. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", @"") message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", @""), [itemURL absoluteString]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", @"") otherButtonTitles:nil];
  209. [alert show];
  210. } else if (itemURL) {
  211. NSString *fileName = [[mutableMediaObject objectAtIndex:0] objectForKey:@"namefile"];
  212. [[(VLCAppDelegate *)[UIApplication sharedApplication].delegate downloadViewController] addURLToDownloadList:itemURL fileNameOfMedia:fileName];
  213. }
  214. }
  215. - (NSString *)_getFileSubtitleFromPlexServer:(NSMutableArray *)mutableMediaObject modeStream:(BOOL)modeStream
  216. {
  217. NSURL *url = [NSURL URLWithString:[[mutableMediaObject objectAtIndex:0] objectForKey:@"keySubtitle"]];
  218. NSString *receivedSub = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
  219. NSArray *searchPaths = nil;
  220. if (modeStream)
  221. searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  222. else
  223. searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  224. NSString *directoryPath = [searchPaths objectAtIndex:0];
  225. NSString *FileSubtitlePath = [[directoryPath stringByAppendingPathComponent:[[[mutableMediaObject objectAtIndex:0] objectForKey:@"namefile"] stringByDeletingPathExtension]] stringByAppendingPathExtension:[[mutableMediaObject objectAtIndex:0] objectForKey:@"codecSubtitle"]];
  226. NSFileManager *fileManager = [NSFileManager defaultManager];
  227. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  228. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  229. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  230. APLog(@"file creation failed, no data was saved");
  231. }
  232. [receivedSub writeToFile:FileSubtitlePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  233. return FileSubtitlePath;
  234. }
  235. - (void)swipeRightGestureAction:(UIGestureRecognizer *)recognizer
  236. {
  237. NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:[recognizer locationInView:self.tableView]];
  238. UITableViewCell *swipedCell = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
  239. VLCLocalNetworkListCell *cell = (VLCLocalNetworkListCell *)[[self tableView] cellForRowAtIndexPath:swipedIndexPath];
  240. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  241. [ObjList removeAllObjects];
  242. [ObjList addObject:_mutableObjectList[[self.tableView indexPathForCell:swipedCell].row]];
  243. NSString *ratingKey = [[ObjList objectAtIndex:0] objectForKey:@"ratingKey"];
  244. NSString *tag = [[ObjList objectAtIndex:0] objectForKey:@"state"];
  245. NSString *cellStatusLbl = nil;
  246. NSInteger status = [_PlexParser MarkWatchedUnwatchedMedia:_PlexServerAddress port:_PlexServerPort videoRatingKey:ratingKey state:tag];
  247. if (status == 200) {
  248. if ([tag isEqualToString:@"watched"]) {
  249. tag = @"unwatched";
  250. cellStatusLbl = NSLocalizedString(@"PLEX_UNWATCHED", @"");
  251. } else if ([tag isEqualToString:@"unwatched"]) {
  252. tag = @"watched";
  253. cellStatusLbl = NSLocalizedString(@"PLEX_WATCHED", @"");
  254. }
  255. } else
  256. cellStatusLbl = NSLocalizedString(@"PLEX_ERROR_MARK", @"");
  257. [cell.statusLabel showStatusMessage:cellStatusLbl];
  258. [[_mutableObjectList objectAtIndex:[self.tableView indexPathForCell:swipedCell].row] setObject:tag forKey:@"state"];
  259. }
  260. - (void)reloadTableViewPlex
  261. {
  262. [_mutableObjectList removeAllObjects];
  263. _mutableObjectList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:_PlexServerPath];
  264. [self.tableView reloadData];
  265. }
  266. #pragma mark - VLCLocalNetworkListCell delegation
  267. - (void)triggerDownloadForCell:(VLCLocalNetworkListCell *)cell
  268. {
  269. NSMutableArray *ObjList = [[NSMutableArray alloc] init];
  270. [ObjList removeAllObjects];
  271. if ([self.searchDisplayController isActive])
  272. [ObjList addObject:_searchData[[self.searchDisplayController.searchResultsTableView indexPathForCell:cell].row]];
  273. else
  274. [ObjList addObject:_mutableObjectList[[self.tableView indexPathForCell:cell].row]];
  275. NSString *path = [[ObjList objectAtIndex:0] objectForKey:@"key"];
  276. [ObjList removeAllObjects];
  277. ObjList = [_PlexParser PlexMediaServerParser:_PlexServerAddress port:_PlexServerPort navigationPath:path];
  278. if ([[ObjList objectAtIndex:0] objectForKey:@"keySubtitle"])
  279. [self _getFileSubtitleFromPlexServer:ObjList modeStream:NO];
  280. [self _downloadFileFromMediaItem:ObjList];
  281. [cell.statusLabel showStatusMessage:NSLocalizedString(@"DOWNLOADING", @"")];
  282. }
  283. #pragma mark - Search Display Controller Delegate
  284. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  285. {
  286. [_searchData removeAllObjects];
  287. for (int i = 0; i < [_mutableObjectList count]; i++) {
  288. NSRange nameRange;
  289. nameRange = [[[_mutableObjectList objectAtIndex:i] objectForKey:@"title"] rangeOfString:searchString options:NSCaseInsensitiveSearch];
  290. if (nameRange.location != NSNotFound)
  291. [_searchData addObject:_mutableObjectList[i]];
  292. }
  293. return YES;
  294. }
  295. - (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
  296. {
  297. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  298. tableView.rowHeight = 80.0f;
  299. else
  300. tableView.rowHeight = 68.0f;
  301. tableView.backgroundColor = [UIColor blackColor];
  302. }
  303. #pragma mark - Refresh
  304. -(void)handleRefresh
  305. {
  306. //set the title while refreshing
  307. refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refresh"];
  308. //set the date and time of refreshing
  309. NSDateFormatter *formattedDate = [[NSDateFormatter alloc] init];
  310. [formattedDate setDateFormat:@"MMM d, h:mm a"];
  311. NSString *lastupdated = [NSString stringWithFormat:@"Last Updated on %@", [formattedDate stringFromDate:[NSDate date]]];
  312. refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastupdated];
  313. //end the refreshing
  314. [refreshControl endRefreshing];
  315. [self performSelector:@selector(reloadTableViewPlex) withObject:nil];
  316. }
  317. @end