VLCOpenNetworkStreamViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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_iOS-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. }
  134. - (void)updatePasteboardTextInURLField
  135. {
  136. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  137. if ([pasteboard containsPasteboardTypes:@[@"public.url"]])
  138. self.urlField.text = [[pasteboard valueForPasteboardType:@"public.url"] absoluteString];
  139. }
  140. - (void)viewWillAppear:(BOOL)animated
  141. {
  142. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  143. self.privateToggleSwitch.on = [defaults boolForKey:kVLCPrivateWebStreaming];
  144. self.ScanSubToggleSwitch.on = [defaults boolForKey:kVLChttpScanSubtitle];
  145. [super viewWillAppear:animated];
  146. }
  147. - (void)viewWillDisappear:(BOOL)animated
  148. {
  149. [[NSNotificationCenter defaultCenter] removeObserver:self
  150. name:UIApplicationDidBecomeActiveNotification
  151. object:[UIApplication sharedApplication]];
  152. NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  153. [defaults setBool:self.privateToggleSwitch.on forKey:kVLCPrivateWebStreaming];
  154. [defaults setBool:self.ScanSubToggleSwitch.on forKey:kVLChttpScanSubtitle];
  155. [self.view endEditing:YES];
  156. /* force update before we leave */
  157. [[NSUbiquitousKeyValueStore defaultStore] synchronize];
  158. [super viewWillDisappear:animated];
  159. }
  160. - (CGSize)contentSizeForViewInPopover {
  161. return [self.view sizeThatFits:CGSizeMake(320, 800)];
  162. }
  163. #pragma mark - UI interaction
  164. - (BOOL)shouldAutorotate
  165. {
  166. UIInterfaceOrientation toInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  167. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
  168. return NO;
  169. return YES;
  170. }
  171. - (IBAction)openButtonAction:(id)sender
  172. {
  173. if ([self.urlField.text length] <= 0 || [NSURL URLWithString:self.urlField.text] == nil) {
  174. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"URL_NOT_SUPPORTED", nil)
  175. errorMessage:NSLocalizedString(@"PROTOCOL_NOT_SELECTED", nil)
  176. viewController:self];
  177. return;
  178. }
  179. if (!self.privateToggleSwitch.on) {
  180. NSString *urlString = self.urlField.text;
  181. if ([_recentURLs indexOfObject:urlString] != NSNotFound)
  182. [_recentURLs removeObject:urlString];
  183. if (_recentURLs.count >= 100)
  184. [_recentURLs removeLastObject];
  185. [_recentURLs addObject:urlString];
  186. [[NSUbiquitousKeyValueStore defaultStore] setArray:_recentURLs forKey:kVLCRecentURLs];
  187. [self.historyTableView reloadData];
  188. }
  189. [self.urlField resignFirstResponder];
  190. [self _openURLStringAndDismiss:self.urlField.text];
  191. }
  192. - (void)renameStreamFromCell:(UITableViewCell *)cell {
  193. NSIndexPath *cellIndexPath = [self.historyTableView indexPathForCell:cell];
  194. NSString *renameString = NSLocalizedString(@"BUTTON_RENAME", nil);
  195. NSString *cancelString = NSLocalizedString(@"BUTTON_CANCEL", nil);
  196. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:renameString
  197. message:nil
  198. preferredStyle:UIAlertControllerStyleAlert];
  199. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelString
  200. style:UIAlertActionStyleCancel
  201. handler:nil];
  202. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  203. NSString *streamTitle = alertController.textFields.firstObject.text;
  204. [self renameStreamWithTitle:streamTitle atIndex:cellIndexPath.row];
  205. }];
  206. [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
  207. textField.text = cell.textLabel.text;
  208. [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification
  209. object:textField
  210. queue:[NSOperationQueue mainQueue]
  211. usingBlock:^(NSNotification * _Nonnull note) {
  212. okAction.enabled = (textField.text.length != 0);
  213. }];
  214. }];
  215. [alertController addAction:cancelAction];
  216. [alertController addAction:okAction];
  217. [self presentViewController:alertController animated:YES completion:nil];
  218. }
  219. - (void)renameStreamWithTitle:(NSString *)title atIndex:(NSInteger)index
  220. {
  221. [_recentURLTitles setObject:title forKey:[@(index) stringValue]];
  222. [[NSUbiquitousKeyValueStore defaultStore] setDictionary:_recentURLTitles forKey:kVLCRecentURLTitles];
  223. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  224. [self.historyTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
  225. }];
  226. }
  227. #pragma mark - table view data source
  228. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  229. {
  230. return 1;
  231. }
  232. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  233. {
  234. return _recentURLs.count;
  235. }
  236. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  237. {
  238. static NSString *CellIdentifier = @"StreamingHistoryCell";
  239. VLCStreamingHistoryCell *cell = (VLCStreamingHistoryCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  240. if (cell == nil) {
  241. cell = [[VLCStreamingHistoryCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
  242. cell.delegate = self;
  243. [cell customizeAppearance];
  244. }
  245. NSString *content = [_recentURLs[indexPath.row] stringByRemovingPercentEncoding];
  246. NSString *possibleTitle = _recentURLTitles[[@(indexPath.row) stringValue]];
  247. cell.detailTextLabel.text = content;
  248. cell.textLabel.text = possibleTitle ?: [content lastPathComponent];
  249. return cell;
  250. }
  251. #pragma mark - table view delegate
  252. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  253. {
  254. cell.backgroundColor = (indexPath.row % 2 == 0)? PresentationTheme.current.colors.cellBackgroundB : PresentationTheme.current.colors.cellBackgroundA;
  255. cell.textLabel.textColor = PresentationTheme.current.colors.cellTextColor;
  256. cell.detailTextLabel.textColor = PresentationTheme.current.colors.cellDetailTextColor;
  257. }
  258. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  259. {
  260. return YES;
  261. }
  262. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  263. {
  264. if (editingStyle == UITableViewCellEditingStyleDelete) {
  265. [_recentURLs removeObjectAtIndex:indexPath.row];
  266. [_recentURLTitles removeObjectForKey:[@(indexPath.row) stringValue]];
  267. [[NSUbiquitousKeyValueStore defaultStore] setArray:_recentURLs forKey:kVLCRecentURLs];
  268. [[NSUbiquitousKeyValueStore defaultStore] setDictionary:_recentURLTitles forKey:kVLCRecentURLTitles];
  269. [tableView reloadData];
  270. }
  271. }
  272. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  273. {
  274. [self.historyTableView deselectRowAtIndexPath:indexPath animated:NO];
  275. [self _openURLStringAndDismiss:_recentURLs[indexPath.row]];
  276. }
  277. - (void)tableView:(UITableView *)tableView
  278. performAction:(SEL)action
  279. forRowAtIndexPath:(NSIndexPath *)indexPath
  280. withSender:(id)sender
  281. {
  282. NSString *actionText = NSStringFromSelector(action);
  283. if ([actionText isEqualToString:@"copy:"])
  284. [UIPasteboard generalPasteboard].string = _recentURLs[indexPath.row];
  285. }
  286. - (BOOL)tableView:(UITableView *)tableView
  287. canPerformAction:(SEL)action
  288. forRowAtIndexPath:(NSIndexPath *)indexPath
  289. withSender:(id)sender
  290. {
  291. NSString *actionText = NSStringFromSelector(action);
  292. if ([actionText isEqualToString:@"copy:"])
  293. return YES;
  294. return NO;
  295. }
  296. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  297. {
  298. return YES;
  299. }
  300. #pragma mark - internals
  301. - (void)_openURLStringAndDismiss:(NSString *)url
  302. {
  303. NSURL *URLscheme = [NSURL URLWithString:url];
  304. NSString *URLofSubtitle = nil;
  305. if ([URLscheme.scheme isEqualToString:@"http"] && self.ScanSubToggleSwitch.on) {
  306. URLofSubtitle = [self _checkURLofSubtitle:url];
  307. }
  308. VLCMedia *media = [VLCMedia mediaWithURL:[NSURL URLWithString:url]];
  309. VLCMediaList *medialist = [[VLCMediaList alloc] init];
  310. [medialist addMedia:media];
  311. [[VLCPlaybackController sharedInstance] playMediaList:medialist firstIndex:0 subtitlesFilePath:URLofSubtitle];
  312. }
  313. - (NSString *)_checkURLofSubtitle:(NSString *)url
  314. {
  315. NSCharacterSet *characterFilter = [NSCharacterSet characterSetWithCharactersInString:@"\\.():$"];
  316. NSString *subtitleFileExtensions = [[kSupportedSubtitleFileExtensions componentsSeparatedByCharactersInSet:characterFilter] componentsJoinedByString:@""];
  317. NSArray *arraySubtitleFileExtensions = [subtitleFileExtensions componentsSeparatedByString:@"|"];
  318. NSString *urlTemp = [[url stringByDeletingPathExtension] stringByAppendingString:@"."];
  319. NSUInteger count = arraySubtitleFileExtensions.count;
  320. for (int i = 0; i < count; i++) {
  321. NSString *checkAddress = [urlTemp stringByAppendingString:arraySubtitleFileExtensions[i]];
  322. NSURL *checkURL = [NSURL URLWithString:checkAddress];
  323. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:checkURL];
  324. request.HTTPMethod = @"HEAD";
  325. NSURLResponse *response = nil;
  326. NSError *error = nil;
  327. [self sendSynchronousRequest:request returningResponse:&response error:&error];
  328. NSInteger httpStatus = [(NSHTTPURLResponse *)response statusCode];
  329. if (httpStatus == 200) {
  330. NSString *fileSubtitlePath = [self _getFileSubtitleFromServer:checkURL];
  331. return fileSubtitlePath;
  332. }
  333. }
  334. return nil;
  335. }
  336. - (NSString *)_getFileSubtitleFromServer:(NSURL *)url
  337. {
  338. NSString *fileSubtitlePath = nil;
  339. NSString *fileName = [[url path] lastPathComponent];
  340. NSData *receivedSub = [NSData dataWithContentsOfURL:url];
  341. if (receivedSub.length < [[UIDevice currentDevice] VLCFreeDiskSpace].longLongValue) {
  342. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  343. NSString *directoryPath = [searchPaths objectAtIndex:0];
  344. fileSubtitlePath = [directoryPath stringByAppendingPathComponent:fileName];
  345. NSFileManager *fileManager = [NSFileManager defaultManager];
  346. if (![fileManager fileExistsAtPath:fileSubtitlePath]) {
  347. [fileManager createFileAtPath:fileSubtitlePath contents:nil attributes:nil];
  348. if (![fileManager fileExistsAtPath:fileSubtitlePath])
  349. APLog(@"file creation failed, no data was saved");
  350. }
  351. [receivedSub writeToFile:fileSubtitlePath atomically:YES];
  352. } else {
  353. [VLCAlertViewController alertViewManagerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  354. errorMessage:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), fileName, [[UIDevice currentDevice] model]]
  355. viewController:self];
  356. }
  357. return fileSubtitlePath;
  358. }
  359. - (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
  360. {
  361. NSError __block *erreur = NULL;
  362. NSData __block *data;
  363. BOOL __block reqProcessed = false;
  364. NSURLResponse __block *urlResponse;
  365. [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
  366. urlResponse = _response;
  367. erreur = _error;
  368. data = _data;
  369. reqProcessed = true;
  370. }] resume];
  371. while (!reqProcessed) {
  372. [NSThread sleepForTimeInterval:0];
  373. }
  374. *response = urlResponse;
  375. *error = erreur;
  376. return data;
  377. }
  378. #pragma mark - text view delegate
  379. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  380. {
  381. [self.urlField resignFirstResponder];
  382. return NO;
  383. }
  384. @end