VLCOpenNetworkStreamViewController.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*****************************************************************************
  2. * VLCOpenNetworkStreamViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Pierre Sagaspe <pierre.sagaspe # me.com>
  11. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCOpenNetworkStreamViewController.h"
  15. #import "VLCAppDelegate.h"
  16. #import "VLCPlaylistViewController.h"
  17. #import "VLCMenuTableViewController.h"
  18. #import "UIDevice+VLC.h"
  19. @interface VLCOpenNetworkStreamViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
  20. {
  21. NSMutableArray *_recentURLs;
  22. }
  23. @end
  24. @implementation VLCOpenNetworkStreamViewController
  25. + (void)initialize
  26. {
  27. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  28. NSDictionary *appDefaults = @{kVLCRecentURLs : @[], kVLCPrivateWebStreaming : @(NO)};
  29. [defaults registerDefaults:appDefaults];
  30. }
  31. - (void)applicationDidBecomeActive:(NSNotification *)notification
  32. {
  33. [self updatePasteboardTextInURLField];
  34. }
  35. - (void)dealloc
  36. {
  37. [[NSNotificationCenter defaultCenter] removeObserver:self
  38. name:UIApplicationDidBecomeActiveNotification
  39. object:[UIApplication sharedApplication]];
  40. }
  41. - (void)viewDidLoad
  42. {
  43. [super viewDidLoad];
  44. /*
  45. * Observe changes to the pasteboard so we can automatically paste it into the URL field.
  46. * Do not use UIPasteboardChangedNotification because we have copy actions that will trigger it on this screen.
  47. * Instead when the user comes back to the application from the background (or the inactive state by pulling down notification center), update the URL field.
  48. * Using the 'active' rather than 'foreground' notification for future proofing if iOS ever allows running multiple apps on the same screen (which would allow the pasteboard to be changed without truly backgrounding the app).
  49. */
  50. [[NSNotificationCenter defaultCenter] addObserver:self
  51. selector:@selector(applicationDidBecomeActive:)
  52. name:UIApplicationDidBecomeActiveNotification
  53. object:[UIApplication sharedApplication]];
  54. if (SYSTEM_RUNS_IOS7_OR_LATER)
  55. [self.openButton setTitle:NSLocalizedString(@"OPEN_NETWORK", nil) forState:UIControlStateNormal];
  56. else
  57. [self.openButton setTitle:NSLocalizedString(@"BUTTON_OPEN", nil) forState:UIControlStateNormal];
  58. [self.privateModeLabel setText:NSLocalizedString(@"PRIVATE_PLAYBACK_TOGGLE", nil)];
  59. [self.ScanSubModeLabel setText:NSLocalizedString(@"SCAN_SUBTITLE_TOGGLE", nil)];
  60. [self.ScanSubModeLabel setAdjustsFontSizeToFitWidth:YES];
  61. [self.ScanSubModeLabel setNumberOfLines:0];
  62. self.title = NSLocalizedString(@"OPEN_NETWORK", nil);
  63. self.navigationItem.leftBarButtonItem = [UIBarButtonItem themedRevealMenuButtonWithTarget:self andSelector:@selector(goBack:)];
  64. [self.whatToOpenHelpLabel setText:NSLocalizedString(@"OPEN_NETWORK_HELP", nil)];
  65. self.urlField.delegate = self;
  66. self.urlField.keyboardType = UIKeyboardTypeURL;
  67. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  68. NSAttributedString *coloredAttributedPlaceholder = [[NSAttributedString alloc] initWithString:@"http://myserver.com/file.mkv" attributes:@{NSForegroundColorAttributeName: [UIColor VLCLightTextColor]}];
  69. self.urlField.attributedPlaceholder = coloredAttributedPlaceholder;
  70. self.edgesForExtendedLayout = UIRectEdgeNone;
  71. }
  72. // This will be called every time this VC is opened by the side menu controller
  73. [self updatePasteboardTextInURLField];
  74. }
  75. - (void)updatePasteboardTextInURLField
  76. {
  77. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  78. if ([pasteboard containsPasteboardTypes:@[@"public.url"]])
  79. self.urlField.text = [[pasteboard valueForPasteboardType:@"public.url"] absoluteString];
  80. }
  81. - (void)viewWillAppear:(BOOL)animated
  82. {
  83. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  84. _recentURLs = [NSMutableArray arrayWithArray:[defaults objectForKey:kVLCRecentURLs]];
  85. self.privateToggleSwitch.on = [defaults boolForKey:kVLCPrivateWebStreaming];
  86. self.ScanSubToggleSwitch.on = [defaults boolForKey:kVLChttpScanSubtitle];
  87. [super viewWillAppear:animated];
  88. }
  89. - (void)viewWillDisappear:(BOOL)animated
  90. {
  91. [[NSNotificationCenter defaultCenter] removeObserver:self
  92. name:UIApplicationDidBecomeActiveNotification
  93. object:[UIApplication sharedApplication]];
  94. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  95. [defaults setObject:[NSArray arrayWithArray:_recentURLs] forKey:kVLCRecentURLs];
  96. [defaults setBool:self.privateToggleSwitch.on forKey:kVLCPrivateWebStreaming];
  97. [defaults setBool:self.ScanSubToggleSwitch.on forKey:kVLChttpScanSubtitle];
  98. [defaults synchronize];
  99. [super viewWillDisappear:animated];
  100. }
  101. - (CGSize)contentSizeForViewInPopover {
  102. return [self.view sizeThatFits:CGSizeMake(320, 800)];
  103. }
  104. #pragma mark - UI interaction
  105. - (BOOL)shouldAutorotate
  106. {
  107. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  108. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  109. return NO;
  110. return YES;
  111. }
  112. - (IBAction)goBack:(id)sender
  113. {
  114. [self.view endEditing:YES];
  115. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController] toggleSidebar:![(VLCAppDelegate*)[UIApplication sharedApplication].delegate revealController].sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
  116. }
  117. - (IBAction)openButtonAction:(id)sender
  118. {
  119. if ([self.urlField.text length] > 0) {
  120. if (!self.privateToggleSwitch.on) {
  121. if ([_recentURLs indexOfObject:self.urlField.text] != NSNotFound)
  122. [_recentURLs removeObject:self.urlField.text];
  123. if (_recentURLs.count >= 15)
  124. [_recentURLs removeLastObject];
  125. [_recentURLs addObject:self.urlField.text];
  126. [self.historyTableView reloadData];
  127. }
  128. [self _openURLStringAndDismiss:self.urlField.text];
  129. }
  130. }
  131. #pragma mark - table view data source
  132. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  133. {
  134. return 1;
  135. }
  136. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  137. {
  138. return _recentURLs.count;
  139. }
  140. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  141. {
  142. static NSString *CellIdentifier = @"StreamingHistoryCell";
  143. UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  144. if (cell == nil) {
  145. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  146. cell.textLabel.textColor = [UIColor whiteColor];
  147. cell.textLabel.highlightedTextColor = [UIColor blackColor];
  148. cell.detailTextLabel.textColor = [UIColor VLCLightTextColor];
  149. cell.detailTextLabel.highlightedTextColor = [UIColor blackColor];
  150. }
  151. NSInteger row = indexPath.row;
  152. cell.textLabel.text = [_recentURLs[row] lastPathComponent];
  153. cell.detailTextLabel.text = _recentURLs[row];
  154. return cell;
  155. }
  156. #pragma mark - table view delegate
  157. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  158. {
  159. cell.backgroundColor = (indexPath.row % 2 == 0)? [UIColor blackColor]: [UIColor VLCDarkBackgroundColor];
  160. }
  161. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  162. {
  163. return YES;
  164. }
  165. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  166. {
  167. if (editingStyle == UITableViewCellEditingStyleDelete) {
  168. [_recentURLs removeObjectAtIndex:indexPath.row];
  169. [tableView reloadData];
  170. }
  171. }
  172. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  173. {
  174. [self _openURLStringAndDismiss:_recentURLs[indexPath.row]];
  175. [self.historyTableView deselectRowAtIndexPath:indexPath animated:NO];
  176. }
  177. - (void)tableView:(UITableView *)tableView
  178. performAction:(SEL)action
  179. forRowAtIndexPath:(NSIndexPath *)indexPath
  180. withSender:(id)sender
  181. {
  182. NSString *actionText = NSStringFromSelector(action);
  183. if ([actionText isEqualToString:@"copy:"])
  184. {
  185. [UIPasteboard generalPasteboard].string = _recentURLs[indexPath.row];
  186. }
  187. }
  188. - (BOOL)tableView:(UITableView *)tableView
  189. canPerformAction:(SEL)action
  190. forRowAtIndexPath:(NSIndexPath *)indexPath
  191. withSender:(id)sender
  192. {
  193. NSString *actionText = NSStringFromSelector(action);
  194. if ([actionText isEqualToString:@"copy:"])
  195. {
  196. return YES;
  197. }
  198. return NO;
  199. }
  200. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  201. {
  202. return YES;
  203. }
  204. #pragma mark - internals
  205. - (void)_openURLStringAndDismiss:(NSString *)url
  206. {
  207. NSURL *URLscheme = [NSURL URLWithString:url];
  208. NSString *URLofSubtitle = nil;
  209. if ([URLscheme.scheme isEqualToString:@"http"])
  210. if (self.ScanSubToggleSwitch.on)
  211. URLofSubtitle = [self _checkURLofSubtitle:url];
  212. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate openMovieWithExternalSubtitleFromURL:[NSURL URLWithString:url] externalSubURL:URLofSubtitle];
  213. }
  214. - (NSString *)_checkURLofSubtitle:(NSString *)url
  215. {
  216. NSString *subtitleFileExtensions = kSupportedSubtitleFileExtensions;
  217. NSCharacterSet *characterFilter = [NSCharacterSet characterSetWithCharactersInString:@"\\.():$"];
  218. subtitleFileExtensions = [[subtitleFileExtensions componentsSeparatedByCharactersInSet:characterFilter] componentsJoinedByString:@""];
  219. NSArray *arraySubtitleFileExtensions = [subtitleFileExtensions componentsSeparatedByString:@"|"];
  220. NSString *urlTemp = [[url stringByDeletingPathExtension] stringByAppendingString:@"."];
  221. for (int cnt = 0; cnt < arraySubtitleFileExtensions.count; cnt++) {
  222. NSString *checkAddress = [urlTemp stringByAppendingString:arraySubtitleFileExtensions[cnt]];
  223. NSURL *checkURL = [NSURL URLWithString:checkAddress];
  224. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:checkURL];
  225. request.HTTPMethod = @"HEAD";
  226. NSURLResponse *response = nil;
  227. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
  228. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  229. if (httpStatus == 200) {
  230. NSString *fileSubtitlePath = [self _getFileSubtitleFromServer:checkURL];
  231. return fileSubtitlePath;
  232. }
  233. }
  234. return nil;
  235. }
  236. - (NSString *)_getFileSubtitleFromServer:(NSURL *)url
  237. {
  238. NSString *FileSubtitlePath = nil;
  239. NSString *fileName = [[url path] lastPathComponent];
  240. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  241. if (receivedSub.length < [[UIDevice currentDevice] freeDiskspace].longLongValue) {
  242. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  243. NSString *directoryPath = [searchPaths objectAtIndex:0];
  244. FileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  245. NSFileManager *fileManager = [NSFileManager defaultManager];
  246. if (![fileManager fileExistsAtPath:FileSubtitlePath]) {
  247. [fileManager createFileAtPath:FileSubtitlePath contents:nil attributes:nil];
  248. if (![fileManager fileExistsAtPath:FileSubtitlePath])
  249. APLog(@"file creation failed, no data was saved");
  250. }
  251. [receivedSub writeToFile:FileSubtitlePath atomically:YES];
  252. } else {
  253. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil) message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]] delegate:self cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil) otherButtonTitles:nil];
  254. [alert show];
  255. }
  256. return FileSubtitlePath;
  257. }
  258. #pragma mark - text view delegate
  259. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  260. {
  261. [self.urlField resignFirstResponder];
  262. return NO;
  263. }
  264. @end