VLCOpenNetworkStreamViewController.m 19 KB

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