VLCOpenNetworkStreamViewController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*****************************************************************************
  2. * VLCOpenNetworkStreamViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2018 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. * Adam Viaud <mcnight # mcnight.fr>
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLCOpenNetworkStreamViewController.h"
  15. #import "VLCPlaybackController.h"
  16. #import "VLCStreamingHistoryCell.h"
  17. #import "UIDevice+VLC.h"
  18. #import "VLC-Swift.h"
  19. @interface VLCOpenNetworkStreamViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, VLCStreamingHistoryCellMenuItemProtocol>
  20. {
  21. NSMutableArray *_recentURLs;
  22. NSMutableDictionary *_recentURLTitles;
  23. }
  24. @end
  25. @implementation VLCOpenNetworkStreamViewController
  26. + (void)initialize
  27. {
  28. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  29. NSDictionary *appDefaults = @{kVLCRecentURLs : @[], kVLCRecentURLTitles : @{}, kVLCPrivateWebStreaming : @(NO)};
  30. [defaults registerDefaults:appDefaults];
  31. }
  32. - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  33. {
  34. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  35. if (self) {
  36. self.title = NSLocalizedString(@"OPEN_NETWORK", comment: "");
  37. }
  38. return self;
  39. }
  40. - (void)applicationDidBecomeActive:(NSNotification *)notification
  41. {
  42. [self updatePasteboardTextInURLField];
  43. }
  44. - (void)ubiquitousKeyValueStoreDidChange:(NSNotification *)notification
  45. {
  46. /* TODO: don't blindly trust that the Cloud knows best */
  47. _recentURLs = [NSMutableArray arrayWithArray:[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:kVLCRecentURLs]];
  48. _recentURLTitles = [NSMutableDictionary dictionaryWithDictionary:[[NSUbiquitousKeyValueStore defaultStore] dictionaryForKey:kVLCRecentURLTitles]];
  49. [self.historyTableView reloadData];
  50. }
  51. - (void)viewDidLoad
  52. {
  53. [super viewDidLoad];
  54. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  55. [notificationCenter addObserver:self
  56. selector:@selector(ubiquitousKeyValueStoreDidChange:)
  57. name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
  58. object:[NSUbiquitousKeyValueStore defaultStore]];
  59. [notificationCenter addObserver:self
  60. selector:@selector(updateForTheme)
  61. name:kVLCThemeDidChangeNotification
  62. object:nil];
  63. /* force store update */
  64. NSUbiquitousKeyValueStore *ubiquitousKeyValueStore = [NSUbiquitousKeyValueStore defaultStore];
  65. [ubiquitousKeyValueStore synchronize];
  66. /* fetch data from cloud */
  67. _recentURLs = [NSMutableArray arrayWithArray:[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:kVLCRecentURLs]];
  68. _recentURLTitles = [NSMutableDictionary dictionaryWithDictionary:[[NSUbiquitousKeyValueStore defaultStore] dictionaryForKey:kVLCRecentURLTitles]];
  69. /* merge data from local storage (aka legacy VLC versions) */
  70. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  71. NSArray *localRecentUrls = [defaults objectForKey:kVLCRecentURLs];
  72. if (localRecentUrls != nil) {
  73. if (localRecentUrls.count != 0) {
  74. [_recentURLs addObjectsFromArray:localRecentUrls];
  75. [defaults setObject:nil forKey:kVLCRecentURLs];
  76. [ubiquitousKeyValueStore setArray:_recentURLs forKey:kVLCRecentURLs];
  77. [ubiquitousKeyValueStore synchronize];
  78. }
  79. }
  80. /*
  81. * Observe changes to the pasteboard so we can automatically paste it into the URL field.
  82. * Do not use UIPasteboardChangedNotification because we have copy actions that will trigger it on this screen.
  83. * 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.
  84. * 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).
  85. */
  86. [notificationCenter addObserver:self
  87. selector:@selector(applicationDidBecomeActive:)
  88. name:UIApplicationDidBecomeActiveNotification
  89. object:[UIApplication sharedApplication]];
  90. [self.openButton setTitle:NSLocalizedString(@"OPEN_NETWORK", nil) forState:UIControlStateNormal];
  91. [self.openButton setAccessibilityIdentifier:@"Open Network Stream"];
  92. [self.privateModeLabel setText:NSLocalizedString(@"PRIVATE_PLAYBACK_TOGGLE", nil)];
  93. UILabel *scanSubModelabel = self.ScanSubModeLabel;
  94. [scanSubModelabel setText:NSLocalizedString(@"SCAN_SUBTITLE_TOGGLE", nil)];
  95. [scanSubModelabel setAdjustsFontSizeToFitWidth:YES];
  96. [scanSubModelabel setNumberOfLines:0];
  97. [self.whatToOpenHelpLabel setText:NSLocalizedString(@"OPEN_NETWORK_HELP", nil)];
  98. self.urlField.delegate = self;
  99. self.urlField.keyboardType = UIKeyboardTypeURL;
  100. self.edgesForExtendedLayout = UIRectEdgeNone;
  101. // This will be called every time this VC is opened by the side menu controller
  102. [self updatePasteboardTextInURLField];
  103. // Registering a custom menu item for renaming streams
  104. NSString *renameTitle = NSLocalizedString(@"BUTTON_RENAME", nil);
  105. SEL renameStreamSelector = @selector(renameStream:);
  106. UIMenuItem *renameItem = [[UIMenuItem alloc] initWithTitle:renameTitle action:renameStreamSelector];
  107. UIMenuController *sharedMenuController = [UIMenuController sharedMenuController];
  108. [sharedMenuController setMenuItems:@[renameItem]];
  109. [sharedMenuController update];
  110. [self updateForTheme];
  111. }
  112. - (NSString *)detailText
  113. {
  114. return NSLocalizedString(@"STREAMVC_DETAILTEXT", nil);
  115. }
  116. - (UIImage *)cellImage
  117. {
  118. return [UIImage imageNamed:@"OpenNetStream"];
  119. }
  120. - (void)updateForTheme
  121. {
  122. self.historyTableView.backgroundColor = PresentationTheme.current.colors.background;
  123. self.view.backgroundColor = PresentationTheme.current.colors.background;
  124. NSAttributedString *coloredAttributedPlaceholder = [[NSAttributedString alloc] initWithString:@"http://myserver.com/file.mkv" attributes:@{NSForegroundColorAttributeName: PresentationTheme.current.colors.lightTextColor}];
  125. self.urlField.attributedPlaceholder = coloredAttributedPlaceholder;
  126. self.urlField.backgroundColor = PresentationTheme.current.colors.cellBackgroundB;
  127. self.urlField.textColor = PresentationTheme.current.colors.cellTextColor;
  128. self.privateModeLabel.textColor = PresentationTheme.current.colors.lightTextColor;
  129. self.ScanSubModeLabel.textColor = PresentationTheme.current.colors.lightTextColor;
  130. self.whatToOpenHelpLabel.textColor = PresentationTheme.current.colors.lightTextColor;
  131. self.openButton.backgroundColor = PresentationTheme.current.colors.orangeUI;
  132. [self.historyTableView reloadData];
  133. [self setNeedsStatusBarAppearanceUpdate];
  134. }
  135. - (UIStatusBarStyle)preferredStatusBarStyle
  136. {
  137. return PresentationTheme.current.colors.statusBarStyle;
  138. }
  139. - (void)updatePasteboardTextInURLField
  140. {
  141. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  142. if ([pasteboard containsPasteboardTypes:@[@"public.url"]])
  143. self.urlField.text = [[pasteboard valueForPasteboardType:@"public.url"] absoluteString];
  144. }
  145. - (void)viewWillAppear:(BOOL)animated
  146. {
  147. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  148. self.privateToggleSwitch.on = [defaults boolForKey:kVLCPrivateWebStreaming];
  149. self.ScanSubToggleSwitch.on = [defaults boolForKey:kVLChttpScanSubtitle];
  150. [super viewWillAppear:animated];
  151. }
  152. - (void)viewWillDisappear:(BOOL)animated
  153. {
  154. [[NSNotificationCenter defaultCenter] removeObserver:self
  155. name:UIApplicationDidBecomeActiveNotification
  156. object:[UIApplication sharedApplication]];
  157. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  158. [defaults setBool:self.privateToggleSwitch.on forKey:kVLCPrivateWebStreaming];
  159. [defaults setBool:self.ScanSubToggleSwitch.on forKey:kVLChttpScanSubtitle];
  160. [self.view endEditing:YES];
  161. /* force update before we leave */
  162. [[NSUbiquitousKeyValueStore defaultStore] synchronize];
  163. [super viewWillDisappear:animated];
  164. }
  165. - (CGSize)contentSizeForViewInPopover {
  166. return [self.view sizeThatFits:CGSizeMake(320, 800)];
  167. }
  168. #pragma mark - UI interaction
  169. - (BOOL)shouldAutorotate
  170. {
  171. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  172. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  173. return NO;
  174. return YES;
  175. }
  176. - (IBAction)openButtonAction:(id)sender
  177. {
  178. if ([self.urlField.text length] <= 0 || [NSURL URLWithString:self.urlField.text] == nil) {
  179. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"URL_NOT_SUPPORTED", nil)
  180. errorMessage:NSLocalizedString(@"PROTOCOL_NOT_SELECTED", nil)
  181. viewController:self];
  182. return;
  183. }
  184. if (!self.privateToggleSwitch.on) {
  185. NSString *urlString = self.urlField.text;
  186. if ([_recentURLs indexOfObject:urlString] != NSNotFound)
  187. [_recentURLs removeObject:urlString];
  188. if (_recentURLs.count >= 100)
  189. [_recentURLs removeLastObject];
  190. [_recentURLs addObject:urlString];
  191. [[NSUbiquitousKeyValueStore defaultStore] setArray:_recentURLs forKey:kVLCRecentURLs];
  192. [self.historyTableView reloadData];
  193. }
  194. [self.urlField resignFirstResponder];
  195. [self _openURLStringAndDismiss:self.urlField.text];
  196. }
  197. - (void)renameStreamFromCell:(UITableViewCell *)cell {
  198. NSIndexPath *cellIndexPath = [self.historyTableView indexPathForCell:cell];
  199. NSString *renameString = NSLocalizedString(@"BUTTON_RENAME", nil);
  200. NSString *cancelString = NSLocalizedString(@"BUTTON_CANCEL", nil);
  201. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:renameString
  202. message:nil
  203. preferredStyle:UIAlertControllerStyleAlert];
  204. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelString
  205. style:UIAlertActionStyleCancel
  206. handler:nil];
  207. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  208. NSString *streamTitle = alertController.textFields.firstObject.text;
  209. [self renameStreamWithTitle:streamTitle atIndex:cellIndexPath.row];
  210. }];
  211. [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
  212. textField.text = cell.textLabel.text;
  213. [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification
  214. object:textField
  215. queue:[NSOperationQueue mainQueue]
  216. usingBlock:^(NSNotification * _Nonnull note) {
  217. okAction.enabled = (textField.text.length != 0);
  218. }];
  219. }];
  220. [alertController addAction:cancelAction];
  221. [alertController addAction:okAction];
  222. [self presentViewController:alertController animated:YES completion:nil];
  223. }
  224. - (void)renameStreamWithTitle:(NSString *)title atIndex:(NSInteger)index
  225. {
  226. [_recentURLTitles setObject:title forKey:[@(index) stringValue]];
  227. [[NSUbiquitousKeyValueStore defaultStore] setDictionary:_recentURLTitles forKey:kVLCRecentURLTitles];
  228. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  229. [self.historyTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  230. }];
  231. }
  232. #pragma mark - table view data source
  233. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  234. {
  235. return 1;
  236. }
  237. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  238. {
  239. return _recentURLs.count;
  240. }
  241. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  242. {
  243. static NSString *CellIdentifier = @"StreamingHistoryCell";
  244. VLCStreamingHistoryCell *cell = (VLCStreamingHistoryCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  245. if (cell == nil) {
  246. cell = [[VLCStreamingHistoryCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  247. cell.delegate = self;
  248. [cell customizeAppearance];
  249. }
  250. NSString *content = [_recentURLs[indexPath.row] stringByRemovingPercentEncoding];
  251. NSString *possibleTitle = _recentURLTitles[[@(indexPath.row) stringValue]];
  252. cell.detailTextLabel.text = content;
  253. cell.textLabel.text = possibleTitle ?: [content lastPathComponent];
  254. return cell;
  255. }
  256. #pragma mark - table view delegate
  257. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  258. {
  259. cell.backgroundColor = (indexPath.row % 2 == 0)? PresentationTheme.current.colors.cellBackgroundB : PresentationTheme.current.colors.cellBackgroundA;
  260. cell.textLabel.textColor = PresentationTheme.current.colors.cellTextColor;
  261. cell.detailTextLabel.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  262. }
  263. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  264. {
  265. return YES;
  266. }
  267. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  268. {
  269. if (editingStyle == UITableViewCellEditingStyleDelete) {
  270. [_recentURLs removeObjectAtIndex:indexPath.row];
  271. [_recentURLTitles removeObjectForKey:[@(indexPath.row) stringValue]];
  272. [[NSUbiquitousKeyValueStore defaultStore] setArray:_recentURLs forKey:kVLCRecentURLs];
  273. [[NSUbiquitousKeyValueStore defaultStore] setDictionary:_recentURLTitles forKey:kVLCRecentURLTitles];
  274. [tableView reloadData];
  275. }
  276. }
  277. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  278. {
  279. [self.historyTableView deselectRowAtIndexPath:indexPath animated:NO];
  280. [self _openURLStringAndDismiss:_recentURLs[indexPath.row]];
  281. }
  282. - (void)tableView:(UITableView *)tableView
  283. performAction:(SEL)action
  284. forRowAtIndexPath:(NSIndexPath *)indexPath
  285. withSender:(id)sender
  286. {
  287. NSString *actionText = NSStringFromSelector(action);
  288. if ([actionText isEqualToString:@"copy:"])
  289. [UIPasteboard generalPasteboard].string = _recentURLs[indexPath.row];
  290. }
  291. - (BOOL)tableView:(UITableView *)tableView
  292. canPerformAction:(SEL)action
  293. forRowAtIndexPath:(NSIndexPath *)indexPath
  294. withSender:(id)sender
  295. {
  296. NSString *actionText = NSStringFromSelector(action);
  297. if ([actionText isEqualToString:@"copy:"])
  298. return YES;
  299. return NO;
  300. }
  301. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  302. {
  303. return YES;
  304. }
  305. #pragma mark - internals
  306. - (void)_openURLStringAndDismiss:(NSString *)url
  307. {
  308. NSURL *URLscheme = [NSURL URLWithString:url];
  309. NSString *URLofSubtitle = nil;
  310. if ([URLscheme.scheme isEqualToString:@"http"] && self.ScanSubToggleSwitch.on) {
  311. URLofSubtitle = [self _checkURLofSubtitle:url];
  312. }
  313. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:url]];
  314. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  315. [medialist addMedia:media];
  316. [[VLCPlaybackController sharedInstance] playMediaList:medialist firstIndex:0 subtitlesFilePath:URLofSubtitle];
  317. }
  318. - (NSString *)_checkURLofSubtitle:(NSString *)url
  319. {
  320. NSCharacterSet *characterFilter = [NSCharacterSet characterSetWithCharactersInString:@"\\.():$"];
  321. NSString *subtitleFileExtensions = [[kSupportedSubtitleFileExtensions componentsSeparatedByCharactersInSet:characterFilter] componentsJoinedByString:@""];
  322. NSArray *arraySubtitleFileExtensions = [subtitleFileExtensions componentsSeparatedByString:@"|"];
  323. NSString *urlTemp = [[url stringByDeletingPathExtension] stringByAppendingString:@"."];
  324. NSUInteger count = arraySubtitleFileExtensions.count;
  325. for (int i = 0; i < count; i++) {
  326. NSString *checkAddress = [urlTemp stringByAppendingString:arraySubtitleFileExtensions[i]];
  327. NSURL *checkURL = [NSURL URLWithString:checkAddress];
  328. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:checkURL];
  329. request.HTTPMethod = @"HEAD";
  330. NSURLResponse *response = nil;
  331. NSError *error = nil;
  332. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  333. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  334. if (httpStatus == 200) {
  335. NSString *fileSubtitlePath = [self _getFileSubtitleFromServer:checkURL];
  336. return fileSubtitlePath;
  337. }
  338. }
  339. return nil;
  340. }
  341. - (NSString *)_getFileSubtitleFromServer:(NSURL *)url
  342. {
  343. NSString *fileSubtitlePath = nil;
  344. NSString *fileName = [[url path] lastPathComponent];
  345. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  346. if (receivedSub.length < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
  347. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  348. NSString *directoryPath = [searchPaths objectAtIndex:0];
  349. fileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  350. NSFileManager *fileManager = [NSFileManager defaultManager];
  351. if (![fileManager fileExistsAtPath:fileSubtitlePath]) {
  352. [fileManager createFileAtPath:fileSubtitlePath contents:nil attributes:nil];
  353. if (![fileManager fileExistsAtPath:fileSubtitlePath])
  354. APLog(@"file creation failed, no data was saved");
  355. }
  356. [receivedSub writeToFile:fileSubtitlePath atomically:YES];
  357. } else {
  358. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  359. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]]
  360. viewController:self];
  361. }
  362. return fileSubtitlePath;
  363. }
  364. - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
  365. {
  366. NSError __block *erreur = NULL;
  367. NSData __block *data;
  368. BOOL __block reqProcessed = false;
  369. NSURLResponse __block *urlResponse;
  370. [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
  371. urlResponse = _response;
  372. erreur = _error;
  373. data = _data;
  374. reqProcessed = true;
  375. }] resume];
  376. while (!reqProcessed) {
  377. [NSThread sleepForTimeInterval:0];
  378. }
  379. *response = urlResponse;
  380. *error = erreur;
  381. return data;
  382. }
  383. #pragma mark - text view delegate
  384. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  385. {
  386. [self.urlField resignFirstResponder];
  387. return NO;
  388. }
  389. @end