diff --git a/changelog/v0.1.0-beta4.txt b/changelog/v0.1.0-beta4.txt index 783412d7c..4dec30d9a 100644 --- a/changelog/v0.1.0-beta4.txt +++ b/changelog/v0.1.0-beta4.txt @@ -221,6 +221,7 @@ PLAYER - When YouTube refuses a video's stream partway through, Flow fetches the same file from another client and carries on from the same byte, so the video keeps playing instead of stopping or reloading. - The video title no longer sits above the seek bar, where it repeated the title under the video. It shows there in fullscreen, where the Fullscreen Title switch is now on by default, and in the pop-out player. - 360° videos can be looked around, as on Android: drag the picture, zoom with the wheel, or use W, A, S and D. The settings menu has a 360° view switch for each video and a Look-around speed of 1x to 3x. The mini player and ambient glow show the flat picture. If a computer can't draw the view smoothly, Flow goes back to the flat picture and says so. +- A Prefer IPv4 switch in Settings > Network & Buffer connects to YouTube over IPv4 when your network offers both. Turn it on if YouTube keeps asking you to confirm you're not a bot on an IPv6 network. SETTINGS - Flow's windows can now shrink to 480 by 360, small enough for a half or quarter screen tile. In a narrow window the menu button opens the side menu over the page, as it does on the Watch page. diff --git a/src-tauri/src/api/app_proxy.rs b/src-tauri/src/api/app_proxy.rs index 6261f63b7..13c493333 100644 --- a/src-tauri/src/api/app_proxy.rs +++ b/src-tauri/src/api/app_proxy.rs @@ -1,4 +1,6 @@ //! The proxy the user set in Settings, for every client that reaches the internet. +//! [`with_app_network`] is the one place those clients are built through, so it also +//! installs the Prefer IPv4 resolver from [`super::ip_family`]. //! //! Each client asks [`route`] for every new connection, so one built before the //! saved proxy loaded, or before the user changed it, still follows it. Devices on @@ -58,9 +60,11 @@ pub fn apply_setting(key: &str, value: Option<&str>) -> bool { true } -/// Sends a client's connections through the proxy in force at the time. -pub fn with_app_proxy(builder: ClientBuilder) -> ClientBuilder { - builder.proxy(Proxy::custom(route)) +/// Sends a client's connections through the proxy and address family in force at the time. +pub fn with_app_network(builder: ClientBuilder) -> ClientBuilder { + builder + .proxy(Proxy::custom(route)) + .dns_resolver(super::ip_family::FamilyResolver) } fn route(destination: &Url) -> Option { @@ -265,7 +269,9 @@ mod tests { // One test, because the settings are process-wide. #[tokio::test] async fn a_client_built_before_the_setting_follows_it() { - let client = with_app_proxy(reqwest::Client::builder()).build().unwrap(); + let client = with_app_network(reqwest::Client::builder()) + .build() + .unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port().to_string(); for (key, value) in [ diff --git a/src-tauri/src/api/http.rs b/src-tauri/src/api/http.rs index 20839e910..41b6c2b69 100644 --- a/src-tauri/src/api/http.rs +++ b/src-tauri/src/api/http.rs @@ -21,7 +21,7 @@ pub const DEFAULT_FETCH_CONCURRENCY: usize = 8; pub fn shared_client() -> &'static reqwest::Client { static CLIENT: OnceLock = OnceLock::new(); CLIENT.get_or_init(|| { - super::app_proxy::with_app_proxy(reqwest::Client::builder()) + super::app_proxy::with_app_network(reqwest::Client::builder()) .tls_backend_rustls() .user_agent(BROWSER_USER_AGENT) .pool_idle_timeout(Duration::from_secs(90)) diff --git a/src-tauri/src/api/innertube/mod.rs b/src-tauri/src/api/innertube/mod.rs index 21b0e9608..7e1d6902f 100644 --- a/src-tauri/src/api/innertube/mod.rs +++ b/src-tauri/src/api/innertube/mod.rs @@ -8,7 +8,7 @@ pub mod renderers; pub mod transport; fn build_http_client() -> reqwest::Client { - crate::api::app_proxy::with_app_proxy(reqwest::Client::builder()) + crate::api::app_proxy::with_app_network(reqwest::Client::builder()) .tls_backend_rustls() .pool_idle_timeout(std::time::Duration::from_secs(120)) .pool_max_idle_per_host(15) diff --git a/src-tauri/src/api/ip_family.rs b/src-tauri/src/api/ip_family.rs new file mode 100644 index 000000000..203b94075 --- /dev/null +++ b/src-tauri/src/api/ip_family.rs @@ -0,0 +1,129 @@ +//! The Prefer IPv4 setting: host names resolve to IPv4 addresses only, when the host has any. +//! +//! Some ISPs' IPv6 ranges are flagged by `YouTube`, so every video asks to confirm you're not +//! a bot until the network's IPv6 is switched off. Each client asks [`FamilyResolver`] on every new +//! connection, so one built before the setting loaded, or before the user changed it, +//! still follows it. A host with no IPv4 address keeps its IPv6 ones, so IPv6-only and +//! NAT64 networks still connect. + +use std::net::SocketAddr; +use std::sync::atomic::{AtomicBool, Ordering}; + +use reqwest::dns::{Addrs, Name, Resolve, Resolving}; + +pub const PREFER_IPV4_SETTING: &str = "network_prefer_ipv4"; + +static PREFER_IPV4: AtomicBool = AtomicBool::new(false); + +/// Whether `key` is the Prefer IPv4 setting; if so, the new value is in force. +pub fn apply_setting(key: &str, value: Option<&str>) -> bool { + if key != PREFER_IPV4_SETTING { + return false; + } + let prefer_ipv4 = value.is_some_and(|value| value.eq_ignore_ascii_case("true")); + if PREFER_IPV4.swap(prefer_ipv4, Ordering::Relaxed) != prefer_ipv4 { + tracing::info!(prefer_ipv4, "network address preference changed"); + } + true +} + +/// The system resolver, narrowed to IPv4 while Prefer IPv4 is on. +pub struct FamilyResolver; + +impl Resolve for FamilyResolver { + fn resolve(&self, name: Name) -> Resolving { + let host = name.as_str().to_owned(); + Box::pin(async move { + // Port 0 is replaced by the URL's port, as with reqwest's own resolver. + let addrs: Vec = + tokio::net::lookup_host((host.as_str(), 0)).await?.collect(); + let addrs = filter_family(addrs, PREFER_IPV4.load(Ordering::Relaxed)); + Ok(Box::new(addrs.into_iter()) as Addrs) + }) + } +} + +fn filter_family(addrs: Vec, prefer_ipv4: bool) -> Vec { + if !prefer_ipv4 || !addrs.iter().any(SocketAddr::is_ipv4) { + return addrs; + } + addrs.into_iter().filter(SocketAddr::is_ipv4).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn addrs(list: &[&str]) -> Vec { + list.iter().map(|addr| addr.parse().unwrap()).collect() + } + + #[test] + fn keeps_every_address_when_off() { + let mixed = addrs(&["[2001:db8::1]:0", "192.0.2.1:0"]); + assert_eq!(filter_family(mixed.clone(), false), mixed); + } + + #[test] + fn keeps_only_ipv4_when_on() { + let mixed = addrs(&[ + "[2001:db8::1]:0", + "192.0.2.1:0", + "[2001:db8::2]:0", + "192.0.2.2:0", + ]); + assert_eq!( + filter_family(mixed, true), + addrs(&["192.0.2.1:0", "192.0.2.2:0"]) + ); + } + + #[test] + fn falls_back_to_ipv6_when_the_host_has_no_ipv4() { + let ipv6_only = addrs(&["[2001:db8::1]:0", "[64:ff9b::c000:201]:0"]); + assert_eq!(filter_family(ipv6_only.clone(), true), ipv6_only); + assert!(filter_family(Vec::new(), true).is_empty()); + } + + // One test, because the setting is process-wide. + #[tokio::test] + async fn a_client_built_before_the_setting_follows_it() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let client = reqwest::Client::builder() + .dns_resolver(FamilyResolver) + .build() + .unwrap(); + assert!(!apply_setting("proxy_enabled", Some("true"))); + assert!(apply_setting(PREFER_IPV4_SETTING, Some("true"))); + + let resolved: Vec = FamilyResolver + .resolve("localhost".parse().unwrap()) + .await + .unwrap() + .collect(); + assert!(!resolved.is_empty()); + assert!(resolved.iter().all(SocketAddr::is_ipv4), "{resolved:?}"); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0_u8; 1024]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let response = client + .get(format!("http://localhost:{port}/")) + .send() + .await + .unwrap(); + assert_eq!(response.text().await.unwrap(), "ok"); + server.await.unwrap(); + + apply_setting(PREFER_IPV4_SETTING, Some("false")); + } +} diff --git a/src-tauri/src/api/mod.rs b/src-tauri/src/api/mod.rs index a54be3f16..bdc44839c 100644 --- a/src-tauri/src/api/mod.rs +++ b/src-tauri/src/api/mod.rs @@ -2,6 +2,7 @@ pub mod app_proxy; pub mod dearrow; pub mod http; pub mod innertube; +pub mod ip_family; pub mod lyrics_http; pub mod lyrics_romanize; pub mod original_title; diff --git a/src-tauri/src/commands/db.rs b/src-tauri/src/commands/db.rs index 3828385d0..367fd41e0 100644 --- a/src-tauri/src/commands/db.rs +++ b/src-tauri/src/commands/db.rs @@ -1,6 +1,6 @@ -use crate::api::app_proxy; use crate::api::innertube::core::{locale, remote_decoder}; use crate::api::innertube::extractors::audio_preference; +use crate::api::{app_proxy, ip_family}; use crate::commands::linked::err as linked_err; use crate::db::settings; use crate::db::watch_history::{self, WatchHistoryRecord}; @@ -228,7 +228,7 @@ pub async fn set_setting( } /// Settings the backend acts on itself, applied at startup and whenever saved. -pub(crate) const BACKEND_SETTINGS: [&str; 10] = [ +pub(crate) const BACKEND_SETTINGS: [&str; 11] = [ remote_decoder::SETTING_KEY, audio_preference::STABLE_VOLUME_SETTING, locale::CONTENT_LANGUAGE_SETTING, @@ -239,10 +239,11 @@ pub(crate) const BACKEND_SETTINGS: [&str; 10] = [ app_proxy::PORT_SETTING, app_proxy::USERNAME_SETTING, app_proxy::PASSWORD_SETTING, + ip_family::PREFER_IPV4_SETTING, ]; pub(crate) fn apply_backend_setting(key: &str, value: Option<&str>) { - if app_proxy::apply_setting(key, value) { + if app_proxy::apply_setting(key, value) || ip_family::apply_setting(key, value) { return; } let enabled = value.is_some_and(|value| value.eq_ignore_ascii_case("true")); diff --git a/src-tauri/src/commands/downloads/transfer.rs b/src-tauri/src/commands/downloads/transfer.rs index 52b0308ba..5749b68aa 100644 --- a/src-tauri/src/commands/downloads/transfer.rs +++ b/src-tauri/src/commands/downloads/transfer.rs @@ -29,7 +29,7 @@ const MAX_RETRY_DELAY: Duration = Duration::from_secs(60); fn download_client() -> &'static Client { static CLIENT: OnceLock = OnceLock::new(); CLIENT.get_or_init(|| { - crate::api::app_proxy::with_app_proxy(Client::builder()) + crate::api::app_proxy::with_app_network(Client::builder()) .connect_timeout(Duration::from_secs(15)) .read_timeout(Duration::from_secs(30)) .no_gzip() diff --git a/src-tauri/src/profiles/device_keys.rs b/src-tauri/src/profiles/device_keys.rs index b988e4078..23f9b8ca2 100644 --- a/src-tauri/src/profiles/device_keys.rs +++ b/src-tauri/src/profiles/device_keys.rs @@ -5,7 +5,7 @@ /// Device settings defined in `src/lib/settings/schema.ts` (`SETTING_SCOPES`); a test keeps the /// two lists equal. -pub const SCHEMA_DEVICE_KEYS: [&str; 65] = [ +pub const SCHEMA_DEVICE_KEYS: [&str; 66] = [ "allow_volume_boost", "player_volume", "player_volume_boost", @@ -33,6 +33,7 @@ pub const SCHEMA_DEVICE_KEYS: [&str; 65] = [ "buffer_for_playback_ms", "buffer_for_playback_after_rebuffer_ms", "remote_signature_fallback", + "network_prefer_ipv4", "highlight_new_settings", "highlight_new_settings_days", "proxy_enabled", diff --git a/src-tauri/src/streaming/proxy.rs b/src-tauri/src/streaming/proxy.rs index 84560c82e..7d747532b 100644 --- a/src-tauri/src/streaming/proxy.rs +++ b/src-tauri/src/streaming/proxy.rs @@ -494,7 +494,7 @@ pub async fn start_proxy_server(manager: StreamingManager, std_listener: std::ne .local_addr() .map_or_else(|_| "an unknown port".to_string(), |addr| addr.to_string()) ); - let client = crate::api::app_proxy::with_app_proxy(reqwest::Client::builder()) + let client = crate::api::app_proxy::with_app_network(reqwest::Client::builder()) .connect_timeout(std::time::Duration::from_secs(10)) .no_gzip() .no_brotli() diff --git a/src-tauri/src/streaming/sabr/engine.rs b/src-tauri/src/streaming/sabr/engine.rs index fec51020e..1b194576a 100644 --- a/src-tauri/src/streaming/sabr/engine.rs +++ b/src-tauri/src/streaming/sabr/engine.rs @@ -224,7 +224,7 @@ impl SabrEngine { None => (String::new(), selected.audio.itag), }; - let client = crate::api::app_proxy::with_app_proxy(reqwest::Client::builder()) + let client = crate::api::app_proxy::with_app_network(reqwest::Client::builder()) .pool_idle_timeout(Duration::from_secs(60)) .build() .unwrap_or_default(); diff --git a/src-tauri/src/sync2/http.rs b/src-tauri/src/sync2/http.rs index 46975977e..16556304e 100644 --- a/src-tauri/src/sync2/http.rs +++ b/src-tauri/src/sync2/http.rs @@ -82,7 +82,7 @@ impl Transport { } pub fn builder(&self) -> ClientBuilder { - let builder = crate::api::app_proxy::with_app_proxy(Client::builder()) + let builder = crate::api::app_proxy::with_app_network(Client::builder()) .tls_backend_rustls() .redirect(redirect::Policy::none()) .user_agent(concat!("FlowDesktop/", env!("CARGO_PKG_VERSION"))) diff --git a/src/components/settings/tabs/NetworkTab.tsx b/src/components/settings/tabs/NetworkTab.tsx index 3ac595b6d..3fc62bba8 100644 --- a/src/components/settings/tabs/NetworkTab.tsx +++ b/src/components/settings/tabs/NetworkTab.tsx @@ -17,6 +17,7 @@ export function NetworkTab() { const [playbackBuffer, setPlaybackBuffer] = useNumberPref(SETTINGS.BUFFER_FOR_PLAYBACK_MS, 2500); const [rebufferBuffer, setRebufferBuffer] = useNumberPref(SETTINGS.BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS, 5000); const [remoteSignatures, setRemoteSignatures] = useBoolPref(SETTINGS.REMOTE_SIGNATURE_FALLBACK, true); + const [preferIpv4, setPreferIpv4] = useBoolPref(SETTINGS.PREFER_IPV4, false); const [proxyEnabled, setProxyEnabled] = useBoolPref(SETTINGS.PROXY_ENABLED, false); const [proxyType, setProxyType] = usePreference(SETTINGS.PROXY_TYPE, 'http'); const [proxyHost, setProxyHost] = usePreference(SETTINGS.PROXY_HOST, ''); @@ -72,6 +73,9 @@ export function NetworkTab() { + + + diff --git a/src/lib/i18n/strings.json b/src/lib/i18n/strings.json index df60c7d2f..cefe6148e 100644 --- a/src/lib/i18n/strings.json +++ b/src/lib/i18n/strings.json @@ -1757,6 +1757,8 @@ "settings_group_playback_sources": "Playback sources", "settings_remote_signature_fallback": "Remote signature fallback", "settings_remote_signature_fallback_desc": "When YouTube stops serving the usual sources, ask PipePipe's public decoder to solve the TV app's signed streams. It receives the signature and player ids, never the video id.", + "settings_prefer_ipv4": "Prefer IPv4", + "settings_prefer_ipv4_desc": "Connect to YouTube over IPv4 when your network offers both. Try this if every video asks you to confirm you're not a bot.", "settings_enable_proxy": "Enable Proxy", "settings_enable_proxy_desc": "Send Flow's traffic through a proxy server. Devices on your network stay direct", "settings_proxy_protocol": "Protocol", @@ -3269,7 +3271,7 @@ "player_error_music_premium_title": "YouTube Music Premium content", "player_error_music_premium_hint": "This track is only available to YouTube Music Premium subscribers.", "player_error_bot_check_title": "YouTube bot check required", - "player_error_bot_check_hint": "YouTube is asking for verification before serving this stream. Try again in a moment, or open it in a browser and solve the check.", + "player_error_bot_check_hint": "YouTube is asking for verification before serving this stream. Try again in a moment, or open it in a browser and solve the check. If every video asks, turn on Prefer IPv4 in Settings > Network & Buffer.", "player_error_account_terminated_title": "Channel no longer exists", "player_error_account_terminated_hint": "This channel has been closed or terminated, so its videos can't be played.", "player_error_not_available_title": "Content not available", diff --git a/src/lib/settings/schema.ts b/src/lib/settings/schema.ts index 021ca524c..39c751743 100644 --- a/src/lib/settings/schema.ts +++ b/src/lib/settings/schema.ts @@ -253,6 +253,7 @@ export const SETTINGS = { BUFFER_FOR_PLAYBACK_MS: "buffer_for_playback_ms", BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS: "buffer_for_playback_after_rebuffer_ms", REMOTE_SIGNATURE_FALLBACK: "remote_signature_fallback", + PREFER_IPV4: "network_prefer_ipv4", PROXY_ENABLED: "proxy_enabled", PROXY_TYPE: "proxy_type", PROXY_HOST: "proxy_host", @@ -532,6 +533,7 @@ export const SETTING_SCOPES = { [SETTINGS.BUFFER_FOR_PLAYBACK_MS]: "device", [SETTINGS.BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS]: "device", [SETTINGS.REMOTE_SIGNATURE_FALLBACK]: "device", + [SETTINGS.PREFER_IPV4]: "device", [SETTINGS.PROXY_ENABLED]: "device", [SETTINGS.PROXY_TYPE]: "device", [SETTINGS.PROXY_HOST]: "device", @@ -905,6 +907,7 @@ export const SETTING_DEFINITIONS = [ num(SETTINGS.BUFFER_FOR_PLAYBACK_MS, "network", 2500, "partial", 500, 5000), num(SETTINGS.BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS, "network", 5000, "partial", 2500, 10000), bool(SETTINGS.REMOTE_SIGNATURE_FALLBACK, "network", true, "wired"), + bool(SETTINGS.PREFER_IPV4, "network", false, "wired"), bool(SETTINGS.PROXY_ENABLED, "network", false, "wired"), str(SETTINGS.PROXY_TYPE, "network", "http", "wired", ["http", "socks5", "socks4"]), str(SETTINGS.PROXY_HOST, "network", "", "wired"), diff --git a/src/lib/settings/settingsIndex.ts b/src/lib/settings/settingsIndex.ts index 49a0bb7f7..af5ee69da 100644 --- a/src/lib/settings/settingsIndex.ts +++ b/src/lib/settings/settingsIndex.ts @@ -292,6 +292,7 @@ export const SETTINGS_INDEX: SettingEntry[] = [ { title: "settings_cache_lyrics", summary: "settings_cache_lyrics_desc", keywords: ["storage", "clear"] }, { title: "settings_cache_network", summary: "settings_cache_network_desc", keywords: ["storage", "clear", "responses"] }, { title: "settings_remote_signature_fallback", summary: "settings_remote_signature_fallback_desc" }, + { title: "settings_prefer_ipv4", summary: "settings_prefer_ipv4_desc", keywords: ["ipv6", "bot", "sign in", "network"] }, { title: "settings_enable_proxy", summary: "settings_enable_proxy_desc", keywords: ["vpn", "socks", "network"] }, { title: "settings_proxy_protocol" }, { title: "settings_proxy_host" },