diff --git a/scripts/check.sh b/scripts/check.sh index dab22dc..e0888d5 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -1,14 +1,16 @@ #!/usr/bin/env bash -# Static checks: Rust unit tests + clippy, TypeScript typecheck + unit tests +# Static checks: Rust formatting, unit tests + clippy, TypeScript typecheck + unit tests # (vitest), and that THIRD_PARTY_NOTICES.md matches the current dependencies. # (End-to-end: scripts/smoke.sh) set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" [[ -f "$ROOT/.deps/env.sh" ]] && . "$ROOT/.deps/env.sh" +echo "==> cargo fmt" +(cd "$ROOT/src-tauri" && cargo fmt --check) echo "==> cargo test" (cd "$ROOT/src-tauri" && cargo test --lib --quiet) echo "==> cargo clippy" -(cd "$ROOT/src-tauri" && cargo clippy --quiet --all-targets -- -D warnings) +(cd "$ROOT/src-tauri" && cargo clippy --quiet --all-targets -- -D warnings -D clippy::undocumented_unsafe_blocks) echo "==> tsc" (cd "$ROOT" && bunx tsc --noEmit -p .) echo "==> vitest" diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 613f919..530dcf1 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -21,7 +21,7 @@ fn main() { /// FFmpeg's headers. Built before the media engine is linked: static /// archives must come after the code that uses them. fn build_cast_remux() { - let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); + let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo")); let prefix = std::env::var("TP_MEDIA_PREFIX") .map(PathBuf::from) .unwrap_or_else(|_| manifest.join("../third_party/prefix")); @@ -39,7 +39,7 @@ fn build_cast_remux() { /// dynamic tail differs: no pkg-config probe (macOS's static archives reference /// frameworks and libSystem), link the well-known set directly. fn link_media_engine_macos() { - let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); + let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo")); let prefix = std::env::var("TP_MEDIA_PREFIX") .map(PathBuf::from) .unwrap_or_else(|_| manifest.join("../third_party/prefix")); @@ -222,7 +222,7 @@ fn link_swift_surface(manifest: &std::path::Path) { /// dynamically. The result is a single self-contained executable whose codec /// support does not depend on the distro's FFmpeg build. fn link_media_engine() { - let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()); + let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo")); let prefix = std::env::var("TP_MEDIA_PREFIX") .map(PathBuf::from) .unwrap_or_else(|_| manifest.join("../third_party/prefix")); @@ -264,7 +264,7 @@ fn link_media_engine() { ); } String::from_utf8(out.stdout) - .unwrap() + .expect("pkg-config prints UTF-8") .split_whitespace() .map(str::to_owned) .collect() diff --git a/src-tauri/src/cast/castv2.rs b/src-tauri/src/cast/castv2.rs index ca7e7cc..436d730 100644 --- a/src-tauri/src/cast/castv2.rs +++ b/src-tauri/src/cast/castv2.rs @@ -13,12 +13,14 @@ use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf}; use tokio::net::TcpStream; +use tokio_rustls::TlsConnector; use tokio_rustls::client::TlsStream; -use tokio_rustls::rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use tokio_rustls::rustls::client::danger::{ + HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier, +}; use tokio_rustls::rustls::crypto::{self, CryptoProvider}; use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName, UnixTime}; use tokio_rustls::rustls::{self, ClientConfig, DigitallySignedStruct, SignatureScheme}; -use tokio_rustls::TlsConnector; pub const NS_CONNECTION: &str = "urn:x-cast:com.google.cast.tp.connection"; pub const NS_HEARTBEAT: &str = "urn:x-cast:com.google.cast.tp.heartbeat"; @@ -42,7 +44,12 @@ pub struct Message { impl Message { pub fn new(destination: &str, namespace: &str, payload: String) -> Self { - Message { source: SENDER.into(), destination: destination.into(), namespace: namespace.into(), payload } + Message { + source: SENDER.into(), + destination: destination.into(), + namespace: namespace.into(), + payload, + } } } @@ -92,7 +99,12 @@ fn get_varint(buf: &[u8], pos: &mut usize) -> Option { /// Parses a `CastMessage`; `None` for malformed or binary-payload messages /// (device authentication, which this sender doesn't use). pub fn decode(buf: &[u8]) -> Option { - let mut m = Message { source: String::new(), destination: String::new(), namespace: String::new(), payload: String::new() }; + let mut m = Message { + source: String::new(), + destination: String::new(), + namespace: String::new(), + payload: String::new(), + }; let mut has_payload = false; let mut pos = 0; while pos < buf.len() { @@ -127,6 +139,12 @@ pub fn decode(buf: &[u8]) -> Option { // --------------------------------------------------------------- TLS +/// Accepts any server certificate. Deliberate: Chromecasts present a +/// self-signed certificate (device authentication happens over the Cast +/// channel, which this sender skips), and the address comes from mDNS or the +/// user on the local network. Handshake signatures are still verified, so +/// the session is encrypted — just not authenticated. Never reuse this for +/// anything that talks to the internet. #[derive(Debug)] struct DeviceCert(Arc); @@ -148,7 +166,12 @@ impl ServerCertVerifier for DeviceCert { cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { - crypto::verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms) + crypto::verify_tls12_signature( + message, + cert, + dss, + &self.0.signature_verification_algorithms, + ) } fn verify_tls13_signature( @@ -157,7 +180,12 @@ impl ServerCertVerifier for DeviceCert { cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result { - crypto::verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms) + crypto::verify_tls13_signature( + message, + cert, + dss, + &self.0.signature_verification_algorithms, + ) } fn supported_verify_schemes(&self) -> Vec { @@ -167,6 +195,9 @@ impl ServerCertVerifier for DeviceCert { type Tls = TlsStream; +/// For each of the TCP connect and the TLS handshake. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(6); + pub struct Reader(ReadHalf); pub struct Writer(WriteHalf); @@ -180,15 +211,18 @@ pub async fn connect(addr: SocketAddr) -> io::Result<(Reader, Writer, IpAddr)> { .dangerous() .with_custom_certificate_verifier(Arc::new(DeviceCert(provider))) .with_no_client_auth(); - let tcp = tokio::time::timeout(Duration::from_secs(6), TcpStream::connect(addr)) + let tcp = tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "the device did not answer"))??; tcp.set_nodelay(true)?; let local = tcp.local_addr()?.ip(); let name = ServerName::IpAddress(addr.ip().into()); - let tls = tokio::time::timeout(Duration::from_secs(6), TlsConnector::from(Arc::new(config)).connect(name, tcp)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "the device did not answer"))??; + let tls = tokio::time::timeout( + CONNECT_TIMEOUT, + TlsConnector::from(Arc::new(config)).connect(name, tcp), + ) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "the device did not answer"))??; let (r, w) = tokio::io::split(tls); Ok((Reader(r), Writer(w), local)) } @@ -199,7 +233,10 @@ impl Reader { loop { let len = self.0.read_u32().await? as usize; if len > MAX_FRAME { - return Err(io::Error::new(io::ErrorKind::InvalidData, "oversized cast frame")); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "oversized cast frame", + )); } let mut buf = vec![0; len]; self.0.read_exact(&mut buf).await?; @@ -227,7 +264,11 @@ mod tests { #[test] fn round_trips_messages() { - let m = Message::new(RECEIVER, NS_RECEIVER, r#"{"type":"LAUNCH","appId":"CC1AD845","requestId":1}"#.into()); + let m = Message::new( + RECEIVER, + NS_RECEIVER, + r#"{"type":"LAUNCH","appId":"CC1AD845","requestId":1}"#.into(), + ); let bytes = encode(&m); // protocol 0, then source "sender-0" assert_eq!(&bytes[..4], &[0x08, 0x00, 0x12, 0x08]); diff --git a/src-tauri/src/cast/commands.rs b/src-tauri/src/cast/commands.rs new file mode 100644 index 0000000..fb691c5 --- /dev/null +++ b/src-tauri/src/cast/commands.rs @@ -0,0 +1,188 @@ +//! The `cast_*` commands the UI drives casting with. + +use super::*; + +/// The cast devices found so far; the first call starts looking +/// (updates follow as `cast://devices`). +#[tauri::command] +pub fn cast_devices(app: AppHandle, cast: State<'_, Cast>) -> Result { + if cast.relay.is_none() { + return Err(Error::msg( + "Casting is unavailable: no network port could be opened", + )); + } + // mDNS is optional: the search by address finds TVs without it + if let Err(e) = start_browsing(&app, &cast) { + log::warn!("cast: {e}"); + } + search(&app, &cast); + Ok(cast.list()) +} + +/// Adds a TV by its IP address (for networks where it can't be found). +#[tauri::command] +pub async fn cast_add_device( + app: AppHandle, + state: State<'_, AppState>, + cast: State<'_, Cast>, + address: String, +) -> Result { + let ip = probe::parse_address(&address) + .ok_or_else(|| Error::msg("Enter the TV's IP address, like 192.168.1.20"))?; + let device = probe::probe(&state.http, ip).await.ok_or_else(|| { + Error::msg(format!( + "No Chromecast answered at {ip}. Check the address in the Google Home app." + )) + })?; + remember(state.inner(), &device).await; + if cast.found(device.clone()) { + emit_devices(&app); + } + Ok(device) +} + +/// Plays `req` on a TV: on `device_id` (starting a session there), or on the +/// TV already being cast to. Local playback stops — the account streams to +/// one place. +#[tauri::command] +#[allow(clippy::too_many_arguments)] // Tauri injects each managed `State` as an argument +pub async fn cast_play( + app: AppHandle, + state: State<'_, AppState>, + player: State<'_, Player>, + probe: State<'_, Arc>, + cast: State<'_, Cast>, + device_id: Option, + req: PlayRequest, + meta: Option, +) -> Result<()> { + let st = state.inner().clone(); + let stream = playback::resolve_and_touch(&st, &req).await?; + let audio_lang = + read_blocking(&st, |conn| Ok(settings::get_str(conn, "player.audioLang"))).await?; + probe.cancel_running().await?; + let _ = player.stop(); + + let mut urls = vec![stream.url]; + urls.extend(stream.alternates); + let mut meta = meta.unwrap_or_default(); + meta.title = meta.title.or(req.title.clone()); + let item = Box::new(Item { + source: relay::Source { + urls, + user_agent: stream.user_agent, + referrer: stream.referrer, + live: stream.live, + audio_lang, + }, + meta, + start: req.start.unwrap_or(0.0), + }); + + let mut session = cast.session.lock(); + let running = session.as_ref().filter(|s| !s.status.lock().finished()); + let reuse = match (&device_id, running) { + (None, Some(_)) => true, + (Some(id), Some(s)) => &s.device.id == id, + (None, None) => return Err(Error::msg("Not casting")), + (Some(_), None) => false, + }; + if reuse { + let s = session.as_ref().expect("running session"); + log::info!( + "cast: {} {}:{} to {}", + req.kind, + req.source_id, + req.id, + s.device.name + ); + return s + .tx + .send(Cmd::Load(item)) + .map_err(|_| Error::msg("The cast session has ended")); + } + + let id = device_id.unwrap_or_default(); + let device = cast + .devices + .lock() + .get(&id) + .cloned() + .ok_or_else(|| Error::msg("That TV is no longer on the network"))?; + if let Some(old) = session.take() { + let _ = old.tx.send(Cmd::Stop); + } + let (tx, rx) = mpsc::unbounded_channel(); + let status = Arc::new(Mutex::new(Status { + device_id: device.id.clone(), + device_name: device.name.clone(), + state: "connecting", + live: item.source.live, + volume: 1.0, + ..Default::default() + })); + let _ = app.emit(STATUS_EVENT, status.lock().clone()); + log::info!( + "cast: {} {}:{} to {}", + req.kind, + req.source_id, + req.id, + device.name + ); + let _ = tx.send(Cmd::Load(item)); + let sid = { + let mut n = cast.next_id.lock(); + *n += 1; + *n + }; + *session = Some(Session { + id: sid, + device: device.clone(), + tx: tx.clone(), + status: status.clone(), + }); + drop(session); + let app2 = app.clone(); + tauri::async_runtime::spawn(async move { + run(app2.clone(), device, rx, tx, status).await; + if let Some(cast) = app2.try_state::() { + let mut s = cast.session.lock(); + if s.as_ref().is_some_and(|s| s.id == sid) { + *s = None; + } + } + }); + Ok(()) +} + +/// play | pause | seek (seconds) | volume (0…1) | mute (0/1) +#[tauri::command] +pub fn cast_control(cast: State<'_, Cast>, action: String, value: Option) -> Result<()> { + let v = value.unwrap_or(0.0); + let cmd = match action.as_str() { + "play" => Cmd::Play, + "pause" => Cmd::Pause, + "seek" => Cmd::Seek(v), + "volume" => Cmd::Volume(v), + "mute" => Cmd::Mute(v != 0.0), + other => return Err(Error::msg(format!("unknown cast action {other}"))), + }; + cast.send(cmd) +} + +/// Ends casting (the TV's player closes). +#[tauri::command] +pub fn cast_stop(cast: State<'_, Cast>) -> Result<()> { + cast.stop(); + Ok(()) +} + +/// The running session, if any. +#[tauri::command] +pub fn cast_status(cast: State<'_, Cast>) -> Option { + cast.session + .lock() + .as_ref() + .map(|s| s.status.lock().clone()) + .filter(|s| !s.finished()) +} diff --git a/src-tauri/src/cast/discovery.rs b/src-tauri/src/cast/discovery.rs new file mode 100644 index 0000000..d816be9 --- /dev/null +++ b/src-tauri/src/cast/discovery.rs @@ -0,0 +1,143 @@ +//! Finding TVs: mDNS browsing, the remembered ones, and a sweep of the +//! local networks by address. + +use super::*; + +fn device_from(s: &mdns_sd::ResolvedService) -> Option { + // capabilities bit 0: video out (speakers and speaker groups lack it) + let ca: u32 = s + .get_property_val_str("ca") + .and_then(|c| c.parse().ok()) + .unwrap_or(1); + if ca & 1 == 0 { + return None; + } + let ip = s + .addresses + .iter() + .map(|a| a.to_ip_addr()) + .find(|ip| ip.is_ipv4() && !ip.is_loopback())?; + let id = probe::normalize_id(s.get_property_val_str("id").unwrap_or(&s.fullname)); + let name = s + .get_property_val_str("fn") + .unwrap_or("Chromecast") + .to_owned(); + let model = s.get_property_val_str("md").unwrap_or("").to_owned(); + Some(Device { + id, + name, + model, + addr: SocketAddr::new(ip, s.port), + fullname: s.fullname.clone(), + }) +} + +pub(super) fn start_browsing(app: &AppHandle, cast: &Cast) -> Result<()> { + let mut browser = cast.browser.lock(); + if browser.is_some() { + return Ok(()); + } + let daemon = mdns_sd::ServiceDaemon::new() + .map_err(|e| Error::msg(format!("cannot search the network: {e}")))?; + let events = daemon + .browse(SERVICE) + .map_err(|e| Error::msg(format!("cannot search the network: {e}")))?; + let devices = cast.devices.clone(); + let app = app.clone(); + std::thread::Builder::new() + .name("cast-discovery".into()) + .spawn(move || { + while let Ok(event) = events.recv() { + let changed = match event { + mdns_sd::ServiceEvent::ServiceResolved(s) => { + match (device_from(&s), app.try_state::()) { + (Some(d), Some(cast)) => { + let mut map = devices.lock(); + match map.get_mut(&d.id) { + // found by address first: now it has a service name + Some(old) if old.fullname.is_empty() => { + old.fullname = d.fullname; + old.model = d.model; + false + } + _ => { + drop(map); + cast.found(d) + } + } + } + _ => false, + } + } + mdns_sd::ServiceEvent::ServiceRemoved(_, fullname) => { + let mut map = devices.lock(); + let before = map.len(); + map.retain(|_, d| d.fullname != fullname); + before != map.len() + } + _ => false, + }; + if changed { + emit_devices(&app); + } + } + })?; + *browser = Some(daemon); + Ok(()) +} + +/// Looks for TVs by address: the remembered ones, then (at most once a +/// minute) a sweep of the local networks for the Cast port. +pub(super) fn search(app: &AppHandle, cast: &Cast) { + if cast.searching.swap(true, Ordering::Relaxed) { + return; + } + let sweep = cast + .last_sweep + .lock() + .is_none_or(|t| t.elapsed() > SWEEP_EVERY); + let app = app.clone(); + tauri::async_runtime::spawn(async move { + let Some(st) = app.try_state::().map(|s| s.inner().clone()) else { + return; + }; + let probe_all = |ips: Vec| { + let app = app.clone(); + let http = st.http.clone(); + async move { + let mut tasks = tokio::task::JoinSet::new(); + for ip in ips { + let http = http.clone(); + tasks.spawn(async move { probe::probe(&http, ip).await }); + } + while let Some(r) = tasks.join_next().await { + if let (Ok(Some(d)), Some(cast)) = (r, app.try_state::()) + && cast.found(d) + { + emit_devices(&app); + } + } + } + }; + let known = read_blocking(&st, |conn| Ok(remembered(conn))) + .await + .unwrap_or_default(); + probe_all(known.into_iter().map(|r| r.ip).collect()).await; + if sweep { + let networks = probe::local_networks(); + log::info!( + "cast: checking {} local network(s) for Cast devices", + networks.len() + ); + let open = probe::sweep(&networks).await; + probe_all(open).await; + if let Some(cast) = app.try_state::() { + *cast.last_sweep.lock() = Some(Instant::now()); + } + } + if let Some(cast) = app.try_state::() { + cast.searching.store(false, Ordering::Relaxed); + } + emit_devices(&app); + }); +} diff --git a/src-tauri/src/cast/mod.rs b/src-tauri/src/cast/mod.rs index 6c59955..cd6f821 100644 --- a/src-tauri/src/cast/mod.rs +++ b/src-tauri/src/cast/mod.rs @@ -10,8 +10,15 @@ //! the TV (the frontend sends it here instead of to `play`). pub mod castv2; +mod commands; +mod discovery; mod probe; mod relay; +mod session; + +pub use commands::*; +use discovery::{search, start_browsing}; +use session::run; use std::collections::BTreeMap; use std::net::{IpAddr, SocketAddr}; @@ -28,8 +35,8 @@ use tokio::sync::mpsc; use crate::error::{Error, Result}; use crate::playback::{self, PlayRequest}; use crate::player::Player; -use crate::state::AppState; -use crate::{library, settings}; +use crate::settings; +use crate::state::{AppState, read_blocking, write_blocking}; use castv2::{Message, NS_CONNECTION, NS_HEARTBEAT, NS_MEDIA, NS_RECEIVER, RECEIVER}; pub const DEVICES_EVENT: &str = "cast://devices"; @@ -146,7 +153,9 @@ pub struct Cast { } pub fn init(app: &AppHandle) { - let relay = relay::Relay::start().map_err(|e| log::error!("cast relay unavailable: {e}")).ok(); + let relay = relay::Relay::start() + .map_err(|e| log::error!("cast relay unavailable: {e}")) + .ok(); app.manage(Cast { relay, devices: Arc::default(), @@ -161,7 +170,10 @@ pub fn init(app: &AppHandle) { impl Cast { /// A cast session is running (the provider stream belongs to it). pub fn busy(&self) -> bool { - self.session.lock().as_ref().is_some_and(|s| !s.status.lock().finished()) + self.session + .lock() + .as_ref() + .is_some_and(|s| !s.status.lock().finished()) } /// Ends the session, if one runs. @@ -174,13 +186,17 @@ impl Cast { fn send(&self, cmd: Cmd) -> Result<()> { let guard = self.session.lock(); let s = guard.as_ref().ok_or_else(|| Error::msg("Not casting"))?; - s.tx.send(cmd).map_err(|_| Error::msg("The cast session has ended")) + s.tx.send(cmd) + .map_err(|_| Error::msg("The cast session has ended")) } fn list(&self) -> Devices { let mut v: Vec = self.devices.lock().values().cloned().collect(); v.sort_by_key(|d| d.name.to_lowercase()); - Devices { devices: v, searching: self.searching.load(Ordering::Relaxed) } + Devices { + devices: v, + searching: self.searching.load(Ordering::Relaxed), + } } /// Adds or updates a device; true when the list changed. @@ -210,786 +226,26 @@ fn emit_devices(app: &AppHandle) { } } -fn remembered(st: &AppState) -> Vec { - serde_json::from_value(settings::get(&st.db.read(), REMEMBERED)).unwrap_or_default() +fn remembered(conn: &rusqlite::Connection) -> Vec { + serde_json::from_value(settings::get(conn, REMEMBERED)).unwrap_or_default() } /// Keeps a TV that worked (or was added by hand) for next time. -fn remember(st: &AppState, d: &Device) { - let mut list = remembered(st); - list.retain(|r| r.id != d.id); - list.insert(0, Remembered { id: d.id.clone(), name: d.name.clone(), ip: d.addr.ip() }); - list.truncate(16); - if let Err(e) = settings::put(&st.db.write(), REMEMBERED, &json!(list)) { - log::warn!("cast: cannot remember {}: {e}", d.name); - } -} - -// ------------------------------------------------------------ discovery - -fn device_from(s: &mdns_sd::ResolvedService) -> Option { - // capabilities bit 0: video out (speakers and speaker groups lack it) - let ca: u32 = s.get_property_val_str("ca").and_then(|c| c.parse().ok()).unwrap_or(1); - if ca & 1 == 0 { - return None; - } - let ip = s.addresses.iter().map(|a| a.to_ip_addr()).find(|ip| ip.is_ipv4() && !ip.is_loopback())?; - let id = probe::normalize_id(s.get_property_val_str("id").unwrap_or(&s.fullname)); - let name = s.get_property_val_str("fn").unwrap_or("Chromecast").to_owned(); - let model = s.get_property_val_str("md").unwrap_or("").to_owned(); - Some(Device { id, name, model, addr: SocketAddr::new(ip, s.port), fullname: s.fullname.clone() }) -} - -fn start_browsing(app: &AppHandle, cast: &Cast) -> Result<()> { - let mut browser = cast.browser.lock(); - if browser.is_some() { - return Ok(()); - } - let daemon = mdns_sd::ServiceDaemon::new().map_err(|e| Error::msg(format!("cannot search the network: {e}")))?; - let events = daemon.browse(SERVICE).map_err(|e| Error::msg(format!("cannot search the network: {e}")))?; - let devices = cast.devices.clone(); - let app = app.clone(); - std::thread::Builder::new().name("cast-discovery".into()).spawn(move || { - while let Ok(event) = events.recv() { - let changed = match event { - mdns_sd::ServiceEvent::ServiceResolved(s) => match (device_from(&s), app.try_state::()) { - (Some(d), Some(cast)) => { - let mut map = devices.lock(); - match map.get_mut(&d.id) { - // found by address first: now it has a service name - Some(old) if old.fullname.is_empty() => { - old.fullname = d.fullname; - old.model = d.model; - false - } - _ => { - drop(map); - cast.found(d) - } - } - } - _ => false, - }, - mdns_sd::ServiceEvent::ServiceRemoved(_, fullname) => { - let mut map = devices.lock(); - let before = map.len(); - map.retain(|_, d| d.fullname != fullname); - before != map.len() - } - _ => false, - }; - if changed { - emit_devices(&app); - } - } - })?; - *browser = Some(daemon); - Ok(()) -} - -/// Looks for TVs by address: the remembered ones, then (at most once a -/// minute) a sweep of the local networks for the Cast port. -fn search(app: &AppHandle, cast: &Cast) { - if cast.searching.swap(true, Ordering::Relaxed) { - return; - } - let sweep = cast.last_sweep.lock().is_none_or(|t| t.elapsed() > SWEEP_EVERY); - let app = app.clone(); - tauri::async_runtime::spawn(async move { - let Some(st) = app.try_state::().map(|s| s.inner().clone()) else { return }; - let probe_all = |ips: Vec| { - let app = app.clone(); - let http = st.http.clone(); - async move { - let mut tasks = tokio::task::JoinSet::new(); - for ip in ips { - let http = http.clone(); - tasks.spawn(async move { probe::probe(&http, ip).await }); - } - while let Some(r) = tasks.join_next().await { - if let (Ok(Some(d)), Some(cast)) = (r, app.try_state::()) - && cast.found(d) - { - emit_devices(&app); - } - } - } - }; - probe_all(remembered(&st).into_iter().map(|r| r.ip).collect()).await; - if sweep { - let networks = probe::local_networks(); - log::info!("cast: checking {} local network(s) for Cast devices", networks.len()); - let open = probe::sweep(&networks).await; - probe_all(open).await; - if let Some(cast) = app.try_state::() { - *cast.last_sweep.lock() = Some(Instant::now()); - } - } - if let Some(cast) = app.try_state::() { - cast.searching.store(false, Ordering::Relaxed); - } - emit_devices(&app); - }); -} - -// ------------------------------------------------------------ session - -struct Current { - generation: u64, - token: String, - /// URL number: every (re)load of the item is a new one - n: u32, - live: bool, - meta: Meta, - /// item position at the start of URL `n` - offset: f64, - duration: f64, - loaded_at: Instant, - /// the relay answered for URL `n` - started: bool, - paused_at: Option, - /// live streams that ended are reloaded a few times - reloads: u32, -} - -struct Conn { - app: AppHandle, - device: Device, - w: castv2::Writer, - local: IpAddr, - tx: mpsc::UnboundedSender, - request_id: u64, - transport: Option, - app_session: Option, - media_session: Option, - generation: u64, - current: Option, - queued: Option>, - /// receiver time of the last media status - media_time: f64, - status: Arc>, -} - -enum Flow { - Continue, - End, -} - -impl Conn { - fn next_id(&mut self) -> u64 { - self.request_id += 1; - self.request_id - } - - async fn send(&mut self, destination: &str, namespace: &str, payload: Value) -> std::io::Result<()> { - self.w.send(&Message::new(destination, namespace, payload.to_string())).await - } - - async fn request(&mut self, destination: &str, namespace: &str, mut payload: Value) -> std::io::Result<()> { - payload["requestId"] = json!(self.next_id()); - self.send(destination, namespace, payload).await - } - - async fn media(&mut self, kind: &str) -> std::io::Result<()> { - let (Some(transport), Some(media)) = (self.transport.clone(), self.media_session) else { return Ok(()) }; - self.request(&transport, NS_MEDIA, json!({"type": kind, "mediaSessionId": media})).await - } - - fn update(&self, f: impl FnOnce(&mut Status)) { - let mut s = self.status.lock(); - let before = s.clone(); - f(&mut s); - if *s != before { - let _ = self.app.emit(STATUS_EVENT, s.clone()); - } - } - - /// Publishes a new item on the relay and loads it. - async fn load_item(&mut self, item: Box) -> std::io::Result<()> { - let app = self.app.clone(); - let Some(cast) = app.try_state::() else { return Ok(()) }; - let Some(relay) = cast.relay.as_ref() else { return Ok(()) }; - if let Some(old) = self.current.take() { - relay.unpublish(&old.token); - } - self.generation += 1; - let generation = self.generation; - let tx = self.tx.clone(); - let live = item.source.live; - let on_start: relay::OnStart = Arc::new(move |n, s| { - let _ = tx.send(Cmd::Started(generation, n, s)); - }); - let token = relay.publish(item.source, self.device.addr.ip(), on_start); - let _ = &cast; // the app borrow ends with this statement - self.current = Some(Current { - generation, - token, - n: 0, - live, - meta: item.meta, - offset: 0.0, - duration: 0.0, - loaded_at: Instant::now(), - started: false, - paused_at: None, - reloads: 0, - }); - self.update(|s| { - s.live = live; - s.duration = 0.0; - s.error = None; - }); - self.load_at(item.start).await - } - - /// (Re)loads the current item from `start` seconds under a new URL. - async fn load_at(&mut self, start: f64) -> std::io::Result<()> { - let Some(transport) = self.transport.clone() else { return Ok(()) }; - let app = self.app.clone(); - let Some(cast) = app.try_state::() else { return Ok(()) }; - let Some(relay) = cast.relay.as_ref() else { return Ok(()) }; - let Some(cur) = self.current.as_mut() else { return Ok(()) }; - cur.n += 1; - let start = if cur.live { 0.0 } else { start.max(0.0) }; - relay.position(&cur.token, cur.n, start); - let url = relay.url(self.local, &cur.token, cur.n); - cur.offset = start; - cur.loaded_at = Instant::now(); - cur.started = false; - cur.paused_at = None; - let mut metadata = json!({"metadataType": 0, "title": cur.meta.title.clone().unwrap_or_default()}); - if let Some(sub) = cur.meta.subtitle.clone().filter(|s| !s.is_empty()) { - metadata["subtitle"] = json!(sub); - } - if let Some(img) = cur.meta.image.clone().filter(|u| u.starts_with("http://") || u.starts_with("https://")) { - metadata["images"] = json!([{ "url": img }]); - } - let payload = json!({ - "type": "LOAD", - "sessionId": self.app_session, - "autoplay": true, - "currentTime": 0, - "media": { - "contentId": url, - "contentUrl": url, - "contentType": "video/mp4", - "streamType": if cur.live { "LIVE" } else { "BUFFERED" }, - "metadata": metadata, - }, - }); - let _ = &cast; - self.media_time = 0.0; - self.update(|s| { - s.state = "loading"; - s.position = start; - }); - self.request(&transport, NS_MEDIA, payload).await - } - - fn position(&self) -> f64 { - let Some(cur) = &self.current else { return 0.0 }; - let p = cur.offset + self.media_time; - if cur.duration > 0.0 { p.min(cur.duration) } else { p } - } - - fn relay_error(&self) -> Option { - let cur = self.current.as_ref()?; - self.app.try_state::()?.relay.as_ref()?.error(&cur.token) - } - - async fn on_message(&mut self, m: Message) -> std::io::Result { - let p: Value = serde_json::from_str(&m.payload).unwrap_or(Value::Null); - let kind = p["type"].as_str().unwrap_or(""); - match (m.namespace.as_str(), kind) { - (NS_HEARTBEAT, "PING") => { - self.send(&m.source, NS_HEARTBEAT, json!({"type": "PONG"})).await?; - } - (NS_CONNECTION, "CLOSE") if Some(&m.source) == self.transport.as_ref() => { - self.update(|s| { - s.state = "stopped"; - s.error = None; - }); - return Ok(Flow::End); - } - (NS_RECEIVER, "RECEIVER_STATUS") => { - let st = &p["status"]; - if let Some(level) = st["volume"]["level"].as_f64() { - let muted = st["volume"]["muted"].as_bool().unwrap_or(false); - self.update(|s| { - s.volume = level; - s.muted = muted; - }); - } - let ours = st["applications"].as_array().and_then(|apps| { - apps.iter().find(|a| a["appId"].as_str() == Some(DEFAULT_RECEIVER)).map(|a| { - (a["transportId"].as_str().unwrap_or("").to_owned(), a["sessionId"].as_str().unwrap_or("").to_owned()) - }) - }); - match (ours, &self.transport) { - (Some((transport, session)), None) if !transport.is_empty() => { - self.send(&transport, NS_CONNECTION, json!({"type": "CONNECT"})).await?; - self.transport = Some(transport); - self.app_session = Some(session); - if let Some(item) = self.queued.take() { - self.load_item(item).await?; - } - } - // another app took over the TV, or the remote closed ours - (None, Some(_)) => { - self.update(|s| { - s.state = "stopped"; - s.error = None; - }); - return Ok(Flow::End); - } - _ => {} - } - } - (NS_RECEIVER, "LAUNCH_ERROR") => { - self.update(|s| { - s.state = "stopped"; - s.error = Some("The TV could not start its media player".into()); - }); - return Ok(Flow::End); - } - (NS_MEDIA, "MEDIA_STATUS") => { - if let Some(ms) = p["status"].as_array().and_then(|a| a.first()) { - return self.on_media_status(ms.clone()).await; - } - } - (NS_MEDIA, "LOAD_FAILED" | "INVALID_REQUEST") => { - let error = self.relay_error().unwrap_or_else(|| "The TV could not play this stream".into()); - self.update(|s| { - s.state = "error"; - s.error = Some(error); - }); - } - _ => {} - } - Ok(Flow::Continue) - } - - async fn on_media_status(&mut self, ms: Value) -> std::io::Result { - if let Some(id) = ms["mediaSessionId"].as_i64() { - self.media_session = Some(id); - } - if let Some(t) = ms["currentTime"].as_f64() { - self.media_time = t; - } - let state = ms["playerState"].as_str().unwrap_or(""); - let reason = ms["idleReason"].as_str().unwrap_or(""); - let position = self.position(); - let live = self.current.as_ref().is_some_and(|c| c.live); - match (state, reason) { - ("PLAYING", _) => { - if let Some(c) = self.current.as_mut() { - c.paused_at = None; - } - self.update(|s| { - s.state = "playing"; - s.position = position; - s.error = None; - }); - } - ("PAUSED", _) => { - if let Some(c) = self.current.as_mut() { - c.paused_at.get_or_insert_with(Instant::now); - } - self.update(|s| { - s.state = "paused"; - s.position = position; - }); - } - ("BUFFERING", _) => self.update(|s| { - s.state = "buffering"; - s.position = position; - }), - ("IDLE", "FINISHED" | "CANCELLED") if live => { - // the channel's stream dropped: tune in again a few times - let retry = self.current.as_mut().map(|c| { - c.reloads += 1; - c.reloads <= 3 - }); - if retry == Some(true) { - self.load_at(0.0).await?; - } else { - // a stream that ended without an error of its own (e.g. a - // file, or a receiver that closed early) is still "playing" - let error = self.relay_error(); - self.update(|s| match error { - Some(e) => { - s.state = "error"; - s.error = Some(e); - } - None => { - s.state = "playing"; - s.error = None; - } - }); - } - } - ("IDLE", "FINISHED") => self.update(|s| { - s.state = "ended"; - s.position = s.duration.max(position); - }), - ("IDLE", "ERROR") => { - let error = self.relay_error().unwrap_or_else(|| "The TV could not play this stream".into()); - self.update(|s| { - s.state = "error"; - s.error = Some(error); - }); - } - _ => {} - } - Ok(Flow::Continue) - } - - async fn on_cmd(&mut self, cmd: Cmd) -> std::io::Result { - match cmd { - Cmd::Load(item) => { - if self.transport.is_some() { - self.load_item(item).await?; - } else { - self.queued = Some(item); - } - } - Cmd::Play => { - let stale = self - .current - .as_ref() - .is_some_and(|c| c.live && c.paused_at.is_some_and(|t| t.elapsed() > LIVE_PAUSE_LIMIT)); - let ended = self.status.lock().state == "ended"; - if stale || ended { - // live: back to "now"; VOD at the end: from the start - self.load_at(0.0).await?; - } else { - self.media("PLAY").await?; - } - } - Cmd::Pause => self.media("PAUSE").await?, - Cmd::Seek(t) => { - let Some(cur) = &self.current else { return Ok(Flow::Continue) }; - if !cur.live { - let end = if cur.duration > 0.0 { (cur.duration - 1.0).max(0.0) } else { f64::MAX }; - self.load_at(t.clamp(0.0, end)).await?; - } - } - Cmd::Volume(level) => { - self.request(RECEIVER, NS_RECEIVER, json!({"type": "SET_VOLUME", "volume": {"level": level.clamp(0.0, 1.0)}})) - .await?; - self.update(|s| s.volume = level.clamp(0.0, 1.0)); - } - Cmd::Mute(muted) => { - self.request(RECEIVER, NS_RECEIVER, json!({"type": "SET_VOLUME", "volume": {"muted": muted}})).await?; - self.update(|s| s.muted = muted); - } - Cmd::Stop => { - if let Some(session) = self.app_session.clone() { - let _ = self.request(RECEIVER, NS_RECEIVER, json!({"type": "STOP", "sessionId": session})).await; - } - self.update(|s| { - s.state = "stopped"; - s.error = None; - }); - return Ok(Flow::End); - } - Cmd::Started(generation, n, started) => { - if let Some(cur) = self.current.as_mut().filter(|c| c.generation == generation && c.n == n) { - cur.started = true; - cur.offset = started.first; - if started.duration > 0.0 { - cur.duration = started.duration; - } - let (duration, position) = (cur.duration, self.position()); - self.update(|s| { - s.duration = duration; - s.position = position; - }); - } - } - } - Ok(Flow::Continue) - } - - async fn on_tick(&mut self) -> std::io::Result { - let state = self.status.lock().state; - if matches!(state, "playing" | "buffering") { - self.media("GET_STATUS").await?; - } - let unreachable = self.current.as_ref().is_some_and(|c| { - !c.started && state == "loading" && c.loaded_at.elapsed() > UNREACHABLE_AFTER - }); - if unreachable { - let error = self.relay_error().unwrap_or_else(|| { - "The TV can't reach this computer. Make sure both are on the same network and no firewall blocks \ - incoming connections." - .into() - }); - self.update(|s| { - s.state = "error"; - s.error = Some(error); - }); - if let Some(c) = self.current.as_mut() { - c.started = true; // report once - } - } - Ok(Flow::Continue) - } -} - -async fn run( - app: AppHandle, - device: Device, - mut rx: mpsc::UnboundedReceiver, - tx: mpsc::UnboundedSender, - status: Arc>, -) { - let emit = |s: &Status| { - let _ = app.emit(STATUS_EVENT, s.clone()); - }; - let (mut reader, writer, local) = match castv2::connect(device.addr).await { - Ok(c) => c, - Err(e) => { - log::warn!("cast: cannot connect to {} at {}: {e}", device.name, device.addr); - let mut s = status.lock(); - s.state = "stopped"; - s.error = Some(format!("Can't connect to {}", device.name)); - emit(&s); - return; - } - }; - log::info!("cast: connected to {} at {}", device.name, device.addr); - if let Some(st) = app.try_state::() { - remember(st.inner(), &device); - } - let mut c = Conn { - app: app.clone(), - device, - w: writer, - local, - tx, - request_id: 0, - transport: None, - app_session: None, - media_session: None, - generation: 0, - current: None, - queued: None, - media_time: 0.0, - status, - }; - let setup = async { - c.send(RECEIVER, NS_CONNECTION, json!({"type": "CONNECT"})).await?; - c.request(RECEIVER, NS_RECEIVER, json!({"type": "LAUNCH", "appId": DEFAULT_RECEIVER})).await - }; - let mut result = setup.await; - - let mut heartbeat = tokio::time::interval(Duration::from_secs(5)); - let mut tick = tokio::time::interval(Duration::from_secs(1)); - let mut last_heard = Instant::now(); - while result.is_ok() { - let flow = tokio::select! { - m = reader.next() => match m { - Ok(m) => { - last_heard = Instant::now(); - c.on_message(m).await - } - Err(e) => Err(e), - }, - cmd = rx.recv() => match cmd { - Some(cmd) => c.on_cmd(cmd).await, - None => Ok(Flow::End), - }, - _ = heartbeat.tick() => { - if last_heard.elapsed() > Duration::from_secs(20) { - Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "the TV stopped answering")) - } else { - c.send(RECEIVER, NS_HEARTBEAT, json!({"type": "PING"})).await.map(|_| Flow::Continue) - } - } - _ = tick.tick() => c.on_tick().await, - }; - match flow { - Ok(Flow::Continue) => {} - Ok(Flow::End) => break, - Err(e) => result = Err(e), - } - } - if let Err(e) = result { - log::warn!("cast: connection to {} lost: {e}", c.device.name); - c.update(|s| { - if !s.finished() { - s.state = "stopped"; - s.error = Some(format!("Lost the connection to {}", c.device.name)); - } - }); - } - if let Some(cur) = c.current.take() - && let Some(relay) = app.try_state::().as_ref().and_then(|cast| cast.relay.as_ref()) - { - relay.unpublish(&cur.token); - } - if let Some(transport) = c.transport.clone() { - let _ = c.send(&transport, NS_CONNECTION, json!({"type": "CLOSE"})).await; - } - let _ = c.send(RECEIVER, NS_CONNECTION, json!({"type": "CLOSE"})).await; - log::info!("cast: session with {} ended", c.device.name); -} - -// ------------------------------------------------------------ commands - -/// The cast devices found so far; the first call starts looking -/// (updates follow as `cast://devices`). -#[tauri::command] -pub fn cast_devices(app: AppHandle, cast: State<'_, Cast>) -> Result { - if cast.relay.is_none() { - return Err(Error::msg("Casting is unavailable: no network port could be opened")); - } - // mDNS is optional: the search by address finds TVs without it - if let Err(e) = start_browsing(&app, &cast) { - log::warn!("cast: {e}"); - } - search(&app, &cast); - Ok(cast.list()) -} - -/// Adds a TV by its IP address (for networks where it can't be found). -#[tauri::command] -pub async fn cast_add_device( - app: AppHandle, - state: State<'_, AppState>, - cast: State<'_, Cast>, - address: String, -) -> Result { - let ip = probe::parse_address(&address) - .ok_or_else(|| Error::msg("Enter the TV's IP address, like 192.168.1.20"))?; - let device = probe::probe(&state.http, ip) - .await - .ok_or_else(|| Error::msg(format!("No Chromecast answered at {ip}. Check the address in the Google Home app.")))?; - remember(state.inner(), &device); - if cast.found(device.clone()) { - emit_devices(&app); - } - Ok(device) -} - -/// Plays `req` on a TV: on `device_id` (starting a session there), or on the -/// TV already being cast to. Local playback stops — the account streams to -/// one place. -#[tauri::command] -pub async fn cast_play( - app: AppHandle, - state: State<'_, AppState>, - player: State<'_, Player>, - cast: State<'_, Cast>, - device_id: Option, - req: PlayRequest, - meta: Option, -) -> Result<()> { - let st = state.inner().clone(); - let (stream, audio_lang) = { - let conn = st.db.read(); - (playback::resolve(&conn, &req)?, settings::get_str(&conn, "player.audioLang")) - }; - if let Some((title, logo)) = stream.channel.clone() { - library::touch_channel(&st.db.write(), req.source_id, &req.id, &title, logo.as_deref())?; - } - if crate::probe::running() { - tokio::task::spawn_blocking(crate::probe::cancel).await.map_err(|e| Error::msg(e.to_string()))?; - } - let _ = player.stop(); - - let mut urls = vec![stream.url]; - urls.extend(stream.alternates); - let mut meta = meta.unwrap_or_default(); - meta.title = meta.title.or(req.title.clone()); - let item = Box::new(Item { - source: relay::Source { - urls, - user_agent: stream.user_agent, - referrer: stream.referrer, - live: stream.live, - audio_lang, - }, - meta, - start: req.start.unwrap_or(0.0), - }); - - let mut session = cast.session.lock(); - let running = session.as_ref().filter(|s| !s.status.lock().finished()); - let reuse = match (&device_id, running) { - (None, Some(_)) => true, - (Some(id), Some(s)) => &s.device.id == id, - (None, None) => return Err(Error::msg("Not casting")), - (Some(_), None) => false, +async fn remember(st: &AppState, d: &Device) { + let entry = Remembered { + id: d.id.clone(), + name: d.name.clone(), + ip: d.addr.ip(), }; - if reuse { - let s = session.as_ref().expect("running session"); - log::info!("cast: {} {}:{} to {}", req.kind, req.source_id, req.id, s.device.name); - return s.tx.send(Cmd::Load(item)).map_err(|_| Error::msg("The cast session has ended")); - } - - let id = device_id.unwrap_or_default(); - let device = cast.devices.lock().get(&id).cloned().ok_or_else(|| Error::msg("That TV is no longer on the network"))?; - if let Some(old) = session.take() { - let _ = old.tx.send(Cmd::Stop); + let saved = write_blocking(st, move |conn| { + let mut list = remembered(conn); + list.retain(|r| r.id != entry.id); + list.insert(0, entry); + list.truncate(16); + settings::put(conn, REMEMBERED, &json!(list)) + }) + .await; + if let Err(e) = saved { + log::warn!("cast: cannot remember {}: {e}", d.name); } - let (tx, rx) = mpsc::unbounded_channel(); - let status = Arc::new(Mutex::new(Status { - device_id: device.id.clone(), - device_name: device.name.clone(), - state: "connecting", - live: item.source.live, - volume: 1.0, - ..Default::default() - })); - let _ = app.emit(STATUS_EVENT, status.lock().clone()); - log::info!("cast: {} {}:{} to {}", req.kind, req.source_id, req.id, device.name); - let _ = tx.send(Cmd::Load(item)); - let sid = { - let mut n = cast.next_id.lock(); - *n += 1; - *n - }; - *session = Some(Session { id: sid, device: device.clone(), tx: tx.clone(), status: status.clone() }); - drop(session); - let app2 = app.clone(); - tauri::async_runtime::spawn(async move { - run(app2.clone(), device, rx, tx, status).await; - if let Some(cast) = app2.try_state::() { - let mut s = cast.session.lock(); - if s.as_ref().is_some_and(|s| s.id == sid) { - *s = None; - } - } - }); - Ok(()) -} - -/// play | pause | seek (seconds) | volume (0…1) | mute (0/1) -#[tauri::command] -pub fn cast_control(cast: State<'_, Cast>, action: String, value: Option) -> Result<()> { - let v = value.unwrap_or(0.0); - let cmd = match action.as_str() { - "play" => Cmd::Play, - "pause" => Cmd::Pause, - "seek" => Cmd::Seek(v), - "volume" => Cmd::Volume(v), - "mute" => Cmd::Mute(v != 0.0), - other => return Err(Error::msg(format!("unknown cast action {other}"))), - }; - cast.send(cmd) -} - -/// Ends casting (the TV's player closes). -#[tauri::command] -pub fn cast_stop(cast: State<'_, Cast>) -> Result<()> { - cast.stop(); - Ok(()) -} - -/// The running session, if any. -#[tauri::command] -pub fn cast_status(cast: State<'_, Cast>) -> Option { - cast.session.lock().as_ref().map(|s| s.status.lock().clone()).filter(|s| !s.finished()) } diff --git a/src-tauri/src/cast/probe.rs b/src-tauri/src/cast/probe.rs index 611e194..5b54e36 100644 --- a/src-tauri/src/cast/probe.rs +++ b/src-tauri/src/cast/probe.rs @@ -27,17 +27,38 @@ struct EurekaInfo { /// mDNS TXT `id` and eureka `ssdp_udn` name the same device: one key for both. pub fn normalize_id(id: &str) -> String { - id.chars().filter(|c| c.is_ascii_hexdigit()).collect::().to_lowercase() + id.chars() + .filter(|c| c.is_ascii_hexdigit()) + .collect::() + .to_lowercase() } /// Asks `ip` whether it is a Cast device; its name and id if so. pub async fn probe(http: &reqwest::Client, ip: IpAddr) -> Option { - let url = format!("http://{}/setup/eureka_info?params=name,device_info", SocketAddr::new(ip, SETUP_PORT)); - let info: EurekaInfo = http.get(url).timeout(Duration::from_secs(3)).send().await.ok()?.json().await.ok()?; - let id = info.ssdp_udn.or(info.mac_address).map(|i| normalize_id(&i)).filter(|i| !i.is_empty())?; + let url = format!( + "http://{}/setup/eureka_info?params=name,device_info", + SocketAddr::new(ip, SETUP_PORT) + ); + let info: EurekaInfo = http + .get(url) + .timeout(Duration::from_secs(3)) + .send() + .await + .ok()? + .json() + .await + .ok()?; + let id = info + .ssdp_udn + .or(info.mac_address) + .map(|i| normalize_id(&i)) + .filter(|i| !i.is_empty())?; Some(Device { id, - name: info.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| format!("Chromecast ({ip})")), + name: info + .name + .filter(|n| !n.trim().is_empty()) + .unwrap_or_else(|| format!("Chromecast ({ip})")), // eureka_info doesn't say; a device that answers is a Cast device model: String::new(), addr: SocketAddr::new(ip, CAST_PORT), @@ -48,7 +69,9 @@ pub async fn probe(http: &reqwest::Client, ip: IpAddr) -> Option { /// This computer's private IPv4 networks of at most 256 addresses (larger /// ones would take too long to sweep; "Add by address" covers them). pub fn local_networks() -> Vec<(Ipv4Addr, u8)> { - let Ok(ifaces) = if_addrs::get_if_addrs() else { return Vec::new() }; + let Ok(ifaces) = if_addrs::get_if_addrs() else { + return Vec::new(); + }; let mut out: Vec<(Ipv4Addr, u8)> = ifaces .into_iter() .filter(|i| !i.is_loopback()) @@ -68,7 +91,10 @@ pub fn hosts(ip: Ipv4Addr, prefix: u8) -> Vec { let mask = u32::MAX << (32 - prefix); let net = u32::from(ip) & mask; let broadcast = net | !mask; - (net + 1..broadcast).map(Ipv4Addr::from).filter(|h| *h != ip).collect() + (net + 1..broadcast) + .map(Ipv4Addr::from) + .filter(|h| *h != ip) + .collect() } /// Addresses on `networks` with the Cast port open (a ~1 s parallel sweep). @@ -78,9 +104,12 @@ pub async fn sweep(networks: &[(Ipv4Addr, u8)]) -> Vec { for host in hosts(ip, prefix) { tasks.spawn(async move { let addr = SocketAddr::new(IpAddr::V4(host), CAST_PORT); - let open = tokio::time::timeout(Duration::from_millis(900), tokio::net::TcpStream::connect(addr)) - .await - .is_ok_and(|c| c.is_ok()); + let open = tokio::time::timeout( + Duration::from_millis(900), + tokio::net::TcpStream::connect(addr), + ) + .await + .is_ok_and(|c| c.is_ok()); open.then_some(IpAddr::V4(host)) }); } @@ -99,7 +128,10 @@ pub async fn sweep(networks: &[(Ipv4Addr, u8)]) -> Vec { pub fn parse_address(input: &str) -> Option { let s = input.trim(); let host = s.strip_suffix(&format!(":{CAST_PORT}")).unwrap_or(s); - host.parse::().ok().filter(|ip| !ip.is_loopback() && !ip.is_unspecified()).map(IpAddr::V4) + host.parse::() + .ok() + .filter(|ip| !ip.is_loopback() && !ip.is_unspecified()) + .map(IpAddr::V4) } #[cfg(test)] @@ -109,7 +141,10 @@ mod tests { #[test] fn mdns_and_setup_ids_match() { // mDNS TXT id vs. eureka_info ssdp_udn of the same Chromecast - assert_eq!(normalize_id("ce33bf0d7d2ab19d3115eca1c2a3b577"), normalize_id("ce33bf0d-7d2a-b19d-3115-eca1c2a3b577")); + assert_eq!( + normalize_id("ce33bf0d7d2ab19d3115eca1c2a3b577"), + normalize_id("ce33bf0d-7d2a-b19d-3115-eca1c2a3b577") + ); assert_eq!(normalize_id("B0:2A:43:3D:1D:DC"), "b02a433d1ddc"); } @@ -126,8 +161,14 @@ mod tests { #[test] fn parses_typed_addresses() { - assert_eq!(parse_address(" 192.168.8.17 "), Some("192.168.8.17".parse().unwrap())); - assert_eq!(parse_address("192.168.8.17:8009"), Some("192.168.8.17".parse().unwrap())); + assert_eq!( + parse_address(" 192.168.8.17 "), + Some("192.168.8.17".parse().unwrap()) + ); + assert_eq!( + parse_address("192.168.8.17:8009"), + Some("192.168.8.17".parse().unwrap()) + ); assert_eq!(parse_address("127.0.0.1"), None); assert_eq!(parse_address("tv.local"), None); assert_eq!(parse_address("192.168.8"), None); diff --git a/src-tauri/src/cast/relay.rs b/src-tauri/src/cast/relay.rs index 83b23ca..a5f3e5e 100644 --- a/src-tauri/src/cast/relay.rs +++ b/src-tauri/src/cast/relay.rs @@ -19,6 +19,14 @@ use std::time::Duration; use parking_lot::Mutex; +/// How long the device gets to send its request. +const READ_TIMEOUT: Duration = Duration::from_secs(10); +/// A device that stops reading this long has gone; ends the stream. +const WRITE_TIMEOUT: Duration = Duration::from_secs(30); +/// Pause before a second round of the stream and its mirrors, for an +/// account whose previous provider connection is still closing. +const RETRY_PAUSE: Duration = Duration::from_millis(1500); + #[repr(C)] struct TpRemux { url: *const c_char, @@ -92,16 +100,20 @@ impl Relay { let port = listener.local_addr()?.port(); let shared: Arc> = Arc::default(); let accept = shared.clone(); - std::thread::Builder::new().name("cast-relay".into()).spawn(move || { - for conn in listener.incoming().flatten() { - let shared = accept.clone(); - let _ = std::thread::Builder::new().name("cast-stream".into()).spawn(move || { - if let Err(e) = serve(conn, &shared) { - log::debug!("cast relay: {e}"); - } - }); - } - })?; + std::thread::Builder::new() + .name("cast-relay".into()) + .spawn(move || { + for conn in listener.incoming().flatten() { + let shared = accept.clone(); + let _ = std::thread::Builder::new() + .name("cast-stream".into()) + .spawn(move || { + if let Err(e) = serve(conn, &shared) { + log::debug!("cast relay: {e}"); + } + }); + } + })?; log::info!("cast relay listening on port {port}"); Ok(Relay { port, shared }) } @@ -115,7 +127,14 @@ impl Relay { } s.entries.insert( token.clone(), - Entry { source, peer, starts: HashMap::new(), active: None, on_start, error: None }, + Entry { + source, + peer, + starts: HashMap::new(), + active: None, + on_start, + error: None, + }, ); token } @@ -130,7 +149,11 @@ impl Relay { /// Why the last request of `token` failed, if it did. pub fn error(&self, token: &str) -> Option { - self.shared.lock().entries.get(token).and_then(|e| e.error.clone()) + self.shared + .lock() + .entries + .get(token) + .and_then(|e| e.error.clone()) } pub fn unpublish(&self, token: &str) { @@ -140,7 +163,10 @@ impl Relay { } pub fn url(&self, local: IpAddr, token: &str, n: u32) -> String { - format!("http://{}/cast/{token}/{n}.mp4", SocketAddr::new(local, self.port)) + format!( + "http://{}/cast/{token}/{n}.mp4", + SocketAddr::new(local, self.port) + ) } } @@ -165,7 +191,10 @@ fn parse_path(path: &str) -> Option<(&str, u32)> { } fn respond(conn: &mut TcpStream, status: &str) -> std::io::Result<()> { - write!(conn, "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + write!( + conn, + "HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) } /// An endless stream: no length, no ranges. @@ -173,7 +202,7 @@ const STREAM_HEADERS: &str = "HTTP/1.1 200 OK\r\nContent-Type: video/mp4\r\nAcce Cache-Control: no-store\r\nConnection: close\r\n\r\n"; fn serve(mut conn: TcpStream, shared: &Mutex) -> std::io::Result<()> { - conn.set_read_timeout(Some(Duration::from_secs(10)))?; + conn.set_read_timeout(Some(READ_TIMEOUT))?; let peer = conn.peer_addr()?.ip(); let mut reader = BufReader::new(conn.try_clone()?); let mut request = String::new(); @@ -189,32 +218,56 @@ fn serve(mut conn: TcpStream, shared: &Mutex) -> std::io::Result<()> { if method != "GET" && method != "HEAD" { return respond(&mut conn, "405 Method Not Allowed"); } - let Some((token, n)) = parse_path(path) else { return respond(&mut conn, "404 Not Found") }; + let Some((token, n)) = parse_path(path) else { + return respond(&mut conn, "404 Not Found"); + }; if method == "HEAD" { - let known = shared.lock().entries.get(token).is_some_and(|e| e.peer == peer || peer.is_loopback()); - return if known { conn.write_all(STREAM_HEADERS.as_bytes()) } else { respond(&mut conn, "404 Not Found") }; + let known = shared + .lock() + .entries + .get(token) + .is_some_and(|e| e.peer == peer || peer.is_loopback()); + return if known { + conn.write_all(STREAM_HEADERS.as_bytes()) + } else { + respond(&mut conn, "404 Not Found") + }; } let job = { let mut s = shared.lock(); - s.entries.get_mut(token).filter(|e| e.peer == peer || peer.is_loopback()).map(|e| { - // one provider connection at a time - stop(e); - let flag = Arc::new(AtomicBool::new(false)); - e.active = Some(flag.clone()); - (e.source.clone(), e.starts.get(&n).copied().unwrap_or(0.0), flag, e.on_start.clone()) - }) + s.entries + .get_mut(token) + .filter(|e| e.peer == peer || peer.is_loopback()) + .map(|e| { + // one provider connection at a time + stop(e); + let flag = Arc::new(AtomicBool::new(false)); + e.active = Some(flag.clone()); + ( + e.source.clone(), + e.starts.get(&n).copied().unwrap_or(0.0), + flag, + e.on_start.clone(), + ) + }) + }; + let Some((source, start, flag, on_start)) = job else { + return respond(&mut conn, "404 Not Found"); }; - let Some((source, start, flag, on_start)) = job else { return respond(&mut conn, "404 Not Found") }; - conn.set_write_timeout(Some(Duration::from_secs(30)))?; + conn.set_write_timeout(Some(WRITE_TIMEOUT))?; log::info!("cast relay: stream #{n} from {start:.1} s to {peer}"); - let mut sink = Sink { conn, sent: false, stop: flag, on_start: Some(Box::new(move |s| on_start(n, s))) }; + let mut sink = Sink { + conn, + sent: false, + stop: flag, + on_start: Some(Box::new(move |s| on_start(n, s))), + }; let mut result = Err(String::new()); - // the stream, then its mirrors; a second round after a pause, for an - // account whose previous connection is still closing + // the stream, then its mirrors; a second round after `RETRY_PAUSE` 'rounds: for round in 0..2 { if round > 0 { - std::thread::sleep(Duration::from_millis(1500)); + std::thread::sleep(RETRY_PAUSE); } for url in &source.urls { if sink.stop.load(Ordering::Relaxed) { @@ -229,7 +282,10 @@ fn serve(mut conn: TcpStream, shared: &Mutex) -> std::io::Result<()> { } let stopped = sink.stop.load(Ordering::Relaxed); match result { - Ok(()) => log::info!("cast relay: stream #{n} {}", if stopped { "stopped" } else { "ended" }), + Ok(()) => log::info!( + "cast relay: stream #{n} {}", + if stopped { "stopped" } else { "ended" } + ), Err(_) if stopped => log::info!("cast relay: stream #{n} stopped"), Err(e) => { let e = crate::player::redact(&e); @@ -253,8 +309,16 @@ struct Sink { on_start: Option>, } +// The three callbacks run on the thread inside `tp_remux_run`, which +// `run_remux` blocks on; `opaque` is its `&mut Sink`, exclusively borrowed +// for the whole call, and remux.c never calls them concurrently. + extern "C" fn sink_write(opaque: *mut c_void, buf: *const u8, len: c_int) -> c_int { + // SAFETY: `opaque` is the `&mut Sink` `run_remux` lent to this call (see + // above); no other reference to it is live while the callback runs. let sink = unsafe { &mut *(opaque as *mut Sink) }; + // SAFETY: FFmpeg's AVIO write callback passes `len` initialized bytes at + // `buf`, valid for the duration of the call. let data = unsafe { std::slice::from_raw_parts(buf, len.max(0) as usize) }; if sink.stop.load(Ordering::Relaxed) { return -1; @@ -265,15 +329,23 @@ extern "C" fn sink_write(opaque: *mut c_void, buf: *const u8, len: c_int) -> c_i return -1; } } - if sink.conn.write_all(data).is_err() { -1 } else { 0 } + if sink.conn.write_all(data).is_err() { + -1 + } else { + 0 + } } extern "C" fn sink_aborted(opaque: *mut c_void) -> c_int { + // SAFETY: `opaque` is the `&mut Sink` `run_remux` lent to this call (see + // above), read here only. let sink = unsafe { &*(opaque as *const Sink) }; sink.stop.load(Ordering::Relaxed) as c_int } extern "C" fn sink_started(opaque: *mut c_void, duration: f64, first: f64) { + // SAFETY: `opaque` is the `&mut Sink` `run_remux` lent to this call (see + // above); no other reference to it is live while the callback runs. let sink = unsafe { &mut *(opaque as *mut Sink) }; if let Some(f) = sink.on_start.take() { f(Started { duration, first }); @@ -285,7 +357,12 @@ extern "C" fn sink_started(opaque: *mut c_void, duration: f64, first: f64) { fn run_remux(source: &Source, url: &str, start: f64, sink: &mut Sink) -> Result<(), String> { let cstr = |s: &str| CString::new(s).map_err(|_| "invalid stream address".to_owned()); let url = cstr(url)?; - let ua = cstr(source.user_agent.as_deref().unwrap_or(crate::player::USER_AGENT))?; + let ua = cstr( + source + .user_agent + .as_deref() + .unwrap_or(crate::player::USER_AGENT), + )?; let referrer = source.referrer.as_deref().map(cstr).transpose()?; let audio_lang = cstr(&source.audio_lang)?; let mut o = TpRemux { @@ -301,12 +378,24 @@ fn run_remux(source: &Source, url: &str, start: f64, sink: &mut Sink) -> Result< started: sink_started, error: [0; 256], }; + // SAFETY: `o` matches remux.c's `tp_remux` layout (`repr(C)`); the C + // strings and `sink` outlive the call, which is synchronous and keeps no + // pointer past its return; `error` is a zeroed buffer remux.c fills with + // a NUL-terminated message (snprintf). let ret = unsafe { tp_remux_run(&mut o) }; if ret == 0 { return Ok(()); } - let msg = unsafe { CStr::from_ptr(o.error.as_ptr()) }.to_string_lossy().into_owned(); - Err(if msg.is_empty() { format!("remux failed ({ret})") } else { msg }) + // SAFETY: `error` started zeroed and remux.c only writes it with + // snprintf into its 256 bytes, so it is always NUL-terminated. + let msg = unsafe { CStr::from_ptr(o.error.as_ptr()) } + .to_string_lossy() + .into_owned(); + Err(if msg.is_empty() { + format!("remux failed ({ret})") + } else { + msg + }) } #[cfg(test)] diff --git a/src-tauri/src/cast/session.rs b/src-tauri/src/cast/session.rs new file mode 100644 index 0000000..743a648 --- /dev/null +++ b/src-tauri/src/cast/session.rs @@ -0,0 +1,603 @@ +//! One cast session: the task that owns the device connection, loads the +//! item, follows the TV's media status and carries out the UI's commands. + +use super::*; + +struct Current { + generation: u64, + token: String, + /// URL number: every (re)load of the item is a new one + n: u32, + live: bool, + meta: Meta, + /// item position at the start of URL `n` + offset: f64, + duration: f64, + loaded_at: Instant, + /// the relay answered for URL `n` + started: bool, + paused_at: Option, + /// live streams that ended are reloaded a few times + reloads: u32, +} + +struct Conn { + app: AppHandle, + device: Device, + w: castv2::Writer, + local: IpAddr, + tx: mpsc::UnboundedSender, + request_id: u64, + transport: Option, + app_session: Option, + media_session: Option, + generation: u64, + current: Option, + queued: Option>, + /// receiver time of the last media status + media_time: f64, + status: Arc>, +} + +enum Flow { + Continue, + End, +} + +impl Conn { + fn next_id(&mut self) -> u64 { + self.request_id += 1; + self.request_id + } + + async fn send( + &mut self, + destination: &str, + namespace: &str, + payload: Value, + ) -> std::io::Result<()> { + self.w + .send(&Message::new(destination, namespace, payload.to_string())) + .await + } + + async fn request( + &mut self, + destination: &str, + namespace: &str, + mut payload: Value, + ) -> std::io::Result<()> { + payload["requestId"] = json!(self.next_id()); + self.send(destination, namespace, payload).await + } + + async fn media(&mut self, kind: &str) -> std::io::Result<()> { + let (Some(transport), Some(media)) = (self.transport.clone(), self.media_session) else { + return Ok(()); + }; + self.request( + &transport, + NS_MEDIA, + json!({"type": kind, "mediaSessionId": media}), + ) + .await + } + + fn update(&self, f: impl FnOnce(&mut Status)) { + let mut s = self.status.lock(); + let before = s.clone(); + f(&mut s); + if *s != before { + let _ = self.app.emit(STATUS_EVENT, s.clone()); + } + } + + /// Publishes a new item on the relay and loads it. + async fn load_item(&mut self, item: Box) -> std::io::Result<()> { + let app = self.app.clone(); + let Some(cast) = app.try_state::() else { + return Ok(()); + }; + let Some(relay) = cast.relay.as_ref() else { + return Ok(()); + }; + if let Some(old) = self.current.take() { + relay.unpublish(&old.token); + } + self.generation += 1; + let generation = self.generation; + let tx = self.tx.clone(); + let live = item.source.live; + let on_start: relay::OnStart = Arc::new(move |n, s| { + let _ = tx.send(Cmd::Started(generation, n, s)); + }); + let token = relay.publish(item.source, self.device.addr.ip(), on_start); + let _ = &cast; // the app borrow ends with this statement + self.current = Some(Current { + generation, + token, + n: 0, + live, + meta: item.meta, + offset: 0.0, + duration: 0.0, + loaded_at: Instant::now(), + started: false, + paused_at: None, + reloads: 0, + }); + self.update(|s| { + s.live = live; + s.duration = 0.0; + s.error = None; + }); + self.load_at(item.start).await + } + + /// (Re)loads the current item from `start` seconds under a new URL. + async fn load_at(&mut self, start: f64) -> std::io::Result<()> { + let Some(transport) = self.transport.clone() else { + return Ok(()); + }; + let app = self.app.clone(); + let Some(cast) = app.try_state::() else { + return Ok(()); + }; + let Some(relay) = cast.relay.as_ref() else { + return Ok(()); + }; + let Some(cur) = self.current.as_mut() else { + return Ok(()); + }; + cur.n += 1; + let start = if cur.live { 0.0 } else { start.max(0.0) }; + relay.position(&cur.token, cur.n, start); + let url = relay.url(self.local, &cur.token, cur.n); + cur.offset = start; + cur.loaded_at = Instant::now(); + cur.started = false; + cur.paused_at = None; + let mut metadata = + json!({"metadataType": 0, "title": cur.meta.title.clone().unwrap_or_default()}); + if let Some(sub) = cur.meta.subtitle.clone().filter(|s| !s.is_empty()) { + metadata["subtitle"] = json!(sub); + } + if let Some(img) = cur + .meta + .image + .clone() + .filter(|u| u.starts_with("http://") || u.starts_with("https://")) + { + metadata["images"] = json!([{ "url": img }]); + } + let payload = json!({ + "type": "LOAD", + "sessionId": self.app_session, + "autoplay": true, + "currentTime": 0, + "media": { + "contentId": url, + "contentUrl": url, + "contentType": "video/mp4", + "streamType": if cur.live { "LIVE" } else { "BUFFERED" }, + "metadata": metadata, + }, + }); + let _ = &cast; + self.media_time = 0.0; + self.update(|s| { + s.state = "loading"; + s.position = start; + }); + self.request(&transport, NS_MEDIA, payload).await + } + + fn position(&self) -> f64 { + let Some(cur) = &self.current else { return 0.0 }; + let p = cur.offset + self.media_time; + if cur.duration > 0.0 { + p.min(cur.duration) + } else { + p + } + } + + fn relay_error(&self) -> Option { + let cur = self.current.as_ref()?; + self.app + .try_state::()? + .relay + .as_ref()? + .error(&cur.token) + } + + async fn on_message(&mut self, m: Message) -> std::io::Result { + let p: Value = serde_json::from_str(&m.payload).unwrap_or(Value::Null); + let kind = p["type"].as_str().unwrap_or(""); + match (m.namespace.as_str(), kind) { + (NS_HEARTBEAT, "PING") => { + self.send(&m.source, NS_HEARTBEAT, json!({"type": "PONG"})) + .await?; + } + (NS_CONNECTION, "CLOSE") if Some(&m.source) == self.transport.as_ref() => { + self.update(|s| { + s.state = "stopped"; + s.error = None; + }); + return Ok(Flow::End); + } + (NS_RECEIVER, "RECEIVER_STATUS") => { + let st = &p["status"]; + if let Some(level) = st["volume"]["level"].as_f64() { + let muted = st["volume"]["muted"].as_bool().unwrap_or(false); + self.update(|s| { + s.volume = level; + s.muted = muted; + }); + } + let ours = st["applications"].as_array().and_then(|apps| { + apps.iter() + .find(|a| a["appId"].as_str() == Some(DEFAULT_RECEIVER)) + .map(|a| { + ( + a["transportId"].as_str().unwrap_or("").to_owned(), + a["sessionId"].as_str().unwrap_or("").to_owned(), + ) + }) + }); + match (ours, &self.transport) { + (Some((transport, session)), None) if !transport.is_empty() => { + self.send(&transport, NS_CONNECTION, json!({"type": "CONNECT"})) + .await?; + self.transport = Some(transport); + self.app_session = Some(session); + if let Some(item) = self.queued.take() { + self.load_item(item).await?; + } + } + // another app took over the TV, or the remote closed ours + (None, Some(_)) => { + self.update(|s| { + s.state = "stopped"; + s.error = None; + }); + return Ok(Flow::End); + } + _ => {} + } + } + (NS_RECEIVER, "LAUNCH_ERROR") => { + self.update(|s| { + s.state = "stopped"; + s.error = Some("The TV could not start its media player".into()); + }); + return Ok(Flow::End); + } + (NS_MEDIA, "MEDIA_STATUS") => { + if let Some(ms) = p["status"].as_array().and_then(|a| a.first()) { + return self.on_media_status(ms.clone()).await; + } + } + (NS_MEDIA, "LOAD_FAILED" | "INVALID_REQUEST") => { + let error = self + .relay_error() + .unwrap_or_else(|| "The TV could not play this stream".into()); + self.update(|s| { + s.state = "error"; + s.error = Some(error); + }); + } + _ => {} + } + Ok(Flow::Continue) + } + + async fn on_media_status(&mut self, ms: Value) -> std::io::Result { + if let Some(id) = ms["mediaSessionId"].as_i64() { + self.media_session = Some(id); + } + if let Some(t) = ms["currentTime"].as_f64() { + self.media_time = t; + } + let state = ms["playerState"].as_str().unwrap_or(""); + let reason = ms["idleReason"].as_str().unwrap_or(""); + let position = self.position(); + let live = self.current.as_ref().is_some_and(|c| c.live); + match (state, reason) { + ("PLAYING", _) => { + if let Some(c) = self.current.as_mut() { + c.paused_at = None; + } + self.update(|s| { + s.state = "playing"; + s.position = position; + s.error = None; + }); + } + ("PAUSED", _) => { + if let Some(c) = self.current.as_mut() { + c.paused_at.get_or_insert_with(Instant::now); + } + self.update(|s| { + s.state = "paused"; + s.position = position; + }); + } + ("BUFFERING", _) => self.update(|s| { + s.state = "buffering"; + s.position = position; + }), + ("IDLE", "FINISHED" | "CANCELLED") if live => { + // the channel's stream dropped: tune in again a few times + let retry = self.current.as_mut().map(|c| { + c.reloads += 1; + c.reloads <= 3 + }); + if retry == Some(true) { + self.load_at(0.0).await?; + } else { + // a stream that ended without an error of its own (e.g. a + // file, or a receiver that closed early) is still "playing" + let error = self.relay_error(); + self.update(|s| match error { + Some(e) => { + s.state = "error"; + s.error = Some(e); + } + None => { + s.state = "playing"; + s.error = None; + } + }); + } + } + ("IDLE", "FINISHED") => self.update(|s| { + s.state = "ended"; + s.position = s.duration.max(position); + }), + ("IDLE", "ERROR") => { + let error = self + .relay_error() + .unwrap_or_else(|| "The TV could not play this stream".into()); + self.update(|s| { + s.state = "error"; + s.error = Some(error); + }); + } + _ => {} + } + Ok(Flow::Continue) + } + + async fn on_cmd(&mut self, cmd: Cmd) -> std::io::Result { + match cmd { + Cmd::Load(item) => { + if self.transport.is_some() { + self.load_item(item).await?; + } else { + self.queued = Some(item); + } + } + Cmd::Play => { + let stale = self.current.as_ref().is_some_and(|c| { + c.live && c.paused_at.is_some_and(|t| t.elapsed() > LIVE_PAUSE_LIMIT) + }); + let ended = self.status.lock().state == "ended"; + if stale || ended { + // live: back to "now"; VOD at the end: from the start + self.load_at(0.0).await?; + } else { + self.media("PLAY").await?; + } + } + Cmd::Pause => self.media("PAUSE").await?, + Cmd::Seek(t) => { + let Some(cur) = &self.current else { + return Ok(Flow::Continue); + }; + if !cur.live { + let end = if cur.duration > 0.0 { + (cur.duration - 1.0).max(0.0) + } else { + f64::MAX + }; + self.load_at(t.clamp(0.0, end)).await?; + } + } + Cmd::Volume(level) => { + self.request( + RECEIVER, + NS_RECEIVER, + json!({"type": "SET_VOLUME", "volume": {"level": level.clamp(0.0, 1.0)}}), + ) + .await?; + self.update(|s| s.volume = level.clamp(0.0, 1.0)); + } + Cmd::Mute(muted) => { + self.request( + RECEIVER, + NS_RECEIVER, + json!({"type": "SET_VOLUME", "volume": {"muted": muted}}), + ) + .await?; + self.update(|s| s.muted = muted); + } + Cmd::Stop => { + if let Some(session) = self.app_session.clone() { + let _ = self + .request( + RECEIVER, + NS_RECEIVER, + json!({"type": "STOP", "sessionId": session}), + ) + .await; + } + self.update(|s| { + s.state = "stopped"; + s.error = None; + }); + return Ok(Flow::End); + } + Cmd::Started(generation, n, started) => { + if let Some(cur) = self + .current + .as_mut() + .filter(|c| c.generation == generation && c.n == n) + { + cur.started = true; + cur.offset = started.first; + if started.duration > 0.0 { + cur.duration = started.duration; + } + let (duration, position) = (cur.duration, self.position()); + self.update(|s| { + s.duration = duration; + s.position = position; + }); + } + } + } + Ok(Flow::Continue) + } + + async fn on_tick(&mut self) -> std::io::Result { + let state = self.status.lock().state; + if matches!(state, "playing" | "buffering") { + self.media("GET_STATUS").await?; + } + let unreachable = self.current.as_ref().is_some_and(|c| { + !c.started && state == "loading" && c.loaded_at.elapsed() > UNREACHABLE_AFTER + }); + if unreachable { + let error = self.relay_error().unwrap_or_else(|| { + "The TV can't reach this computer. Make sure both are on the same network and no firewall blocks \ + incoming connections." + .into() + }); + self.update(|s| { + s.state = "error"; + s.error = Some(error); + }); + if let Some(c) = self.current.as_mut() { + c.started = true; // report once + } + } + Ok(Flow::Continue) + } +} + +pub(super) async fn run( + app: AppHandle, + device: Device, + mut rx: mpsc::UnboundedReceiver, + tx: mpsc::UnboundedSender, + status: Arc>, +) { + let emit = |s: &Status| { + let _ = app.emit(STATUS_EVENT, s.clone()); + }; + let (mut reader, writer, local) = match castv2::connect(device.addr).await { + Ok(c) => c, + Err(e) => { + log::warn!( + "cast: cannot connect to {} at {}: {e}", + device.name, + device.addr + ); + let mut s = status.lock(); + s.state = "stopped"; + s.error = Some(format!("Can't connect to {}", device.name)); + emit(&s); + return; + } + }; + log::info!("cast: connected to {} at {}", device.name, device.addr); + if let Some(st) = app.try_state::() { + remember(st.inner(), &device).await; + } + let mut c = Conn { + app: app.clone(), + device, + w: writer, + local, + tx, + request_id: 0, + transport: None, + app_session: None, + media_session: None, + generation: 0, + current: None, + queued: None, + media_time: 0.0, + status, + }; + let setup = async { + c.send(RECEIVER, NS_CONNECTION, json!({"type": "CONNECT"})) + .await?; + c.request( + RECEIVER, + NS_RECEIVER, + json!({"type": "LAUNCH", "appId": DEFAULT_RECEIVER}), + ) + .await + }; + let mut result = setup.await; + + let mut heartbeat = tokio::time::interval(Duration::from_secs(5)); + let mut tick = tokio::time::interval(Duration::from_secs(1)); + let mut last_heard = Instant::now(); + while result.is_ok() { + let flow = tokio::select! { + m = reader.next() => match m { + Ok(m) => { + last_heard = Instant::now(); + c.on_message(m).await + } + Err(e) => Err(e), + }, + cmd = rx.recv() => match cmd { + Some(cmd) => c.on_cmd(cmd).await, + None => Ok(Flow::End), + }, + _ = heartbeat.tick() => { + if last_heard.elapsed() > Duration::from_secs(20) { + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "the TV stopped answering")) + } else { + c.send(RECEIVER, NS_HEARTBEAT, json!({"type": "PING"})).await.map(|_| Flow::Continue) + } + } + _ = tick.tick() => c.on_tick().await, + }; + match flow { + Ok(Flow::Continue) => {} + Ok(Flow::End) => break, + Err(e) => result = Err(e), + } + } + if let Err(e) = result { + log::warn!("cast: connection to {} lost: {e}", c.device.name); + c.update(|s| { + if !s.finished() { + s.state = "stopped"; + s.error = Some(format!("Lost the connection to {}", c.device.name)); + } + }); + } + if let Some(cur) = c.current.take() + && let Some(relay) = app + .try_state::() + .as_ref() + .and_then(|cast| cast.relay.as_ref()) + { + relay.unpublish(&cur.token); + } + if let Some(transport) = c.transport.clone() { + let _ = c + .send(&transport, NS_CONNECTION, json!({"type": "CLOSE"})) + .await; + } + let _ = c + .send(RECEIVER, NS_CONNECTION, json!({"type": "CLOSE"})) + .await; + log::info!("cast: session with {} ended", c.device.name); +} diff --git a/src-tauri/src/catalog.rs b/src-tauri/src/catalog.rs deleted file mode 100644 index d52331c..0000000 --- a/src-tauri/src/catalog.rs +++ /dev/null @@ -1,2820 +0,0 @@ -//! Read-side commands: categories, channel/movie/series listings, details, -//! programme guide and search. - -use std::collections::{BTreeMap, HashMap}; -use std::time::Instant; - -use base64::Engine; -use rusqlite::types::Value as Sql; -use rusqlite::{Connection, OptionalExtension, Row, params, params_from_iter}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; -use tauri::State; - -use crate::db::now; -use crate::epg::{self, ProgrammeRow}; -use crate::error::{Error, Result}; -use crate::settings; -use crate::sources::{self, SourceKind}; -use crate::state::{AppState, http_client}; -use crate::util::json::{f64_of, first_str, i64_of, str_of}; -use crate::works::versions::{self, VersionInfo}; - -const MOVIE_DETAIL_TTL: i64 = 7 * 86400; -const SERIES_DETAIL_TTL: i64 = 12 * 3600; - -// ---------------------------------------------------------------- types - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Page { - pub total: i64, - pub items: Vec, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct CategoryItem { - pub source_id: i64, - pub id: String, - pub title: String, - pub region: Option, - pub badges: Vec, - pub count: i64, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Brief { - pub title: String, - pub start: i64, - pub stop: i64, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ChannelItem { - pub source_id: i64, - pub id: String, - pub num: Option, - pub title: String, - pub logo: Option, - pub epg_id: Option, - pub category_id: Option, - pub badges: Vec, - pub archive: bool, - pub archive_days: i64, - pub favorite: bool, - pub now: Option, - pub next: Option, - /// the channel this feed belongs to (all its quality variants) - pub group: Option, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct GroupInfo { - pub key: String, - /// number of feeds (quality variants) of the channel - pub variants: i64, - pub country: Option, - pub genre: String, -} - -/// Grouping info shared by movie and series items (see `works`): the work -/// key and what its versions offer. -#[derive(Debug, Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct WorkInfo { - pub key: Option, - /// number of provider copies of this title (details list them in `versions`) - pub version_count: i64, - /// "4K", "Dolby Vision", "Dolby Audio", "HEVC", "Blu-ray" - pub quality: Vec, - pub services: Vec, -} - -fn work_info( - key: Option, - versions: Option, - badges: Option, - services: Option, -) -> WorkInfo { - let split = |s: Option| -> Vec { - s.unwrap_or_default() - .split('|') - .filter(|x| !x.is_empty()) - .map(str::to_owned) - .collect() - }; - WorkInfo { - version_count: versions.unwrap_or(1), - quality: split(badges), - services: split(services), - key, - } -} - -/// A movie as listed: in browse lists one row per work (`work` table) whose -/// `source_id`/`id` name a representative copy. -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct MovieItem { - pub source_id: i64, - pub id: String, - pub title: String, - pub year: Option, - pub poster: Option, - pub rating: Option, - pub added: Option, - pub tag: Option, - pub ext: Option, - pub favorite: bool, - /// 0..1 watch progress, when started. - pub progress: Option, - pub watched: bool, - #[serde(flatten)] - pub work: WorkInfo, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SeriesItem { - pub source_id: i64, - pub id: String, - pub title: String, - pub year: Option, - pub cover: Option, - pub backdrop: Option, - pub rating: Option, - pub genre: Option, - pub last_modified: Option, - pub tag: Option, - pub favorite: bool, - #[serde(flatten)] - pub work: WorkInfo, -} - -#[derive(Debug, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ChannelQuery { - pub source_id: Option, - pub category_id: Option, - /// one row per channel (`channel_group`) playing its chosen variant, - /// instead of every provider feed - #[serde(default)] - pub grouped: bool, - /// channel groups of one country ("DK") / live genre ("Sports") - pub country: Option, - pub genre: Option, - #[serde(default)] - pub favorites: bool, - /// Only channels that have programme data (TV guide). - #[serde(default)] - pub with_epg: bool, - pub q: Option, - pub offset: Option, - pub limit: Option, -} - -#[derive(Debug, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MediaQuery { - /// with `category_id`: a provider category ("collection") - pub source_id: Option, - pub category_id: Option, - #[serde(default)] - pub favorites: bool, - pub q: Option, - /// 'added' (default) | 'title' | 'rating' | 'year' - pub sort: Option, - /// browse facets that must all match (`work_facet`) - #[serde(default)] - pub facets: Vec, - pub offset: Option, - pub limit: Option, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FacetFilter { - pub facet: String, - pub value: String, -} - -const FACETS: &[&str] = &[ - "service", - "language", - "quality", - "genre", - "decade", - "collection", - "original", - "franchise", - "network", -]; - -/// Badges are stored space separated; multi-word ones ("DOLBY VISION") are -/// re-joined here. -pub(crate) fn split_badges(s: String) -> Vec { - let mut out: Vec = Vec::new(); - for w in s.split_whitespace() { - match (out.last_mut(), w) { - (Some(last), "VISION" | "AUDIO") if last == "DOLBY" => { - last.push(' '); - last.push_str(w); - } - _ => out.push(w.to_owned()), - } - } - out -} - -async fn blocking( - st: &AppState, - f: impl FnOnce(&Connection) -> Result + Send + 'static, -) -> Result { - let st = st.clone(); - tokio::task::spawn_blocking(move || { - let conn = st.db.read(); - f(&conn) - }) - .await - .map_err(|e| Error::msg(e.to_string()))? -} - -fn like_pattern(q: &str) -> String { - let escaped = q - .trim() - .replace('\\', "\\\\") - .replace('%', "\\%") - .replace('_', "\\_"); - format!("%{escaped}%") -} - -// ------------------------------------------------------------ categories - -#[tauri::command] -pub async fn categories(state: State<'_, AppState>, kind: String) -> Result> { - let table = match kind.as_str() { - "live" => "channel", - "movie" => "movie", - "series" => "series", - _ => return Err(Error::msg(format!("unknown category kind {kind}"))), - }; - blocking(state.inner(), move |conn| { - let show_adult = settings::get_bool(conn, "content.showAdult"); - let extra = if table == "channel" { " AND x.separator = 0" } else { "" }; - let sql = format!( - "SELECT c.source_id, c.id, c.title, c.region, c.badges, - (SELECT COUNT(*) FROM {table} x WHERE x.source_id = c.source_id AND x.category_id = c.id{extra}) AS n - FROM category c - WHERE c.kind = ?1 AND (?2 OR c.adult = 0) - ORDER BY c.source_id, c.position" - ); - let mut stmt = conn.prepare_cached(&sql)?; - let rows = stmt - .query_map(params![kind, show_adult], |r| { - Ok(CategoryItem { - source_id: r.get(0)?, - id: r.get(1)?, - title: r.get(2)?, - region: r.get(3)?, - badges: split_badges(r.get(4)?), - count: r.get(5)?, - }) - })? - .collect::, _>>()?; - Ok(rows.into_iter().filter(|c| c.count > 0).collect()) - }) - .await -} - -// -------------------------------------------------------------- channels - -/// Channel rows with now/next. `grouped`: one row per channel group, -/// titled as the group and playing its chosen variant (`g.source_id`/ -/// `g.item_id`), a favorite when any variant is. A feed without its own EPG -/// id uses its group's. -fn channel_select(grouped: bool) -> String { - let (title, favorite, from) = if grouped { - ( - "g.title", - "EXISTS(SELECT 1 FROM channel x JOIN favorite f ON f.source_id = x.source_id AND f.kind = 'live' AND f.item_id = x.id - WHERE x.group_key = g.key)", - "channel_group g JOIN channel c ON c.source_id = g.source_id AND c.id = g.item_id", - ) - } else { - ( - "c.title", - "EXISTS(SELECT 1 FROM favorite f WHERE f.source_id = c.source_id AND f.kind = 'live' AND f.item_id = c.id)", - "channel c LEFT JOIN channel_group g ON g.key = c.group_key", - ) - }; - format!( - "SELECT c.source_id, c.id, c.num, {title}, COALESCE(c.logo, g.logo), COALESCE(c.epg_id, g.epg_id), c.category_id, - c.badges, c.archive, c.archive_days, {favorite}, - p.title, p.start, p.stop, q.title, q.start, q.stop, g.key, g.variants, g.country, g.genre - FROM {from} - LEFT JOIN programme p ON p.source_id = c.source_id AND p.epg_id = COALESCE(c.epg_id, g.epg_id) - AND p.start = (SELECT MAX(start) FROM programme - WHERE source_id = c.source_id AND epg_id = COALESCE(c.epg_id, g.epg_id) AND start <= :now) - AND p.stop > :now - LEFT JOIN programme q ON q.source_id = c.source_id AND q.epg_id = COALESCE(c.epg_id, g.epg_id) - AND q.start = (SELECT MIN(start) FROM programme - WHERE source_id = c.source_id AND epg_id = COALESCE(c.epg_id, g.epg_id) AND start > :now)" - ) -} - -fn row_to_channel(r: &Row) -> rusqlite::Result { - let brief = |i: usize| -> rusqlite::Result> { - Ok(match r.get::<_, Option>(i)? { - Some(title) => Some(Brief { - title, - start: r.get(i + 1)?, - stop: r.get(i + 2)?, - }), - None => None, - }) - }; - Ok(ChannelItem { - source_id: r.get(0)?, - id: r.get(1)?, - num: r.get(2)?, - title: r.get(3)?, - logo: r.get(4)?, - epg_id: r.get(5)?, - category_id: r.get(6)?, - badges: split_badges(r.get(7)?), - archive: r.get(8)?, - archive_days: r.get(9)?, - favorite: r.get(10)?, - now: brief(11)?, - next: brief(14)?, - group: match r.get::<_, Option>(17)? { - Some(key) => Some(GroupInfo { - key, - variants: r.get(18)?, - country: r.get(19)?, - genre: r.get(20)?, - }), - None => None, - }, - }) -} - -pub fn query_channels(conn: &Connection, q: &ChannelQuery) -> Result> { - let g = q.grouped; - let mut filters = vec!["c.separator = 0".to_owned()]; - let mut args: Vec<(String, Sql)> = vec![(":now".into(), Sql::Integer(now()))]; - if !settings::get_bool(conn, "content.showAdult") { - filters.push(if g { "g.adult = 0" } else { "c.adult = 0" }.into()); - } - match (q.source_id, &q.category_id, g) { - (Some(s), Some(cat), true) => { - filters.push("g.key IN (SELECT group_key FROM channel WHERE source_id = :source AND category_id = :cat)".into()); - args.push((":source".into(), Sql::Integer(s))); - args.push((":cat".into(), Sql::Text(cat.clone()))); - } - (Some(s), None, true) => { - filters - .push("g.key IN (SELECT group_key FROM channel WHERE source_id = :source)".into()); - args.push((":source".into(), Sql::Integer(s))); - } - (s, cat, false) => { - if let Some(s) = s { - filters.push("c.source_id = :source".into()); - args.push((":source".into(), Sql::Integer(s))); - } - if let Some(cat) = cat { - filters.push("c.category_id = :cat".into()); - args.push((":cat".into(), Sql::Text(cat.clone()))); - } - } - _ => {} - } - match q.country.as_deref() { - // channels whose category has no region - Some("") => filters.push("g.key IS NOT NULL AND g.country IS NULL".into()), - Some(country) => { - filters.push("g.country = :country".into()); - args.push((":country".into(), Sql::Text(country.to_owned()))); - } - None => {} - } - if let Some(genre) = &q.genre { - filters.push("g.genre = :genre".into()); - args.push((":genre".into(), Sql::Text(genre.clone()))); - } - if q.with_epg { - filters.push( - "COALESCE(c.epg_id, g.epg_id) IS NOT NULL - AND EXISTS (SELECT 1 FROM programme pe WHERE pe.source_id = c.source_id AND pe.epg_id = COALESCE(c.epg_id, g.epg_id))" - .into(), - ); - } - if let Some(text) = q.q.as_deref().filter(|t| !t.trim().is_empty()) { - filters.push( - if g { - "g.title LIKE :q ESCAPE '\\'" - } else { - "c.title LIKE :q ESCAPE '\\'" - } - .into(), - ); - args.push((":q".into(), Sql::Text(like_pattern(text)))); - } - let (join, order) = match (q.favorites, g) { - // a channel is a favorite since its first favorited variant - (true, true) => ( - " JOIN (SELECT x.group_key AS key, MIN(f.added_at) AS added_at FROM favorite f - JOIN channel x ON x.source_id = f.source_id AND x.id = f.item_id - WHERE f.kind = 'live' AND x.group_key IS NOT NULL GROUP BY x.group_key) fv ON fv.key = g.key", - "fv.added_at".to_owned(), - ), - (true, false) => ( - " JOIN favorite fv ON fv.source_id = c.source_id AND fv.kind = 'live' AND fv.item_id = c.id", - "fv.added_at".to_owned(), - ), - // a country: its regular channels first, event feeds last; a genre: - // the viewer's countries first - (false, true) if q.country.is_some() => ("", genre_order()), - (false, true) if q.genre.is_some() => ("", country_order_sql(conn)?), - (false, true) => ("", "g.position".to_owned()), - (false, false) => ("", "c.source_id, c.position".to_owned()), - }; - let where_sql = filters.join(" AND "); - let from = if g { - "channel_group g JOIN channel c ON c.source_id = g.source_id AND c.id = g.item_id" - } else { - "channel c LEFT JOIN channel_group g ON g.key = c.group_key" - }; - - let count_sql = format!("SELECT COUNT(*) FROM {from}{join} WHERE {where_sql}"); - let count_args: Vec<(&str, &dyn rusqlite::ToSql)> = args - .iter() - .filter(|(k, _)| k != ":now") - .map(|(k, v)| (k.as_str(), v as &dyn rusqlite::ToSql)) - .collect(); - let total: i64 = conn - .prepare_cached(&count_sql)? - .query_row(count_args.as_slice(), |r| r.get(0))?; - - let limit = q.limit.unwrap_or(500).clamp(1, 5000); - let offset = q.offset.unwrap_or(0).max(0); - let sql = format!( - "{}{join} WHERE {where_sql} ORDER BY {order} LIMIT {limit} OFFSET {offset}", - channel_select(g) - ); - let named: Vec<(&str, &dyn rusqlite::ToSql)> = args - .iter() - .map(|(k, v)| (k.as_str(), v as &dyn rusqlite::ToSql)) - .collect(); - let items = conn - .prepare_cached(&sql)? - .query_map(named.as_slice(), row_to_channel)? - .collect::, _>>()?; - Ok(Page { total, items }) -} - -#[tauri::command] -pub async fn channels( - state: State<'_, AppState>, - query: ChannelQuery, -) -> Result> { - blocking(state.inner(), move |conn| { - let t = Instant::now(); - let page = query_channels(conn, &query)?; - log::debug!( - "channels {:?}: {} of {} in {:?}", - query.category_id, - page.items.len(), - page.total, - t.elapsed() - ); - Ok(page) - }) - .await -} - -pub fn channel_by_id(conn: &Connection, source_id: i64, id: &str) -> Result { - let sql = format!( - "{} WHERE c.source_id = :source AND c.id = :id", - channel_select(false) - ); - conn.prepare_cached(&sql)? - .query_row( - &[ - (":now", &now() as &dyn rusqlite::ToSql), - (":source", &source_id), - (":id", &id), - ], - row_to_channel, - ) - .optional()? - .ok_or_else(|| Error::NotFound(format!("channel {id}"))) -} - -#[tauri::command] -pub async fn channel( - state: State<'_, AppState>, - source_id: i64, - id: String, -) -> Result { - blocking(state.inner(), move |conn| { - channel_by_id(conn, source_id, &id) - }) - .await -} - -/// A channel group as a row: its title, playing its chosen variant. -pub fn channel_group_by_key(conn: &Connection, key: &str) -> Result { - let sql = format!("{} WHERE g.key = :key", channel_select(true)); - conn.prepare_cached(&sql)? - .query_row( - &[(":now", &now() as &dyn rusqlite::ToSql), (":key", &key)], - row_to_channel, - ) - .optional()? - .ok_or_else(|| Error::NotFound(format!("channel {key}"))) -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct LiveCountry { - /// region code from the provider's categories ("DK"); None = no region - pub code: Option, - pub name: String, - pub count: i64, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct LiveCell { - pub country: Option, - pub genre: String, - pub count: i64, -} - -/// Live TV navigation: channel groups per country and genre. -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct LiveNav { - /// the viewer's countries first (player languages), then by size - pub countries: Vec, - /// genres in display order - pub genres: Vec, - pub cells: Vec, -} - -/// `ORDER BY` for channel groups: genres in `LIVE_GENRES` order; within one, -/// channels with guide data first — the linear channels (BBC One, ITV, …) -/// ahead of a provider's 24/7 and FAST feeds, which rarely have any. -fn genre_order() -> String { - let cases: String = crate::works::genre::LIVE_GENRES - .iter() - .enumerate() - .map(|(i, g)| format!(" WHEN '{}' THEN {i}", g.replace('\'', "''"))) - .collect(); - format!("CASE g.genre{cases} ELSE 99 END, g.epg_id IS NULL, g.position") -} - -/// `ORDER BY` for channel groups: countries as `live_nav` lists them, each -/// with its guide channels first. -fn country_order_sql(conn: &Connection) -> Result { - let cases: String = live_nav_for(conn)? - .countries - .iter() - .enumerate() - .filter_map(|(i, c)| { - c.code - .as_ref() - .map(|code| format!(" WHEN '{}' THEN {i}", code.replace('\'', "''"))) - }) - .collect(); - Ok(format!( - "CASE g.country{cases} ELSE 9999 END, g.epg_id IS NULL, g.position" - )) -} - -pub fn live_nav_for(conn: &Connection) -> Result { - let show_adult = settings::get_bool(conn, "content.showAdult"); - let cells: Vec = conn - .prepare_cached( - "SELECT country, genre, COUNT(*) FROM channel_group WHERE ?1 OR adult = 0 GROUP BY country, genre", - )? - .query_map([show_adult], |r| Ok(LiveCell { country: r.get(0)?, genre: r.get(1)?, count: r.get(2)? }))? - .collect::>()?; - let mut countries: Vec = Vec::new(); - for c in &cells { - match countries.iter_mut().find(|x| x.code == c.country) { - Some(x) => x.count += c.count, - None => countries.push(LiveCountry { - code: c.country.clone(), - name: c - .country - .as_deref() - .map(crate::works::genre::country_name) - .unwrap_or_else(|| "Other".into()), - count: c.count, - }), - } - } - let home: Vec<&str> = versions::language_prefs(conn) - .into_iter() - .flat_map(|l| { - crate::works::genre::countries_for_language(l) - .iter() - .copied() - }) - .collect(); - let rank = |c: &LiveCountry| { - c.code - .as_deref() - .and_then(|code| home.iter().position(|h| *h == code)) - .unwrap_or(usize::MAX) - }; - countries.sort_by(|a, b| { - rank(a) - .cmp(&rank(b)) - .then(a.code.is_none().cmp(&b.code.is_none())) - .then(b.count.cmp(&a.count)) - .then(a.name.cmp(&b.name)) - }); - let genres = crate::works::genre::LIVE_GENRES - .iter() - .filter(|g| cells.iter().any(|c| c.genre == **g)) - .map(|g| g.to_string()) - .collect(); - Ok(LiveNav { - countries, - genres, - cells, - }) -} - -#[tauri::command] -pub async fn live_nav(state: State<'_, AppState>) -> Result { - blocking(state.inner(), live_nav_for).await -} - -/// One provider feed of a channel, for the variant chips. -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ChannelVariant { - #[serde(flatten)] - pub channel: ChannelItem, - /// "RAW · HEVC", "HD · VIP", "4K" - pub label: String, - /// provider category, e.g. "Now TV Sport · HD RAW" - pub category: Option, - /// the one that plays for this channel - pub selected: bool, -} - -pub fn variants_of(conn: &Connection, key: &str) -> Result> { - let chosen: Option<(i64, String)> = conn - .query_row( - "SELECT source_id, item_id FROM channel_group WHERE key = ?1", - [key], - |r| Ok((r.get(0)?, r.get(1)?)), - ) - .optional()?; - type Row = (i64, String, String, Option, Option, i64); - let rows: Vec = conn - .prepare_cached( - "SELECT c.source_id, c.id, c.badges, k.badges, k.name, COALESCE(k.position, 0) * 100000 + c.position - FROM channel c - LEFT JOIN category k ON k.source_id = c.source_id AND k.kind = 'live' AND k.id = c.category_id - WHERE c.group_key = ?1", - )? - .query_map([key], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))? - .collect::>()?; - let mut out: Vec<(i32, i64, ChannelVariant)> = Vec::new(); - for (sid, id, badges, cat_badges, cat_name, order) in rows { - let channel = channel_by_id(conn, sid, &id)?; - let selected = chosen.as_ref().is_some_and(|(s, i)| *s == sid && *i == id); - let label = - crate::works::channel_variant_label(&badges, cat_badges.as_deref().unwrap_or("")); - let category = cat_name.as_deref().map(crate::names::display_category); - out.push(( - crate::works::channel_rank(&badges), - order, - ChannelVariant { - channel, - label, - category, - selected, - }, - )); - } - out.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); - // identical feeds (backups in the same category) get a number - let mut seen: HashMap = HashMap::new(); - let mut variants: Vec = out.into_iter().map(|(_, _, v)| v).collect(); - for v in &mut variants { - let n = seen.entry(v.label.clone()).or_insert(0); - *n += 1; - if *n > 1 { - v.label = format!("{} ({n})", v.label); - } - } - Ok(variants) -} - -#[tauri::command] -pub async fn channel_variants( - state: State<'_, AppState>, - key: String, -) -> Result> { - blocking(state.inner(), move |conn| variants_of(conn, &key)).await -} - -// ---------------------------------------------------------------- movies - -/// One movie copy with its work's grouping info. -const MOVIE_SELECT: &str = " - SELECT m.source_id, m.id, m.title, m.year, m.poster, m.rating, m.added, m.tag, m.ext, - EXISTS(SELECT 1 FROM favorite f WHERE f.source_id = m.source_id AND f.kind = 'movie' AND f.item_id = m.id), - h.position, h.duration, COALESCE(h.watched, 0), - m.work_key, w.versions, w.badges, w.services - FROM movie m - LEFT JOIN history h ON h.source_id = m.source_id AND h.kind = 'movie' AND h.item_id = m.id - LEFT JOIN work w ON w.kind = 'movie' AND w.key = m.work_key"; - -/// Watch state of a movie work: the most recently played copy. -fn work_history(col: &str) -> String { - format!( - "(SELECT h.{col} FROM movie hm JOIN history h ON h.source_id = hm.source_id AND h.kind = 'movie' AND h.item_id = hm.id - WHERE hm.work_key = w.key ORDER BY h.updated_at DESC LIMIT 1)" - ) -} - -/// One movie work (browse lists), same columns as `MOVIE_SELECT`. -fn movie_work_select() -> String { - format!( - "SELECT w.source_id, w.item_id, w.title, w.year, w.poster, w.rating, w.added, m.tag, m.ext, - EXISTS(SELECT 1 FROM favorite f JOIN movie fm ON fm.source_id = f.source_id AND fm.id = f.item_id - WHERE f.kind = 'movie' AND fm.work_key = w.key), - {}, {}, COALESCE({}, 0), - w.key, w.versions, w.badges, w.services - FROM work w - LEFT JOIN movie m ON m.source_id = w.source_id AND m.id = w.item_id", - work_history("position"), - work_history("duration"), - work_history("watched") - ) -} - -fn row_to_movie(r: &Row) -> rusqlite::Result { - let pos: Option = r.get(10)?; - let dur: Option = r.get(11)?; - Ok(MovieItem { - source_id: r.get(0)?, - id: r.get(1)?, - title: r.get(2)?, - year: r.get(3)?, - poster: r.get(4)?, - rating: r.get(5)?, - added: r.get(6)?, - tag: r.get(7)?, - ext: r.get(8)?, - favorite: r.get(9)?, - progress: match (pos, dur) { - (Some(p), Some(d)) if d > 0.0 && p > 0.0 => Some((p / d).clamp(0.0, 1.0)), - _ => None, - }, - watched: r.get(12)?, - work: work_info(r.get(13)?, r.get(14)?, r.get(15)?, r.get(16)?), - }) -} - -/// One series copy with its work's grouping info. -const SERIES_SELECT: &str = " - SELECT s.source_id, s.id, s.title, s.year, s.cover, s.backdrop, s.rating, s.genre, s.last_modified, s.tag, - EXISTS(SELECT 1 FROM favorite f WHERE f.source_id = s.source_id AND f.kind = 'series' AND f.item_id = s.id), - s.work_key, w.versions, w.badges, w.services - FROM series s - LEFT JOIN work w ON w.kind = 'series' AND w.key = s.work_key"; - -/// One series work (browse lists), same columns as `SERIES_SELECT`. -const SERIES_WORK_SELECT: &str = " - SELECT w.source_id, w.item_id, w.title, w.year, w.poster, w.backdrop, w.rating, w.genre, w.added, s.tag, - EXISTS(SELECT 1 FROM favorite f JOIN series fs ON fs.source_id = f.source_id AND fs.id = f.item_id - WHERE f.kind = 'series' AND fs.work_key = w.key), - w.key, w.versions, w.badges, w.services - FROM work w - LEFT JOIN series s ON s.source_id = w.source_id AND s.id = w.item_id"; - -fn row_to_series(r: &Row) -> rusqlite::Result { - Ok(SeriesItem { - source_id: r.get(0)?, - id: r.get(1)?, - title: r.get(2)?, - year: r.get(3)?, - cover: r.get(4)?, - backdrop: r.get(5)?, - rating: r.get(6)?, - genre: r.get(7)?, - last_modified: r.get(8)?, - tag: r.get(9)?, - favorite: r.get(10)?, - work: work_info(r.get(11)?, r.get(12)?, r.get(13)?, r.get(14)?), - }) -} - -/// Browse lists: one row per work. Filters match through the members, so a -/// work shows up in every provider category and facet any copy belongs to. -/// WHERE clause over `work w` for a browse query (`?1` = kind). Facet -/// `skip` is left out — facet counts show what choosing another value of -/// that facet would give. -fn work_filters( - conn: &Connection, - q: &MediaQuery, - kind: &str, - skip: Option<&str>, -) -> Result<(String, Vec)> { - let table = if kind == "movie" { "movie" } else { "series" }; - let mut args: Vec = vec![Sql::Text(kind.to_owned())]; - let mut filters: Vec = vec!["w.kind = ?1".into()]; - if !settings::get_bool(conn, "content.showAdult") { - filters.push("w.adult = 0".into()); - } - match (q.source_id, &q.category_id) { - (Some(s), Some(cat)) => { - args.push(Sql::Integer(s)); - args.push(Sql::Text(cat.clone())); - filters.push(format!( - "w.key IN (SELECT work_key FROM {table} WHERE source_id = ?{} AND category_id = ?{})", - args.len() - 1, - args.len() - )); - } - (Some(s), None) => { - args.push(Sql::Integer(s)); - filters.push(format!( - "w.key IN (SELECT work_key FROM {table} WHERE source_id = ?{})", - args.len() - )); - } - _ => {} - } - for f in &q.facets { - if !FACETS.contains(&f.facet.as_str()) { - return Err(Error::msg(format!("unknown facet {}", f.facet))); - } - if skip == Some(f.facet.as_str()) { - continue; - } - args.push(Sql::Text(f.facet.clone())); - args.push(Sql::Text(f.value.clone())); - filters.push(format!( - "w.key IN (SELECT key FROM work_facet WHERE kind = ?1 AND facet = ?{} AND value = ?{})", - args.len() - 1, - args.len() - )); - } - if q.favorites { - filters.push(format!( - "w.key IN (SELECT x.work_key FROM favorite f JOIN {table} x ON x.source_id = f.source_id AND x.id = f.item_id - WHERE f.kind = ?1)" - )); - } - if let Some(text) = q.q.as_deref().filter(|t| !t.trim().is_empty()) { - // any copy's title: "Kastanjemanden" finds "The Chestnut Man" - args.push(Sql::Text(like_pattern(text))); - filters.push(format!( - "w.key IN (SELECT work_key FROM {table} WHERE title LIKE ?{} ESCAPE '\\')", - args.len() - )); - } - Ok((filters.join(" AND "), args)) -} - -fn query_works( - conn: &Connection, - q: &MediaQuery, - kind: &str, - select: &str, - map: fn(&Row) -> rusqlite::Result, -) -> Result> { - let table = if kind == "movie" { "movie" } else { "series" }; - let (where_sql, args) = work_filters(conn, q, kind, None)?; - let order = match (q.favorites, q.sort.as_deref().unwrap_or("added")) { - (true, _) => format!( - "(SELECT MAX(f.added_at) FROM favorite f JOIN {table} x ON x.source_id = f.source_id AND x.id = f.item_id - WHERE f.kind = ?1 AND x.work_key = w.key) DESC" - ), - (_, "title") => "w.title COLLATE NOCASE".to_owned(), - (_, "rating") => "w.rating IS NULL, w.rating DESC, w.title COLLATE NOCASE".to_owned(), - (_, "year") => "w.year IS NULL, w.year DESC, w.title COLLATE NOCASE".to_owned(), - (_, "provider") => format!( - "w.source_id, (SELECT position FROM {table} x WHERE x.source_id = w.source_id AND x.id = w.item_id)" - ), - _ => "w.added IS NULL, w.added DESC, w.title COLLATE NOCASE".to_owned(), - }; - let total: i64 = conn - .prepare_cached(&format!("SELECT COUNT(*) FROM work w WHERE {where_sql}"))? - .query_row(params_from_iter(args.iter()), |r| r.get(0))?; - let limit = q.limit.unwrap_or(120).clamp(1, 2000); - let offset = q.offset.unwrap_or(0).max(0); - let sql = format!("{select} WHERE {where_sql} ORDER BY {order} LIMIT {limit} OFFSET {offset}"); - let items = conn - .prepare_cached(&sql)? - .query_map(params_from_iter(args.iter()), map)? - .collect::, _>>()?; - Ok(Page { total, items }) -} - -#[tauri::command] -pub async fn movies(state: State<'_, AppState>, query: MediaQuery) -> Result> { - blocking(state.inner(), move |conn| { - let t = Instant::now(); - let page = query_works(conn, &query, "movie", &movie_work_select(), row_to_movie)?; - log::debug!( - "movies {:?}/{:?}: {} of {} in {:?}", - query.category_id, - query.sort, - page.items.len(), - page.total, - t.elapsed() - ); - Ok(page) - }) - .await -} - -#[tauri::command] -pub async fn series_list( - state: State<'_, AppState>, - query: MediaQuery, -) -> Result> { - blocking(state.inner(), move |conn| { - query_works(conn, &query, "series", SERIES_WORK_SELECT, row_to_series) - }) - .await -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct FacetValue { - pub value: String, - /// display name (collections: the provider category) - pub label: String, - /// works, not copies - pub count: i64, - /// collections: service/language group they are shown under - pub group: Option, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Facets { - pub total: i64, - pub service: Vec, - pub genre: Vec, - pub language: Vec, - pub quality: Vec, - pub decade: Vec, - pub collection: Vec, - /// from TMDB: original language, movie collections, TV networks - pub original: Vec, - pub franchise: Vec, - pub network: Vec, -} - -/// Everything the Movies / Series browse panel offers, with work counts. -/// Facet values with the number of works each would show, given the rest -/// of `query` (its other facets, favorites, text filter). -#[tauri::command] -pub async fn work_facets( - state: State<'_, AppState>, - kind: String, - query: Option, -) -> Result { - if kind != "movie" && kind != "series" { - return Err(Error::msg(format!("no facets for {kind}"))); - } - blocking(state.inner(), move |conn| { - let t = Instant::now(); - let f = facets_for(conn, &kind, &query.unwrap_or_default())?; - log::debug!("{kind} facets in {:?}", t.elapsed()); - Ok(f) - }) - .await -} - -pub fn facets_for(conn: &Connection, kind: &str, q: &MediaQuery) -> Result { - let show_adult = settings::get_bool(conn, "content.showAdult"); - let (where_sql, args) = work_filters(conn, q, kind, None)?; - let total: i64 = conn - .prepare_cached(&format!("SELECT COUNT(*) FROM work w WHERE {where_sql}"))? - .query_row(params_from_iter(args.iter()), |r| r.get(0))?; - let count = |facet: Option<&str>| -> Result> { - let (where_sql, args) = work_filters(conn, q, kind, facet)?; - let only = facet - .map(|f| format!("AND f.facet = '{f}'")) - .unwrap_or_default(); - Ok(conn - .prepare_cached(&format!( - "SELECT f.facet, f.value, COUNT(*) FROM work_facet f - JOIN work w ON w.kind = f.kind AND w.key = f.key - WHERE f.kind = ?1 {only} AND {where_sql} - GROUP BY f.facet, f.value" - ))? - .query_map(params_from_iter(args.iter()), |r| { - Ok((r.get(0)?, r.get(1)?, r.get(2)?)) - })? - .collect::>()?) - }; - let narrowed = q.favorites - || q.source_id.is_some() - || !q.facets.is_empty() - || q.q.as_deref().is_some_and(|t| !t.trim().is_empty()); - let rows = if narrowed { - // each facet counted without its own selection (FACETS are fixed names) - let mut rows = Vec::new(); - for f in FACETS { - rows.extend(count(Some(f))?); - } - rows - } else { - count(None)? - }; - let mut out = Facets { - total, - service: vec![], - genre: vec![], - language: vec![], - quality: vec![], - decade: vec![], - collection: vec![], - original: vec![], - franchise: vec![], - network: vec![], - }; - // provider categories behind the collection values - let cats: std::collections::HashMap = conn - .prepare_cached( - "SELECT source_id, id, name, position, adult FROM category WHERE kind = ?1", - )? - .query_map([kind], |r| { - let sid: i64 = r.get(0)?; - let id: String = r.get(1)?; - Ok(( - format!("{sid}:{id}"), - (r.get(2)?, sid, r.get(3)?, r.get(4)?), - )) - })? - .collect::>()?; - let mut collections: Vec<(i64, i64, FacetValue)> = Vec::new(); - for (facet, value, count) in rows { - let label = value.clone(); - let fv = FacetValue { - value, - label, - count, - group: None, - }; - match facet.as_str() { - "service" => out.service.push(fv), - "genre" => out.genre.push(fv), - "language" => out.language.push(fv), - "quality" => out.quality.push(fv), - "decade" => out.decade.push(fv), - "original" => out.original.push(fv), - "franchise" => out.franchise.push(fv), - "network" => out.network.push(fv), - "collection" => { - if let Some((name, sid, pos, adult)) = cats.get(&fv.value) - && (show_adult || !adult) - { - let v = crate::works::variant::parse(None, Some(name)); - let group = v.service.or(v.language).unwrap_or("Other").to_owned(); - let label = crate::names::display_category(name); - collections.push(( - *sid, - *pos, - FacetValue { - label, - group: Some(group), - ..fv - }, - )); - } - } - _ => {} - } - } - let by_count = |v: &mut Vec| { - v.sort_by(|a, b| b.count.cmp(&a.count).then(a.label.cmp(&b.label))) - }; - by_count(&mut out.service); - by_count(&mut out.language); - by_count(&mut out.original); - by_count(&mut out.franchise); - by_count(&mut out.network); - out.genre.sort_by_key(|g| { - crate::works::genre::GENRES - .iter() - .position(|x| *x == g.value) - .unwrap_or(usize::MAX) - }); - const QUALITY: &[&str] = &["4K", "Dolby Vision", "Dolby Audio", "HEVC", "Blu-ray"]; - out.quality.sort_by_key(|q| { - QUALITY - .iter() - .position(|x| *x == q.value) - .unwrap_or(usize::MAX) - }); - // newest decade first, "Older" last - out.decade.sort_by(|a, b| { - let key = |v: &str| { - if v == "Older" { - 0 - } else { - v.trim_end_matches('s').parse::().unwrap_or(0) - } - }; - key(&b.value).cmp(&key(&a.value)) - }); - collections.sort_by_key(|(sid, pos, _)| (*sid, *pos)); - out.collection = collections.into_iter().map(|(_, _, f)| f).collect(); - Ok(out) -} - -// --------------------------------------------------------------- details - -#[derive(Debug, Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TechInfo { - pub codec: Option, - pub width: Option, - pub height: Option, - pub hdr: bool, - pub channels: Option, - pub language: Option, -} - -fn tech(v: &Value) -> Option { - if !v.is_object() { - return None; - } - let transfer = str_of(&v["color_transfer"]).unwrap_or_default(); - Some(TechInfo { - codec: str_of(&v["codec_name"]), - width: i64_of(&v["width"]), - height: i64_of(&v["height"]), - hdr: transfer.contains("2084") || transfer.contains("hlg"), - channels: i64_of(&v["channels"]), - language: str_of(&v["tags"]["language"]), - }) -} - -/// Providers send backdrops as an array, a URL, or a stringified Python list. -fn first_url(v: &Value) -> Option { - match v { - Value::Array(a) => a.iter().find_map(first_url), - Value::String(s) => { - let s = s.trim(); - if s.starts_with('[') { - s.split(['\'', '"', ',', '[', ']', ' ']) - .find(|p| p.starts_with("http")) - .map(str::to_owned) - } else if s.starts_with("http") { - Some(s.to_owned()) - } else { - None - } - } - _ => None, - } -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct MovieDetail { - /// The copy that plays (see `versions`), titled/illustrated as its work. - #[serde(flatten)] - pub item: MovieItem, - pub plot: Option, - pub cast: Option, - pub director: Option, - pub genre: Option, - pub country: Option, - pub release_date: Option, - pub duration: Option, - pub backdrop: Option, - pub trailer: Option, - pub age_rating: Option, - pub video: Option, - pub audio: Option, - pub position: f64, - /// every provider copy of this movie, the playing one `selected` - pub versions: Vec, - /// some copies' provider details are still loading — ask again shortly - pub versions_pending: bool, - /// from TMDB, when a key is configured - pub tmdb: Option, -} - -struct CachedDetail { - json: Value, - fetched_at: i64, -} - -fn cached(conn: &Connection, source_id: i64, kind: &str, id: &str) -> Result> { - Ok(conn - .query_row( - "SELECT json, fetched_at FROM detail_cache WHERE source_id = ?1 AND kind = ?2 AND id = ?3", - params![source_id, kind, id], - |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)), - ) - .optional()? - .and_then(|(j, t)| serde_json::from_str(&j).ok().map(|json| CachedDetail { json, fetched_at: t }))) -} - -/// Provider detail JSON with a TTL cache; serves stale data when offline. -async fn provider_detail( - st: &AppState, - source_id: i64, - kind: &'static str, - id: &str, - ttl: i64, -) -> Result> { - let (src, cache) = { - let conn = st.db.read(); - ( - sources::load(&conn, source_id)?, - cached(&conn, source_id, kind, id)?, - ) - }; - if src.kind != SourceKind::Xtream { - return Ok(None); - } - if let Some(c) = &cache - && now() - c.fetched_at < ttl - { - return Ok(Some(c.json.clone())); - } - let fetched = match sources::xtream_for(&src, http_client(src.user_agent.as_deref())) { - Ok(x) if kind == "movie" => x.vod_info(id).await, - Ok(x) => x.series_info(id).await, - Err(e) => Err(e), - }; - match fetched { - Ok(v) if v.is_object() => { - let conn = st.db.write(); - conn.execute( - "INSERT OR REPLACE INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (?1, ?2, ?3, ?4, ?5)", - params![source_id, kind, id, v.to_string(), now()], - )?; - Ok(Some(v)) - } - Ok(_) => Ok(cache.map(|c| c.json)), - Err(e) => match cache { - Some(c) => { - log::warn!("{kind} {id}: using stale detail ({e})"); - Ok(Some(c.json)) - } - None => Err(e), - }, - } -} - -/// How long a detail page waits for the provider before showing what it has. -const DETAIL_DEADLINE: std::time::Duration = std::time::Duration::from_millis(2500); - -/// Provider details of several copies at once. This provider stalls for ~9 s -/// on single requests now and then, so the page doesn't wait for every copy: -/// what arrives within `DETAIL_DEADLINE` (or from the cache) is used, the rest -/// keeps loading in the background (into the cache) and is reported as -/// pending — the UI asks again. At least one copy is always waited for. -async fn details_of( - st: &AppState, - kind: &'static str, - copies: &[(i64, String)], - ttl: i64, -) -> (Vec>, bool) { - let mut handles: Vec>>>> = copies - .iter() - .map(|(sid, id)| { - let (st, sid, id) = (st.clone(), *sid, id.clone()); - Some(tokio::spawn(async move { - match provider_detail(&st, sid, kind, &id, ttl).await { - // M3U series: episodes come from the playlist - Ok(None) if kind == "series" => { - blocking(&st, move |conn| m3u_series_json(conn, sid, &id)).await - } - other => other, - } - })) - }) - .collect(); - let deadline = tokio::time::Instant::now() + DETAIL_DEADLINE; - let mut out: Vec> = vec![None; copies.len()]; - let mut finished = 0; - for (i, h) in handles.iter_mut().enumerate() { - let Some(handle) = h.as_mut() else { continue }; - if let Ok(joined) = tokio::time::timeout_at(deadline, handle).await { - *h = None; - finished += 1; - match joined { - Ok(Ok(v)) => out[i] = v, - Ok(Err(e)) => log::warn!("{kind} {}: no provider detail ({e})", copies[i].1), - Err(e) => log::warn!("{kind} {}: detail task failed ({e})", copies[i].1), - } - } - } - if finished == 0 { - // nothing within the deadline: take the first copy that answers - let pending: Vec<(usize, tokio::task::JoinHandle>>)> = handles - .iter_mut() - .enumerate() - .filter_map(|(i, h)| h.take().map(|h| (i, h))) - .collect(); - let (idx, futs): (Vec, Vec<_>) = pending.into_iter().unzip(); - if !futs.is_empty() { - let (res, pos, rest) = futures_util::future::select_all(futs).await; - if let Ok(Ok(v)) = res { - out[idx[pos]] = v; - } - // the others keep filling the cache in the background - drop(rest); - return (out, idx.len() > 1); - } - } - let pending = handles.iter().any(Option::is_some); - (out, pending) -} - -#[tauri::command] -pub async fn movie_detail( - state: State<'_, AppState>, - source_id: i64, - id: String, -) -> Result { - let st = state.inner().clone(); - let (members, pref, langs, work, facts, tracks) = { - let id = id.clone(); - blocking(&st, move |conn| { - let members = versions::members(conn, "movie", source_id, &id)?; - if members.is_empty() { - return Err(Error::NotFound(format!("movie {id}"))); - } - let key = versions::work_key(conn, "movie", source_id, &id)?; - let pref = match &key { - Some(k) => versions::preference(conn, "movie", k)?, - None => None, - }; - let work = match &key { - Some(k) => conn - .prepare_cached(&format!( - "{} WHERE w.kind = 'movie' AND w.key = ?1", - movie_work_select() - ))? - .query_row([k], row_to_movie) - .optional()?, - None => None, - }; - let facts = match (&key, &work) { - (Some(k), Some(w)) => crate::tmdb::facts_for(conn, "movie", k, &w.title, w.year)?, - _ => None, - }; - let tracks = members - .iter() - .map(|m| versions::tracks(conn, m.source_id, "movie", &m.id)) - .collect::>>()?; - Ok(( - members, - pref, - versions::language_prefs(conn), - work, - facts, - tracks, - )) - }) - .await? - }; - // provider details of every copy at once (cached for a week) - let copies: Vec<(i64, String)> = members - .iter() - .map(|m| (m.source_id, m.id.clone())) - .collect(); - let (details, pending) = details_of(&st, "movie", &copies, MOVIE_DETAIL_TTL).await; - let info_of = |i: usize| { - details[i] - .as_ref() - .map(|d| d["info"].clone()) - .unwrap_or(Value::Null) - }; - // a copy much shorter than the others is a trailer or cut off - let durations: Vec> = (0..members.len()) - .map(|i| i64_of(&info_of(i)["duration_secs"]).filter(|d| *d > 0)) - .collect(); - let longest = durations.iter().flatten().copied().max().unwrap_or(0); - let sel = versions::choose(&members, pref.as_ref(), &langs, |i| match durations[i] { - _ if versions::unavailable(&tracks[i]) => versions::BROKEN, - Some(d) if longest > 0 => d as f64 / longest as f64, - _ => 1.0, - }); - let chosen = members[sel].clone(); - let info = info_of(sel); - // missing fields from the other copies' details - let pick = |keys: &[&str]| -> Option { - first_str(&info, keys) - .or_else(|| (0..members.len()).find_map(|i| first_str(&info_of(i), keys))) - }; - - let mut item = { - let (sid, mid) = (chosen.source_id, chosen.id.clone()); - blocking(&st, move |conn| { - conn.prepare_cached(&format!( - "{MOVIE_SELECT} WHERE m.source_id = ?1 AND m.id = ?2" - ))? - .query_row(params![sid, mid], row_to_movie) - .optional()? - .ok_or_else(|| Error::NotFound(format!("movie {mid}"))) - }) - .await? - }; - if let Some(w) = &work { - item.title = w.title.clone(); - item.year = w.year.or(item.year); - item.poster = w.poster.clone().or(item.poster); - item.rating = w.rating.or(item.rating); - item.work = w.work.clone(); - item.favorite = w.favorite; - } - if item.poster.is_none() { - item.poster = pick(&["cover_big", "movie_image"]); - } - if item.rating.is_none() { - item.rating = f64_of(&info["rating"]).filter(|r| *r > 0.0); - } - // resume where any copy was left off (versions are the same film) - let latest = members - .iter() - .filter(|m| m.played_at > 0) - .max_by_key(|m| m.played_at); - let position = if chosen.position > 0.0 { - chosen.position - } else { - latest - .filter(|m| !m.watched) - .map(|m| m.position) - .unwrap_or(0.0) - }; - let multi_source = members.iter().any(|m| m.source_id != members[0].source_id); - let versions = members - .iter() - .enumerate() - .map(|(i, m)| { - let mut v = m.info(multi_source, i == sel); - let inf = info_of(i); - v.video = tech(&inf["video"]); - v.audio = tech(&inf["audio"]); - v.duration = i64_of(&inf["duration_secs"]).filter(|d| *d > 0); - v.tracks = tracks[i].clone(); - v - }) - .collect(); - let trailer = pick(&["youtube_trailer", "trailer"]).or_else(|| { - let conn = st.db.read(); - conn.query_row( - "SELECT trailer FROM movie WHERE source_id = ?1 AND id = ?2", - params![chosen.source_id, chosen.id], - |r| r.get(0), - ) - .ok() - .flatten() - }); - Ok(MovieDetail { - versions_pending: pending, - plot: pick(&["plot", "description"]), - cast: pick(&["cast", "actors"]), - director: pick(&["director"]), - genre: pick(&["genre"]), - country: pick(&["country"]), - release_date: pick(&["releasedate", "release_date"]), - duration: i64_of(&info["duration_secs"]).filter(|d| *d > 0), - backdrop: first_url(&info["backdrop_path"]) - .or_else(|| (0..members.len()).find_map(|i| first_url(&info_of(i)["backdrop_path"]))), - trailer, - age_rating: pick(&["mpaa_rating", "age"]), - video: tech(&info["video"]), - audio: tech(&info["audio"]), - position, - versions, - tmdb: facts, - item, - }) -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Episode { - pub id: String, - pub season: i64, - pub episode: i64, - pub title: String, - pub plot: Option, - pub duration: Option, - pub image: Option, - pub ext: Option, - pub rating: Option, - pub air_date: Option, - pub video: Option, - pub position: f64, - pub watched: bool, - /// the copy (series row) this episode plays from - pub source_id: i64, - pub series_id: String, - /// label of that copy when it isn't the selected version - pub version: Option, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Season { - pub season: i64, - pub name: String, - pub cover: Option, - pub overview: Option, - pub air_date: Option, - pub episodes: Vec, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Resume { - pub episode_id: String, - pub season: i64, - pub episode: i64, - pub position: f64, - pub started: bool, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SeriesDetail { - #[serde(flatten)] - pub item: SeriesItem, - pub plot: Option, - pub cast: Option, - pub director: Option, - pub release_date: Option, - pub trailer: Option, - pub seasons: Vec, - pub resume: Option, - /// every provider copy; seasons/episodes above are their union, each - /// episode from the selected copy when it has it - pub versions: Vec, - /// some copies' episode lists are still loading — ask again shortly - pub versions_pending: bool, - /// from TMDB, when a key is configured - pub tmdb: Option, -} - -/// Episodes of an M3U series (`episode` table) in the shape of Xtream's -/// `get_series_info` (`{"episodes": {"1": [...]}}`), so series pages, resume -/// and Up next treat both source kinds alike. -pub fn m3u_series_json( - conn: &Connection, - source_id: i64, - series_id: &str, -) -> Result> { - let mut stmt = conn.prepare_cached( - "SELECT id, season, episode, title, image, ext FROM episode - WHERE source_id = ?1 AND series_id = ?2 ORDER BY season, episode, position", - )?; - type Row = (String, i64, i64, String, Option, Option); - let rows: Vec = stmt - .query_map(params![source_id, series_id], |r| { - Ok(( - r.get(0)?, - r.get(1)?, - r.get(2)?, - r.get(3)?, - r.get(4)?, - r.get(5)?, - )) - })? - .collect::>()?; - if rows.is_empty() { - return Ok(None); - } - let mut seasons = serde_json::Map::new(); - for (id, season, episode, title, image, ext) in rows { - if let Value::Array(list) = seasons - .entry(season.to_string()) - .or_insert_with(|| Value::Array(Vec::new())) - { - list.push(serde_json::json!({ - "id": id, "episode_num": episode, "title": title, "container_extension": ext, - "info": { "movie_image": image }, - })); - } - } - Ok(Some(serde_json::json!({ "episodes": seasons }))) -} - -/// Provider `episodes` payload ({"1": [...]} or [[...]]) → seasons in order, -/// episodes sorted, without watch state. `source_id`/`series_id` name the -/// copy the payload belongs to. -fn parse_episodes( - detail: &Value, - series_title: &str, - source_id: i64, - series_id: &str, -) -> Vec<(i64, Vec)> { - let mut groups: Vec<(i64, Vec)> = match &detail["episodes"] { - Value::Object(map) => map - .iter() - .map(|(k, v)| { - ( - k.parse().unwrap_or(0), - v.as_array().cloned().unwrap_or_default(), - ) - }) - .collect(), - Value::Array(arr) => arr - .iter() - .enumerate() - .map(|(i, v)| { - let eps = v.as_array().cloned().unwrap_or_default(); - let n = eps - .first() - .and_then(|e| i64_of(&e["season"])) - .unwrap_or(i as i64 + 1); - (n, eps) - }) - .collect(), - _ => Vec::new(), - }; - groups.sort_by_key(|(n, _)| *n); - groups - .into_iter() - .map(|(n, eps)| { - let mut episodes: Vec = eps - .iter() - .enumerate() - .filter_map(|(i, e)| { - let eid = str_of(&e["id"])?; - let ei = &e["info"]; - let num = i64_of(&e["episode_num"]).unwrap_or(i as i64 + 1); - let raw_title = first_str(ei, &["name"]) - .or_else(|| str_of(&e["title"])) - .unwrap_or_default(); - Some(Episode { - title: episode_title(&raw_title, series_title, num), - season: n, - episode: num, - plot: first_str(ei, &["plot", "overview"]), - duration: i64_of(&ei["duration_secs"]).filter(|d| *d > 0), - image: first_str(ei, &["movie_image", "cover_big"]), - ext: str_of(&e["container_extension"]), - rating: f64_of(&ei["rating"]).filter(|r| *r > 0.0), - air_date: first_str(ei, &["releasedate", "air_date"]), - video: tech(&ei["video"]), - position: 0.0, - watched: false, - source_id, - series_id: series_id.to_owned(), - version: None, - id: eid, - }) - }) - .collect(); - episodes.sort_by_key(|e| e.episode); - (n, episodes) - }) - .collect() -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct UpNext { - pub series: SeriesItem, - pub episode: Episode, -} - -/// Next episode for series whose most recently watched episode was finished -/// (partially watched ones already show in "Continue watching"). -#[tauri::command] -pub async fn up_next(state: State<'_, AppState>, limit: Option) -> Result> { - let limit = limit.unwrap_or(20).clamp(1, 50) as usize; - blocking(state.inner(), move |conn| up_next_rows(conn, limit)).await -} - -/// Episodes of one series copy from what is stored locally (the provider -/// detail cache, or the playlist for M3U series) — no network. -pub fn stored_episodes( - conn: &Connection, - source_id: i64, - series_id: &str, - title: &str, -) -> Result)>> { - let json = match cached(conn, source_id, "series", series_id)? { - Some(d) => d.json, - None => match m3u_series_json(conn, source_id, series_id)? { - Some(v) => v, - None => return Ok(Vec::new()), - }, - }; - Ok(parse_episodes(&json, title, source_id, series_id)) -} - -/// Union of all copies' episodes keyed by (season, episode), each taken from -/// the first copy in `order` that has it. -fn union_episodes( - per_copy: &[Vec<(i64, Vec)>], - order: &[usize], -) -> BTreeMap<(i64, i64), (usize, Episode)> { - let mut out = BTreeMap::new(); - for &i in order { - for (_, eps) in &per_copy[i] { - for e in eps { - out.entry((e.season, e.episode)) - .or_insert_with(|| (i, e.clone())); - } - } - } - out -} - -fn up_next_rows(conn: &Connection, limit: usize) -> Result> { - // Latest episode per show — all copies of a show count as one. Timestamps - // are whole seconds, so ties (two episodes marked within a second) go to - // the furthest episode. - type Latest = (i64, String, String, bool, Option, Option); - let latest: Vec = conn - .prepare_cached( - "SELECT source_id, series_id, item_id, watched, season, episode FROM ( - SELECT h.source_id, h.series_id, h.item_id, h.watched, h.season, h.episode, h.updated_at, - ROW_NUMBER() OVER ( - PARTITION BY COALESCE(s.work_key, 'item:' || h.source_id || ':' || h.series_id) - ORDER BY h.updated_at DESC, h.season DESC, h.episode DESC) AS n - FROM history h - LEFT JOIN series s ON s.source_id = h.source_id AND s.id = h.series_id - WHERE h.kind = 'episode' AND h.series_id IS NOT NULL) - WHERE n = 1 ORDER BY updated_at DESC LIMIT 60", - )? - .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))? - .collect::>()?; - let mut out = Vec::new(); - for (sid, series_id, last_id, watched, season, episode) in latest { - if !watched || out.len() >= limit { - continue; - } - let members = versions::members(conn, "series", sid, &series_id)?; - if members.is_empty() { - continue; - } - let key = versions::work_key(conn, "series", sid, &series_id)?; - let series = match &key { - Some(k) => conn - .prepare_cached(&format!( - "{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1" - ))? - .query_row([k], row_to_series) - .optional()?, - None => conn - .prepare_cached(&format!( - "{SERIES_SELECT} WHERE s.source_id = ?1 AND s.id = ?2" - ))? - .query_row(params![sid, series_id], row_to_series) - .optional()?, - }; - let Some(series) = series else { continue }; - let per_copy: Vec<_> = members - .iter() - .map(|m| stored_episodes(conn, m.source_id, &m.id, &series.title)) - .collect::>()?; - // continue in the copy that was being watched, then the chosen one - let watching = members - .iter() - .position(|m| m.source_id == sid && m.id == series_id) - .unwrap_or(0); - let pref = match &key { - Some(k) => versions::preference(conn, "series", k)?, - None => None, - }; - let chosen = versions::choose( - &members, - pref.as_ref(), - &versions::language_prefs(conn), - |_| 1.0, - ); - let mut order = vec![watching, chosen]; - order.extend(0..members.len()); - order.dedup(); - let union = union_episodes(&per_copy, &order); - // where we are: the history row's numbers, else find its episode id - let here = match (season, episode) { - (Some(s), Some(e)) => Some((s, e)), - _ => union - .iter() - .find(|(_, (_, e))| e.id == last_id) - .map(|(k, _)| *k), - }; - let Some(here) = here else { continue }; - let Some((_, (copy, next))) = union - .range((here.0, here.1 + 1)..) - .find(|((s, _), _)| *s > 0) - else { - continue; - }; - let mut next = next.clone(); - if *copy != chosen { - next.version = Some(members[*copy].variant.label.clone()); - } - let seen: bool = conn - .query_row( - "SELECT MAX(h.watched) FROM history h - LEFT JOIN series s ON s.source_id = h.source_id AND s.id = h.series_id - WHERE h.kind = 'episode' AND h.season = ?1 AND h.episode = ?2 - AND ((?3 IS NOT NULL AND s.work_key = ?3) OR (h.source_id = ?4 AND h.series_id = ?5))", - params![next.season, next.episode, key, sid, series_id], - |r| r.get::<_, Option>(0), - )? - .unwrap_or(false); - if !seen { - out.push(UpNext { - series, - episode: next, - }); - } - } - Ok(out) -} - -/// "Deadly Ties - S01E01" / "S01E01 - Pilot" → "Pilot" or "Episode 1". -fn episode_title(raw: &str, series_title: &str, n: i64) -> String { - static SXXEXX: std::sync::LazyLock = - std::sync::LazyLock::new(|| regex::Regex::new(r"(?i)\bS\d{1,3}\s*E\d{1,4}\b").unwrap()); - let mut t = raw.trim().to_owned(); - if let Some(m) = SXXEXX.find(&t) { - let after = t[m.end()..] - .trim() - .trim_start_matches(['-', ':', '.', '|']) - .trim() - .to_owned(); - let before = t[..m.start()] - .trim() - .trim_end_matches(['-', ':', '.', '|']) - .trim() - .to_owned(); - t = if !after.is_empty() { - after - } else if !before.is_empty() - && !before.eq_ignore_ascii_case(series_title) - && !series_title.contains(&before) - { - before - } else { - String::new() - }; - } - if t.is_empty() { - format!("Episode {n}") - } else { - t - } -} - -/// Long-form series fields that list rows don't carry. -struct SeriesText { - plot: Option, - cast: Option, - director: Option, - release: Option, - trailer: Option, -} - -/// Watch state of one episode (of any copy of the show). -struct Watched { - source_id: i64, - id: String, - season: Option, - episode: Option, - position: f64, - watched: bool, - at: i64, -} - -#[tauri::command] -pub async fn series_detail( - state: State<'_, AppState>, - source_id: i64, - id: String, -) -> Result { - let st = state.inner().clone(); - let (members, pref, langs, work, text, history, facts) = { - let id = id.clone(); - blocking(&st, move |conn| { - let members = versions::members(conn, "series", source_id, &id)?; - if members.is_empty() { - return Err(Error::NotFound(format!("series {id}"))); - } - let key = versions::work_key(conn, "series", source_id, &id)?; - let pref = match &key { - Some(k) => versions::preference(conn, "series", k)?, - None => None, - }; - let work = match &key { - Some(k) => conn - .prepare_cached(&format!("{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1"))? - .query_row([k], row_to_series) - .optional()?, - None => None, - }; - let work = match work { - Some(w) => w, - None => conn - .prepare_cached(&format!("{SERIES_SELECT} WHERE s.source_id = ?1 AND s.id = ?2"))? - .query_row(params![source_id, id], row_to_series) - .optional()? - .ok_or_else(|| Error::NotFound(format!("series {id}")))?, - }; - // long texts: the requested copy, else any copy that has them - let text = conn.query_row( - "SELECT (SELECT plot FROM series x WHERE x.work_key IS s.work_key AND x.plot IS NOT NULL - ORDER BY x.source_id = s.source_id AND x.id = s.id DESC LIMIT 1), - COALESCE(s.cast_list, (SELECT cast_list FROM series x WHERE x.work_key = s.work_key AND x.cast_list IS NOT NULL LIMIT 1)), - COALESCE(s.director, (SELECT director FROM series x WHERE x.work_key = s.work_key AND x.director IS NOT NULL LIMIT 1)), - COALESCE(s.release_date, (SELECT release_date FROM series x WHERE x.work_key = s.work_key AND x.release_date IS NOT NULL LIMIT 1)), - COALESCE(s.trailer, (SELECT trailer FROM series x WHERE x.work_key = s.work_key AND x.trailer IS NOT NULL LIMIT 1)) - FROM series s WHERE s.source_id = ?1 AND s.id = ?2", - params![source_id, id], - |r| { - Ok(SeriesText { - plot: r.get(0)?, - cast: r.get(1)?, - director: r.get(2)?, - release: r.get(3)?, - trailer: r.get(4)?, - }) - }, - )?; - let history: Vec = conn - .prepare_cached( - "SELECT h.source_id, h.item_id, h.season, h.episode, h.position, h.watched, h.updated_at - FROM history h - LEFT JOIN series s ON s.source_id = h.source_id AND s.id = h.series_id - WHERE h.kind = 'episode' - AND ((?1 IS NOT NULL AND s.work_key = ?1) OR (h.source_id = ?2 AND h.series_id = ?3))", - )? - .query_map(params![key, source_id, id], |r| { - Ok(Watched { - source_id: r.get(0)?, - id: r.get(1)?, - season: r.get(2)?, - episode: r.get(3)?, - position: r.get(4)?, - watched: r.get(5)?, - at: r.get(6)?, - }) - })? - .collect::>()?; - let facts = match &key { - Some(k) => crate::tmdb::facts_for(conn, "series", k, &work.title, work.year)?, - None => None, - }; - Ok((members, pref, versions::language_prefs(conn), work, text, history, facts)) - }) - .await? - }; - - // every copy's episodes at once (cached for 12 h) - let copies: Vec<(i64, String)> = members - .iter() - .map(|m| (m.source_id, m.id.clone())) - .collect(); - let (details, pending) = details_of(&st, "series", &copies, SERIES_DETAIL_TTL).await; - let details: Vec = details - .into_iter() - .map(|d| d.unwrap_or(Value::Null)) - .collect(); - let per_copy: Vec)>> = members - .iter() - .zip(&details) - .map(|(m, d)| parse_episodes(d, &work.title, m.source_id, &m.id)) - .collect(); - let counts: Vec = per_copy - .iter() - .map(|seasons| { - seasons - .iter() - .filter(|(n, _)| *n > 0) - .map(|(_, e)| e.len()) - .sum() - }) - .collect(); - let most = counts.iter().copied().max().unwrap_or(0).max(1); - // tracks seen in each copy (the first of its episodes with any) - let tracks: Vec> = { - let ids: Vec<(i64, Vec)> = per_copy - .iter() - .zip(&members) - .map(|(seasons, m)| { - ( - m.source_id, - seasons - .iter() - .flat_map(|(_, e)| e.iter().map(|e| e.id.clone())) - .take(40) - .collect(), - ) - }) - .collect(); - blocking(&st, move |conn| { - ids.iter() - .map(|(sid, eps)| { - for e in eps { - if let Some(t) = versions::tracks(conn, *sid, "episode", e)? { - return Ok(Some(t)); - } - } - Ok(None) - }) - .collect::>>() - }) - .await? - }; - let sel = versions::choose(&members, pref.as_ref(), &langs, |i| { - if versions::unavailable(&tracks[i]) { - versions::BROKEN - } else { - counts[i] as f64 / most as f64 - } - }); - - // selected copy first, then the others by their own fit - let mut order: Vec = (0..members.len()).collect(); - order.sort_by_key(|&i| { - let m = &members[i]; - ( - i != sel, - -(crate::works::variant::affinity(&m.variant, &langs) - + crate::works::variant::score(&m.variant)), - ) - }); - let union = union_episodes(&per_copy, &order); - - // history rows → (season, episode): by the episode id in its copy, else the stored numbers - let number_of = |w: &Watched| -> Option<(i64, i64)> { - per_copy - .iter() - .flatten() - .flat_map(|(_, eps)| eps) - .find(|e| e.source_id == w.source_id && e.id == w.id) - .map(|e| (e.season, e.episode)) - .or(match (w.season, w.episode) { - (Some(s), Some(e)) => Some((s, e)), - _ => None, - }) - }; - let mut state_of: HashMap<(i64, i64), &Watched> = HashMap::new(); - for w in &history { - if let Some(k) = number_of(w) - && state_of.get(&k).is_none_or(|prev| w.at > prev.at) - { - state_of.insert(k, w); - } - } - - let mut seasons: Vec = Vec::new(); - for ((s_no, _), (copy, e)) in &union { - let mut e = e.clone(); - if let Some(w) = state_of.get(&(e.season, e.episode)) { - e.position = w.position; - e.watched = w.watched; - } - if *copy != sel { - e.version = Some(members[*copy].variant.label.clone()); - } - match seasons.last_mut() { - Some(last) if last.season == *s_no => last.episodes.push(e), - _ => { - // season names/art from the selected copy, else any copy - let meta = order.iter().find_map(|&i| { - details[i]["seasons"].as_array().and_then(|a| { - a.iter() - .find(|m| i64_of(&m["season_number"]) == Some(*s_no)) - }) - }); - seasons.push(Season { - season: *s_no, - name: meta.and_then(|m| str_of(&m["name"])).unwrap_or_else(|| { - if *s_no == 0 { - "Specials".into() - } else { - format!("Season {s_no}") - } - }), - cover: meta.and_then(|m| first_str(m, &["cover_big", "cover"])), - overview: meta.and_then(|m| str_of(&m["overview"])), - air_date: meta.and_then(|m| str_of(&m["air_date"])), - episodes: vec![e], - }); - } - } - } - - // Resume: the most recent unfinished episode, else the one after the - // most recently finished, else S1E1 — across all copies. - let flat: Vec<&Episode> = seasons - .iter() - .filter(|s| s.season > 0) - .flat_map(|s| &s.episodes) - .collect(); - let latest = history - .iter() - .filter_map(|w| number_of(w).map(|k| (k, w))) - .max_by_key(|(_, w)| w.at); - let resume = match latest { - Some((k, w)) if !w.watched => { - flat.iter() - .find(|e| (e.season, e.episode) == k) - .map(|e| Resume { - episode_id: e.id.clone(), - season: e.season, - episode: e.episode, - position: w.position, - started: true, - }) - } - Some((k, _)) => flat - .iter() - .position(|e| (e.season, e.episode) == k) - .and_then(|i| flat.get(i + 1)) - .map(|e| Resume { - episode_id: e.id.clone(), - season: e.season, - episode: e.episode, - position: 0.0, - started: true, - }), - None => None, - } - .or_else(|| { - flat.first().map(|e| Resume { - episode_id: e.id.clone(), - season: e.season, - episode: e.episode, - position: 0.0, - started: false, - }) - }); - - let multi_source = members.iter().any(|m| m.source_id != members[0].source_id); - let versions: Vec = members - .iter() - .enumerate() - .map(|(i, m)| { - let mut v = m.info(multi_source, i == sel); - v.seasons = per_copy[i] - .iter() - .filter(|(n, e)| *n > 0 && !e.is_empty()) - .map(|(n, _)| *n) - .collect(); - v.episodes = counts[i] as i64; - let first = per_copy[i].iter().flat_map(|(_, e)| e).next(); - v.video = first.and_then(|e| e.video.clone()); - v.duration = first.and_then(|e| e.duration); - v.tracks = tracks[i].clone(); - v - }) - .collect(); - - let mut item = work; - if item.backdrop.is_none() { - item.backdrop = order - .iter() - .find_map(|&i| first_url(&details[i]["info"]["backdrop_path"])); - } - let info = &details[sel]["info"]; - Ok(SeriesDetail { - versions_pending: pending, - plot: text.plot.or_else(|| str_of(&info["plot"])), - cast: text.cast.or_else(|| str_of(&info["cast"])), - director: text.director.or_else(|| str_of(&info["director"])), - release_date: text - .release - .or_else(|| first_str(info, &["releaseDate", "release_date"])), - trailer: text.trailer.or_else(|| str_of(&info["youtube_trailer"])), - seasons, - resume, - versions, - tmdb: facts, - item, - }) -} - -// ------------------------------------------------------------------- EPG - -#[tauri::command] -pub async fn epg_channel( - state: State<'_, AppState>, - source_id: i64, - channel_id: String, - from: i64, - to: i64, -) -> Result> { - let st = state.inner().clone(); - let (epg_id, rows) = { - let channel_id = channel_id.clone(); - blocking(&st, move |conn| { - let epg_id: Option = conn - .query_row( - "SELECT COALESCE(c.epg_id, g.epg_id) FROM channel c LEFT JOIN channel_group g ON g.key = c.group_key - WHERE c.source_id = ?1 AND c.id = ?2", - params![source_id, channel_id], - |r| r.get(0), - ) - .optional()? - .flatten(); - let rows = match &epg_id { - Some(e) => epg::programmes(conn, source_id, e, from, to)?, - None => Vec::new(), - }; - Ok((epg_id, rows)) - }) - .await? - }; - if !rows.is_empty() || epg_id.is_none() { - return Ok(rows); - } - // Fall back to the panel's short EPG (base64 encoded fields). - let src = { - let conn = st.db.read(); - sources::load(&conn, source_id)? - }; - if src.kind != SourceKind::Xtream { - return Ok(rows); - } - let Ok(x) = sources::xtream_for(&src, http_client(src.user_agent.as_deref())) else { - return Ok(rows); - }; - let v = match x.short_epg(&channel_id, 24).await { - Ok(v) => v, - Err(e) => { - log::debug!("short epg {channel_id}: {e}"); - return Ok(rows); - } - }; - let b64 = |v: &Value| -> Option { - let s = str_of(v)?; - base64::engine::general_purpose::STANDARD - .decode(s.as_bytes()) - .ok() - .map(|b| String::from_utf8_lossy(&b).trim().to_owned()) - .or(Some(s)) - }; - let list = v["epg_listings"].as_array().cloned().unwrap_or_default(); - Ok(list - .iter() - .filter_map(|p| { - let start = i64_of(&p["start_timestamp"])?; - let stop = i64_of(&p["stop_timestamp"])?; - (stop > from && start < to).then(|| ProgrammeRow { - epg_id: epg_id.clone().unwrap_or_default(), - start, - stop, - title: b64(&p["title"]).unwrap_or_default(), - subtitle: None, - description: b64(&p["description"]), - category: None, - episode: None, - icon: None, - }) - }) - .collect()) -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct GuideRow { - pub channel: ChannelItem, - pub programmes: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct GuideQuery { - #[serde(flatten)] - pub channels: ChannelQuery, - pub from: i64, - pub to: i64, -} - -/// Channels plus their programmes in a time window (TV guide grid). -#[tauri::command] -pub async fn epg_grid(state: State<'_, AppState>, query: GuideQuery) -> Result> { - blocking(state.inner(), move |conn| { - let page = query_channels(conn, &query.channels)?; - let mut items = Vec::with_capacity(page.items.len()); - for channel in page.items { - let programmes = match &channel.epg_id { - Some(e) => epg::programmes(conn, channel.source_id, e, query.from, query.to)?, - None => Vec::new(), - }; - items.push(GuideRow { - channel, - programmes, - }); - } - Ok(Page { - total: page.total, - items, - }) - }) - .await -} - -// ---------------------------------------------------------------- search - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SearchResults { - pub channels: Vec, - pub movies: Vec, - pub series: Vec, -} - -fn fts_query(q: &str) -> Option { - let tokens: Vec = q - .split(|c: char| !c.is_alphanumeric()) - .filter(|t| !t.is_empty()) - .map(|t| format!("\"{}\"*", t.replace('"', ""))) - .collect(); - (!tokens.is_empty()).then(|| tokens.join(" ")) -} - -#[tauri::command] -pub async fn search( - state: State<'_, AppState>, - q: String, - limit: Option, -) -> Result { - let limit = limit.unwrap_or(30).clamp(1, 200); - blocking(state.inner(), move |conn| { - let Some(fts) = fts_query(&q) else { - return Ok(SearchResults { channels: vec![], movies: vec![], series: vec![] }); - }; - let t = Instant::now(); - let show_adult = settings::get_bool(conn, "content.showAdult"); - let ids = |kind: &str| -> Result> { - let mut stmt = conn.prepare_cached( - "SELECT source_id, item_id FROM search WHERE search MATCH ?1 AND kind = ?2 ORDER BY rank LIMIT ?3", - )?; - let rows = stmt - .query_map(params![fts, kind, limit * 8], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))? - .collect::, _>>()?; - Ok(rows) - }; - let adult_ok = |table: &str, sid: i64, id: &str| -> bool { - show_adult - || conn - .query_row(&format!("SELECT adult FROM {table} WHERE source_id = ?1 AND id = ?2"), params![sid, id], |r| { - r.get::<_, bool>(0) - }) - .map(|a| !a) - .unwrap_or(false) - }; - // feeds of the same channel collapse into their group - let mut channels: Vec = Vec::new(); - let mut group_of = conn.prepare_cached("SELECT group_key FROM channel WHERE source_id = ?1 AND id = ?2")?; - for (sid, id) in ids("live")? { - if channels.len() as i64 >= limit { - break; - } - if !adult_ok("channel", sid, &id) { - continue; - } - let key: Option = group_of.query_row(params![sid, id], |r| r.get(0)).optional()?.flatten(); - if key.as_ref().is_some_and(|k| channels.iter().any(|c| c.group.as_ref().is_some_and(|g| &g.key == k))) { - continue; - } - let c = match &key { - Some(k) => channel_group_by_key(conn, k), - None => channel_by_id(conn, sid, &id), - }; - if let Ok(c) = c { - channels.push(c); - } - } - // copies of the same title collapse into their work - let works = |kind: &str| -> Result> { - let table = if kind == "movie" { "movie" } else { "series" }; - let mut key_of = conn.prepare_cached(&format!("SELECT work_key FROM {table} WHERE source_id = ?1 AND id = ?2"))?; - let mut keys: Vec = Vec::new(); - for (sid, id) in ids(kind)? { - if keys.len() as i64 >= limit { - break; - } - if !adult_ok(table, sid, &id) { - continue; - } - if let Some(Some(k)) = key_of.query_row(params![sid, id], |r| r.get::<_, Option>(0)).optional()? - && !keys.contains(&k) - { - keys.push(k); - } - } - Ok(keys) - }; - let mut movies = Vec::new(); - { - let mut stmt = conn.prepare_cached(&format!("{} WHERE w.kind = 'movie' AND w.key = ?1", movie_work_select()))?; - for key in works("movie")? { - if let Some(m) = stmt.query_row([key], row_to_movie).optional()? { - movies.push(m); - } - } - } - let mut series = Vec::new(); - { - let mut stmt = conn.prepare_cached(&format!("{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1"))?; - for key in works("series")? { - if let Some(s) = stmt.query_row([key], row_to_series).optional()? { - series.push(s); - } - } - } - log::debug!("search {q:?}: {}/{}/{} in {:?}", channels.len(), movies.len(), series.len(), t.elapsed()); - Ok(SearchResults { channels, movies, series }) - }) - .await -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn episode_titles() { - assert_eq!( - episode_title("Deadly Ties - S01E01", "Deadly Ties", 1), - "Episode 1" - ); - assert_eq!(episode_title("S01E02 - The Pilot", "X", 2), "The Pilot"); - assert_eq!(episode_title("The Pilot", "X", 2), "The Pilot"); - assert_eq!(episode_title("", "X", 3), "Episode 3"); - } - - #[test] - fn backdrop_variants() { - assert_eq!( - first_url(&Value::String("['https://a/b.jpg']".into())).as_deref(), - Some("https://a/b.jpg") - ); - assert_eq!( - first_url(&serde_json::json!(["https://c/d.jpg"])).as_deref(), - Some("https://c/d.jpg") - ); - assert_eq!(first_url(&Value::String("".into())), None); - } - - #[test] - fn fts_queries() { - assert_eq!(fts_query("bbc news").as_deref(), Some("\"bbc\"* \"news\"*")); - assert_eq!(fts_query(" \" ").as_deref(), None); - assert_eq!(fts_query("top-gun").as_deref(), Some("\"top\"* \"gun\"*")); - } - - #[test] - fn badge_joining() { - assert_eq!( - split_badges("4K DOLBY VISION HEVC".into()), - vec!["4K", "DOLBY VISION", "HEVC"] - ); - } - - #[test] - fn m3u_series_read_like_xtream_ones() { - let c = crate::db::test_conn(); - c.execute("INSERT INTO series (source_id, id, name, title, position) VALUES (1, 'sh', 'Show', 'Show', 0)", []) - .unwrap(); - for (id, season, ep, title) in [ - ("a", 1, 2, "Second"), - ("b", 1, 1, ""), - ("c", 2, 1, "Premiere"), - ] { - c.execute( - "INSERT INTO episode (source_id, series_id, id, season, episode, title, url, ext, position) - VALUES (1, 'sh', ?1, ?2, ?3, ?4, 'http://h/x.mkv', 'mkv', 0)", - params![id, season, ep, title], - ) - .unwrap(); - } - let json = m3u_series_json(&c, 1, "sh").unwrap().unwrap(); - let seasons = parse_episodes(&json, "Show", 1, "sh"); - type Shape = Vec<(i64, Vec<(String, i64, String)>)>; - let shape: Shape = seasons - .into_iter() - .map(|(n, eps)| { - ( - n, - eps.into_iter() - .map(|e| (e.id, e.episode, e.title)) - .collect(), - ) - }) - .collect(); - assert_eq!( - shape, - vec![ - ( - 1, - vec![ - ("b".into(), 1, "Episode 1".into()), - ("a".into(), 2, "Second".into()) - ] - ), - (2, vec![("c".into(), 1, "Premiere".into())]), - ] - ); - assert!(m3u_series_json(&c, 1, "missing").unwrap().is_none()); - // Up next works without a provider detail cache - c.execute( - "INSERT INTO history (source_id, kind, item_id, series_id, season, episode, title, watched, updated_at) - VALUES (1, 'episode', 'a', 'sh', 1, 2, 'Show', 1, 100)", - [], - ) - .unwrap(); - let next: Vec = up_next_rows(&c, 20) - .unwrap() - .into_iter() - .map(|u| u.episode.id) - .collect(); - assert_eq!(next, vec!["c"]); - } - - /// Two copies of one show: the Nordic one only has season 5. - fn two_copy_show(c: &Connection) { - for (cat, name) in [("ap", "APPLE+ SERIES"), ("sc", "NORDIC SERIES")] { - c.execute("INSERT INTO category (source_id, kind, id, name, title, position) VALUES (1, 'series', ?1, ?2, ?2, 0)", params![cat, name]) - .unwrap(); - } - for (id, tag, cat) in [("full", "A+", "ap"), ("s5", "SC", "sc")] { - c.execute( - "INSERT INTO series (source_id, id, name, title, tag, year, tmdb, category_id, position) - VALUES (1, ?1, 'x', 'Show', ?2, 2019, '777', ?3, 0)", - params![id, tag, cat], - ) - .unwrap(); - } - let eps = |prefix: &str, seasons: std::ops::RangeInclusive| { - let mut map = serde_json::Map::new(); - for season in seasons { - let list: Vec = (1..=3) - .map(|n| serde_json::json!({"id": format!("{prefix}{season}{n}"), "episode_num": n, "title": format!("E{n}")})) - .collect(); - map.insert(season.to_string(), Value::Array(list)); - } - serde_json::json!({ "episodes": map }).to_string() - }; - for (id, json) in [("full", eps("f", 1..=5)), ("s5", eps("n", 5..=5))] { - c.execute("INSERT INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (1, 'series', ?1, ?2, 0)", params![id, json]) - .unwrap(); - } - crate::works::rebuild(c).unwrap(); - } - - fn finish(c: &Connection, series: &str, ep_id: &str, season: i64, episode: i64, at: i64) { - c.execute( - "INSERT OR REPLACE INTO history (source_id, kind, item_id, series_id, season, episode, title, watched, updated_at) - VALUES (1, 'episode', ?1, ?2, ?3, ?4, 'Show', 1, ?5)", - params![ep_id, series, season, episode, at], - ) - .unwrap(); - } - - #[test] - fn up_next_follows_a_show_across_its_copies() { - let c = crate::db::test_conn(); - two_copy_show(&c); - let next = |c: &Connection| -> Vec<(String, String, i64, i64, Option)> { - up_next_rows(c, 20) - .unwrap() - .into_iter() - .map(|u| { - ( - u.episode.series_id, - u.episode.id, - u.episode.season, - u.episode.episode, - u.episode.version, - ) - }) - .collect() - }; - // one entry per show, continuing in the copy being watched - finish(&c, "full", "f11", 1, 1, 100); - assert_eq!(next(&c), vec![("full".into(), "f12".into(), 1, 2, None)]); - // switched to the Nordic copy for season 5: continue there - finish(&c, "s5", "n51", 5, 1, 200); - assert_eq!(next(&c), vec![("s5".into(), "n52".into(), 5, 2, None)]); - // the next one was already seen in the other copy: nothing to offer - finish(&c, "full", "f52", 5, 2, 150); - assert!(next(&c).is_empty()); - // after the Nordic copy's last episode there is nothing more anywhere - finish(&c, "s5", "n53", 5, 3, 300); - assert!(next(&c).is_empty()); - } - - #[test] - fn up_next_takes_missing_episodes_from_another_copy() { - let c = crate::db::test_conn(); - two_copy_show(&c); - // chose the Nordic copy (season 5 only) but watched S4E3 in the full one - c.execute("INSERT INTO work_pref (kind, key, source_id, item_id, updated_at) VALUES ('series', 'tmdb:777', 1, 's5', 0)", []) - .unwrap(); - finish(&c, "full", "f43", 4, 3, 100); - let u = up_next_rows(&c, 20).unwrap(); - assert_eq!(u.len(), 1); - // S5E1 continues in the copy that was being watched - assert_eq!( - ( - u[0].episode.id.as_str(), - u[0].episode.season, - u[0].episode.episode - ), - ("f51", 5, 1) - ); - assert_eq!(u[0].series.title, "Show"); - assert_eq!(u[0].series.work.version_count, 2); - } - - #[test] - fn a_country_lists_its_guide_channels_first() { - let c = crate::db::test_conn(); - c.execute( - "INSERT INTO category (source_id, kind, id, name, title, region, position) - VALUES (1, 'live', 'ent', 'UK| ENTERTAINMENT', 'ENTERTAINMENT', 'UK', 0)", - [], - ) - .unwrap(); - // the provider lists its 24/7 feeds (no guide data) before BBC One - for (id, title, epg, pos) in [ - ("fast", "BAYWATCH", None, 0), - ("bbc1", "BBC ONE", Some("BBCOne.uk"), 1), - ] { - c.execute( - "INSERT INTO channel (source_id, id, name, title, category_id, epg_id, position) - VALUES (1, ?1, ?2, ?2, 'ent', ?3, ?4)", - params![id, title, epg, pos], - ) - .unwrap(); - } - crate::works::rebuild(&c).unwrap(); - let titles = |q: ChannelQuery| -> Vec { - query_channels(&c, &q) - .unwrap() - .items - .into_iter() - .map(|i| i.title) - .collect() - }; - let uk = ChannelQuery { - grouped: true, - country: Some("UK".into()), - ..Default::default() - }; - assert_eq!(titles(uk), ["BBC ONE", "BAYWATCH"]); - let genre = ChannelQuery { - grouped: true, - genre: Some("Entertainment".into()), - ..Default::default() - }; - assert_eq!(titles(genre), ["BBC ONE", "BAYWATCH"]); - } - - #[test] - fn works_list_one_row_per_title_and_filter_through_copies() { - let c = crate::db::test_conn(); - two_copy_show(&c); - let q = |q: MediaQuery| { - query_works(&c, &q, "series", SERIES_WORK_SELECT, row_to_series).unwrap() - }; - let all = q(MediaQuery::default()); - assert_eq!((all.total, all.items[0].work.version_count), (1, 2)); - // a category of either copy finds the work - let nordic = q(MediaQuery { - source_id: Some(1), - category_id: Some("sc".into()), - ..Default::default() - }); - assert_eq!(nordic.total, 1); - let by_service = q(MediaQuery { - facets: vec![FacetFilter { - facet: "service".into(), - value: "Apple TV+".into(), - }], - ..Default::default() - }); - assert_eq!(by_service.total, 1); - let none = q(MediaQuery { - facets: vec![FacetFilter { - facet: "service".into(), - value: "Netflix".into(), - }], - ..Default::default() - }); - assert_eq!(none.total, 0); - let bad = query_works( - &c, - &MediaQuery { - facets: vec![FacetFilter { - facet: "x; DROP".into(), - value: "1".into(), - }], - ..Default::default() - }, - "series", - SERIES_WORK_SELECT, - row_to_series, - ); - assert!(bad.is_err()); - let f = facets_for(&c, "series", &MediaQuery::default()).unwrap(); - assert_eq!(f.total, 1); - assert!( - f.service - .iter() - .any(|v| v.value == "Apple TV+" && v.count == 1) - ); - assert!( - f.collection - .iter() - .any(|v| v.value == "1:sc" && v.group.as_deref() == Some("Nordic")) - ); - assert!(f.collection.iter().any(|v| v.label == "Apple+ Series")); - // counts follow the other filters but not the facet's own choice - c.execute( - "INSERT INTO series (source_id, id, name, title, tag, year, tmdb, category_id, position) - VALUES (1, 'nf', 'x', 'Other', 'NF', 2001, '888', 'ap', 0)", - [], - ) - .unwrap(); - crate::works::rebuild(&c).unwrap(); - let netflix = MediaQuery { - facets: vec![FacetFilter { - facet: "service".into(), - value: "Netflix".into(), - }], - ..Default::default() - }; - let f = facets_for(&c, "series", &netflix).unwrap(); - assert_eq!(f.total, 1); - let count = - |v: &[FacetValue], value: &str| v.iter().find(|x| x.value == value).map(|x| x.count); - assert_eq!( - (count(&f.service, "Netflix"), count(&f.service, "Apple TV+")), - (Some(1), Some(1)) - ); - assert_eq!( - (count(&f.decade, "2000s"), count(&f.decade, "2010s")), - (Some(1), None) - ); - } - - #[test] - fn up_next_follows_the_latest_finished_episode() { - let c = crate::db::test_conn(); - c.execute("INSERT INTO series (source_id, id, name, title, position) VALUES (1, 's1', 'Show', 'Show', 0)", []) - .unwrap(); - let episodes: Vec = (1..=5) - .map(|n| serde_json::json!({"id": format!("e{n}"), "episode_num": n, "title": format!("Show - S01E0{n}")})) - .collect(); - let detail = serde_json::json!({ "episodes": { "1": episodes } }).to_string(); - c.execute("INSERT INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (1, 'series', 's1', ?1, 0)", [detail]) - .unwrap(); - let finish = |ep: i64, at: i64| { - c.execute( - "INSERT OR REPLACE INTO history (source_id, kind, item_id, series_id, season, episode, title, watched, updated_at) - VALUES (1, 'episode', ?1, 's1', 1, ?2, 'Show', 1, ?3)", - params![format!("e{ep}"), ep, at], - ) - .unwrap(); - }; - let next = |c: &Connection| -> Vec { - up_next_rows(c, 20) - .unwrap() - .into_iter() - .map(|u| u.episode.id) - .collect() - }; - - finish(1, 100); - assert_eq!(next(&c), vec!["e2"]); - // two episodes finished within the same second: one entry, after the furthest - finish(4, 200); - finish(2, 200); - assert_eq!(next(&c), vec!["e5"]); - // nothing after the last episode - finish(5, 300); - assert!(next(&c).is_empty()); - } -} diff --git a/src-tauri/src/catalog/categories.rs b/src-tauri/src/catalog/categories.rs new file mode 100644 index 0000000..b4a1612 --- /dev/null +++ b/src-tauri/src/catalog/categories.rs @@ -0,0 +1,37 @@ +//! Category lists of each kind (the browse sidebars). + +use super::*; + +#[tauri::command] +pub async fn categories(state: State<'_, AppState>, kind: ItemKind) -> Result> { + if kind == ItemKind::Episode { + return Err(Error::msg("episodes have no categories")); + } + let table = kind.table(); + read_blocking(state.inner(), move |conn| { + let show_adult = settings::get_bool(conn, "content.showAdult"); + let extra = if table == "channel" { " AND x.separator = 0" } else { "" }; + let sql = format!( + "SELECT c.source_id, c.id, c.title, c.region, c.badges, + (SELECT COUNT(*) FROM {table} x WHERE x.source_id = c.source_id AND x.category_id = c.id{extra}) AS n + FROM category c + WHERE c.kind = ?1 AND (?2 OR c.adult = 0) + ORDER BY c.source_id, c.position" + ); + let mut stmt = conn.prepare_cached(&sql)?; + let rows = stmt + .query_map(params![kind, show_adult], |r| { + Ok(CategoryItem { + source_id: r.get(0)?, + id: r.get(1)?, + title: r.get(2)?, + region: r.get(3)?, + badges: split_badges(r.get(4)?), + count: r.get(5)?, + }) + })? + .collect::, _>>()?; + Ok(rows.into_iter().filter(|c| c.count > 0).collect()) + }) + .await +} diff --git a/src-tauri/src/catalog/channels.rs b/src-tauri/src/catalog/channels.rs new file mode 100644 index 0000000..c18697a --- /dev/null +++ b/src-tauri/src/catalog/channels.rs @@ -0,0 +1,491 @@ +//! Live channels: listings with now/next, channel groups and their feeds, and +//! the Live page's country/genre navigation. + +use super::*; + +/// Channel rows with now/next. `grouped`: one row per channel group, +/// titled as the group and playing its chosen variant (`g.source_id`/ +/// `g.item_id`), a favorite when any variant is. A feed without its own EPG +/// id uses its group's. +fn channel_select(grouped: bool) -> String { + let (title, favorite, from) = if grouped { + ( + "g.title", + "EXISTS(SELECT 1 FROM channel x JOIN favorite f ON f.source_id = x.source_id AND f.kind = 'live' AND f.item_id = x.id + WHERE x.group_key = g.key)", + "channel_group g JOIN channel c ON c.source_id = g.source_id AND c.id = g.item_id", + ) + } else { + ( + "c.title", + "EXISTS(SELECT 1 FROM favorite f WHERE f.source_id = c.source_id AND f.kind = 'live' AND f.item_id = c.id)", + "channel c LEFT JOIN channel_group g ON g.key = c.group_key", + ) + }; + format!( + "SELECT c.source_id, c.id, c.num, {title}, COALESCE(c.logo, g.logo), COALESCE(c.epg_id, g.epg_id), c.category_id, + c.badges, c.archive, c.archive_days, {favorite}, + p.title, p.start, p.stop, q.title, q.start, q.stop, g.key, g.variants, g.country, g.genre + FROM {from} + LEFT JOIN programme p ON p.source_id = c.source_id AND p.epg_id = COALESCE(c.epg_id, g.epg_id) + AND p.start = (SELECT MAX(start) FROM programme + WHERE source_id = c.source_id AND epg_id = COALESCE(c.epg_id, g.epg_id) AND start <= :now) + AND p.stop > :now + LEFT JOIN programme q ON q.source_id = c.source_id AND q.epg_id = COALESCE(c.epg_id, g.epg_id) + AND q.start = (SELECT MIN(start) FROM programme + WHERE source_id = c.source_id AND epg_id = COALESCE(c.epg_id, g.epg_id) AND start > :now)" + ) +} + +fn row_to_channel(r: &Row) -> rusqlite::Result { + let brief = |i: usize| -> rusqlite::Result> { + Ok(match r.get::<_, Option>(i)? { + Some(title) => Some(Brief { + title, + start: r.get(i + 1)?, + stop: r.get(i + 2)?, + }), + None => None, + }) + }; + Ok(ChannelItem { + source_id: r.get(0)?, + id: r.get(1)?, + num: r.get(2)?, + title: r.get(3)?, + logo: r.get(4)?, + epg_id: r.get(5)?, + category_id: r.get(6)?, + badges: split_badges(r.get(7)?), + archive: r.get(8)?, + archive_days: r.get(9)?, + favorite: r.get(10)?, + now: brief(11)?, + next: brief(14)?, + group: match r.get::<_, Option>(17)? { + Some(key) => Some(GroupInfo { + key, + variants: r.get(18)?, + country: r.get(19)?, + genre: r.get(20)?, + }), + None => None, + }, + }) +} + +pub fn query_channels(conn: &Connection, q: &ChannelQuery) -> Result> { + let g = q.grouped; + let mut filters = vec!["c.separator = 0".to_owned()]; + let mut args: Vec<(String, Sql)> = vec![(":now".into(), Sql::Integer(now()))]; + if !settings::get_bool(conn, "content.showAdult") { + filters.push(if g { "g.adult = 0" } else { "c.adult = 0" }.into()); + } + match (q.source_id, &q.category_id, g) { + (Some(s), Some(cat), true) => { + filters.push("g.key IN (SELECT group_key FROM channel WHERE source_id = :source AND category_id = :cat)".into()); + args.push((":source".into(), Sql::Integer(s))); + args.push((":cat".into(), Sql::Text(cat.clone()))); + } + (Some(s), None, true) => { + filters + .push("g.key IN (SELECT group_key FROM channel WHERE source_id = :source)".into()); + args.push((":source".into(), Sql::Integer(s))); + } + (s, cat, false) => { + if let Some(s) = s { + filters.push("c.source_id = :source".into()); + args.push((":source".into(), Sql::Integer(s))); + } + if let Some(cat) = cat { + filters.push("c.category_id = :cat".into()); + args.push((":cat".into(), Sql::Text(cat.clone()))); + } + } + _ => {} + } + match q.country.as_deref() { + // channels whose category has no region + Some("") => filters.push("g.key IS NOT NULL AND g.country IS NULL".into()), + Some(country) => { + filters.push("g.country = :country".into()); + args.push((":country".into(), Sql::Text(country.to_owned()))); + } + None => {} + } + if let Some(genre) = &q.genre { + filters.push("g.genre = :genre".into()); + args.push((":genre".into(), Sql::Text(genre.clone()))); + } + if q.with_epg { + filters.push( + "COALESCE(c.epg_id, g.epg_id) IS NOT NULL + AND EXISTS (SELECT 1 FROM programme pe WHERE pe.source_id = c.source_id AND pe.epg_id = COALESCE(c.epg_id, g.epg_id))" + .into(), + ); + } + if let Some(text) = q.q.as_deref().filter(|t| !t.trim().is_empty()) { + filters.push( + if g { + "g.title LIKE :q ESCAPE '\\'" + } else { + "c.title LIKE :q ESCAPE '\\'" + } + .into(), + ); + args.push((":q".into(), Sql::Text(like_pattern(text)))); + } + let (join, order) = match (q.favorites, g) { + // a channel is a favorite since its first favorited variant + (true, true) => ( + " JOIN (SELECT x.group_key AS key, MIN(f.added_at) AS added_at FROM favorite f + JOIN channel x ON x.source_id = f.source_id AND x.id = f.item_id + WHERE f.kind = 'live' AND x.group_key IS NOT NULL GROUP BY x.group_key) fv ON fv.key = g.key", + "fv.added_at".to_owned(), + ), + (true, false) => ( + " JOIN favorite fv ON fv.source_id = c.source_id AND fv.kind = 'live' AND fv.item_id = c.id", + "fv.added_at".to_owned(), + ), + // a country: its regular channels first, event feeds last; a genre: + // the viewer's countries first + (false, true) if q.country.is_some() => ("", genre_order()), + (false, true) if q.genre.is_some() => ("", country_order_sql(conn)?), + (false, true) => ("", "g.position".to_owned()), + (false, false) => ("", "c.source_id, c.position".to_owned()), + }; + let where_sql = filters.join(" AND "); + let from = if g { + "channel_group g JOIN channel c ON c.source_id = g.source_id AND c.id = g.item_id" + } else { + "channel c LEFT JOIN channel_group g ON g.key = c.group_key" + }; + + let count_sql = format!("SELECT COUNT(*) FROM {from}{join} WHERE {where_sql}"); + let count_args: Vec<(&str, &dyn rusqlite::ToSql)> = args + .iter() + .filter(|(k, _)| k != ":now") + .map(|(k, v)| (k.as_str(), v as &dyn rusqlite::ToSql)) + .collect(); + let total: i64 = conn + .prepare_cached(&count_sql)? + .query_row(count_args.as_slice(), |r| r.get(0))?; + + let limit = q.limit.unwrap_or(500).clamp(1, 5000); + let offset = q.offset.unwrap_or(0).max(0); + let sql = format!( + "{}{join} WHERE {where_sql} ORDER BY {order} LIMIT {limit} OFFSET {offset}", + channel_select(g) + ); + let named: Vec<(&str, &dyn rusqlite::ToSql)> = args + .iter() + .map(|(k, v)| (k.as_str(), v as &dyn rusqlite::ToSql)) + .collect(); + let items = conn + .prepare_cached(&sql)? + .query_map(named.as_slice(), row_to_channel)? + .collect::, _>>()?; + Ok(Page { total, items }) +} + +#[tauri::command] +pub async fn channels( + state: State<'_, AppState>, + query: ChannelQuery, +) -> Result> { + read_blocking(state.inner(), move |conn| { + let t = Instant::now(); + let page = query_channels(conn, &query)?; + log::debug!( + "channels {:?}: {} of {} in {:?}", + query.category_id, + page.items.len(), + page.total, + t.elapsed() + ); + Ok(page) + }) + .await +} + +pub fn channel_by_id(conn: &Connection, source_id: i64, id: &str) -> Result { + let sql = format!( + "{} WHERE c.source_id = :source AND c.id = :id", + channel_select(false) + ); + conn.prepare_cached(&sql)? + .query_row( + &[ + (":now", &now() as &dyn rusqlite::ToSql), + (":source", &source_id), + (":id", &id), + ], + row_to_channel, + ) + .optional()? + .ok_or_else(|| Error::NotFound(format!("channel {id}"))) +} + +#[tauri::command] +pub async fn channel( + state: State<'_, AppState>, + source_id: i64, + id: String, +) -> Result { + read_blocking(state.inner(), move |conn| { + channel_by_id(conn, source_id, &id) + }) + .await +} + +/// A channel group as a row: its title, playing its chosen variant. +pub fn channel_group_by_key(conn: &Connection, key: &str) -> Result { + let sql = format!("{} WHERE g.key = :key", channel_select(true)); + conn.prepare_cached(&sql)? + .query_row( + &[(":now", &now() as &dyn rusqlite::ToSql), (":key", &key)], + row_to_channel, + ) + .optional()? + .ok_or_else(|| Error::NotFound(format!("channel {key}"))) +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LiveCountry { + /// region code from the provider's categories ("DK"); None = no region + pub code: Option, + pub name: String, + pub count: i64, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LiveCell { + pub country: Option, + pub genre: String, + pub count: i64, +} + +/// Live TV navigation: channel groups per country and genre. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LiveNav { + /// the viewer's countries first (player languages), then by size + pub countries: Vec, + /// genres in display order + pub genres: Vec, + pub cells: Vec, +} + +/// `ORDER BY` for channel groups: genres in `LIVE_GENRES` order; within one, +/// channels with guide data first — the linear channels (BBC One, ITV, …) +/// ahead of a provider's 24/7 and FAST feeds, which rarely have any. +fn genre_order() -> String { + let cases: String = crate::works::genre::LIVE_GENRES + .iter() + .enumerate() + .map(|(i, g)| format!(" WHEN '{}' THEN {i}", g.replace('\'', "''"))) + .collect(); + format!("CASE g.genre{cases} ELSE 99 END, g.epg_id IS NULL, g.position") +} + +/// `ORDER BY` for channel groups: countries as `live_nav` lists them, each +/// with its guide channels first. +fn country_order_sql(conn: &Connection) -> Result { + let cases: String = live_nav_for(conn)? + .countries + .iter() + .enumerate() + .filter_map(|(i, c)| { + c.code + .as_ref() + .map(|code| format!(" WHEN '{}' THEN {i}", code.replace('\'', "''"))) + }) + .collect(); + Ok(format!( + "CASE g.country{cases} ELSE 9999 END, g.epg_id IS NULL, g.position" + )) +} + +pub fn live_nav_for(conn: &Connection) -> Result { + let show_adult = settings::get_bool(conn, "content.showAdult"); + let cells: Vec = conn + .prepare_cached( + "SELECT country, genre, COUNT(*) FROM channel_group WHERE ?1 OR adult = 0 GROUP BY country, genre", + )? + .query_map([show_adult], |r| Ok(LiveCell { country: r.get(0)?, genre: r.get(1)?, count: r.get(2)? }))? + .collect::>()?; + let mut countries: Vec = Vec::new(); + for c in &cells { + match countries.iter_mut().find(|x| x.code == c.country) { + Some(x) => x.count += c.count, + None => countries.push(LiveCountry { + code: c.country.clone(), + name: c + .country + .as_deref() + .map(crate::works::genre::country_name) + .unwrap_or_else(|| "Other".into()), + count: c.count, + }), + } + } + let home: Vec<&str> = versions::language_prefs(conn) + .into_iter() + .flat_map(|l| { + crate::works::genre::countries_for_language(l) + .iter() + .copied() + }) + .collect(); + let rank = |c: &LiveCountry| { + c.code + .as_deref() + .and_then(|code| home.iter().position(|h| *h == code)) + .unwrap_or(usize::MAX) + }; + countries.sort_by(|a, b| { + rank(a) + .cmp(&rank(b)) + .then(a.code.is_none().cmp(&b.code.is_none())) + .then(b.count.cmp(&a.count)) + .then(a.name.cmp(&b.name)) + }); + let genres = crate::works::genre::LIVE_GENRES + .iter() + .filter(|g| cells.iter().any(|c| c.genre == **g)) + .map(|g| g.to_string()) + .collect(); + Ok(LiveNav { + countries, + genres, + cells, + }) +} + +#[tauri::command] +pub async fn live_nav(state: State<'_, AppState>) -> Result { + read_blocking(state.inner(), live_nav_for).await +} + +/// One provider feed of a channel, for the variant chips. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelVariant { + #[serde(flatten)] + pub channel: ChannelItem, + /// "RAW · HEVC", "HD · VIP", "4K" + pub label: String, + /// provider category, e.g. "Now TV Sport · HD RAW" + pub category: Option, + /// the one that plays for this channel + pub selected: bool, +} + +pub fn variants_of(conn: &Connection, key: &str) -> Result> { + let chosen: Option<(i64, String)> = conn + .query_row( + "SELECT source_id, item_id FROM channel_group WHERE key = ?1", + [key], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + type Row = (i64, String, String, Option, Option, i64); + let rows: Vec = conn + .prepare_cached( + "SELECT c.source_id, c.id, c.badges, k.badges, k.name, COALESCE(k.position, 0) * 100000 + c.position + FROM channel c + LEFT JOIN category k ON k.source_id = c.source_id AND k.kind = 'live' AND k.id = c.category_id + WHERE c.group_key = ?1", + )? + .query_map([key], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))? + .collect::>()?; + let mut out: Vec<(i32, i64, ChannelVariant)> = Vec::new(); + for (sid, id, badges, cat_badges, cat_name, order) in rows { + let channel = channel_by_id(conn, sid, &id)?; + let selected = chosen.as_ref().is_some_and(|(s, i)| *s == sid && *i == id); + let label = + crate::works::channel_variant_label(&badges, cat_badges.as_deref().unwrap_or("")); + let category = cat_name.as_deref().map(crate::names::display_category); + out.push(( + crate::works::channel_rank(&badges), + order, + ChannelVariant { + channel, + label, + category, + selected, + }, + )); + } + out.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + // identical feeds (backups in the same category) get a number + let mut seen: HashMap = HashMap::new(); + let mut variants: Vec = out.into_iter().map(|(_, _, v)| v).collect(); + for v in &mut variants { + let n = seen.entry(v.label.clone()).or_insert(0); + *n += 1; + if *n > 1 { + v.label = format!("{} ({n})", v.label); + } + } + Ok(variants) +} + +#[tauri::command] +pub async fn channel_variants( + state: State<'_, AppState>, + key: String, +) -> Result> { + read_blocking(state.inner(), move |conn| variants_of(conn, &key)).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_country_lists_its_guide_channels_first() { + let c = crate::db::test_conn(); + c.execute( + "INSERT INTO category (source_id, kind, id, name, title, region, position) + VALUES (1, 'live', 'ent', 'UK| ENTERTAINMENT', 'ENTERTAINMENT', 'UK', 0)", + [], + ) + .unwrap(); + // the provider lists its 24/7 feeds (no guide data) before BBC One + for (id, title, epg, pos) in [ + ("fast", "BAYWATCH", None, 0), + ("bbc1", "BBC ONE", Some("BBCOne.uk"), 1), + ] { + c.execute( + "INSERT INTO channel (source_id, id, name, title, category_id, epg_id, position) + VALUES (1, ?1, ?2, ?2, 'ent', ?3, ?4)", + params![id, title, epg, pos], + ) + .unwrap(); + } + crate::works::rebuild(&c).unwrap(); + let titles = |q: ChannelQuery| -> Vec { + query_channels(&c, &q) + .unwrap() + .items + .into_iter() + .map(|i| i.title) + .collect() + }; + let uk = ChannelQuery { + grouped: true, + country: Some("UK".into()), + ..Default::default() + }; + assert_eq!(titles(uk), ["BBC ONE", "BAYWATCH"]); + let genre = ChannelQuery { + grouped: true, + genre: Some("Entertainment".into()), + ..Default::default() + }; + assert_eq!(titles(genre), ["BBC ONE", "BAYWATCH"]); + } +} diff --git a/src-tauri/src/catalog/details.rs b/src-tauri/src/catalog/details.rs new file mode 100644 index 0000000..464a16b --- /dev/null +++ b/src-tauri/src/catalog/details.rs @@ -0,0 +1,1355 @@ +//! Movie and series detail pages: every copy's provider details, the chosen +//! version, episodes and where to resume; plus "up next". + +use super::*; + +const MOVIE_DETAIL_TTL: i64 = 7 * 86400; +const SERIES_DETAIL_TTL: i64 = 12 * 3600; + +// --------------------------------------------------------------- details + +#[derive(Debug, Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TechInfo { + pub codec: Option, + pub width: Option, + pub height: Option, + pub hdr: bool, + pub channels: Option, + pub language: Option, +} + +fn tech(v: &Value) -> Option { + if !v.is_object() { + return None; + } + let transfer = str_of(&v["color_transfer"]).unwrap_or_default(); + Some(TechInfo { + codec: str_of(&v["codec_name"]), + width: i64_of(&v["width"]), + height: i64_of(&v["height"]), + hdr: transfer.contains("2084") || transfer.contains("hlg"), + channels: i64_of(&v["channels"]), + language: str_of(&v["tags"]["language"]), + }) +} + +/// Providers send backdrops as an array, a URL, or a stringified Python list. +fn first_url(v: &Value) -> Option { + match v { + Value::Array(a) => a.iter().find_map(first_url), + Value::String(s) => { + let s = s.trim(); + if s.starts_with('[') { + s.split(['\'', '"', ',', '[', ']', ' ']) + .find(|p| p.starts_with("http")) + .map(str::to_owned) + } else if s.starts_with("http") { + Some(s.to_owned()) + } else { + None + } + } + _ => None, + } +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MovieDetail { + /// The copy that plays (see `versions`), titled/illustrated as its work. + #[serde(flatten)] + pub item: MovieItem, + pub plot: Option, + pub cast: Option, + pub director: Option, + pub genre: Option, + pub country: Option, + pub release_date: Option, + pub duration: Option, + pub backdrop: Option, + pub trailer: Option, + pub age_rating: Option, + pub video: Option, + pub audio: Option, + pub position: f64, + /// every provider copy of this movie, the playing one `selected` + pub versions: Vec, + /// some copies' provider details are still loading — ask again shortly + pub versions_pending: bool, + /// from TMDB, when a key is configured + pub tmdb: Option, +} + +struct CachedDetail { + json: Value, + fetched_at: i64, +} + +fn cached( + conn: &Connection, + source_id: i64, + kind: WorkKind, + id: &str, +) -> Result> { + Ok(conn + .query_row( + "SELECT json, fetched_at FROM detail_cache WHERE source_id = ?1 AND kind = ?2 AND id = ?3", + params![source_id, kind, id], + |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)), + ) + .optional()? + .and_then(|(j, t)| serde_json::from_str(&j).ok().map(|json| CachedDetail { json, fetched_at: t }))) +} + +/// Provider detail JSON with a TTL cache; serves stale data when offline. +async fn provider_detail( + st: &AppState, + source_id: i64, + kind: WorkKind, + id: &str, + ttl: i64, +) -> Result> { + let (src, cache) = { + let id = id.to_owned(); + read_blocking(st, move |conn| { + Ok(( + sources::load(conn, source_id)?, + cached(conn, source_id, kind, &id)?, + )) + }) + .await? + }; + if src.kind != SourceKind::Xtream { + return Ok(None); + } + if let Some(c) = &cache + && now() - c.fetched_at < ttl + { + return Ok(Some(c.json.clone())); + } + let fetched = match sources::xtream_for(&src, http_client(src.user_agent.as_deref())) { + Ok(x) => match kind { + WorkKind::Movie => x.vod_info(id).await, + WorkKind::Series => x.series_info(id).await, + }, + Err(e) => Err(e), + }; + match fetched { + Ok(v) if v.is_object() => { + let (id, json) = (id.to_owned(), v.to_string()); + write_blocking(st, move |conn| { + conn.execute( + "INSERT OR REPLACE INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (?1, ?2, ?3, ?4, ?5)", + params![source_id, kind, id, json, now()], + )?; + Ok(()) + }) + .await?; + Ok(Some(v)) + } + Ok(_) => Ok(cache.map(|c| c.json)), + Err(e) => match cache { + Some(c) => { + log::warn!("{kind} {id}: using stale detail ({e})"); + Ok(Some(c.json)) + } + None => Err(e), + }, + } +} + +/// How long a detail page waits for the provider before showing what it has. +const DETAIL_DEADLINE: std::time::Duration = std::time::Duration::from_millis(2500); + +/// Provider details of several copies at once. This provider stalls for ~9 s +/// on single requests now and then, so the page doesn't wait for every copy: +/// what arrives within `DETAIL_DEADLINE` (or from the cache) is used, the rest +/// keeps loading in the background (into the cache) and is reported as +/// pending — the UI asks again. At least one copy is always waited for. +async fn details_of( + st: &AppState, + kind: WorkKind, + copies: &[(i64, String)], + ttl: i64, +) -> (Vec>, bool) { + let mut handles: Vec>>>> = copies + .iter() + .map(|(sid, id)| { + let (st, sid, id) = (st.clone(), *sid, id.clone()); + Some(tokio::spawn(async move { + match provider_detail(&st, sid, kind, &id, ttl).await { + // M3U series: episodes come from the playlist + Ok(None) if kind == WorkKind::Series => { + read_blocking(&st, move |conn| m3u_series_json(conn, sid, &id)).await + } + other => other, + } + })) + }) + .collect(); + let deadline = tokio::time::Instant::now() + DETAIL_DEADLINE; + let mut out: Vec> = vec![None; copies.len()]; + let mut finished = 0; + for (i, h) in handles.iter_mut().enumerate() { + let Some(handle) = h.as_mut() else { continue }; + if let Ok(joined) = tokio::time::timeout_at(deadline, handle).await { + *h = None; + finished += 1; + match joined { + Ok(Ok(v)) => out[i] = v, + Ok(Err(e)) => log::warn!("{kind} {}: no provider detail ({e})", copies[i].1), + Err(e) => log::warn!("{kind} {}: detail task failed ({e})", copies[i].1), + } + } + } + if finished == 0 { + // nothing within the deadline: take the first copy that answers + let pending: Vec<(usize, tokio::task::JoinHandle>>)> = handles + .iter_mut() + .enumerate() + .filter_map(|(i, h)| h.take().map(|h| (i, h))) + .collect(); + let (idx, futs): (Vec, Vec<_>) = pending.into_iter().unzip(); + if !futs.is_empty() { + let (res, pos, rest) = futures_util::future::select_all(futs).await; + if let Ok(Ok(v)) = res { + out[idx[pos]] = v; + } + // the others keep filling the cache in the background + drop(rest); + return (out, idx.len() > 1); + } + } + let pending = handles.iter().any(Option::is_some); + (out, pending) +} + +/// What both detail pages start from: every copy of the work, the copy the +/// user picked, the language preferences and the work's key. +struct WorkContext { + members: Vec, + pref: Option<(i64, String)>, + langs: Vec<&'static str>, + key: Option, +} + +fn work_context( + conn: &Connection, + kind: WorkKind, + source_id: i64, + id: &str, +) -> Result { + let members = versions::members(conn, kind, source_id, id)?; + if members.is_empty() { + return Err(Error::NotFound(format!("{kind} {id}"))); + } + let key = versions::work_key(conn, kind, source_id, id)?; + let pref = match &key { + Some(k) => versions::preference(conn, kind, k)?, + None => None, + }; + Ok(WorkContext { + members, + pref, + langs: versions::language_prefs(conn), + key, + }) +} + +#[tauri::command] +pub async fn movie_detail( + state: State<'_, AppState>, + source_id: i64, + id: String, +) -> Result { + let st = state.inner().clone(); + let ( + WorkContext { + members, + pref, + langs, + .. + }, + work, + facts, + tracks, + ) = { + let id = id.clone(); + read_blocking(&st, move |conn| { + let ctx = work_context(conn, WorkKind::Movie, source_id, &id)?; + let work = match &ctx.key { + Some(k) => conn + .prepare_cached(&format!( + "{} WHERE w.kind = 'movie' AND w.key = ?1", + movie_work_select() + ))? + .query_row([k], row_to_movie) + .optional()?, + None => None, + }; + let facts = match (&ctx.key, &work) { + (Some(k), Some(w)) => { + crate::tmdb::facts_for(conn, WorkKind::Movie, k, &w.title, w.year)? + } + _ => None, + }; + let tracks = ctx + .members + .iter() + .map(|m| versions::tracks(conn, m.source_id, ItemKind::Movie, &m.id)) + .collect::>>()?; + Ok((ctx, work, facts, tracks)) + }) + .await? + }; + // provider details of every copy at once (cached for a week) + let copies: Vec<(i64, String)> = members + .iter() + .map(|m| (m.source_id, m.id.clone())) + .collect(); + let (details, pending) = details_of(&st, WorkKind::Movie, &copies, MOVIE_DETAIL_TTL).await; + let info_of = |i: usize| { + details[i] + .as_ref() + .map(|d| d["info"].clone()) + .unwrap_or(Value::Null) + }; + // a copy much shorter than the others is a trailer or cut off + let durations: Vec> = (0..members.len()) + .map(|i| i64_of(&info_of(i)["duration_secs"]).filter(|d| *d > 0)) + .collect(); + let longest = durations.iter().flatten().copied().max().unwrap_or(0); + let sel = versions::choose(&members, pref.as_ref(), &langs, |i| match durations[i] { + _ if versions::unavailable(&tracks[i]) => versions::BROKEN, + Some(d) if longest > 0 => d as f64 / longest as f64, + _ => 1.0, + }); + let chosen = members[sel].clone(); + let info = info_of(sel); + // missing fields from the other copies' details + let pick = |keys: &[&str]| -> Option { + first_str(&info, keys) + .or_else(|| (0..members.len()).find_map(|i| first_str(&info_of(i), keys))) + }; + + let mut item = { + let (sid, mid) = (chosen.source_id, chosen.id.clone()); + read_blocking(&st, move |conn| { + conn.prepare_cached(&format!( + "{MOVIE_SELECT} WHERE m.source_id = ?1 AND m.id = ?2" + ))? + .query_row(params![sid, mid], row_to_movie) + .optional()? + .ok_or_else(|| Error::NotFound(format!("movie {mid}"))) + }) + .await? + }; + if let Some(w) = &work { + item.title = w.title.clone(); + item.year = w.year.or(item.year); + item.poster = w.poster.clone().or(item.poster); + item.rating = w.rating.or(item.rating); + item.work = w.work.clone(); + item.favorite = w.favorite; + } + if item.poster.is_none() { + item.poster = pick(&["cover_big", "movie_image"]); + } + if item.rating.is_none() { + item.rating = f64_of(&info["rating"]).filter(|r| *r > 0.0); + } + // resume where any copy was left off (versions are the same film) + let latest = members + .iter() + .filter(|m| m.played_at > 0) + .max_by_key(|m| m.played_at); + let position = if chosen.position > 0.0 { + chosen.position + } else { + latest + .filter(|m| !m.watched) + .map(|m| m.position) + .unwrap_or(0.0) + }; + let multi_source = members.iter().any(|m| m.source_id != members[0].source_id); + let versions = members + .iter() + .enumerate() + .map(|(i, m)| { + let mut v = m.info(multi_source, i == sel); + let inf = info_of(i); + v.video = tech(&inf["video"]); + v.audio = tech(&inf["audio"]); + v.duration = i64_of(&inf["duration_secs"]).filter(|d| *d > 0); + v.tracks = tracks[i].clone(); + v + }) + .collect(); + let trailer = match pick(&["youtube_trailer", "trailer"]) { + Some(t) => Some(t), + None => { + let (sid, mid) = (chosen.source_id, chosen.id.clone()); + read_blocking(&st, move |conn| { + Ok(conn + .query_row( + "SELECT trailer FROM movie WHERE source_id = ?1 AND id = ?2", + params![sid, mid], + |r| r.get(0), + ) + .optional()? + .flatten()) + }) + .await? + } + }; + Ok(MovieDetail { + versions_pending: pending, + plot: pick(&["plot", "description"]), + cast: pick(&["cast", "actors"]), + director: pick(&["director"]), + genre: pick(&["genre"]), + country: pick(&["country"]), + release_date: pick(&["releasedate", "release_date"]), + duration: i64_of(&info["duration_secs"]).filter(|d| *d > 0), + backdrop: first_url(&info["backdrop_path"]) + .or_else(|| (0..members.len()).find_map(|i| first_url(&info_of(i)["backdrop_path"]))), + trailer, + age_rating: pick(&["mpaa_rating", "age"]), + video: tech(&info["video"]), + audio: tech(&info["audio"]), + position, + versions, + tmdb: facts, + item, + }) +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Episode { + pub id: String, + pub season: i64, + pub episode: i64, + pub title: String, + pub plot: Option, + pub duration: Option, + pub image: Option, + pub ext: Option, + pub rating: Option, + pub air_date: Option, + pub video: Option, + pub position: f64, + pub watched: bool, + /// the copy (series row) this episode plays from + pub source_id: i64, + pub series_id: String, + /// label of that copy when it isn't the selected version + pub version: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Season { + pub season: i64, + pub name: String, + pub cover: Option, + pub overview: Option, + pub air_date: Option, + pub episodes: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Resume { + pub episode_id: String, + pub season: i64, + pub episode: i64, + pub position: f64, + pub started: bool, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SeriesDetail { + #[serde(flatten)] + pub item: SeriesItem, + pub plot: Option, + pub cast: Option, + pub director: Option, + pub release_date: Option, + pub trailer: Option, + pub seasons: Vec, + pub resume: Option, + /// every provider copy; seasons/episodes above are their union, each + /// episode from the selected copy when it has it + pub versions: Vec, + /// some copies' episode lists are still loading — ask again shortly + pub versions_pending: bool, + /// from TMDB, when a key is configured + pub tmdb: Option, +} + +/// Episodes of an M3U series (`episode` table) in the shape of Xtream's +/// `get_series_info` (`{"episodes": {"1": [...]}}`), so series pages, resume +/// and Up next treat both source kinds alike. +pub fn m3u_series_json( + conn: &Connection, + source_id: i64, + series_id: &str, +) -> Result> { + let mut stmt = conn.prepare_cached( + "SELECT id, season, episode, title, image, ext FROM episode + WHERE source_id = ?1 AND series_id = ?2 ORDER BY season, episode, position", + )?; + type Row = (String, i64, i64, String, Option, Option); + let rows: Vec = stmt + .query_map(params![source_id, series_id], |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + )) + })? + .collect::>()?; + if rows.is_empty() { + return Ok(None); + } + let mut seasons = serde_json::Map::new(); + for (id, season, episode, title, image, ext) in rows { + if let Value::Array(list) = seasons + .entry(season.to_string()) + .or_insert_with(|| Value::Array(Vec::new())) + { + list.push(serde_json::json!({ + "id": id, "episode_num": episode, "title": title, "container_extension": ext, + "info": { "movie_image": image }, + })); + } + } + Ok(Some(serde_json::json!({ "episodes": seasons }))) +} + +/// Provider `episodes` payload ({"1": [...]} or [[...]]) → seasons in order, +/// episodes sorted, without watch state. `source_id`/`series_id` name the +/// copy the payload belongs to. +fn parse_episodes( + detail: &Value, + series_title: &str, + source_id: i64, + series_id: &str, +) -> Vec<(i64, Vec)> { + let mut groups: Vec<(i64, Vec)> = match &detail["episodes"] { + Value::Object(map) => map + .iter() + .map(|(k, v)| { + ( + k.parse().unwrap_or(0), + v.as_array().cloned().unwrap_or_default(), + ) + }) + .collect(), + Value::Array(arr) => arr + .iter() + .enumerate() + .map(|(i, v)| { + let eps = v.as_array().cloned().unwrap_or_default(); + let n = eps + .first() + .and_then(|e| i64_of(&e["season"])) + .unwrap_or(i as i64 + 1); + (n, eps) + }) + .collect(), + _ => Vec::new(), + }; + groups.sort_by_key(|(n, _)| *n); + groups + .into_iter() + .map(|(n, eps)| { + let mut episodes: Vec = eps + .iter() + .enumerate() + .filter_map(|(i, e)| { + let eid = str_of(&e["id"])?; + let ei = &e["info"]; + let num = i64_of(&e["episode_num"]).unwrap_or(i as i64 + 1); + let raw_title = first_str(ei, &["name"]) + .or_else(|| str_of(&e["title"])) + .unwrap_or_default(); + Some(Episode { + title: episode_title(&raw_title, series_title, num), + season: n, + episode: num, + plot: first_str(ei, &["plot", "overview"]), + duration: i64_of(&ei["duration_secs"]).filter(|d| *d > 0), + image: first_str(ei, &["movie_image", "cover_big"]), + ext: str_of(&e["container_extension"]), + rating: f64_of(&ei["rating"]).filter(|r| *r > 0.0), + air_date: first_str(ei, &["releasedate", "air_date"]), + video: tech(&ei["video"]), + position: 0.0, + watched: false, + source_id, + series_id: series_id.to_owned(), + version: None, + id: eid, + }) + }) + .collect(); + episodes.sort_by_key(|e| e.episode); + (n, episodes) + }) + .collect() +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct UpNext { + pub series: SeriesItem, + pub episode: Episode, +} + +/// Next episode for series whose most recently watched episode was finished +/// (partially watched ones already show in "Continue watching"). +#[tauri::command] +pub async fn up_next(state: State<'_, AppState>, limit: Option) -> Result> { + let limit = limit.unwrap_or(20).clamp(1, 50) as usize; + read_blocking(state.inner(), move |conn| up_next_rows(conn, limit)).await +} + +/// Episodes of one series copy from what is stored locally (the provider +/// detail cache, or the playlist for M3U series) — no network. +pub fn stored_episodes( + conn: &Connection, + source_id: i64, + series_id: &str, + title: &str, +) -> Result)>> { + let json = match cached(conn, source_id, WorkKind::Series, series_id)? { + Some(d) => d.json, + None => match m3u_series_json(conn, source_id, series_id)? { + Some(v) => v, + None => return Ok(Vec::new()), + }, + }; + Ok(parse_episodes(&json, title, source_id, series_id)) +} + +/// Union of all copies' episodes keyed by (season, episode), each taken from +/// the first copy in `order` that has it. +fn union_episodes( + per_copy: &[Vec<(i64, Vec)>], + order: &[usize], +) -> BTreeMap<(i64, i64), (usize, Episode)> { + let mut out = BTreeMap::new(); + for &i in order { + for (_, eps) in &per_copy[i] { + for e in eps { + out.entry((e.season, e.episode)) + .or_insert_with(|| (i, e.clone())); + } + } + } + out +} + +fn up_next_rows(conn: &Connection, limit: usize) -> Result> { + // Latest episode per show — all copies of a show count as one. Timestamps + // are whole seconds, so ties (two episodes marked within a second) go to + // the furthest episode. + type Latest = (i64, String, String, bool, Option, Option); + let latest: Vec = conn + .prepare_cached( + "SELECT source_id, series_id, item_id, watched, season, episode FROM ( + SELECT h.source_id, h.series_id, h.item_id, h.watched, h.season, h.episode, h.updated_at, + ROW_NUMBER() OVER ( + PARTITION BY COALESCE(s.work_key, 'item:' || h.source_id || ':' || h.series_id) + ORDER BY h.updated_at DESC, h.season DESC, h.episode DESC) AS n + FROM history h + LEFT JOIN series s ON s.source_id = h.source_id AND s.id = h.series_id + WHERE h.kind = 'episode' AND h.series_id IS NOT NULL) + WHERE n = 1 ORDER BY updated_at DESC LIMIT 60", + )? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))? + .collect::>()?; + let mut out = Vec::new(); + for (sid, series_id, last_id, watched, season, episode) in latest { + if !watched || out.len() >= limit { + continue; + } + let members = versions::members(conn, WorkKind::Series, sid, &series_id)?; + if members.is_empty() { + continue; + } + let key = versions::work_key(conn, WorkKind::Series, sid, &series_id)?; + let series = match &key { + Some(k) => conn + .prepare_cached(&format!( + "{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1" + ))? + .query_row([k], row_to_series) + .optional()?, + None => conn + .prepare_cached(&format!( + "{SERIES_SELECT} WHERE s.source_id = ?1 AND s.id = ?2" + ))? + .query_row(params![sid, series_id], row_to_series) + .optional()?, + }; + let Some(series) = series else { continue }; + let per_copy: Vec<_> = members + .iter() + .map(|m| stored_episodes(conn, m.source_id, &m.id, &series.title)) + .collect::>()?; + // continue in the copy that was being watched, then the chosen one + let watching = members + .iter() + .position(|m| m.source_id == sid && m.id == series_id) + .unwrap_or(0); + let pref = match &key { + Some(k) => versions::preference(conn, WorkKind::Series, k)?, + None => None, + }; + let chosen = versions::choose( + &members, + pref.as_ref(), + &versions::language_prefs(conn), + |_| 1.0, + ); + let mut order = vec![watching, chosen]; + order.extend(0..members.len()); + order.dedup(); + let union = union_episodes(&per_copy, &order); + // where we are: the history row's numbers, else find its episode id + let here = match (season, episode) { + (Some(s), Some(e)) => Some((s, e)), + _ => union + .iter() + .find(|(_, (_, e))| e.id == last_id) + .map(|(k, _)| *k), + }; + let Some(here) = here else { continue }; + let Some((_, (copy, next))) = union + .range((here.0, here.1 + 1)..) + .find(|((s, _), _)| *s > 0) + else { + continue; + }; + let mut next = next.clone(); + if *copy != chosen { + next.version = Some(members[*copy].variant.label.clone()); + } + let seen: bool = conn + .query_row( + "SELECT MAX(h.watched) FROM history h + LEFT JOIN series s ON s.source_id = h.source_id AND s.id = h.series_id + WHERE h.kind = 'episode' AND h.season = ?1 AND h.episode = ?2 + AND ((?3 IS NOT NULL AND s.work_key = ?3) OR (h.source_id = ?4 AND h.series_id = ?5))", + params![next.season, next.episode, key, sid, series_id], + |r| r.get::<_, Option>(0), + )? + .unwrap_or(false); + if !seen { + out.push(UpNext { + series, + episode: next, + }); + } + } + Ok(out) +} + +/// "Deadly Ties - S01E01" / "S01E01 - Pilot" → "Pilot" or "Episode 1". +fn episode_title(raw: &str, series_title: &str, n: i64) -> String { + static SXXEXX: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"(?i)\bS\d{1,3}\s*E\d{1,4}\b").expect("valid regex") + }); + let mut t = raw.trim().to_owned(); + if let Some(m) = SXXEXX.find(&t) { + let after = t[m.end()..] + .trim() + .trim_start_matches(['-', ':', '.', '|']) + .trim() + .to_owned(); + let before = t[..m.start()] + .trim() + .trim_end_matches(['-', ':', '.', '|']) + .trim() + .to_owned(); + t = if !after.is_empty() { + after + } else if !before.is_empty() + && !before.eq_ignore_ascii_case(series_title) + && !series_title.contains(&before) + { + before + } else { + String::new() + }; + } + if t.is_empty() { + format!("Episode {n}") + } else { + t + } +} + +/// Long-form series fields that list rows don't carry. +struct SeriesText { + plot: Option, + cast: Option, + director: Option, + release: Option, + trailer: Option, +} + +/// Watch state of one episode (of any copy of the show). +struct Watched { + source_id: i64, + id: String, + season: Option, + episode: Option, + position: f64, + watched: bool, + at: i64, +} + +#[tauri::command] +pub async fn series_detail( + state: State<'_, AppState>, + source_id: i64, + id: String, +) -> Result { + let st = state.inner().clone(); + let ( + WorkContext { + members, + pref, + langs, + .. + }, + work, + text, + history, + facts, + ) = { + let id = id.clone(); + read_blocking(&st, move |conn| { + let ctx = work_context(conn, WorkKind::Series, source_id, &id)?; + let key = ctx.key.clone(); + let work = match &key { + Some(k) => conn + .prepare_cached(&format!("{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1"))? + .query_row([k], row_to_series) + .optional()?, + None => None, + }; + let work = match work { + Some(w) => w, + None => conn + .prepare_cached(&format!("{SERIES_SELECT} WHERE s.source_id = ?1 AND s.id = ?2"))? + .query_row(params![source_id, id], row_to_series) + .optional()? + .ok_or_else(|| Error::NotFound(format!("series {id}")))?, + }; + // long texts: the requested copy, else any copy that has them + let text = conn.query_row( + "SELECT (SELECT plot FROM series x WHERE x.work_key IS s.work_key AND x.plot IS NOT NULL + ORDER BY x.source_id = s.source_id AND x.id = s.id DESC LIMIT 1), + COALESCE(s.cast_list, (SELECT cast_list FROM series x WHERE x.work_key = s.work_key AND x.cast_list IS NOT NULL LIMIT 1)), + COALESCE(s.director, (SELECT director FROM series x WHERE x.work_key = s.work_key AND x.director IS NOT NULL LIMIT 1)), + COALESCE(s.release_date, (SELECT release_date FROM series x WHERE x.work_key = s.work_key AND x.release_date IS NOT NULL LIMIT 1)), + COALESCE(s.trailer, (SELECT trailer FROM series x WHERE x.work_key = s.work_key AND x.trailer IS NOT NULL LIMIT 1)) + FROM series s WHERE s.source_id = ?1 AND s.id = ?2", + params![source_id, id], + |r| { + Ok(SeriesText { + plot: r.get(0)?, + cast: r.get(1)?, + director: r.get(2)?, + release: r.get(3)?, + trailer: r.get(4)?, + }) + }, + )?; + let history: Vec = conn + .prepare_cached( + "SELECT h.source_id, h.item_id, h.season, h.episode, h.position, h.watched, h.updated_at + FROM history h + LEFT JOIN series s ON s.source_id = h.source_id AND s.id = h.series_id + WHERE h.kind = 'episode' + AND ((?1 IS NOT NULL AND s.work_key = ?1) OR (h.source_id = ?2 AND h.series_id = ?3))", + )? + .query_map(params![key, source_id, id], |r| { + Ok(Watched { + source_id: r.get(0)?, + id: r.get(1)?, + season: r.get(2)?, + episode: r.get(3)?, + position: r.get(4)?, + watched: r.get(5)?, + at: r.get(6)?, + }) + })? + .collect::>()?; + let facts = match &key { + Some(k) => crate::tmdb::facts_for(conn, WorkKind::Series, k, &work.title, work.year)?, + None => None, + }; + Ok((ctx, work, text, history, facts)) + }) + .await? + }; + + // every copy's episodes at once (cached for 12 h) + let copies: Vec<(i64, String)> = members + .iter() + .map(|m| (m.source_id, m.id.clone())) + .collect(); + let (details, pending) = details_of(&st, WorkKind::Series, &copies, SERIES_DETAIL_TTL).await; + let details: Vec = details + .into_iter() + .map(|d| d.unwrap_or(Value::Null)) + .collect(); + let per_copy: Vec)>> = members + .iter() + .zip(&details) + .map(|(m, d)| parse_episodes(d, &work.title, m.source_id, &m.id)) + .collect(); + let counts: Vec = per_copy + .iter() + .map(|seasons| { + seasons + .iter() + .filter(|(n, _)| *n > 0) + .map(|(_, e)| e.len()) + .sum() + }) + .collect(); + let most = counts.iter().copied().max().unwrap_or(0).max(1); + // tracks seen in each copy (the first of its episodes with any) + let tracks: Vec> = { + let ids: Vec<(i64, Vec)> = per_copy + .iter() + .zip(&members) + .map(|(seasons, m)| { + ( + m.source_id, + seasons + .iter() + .flat_map(|(_, e)| e.iter().map(|e| e.id.clone())) + .take(40) + .collect(), + ) + }) + .collect(); + read_blocking(&st, move |conn| { + ids.iter() + .map(|(sid, eps)| { + for e in eps { + if let Some(t) = versions::tracks(conn, *sid, ItemKind::Episode, e)? { + return Ok(Some(t)); + } + } + Ok(None) + }) + .collect::>>() + }) + .await? + }; + let sel = versions::choose(&members, pref.as_ref(), &langs, |i| { + if versions::unavailable(&tracks[i]) { + versions::BROKEN + } else { + counts[i] as f64 / most as f64 + } + }); + + // selected copy first, then the others by their own fit + let mut order: Vec = (0..members.len()).collect(); + order.sort_by_key(|&i| { + let m = &members[i]; + ( + i != sel, + -(crate::works::variant::affinity(&m.variant, &langs) + + crate::works::variant::score(&m.variant)), + ) + }); + let union = union_episodes(&per_copy, &order); + + // history rows → (season, episode): by the episode id in its copy, else the stored numbers + let number_of = |w: &Watched| -> Option<(i64, i64)> { + per_copy + .iter() + .flatten() + .flat_map(|(_, eps)| eps) + .find(|e| e.source_id == w.source_id && e.id == w.id) + .map(|e| (e.season, e.episode)) + .or(match (w.season, w.episode) { + (Some(s), Some(e)) => Some((s, e)), + _ => None, + }) + }; + let mut state_of: HashMap<(i64, i64), &Watched> = HashMap::new(); + for w in &history { + if let Some(k) = number_of(w) + && state_of.get(&k).is_none_or(|prev| w.at > prev.at) + { + state_of.insert(k, w); + } + } + + let mut seasons: Vec = Vec::new(); + for ((s_no, _), (copy, e)) in &union { + let mut e = e.clone(); + if let Some(w) = state_of.get(&(e.season, e.episode)) { + e.position = w.position; + e.watched = w.watched; + } + if *copy != sel { + e.version = Some(members[*copy].variant.label.clone()); + } + match seasons.last_mut() { + Some(last) if last.season == *s_no => last.episodes.push(e), + _ => { + // season names/art from the selected copy, else any copy + let meta = order.iter().find_map(|&i| { + details[i]["seasons"].as_array().and_then(|a| { + a.iter() + .find(|m| i64_of(&m["season_number"]) == Some(*s_no)) + }) + }); + seasons.push(Season { + season: *s_no, + name: meta.and_then(|m| str_of(&m["name"])).unwrap_or_else(|| { + if *s_no == 0 { + "Specials".into() + } else { + format!("Season {s_no}") + } + }), + cover: meta.and_then(|m| first_str(m, &["cover_big", "cover"])), + overview: meta.and_then(|m| str_of(&m["overview"])), + air_date: meta.and_then(|m| str_of(&m["air_date"])), + episodes: vec![e], + }); + } + } + } + + // Resume: the most recent unfinished episode, else the one after the + // most recently finished, else S1E1 — across all copies. + let flat: Vec<&Episode> = seasons + .iter() + .filter(|s| s.season > 0) + .flat_map(|s| &s.episodes) + .collect(); + let latest = history + .iter() + .filter_map(|w| number_of(w).map(|k| (k, w))) + .max_by_key(|(_, w)| w.at); + let resume = match latest { + Some((k, w)) if !w.watched => { + flat.iter() + .find(|e| (e.season, e.episode) == k) + .map(|e| Resume { + episode_id: e.id.clone(), + season: e.season, + episode: e.episode, + position: w.position, + started: true, + }) + } + Some((k, _)) => flat + .iter() + .position(|e| (e.season, e.episode) == k) + .and_then(|i| flat.get(i + 1)) + .map(|e| Resume { + episode_id: e.id.clone(), + season: e.season, + episode: e.episode, + position: 0.0, + started: true, + }), + None => None, + } + .or_else(|| { + flat.first().map(|e| Resume { + episode_id: e.id.clone(), + season: e.season, + episode: e.episode, + position: 0.0, + started: false, + }) + }); + + let multi_source = members.iter().any(|m| m.source_id != members[0].source_id); + let versions: Vec = members + .iter() + .enumerate() + .map(|(i, m)| { + let mut v = m.info(multi_source, i == sel); + v.seasons = per_copy[i] + .iter() + .filter(|(n, e)| *n > 0 && !e.is_empty()) + .map(|(n, _)| *n) + .collect(); + v.episodes = counts[i] as i64; + let first = per_copy[i].iter().flat_map(|(_, e)| e).next(); + v.video = first.and_then(|e| e.video.clone()); + v.duration = first.and_then(|e| e.duration); + v.tracks = tracks[i].clone(); + v + }) + .collect(); + + let mut item = work; + if item.backdrop.is_none() { + item.backdrop = order + .iter() + .find_map(|&i| first_url(&details[i]["info"]["backdrop_path"])); + } + let info = &details[sel]["info"]; + Ok(SeriesDetail { + versions_pending: pending, + plot: text.plot.or_else(|| str_of(&info["plot"])), + cast: text.cast.or_else(|| str_of(&info["cast"])), + director: text.director.or_else(|| str_of(&info["director"])), + release_date: text + .release + .or_else(|| first_str(info, &["releaseDate", "release_date"])), + trailer: text.trailer.or_else(|| str_of(&info["youtube_trailer"])), + seasons, + resume, + versions, + tmdb: facts, + item, + }) +} + +#[cfg(test)] +pub(super) mod tests { + use super::*; + + #[test] + fn episode_titles() { + assert_eq!( + episode_title("Deadly Ties - S01E01", "Deadly Ties", 1), + "Episode 1" + ); + assert_eq!(episode_title("S01E02 - The Pilot", "X", 2), "The Pilot"); + assert_eq!(episode_title("The Pilot", "X", 2), "The Pilot"); + assert_eq!(episode_title("", "X", 3), "Episode 3"); + } + + #[test] + fn backdrop_variants() { + assert_eq!( + first_url(&Value::String("['https://a/b.jpg']".into())).as_deref(), + Some("https://a/b.jpg") + ); + assert_eq!( + first_url(&serde_json::json!(["https://c/d.jpg"])).as_deref(), + Some("https://c/d.jpg") + ); + assert_eq!(first_url(&Value::String("".into())), None); + } + + #[test] + fn m3u_series_read_like_xtream_ones() { + let c = crate::db::test_conn(); + c.execute("INSERT INTO series (source_id, id, name, title, position) VALUES (1, 'sh', 'Show', 'Show', 0)", []) + .unwrap(); + for (id, season, ep, title) in [ + ("a", 1, 2, "Second"), + ("b", 1, 1, ""), + ("c", 2, 1, "Premiere"), + ] { + c.execute( + "INSERT INTO episode (source_id, series_id, id, season, episode, title, url, ext, position) + VALUES (1, 'sh', ?1, ?2, ?3, ?4, 'http://h/x.mkv', 'mkv', 0)", + params![id, season, ep, title], + ) + .unwrap(); + } + let json = m3u_series_json(&c, 1, "sh").unwrap().unwrap(); + let seasons = parse_episodes(&json, "Show", 1, "sh"); + type Shape = Vec<(i64, Vec<(String, i64, String)>)>; + let shape: Shape = seasons + .into_iter() + .map(|(n, eps)| { + ( + n, + eps.into_iter() + .map(|e| (e.id, e.episode, e.title)) + .collect(), + ) + }) + .collect(); + assert_eq!( + shape, + vec![ + ( + 1, + vec![ + ("b".into(), 1, "Episode 1".into()), + ("a".into(), 2, "Second".into()) + ] + ), + (2, vec![("c".into(), 1, "Premiere".into())]), + ] + ); + assert!(m3u_series_json(&c, 1, "missing").unwrap().is_none()); + // Up next works without a provider detail cache + c.execute( + "INSERT INTO history (source_id, kind, item_id, series_id, season, episode, title, watched, updated_at) + VALUES (1, 'episode', 'a', 'sh', 1, 2, 'Show', 1, 100)", + [], + ) + .unwrap(); + let next: Vec = up_next_rows(&c, 20) + .unwrap() + .into_iter() + .map(|u| u.episode.id) + .collect(); + assert_eq!(next, vec!["c"]); + } + + /// Two copies of one show: the Nordic one only has season 5. + pub(in crate::catalog) fn two_copy_show(c: &Connection) { + for (cat, name) in [("ap", "APPLE+ SERIES"), ("sc", "NORDIC SERIES")] { + c.execute("INSERT INTO category (source_id, kind, id, name, title, position) VALUES (1, 'series', ?1, ?2, ?2, 0)", params![cat, name]) + .unwrap(); + } + for (id, tag, cat) in [("full", "A+", "ap"), ("s5", "SC", "sc")] { + c.execute( + "INSERT INTO series (source_id, id, name, title, tag, year, tmdb, category_id, position) + VALUES (1, ?1, 'x', 'Show', ?2, 2019, '777', ?3, 0)", + params![id, tag, cat], + ) + .unwrap(); + } + let eps = |prefix: &str, seasons: std::ops::RangeInclusive| { + let mut map = serde_json::Map::new(); + for season in seasons { + let list: Vec = (1..=3) + .map(|n| serde_json::json!({"id": format!("{prefix}{season}{n}"), "episode_num": n, "title": format!("E{n}")})) + .collect(); + map.insert(season.to_string(), Value::Array(list)); + } + serde_json::json!({ "episodes": map }).to_string() + }; + for (id, json) in [("full", eps("f", 1..=5)), ("s5", eps("n", 5..=5))] { + c.execute("INSERT INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (1, 'series', ?1, ?2, 0)", params![id, json]) + .unwrap(); + } + crate::works::rebuild(c).unwrap(); + } + + fn finish(c: &Connection, series: &str, ep_id: &str, season: i64, episode: i64, at: i64) { + c.execute( + "INSERT OR REPLACE INTO history (source_id, kind, item_id, series_id, season, episode, title, watched, updated_at) + VALUES (1, 'episode', ?1, ?2, ?3, ?4, 'Show', 1, ?5)", + params![ep_id, series, season, episode, at], + ) + .unwrap(); + } + + #[test] + fn up_next_follows_a_show_across_its_copies() { + let c = crate::db::test_conn(); + two_copy_show(&c); + let next = |c: &Connection| -> Vec<(String, String, i64, i64, Option)> { + up_next_rows(c, 20) + .unwrap() + .into_iter() + .map(|u| { + ( + u.episode.series_id, + u.episode.id, + u.episode.season, + u.episode.episode, + u.episode.version, + ) + }) + .collect() + }; + // one entry per show, continuing in the copy being watched + finish(&c, "full", "f11", 1, 1, 100); + assert_eq!(next(&c), vec![("full".into(), "f12".into(), 1, 2, None)]); + // switched to the Nordic copy for season 5: continue there + finish(&c, "s5", "n51", 5, 1, 200); + assert_eq!(next(&c), vec![("s5".into(), "n52".into(), 5, 2, None)]); + // the next one was already seen in the other copy: nothing to offer + finish(&c, "full", "f52", 5, 2, 150); + assert!(next(&c).is_empty()); + // after the Nordic copy's last episode there is nothing more anywhere + finish(&c, "s5", "n53", 5, 3, 300); + assert!(next(&c).is_empty()); + } + + #[test] + fn up_next_takes_missing_episodes_from_another_copy() { + let c = crate::db::test_conn(); + two_copy_show(&c); + // chose the Nordic copy (season 5 only) but watched S4E3 in the full one + c.execute("INSERT INTO work_pref (kind, key, source_id, item_id, updated_at) VALUES ('series', 'tmdb:777', 1, 's5', 0)", []) + .unwrap(); + finish(&c, "full", "f43", 4, 3, 100); + let u = up_next_rows(&c, 20).unwrap(); + assert_eq!(u.len(), 1); + // S5E1 continues in the copy that was being watched + assert_eq!( + ( + u[0].episode.id.as_str(), + u[0].episode.season, + u[0].episode.episode + ), + ("f51", 5, 1) + ); + assert_eq!(u[0].series.title, "Show"); + assert_eq!(u[0].series.work.version_count, 2); + } + + #[test] + fn up_next_follows_the_latest_finished_episode() { + let c = crate::db::test_conn(); + c.execute("INSERT INTO series (source_id, id, name, title, position) VALUES (1, 's1', 'Show', 'Show', 0)", []) + .unwrap(); + let episodes: Vec = (1..=5) + .map(|n| serde_json::json!({"id": format!("e{n}"), "episode_num": n, "title": format!("Show - S01E0{n}")})) + .collect(); + let detail = serde_json::json!({ "episodes": { "1": episodes } }).to_string(); + c.execute("INSERT INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (1, 'series', 's1', ?1, 0)", [detail]) + .unwrap(); + let finish = |ep: i64, at: i64| { + c.execute( + "INSERT OR REPLACE INTO history (source_id, kind, item_id, series_id, season, episode, title, watched, updated_at) + VALUES (1, 'episode', ?1, 's1', 1, ?2, 'Show', 1, ?3)", + params![format!("e{ep}"), ep, at], + ) + .unwrap(); + }; + let next = |c: &Connection| -> Vec { + up_next_rows(c, 20) + .unwrap() + .into_iter() + .map(|u| u.episode.id) + .collect() + }; + + finish(1, 100); + assert_eq!(next(&c), vec!["e2"]); + // two episodes finished within the same second: one entry, after the furthest + finish(4, 200); + finish(2, 200); + assert_eq!(next(&c), vec!["e5"]); + // nothing after the last episode + finish(5, 300); + assert!(next(&c).is_empty()); + } +} diff --git a/src-tauri/src/catalog/guide.rs b/src-tauri/src/catalog/guide.rs new file mode 100644 index 0000000..5565b9f --- /dev/null +++ b/src-tauri/src/catalog/guide.rs @@ -0,0 +1,119 @@ +//! Programme guide: one channel's programmes and the guide grid. + +use super::*; + +#[tauri::command] +pub async fn epg_channel( + state: State<'_, AppState>, + source_id: i64, + channel_id: String, + from: i64, + to: i64, +) -> Result> { + let st = state.inner().clone(); + let (epg_id, rows) = { + let channel_id = channel_id.clone(); + read_blocking(&st, move |conn| { + let epg_id: Option = conn + .query_row( + "SELECT COALESCE(c.epg_id, g.epg_id) FROM channel c LEFT JOIN channel_group g ON g.key = c.group_key + WHERE c.source_id = ?1 AND c.id = ?2", + params![source_id, channel_id], + |r| r.get(0), + ) + .optional()? + .flatten(); + let rows = match &epg_id { + Some(e) => epg::programmes(conn, source_id, e, from, to)?, + None => Vec::new(), + }; + Ok((epg_id, rows)) + }) + .await? + }; + if !rows.is_empty() || epg_id.is_none() { + return Ok(rows); + } + // Fall back to the panel's short EPG (base64 encoded fields). + let src = read_blocking(&st, move |conn| sources::load(conn, source_id)).await?; + if src.kind != SourceKind::Xtream { + return Ok(rows); + } + let Ok(x) = sources::xtream_for(&src, http_client(src.user_agent.as_deref())) else { + return Ok(rows); + }; + let v = match x.short_epg(&channel_id, 24).await { + Ok(v) => v, + Err(e) => { + log::debug!("short epg {channel_id}: {e}"); + return Ok(rows); + } + }; + let b64 = |v: &Value| -> Option { + let s = str_of(v)?; + base64::engine::general_purpose::STANDARD + .decode(s.as_bytes()) + .ok() + .map(|b| String::from_utf8_lossy(&b).trim().to_owned()) + .or(Some(s)) + }; + let list = v["epg_listings"].as_array().cloned().unwrap_or_default(); + Ok(list + .iter() + .filter_map(|p| { + let start = i64_of(&p["start_timestamp"])?; + let stop = i64_of(&p["stop_timestamp"])?; + (stop > from && start < to).then(|| ProgrammeRow { + epg_id: epg_id.clone().unwrap_or_default(), + start, + stop, + title: b64(&p["title"]).unwrap_or_default(), + subtitle: None, + description: b64(&p["description"]), + category: None, + episode: None, + icon: None, + }) + }) + .collect()) +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GuideRow { + pub channel: ChannelItem, + pub programmes: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GuideQuery { + #[serde(flatten)] + pub channels: ChannelQuery, + pub from: i64, + pub to: i64, +} + +/// Channels plus their programmes in a time window (TV guide grid). +#[tauri::command] +pub async fn epg_grid(state: State<'_, AppState>, query: GuideQuery) -> Result> { + read_blocking(state.inner(), move |conn| { + let page = query_channels(conn, &query.channels)?; + let mut items = Vec::with_capacity(page.items.len()); + for channel in page.items { + let programmes = match &channel.epg_id { + Some(e) => epg::programmes(conn, channel.source_id, e, query.from, query.to)?, + None => Vec::new(), + }; + items.push(GuideRow { + channel, + programmes, + }); + } + Ok(Page { + total: page.total, + items, + }) + }) + .await +} diff --git a/src-tauri/src/catalog/mod.rs b/src-tauri/src/catalog/mod.rs new file mode 100644 index 0000000..59ffe78 --- /dev/null +++ b/src-tauri/src/catalog/mod.rs @@ -0,0 +1,263 @@ +//! Read-side commands: categories, channel/movie/series listings, details, +//! programme guide and search. + +mod categories; +mod channels; +mod details; +mod guide; +mod search; +mod works; + +pub use categories::*; +pub use channels::*; +pub use details::*; +pub use guide::*; +pub use search::*; +pub use works::*; + +use std::collections::{BTreeMap, HashMap}; +use std::time::Instant; + +use base64::Engine; +use rusqlite::types::Value as Sql; +use rusqlite::{Connection, OptionalExtension, Row, params, params_from_iter}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tauri::State; + +use crate::db::now; +use crate::epg::{self, ProgrammeRow}; +use crate::error::{Error, Result}; +use crate::kind::{ItemKind, WorkKind}; +use crate::settings; +use crate::sources::{self, SourceKind}; +use crate::state::{AppState, http_client, read_blocking, write_blocking}; +use crate::util::json::{f64_of, first_str, i64_of, str_of}; +use crate::works::versions::{self, VersionInfo}; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Page { + pub total: i64, + pub items: Vec, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CategoryItem { + pub source_id: i64, + pub id: String, + pub title: String, + pub region: Option, + pub badges: Vec, + pub count: i64, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Brief { + pub title: String, + pub start: i64, + pub stop: i64, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelItem { + pub source_id: i64, + pub id: String, + pub num: Option, + pub title: String, + pub logo: Option, + pub epg_id: Option, + pub category_id: Option, + pub badges: Vec, + pub archive: bool, + pub archive_days: i64, + pub favorite: bool, + pub now: Option, + pub next: Option, + /// the channel this feed belongs to (all its quality variants) + pub group: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GroupInfo { + pub key: String, + /// number of feeds (quality variants) of the channel + pub variants: i64, + pub country: Option, + pub genre: String, +} + +/// Grouping info shared by movie and series items (see `works`): the work +/// key and what its versions offer. +#[derive(Debug, Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkInfo { + pub key: Option, + /// number of provider copies of this title (details list them in `versions`) + pub version_count: i64, + /// "4K", "Dolby Vision", "Dolby Audio", "HEVC", "Blu-ray" + pub quality: Vec, + pub services: Vec, +} + +fn work_info( + key: Option, + versions: Option, + badges: Option, + services: Option, +) -> WorkInfo { + let split = |s: Option| -> Vec { + s.unwrap_or_default() + .split('|') + .filter(|x| !x.is_empty()) + .map(str::to_owned) + .collect() + }; + WorkInfo { + version_count: versions.unwrap_or(1), + quality: split(badges), + services: split(services), + key, + } +} + +/// A movie as listed: in browse lists one row per work (`work` table) whose +/// `source_id`/`id` name a representative copy. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MovieItem { + pub source_id: i64, + pub id: String, + pub title: String, + pub year: Option, + pub poster: Option, + pub rating: Option, + pub added: Option, + pub tag: Option, + pub ext: Option, + pub favorite: bool, + /// 0..1 watch progress, when started. + pub progress: Option, + pub watched: bool, + #[serde(flatten)] + pub work: WorkInfo, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SeriesItem { + pub source_id: i64, + pub id: String, + pub title: String, + pub year: Option, + pub cover: Option, + pub backdrop: Option, + pub rating: Option, + pub genre: Option, + pub last_modified: Option, + pub tag: Option, + pub favorite: bool, + #[serde(flatten)] + pub work: WorkInfo, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelQuery { + pub source_id: Option, + pub category_id: Option, + /// one row per channel (`channel_group`) playing its chosen variant, + /// instead of every provider feed + #[serde(default)] + pub grouped: bool, + /// channel groups of one country ("DK") / live genre ("Sports") + pub country: Option, + pub genre: Option, + #[serde(default)] + pub favorites: bool, + /// Only channels that have programme data (TV guide). + #[serde(default)] + pub with_epg: bool, + pub q: Option, + pub offset: Option, + pub limit: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MediaQuery { + /// with `category_id`: a provider category ("collection") + pub source_id: Option, + pub category_id: Option, + #[serde(default)] + pub favorites: bool, + pub q: Option, + /// 'added' (default) | 'title' | 'rating' | 'year' + pub sort: Option, + /// browse facets that must all match (`work_facet`) + #[serde(default)] + pub facets: Vec, + pub offset: Option, + pub limit: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FacetFilter { + pub facet: String, + pub value: String, +} + +const FACETS: &[&str] = &[ + "service", + "language", + "quality", + "genre", + "decade", + "collection", + "original", + "franchise", + "network", +]; + +/// Badges are stored space separated; multi-word ones ("DOLBY VISION") are +/// re-joined here. +pub(crate) fn split_badges(s: String) -> Vec { + let mut out: Vec = Vec::new(); + for w in s.split_whitespace() { + match (out.last_mut(), w) { + (Some(last), "VISION" | "AUDIO") if last == "DOLBY" => { + last.push(' '); + last.push_str(w); + } + _ => out.push(w.to_owned()), + } + } + out +} + +fn like_pattern(q: &str) -> String { + let escaped = q + .trim() + .replace('\\', "\\\\") + .replace('%', "\\%") + .replace('_', "\\_"); + format!("%{escaped}%") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn badge_joining() { + assert_eq!( + split_badges("4K DOLBY VISION HEVC".into()), + vec!["4K", "DOLBY VISION", "HEVC"] + ); + } +} diff --git a/src-tauri/src/catalog/search.rs b/src-tauri/src/catalog/search.rs new file mode 100644 index 0000000..4ca7cf5 --- /dev/null +++ b/src-tauri/src/catalog/search.rs @@ -0,0 +1,129 @@ +//! Full-text search over channels, movies and series. + +use super::*; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchResults { + pub channels: Vec, + pub movies: Vec, + pub series: Vec, +} + +fn fts_query(q: &str) -> Option { + let tokens: Vec = q + .split(|c: char| !c.is_alphanumeric()) + .filter(|t| !t.is_empty()) + .map(|t| format!("\"{}\"*", t.replace('"', ""))) + .collect(); + (!tokens.is_empty()).then(|| tokens.join(" ")) +} + +#[tauri::command] +pub async fn search( + state: State<'_, AppState>, + q: String, + limit: Option, +) -> Result { + let limit = limit.unwrap_or(30).clamp(1, 200); + read_blocking(state.inner(), move |conn| { + let Some(fts) = fts_query(&q) else { + return Ok(SearchResults { channels: vec![], movies: vec![], series: vec![] }); + }; + let t = Instant::now(); + let show_adult = settings::get_bool(conn, "content.showAdult"); + let ids = |kind: ItemKind| -> Result> { + let mut stmt = conn.prepare_cached( + "SELECT source_id, item_id FROM search WHERE search MATCH ?1 AND kind = ?2 ORDER BY rank LIMIT ?3", + )?; + let rows = stmt + .query_map(params![fts, kind, limit * 8], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))? + .collect::, _>>()?; + Ok(rows) + }; + let adult_ok = |table: &str, sid: i64, id: &str| -> bool { + show_adult + || conn + .query_row(&format!("SELECT adult FROM {table} WHERE source_id = ?1 AND id = ?2"), params![sid, id], |r| { + r.get::<_, bool>(0) + }) + .map(|a| !a) + .unwrap_or(false) + }; + // feeds of the same channel collapse into their group + let mut channels: Vec = Vec::new(); + let mut group_of = conn.prepare_cached("SELECT group_key FROM channel WHERE source_id = ?1 AND id = ?2")?; + for (sid, id) in ids(ItemKind::Live)? { + if channels.len() as i64 >= limit { + break; + } + if !adult_ok("channel", sid, &id) { + continue; + } + let key: Option = group_of.query_row(params![sid, id], |r| r.get(0)).optional()?.flatten(); + if key.as_ref().is_some_and(|k| channels.iter().any(|c| c.group.as_ref().is_some_and(|g| &g.key == k))) { + continue; + } + let c = match &key { + Some(k) => channel_group_by_key(conn, k), + None => channel_by_id(conn, sid, &id), + }; + if let Ok(c) = c { + channels.push(c); + } + } + // copies of the same title collapse into their work + let works = |kind: WorkKind| -> Result> { + let table = kind.table(); + let mut key_of = conn.prepare_cached(&format!("SELECT work_key FROM {table} WHERE source_id = ?1 AND id = ?2"))?; + let mut keys: Vec = Vec::new(); + for (sid, id) in ids(kind.into())? { + if keys.len() as i64 >= limit { + break; + } + if !adult_ok(table, sid, &id) { + continue; + } + if let Some(Some(k)) = key_of.query_row(params![sid, id], |r| r.get::<_, Option>(0)).optional()? + && !keys.contains(&k) + { + keys.push(k); + } + } + Ok(keys) + }; + let mut movies = Vec::new(); + { + let mut stmt = conn.prepare_cached(&format!("{} WHERE w.kind = 'movie' AND w.key = ?1", movie_work_select()))?; + for key in works(WorkKind::Movie)? { + if let Some(m) = stmt.query_row([key], row_to_movie).optional()? { + movies.push(m); + } + } + } + let mut series = Vec::new(); + { + let mut stmt = conn.prepare_cached(&format!("{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1"))?; + for key in works(WorkKind::Series)? { + if let Some(s) = stmt.query_row([key], row_to_series).optional()? { + series.push(s); + } + } + } + log::debug!("search {q:?}: {}/{}/{} in {:?}", channels.len(), movies.len(), series.len(), t.elapsed()); + Ok(SearchResults { channels, movies, series }) + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fts_queries() { + assert_eq!(fts_query("bbc news").as_deref(), Some("\"bbc\"* \"news\"*")); + assert_eq!(fts_query(" \" ").as_deref(), None); + assert_eq!(fts_query("top-gun").as_deref(), Some("\"top\"* \"gun\"*")); + } +} diff --git a/src-tauri/src/catalog/works.rs b/src-tauri/src/catalog/works.rs new file mode 100644 index 0000000..85bdcd0 --- /dev/null +++ b/src-tauri/src/catalog/works.rs @@ -0,0 +1,517 @@ +//! Movie and series listings (one row per work) and their browse facets. + +use super::*; + +/// One movie copy with its work's grouping info. +pub(super) const MOVIE_SELECT: &str = " + SELECT m.source_id, m.id, m.title, m.year, m.poster, m.rating, m.added, m.tag, m.ext, + EXISTS(SELECT 1 FROM favorite f WHERE f.source_id = m.source_id AND f.kind = 'movie' AND f.item_id = m.id), + h.position, h.duration, COALESCE(h.watched, 0), + m.work_key, w.versions, w.badges, w.services + FROM movie m + LEFT JOIN history h ON h.source_id = m.source_id AND h.kind = 'movie' AND h.item_id = m.id + LEFT JOIN work w ON w.kind = 'movie' AND w.key = m.work_key"; + +/// Watch state of a movie work: the most recently played copy. +fn work_history(col: &str) -> String { + format!( + "(SELECT h.{col} FROM movie hm JOIN history h ON h.source_id = hm.source_id AND h.kind = 'movie' AND h.item_id = hm.id + WHERE hm.work_key = w.key ORDER BY h.updated_at DESC LIMIT 1)" + ) +} + +/// One movie work (browse lists), same columns as `MOVIE_SELECT`. +pub(super) fn movie_work_select() -> String { + format!( + "SELECT w.source_id, w.item_id, w.title, w.year, w.poster, w.rating, w.added, m.tag, m.ext, + EXISTS(SELECT 1 FROM favorite f JOIN movie fm ON fm.source_id = f.source_id AND fm.id = f.item_id + WHERE f.kind = 'movie' AND fm.work_key = w.key), + {}, {}, COALESCE({}, 0), + w.key, w.versions, w.badges, w.services + FROM work w + LEFT JOIN movie m ON m.source_id = w.source_id AND m.id = w.item_id", + work_history("position"), + work_history("duration"), + work_history("watched") + ) +} + +pub(super) fn row_to_movie(r: &Row) -> rusqlite::Result { + let pos: Option = r.get(10)?; + let dur: Option = r.get(11)?; + Ok(MovieItem { + source_id: r.get(0)?, + id: r.get(1)?, + title: r.get(2)?, + year: r.get(3)?, + poster: r.get(4)?, + rating: r.get(5)?, + added: r.get(6)?, + tag: r.get(7)?, + ext: r.get(8)?, + favorite: r.get(9)?, + progress: match (pos, dur) { + (Some(p), Some(d)) if d > 0.0 && p > 0.0 => Some((p / d).clamp(0.0, 1.0)), + _ => None, + }, + watched: r.get(12)?, + work: work_info(r.get(13)?, r.get(14)?, r.get(15)?, r.get(16)?), + }) +} + +/// One series copy with its work's grouping info. +pub(super) const SERIES_SELECT: &str = " + SELECT s.source_id, s.id, s.title, s.year, s.cover, s.backdrop, s.rating, s.genre, s.last_modified, s.tag, + EXISTS(SELECT 1 FROM favorite f WHERE f.source_id = s.source_id AND f.kind = 'series' AND f.item_id = s.id), + s.work_key, w.versions, w.badges, w.services + FROM series s + LEFT JOIN work w ON w.kind = 'series' AND w.key = s.work_key"; + +/// One series work (browse lists), same columns as `SERIES_SELECT`. +pub(super) const SERIES_WORK_SELECT: &str = " + SELECT w.source_id, w.item_id, w.title, w.year, w.poster, w.backdrop, w.rating, w.genre, w.added, s.tag, + EXISTS(SELECT 1 FROM favorite f JOIN series fs ON fs.source_id = f.source_id AND fs.id = f.item_id + WHERE f.kind = 'series' AND fs.work_key = w.key), + w.key, w.versions, w.badges, w.services + FROM work w + LEFT JOIN series s ON s.source_id = w.source_id AND s.id = w.item_id"; + +pub(super) fn row_to_series(r: &Row) -> rusqlite::Result { + Ok(SeriesItem { + source_id: r.get(0)?, + id: r.get(1)?, + title: r.get(2)?, + year: r.get(3)?, + cover: r.get(4)?, + backdrop: r.get(5)?, + rating: r.get(6)?, + genre: r.get(7)?, + last_modified: r.get(8)?, + tag: r.get(9)?, + favorite: r.get(10)?, + work: work_info(r.get(11)?, r.get(12)?, r.get(13)?, r.get(14)?), + }) +} + +/// Browse lists: one row per work. Filters match through the members, so a +/// work shows up in every provider category and facet any copy belongs to. +/// WHERE clause over `work w` for a browse query (`?1` = kind). Facet +/// `skip` is left out — facet counts show what choosing another value of +/// that facet would give. +fn work_filters( + conn: &Connection, + q: &MediaQuery, + kind: WorkKind, + skip: Option<&str>, +) -> Result<(String, Vec)> { + let table = kind.table(); + let mut args: Vec = vec![Sql::Text(kind.as_str().to_owned())]; + let mut filters: Vec = vec!["w.kind = ?1".into()]; + if !settings::get_bool(conn, "content.showAdult") { + filters.push("w.adult = 0".into()); + } + match (q.source_id, &q.category_id) { + (Some(s), Some(cat)) => { + args.push(Sql::Integer(s)); + args.push(Sql::Text(cat.clone())); + filters.push(format!( + "w.key IN (SELECT work_key FROM {table} WHERE source_id = ?{} AND category_id = ?{})", + args.len() - 1, + args.len() + )); + } + (Some(s), None) => { + args.push(Sql::Integer(s)); + filters.push(format!( + "w.key IN (SELECT work_key FROM {table} WHERE source_id = ?{})", + args.len() + )); + } + _ => {} + } + for f in &q.facets { + if !FACETS.contains(&f.facet.as_str()) { + return Err(Error::msg(format!("unknown facet {}", f.facet))); + } + if skip == Some(f.facet.as_str()) { + continue; + } + args.push(Sql::Text(f.facet.clone())); + args.push(Sql::Text(f.value.clone())); + filters.push(format!( + "w.key IN (SELECT key FROM work_facet WHERE kind = ?1 AND facet = ?{} AND value = ?{})", + args.len() - 1, + args.len() + )); + } + if q.favorites { + filters.push(format!( + "w.key IN (SELECT x.work_key FROM favorite f JOIN {table} x ON x.source_id = f.source_id AND x.id = f.item_id + WHERE f.kind = ?1)" + )); + } + if let Some(text) = q.q.as_deref().filter(|t| !t.trim().is_empty()) { + // any copy's title: "Kastanjemanden" finds "The Chestnut Man" + args.push(Sql::Text(like_pattern(text))); + filters.push(format!( + "w.key IN (SELECT work_key FROM {table} WHERE title LIKE ?{} ESCAPE '\\')", + args.len() + )); + } + Ok((filters.join(" AND "), args)) +} + +fn query_works( + conn: &Connection, + q: &MediaQuery, + kind: WorkKind, + select: &str, + map: fn(&Row) -> rusqlite::Result, +) -> Result> { + let table = kind.table(); + let (where_sql, args) = work_filters(conn, q, kind, None)?; + let order = match (q.favorites, q.sort.as_deref().unwrap_or("added")) { + (true, _) => format!( + "(SELECT MAX(f.added_at) FROM favorite f JOIN {table} x ON x.source_id = f.source_id AND x.id = f.item_id + WHERE f.kind = ?1 AND x.work_key = w.key) DESC" + ), + (_, "title") => "w.title COLLATE NOCASE".to_owned(), + (_, "rating") => "w.rating IS NULL, w.rating DESC, w.title COLLATE NOCASE".to_owned(), + (_, "year") => "w.year IS NULL, w.year DESC, w.title COLLATE NOCASE".to_owned(), + (_, "provider") => format!( + "w.source_id, (SELECT position FROM {table} x WHERE x.source_id = w.source_id AND x.id = w.item_id)" + ), + _ => "w.added IS NULL, w.added DESC, w.title COLLATE NOCASE".to_owned(), + }; + let total: i64 = conn + .prepare_cached(&format!("SELECT COUNT(*) FROM work w WHERE {where_sql}"))? + .query_row(params_from_iter(args.iter()), |r| r.get(0))?; + let limit = q.limit.unwrap_or(120).clamp(1, 2000); + let offset = q.offset.unwrap_or(0).max(0); + let sql = format!("{select} WHERE {where_sql} ORDER BY {order} LIMIT {limit} OFFSET {offset}"); + let items = conn + .prepare_cached(&sql)? + .query_map(params_from_iter(args.iter()), map)? + .collect::, _>>()?; + Ok(Page { total, items }) +} + +#[tauri::command] +pub async fn movies(state: State<'_, AppState>, query: MediaQuery) -> Result> { + read_blocking(state.inner(), move |conn| { + let t = Instant::now(); + let page = query_works( + conn, + &query, + WorkKind::Movie, + &movie_work_select(), + row_to_movie, + )?; + log::debug!( + "movies {:?}/{:?}: {} of {} in {:?}", + query.category_id, + query.sort, + page.items.len(), + page.total, + t.elapsed() + ); + Ok(page) + }) + .await +} + +#[tauri::command] +pub async fn series_list( + state: State<'_, AppState>, + query: MediaQuery, +) -> Result> { + read_blocking(state.inner(), move |conn| { + query_works( + conn, + &query, + WorkKind::Series, + SERIES_WORK_SELECT, + row_to_series, + ) + }) + .await +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FacetValue { + pub value: String, + /// display name (collections: the provider category) + pub label: String, + /// works, not copies + pub count: i64, + /// collections: service/language group they are shown under + pub group: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Facets { + pub total: i64, + pub service: Vec, + pub genre: Vec, + pub language: Vec, + pub quality: Vec, + pub decade: Vec, + pub collection: Vec, + /// from TMDB: original language, movie collections, TV networks + pub original: Vec, + pub franchise: Vec, + pub network: Vec, +} + +/// Everything the Movies / Series browse panel offers, with work counts. +/// Facet values with the number of works each would show, given the rest +/// of `query` (its other facets, favorites, text filter). +#[tauri::command] +pub async fn work_facets( + state: State<'_, AppState>, + kind: WorkKind, + query: Option, +) -> Result { + read_blocking(state.inner(), move |conn| { + let t = Instant::now(); + let f = facets_for(conn, kind, &query.unwrap_or_default())?; + log::debug!("{kind} facets in {:?}", t.elapsed()); + Ok(f) + }) + .await +} + +pub fn facets_for(conn: &Connection, kind: WorkKind, q: &MediaQuery) -> Result { + let show_adult = settings::get_bool(conn, "content.showAdult"); + let (where_sql, args) = work_filters(conn, q, kind, None)?; + let total: i64 = conn + .prepare_cached(&format!("SELECT COUNT(*) FROM work w WHERE {where_sql}"))? + .query_row(params_from_iter(args.iter()), |r| r.get(0))?; + let count = |facet: Option<&str>| -> Result> { + let (where_sql, args) = work_filters(conn, q, kind, facet)?; + let only = facet + .map(|f| format!("AND f.facet = '{f}'")) + .unwrap_or_default(); + Ok(conn + .prepare_cached(&format!( + "SELECT f.facet, f.value, COUNT(*) FROM work_facet f + JOIN work w ON w.kind = f.kind AND w.key = f.key + WHERE f.kind = ?1 {only} AND {where_sql} + GROUP BY f.facet, f.value" + ))? + .query_map(params_from_iter(args.iter()), |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?)) + })? + .collect::>()?) + }; + let narrowed = q.favorites + || q.source_id.is_some() + || !q.facets.is_empty() + || q.q.as_deref().is_some_and(|t| !t.trim().is_empty()); + let rows = if narrowed { + // each facet counted without its own selection (FACETS are fixed names) + let mut rows = Vec::new(); + for f in FACETS { + rows.extend(count(Some(f))?); + } + rows + } else { + count(None)? + }; + let mut out = Facets { + total, + service: vec![], + genre: vec![], + language: vec![], + quality: vec![], + decade: vec![], + collection: vec![], + original: vec![], + franchise: vec![], + network: vec![], + }; + // provider categories behind the collection values + let cats: std::collections::HashMap = conn + .prepare_cached( + "SELECT source_id, id, name, position, adult FROM category WHERE kind = ?1", + )? + .query_map([kind], |r| { + let sid: i64 = r.get(0)?; + let id: String = r.get(1)?; + Ok(( + format!("{sid}:{id}"), + (r.get(2)?, sid, r.get(3)?, r.get(4)?), + )) + })? + .collect::>()?; + let mut collections: Vec<(i64, i64, FacetValue)> = Vec::new(); + for (facet, value, count) in rows { + let label = value.clone(); + let fv = FacetValue { + value, + label, + count, + group: None, + }; + match facet.as_str() { + "service" => out.service.push(fv), + "genre" => out.genre.push(fv), + "language" => out.language.push(fv), + "quality" => out.quality.push(fv), + "decade" => out.decade.push(fv), + "original" => out.original.push(fv), + "franchise" => out.franchise.push(fv), + "network" => out.network.push(fv), + "collection" => { + if let Some((name, sid, pos, adult)) = cats.get(&fv.value) + && (show_adult || !adult) + { + let v = crate::works::variant::parse(None, Some(name)); + let group = v.service.or(v.language).unwrap_or("Other").to_owned(); + let label = crate::names::display_category(name); + collections.push(( + *sid, + *pos, + FacetValue { + label, + group: Some(group), + ..fv + }, + )); + } + } + _ => {} + } + } + let by_count = |v: &mut Vec| { + v.sort_by(|a, b| b.count.cmp(&a.count).then(a.label.cmp(&b.label))) + }; + by_count(&mut out.service); + by_count(&mut out.language); + by_count(&mut out.original); + by_count(&mut out.franchise); + by_count(&mut out.network); + out.genre.sort_by_key(|g| { + crate::works::genre::GENRES + .iter() + .position(|x| *x == g.value) + .unwrap_or(usize::MAX) + }); + const QUALITY: &[&str] = &["4K", "Dolby Vision", "Dolby Audio", "HEVC", "Blu-ray"]; + out.quality.sort_by_key(|q| { + QUALITY + .iter() + .position(|x| *x == q.value) + .unwrap_or(usize::MAX) + }); + // newest decade first, "Older" last + out.decade.sort_by(|a, b| { + let key = |v: &str| { + if v == "Older" { + 0 + } else { + v.trim_end_matches('s').parse::().unwrap_or(0) + } + }; + key(&b.value).cmp(&key(&a.value)) + }); + collections.sort_by_key(|(sid, pos, _)| (*sid, *pos)); + out.collection = collections.into_iter().map(|(_, _, f)| f).collect(); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::catalog::details::tests::two_copy_show; + + #[test] + fn works_list_one_row_per_title_and_filter_through_copies() { + let c = crate::db::test_conn(); + two_copy_show(&c); + let q = |q: MediaQuery| { + query_works(&c, &q, WorkKind::Series, SERIES_WORK_SELECT, row_to_series).unwrap() + }; + let all = q(MediaQuery::default()); + assert_eq!((all.total, all.items[0].work.version_count), (1, 2)); + // a category of either copy finds the work + let nordic = q(MediaQuery { + source_id: Some(1), + category_id: Some("sc".into()), + ..Default::default() + }); + assert_eq!(nordic.total, 1); + let by_service = q(MediaQuery { + facets: vec![FacetFilter { + facet: "service".into(), + value: "Apple TV+".into(), + }], + ..Default::default() + }); + assert_eq!(by_service.total, 1); + let none = q(MediaQuery { + facets: vec![FacetFilter { + facet: "service".into(), + value: "Netflix".into(), + }], + ..Default::default() + }); + assert_eq!(none.total, 0); + let bad = query_works( + &c, + &MediaQuery { + facets: vec![FacetFilter { + facet: "x; DROP".into(), + value: "1".into(), + }], + ..Default::default() + }, + WorkKind::Series, + SERIES_WORK_SELECT, + row_to_series, + ); + assert!(bad.is_err()); + let f = facets_for(&c, WorkKind::Series, &MediaQuery::default()).unwrap(); + assert_eq!(f.total, 1); + assert!( + f.service + .iter() + .any(|v| v.value == "Apple TV+" && v.count == 1) + ); + assert!( + f.collection + .iter() + .any(|v| v.value == "1:sc" && v.group.as_deref() == Some("Nordic")) + ); + assert!(f.collection.iter().any(|v| v.label == "Apple+ Series")); + // counts follow the other filters but not the facet's own choice + c.execute( + "INSERT INTO series (source_id, id, name, title, tag, year, tmdb, category_id, position) + VALUES (1, 'nf', 'x', 'Other', 'NF', 2001, '888', 'ap', 0)", + [], + ) + .unwrap(); + crate::works::rebuild(&c).unwrap(); + let netflix = MediaQuery { + facets: vec![FacetFilter { + facet: "service".into(), + value: "Netflix".into(), + }], + ..Default::default() + }; + let f = facets_for(&c, WorkKind::Series, &netflix).unwrap(); + assert_eq!(f.total, 1); + let count = + |v: &[FacetValue], value: &str| v.iter().find(|x| x.value == value).map(|x| x.count); + assert_eq!( + (count(&f.service, "Netflix"), count(&f.service, "Apple TV+")), + (Some(1), Some(1)) + ); + assert_eq!( + (count(&f.decade, "2000s"), count(&f.decade, "2010s")), + (Some(1), None) + ); + } +} diff --git a/src-tauri/src/devtools.rs b/src-tauri/src/devtools.rs index db44b76..dcdb417 100644 --- a/src-tauri/src/devtools.rs +++ b/src-tauri/src/devtools.rs @@ -33,6 +33,19 @@ use tauri::{AppHandle, Manager, Runtime}; /// Pages that may use the bridge: the Vite dev server (`bun run dev`). const ALLOWED_ORIGINS: &[&str] = &["http://localhost:1420", "http://127.0.0.1:1420"]; const MAX_BODY: usize = 16 << 20; +/// How long a client gets to send its request. +const READ_TIMEOUT: Duration = Duration::from_secs(10); +/// Main-thread work (snapshot, click) that does not report back by then +/// failed (the main loop is wedged or the window is gone). +#[cfg(target_os = "linux")] +const MAIN_THREAD_TIMEOUT: Duration = Duration::from_secs(10); +/// Longest a script may run in the webview (Linux). +#[cfg(target_os = "linux")] +const EVAL_TIMEOUT: Duration = Duration::from_secs(20); +/// macOS: longer than the wrapper's ~10 s IPC retry loop (`eval_wrapper`) on +/// top of the script's own run time, so its error result arrives first. +#[cfg(target_os = "macos")] +const EVAL_TIMEOUT: Duration = Duration::from_secs(25); pub fn start(app: &AppHandle) { let port: u16 = std::env::var("TP_DEV_PORT") @@ -97,7 +110,7 @@ fn check_request(method: &str, path: &str, port: u16, h: &Headers) -> Result<(), } fn handle(mut stream: TcpStream, app: &AppHandle, port: u16) -> std::io::Result<()> { - stream.set_read_timeout(Some(Duration::from_secs(10)))?; + stream.set_read_timeout(Some(READ_TIMEOUT))?; let mut reader = BufReader::new(stream.try_clone()?); let mut request_line = String::new(); reader.read_line(&mut request_line)?; @@ -243,7 +256,7 @@ fn invoke_via_webview(app: &AppHandle, body: &str) -> Result(app: &AppHandle, out: &str) -> Result<(), String> { let _ = tx.send(result); }) .map_err(|e| e.to_string())?; - rx.recv_timeout(Duration::from_secs(10)) + rx.recv_timeout(MAIN_THREAD_TIMEOUT) .map_err(|e| e.to_string())? } @@ -347,6 +360,11 @@ fn click(app: &AppHandle, x: f64, y: f64) -> Result<(), String> { let pointer = seat.pointer().ok_or("no pointer")?; for kind in [gdk::EventType::ButtonPress, gdk::EventType::ButtonRelease] { let mut ev = gdk::Event::new(kind); + // SAFETY: on the GTK main thread (`with_webview`). `ev` + // was created as a button event, so its GdkEvent union + // is a GdkEventButton. `to_glib_full` gives the event the + // window reference it releases when freed; `pointer` + // outlives `ev`, so the device it records stays valid. unsafe { let raw: *mut gdk::ffi::GdkEvent = ev.to_glib_none_mut().0; let b = raw as *mut gdk::ffi::GdkEventButton; @@ -367,7 +385,7 @@ fn click(app: &AppHandle, x: f64, y: f64) -> Result<(), String> { let _ = tx.send(result); }) .map_err(|e| e.to_string())?; - rx.recv_timeout(Duration::from_secs(10)) + rx.recv_timeout(MAIN_THREAD_TIMEOUT) .map_err(|e| e.to_string())? } @@ -411,8 +429,7 @@ fn eval(app: &AppHandle, js: &str) -> Result { ); }) .map_err(|e| e.to_string())?; - rx.recv_timeout(Duration::from_secs(20)) - .map_err(|e| e.to_string())? + rx.recv_timeout(EVAL_TIMEOUT).map_err(|e| e.to_string())? } /// macOS: WKWebView's `evaluateJavaScript` completion path loses the result @@ -446,7 +463,7 @@ fn eval(app: &AppHandle, js: &str) -> Result { eval_bus::unregister(id); return Err("evaluateJavaScript dispatch failed".into()); } - let r = rx.recv_timeout(Duration::from_secs(25)); + let r = rx.recv_timeout(EVAL_TIMEOUT); eval_bus::unregister(id); r.map_err(|e| format!("evaluateJavaScript completion never fired: {e}"))? } @@ -479,15 +496,24 @@ mod eval_bus { } pub fn register(id: u64, tx: Tx) { - channels().lock().unwrap().insert(id, tx); + channels() + .lock() + .expect("no panics while held") + .insert(id, tx); } pub fn unregister(id: u64) { - channels().lock().unwrap().remove(&id); + channels().lock().expect("no panics while held").remove(&id); } pub fn resolve(id: u64, result: String) -> bool { - let tx = { channels().lock().unwrap().get(&id).cloned() }; + let tx = { + channels() + .lock() + .expect("no panics while held") + .get(&id) + .cloned() + }; match tx { Some(tx) => tx.send(Ok(result)).is_ok(), None => false, diff --git a/src-tauri/src/error.rs b/src-tauri/src/error.rs index 2a7335d..5eb819c 100644 --- a/src-tauri/src/error.rs +++ b/src-tauri/src/error.rs @@ -19,6 +19,10 @@ pub enum Error { Json(#[from] serde_json::Error), #[error("{0}")] Tauri(#[from] tauri::Error), + /// TMDB refused the API key (401/403); stops a run instead of counting as + /// one failed title. + #[error("TMDB did not accept the API key")] + TmdbRejected, } impl From for Error { diff --git a/src-tauri/src/images.rs b/src-tauri/src/images.rs index c2d40d8..bfb5683 100644 --- a/src-tauri/src/images.rs +++ b/src-tauri/src/images.rs @@ -20,7 +20,7 @@ use tokio::sync::Semaphore; use crate::error::{Error, Result}; use crate::settings; -use crate::state::AppState; +use crate::state::{AppState, read_blocking}; use crate::util::fnv1a; /// Dead links are remembered this long (`.miss` markers). @@ -52,7 +52,7 @@ fn status(code: StatusCode) -> Response> { .status(code) .header("Access-Control-Allow-Origin", "*") .body(Vec::new()) - .unwrap() + .expect("static status and headers are valid") } fn content_type(bytes: &[u8]) -> &'static str { @@ -87,7 +87,7 @@ fn ok(bytes: Vec) -> Response> { .header("Cache-Control", "public, max-age=604800, immutable") .header("Access-Control-Allow-Origin", "*") .body(bytes) - .unwrap() + .expect("static headers are valid") } fn params(request: &Request>) -> Option<(String, u32)> { @@ -293,13 +293,14 @@ fn cache_dir(st: &AppState) -> PathBuf { /// Applies the size limit (setting `cache.imagesMb`) in the background. pub async fn enforce_limit(st: AppState) { - let cap_mb = { - let conn = st.db.read(); - settings::get(&conn, "cache.imagesMb") - .as_u64() - .unwrap_or(DEFAULT_CACHE_MB) - .max(16) - }; + let cap_mb = read_blocking(&st, |conn| { + Ok(settings::get(conn, "cache.imagesMb").as_u64()) + }) + .await + .ok() + .flatten() + .unwrap_or(DEFAULT_CACHE_MB) + .max(16); let dir = cache_dir(&st); match tokio::task::spawn_blocking(move || prune(&dir, cap_mb << 20, SystemTime::now())).await { Ok(Ok(s)) => log::info!( diff --git a/src-tauri/src/kind.rs b/src-tauri/src/kind.rs new file mode 100644 index 0000000..d28b981 --- /dev/null +++ b/src-tauri/src/kind.rs @@ -0,0 +1,178 @@ +//! What a catalog item is. The same lowercase names are used in the +//! database (`kind` columns), on the wire to the UI, and in the `search` +//! index, so a typo can't silently select the wrong table. + +use std::fmt; + +use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; +use serde::{Deserialize, Serialize}; + +/// Any catalog item: categories, favorites, history and track info are +/// keyed by it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ItemKind { + Live, + Movie, + Series, + Episode, +} + +impl ItemKind { + pub fn as_str(self) -> &'static str { + match self { + ItemKind::Live => "live", + ItemKind::Movie => "movie", + ItemKind::Series => "series", + ItemKind::Episode => "episode", + } + } + + /// The kind's own catalog table. + pub fn table(self) -> &'static str { + match self { + ItemKind::Live => "channel", + ItemKind::Movie => "movie", + ItemKind::Series => "series", + ItemKind::Episode => "episode", + } + } +} + +/// The kinds that are grouped into works (copies of the same film or show +/// across categories and sources). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WorkKind { + Movie, + Series, +} + +impl WorkKind { + pub fn as_str(self) -> &'static str { + ItemKind::from(self).as_str() + } + + pub fn table(self) -> &'static str { + ItemKind::from(self).table() + } + + /// The tmdb table's spelling: our "series" are TMDB's "tv". + pub fn tmdb(self) -> &'static str { + match self { + WorkKind::Movie => "movie", + WorkKind::Series => "tv", + } + } +} + +impl From for ItemKind { + fn from(k: WorkKind) -> Self { + match k { + WorkKind::Movie => ItemKind::Movie, + WorkKind::Series => ItemKind::Series, + } + } +} + +/// What `play` opens: a catalog item, or a past programme of a channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum PlayKind { + #[default] + Live, + Movie, + Episode, + Catchup, +} + +impl PlayKind { + /// The catalog item behind a file whose tracks are worth remembering + /// (the version picker shows them): movies and episodes. + pub fn file_item(self) -> Option { + match self { + PlayKind::Movie => Some(ItemKind::Movie), + PlayKind::Episode => Some(ItemKind::Episode), + PlayKind::Live | PlayKind::Catchup => None, + } + } +} + +impl fmt::Display for PlayKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + PlayKind::Live => "live", + PlayKind::Movie => "movie", + PlayKind::Episode => "episode", + PlayKind::Catchup => "catchup", + }) + } +} + +impl fmt::Display for ItemKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl fmt::Display for WorkKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl ToSql for ItemKind { + fn to_sql(&self) -> rusqlite::Result> { + Ok(ToSqlOutput::from(self.as_str())) + } +} + +impl FromSql for ItemKind { + fn column_result(v: ValueRef<'_>) -> FromSqlResult { + match v.as_str()? { + "live" => Ok(ItemKind::Live), + "movie" => Ok(ItemKind::Movie), + "series" => Ok(ItemKind::Series), + "episode" => Ok(ItemKind::Episode), + other => Err(FromSqlError::Other( + format!("unknown item kind {other:?}").into(), + )), + } + } +} + +impl ToSql for WorkKind { + fn to_sql(&self) -> rusqlite::Result> { + Ok(ToSqlOutput::from(self.as_str())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wire_names_match_the_database() { + for k in [ + ItemKind::Live, + ItemKind::Movie, + ItemKind::Series, + ItemKind::Episode, + ] { + assert_eq!(serde_json::to_value(k).unwrap(), k.as_str()); + assert_eq!( + serde_json::from_value::(k.as_str().into()).unwrap(), + k + ); + } + assert!(serde_json::from_str::("\"live\"").is_err()); + let c = rusqlite::Connection::open_in_memory().unwrap(); + let k: ItemKind = c + .query_row("SELECT ?1", [ItemKind::Episode], |r| r.get(0)) + .unwrap(); + assert_eq!(k, ItemKind::Episode); + assert_eq!(WorkKind::Series.table(), "series"); + assert_eq!(WorkKind::Series.tmdb(), "tv"); + assert_eq!(ItemKind::Live.table(), "channel"); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 45b8ea0..f884906 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -6,6 +6,7 @@ mod devtools; mod epg; mod error; mod images; +mod kind; mod library; mod names; mod playback; @@ -27,6 +28,10 @@ use tauri::Manager; /// Catalog / EPG refresh policy for background syncs. const CATALOG_MAX_AGE: i64 = 12 * 3600; const EPG_MAX_AGE: i64 = 6 * 3600; +const STALE_CHECK_EVERY: Duration = Duration::from_secs(30 * 60); +const CACHE_LIMIT_DELAY: Duration = Duration::from_secs(60); +const CACHE_LIMIT_EVERY: Duration = Duration::from_secs(6 * 3600); +const TMDB_DELAY: Duration = Duration::from_secs(20); pub fn run() { env_logger::Builder::from_env( @@ -70,10 +75,11 @@ pub fn run() { syncing: Default::default(), }); app.manage(st.clone()); + app.manage(Arc::new(probe::Probe::default())); let window = app.get_webview_window("main").expect("main window"); match player::init(app.handle(), &window) { - Ok(()) => settings::apply_player(app.handle(), &st, None), + Ok(()) => settings::apply_player(app.handle(), &st.db.read(), None), Err(e) => log::error!("native player unavailable: {e}"), } cast::init(app.handle()); @@ -84,31 +90,31 @@ pub fn run() { // Artwork cache size limit: shortly after startup, then every 6 h. let cache_state = st.clone(); tauri::async_runtime::spawn(async move { - tokio::time::sleep(Duration::from_secs(60)).await; - let mut tick = tokio::time::interval(Duration::from_secs(6 * 3600)); + tokio::time::sleep(CACHE_LIMIT_DELAY).await; + let mut tick = tokio::time::interval(CACHE_LIMIT_EVERY); loop { tick.tick().await; images::enforce_limit(cache_state.clone()).await; } }); - // Keep catalogs and guides fresh: a first pass as soon as the // TMDB details of titles added since the last run (tmdb.rs), after // startup settled; syncs start further runs. let (tmdb_app, tmdb_state) = (app.handle().clone(), st.clone()); tauri::async_runtime::spawn(async move { - tokio::time::sleep(Duration::from_secs(20)).await; + tokio::time::sleep(TMDB_DELAY).await; tmdb::spawn(tmdb_app, tmdb_state); }); + // Keep catalogs and guides fresh: a first pass as soon as the // keyring passwords are loaded (secrets.rs), then every 30 min. let handle = app.handle().clone(); tauri::async_runtime::spawn(async move { secrets::startup(&st).await; - let mut tick = tokio::time::interval(Duration::from_secs(30 * 60)); + let mut tick = tokio::time::interval(STALE_CHECK_EVERY); tick.tick().await; loop { - sources::sync_stale(&handle, &st, CATALOG_MAX_AGE, EPG_MAX_AGE); + sources::sync_stale(&handle, &st, CATALOG_MAX_AGE, EPG_MAX_AGE).await; tick.tick().await; // a keyring that was locked until now (no prompt) secrets::ensure_loaded(&st, None, secrets::Unlock::Never).await; diff --git a/src-tauri/src/library.rs b/src-tauri/src/library.rs index 162ecc7..fcc90f8 100644 --- a/src-tauri/src/library.rs +++ b/src-tauri/src/library.rs @@ -8,47 +8,47 @@ use tauri::State; use crate::catalog::channel_by_id; use crate::db::now; use crate::error::{Error, Result}; -use crate::state::AppState; +use crate::kind::ItemKind; +use crate::state::{AppState, read_blocking, write_blocking}; #[tauri::command] pub async fn favorite_toggle( state: State<'_, AppState>, - kind: String, + kind: ItemKind, source_id: i64, item_id: String, ) -> Result { - if !matches!(kind.as_str(), "live" | "movie" | "series") { - return Err(Error::msg(format!("cannot favorite {kind}"))); - } - let conn = state.db.write(); - toggle_favorite(&conn, &kind, source_id, &item_id) + write_blocking(state.inner(), move |conn| { + toggle_favorite(conn, kind, source_id, &item_id) + }) + .await } /// Movies and series are favorites as a whole: a work counts as favorite when /// any of its copies is, and un-favoriting clears every copy. pub fn toggle_favorite( conn: &Connection, - kind: &str, + kind: ItemKind, source_id: i64, item_id: &str, ) -> Result { - let removed = if kind == "live" { - conn.execute( + let removed = match kind { + ItemKind::Live => conn.execute( "DELETE FROM favorite WHERE source_id = ?1 AND kind = ?2 AND item_id = ?3", params![source_id, kind, item_id], - )? - } else { - let table = if kind == "movie" { "movie" } else { "series" }; - conn.execute( + )?, + ItemKind::Episode => return Err(Error::msg("cannot favorite an episode")), + ItemKind::Movie | ItemKind::Series => conn.execute( &format!( "DELETE FROM favorite WHERE kind = ?2 AND ( (source_id = ?1 AND item_id = ?3) OR (source_id, item_id) IN ( SELECT x.source_id, x.id FROM {table} x - WHERE x.work_key = (SELECT work_key FROM {table} WHERE source_id = ?1 AND id = ?3)))" + WHERE x.work_key = (SELECT work_key FROM {table} WHERE source_id = ?1 AND id = ?3)))", + table = kind.table() ), params![source_id, kind, item_id], - )? + )?, }; if removed > 0 { return Ok(false); @@ -90,7 +90,10 @@ pub async fn channel_prefer( source_id: i64, id: String, ) -> Result<()> { - prefer_channel(&state.db.write(), &key, source_id, &id) + write_blocking(state.inner(), move |conn| { + prefer_channel(conn, &key, source_id, &id) + }) + .await } /// Heart on a channel row (all feeds of the channel): clears the favorite @@ -121,13 +124,13 @@ pub fn toggle_group_favorite(conn: &Connection, key: &str) -> Result { #[tauri::command] pub async fn channel_group_favorite(state: State<'_, AppState>, key: String) -> Result { - toggle_group_favorite(&state.db.write(), &key) + write_blocking(state.inner(), move |conn| toggle_group_favorite(conn, &key)).await } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HistoryInput { - pub kind: String, + pub kind: ItemKind, pub source_id: i64, pub item_id: String, pub series_id: Option, @@ -152,7 +155,7 @@ fn is_finished(position: f64, duration: f64) -> bool { #[tauri::command] pub async fn history_update(state: State<'_, AppState>, entry: HistoryInput) -> Result<()> { - update_history(&state.db.write(), &entry) + write_blocking(state.inner(), move |conn| update_history(conn, &entry)).await } pub fn update_history(conn: &Connection, entry: &HistoryInput) -> Result<()> { @@ -225,31 +228,34 @@ pub struct WatchedMeta { #[tauri::command] pub async fn mark_watched( state: State<'_, AppState>, - kind: String, + kind: ItemKind, source_id: i64, item_id: String, watched: bool, meta: Option, ) -> Result<()> { - set_watched( - &state.db.write(), - &kind, - source_id, - &item_id, - watched, - meta.unwrap_or_default(), - ) + write_blocking(state.inner(), move |conn| { + set_watched( + conn, + kind, + source_id, + &item_id, + watched, + meta.unwrap_or_default(), + ) + }) + .await } pub fn set_watched( conn: &Connection, - kind: &str, + kind: ItemKind, source_id: i64, item_id: &str, watched: bool, meta: WatchedMeta, ) -> Result<()> { - if !matches!(kind, "movie" | "episode") { + if !matches!(kind, ItemKind::Movie | ItemKind::Episode) { return Err(Error::msg(format!("cannot mark {kind} as watched"))); } let n = conn.execute( @@ -262,7 +268,7 @@ pub fn set_watched( } let title = match meta.title { Some(t) => t, - None if kind == "movie" => conn + None if kind == ItemKind::Movie => conn .query_row( "SELECT title FROM movie WHERE source_id = ?1 AND id = ?2", params![source_id, item_id], @@ -298,22 +304,24 @@ pub fn set_watched( #[tauri::command] pub async fn history_remove( state: State<'_, AppState>, - kind: String, + kind: ItemKind, source_id: i64, item_id: String, ) -> Result<()> { - let conn = state.db.write(); - conn.execute( - "DELETE FROM history WHERE source_id = ?1 AND kind = ?2 AND item_id = ?3", - params![source_id, kind, item_id], - )?; - Ok(()) + write_blocking(state.inner(), move |conn| { + conn.execute( + "DELETE FROM history WHERE source_id = ?1 AND kind = ?2 AND item_id = ?3", + params![source_id, kind, item_id], + )?; + Ok(()) + }) + .await } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct HistoryItem { - pub kind: String, + pub kind: ItemKind, pub source_id: i64, pub item_id: String, pub series_id: Option, @@ -334,7 +342,10 @@ pub async fn continue_watching( state: State<'_, AppState>, limit: Option, ) -> Result> { - let conn = state.db.read(); + read_blocking(state.inner(), move |conn| continue_rows(conn, limit)).await +} + +fn continue_rows(conn: &Connection, limit: Option) -> Result> { // One entry per title: the latest play of any copy (episode of any copy of // a show). A title whose latest play was finished is not "in progress". let mut stmt = conn.prepare_cached( @@ -387,7 +398,10 @@ pub async fn recent_channels( state: State<'_, AppState>, limit: Option, ) -> Result> { - let conn = state.db.read(); + read_blocking(state.inner(), move |conn| recent_rows(conn, limit)).await +} + +fn recent_rows(conn: &Connection, limit: Option) -> Result> { // one entry per channel: the feed watched last let recent: Vec<(i64, String, i64)> = conn .prepare_cached( @@ -405,7 +419,7 @@ pub async fn recent_channels( Ok(recent .into_iter() .filter_map(|(sid, id, at)| { - channel_by_id(&conn, sid, &id) + channel_by_id(conn, sid, &id) .ok() .map(|channel| RecentChannel { channel, @@ -438,7 +452,7 @@ mod tests { fn progress(position: f64, duration: f64) -> HistoryInput { HistoryInput { - kind: "episode".into(), + kind: ItemKind::Episode, source_id: 1, item_id: "e1".into(), series_id: Some("s1".into()), @@ -544,9 +558,9 @@ mod tests { fn favorites_belong_to_the_whole_work() { let c = crate::db::test_conn(); two_copies(&c); - assert!(toggle_favorite(&c, "movie", 1, "m1").unwrap()); + assert!(toggle_favorite(&c, ItemKind::Movie, 1, "m1").unwrap()); // un-favoriting through the other copy clears the work - assert!(!toggle_favorite(&c, "movie", 1, "m2").unwrap()); + assert!(!toggle_favorite(&c, ItemKind::Movie, 1, "m2").unwrap()); let n: i64 = c .query_row("SELECT COUNT(*) FROM favorite", [], |r| r.get(0)) .unwrap(); @@ -624,7 +638,7 @@ mod tests { duration: Some(2700.0), ..Default::default() }; - set_watched(&c, "episode", 1, "e3", true, meta).unwrap(); + set_watched(&c, ItemKind::Episode, 1, "e3", true, meta).unwrap(); let row: (String, i64, String, bool) = c .query_row( "SELECT series_id, episode, title, watched FROM history WHERE item_id = 'e3'", @@ -633,10 +647,18 @@ mod tests { ) .unwrap(); assert_eq!(row, ("s1".into(), 3, "Show".into(), true)); - set_watched(&c, "episode", 1, "e3", false, WatchedMeta::default()).unwrap(); + set_watched( + &c, + ItemKind::Episode, + 1, + "e3", + false, + WatchedMeta::default(), + ) + .unwrap(); assert!(!watched(&c, "e3")); // unmarking something never played is a no-op, live TV can't be marked - set_watched(&c, "movie", 1, "m9", false, WatchedMeta::default()).unwrap(); + set_watched(&c, ItemKind::Movie, 1, "m9", false, WatchedMeta::default()).unwrap(); assert_eq!( c.query_row( "SELECT COUNT(*) FROM history WHERE item_id = 'm9'", @@ -646,6 +668,6 @@ mod tests { .unwrap(), 0 ); - assert!(set_watched(&c, "live", 1, "c1", true, WatchedMeta::default()).is_err()); + assert!(set_watched(&c, ItemKind::Live, 1, "c1", true, WatchedMeta::default()).is_err()); } } diff --git a/src-tauri/src/names.rs b/src-tauri/src/names.rs index b7ec7f3..0abb0f6 100644 --- a/src-tauri/src/names.rs +++ b/src-tauri/src/names.rs @@ -175,25 +175,27 @@ fn take_superscripts(name: &str, badges: &mut Vec<&'static str>) -> String { out } -static DECOR: LazyLock = - LazyLock::new(|| Regex::new(r"[◉•●★☆✪⚽♦◆▶►▬■□▪\u{2066}-\u{2069}\u{FE0F}]").unwrap()); -static SPACES: LazyLock = LazyLock::new(|| Regex::new(r"\s{2,}").unwrap()); -static PREFIX: LazyLock = - LazyLock::new(|| Regex::new(r"^\s*([A-Z0-9][A-Z0-9&+/.]{0,11})\s*[:|]\s+").unwrap()); +static DECOR: LazyLock = LazyLock::new(|| { + Regex::new(r"[◉•●★☆✪⚽♦◆▶►▬■□▪\u{2066}-\u{2069}\u{FE0F}]").expect("valid regex") +}); +static SPACES: LazyLock = LazyLock::new(|| Regex::new(r"\s{2,}").expect("valid regex")); +static PREFIX: LazyLock = LazyLock::new(|| { + Regex::new(r"^\s*([A-Z0-9][A-Z0-9&+/.]{0,11})\s*[:|]\s+").expect("valid regex") +}); static SEPARATOR: LazyLock = - LazyLock::new(|| Regex::new(r"^\s*(?:#\s*#|(?:[=*~_\-•●▬◆★]\s*){3,})").unwrap()); + LazyLock::new(|| Regex::new(r"^\s*(?:#\s*#|(?:[=*~_\-•●▬◆★]\s*){3,})").expect("valid regex")); // "SC - ", and compound ones like "4K-AMZ - ", "4K-A+ - ", "EN-TOP - " (the // first part a quality or a two-letter code, so "X-MEN - …" stays a title) static TAG_PREFIX: LazyLock = LazyLock::new(|| { Regex::new(r"^\s*((?:(?:4K|8K|UHD|FHD|HD|SD|[A-Z]{2})-[A-Z0-9+]{1,5})|[A-Z0-9+]{2,4})\s*-\s+") - .unwrap() + .expect("valid regex") }); static TRAILING_YEAR: LazyLock = - LazyLock::new(|| Regex::new(r"\s*[\(\[]((?:19|20)\d{2})[\)\]]\s*$").unwrap()); + LazyLock::new(|| Regex::new(r"\s*[\(\[]((?:19|20)\d{2})[\)\]]\s*$").expect("valid regex")); static MIDDLE_YEAR: LazyLock = - LazyLock::new(|| Regex::new(r"^(.{2,}?)\s*\(((?:19|20)\d{2})\)\s+\S.*$").unwrap()); + LazyLock::new(|| Regex::new(r"^(.{2,}?)\s*\(((?:19|20)\d{2})\)\s+\S.*$").expect("valid regex")); static TRAILING_COUNTRY: LazyLock = - LazyLock::new(|| Regex::new(r"\s*\(([A-Z]{2})\)\s*$").unwrap()); + LazyLock::new(|| Regex::new(r"\s*\(([A-Z]{2})\)\s*$").expect("valid regex")); /// "ᴰᵒˡᵇʸ ⱽᶦˢᶦᵒⁿ" → "Dolby Vision": superscript/modifier letters to ASCII, /// everything else untouched. @@ -285,9 +287,10 @@ fn take_trailing_badges(title: &mut String, badges: &mut Vec<&'static str>) { let trimmed = title.trim_end().to_owned(); if let Some(idx) = trimmed.rfind(' ') { let last = &trimmed[idx + 1..]; - if last.contains('/') && last.split('/').all(|p| badge_for(p).is_some()) { - for p in last.split('/') { - push_badge(badges, badge_for(p).unwrap()); + let combo: Option> = last.split('/').map(badge_for).collect(); + if let Some(combo) = combo.filter(|_| last.contains('/')) { + for b in combo { + push_badge(badges, b); } *title = trimmed[..idx].to_owned(); } @@ -302,7 +305,9 @@ pub fn channel(name: &str) -> Cleaned { let mut region = None; if let Some(m) = PREFIX.captures(&s) { // keep event-style names ("US (ESPN+ 358) | ...") untouched - let rest = s[m.get(0).unwrap().end()..].trim().to_owned(); + let rest = s[m.get(0).expect("group 0 is the whole match").end()..] + .trim() + .to_owned(); if !rest.is_empty() { region = Some(m[1].to_owned()); s = rest; @@ -334,18 +339,18 @@ pub fn title(name: &str) -> CleanedTitle { let mut tag = None; if let Some(m) = TAG_PREFIX.captures(&s) { tag = Some(m[1].to_owned()); - s = s[m.get(0).unwrap().end()..].to_owned(); + s = s[m.get(0).expect("group 0 is the whole match").end()..].to_owned(); } let mut year = None; // strip trailing "(US)" / "(2021)" in any order for _ in 0..3 { if let Some(m) = TRAILING_COUNTRY.captures(&s) { - s.truncate(m.get(0).unwrap().start()); + s.truncate(m.get(0).expect("group 0 is the whole match").start()); continue; } if let Some(m) = TRAILING_YEAR.captures(&s) { year = year.or_else(|| m[1].parse().ok()); - s.truncate(m.get(0).unwrap().start()); + s.truncate(m.get(0).expect("group 0 is the whole match").start()); continue; } break; diff --git a/src-tauri/src/playback.rs b/src-tauri/src/playback.rs index 62398fc..2eb1df4 100644 --- a/src-tauri/src/playback.rs +++ b/src-tauri/src/playback.rs @@ -1,22 +1,25 @@ //! `play`: resolves (source, item) to a stream URL — credentials never leave //! the backend — and hands it to the native player. +use std::sync::Arc; + use rusqlite::{Connection, OptionalExtension, params}; use serde::Deserialize; use tauri::{Manager, Runtime, State}; use crate::error::{Error, Result}; +use crate::kind::PlayKind; use crate::player::{LoadOptions, MediaRef, Player}; +use crate::probe::Probe; use crate::sources::{self, SourceKind, m3u}; -use crate::state::{AppState, http_client}; +use crate::state::{AppState, http_client, read_blocking, write_blocking}; use crate::util::json::i64_of; use crate::{library, settings}; -#[derive(Debug, Default, Deserialize)] +#[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PlayRequest { - /// 'live' | 'movie' | 'episode' | 'catchup' - pub kind: String, + pub kind: PlayKind, pub source_id: i64, pub id: String, /// Container extension for episodes (from series_detail). @@ -44,163 +47,195 @@ pub struct Stream { pub channel: Option<(String, Option)>, } +/// The stored row of a playable item: its own URL (M3U, or an Xtream item +/// with one) and the request headers of M3U items (none for Xtream). +#[derive(Default)] +struct ItemRow { + url: Option, + user_agent: Option, + referrer: Option, +} + +fn item_row(conn: &Connection, sql: &str, req: &PlayRequest, what: &str) -> Result { + conn.query_row(sql, params![req.source_id, req.id], |r| { + Ok(ItemRow { + url: r.get("url")?, + user_agent: r.get("user_agent")?, + referrer: r.get("referrer")?, + }) + }) + .optional()? + .ok_or_else(|| Error::NotFound(format!("{what} {}", req.id))) +} + /// Resolves (source, item) to its stream. pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { - let (url, alternates, live, user_agent, referrer, channel) = { - let src = sources::load(conn, req.source_id)?; - let live_format = settings::get_str(conn, "player.liveFormat"); - let fmt = if live_format == "m3u8" { "m3u8" } else { "ts" }; - let x = match src.kind { - SourceKind::Xtream => Some(sources::xtream_for(&src, http_client(None))?), - SourceKind::M3u => None, - }; + let src = sources::load(conn, req.source_id)?; + let live_format = settings::get_str(conn, "player.liveFormat"); + let fmt = if live_format == "m3u8" { "m3u8" } else { "ts" }; + let x = match src.kind { + SourceKind::Xtream => Some(sources::xtream_for(&src, http_client(None))?), + SourceKind::M3u => None, + }; - // request headers of M3U items (user agent, referrer); none for Xtream - let mut headers: (Option, Option) = (None, None); - let mut channel = None; - let (url, live) = match req.kind.as_str() { - "live" => { - let (title, logo, direct, ua, referrer): (String, Option, Option, Option, Option) = conn - .query_row( - "SELECT title, logo, url, user_agent, referrer FROM channel WHERE source_id = ?1 AND id = ?2", - params![req.source_id, req.id], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)), - ) - .optional()? - .ok_or_else(|| Error::NotFound(format!("channel {}", req.id)))?; - headers = (ua, referrer); - channel = Some((title, logo)); - let url = match (&x, direct) { - (_, Some(u)) => u, - (Some(x), None) => x.live_url(&req.id, fmt), - (None, None) => return Err(Error::msg("channel has no stream url")), - }; - (url, true) + let mut channel = None; + let (url, row) = match req.kind { + PlayKind::Live => { + let (title, logo): (String, Option) = conn + .query_row( + "SELECT title, logo FROM channel WHERE source_id = ?1 AND id = ?2", + params![req.source_id, req.id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()? + .ok_or_else(|| Error::NotFound(format!("channel {}", req.id)))?; + channel = Some((title, logo)); + let row = item_row( + conn, + "SELECT url, user_agent, referrer FROM channel WHERE source_id = ?1 AND id = ?2", + req, + "channel", + )?; + let url = match (&x, row.url.clone()) { + (_, Some(u)) => u, + (Some(x), None) => x.live_url(&req.id, fmt), + (None, None) => return Err(Error::msg("channel has no stream url")), + }; + (url, row) + } + PlayKind::Movie => { + let ext: Option = conn + .query_row( + "SELECT ext FROM movie WHERE source_id = ?1 AND id = ?2", + params![req.source_id, req.id], + |r| r.get(0), + ) + .optional()? + .ok_or_else(|| Error::NotFound(format!("movie {}", req.id)))?; + let row = item_row( + conn, + "SELECT url, user_agent, referrer FROM movie WHERE source_id = ?1 AND id = ?2", + req, + "movie", + )?; + let url = match (&x, row.url.clone()) { + (_, Some(u)) => u, + (Some(x), None) => x.movie_url(&req.id, ext.as_deref().unwrap_or("mp4")), + (None, None) => return Err(Error::msg("movie has no stream url")), + }; + (url, row) + } + PlayKind::Episode => match &x { + Some(x) => ( + x.episode_url(&req.id, req.ext.as_deref().unwrap_or("mp4")), + ItemRow::default(), + ), + // M3U series (sources::write_m3u): the playlist's own URL + None => { + let row = item_row( + conn, + "SELECT url, user_agent, referrer FROM episode WHERE source_id = ?1 AND id = ?2", + req, + "episode", + )?; + let url = row + .url + .clone() + .ok_or_else(|| Error::msg("episode has no stream url"))?; + (url, row) } - "movie" => { - let (ext, direct, ua, referrer): (Option, Option, Option, Option) = conn - .query_row( - "SELECT ext, url, user_agent, referrer FROM movie WHERE source_id = ?1 AND id = ?2", - params![req.source_id, req.id], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + }, + PlayKind::Catchup => { + let start = req + .catchup_start + .ok_or_else(|| Error::msg("missing catch-up start"))?; + let minutes = req.catchup_minutes.unwrap_or(60).max(1); + match &x { + Some(x) => { + let offset = src + .account + .as_ref() + .and_then(|a| i64_of(&a["serverUtcOffset"])) + .unwrap_or(0); + let local = chrono::DateTime::from_timestamp( + start + offset + src.catchup_shift_minutes * 60, + 0, ) - .optional()? - .ok_or_else(|| Error::NotFound(format!("movie {}", req.id)))?; - headers = (ua, referrer); - let url = match (&x, direct) { - (_, Some(u)) => u, - (Some(x), None) => x.movie_url(&req.id, ext.as_deref().unwrap_or("mp4")), - (None, None) => return Err(Error::msg("movie has no stream url")), - }; - (url, false) - } - "episode" => match &x { - Some(x) => ( - x.episode_url(&req.id, req.ext.as_deref().unwrap_or("mp4")), - false, - ), - // M3U series (sources::write_m3u): the playlist's own URL + .ok_or_else(|| Error::msg("bad catch-up time"))? + .naive_utc(); + (x.timeshift_url(&req.id, local, minutes), ItemRow::default()) + } + // M3U: the playlist's catch-up scheme (sources::m3u::catchup_url) None => { - let (url, ua, referrer): (String, Option, Option) = conn + let (mode, template): (Option, Option) = conn .query_row( - "SELECT url, user_agent, referrer FROM episode WHERE source_id = ?1 AND id = ?2", + "SELECT catchup_mode, catchup_source FROM channel WHERE source_id = ?1 AND id = ?2", params![req.source_id, req.id], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()? - .ok_or_else(|| Error::NotFound(format!("episode {}", req.id)))?; - headers = (ua, referrer); - (url, false) - } - }, - "catchup" => { - let start = req - .catchup_start - .ok_or_else(|| Error::msg("missing catch-up start"))?; - let minutes = req.catchup_minutes.unwrap_or(60).max(1); - let url = match &x { - Some(x) => { - let offset = src - .account - .as_ref() - .and_then(|a| i64_of(&a["serverUtcOffset"])) - .unwrap_or(0); - let local = chrono::DateTime::from_timestamp( - start + offset + src.catchup_shift_minutes * 60, - 0, - ) - .ok_or_else(|| Error::msg("bad catch-up time"))? - .naive_utc(); - x.timeshift_url(&req.id, local, minutes) - } - // M3U: the playlist's catch-up scheme (sources::m3u::catchup_url) - None => { - type Row = ( - Option, - Option, - Option, - Option, - Option, - ); - let (stream, mode, template, ua, referrer): Row = conn - .query_row( - "SELECT url, catchup_mode, catchup_source, user_agent, referrer - FROM channel WHERE source_id = ?1 AND id = ?2", - params![req.source_id, req.id], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)), + .ok_or_else(|| Error::NotFound(format!("channel {}", req.id)))?; + let row = item_row( + conn, + "SELECT url, user_agent, referrer FROM channel WHERE source_id = ?1 AND id = ?2", + req, + "channel", + )?; + let url = row + .url + .clone() + .zip(mode) + .and_then(|(stream, mode)| { + m3u::catchup_url( + &mode, + template.as_deref(), + &stream, + start, + minutes * 60, + crate::db::now(), + src.catchup_shift_minutes * 60, ) - .optional()? - .ok_or_else(|| Error::NotFound(format!("channel {}", req.id)))?; - headers = (ua, referrer); - stream - .zip(mode) - .and_then(|(stream, mode)| { - let shift = src.catchup_shift_minutes * 60; - m3u::catchup_url( - &mode, - template.as_deref(), - &stream, - start, - minutes * 60, - crate::db::now(), - shift, - ) - }) - .ok_or_else(|| Error::msg("This channel does not offer catch-up"))? - } - }; - (url, false) + }) + .ok_or_else(|| Error::msg("This channel does not offer catch-up"))?; + (url, row) + } } - other => return Err(Error::msg(format!("cannot play {other}"))), - }; - let alternates = x - .as_ref() - .map(|x| x.alternates_for(&url)) - .unwrap_or_default(); - ( - url, - alternates, - live, - headers.0.or(src.user_agent), - headers.1, - channel, - ) + } }; + let alternates = x + .as_ref() + .map(|x| x.alternates_for(&url)) + .unwrap_or_default(); Ok(Stream { url, alternates, - live, - user_agent, - referrer, + live: matches!(req.kind, PlayKind::Live), + user_agent: row.user_agent.or(src.user_agent), + referrer: row.referrer, channel, }) } +/// `resolve` off the async runtime, recording a tuned live channel for +/// "recently watched" (`play` and `cast_play`). +pub async fn resolve_and_touch(st: &AppState, req: &PlayRequest) -> Result { + let req = req.clone(); + write_blocking(st, move |conn| { + let stream = resolve(conn, &req)?; + if let Some((title, logo)) = &stream.channel { + library::touch_channel(conn, req.source_id, &req.id, title, logo.as_deref())?; + } + Ok(stream) + }) + .await +} + #[tauri::command] pub async fn play( - _app: tauri::AppHandle, + app: tauri::AppHandle, state: State<'_, AppState>, player: State<'_, Player>, + probe: State<'_, Arc>, req: PlayRequest, ) -> Result<()> { let st = state.inner().clone(); @@ -210,23 +245,15 @@ pub async fn play( live, user_agent, referrer, - channel, - } = resolve(&st.db.read(), &req)?; - if let Some((title, logo)) = channel { - let w = st.db.write(); - library::touch_channel(&w, req.source_id, &req.id, &title, logo.as_deref())?; - } + .. + } = resolve_and_touch(&st, &req).await?; // one stream per account: casting and a running version check close // their stream first - if let Some(cast) = _app.try_state::().filter(|c| c.busy()) { + if let Some(cast) = app.try_state::().filter(|c| c.busy()) { log::info!("play: ending the cast session first"); cast.stop(); } - if crate::probe::running() { - tokio::task::spawn_blocking(crate::probe::cancel) - .await - .map_err(|e| Error::msg(e.to_string()))?; - } + probe.cancel_running().await?; log::info!( "play {} {}:{} (live={live}, mirrors={})", @@ -235,12 +262,7 @@ pub async fn play( req.id, alternates.len() ); - let media = match req.kind.as_str() { - "movie" => Some("movie"), - "episode" => Some("episode"), - _ => None, - } - .map(|kind| MediaRef { + let media = req.kind.file_item().map(|kind| MediaRef { kind, source_id: req.source_id, id: req.id.clone(), @@ -275,7 +297,11 @@ pub async fn player_record( if !on { return Ok(player.stop_recording().map(|p| p.display().to_string())); } - let dir = recording_dir(&app, state.inner())?; + let configured = read_blocking(state.inner(), |conn| { + Ok(settings::get_str(conn, "recording.dir")) + }) + .await?; + let dir = recording_dir(&app, &configured)?; tokio::fs::create_dir_all(&dir).await?; let file = player.start_recording(&dir).map_err(Error::msg)?; log::info!("recording to {}", file.display()); @@ -284,10 +310,8 @@ pub async fn player_record( fn recording_dir( app: &tauri::AppHandle, - st: &AppState, + configured: &str, ) -> Result { - use tauri::Manager; - let configured = settings::get_str(&st.db.read(), "recording.dir"); if !configured.trim().is_empty() { return Ok(configured.trim().into()); } @@ -297,3 +321,124 @@ fn recording_dir( .or_else(|_| app.path().home_dir().map(|h| h.join("Videos")))?; Ok(videos.join("testpattern")) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::test_conn; + + /// Source 1 (Xtream, from `test_conn`) with credentials, plus an M3U + /// source 2, each with one channel, movie and episode. + fn catalog() -> Connection { + let c = test_conn(); + c.execute_batch( + "UPDATE source SET username = 'u', password = 'p', + account_json = '{\"serverUtcOffset\": 3600}' WHERE id = 1; + INSERT INTO source (id, kind, name, url, created_at) VALUES (2, 'm3u', 'list', 'http://l.tv/a.m3u', 0); + INSERT INTO channel (source_id, id, name, title, position) VALUES (1, '7', 'DR1', 'DR1', 0); + INSERT INTO movie (source_id, id, name, title, ext, position) VALUES (1, '9', 'm', 'Film', 'mkv', 0); + INSERT INTO channel (source_id, id, name, title, position, url, user_agent, referrer, + catchup_mode, catchup_source) + VALUES (2, 'c', 'TV2', 'TV2', 0, 'http://s.tv/tv2.m3u8', 'UA/1', 'http://ref', 'shift', NULL); + INSERT INTO movie (source_id, id, name, title, position, url) VALUES (2, 'm', 'm', 'Film', 0, 'http://s.tv/m.mp4'); + INSERT INTO series (source_id, id, name, title, position) VALUES (2, 's', 's', 'Show', 0); + INSERT INTO episode (source_id, series_id, id, season, episode, title, url, position) + VALUES (2, 's', 'e', 1, 1, 'Pilot', 'http://s.tv/e.mkv', 0);", + ) + .unwrap(); + c + } + + fn req(source_id: i64, kind: PlayKind, id: &str) -> PlayRequest { + PlayRequest { + kind, + source_id, + id: id.into(), + ..Default::default() + } + } + + #[test] + fn xtream_items_build_panel_urls() { + let c = catalog(); + let live = resolve(&c, &req(1, PlayKind::Live, "7")).unwrap(); + assert_eq!(live.url, "http://h.tv/live/u/p/7.ts"); + assert!(live.live); + assert_eq!(live.channel, Some(("DR1".into(), None))); + let movie = resolve(&c, &req(1, PlayKind::Movie, "9")).unwrap(); + assert_eq!(movie.url, "http://h.tv/movie/u/p/9.mkv"); + assert!(!movie.live && movie.channel.is_none()); + let ep = resolve( + &c, + &PlayRequest { + ext: Some("mp4".into()), + ..req(1, PlayKind::Episode, "e5") + }, + ) + .unwrap(); + assert_eq!(ep.url, "http://h.tv/series/u/p/e5.mp4"); + } + + #[test] + fn xtream_catch_up_is_in_server_time() { + let c = catalog(); + // 2024-01-01 20:00 UTC, the server one hour ahead + let r = PlayRequest { + catchup_start: Some(1_704_139_200), + catchup_minutes: Some(90), + ..req(1, PlayKind::Catchup, "7") + }; + let s = resolve(&c, &r).unwrap(); + assert_eq!(s.url, "http://h.tv/timeshift/u/p/90/2024-01-01:21-00/7.ts"); + assert!(!s.live, "catch-up is seekable, not live"); + assert!( + resolve(&c, &req(1, PlayKind::Catchup, "7")).is_err(), + "needs a start" + ); + } + + #[test] + fn m3u_items_play_their_own_urls_with_headers() { + let c = catalog(); + let live = resolve(&c, &req(2, PlayKind::Live, "c")).unwrap(); + assert_eq!(live.url, "http://s.tv/tv2.m3u8"); + assert_eq!(live.user_agent.as_deref(), Some("UA/1")); + assert_eq!(live.referrer.as_deref(), Some("http://ref")); + assert!(live.alternates.is_empty()); + assert_eq!( + resolve(&c, &req(2, PlayKind::Movie, "m")).unwrap().url, + "http://s.tv/m.mp4" + ); + assert_eq!( + resolve(&c, &req(2, PlayKind::Episode, "e")).unwrap().url, + "http://s.tv/e.mkv" + ); + let catchup = PlayRequest { + catchup_start: Some(100), + ..req(2, PlayKind::Catchup, "c") + }; + assert!( + resolve(&c, &catchup) + .unwrap() + .url + .starts_with("http://s.tv/tv2.m3u8?utc=100&lutc=") + ); + } + + #[test] + fn unknown_items_are_not_found() { + let c = catalog(); + assert!(matches!( + resolve(&c, &req(1, PlayKind::Movie, "nope")), + Err(Error::NotFound(_)) + )); + assert!(matches!( + resolve(&c, &req(2, PlayKind::Live, "nope")), + Err(Error::NotFound(_)) + )); + assert!(matches!( + resolve(&c, &req(9, PlayKind::Live, "7")), + Err(Error::NotFound(_)) + )); + } +} diff --git a/src-tauri/src/player/linux.rs b/src-tauri/src/player/linux.rs index 180ea3e..693a705 100644 --- a/src-tauri/src/player/linux.rs +++ b/src-tauri/src/player/linux.rs @@ -20,7 +20,6 @@ use std::os::fd::AsRawFd; use std::os::raw::{c_char, c_int}; use std::path::PathBuf; use std::ptr; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use gtk::prelude::*; @@ -28,7 +27,16 @@ use tauri::{Runtime, WebviewWindow}; use webkit2gtk::WebViewExt; use super::mpv::Mpv; -use super::mpv_sys::*; +use super::mpv_sys::{ + MPV_RENDER_API_TYPE_OPENGL, MPV_RENDER_PARAM_API_TYPE, MPV_RENDER_PARAM_DRM_DISPLAY_V2, + MPV_RENDER_PARAM_FLIP_Y, MPV_RENDER_PARAM_INVALID, MPV_RENDER_PARAM_OPENGL_FBO, + MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, MPV_RENDER_UPDATE_FRAME, mpv_error_string, + mpv_opengl_drm_params_v2, mpv_opengl_fbo, mpv_opengl_init_params, mpv_render_context, + mpv_render_context_create, mpv_render_context_free, mpv_render_context_render, + mpv_render_context_report_swap, mpv_render_context_set_update_callback, + mpv_render_context_update, mpv_render_param, +}; +use super::render::{GL_FRAMEBUFFER_BINDING, RedrawFlag, gl_get_integerv}; thread_local! { static SURFACE: RefCell> = const { RefCell::new(None) }; @@ -42,7 +50,7 @@ struct Surface { render_node: Option, } -static REDRAW_PENDING: AtomicBool = AtomicBool::new(false); +static REDRAW: RedrawFlag = RedrawFlag::new(); /// Installs the video surface under the window's webview. Must be called /// from the setup hook; the actual widget surgery runs on the GTK thread. @@ -161,9 +169,17 @@ fn on_realize(area: >k::GLArea) { data: ptr::null_mut(), }); let mut ctx = ptr::null_mut(); + // SAFETY: the mpv handle is alive (`surface.mpv` holds an Arc), the + // GLArea's context was made current above, and `params` is + // INVALID-terminated with every `data` pointing at a local + // (`init`, `drm`) or a static (the API name) that outlives the call; + // mpv copies what it keeps. `render_node` stays open in `surface` + // for as long as the context exists. let rc = unsafe { mpv_render_context_create(&mut ctx, surface.mpv.raw(), params.as_mut_ptr()) }; if rc < 0 { + // SAFETY: mpv_error_string returns a static, NUL-terminated + // string for any code. let msg = unsafe { CStr::from_ptr(mpv_error_string(rc)) }; log::error!("mpv_render_context_create failed: {msg:?}"); return; @@ -174,6 +190,9 @@ fn on_realize(area: >k::GLArea) { // Registering fires the callback right away, so do it with no borrow held. let ctx = SURFACE.with(|s| s.borrow().as_ref().map_or(ptr::null_mut(), |s| s.ctx)); if !ctx.is_null() { + // SAFETY: `ctx` was just created on this thread and is only freed in + // `on_unrealize`, on this thread too. The callback ignores its + // argument, so a null context pointer is fine. unsafe { mpv_render_context_set_update_callback(ctx, Some(on_mpv_update), ptr::null_mut()) }; @@ -187,6 +206,9 @@ fn on_unrealize(area: >k::GLArea) { if let Some(surface) = s.borrow_mut().as_mut() && !surface.ctx.is_null() { + // SAFETY: a live context created on this (the GTK) thread, with + // its GL context made current above; nulled right after, so it + // is freed once. unsafe { mpv_render_context_free(surface.ctx) }; surface.ctx = ptr::null_mut(); surface.render_node = None; // mpv's VA display is gone with the context @@ -207,7 +229,10 @@ fn on_render(area: >k::GLArea, _ctx: &gdk::GLContext) -> glib::Propagation { area.allocated_height() * scale, ); let mut fbo: c_int = 0; - unsafe { gl_get_integerv(GL_FRAMEBUFFER_BINDING, &mut fbo) }; + // SAFETY: GTK makes the area's GL context current before emitting + // `render`; GL_FRAMEBUFFER_BINDING writes one GLint into `fbo`, and + // `get_proc_address` takes a null context. + unsafe { gl_get_integerv(get_proc_address, GL_FRAMEBUFFER_BINDING, &mut fbo) }; let mut target = mpv_opengl_fbo { fbo, w, @@ -229,6 +254,11 @@ fn on_render(area: >k::GLArea, _ctx: &gdk::GLContext) -> glib::Propagation { data: ptr::null_mut(), }, ]; + // SAFETY: `surface.ctx` is non-null, so live (only `on_unrealize` + // frees it, on this thread, and nulls it); the GL context is current + // (GTK's `render` contract); `params` is INVALID-terminated and + // points at locals that outlive the call. This is the render thread: + // no other libmpv calls are made from it while rendering. unsafe { mpv_render_context_render(surface.ctx, params.as_mut_ptr()); mpv_render_context_report_swap(surface.ctx); @@ -239,19 +269,21 @@ fn on_render(area: >k::GLArea, _ctx: &gdk::GLContext) -> glib::Propagation { /// Called by mpv from arbitrary threads whenever a new frame is due. unsafe extern "C" fn on_mpv_update(_: *mut c_void) { - if REDRAW_PENDING.swap(true, Ordering::AcqRel) { + if !REDRAW.begin() { return; // a redraw is already queued on the GTK thread } // Always go through the main loop (never run inline), ahead of GTK's // redraw priority so the frame lands in the upcoming paint. glib::idle_add_full(glib::Priority::HIGH_IDLE, || { - REDRAW_PENDING.store(false, Ordering::Release); + REDRAW.end(); SURFACE.with(|s| { let Ok(s) = s.try_borrow() else { return }; if let Some(surface) = s.as_ref() { if surface.ctx.is_null() { return; } + // SAFETY: on the GTK (render) thread, outside mpv's update + // callback; non-null means not yet freed by `on_unrealize`. let flags = unsafe { mpv_render_context_update(surface.ctx) }; if flags & MPV_RENDER_UPDATE_FRAME != 0 { surface.area.queue_render(); @@ -267,8 +299,6 @@ unsafe extern "C" fn on_mpv_update(_: *mut c_void) { // GTK3 uses EGL on Wayland and GLX on X11; resolve GL entry points through // whichever one owns the current context. -const GL_FRAMEBUFFER_BINDING: u32 = 0x8CA6; - struct GlLoader { egl_get_proc: Option *mut c_void>, egl_current_ctx: Option *mut c_void>, @@ -279,6 +309,11 @@ struct GlLoader { fn loader() -> &'static GlLoader { static LOADER: OnceLock = OnceLock::new(); + // SAFETY: libEGL/libGL are system libraries whose initializers have no + // preconditions; each symbol is typed with its C prototype from the EGL + // and GLX headers, and the libraries are kept loaded in `_libs` for the + // process lifetime (the loader is a static), so the copied function + // pointers never dangle. LOADER.get_or_init(|| unsafe { let mut libs = Vec::new(); let mut l = GlLoader { @@ -318,6 +353,8 @@ fn loader() -> &'static GlLoader { fn using_egl() -> bool { let l = loader(); match l.egl_current_ctx { + // SAFETY: eglGetCurrentContext takes no arguments and only reads + // thread-local EGL state. Some(f) => !unsafe { f() }.is_null(), None => false, } @@ -327,8 +364,15 @@ fn gl_flavor() -> &'static str { if using_egl() { "EGL" } else { "GLX" } } +/// mpv's GL loader callback (also used by `gl_get_integerv`). +/// +/// # Safety +/// +/// `name` must be a valid NUL-terminated string. unsafe extern "C" fn get_proc_address(_ctx: *mut c_void, name: *const c_char) -> *mut c_void { let l = loader(); + // SAFETY: `name` is a C string (caller contract, mpv passes GL function + // names); eglGetProcAddress/glXGetProcAddressARB only look it up. unsafe { if using_egl() && let Some(f) = l.egl_get_proc @@ -382,6 +426,12 @@ fn egl_render_node() -> Option { type QueryDeviceString = unsafe extern "C" fn(*mut c_void, i32) -> *const c_char; let l = loader(); let (current_display, get_proc) = (l.egl_current_display?, l.egl_get_proc?); + // SAFETY: called with the GLArea's EGL context current (from + // `on_realize`). The two extension functions are looked up by name and + // checked for null before being transmuted to their prototypes from + // EGL_EXT_device_query / EGL_EXT_device_drm_render_node; `device` is + // checked before use; the returned string is owned by EGL, NUL-terminated + // and copied before returning. unsafe { let display = current_display(); let query_attrib = get_proc(c"eglQueryDisplayAttribEXT".as_ptr()); @@ -402,15 +452,3 @@ fn egl_render_node() -> Option { Some(PathBuf::from(CStr::from_ptr(node).to_str().ok()?)) } } - -unsafe fn gl_get_integerv(pname: u32, out: *mut c_int) { - type GetIntegerv = unsafe extern "C" fn(u32, *mut c_int); - static FN: OnceLock = OnceLock::new(); - let addr = *FN.get_or_init(|| unsafe { - get_proc_address(ptr::null_mut(), c"glGetIntegerv".as_ptr()) as usize - }); - if addr != 0 { - let f: GetIntegerv = unsafe { std::mem::transmute(addr) }; - unsafe { f(pname, out) }; - } -} diff --git a/src-tauri/src/player/macos.rs b/src-tauri/src/player/macos.rs index 7ff8cf1..c2b198f 100644 --- a/src-tauri/src/player/macos.rs +++ b/src-tauri/src/player/macos.rs @@ -28,7 +28,6 @@ use std::cell::RefCell; use std::ffi::{CStr, c_void}; use std::os::raw::{c_char, c_int}; use std::ptr; -use std::sync::atomic::{AtomicBool, Ordering}; // The Swift companion's static library is mostly ObjC metadata that nothing // else references; force it in so dyld registers the class. @@ -48,7 +47,15 @@ use objc2_foundation::NSString; use tauri::{Runtime, WebviewWindow, WindowEvent}; use super::mpv::Mpv; -use super::mpv_sys::*; +use super::mpv_sys::{ + MPV_RENDER_API_TYPE_OPENGL, MPV_RENDER_PARAM_ADVANCED_CONTROL, MPV_RENDER_PARAM_API_TYPE, + MPV_RENDER_PARAM_FLIP_Y, MPV_RENDER_PARAM_INVALID, MPV_RENDER_PARAM_OPENGL_FBO, + MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, MPV_RENDER_UPDATE_FRAME, mpv_error_string, mpv_opengl_fbo, + mpv_opengl_init_params, mpv_render_context, mpv_render_context_create, mpv_render_context_free, + mpv_render_context_render, mpv_render_context_report_swap, + mpv_render_context_set_update_callback, mpv_render_context_update, mpv_render_param, +}; +use super::render::{GL_FRAMEBUFFER_BINDING, RedrawFlag, gl_get_integerv}; thread_local! { static SURFACE: RefCell> = const { RefCell::new(None) }; @@ -60,7 +67,7 @@ struct Surface { ctx: *mut mpv_render_context, } -static REDRAW_PENDING: AtomicBool = AtomicBool::new(false); +static REDRAW: RedrawFlag = RedrawFlag::new(); /// Installs the video surface under the window's webview. Must be called /// from the setup hook; `with_webview` runs on the main thread. @@ -86,7 +93,9 @@ pub fn attach(window: &WebviewWindow, mpv: Arc) -> tauri::Re } }); window.with_webview(move |platform| { - // wry's `inner()` is a `*mut WKWebView`. + // SAFETY: wry's `inner()` is its live, retained `*mut WKWebView`; + // `with_webview` runs this closure on the main thread while wry keeps + // the view alive, and the reference does not escape the closure. let webview: &objc2_web_kit::WKWebView = unsafe { &*(platform.inner() as *const _) }; if let Err(e) = install(webview, mpv) { log::error!("video surface: {e}"); @@ -95,12 +104,18 @@ pub fn attach(window: &WebviewWindow, mpv: Arc) -> tauri::Re } fn install(webview: &objc2_web_kit::WKWebView, mpv: Arc) -> Result<(), String> { + // SAFETY: AppKit view-hierarchy call on the main thread (`with_webview`). let parent = unsafe { webview.superview() }.ok_or("WKWebView has no superview")?; // CGL/OpenGL view sized to the window, inserted *below* the webview. // Pixel format made on the Swift side — the objc2 binding of // initWithAttributes: goes through a calling convention that delivers nil. let frame = webview.frame(); + // SAFETY: main thread. `tp_mpvPixelFormat` is a class method of the + // Swift class returning an autoreleased NSOpenGLPixelFormat (checked for + // nil); `alloc` + `initWithFrame:pixelFormat:` is NSOpenGLView's + // designated initializer with matching argument types; `Retained::retain` + // takes its own +1 reference on the (checked) result. let gl_view = unsafe { let cls = swift_view_class()?; let pf: *mut NSOpenGLPixelFormat = msg_send![cls, tp_mpvPixelFormat]; @@ -118,6 +133,8 @@ fn install(webview: &objc2_web_kit::WKWebView, mpv: Arc) -> Result<(), Stri objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable, ); + // SAFETY: NSView's `setWantsBestResolutionOpenGLSurface:` takes a BOOL + // and returns void; main thread, live view. unsafe { let _: () = msg_send![&*gl_view, setWantsBestResolutionOpenGLSurface: true]; } @@ -125,6 +142,9 @@ fn install(webview: &objc2_web_kit::WKWebView, mpv: Arc) -> Result<(), Stri // Let the GL view show through wherever the UI doesn't paint: the webview // stops drawing its background, the window below it goes clear. + // SAFETY: KVC `setValue:forKey:` with an NSNumber and NSString that live + // across the call; WKWebView has a `drawsBackground` key (otherwise KVC + // raises, it does not corrupt memory); main thread. unsafe { let key = NSString::from_str("drawsBackground"); let value = bool_number(false); @@ -172,10 +192,15 @@ fn init_mpv() { }; // GL calls mpv makes while probing the context need a current CGL // context on this thread. + // SAFETY: NSOpenGLView's `openGLContext` returns an object pointer + // (possibly nil, checked) owned by the view, which `surface` keeps + // alive; main thread. let gl_ctx: *mut AnyObject = unsafe { msg_send![&*surface.gl_view, openGLContext] }; if gl_ctx.is_null() { return ptr::null_mut(); } + // SAFETY: `gl_ctx` is a non-nil NSOpenGLContext (above); + // `makeCurrentContext` takes no arguments and returns void. let _: () = unsafe { msg_send![gl_ctx, makeCurrentContext] }; let mut init = mpv_opengl_init_params { @@ -202,9 +227,15 @@ fn init_mpv() { }, ]; let mut ctx = ptr::null_mut(); + // SAFETY: the mpv handle is alive (`surface.mpv` holds an Arc), the + // view's CGL context is current (above), and `params` is + // INVALID-terminated with every `data` pointing at a local or a + // static that outlives the call; mpv copies what it keeps. let rc = unsafe { mpv_render_context_create(&mut ctx, surface.mpv.raw(), params.as_mut_ptr()) }; if rc < 0 { + // SAFETY: mpv_error_string returns a static, NUL-terminated + // string for any code. let msg = unsafe { CStr::from_ptr(mpv_error_string(rc)) }; log::error!("mpv_render_context_create failed: {msg:?}"); return ptr::null_mut(); @@ -215,6 +246,9 @@ fn init_mpv() { if ctx.is_null() { return; } + // SAFETY: `ctx` was just created on this (the main) thread and is only + // freed in `teardown`, also on the main thread. The callback ignores its + // argument, so a null context pointer is fine. unsafe { mpv_render_context_set_update_callback(ctx, Some(on_mpv_update), ptr::null_mut()) }; // Hand Swift the frame renderer; `drawRect:` calls it with the CGL // context already locked and current. @@ -234,6 +268,9 @@ fn teardown() { let surface = SURFACE.with(|s| s.borrow_mut().take()); if let Some(mut surface) = surface { if !surface.ctx.is_null() { + // SAFETY: a live context created on this (the main) thread; + // the callback is cleared first so mpv stops calling into us, + // and the pointer is nulled right after so it is freed once. unsafe { mpv_render_context_set_update_callback(surface.ctx, None, ptr::null_mut()); mpv_render_context_free(surface.ctx); @@ -262,7 +299,10 @@ fn render(ctx: *mut mpv_render_context, gl_view: &NSOpenGLView) { let bounds = gl_view.bounds(); let backing = gl_view.convertRectToBacking(bounds); let mut fbo: c_int = 0; - unsafe { gl_get_integerv(GL_FRAMEBUFFER_BINDING, &mut fbo) }; + // SAFETY: `drawRect:` (Swift) made the view's CGL context current; + // GL_FRAMEBUFFER_BINDING writes one GLint into `fbo`, and + // `get_proc_address` ignores its context argument. + unsafe { gl_get_integerv(get_proc_address, GL_FRAMEBUFFER_BINDING, &mut fbo) }; let mut target = mpv_opengl_fbo { fbo, w: backing.size.width as c_int, @@ -284,6 +324,10 @@ fn render(ctx: *mut mpv_render_context, gl_view: &NSOpenGLView) { data: ptr::null_mut(), }, ]; + // SAFETY: `ctx` is non-null, so live (only `teardown` frees it, on this + // thread); the CGL context is current and locked (`drawRect:`); + // `params` is INVALID-terminated and points at locals that outlive the + // call. unsafe { mpv_render_context_render(ctx, params.as_mut_ptr()); // drawRect: (Swift) flushes; report the swap straight away. @@ -293,17 +337,19 @@ fn render(ctx: *mut mpv_render_context, gl_view: &NSOpenGLView) { /// Called by mpv from arbitrary threads whenever a new frame is due. unsafe extern "C" fn on_mpv_update(_: *mut c_void) { - if REDRAW_PENDING.swap(true, Ordering::AcqRel) { + if !REDRAW.begin() { return; // a redraw is already queued on the main queue } let block = RcBlock::new(|| { - REDRAW_PENDING.store(false, Ordering::Release); + REDRAW.end(); SURFACE.with(|s| { let Ok(s) = s.try_borrow() else { return }; let Some(surface) = s.as_ref() else { return }; if surface.ctx.is_null() { return; } + // SAFETY: on the main (render) thread, outside mpv's update + // callback; non-null means not yet freed by `teardown`. let flags = unsafe { mpv_render_context_update(surface.ctx) }; if flags & MPV_RENDER_UPDATE_FRAME != 0 { surface.gl_view.setNeedsDisplay(true); @@ -311,6 +357,9 @@ unsafe extern "C" fn on_mpv_update(_: *mut c_void) { }); }); // Never render on mpv's thread; hop onto AppKit's display cycle. + // SAFETY: the main queue is a valid, never-released dispatch queue; + // `into_raw` hands the block's +1 reference to libdispatch, and + // `trampoline` takes it back exactly once when the work item runs. unsafe { dispatch_async_f( main_queue(), @@ -320,7 +369,14 @@ unsafe extern "C" fn on_mpv_update(_: *mut c_void) { }; } +/// # Safety +/// +/// `ctx` must come from `RcBlock::into_raw` of an `RcBlock`, and +/// be passed here once. unsafe extern "C" fn trampoline(ctx: *mut c_void) { + // SAFETY: `on_mpv_update` passes the block it leaked with `into_raw`; + // libdispatch runs each work item once, so the reference is reclaimed + // (and released on drop) once. let block = unsafe { RcBlock::::from_raw(ctx.cast()) }; if let Some(b) = block { b.call(()); @@ -340,6 +396,8 @@ unsafe extern "C" { } fn main_queue() -> *mut c_void { + // SAFETY: only takes the address of libdispatch's static main-queue + // object (what `dispatch_get_main_queue()` expands to); nothing is read. unsafe { &_dispatch_main_q as *const c_void as *mut c_void } } @@ -348,6 +406,9 @@ fn main_queue() -> *mut c_void { /// `+[MpvOpenGLView setRenderCallback:]`; installed once at init. fn set_swift_render_callback(view: &NSOpenGLView, cb: extern "C" fn(*mut c_void)) { let cls = view.class(); + // SAFETY: `+setRenderCallback:` takes a `@convention(c)` function pointer + // (`RenderFn`), which `cb` is (`extern "C" fn(*mut c_void)`, a `'static` + // fn item); main thread. unsafe { let _: () = msg_send![cls, setRenderCallback: cb as *const c_void]; } @@ -358,36 +419,37 @@ fn set_swift_render_callback(view: &NSOpenGLView, cb: extern "C" fn(*mut c_void) // macOS's OpenGL ABI is stable (3.2 Core / 4.1); CGL has no public // GetProcAddress, so mpv's entry points come from the framework via dlsym. -const GL_FRAMEBUFFER_BINDING: u32 = 0x8CA6; - +/// mpv's GL loader callback (also used by `gl_get_integerv`). +/// +/// # Safety +/// +/// `name` must be a valid NUL-terminated string. unsafe extern "C" fn get_proc_address(_ctx: *mut c_void, name: *const c_char) -> *mut c_void { // OpenGL.framework never gets unloaded; dlopen it once and look symbols // up from the cached handle instead of a per-call dlopen + mem::forget. static LIB: OnceLock> = OnceLock::new(); let Some(lib) = LIB - .get_or_init(|| unsafe { - libloading::os::unix::Library::new("/System/Library/Frameworks/OpenGL.framework/OpenGL") + .get_or_init(|| { + // SAFETY: OpenGL.framework is a system framework with no + // initializer preconditions; it stays loaded for the process (a + // static), so looked-up symbols never dangle. + unsafe { + libloading::os::unix::Library::new( + "/System/Library/Frameworks/OpenGL.framework/OpenGL", + ) .ok() + } }) .as_ref() else { return ptr::null_mut(); }; + // SAFETY: `name` is a C string (caller contract). let name = unsafe { CStr::from_ptr(name).to_bytes() }; + // SAFETY: the symbol is read as an untyped address and handed back to + // mpv, which knows its real prototype. let Ok(sym) = (unsafe { lib.get::<*mut c_void>(name) }) else { return ptr::null_mut(); }; *sym } - -unsafe fn gl_get_integerv(pname: u32, out: *mut c_int) { - type GetIntegerv = unsafe extern "C" fn(u32, *mut c_int); - static FN: OnceLock = OnceLock::new(); - let addr = *FN.get_or_init(|| unsafe { - get_proc_address(ptr::null_mut(), c"glGetIntegerv".as_ptr()) as usize - }); - if addr != 0 { - let f: GetIntegerv = unsafe { std::mem::transmute(addr) }; - unsafe { f(pname, out) }; - } -} diff --git a/src-tauri/src/player/mod.rs b/src-tauri/src/player/mod.rs index bbbb889..030ff0f 100644 --- a/src-tauri/src/player/mod.rs +++ b/src-tauri/src/player/mod.rs @@ -8,6 +8,8 @@ mod macos; pub mod mpv; /// libmpv constants (also used by `crate::probe` for a `video-params` node watch). pub(crate) mod mpv_sys; +#[cfg(any(target_os = "linux", target_os = "macos"))] +mod render; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -18,12 +20,26 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use tauri::{AppHandle, Emitter, Manager, Runtime, State, WebviewWindow}; +use crate::error::Error; +use crate::kind::ItemKind; use mpv::{EndReason, Event, Mpv}; -use mpv_sys::*; +use mpv_sys::{ + MPV_FORMAT_DOUBLE, MPV_FORMAT_FLAG, MPV_FORMAT_INT64, MPV_FORMAT_NODE, MPV_FORMAT_STRING, + mpv_format, +}; pub const EVENT: &str = "player://event"; pub const USER_AGENT: &str = concat!("testpattern/", env!("CARGO_PKG_VERSION")); +/// `time-pos` changes every frame; ~5 Hz is plenty for the UI. +const TIME_POS_INTERVAL: Duration = Duration::from_millis(200); +/// A live stream that played this long earns a fresh reconnect budget. +const RECONNECT_BUDGET_RESET: Duration = Duration::from_secs(30); +/// Automatic re-opens of a live stream before giving up. +const MAX_RECONNECTS: u32 = 5; +/// Reconnect backoff: attempt `n` waits `n` times this. +const RECONNECT_BACKOFF_STEP: Duration = Duration::from_millis(500); + #[derive(Debug, Clone, Serialize)] #[serde( tag = "type", @@ -56,8 +72,8 @@ pub enum PlayerEvent { /// learns about its tracks can be stored for the version picker. #[derive(Debug, Clone)] pub struct MediaRef { - /// "movie" | "episode" - pub kind: &'static str, + /// Movie or Episode + pub kind: ItemKind, pub source_id: i64, pub id: String, } @@ -187,6 +203,9 @@ impl Player { fn new(app: &AppHandle) -> Result { // libmpv refuses to start unless numbers are formatted the C way; GTK // has already applied the user's locale at this point. + // SAFETY: a static C string for the locale name; this runs once in + // the setup hook, before mpv or any other thread of ours reads the + // locale (setlocale is not thread-safe against concurrent locale use). unsafe { libc::setlocale(libc::LC_NUMERIC, c"C".as_ptr()) }; let mpv = Arc::new(Mpv::new(&[ ("vo", "libmpv"), @@ -239,7 +258,8 @@ impl Player { std::thread::Builder::new() .name("mpv-events".into()) .spawn(move || { - let mut last_time_emit = Instant::now() - Duration::from_secs(1); + // None: emit the next time-pos right away + let mut last_time_emit: Option = None; loop { let Some(ev) = mpv.wait_event(-1.0) else { continue; @@ -247,12 +267,11 @@ impl Player { let out = match ev { Event::Shutdown => break, Event::PropertyChange { name, value } => { - // time-pos changes every frame; ~5 Hz is plenty for the UI. if name == "time-pos" { - if last_time_emit.elapsed() < Duration::from_millis(200) { + if last_time_emit.is_some_and(|t| t.elapsed() < TIME_POS_INTERVAL) { continue; } - last_time_emit = Instant::now(); + last_time_emit = Some(Instant::now()); } if name == "track-list" || name == "video-params" { Self::learn_tracks(&app, &session, &name, &value); @@ -268,7 +287,7 @@ impl Player { PlayerEvent::FileLoaded } Event::PlaybackRestart | Event::Seek => { - last_time_emit = Instant::now() - Duration::from_secs(1); + last_time_emit = None; if matches!(ev, Event::Seek) { continue; } @@ -383,11 +402,11 @@ impl Player { } // A stream that played fine for a while earns a fresh retry budget. if s.loaded_at - .is_some_and(|t| t.elapsed() > Duration::from_secs(30)) + .is_some_and(|t| t.elapsed() > RECONNECT_BUDGET_RESET) { s.reconnects = 0; } - if s.reconnects >= 5 { + if s.reconnects >= MAX_RECONNECTS { if s.recording.take().is_some() { let _ = mpv.set_string("stream-record", ""); } @@ -406,7 +425,7 @@ impl Player { drop(guard); let mpv = mpv.clone(); std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(500 * attempt as u64)); + std::thread::sleep(RECONNECT_BACKOFF_STEP * attempt); let _ = mpv.command_async(&["loadfile", &url, "replace", "-1", &opts]); }); Some(attempt) @@ -490,10 +509,10 @@ impl Player { /// (`/live///…`, `username=…&password=…`). pub fn redact(text: &str) -> String { static PATH: std::sync::LazyLock = std::sync::LazyLock::new(|| { - regex::Regex::new(r"/(live|movie|series|timeshift)/[^/\s]+/[^/\s]+/").unwrap() + regex::Regex::new(r"/(live|movie|series|timeshift)/[^/\s]+/[^/\s]+/").expect("valid regex") }); static QUERY: std::sync::LazyLock = std::sync::LazyLock::new(|| { - regex::Regex::new(r"(?i)\b(username|password)=[^&\s]*").unwrap() + regex::Regex::new(r"(?i)\b(username|password)=[^&\s]*").expect("valid regex") }); let t = PATH.replace_all(text, "/$1/***/***/"); QUERY.replace_all(&t, "$1=***").into_owned() @@ -609,48 +628,52 @@ fn readable(name: &str) -> bool { && !name.starts_with("playlist") } -type Res = Result; +/// mpv failures reach the UI as their message, as before. +fn mpv_error(e: mpv::MpvError) -> Error { + Error::msg(e.to_string()) +} #[tauri::command] pub fn player_load( player: State<'_, Player>, url: String, options: Option, -) -> Res<()> { +) -> crate::error::Result<()> { if !(url.starts_with("http://") || url.starts_with("https://")) { - return Err("only http(s) streams can be loaded".into()); + return Err(Error::msg("only http(s) streams can be loaded")); } player .load(&url, options.unwrap_or_default()) - .map_err(|e| e.to_string()) + .map_err(mpv_error) } #[tauri::command] -pub fn player_stop(player: State<'_, Player>) -> Res<()> { - player.stop().map_err(|e| e.to_string()) +pub fn player_stop(player: State<'_, Player>) -> crate::error::Result<()> { + player.stop().map_err(mpv_error) } #[tauri::command] -pub fn player_command(player: State<'_, Player>, args: Vec) -> Res<()> { +pub fn player_command(player: State<'_, Player>, args: Vec) -> crate::error::Result<()> { if !command_allowed(&args) { - return Err(format!( + return Err(Error::msg(format!( "mpv command not allowed: {}", args.first().map_or("", String::as_str) - )); + ))); } let args: Vec<&str> = args.iter().map(String::as_str).collect(); - player.mpv.command(&args).map_err(|e| e.to_string()) + player.mpv.command(&args).map_err(mpv_error) } #[tauri::command] -pub fn player_set(player: State<'_, Player>, name: String, value: Value) -> Res<()> { +pub fn player_set( + player: State<'_, Player>, + name: String, + value: Value, +) -> crate::error::Result<()> { if !property_allowed(&name) { - return Err(format!("mpv property not allowed: {name}")); + return Err(Error::msg(format!("mpv property not allowed: {name}"))); } - player - .mpv - .set_json(&name, &value) - .map_err(|e| e.to_string()) + player.mpv.set_json(&name, &value).map_err(mpv_error) } #[tauri::command] diff --git a/src-tauri/src/player/mpv.rs b/src-tauri/src/player/mpv.rs index 239a40b..5e635a3 100644 --- a/src-tauri/src/player/mpv.rs +++ b/src-tauri/src/player/mpv.rs @@ -8,7 +8,20 @@ use std::ptr; use serde_json::{Map, Value}; -use super::mpv_sys::*; +use super::mpv_sys::{ + MPV_END_FILE_REASON_EOF, MPV_END_FILE_REASON_ERROR, MPV_END_FILE_REASON_QUIT, + MPV_END_FILE_REASON_REDIRECT, MPV_END_FILE_REASON_STOP, MPV_EVENT_END_FILE, + MPV_EVENT_FILE_LOADED, MPV_EVENT_IDLE, MPV_EVENT_LOG_MESSAGE, MPV_EVENT_NONE, + MPV_EVENT_PLAYBACK_RESTART, MPV_EVENT_PROPERTY_CHANGE, MPV_EVENT_SEEK, MPV_EVENT_SHUTDOWN, + MPV_EVENT_START_FILE, MPV_EVENT_VIDEO_RECONFIG, MPV_FORMAT_DOUBLE, MPV_FORMAT_FLAG, + MPV_FORMAT_INT64, MPV_FORMAT_NODE, MPV_FORMAT_NODE_ARRAY, MPV_FORMAT_NODE_MAP, + MPV_FORMAT_OSD_STRING, MPV_FORMAT_STRING, mpv_client_api_version, mpv_command, + mpv_command_async, mpv_create, mpv_error_string, mpv_event_end_file, mpv_event_log_message, + mpv_event_property, mpv_format, mpv_free_node_contents, mpv_get_property, mpv_handle, + mpv_initialize, mpv_node, mpv_observe_property, mpv_request_log_messages, + mpv_set_option_string, mpv_set_property, mpv_set_property_string, mpv_terminate_destroy, + mpv_wait_event, +}; #[derive(Debug, thiserror::Error)] #[error("mpv: {context}: {message}")] @@ -22,6 +35,8 @@ fn check(code: c_int, context: impl FnOnce() -> String) -> Result<(), MpvError> if code >= 0 { return Ok(()); } + // SAFETY: mpv_error_string returns a static, NUL-terminated string for + // any code ("unknown error" for unknown ones). let message = unsafe { CStr::from_ptr(mpv_error_string(code)) } .to_string_lossy() .into_owned(); @@ -33,15 +48,22 @@ fn check(code: c_int, context: impl FnOnce() -> String) -> Result<(), MpvError> } fn cstr(s: &str) -> CString { - CString::new(s.replace('\0', "")).unwrap() + CString::new(s.replace('\0', "")).expect("NUL bytes were removed") } pub struct Mpv { handle: *mut mpv_handle, } -// SAFETY: the libmpv client API is documented as fully thread-safe. +// SAFETY: the handle is an opaque pointer owned by this struct (destroyed +// once, in `Drop`), and the libmpv client API is documented as fully +// thread-safe ("Multithreading" in client.h), so it may move between threads. unsafe impl Send for Mpv {} +// SAFETY: every `&self` method is a client API call, which libmpv allows +// concurrently on one handle. The one exception, `mpv_wait_event` (one +// caller at a time; its result is only valid until the next call), is +// confined to the single event thread of each `Mpv` (the player's +// `mpv-events` thread, the probe's loop); see `wait_event`. unsafe impl Sync for Mpv {} #[derive(Debug)] @@ -83,6 +105,8 @@ pub enum EndReason { impl Mpv { /// Creates and initializes an mpv instance with the given options. pub fn new(options: &[(&str, &str)]) -> Result { + // SAFETY: no preconditions; failure (out of memory, LC_NUMERIC not + // "C") is a null return, handled below. let handle = unsafe { mpv_create() }; if handle.is_null() { return Err(MpvError { @@ -94,12 +118,16 @@ impl Mpv { let mpv = Mpv { handle }; for (k, v) in options { let (ck, cv) = (cstr(k), cstr(v)); + // SAFETY: `handle` is valid and not yet shared; both C strings + // outlive the call (mpv copies them). let rc = unsafe { mpv_set_option_string(handle, ck.as_ptr(), cv.as_ptr()) }; if let Err(e) = check(rc, || format!("option {k}={v}")) { // Non-fatal: an unknown option should not prevent playback. log::warn!("{e}"); } } + // SAFETY: `handle` is valid and initialized only once, before it is + // shared with other threads. check(unsafe { mpv_initialize(handle) }, || "initialize".into())?; Ok(mpv) } @@ -112,10 +140,13 @@ impl Mpv { } pub fn api_version() -> (u32, u32) { + // SAFETY: no arguments, no preconditions. let v = unsafe { mpv_client_api_version() } as u32; (v >> 16, v & 0xffff) } + /// Calls `f` with a NULL-terminated `char **` of `args` that stays valid + /// for the duration of the call. fn with_args(args: &[&str], f: impl FnOnce(*mut *const c_char) -> R) -> R { let owned: Vec = args.iter().map(|a| cstr(a)).collect(); let mut ptrs: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect(); @@ -124,18 +155,24 @@ impl Mpv { } pub fn command(&self, args: &[&str]) -> Result<(), MpvError> { + // SAFETY: valid handle; `p` is a NULL-terminated argument array alive + // for the call (`with_args`). let rc = Self::with_args(args, |p| unsafe { mpv_command(self.handle, p) }); check(rc, || format!("command {args:?}")) } /// Fire-and-forget command; the result arrives as a COMMAND_REPLY event. pub fn command_async(&self, args: &[&str]) -> Result<(), MpvError> { + // SAFETY: valid handle; `p` is a NULL-terminated argument array alive + // for the call (`with_args`); mpv copies the arguments before it + // returns. let rc = Self::with_args(args, |p| unsafe { mpv_command_async(self.handle, 0, p) }); check(rc, || format!("command_async {args:?}")) } pub fn set_string(&self, name: &str, value: &str) -> Result<(), MpvError> { let (n, v) = (cstr(name), cstr(value)); + // SAFETY: valid handle; both C strings outlive the call. let rc = unsafe { mpv_set_property_string(self.handle, n.as_ptr(), v.as_ptr()) }; check(rc, || format!("set {name}={value}")) } @@ -143,6 +180,8 @@ impl Mpv { pub fn set_flag(&self, name: &str, value: bool) -> Result<(), MpvError> { let n = cstr(name); let mut v: c_int = value.into(); + // SAFETY: valid handle; `n` outlives the call and `data` points at + // a live `c_int`, the C type MPV_FORMAT_FLAG reads (mpv copies the value). let rc = unsafe { mpv_set_property( self.handle, @@ -157,6 +196,8 @@ impl Mpv { pub fn set_double(&self, name: &str, value: f64) -> Result<(), MpvError> { let n = cstr(name); let mut v = value; + // SAFETY: valid handle; `n` outlives the call and `data` points at + // a live `f64`, the C type MPV_FORMAT_DOUBLE reads (mpv copies the value). let rc = unsafe { mpv_set_property( self.handle, @@ -171,6 +212,8 @@ impl Mpv { pub fn set_int(&self, name: &str, value: i64) -> Result<(), MpvError> { let n = cstr(name); let mut v = value; + // SAFETY: valid handle; `n` outlives the call and `data` points at + // a live `i64`, the C type MPV_FORMAT_INT64 reads (mpv copies the value). let rc = unsafe { mpv_set_property( self.handle, @@ -186,8 +229,10 @@ impl Mpv { pub fn set_json(&self, name: &str, value: &Value) -> Result<(), MpvError> { match value { Value::Bool(b) => self.set_flag(name, *b), - Value::Number(n) if n.is_i64() => self.set_int(name, n.as_i64().unwrap()), - Value::Number(n) => self.set_double(name, n.as_f64().unwrap_or_default()), + Value::Number(n) => match n.as_i64() { + Some(i) => self.set_int(name, i), + None => self.set_double(name, n.as_f64().unwrap_or_default()), + }, Value::String(s) => self.set_string(name, s), Value::Null => self.set_string(name, "no"), other => self.set_string(name, &other.to_string()), @@ -197,7 +242,11 @@ impl Mpv { /// Reads any property as JSON (via MPV_FORMAT_NODE). pub fn get_json(&self, name: &str) -> Option { let n = cstr(name); + // SAFETY: mpv_node is a plain C struct (a union of scalars and raw + // pointers plus an int); all-zero is MPV_FORMAT_NONE with null data. let mut node: mpv_node = unsafe { std::mem::zeroed() }; + // SAFETY: valid handle; `n` outlives the call and `data` points at an + // mpv_node, what MPV_FORMAT_NODE writes. let rc = unsafe { mpv_get_property( self.handle, @@ -209,38 +258,59 @@ impl Mpv { if rc < 0 { return None; } + // SAFETY: on success mpv filled `node` with a well-formed tree it + // owns until it is freed below. let v = unsafe { node_to_json(&node) }; + // SAFETY: the node came from a successful mpv_get_property and is + // freed exactly once; `v` holds only owned copies. unsafe { mpv_free_node_contents(&mut node) }; Some(v) } pub fn observe(&self, name: &str, format: mpv_format) -> Result<(), MpvError> { let n = cstr(name); + // SAFETY: valid handle; `n` outlives the call (mpv copies the name). let rc = unsafe { mpv_observe_property(self.handle, 0, n.as_ptr(), format) }; check(rc, || format!("observe {name}")) } pub fn request_log_messages(&self, level: &str) { let l = cstr(level); + // SAFETY: valid handle; `l` outlives the call. unsafe { mpv_request_log_messages(self.handle, l.as_ptr()) }; } /// Blocks up to `timeout` seconds (negative = forever) for the next event. + /// + /// libmpv allows only one thread at a time to wait on a handle: call + /// this from a single event thread per `Mpv` (see the `Sync` impl). pub fn wait_event(&self, timeout: f64) -> Option { + // SAFETY: valid handle; mpv_wait_event never returns null, and the + // event (with everything it points to) stays valid until the next + // mpv_wait_event on this handle, which only this function makes, on + // the one event thread. Everything is copied out before returning. let ev = unsafe { &*mpv_wait_event(self.handle, timeout) }; Some(match ev.event_id { MPV_EVENT_NONE => return None, MPV_EVENT_SHUTDOWN => Event::Shutdown, MPV_EVENT_LOG_MESSAGE => { + // SAFETY: for MPV_EVENT_LOG_MESSAGE, `data` points to an + // mpv_event_log_message valid as long as `ev`. let m = unsafe { &*(ev.data as *const mpv_event_log_message) }; + // SAFETY: the fields are NUL-terminated strings owned by + // the event, valid as long as `ev`. + let (prefix, level, text) = + unsafe { (lossy(m.prefix), lossy(m.level), lossy(m.text)) }; Event::Log { - prefix: unsafe { lossy(m.prefix) }, - level: unsafe { lossy(m.level) }, - text: unsafe { lossy(m.text) }.trim_end().to_owned(), + prefix, + level, + text: text.trim_end().to_owned(), } } MPV_EVENT_START_FILE => Event::StartFile, MPV_EVENT_END_FILE => { + // SAFETY: for MPV_EVENT_END_FILE, `data` points to an + // mpv_event_end_file valid as long as `ev`. let e = unsafe { &*(ev.data as *const mpv_event_end_file) }; let reason = match e.reason { MPV_END_FILE_REASON_EOF => EndReason::Eof, @@ -251,6 +321,8 @@ impl Mpv { _ => EndReason::Unknown, }; let error = (reason == EndReason::Error).then(|| { + // SAFETY: mpv_error_string returns a static, + // NUL-terminated string for any code. unsafe { CStr::from_ptr(mpv_error_string(e.error)) } .to_string_lossy() .into_owned() @@ -263,8 +335,13 @@ impl Mpv { MPV_EVENT_PLAYBACK_RESTART => Event::PlaybackRestart, MPV_EVENT_SEEK => Event::Seek, MPV_EVENT_PROPERTY_CHANGE => { + // SAFETY: for MPV_EVENT_PROPERTY_CHANGE, `data` points to an + // mpv_event_property valid as long as `ev`. let p = unsafe { &*(ev.data as *const mpv_event_property) }; + // SAFETY: `name` is a NUL-terminated string owned by the event. let name = unsafe { lossy(p.name) }; + // SAFETY: mpv guarantees `data` matches `format` (or is null + // with MPV_FORMAT_NONE), valid as long as `ev`. let value = unsafe { format_to_json(p.format, p.data) }; Event::PropertyChange { name, value } } @@ -275,22 +352,40 @@ impl Mpv { impl Drop for Mpv { fn drop(&mut self) { + // SAFETY: the handle is valid and owned by this struct; `Drop` runs + // once and no `&Mpv` outlives it, so no other call can race with or + // follow the destroy. unsafe { mpv_terminate_destroy(self.handle) } } } +/// Copies a C string; null reads as empty. +/// +/// # Safety +/// +/// `p` must be null or point to a NUL-terminated string valid for the call. unsafe fn lossy(p: *const c_char) -> String { if p.is_null() { String::new() } else { + // SAFETY: non-null, so a valid C string (caller contract). unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned() } } +/// Converts an mpv value of `format` to JSON (unknown formats are null). +/// +/// # Safety +/// +/// `data` must be null or point to a live value of the C type `format` +/// denotes (`char *` for strings, `int` for flags, `int64_t`, `double`, or +/// an `mpv_node` tree), as mpv lays it out for property events. unsafe fn format_to_json(format: mpv_format, data: *mut c_void) -> Value { if data.is_null() { return Value::Null; } + // SAFETY: non-null, and each arm reads the C type its format denotes + // (caller contract); strings and nodes are valid per the same contract. unsafe { match format { MPV_FORMAT_STRING | MPV_FORMAT_OSD_STRING => { @@ -306,7 +401,18 @@ unsafe fn format_to_json(format: mpv_format, data: *mut c_void) -> Value { } } +/// Converts an mpv node tree to JSON (unknown formats are null). +/// +/// # Safety +/// +/// `node` must be a well-formed node as mpv produces it: `u` holds the +/// member `format` names, strings are NUL-terminated, lists hold `num` valid +/// values (and keys, for maps), recursively. unsafe fn node_to_json(node: &mpv_node) -> Value { + // SAFETY: each arm reads the union member `format` names; list pointers + // and counts are checked before building slices of `num` elements, which + // a well-formed node guarantees are valid (caller contract), and the + // contract holds for every child. unsafe { match node.format { MPV_FORMAT_STRING | MPV_FORMAT_OSD_STRING => Value::String(lossy(node.u.string)), diff --git a/src-tauri/src/player/render.rs b/src-tauri/src/player/render.rs new file mode 100644 index 0000000..c43a2c4 --- /dev/null +++ b/src-tauri/src/player/render.rs @@ -0,0 +1,61 @@ +//! Pieces the Linux and macOS video surfaces share: redraw coalescing for +//! mpv's update callback and the one GL call the platform code makes itself. + +use std::os::raw::c_int; +use std::ptr; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::mpv_sys::GetProcAddressFn; + +pub const GL_FRAMEBUFFER_BINDING: u32 = 0x8CA6; + +/// Coalesces mpv's update callbacks: mpv may call back many times before the +/// UI thread gets to the redraw, which only needs to run once. +pub struct RedrawFlag(AtomicBool); + +impl RedrawFlag { + pub const fn new() -> Self { + RedrawFlag(AtomicBool::new(false)) + } + + /// From mpv's update callback: true if the caller should queue a redraw, + /// false if one is already queued. + pub fn begin(&self) -> bool { + !self.0.swap(true, Ordering::AcqRel) + } + + /// From the queued redraw, before it asks mpv for the frame, so a + /// callback arriving meanwhile queues the next one. + pub fn end(&self) { + self.0.store(false, Ordering::Release); + } +} + +/// `glGetIntegerv`, resolved once through the platform's `get_proc_address` +/// (the address is cached process-wide, so every call must pass the same +/// loader). Does nothing if the loader cannot find it. +/// +/// # Safety +/// +/// A GL context must be current on the calling thread, `out` must be valid +/// for writing as many `GLint`s as `pname` returns (one for the scalar +/// queries used here), and `get_proc_address` must accept a null context +/// and resolve GL entry points by NUL-terminated name. +pub unsafe fn gl_get_integerv(get_proc_address: GetProcAddressFn, pname: u32, out: *mut c_int) { + type GetIntegerv = unsafe extern "C" fn(u32, *mut c_int); + static FN: OnceLock = OnceLock::new(); + let addr = *FN.get_or_init(|| { + // SAFETY: the caller guarantees `get_proc_address` takes a null + // context; the name is a static C string. + unsafe { get_proc_address(ptr::null_mut(), c"glGetIntegerv".as_ptr()) as usize } + }); + if addr != 0 { + // SAFETY: a non-null address the GL loader returned for + // `glGetIntegerv`, whose C prototype is `void (GLenum, GLint *)`. + let f: GetIntegerv = unsafe { std::mem::transmute(addr) }; + // SAFETY: the caller guarantees a current context and a writable + // `out` of the size `pname` needs. + unsafe { f(pname, out) }; + } +} diff --git a/src-tauri/src/probe.rs b/src-tauri/src/probe.rs index f3b0217..d9280bc 100644 --- a/src-tauri/src/probe.rs +++ b/src-tauri/src/probe.rs @@ -16,48 +16,72 @@ use tauri::{Manager, Runtime, State}; use crate::catalog; use crate::error::{Error, Result}; +use crate::kind::{ItemKind, PlayKind, WorkKind}; use crate::playback::{PlayRequest, Stream, resolve}; use crate::player::mpv::{EndReason, Event, Mpv}; use crate::player::{LoadOptions, Player, USER_AGENT, file_options}; -use crate::state::AppState; +use crate::state::{AppState, read_blocking, run_blocking, write_blocking}; use crate::works::versions; -/// Held for the whole life of a check's mpv instance. -static RUNNING: Mutex<()> = Mutex::new(()); -/// The instance of the running check, so `cancel` can stop it. -static CURRENT: Mutex>> = Mutex::new(None); -static BUSY: AtomicBool = AtomicBool::new(false); - const TIMEOUT: Duration = Duration::from_secs(20); -pub fn running() -> bool { - BUSY.load(Ordering::SeqCst) +/// The version checker, managed Tauri state (one check at a time). +#[derive(Default)] +pub struct Probe { + /// Held for the whole life of a check's mpv instance. + running: Mutex<()>, + /// The instance of the running check, so `cancel` can stop it. + current: Mutex>>, + busy: AtomicBool, } -/// Stops a running check and waits until its stream is closed. -pub fn cancel() { - if let Some(mpv) = CURRENT.lock().clone() { - let _ = mpv.command(&["stop"]); +impl Probe { + pub fn running(&self) -> bool { + self.busy.load(Ordering::SeqCst) + } + + /// Stops a running check and waits until its stream is closed. + pub fn cancel(&self) { + if let Some(mpv) = self.current.lock().clone() { + let _ = mpv.command(&["stop"]); + } + drop(self.running.lock()); } - drop(RUNNING.lock()); -} -/// Opens `stream`, decodes one video frame and returns its track summary -/// (`versions::summarize_tracks`, with HDR taken from the first frame's -/// `video-params.gamma`), or `None` when it didn't open in time. -fn read_tracks(stream: &Stream) -> std::result::Result, String> { - let _running = RUNNING - .try_lock_for(TIMEOUT) - .ok_or("another check is still running")?; - BUSY.store(true, Ordering::SeqCst); - struct Done; - impl Drop for Done { - fn drop(&mut self) { - *CURRENT.lock() = None; - BUSY.store(false, Ordering::SeqCst); + /// `cancel` off the async runtime, when a check is running at all. + pub async fn cancel_running(self: &Arc) -> Result<()> { + if self.running() { + let probe = self.clone(); + run_blocking(move || probe.cancel()).await?; } + Ok(()) } - let _done = Done; + + /// Opens `stream`, decodes one video frame and returns its track summary + /// (`versions::summarize_tracks`, with HDR taken from the first frame's + /// `video-params.gamma`), or `None` when it didn't open in time. + fn read_tracks(&self, stream: &Stream) -> std::result::Result, String> { + let _running = self + .running + .try_lock_for(TIMEOUT) + .ok_or("another check is still running")?; + self.busy.store(true, Ordering::SeqCst); + struct Done<'a>(&'a Probe); + impl Drop for Done<'_> { + fn drop(&mut self) { + *self.0.current.lock() = None; + self.0.busy.store(false, Ordering::SeqCst); + } + } + let _done = Done(self); + read_with(stream, &self.current) + } +} + +fn read_with( + stream: &Stream, + current: &Mutex>>, +) -> std::result::Result, String> { let mpv = Arc::new( Mpv::new(&[ ("vo", "null"), @@ -81,7 +105,7 @@ fn read_tracks(stream: &Stream) -> std::result::Result, String> { mpv.request_log_messages("error"); mpv.observe("video-params", crate::player::mpv_sys::MPV_FORMAT_NODE) .map_err(|e| e.to_string())?; - *CURRENT.lock() = Some(mpv.clone()); + *current.lock() = Some(mpv.clone()); let opts = file_options(&LoadOptions { paused: true, user_agent: stream.user_agent.clone(), @@ -159,24 +183,28 @@ fn read_tracks(stream: &Stream) -> std::result::Result, String> { // audio-only or a failed video decode: track list without gamma (hdr=false) let found = track_list.and_then(|t| versions::summarize_tracks(&t, hdr)); let _ = mpv.command(&["stop"]); - *CURRENT.lock() = None; - // the last reference: closes the connection before RUNNING is released + *current.lock() = None; + // the last reference: closes the connection before `running` is released drop(mpv); Ok(found) } -/// Checks the tracks of one version of a movie (`kind` "movie") or series -/// ("series": its first episode) and remembers them for the version list. +/// Checks the tracks of one version of a movie, or of a series (its first +/// episode), and remembers them for the version list. #[tauri::command] pub async fn version_probe( app: tauri::AppHandle, state: State<'_, AppState>, player: State<'_, Player>, - kind: String, + probe: State<'_, Arc>, + kind: WorkKind, source_id: i64, id: String, ) -> Result> { - let casting = || app.try_state::().is_some_and(|c| c.busy()); + let casting = || { + app.try_state::() + .is_some_and(|c| c.busy()) + }; if player.busy() || casting() { return Err(Error::msg( "Stop playback first: the account allows one stream at a time", @@ -185,38 +213,38 @@ pub async fn version_probe( let st = state.inner().clone(); // what to open: the movie, or a show's first two episodes (a single // episode is sometimes missing on the server) - let (reqs, item_kind) = { - let conn = st.db.read(); - match kind.as_str() { - "movie" => ( - vec![PlayRequest { - kind: "movie".into(), + let (reqs, item_kind) = match kind { + WorkKind::Movie => ( + vec![PlayRequest { + kind: PlayKind::Movie, + source_id, + id: id.clone(), + ..Default::default() + }], + ItemKind::Movie, + ), + WorkKind::Series => { + let id = id.clone(); + let seasons = read_blocking(&st, move |conn| { + catalog::stored_episodes(conn, source_id, &id, "") + }) + .await?; + let regular = seasons.iter().filter(|(n, _)| *n > 0).flat_map(|(_, e)| e); + let reqs: Vec = regular + .chain(seasons.iter().filter(|(n, _)| *n <= 0).flat_map(|(_, e)| e)) + .take(2) + .map(|e| PlayRequest { + kind: PlayKind::Episode, source_id, - id: id.clone(), + id: e.id.clone(), + ext: e.ext.clone(), ..Default::default() - }], - "movie", - ), - "series" => { - let seasons = catalog::stored_episodes(&conn, source_id, &id, "")?; - let regular = seasons.iter().filter(|(n, _)| *n > 0).flat_map(|(_, e)| e); - let reqs: Vec = regular - .chain(seasons.iter().filter(|(n, _)| *n <= 0).flat_map(|(_, e)| e)) - .take(2) - .map(|e| PlayRequest { - kind: "episode".into(), - source_id, - id: e.id.clone(), - ext: e.ext.clone(), - ..Default::default() - }) - .collect(); - if reqs.is_empty() { - return Err(Error::msg("This version has no episodes yet")); - } - (reqs, "episode") + }) + .collect(); + if reqs.is_empty() { + return Err(Error::msg("This version has no episodes yet")); } - other => return Err(Error::msg(format!("cannot check {other}"))), + (reqs, ItemKind::Episode) } }; let mut last = None; @@ -224,10 +252,13 @@ pub async fn version_probe( if player.busy() || casting() { return Ok(None); } - let stream = resolve(&st.db.read(), &req)?; - let found = tokio::task::spawn_blocking(move || read_tracks(&stream)) - .await - .map_err(|e| Error::msg(e.to_string()))? + let stream = { + let req = req.clone(); + read_blocking(&st, move |conn| resolve(conn, &req)).await? + }; + let probe = probe.inner().clone(); + let found = run_blocking(move || probe.read_tracks(&stream)) + .await? .map_err(Error::msg)?; log::info!( "checked tracks of {kind} {source_id}:{id} ({}): {}", @@ -235,13 +266,11 @@ pub async fn version_probe( if found.is_some() { "ok" } else { "no answer" } ); if let Some(t) = found { - versions::save_tracks( - &st.db.write(), - source_id, - item_kind, - &req.id, - &t.to_string(), - )?; + let (item, json) = (req.id.clone(), t.to_string()); + write_blocking(&st, move |conn| { + versions::save_tracks(conn, source_id, item_kind, &item, &json) + }) + .await?; return Ok(Some(t)); } last = Some(req.id); @@ -249,13 +278,10 @@ pub async fn version_probe( // the server couldn't open it: remembered (the version list says so and // the automatic choice avoids it) until a check or playback succeeds if let Some(item) = last { - versions::save_tracks( - &st.db.write(), - source_id, - item_kind, - &item, - r#"{"unavailable":true}"#, - )?; + write_blocking(&st, move |conn| { + versions::save_tracks(conn, source_id, item_kind, &item, r#"{"unavailable":true}"#) + }) + .await?; } Ok(None) } diff --git a/src-tauri/src/secrets.rs b/src-tauri/src/secrets.rs index 130bb7f..5087c2e 100644 --- a/src-tauri/src/secrets.rs +++ b/src-tauri/src/secrets.rs @@ -20,7 +20,7 @@ use parking_lot::Mutex; use rusqlite::{Connection, OptionalExtension}; use crate::error::{Error, Result}; -use crate::state::AppState; +use crate::state::{AppState, read_blocking, write_blocking}; /// Shown when a source's password is in the keyring but couldn't be read. pub const UNAVAILABLE: &str = "The password is stored in the system keyring, which is locked or not available. \ @@ -434,17 +434,18 @@ pub async fn move_to_keyring( password: &str, unlock: Unlock, ) -> bool { - let (profile, name) = { - let conn = st.db.write(); - let Ok(profile) = profile_id(&conn) else { - return false; - }; + let found = write_blocking(st, move |conn| { + let profile = profile_id(conn)?; let name: String = conn .query_row("SELECT name FROM source WHERE id = ?1", [source_id], |r| { r.get(0) }) .unwrap_or_else(|_| format!("source {source_id}")); - (profile, name) + Ok((profile, name)) + }) + .await; + let Ok((profile, name)) = found else { + return false; }; let label = format!("testpattern: {name}"); match timed( @@ -455,7 +456,7 @@ pub async fn move_to_keyring( { Ok(true) => { remember(source_id, password); - match clear_plaintext(&st.db.write(), source_id) { + match write_blocking(st, move |conn| clear_plaintext(conn, source_id)).await { Ok(()) => true, Err(e) => { log::warn!( @@ -513,7 +514,7 @@ fn scrub(conn: &Connection) { /// keyring can't delete anything. pub async fn forget(st: &AppState, source_id: i64) { uncache(source_id); - let Ok(profile) = profile_id(&st.db.write()) else { + let Ok(profile) = write_blocking(st, |conn| profile_id(conn)).await else { return; }; if let Err(e) = timed( @@ -575,7 +576,7 @@ fn label_of(name: &str) -> &'static str { /// — without one — in the database setting `name`. Returns whether it went /// into the keyring. pub async fn store_named(st: &AppState, name: &str, secret: &str, unlock: Unlock) -> Result { - let profile = profile_id(&st.db.write())?; + let profile = write_blocking(st, |conn| profile_id(conn)).await?; let label = format!("testpattern: {}", label_of(name)); match timed( unlock, @@ -587,7 +588,8 @@ pub async fn store_named(st: &AppState, name: &str, secret: &str, unlock: Unlock NAMED_CACHE .lock() .insert(name.to_owned(), secret.to_owned()); - clear_plaintext_setting(&st.db.write(), name)?; + let key = name.to_owned(); + write_blocking(st, move |conn| clear_plaintext_setting(conn, &key)).await?; Ok(true) } stored => { @@ -595,12 +597,16 @@ pub async fn store_named(st: &AppState, name: &str, secret: &str, unlock: Unlock Ok(_) => log::info!("{name}: keyring locked, stored in the database for now"), Err(e) => log::info!("{name}: stored in the database ({e})"), } - let conn = st.db.write(); - conn.execute("DELETE FROM setting WHERE key = ?1", [flag(name)])?; - conn.execute( - "INSERT INTO setting (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", - rusqlite::params![name, serde_json::to_string(secret)?], - )?; + let (key, value) = (name.to_owned(), serde_json::to_string(secret)?); + write_blocking(st, move |conn| { + conn.execute("DELETE FROM setting WHERE key = ?1", [flag(&key)])?; + conn.execute( + "INSERT INTO setting (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + rusqlite::params![key, value], + )?; + Ok(()) + }) + .await?; NAMED_CACHE.lock().remove(name); Ok(false) } @@ -609,16 +615,18 @@ pub async fn store_named(st: &AppState, name: &str, secret: &str, unlock: Unlock /// Removes a `NAMED` secret everywhere; the keyring entry goes in the /// background (a locked keyring asks first). -pub fn forget_named(st: &AppState, name: &str) -> Result<()> { - { - let conn = st.db.write(); - clear_plaintext_setting(&conn, name)?; - conn.execute("DELETE FROM setting WHERE key = ?1", [flag(name)])?; - } +pub async fn forget_named(st: &AppState, name: &str) -> Result<()> { + let key = name.to_owned(); + write_blocking(st, move |conn| { + clear_plaintext_setting(conn, &key)?; + conn.execute("DELETE FROM setting WHERE key = ?1", [flag(&key)])?; + Ok(()) + }) + .await?; NAMED_CACHE.lock().remove(name); let (st, name) = (st.clone(), name.to_owned()); tauri::async_runtime::spawn(async move { - let Ok(profile) = profile_id(&st.db.write()) else { + let Ok(profile) = write_blocking(&st, |conn| profile_id(conn)).await else { return; }; if let Err(e) = timed( @@ -655,8 +663,7 @@ fn clear_plaintext_setting(conn: &Connection, name: &str) -> Result<()> { /// again later when the keyring was locked then) — all, or `only` one source. /// Without `only`, the `NAMED` secrets that live in the keyring too. pub async fn ensure_loaded(st: &AppState, only: Option, unlock: Unlock) { - let (profile, missing) = { - let conn = st.db.write(); + let found = write_blocking(st, move |conn| { let ids: Vec = conn .prepare( "SELECT id FROM source WHERE password_in_keyring = 1 AND (?1 IS NULL OR id = ?1)", @@ -673,19 +680,20 @@ pub async fn ensure_loaded(st: &AppState, only: Option, unlock: Unlock) { NAMED .iter() .filter(|(name, _)| { - setting(&conn, &flag(name)).is_some() + setting(conn, &flag(name)).is_some() && !NAMED_CACHE.lock().contains_key(*name) }) .map(|(name, _)| Entry::Named(name)), ); } if missing.is_empty() { - return; + return Ok(None); } - let Ok(profile) = profile_id(&conn) else { - return; - }; - (profile, missing) + Ok(Some((profile_id(conn)?, missing))) + }) + .await; + let Ok(Some((profile, missing))) = found else { + return; }; let mut unlock = unlock; for entry in missing { @@ -712,12 +720,14 @@ pub async fn ensure_loaded(st: &AppState, only: Option, unlock: Unlock) { /// while the keyring is unlocked (never prompts). pub async fn startup(st: &AppState) { ensure_loaded(st, None, Unlock::Prompt).await; - let plaintext: Vec<(i64, String)> = { - let conn = st.db.read(); - conn.prepare("SELECT id, password FROM source WHERE password_in_keyring = 0 AND COALESCE(password, '') <> ''") + let plaintext: Vec<(i64, String)> = read_blocking(st, |conn| { + Ok(conn + .prepare("SELECT id, password FROM source WHERE password_in_keyring = 0 AND COALESCE(password, '') <> ''") .and_then(|mut s| s.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?.collect()) - .unwrap_or_default() - }; + .unwrap_or_default()) + }) + .await + .unwrap_or_default(); let mut moved = 0; let mut blocked = false; for (id, password) in plaintext { @@ -729,8 +739,12 @@ pub async fn startup(st: &AppState) { moved += 1; } for (name, _) in NAMED { - let plain = - setting(&st.db.read(), name).filter(|_| setting(&st.db.read(), &flag(name)).is_none()); + let plain = read_blocking(st, move |conn| { + Ok(setting(conn, name).filter(|_| setting(conn, &flag(name)).is_none())) + }) + .await + .ok() + .flatten(); if blocked || plain.is_none() { continue; } @@ -750,8 +764,14 @@ pub async fn startup(st: &AppState) { } } if moved > 0 { - let st = st.clone(); - let _ = tokio::task::spawn_blocking(move || scrub(&st.db.write())).await; + let scrubbed = write_blocking(st, |conn| { + scrub(conn); + Ok(()) + }) + .await; + if let Err(e) = scrubbed { + log::warn!("could not rebuild the database: {e}"); + } } } diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index 4f229a0..08c1183 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -5,7 +5,7 @@ use serde_json::{Map, Value, json}; use tauri::{AppHandle, Manager, Runtime, State}; use crate::error::Result; -use crate::state::AppState; +use crate::state::{AppState, read_blocking, write_blocking}; pub fn defaults() -> Map { let v = json!({ @@ -83,11 +83,10 @@ pub fn sub_visibility(conn: &Connection) -> &'static str { /// Pushes player settings into mpv: all of them (startup) or just `only` — /// re-applying e.g. `hwdec` mid-playback would needlessly touch the decoder. -pub fn apply_player(app: &AppHandle, st: &AppState, only: Option<&str>) { +pub fn apply_player(app: &AppHandle, conn: &Connection, only: Option<&str>) { let Some(player) = app.try_state::() else { return; }; - let conn = st.db.read(); let wanted = |key: &str| only.is_none_or(|o| o == key); let set = |name: &str, v: String| { if let Err(e) = player.mpv().set_string(name, &v) { @@ -95,20 +94,20 @@ pub fn apply_player(app: &AppHandle, st: &AppState, only: Option< } }; if wanted("player.hwdec") { - set("hwdec", get_str(&conn, "player.hwdec")); + set("hwdec", get_str(conn, "player.hwdec")); } if wanted("player.audioLang") { - set("alang", get_str(&conn, "player.audioLang")); + set("alang", get_str(conn, "player.audioLang")); } if wanted("player.subLang") { - set("slang", get_str(&conn, "player.subLang")); + set("slang", get_str(conn, "player.subLang")); } if wanted("player.subsEnabled") { - set("sub-visibility", sub_visibility(&conn).into()); + set("sub-visibility", sub_visibility(conn).into()); } // the UI remembers the volume it last set (stores/player.ts) if wanted("player.volume") - && let Some(v) = get(&conn, "player.volume").as_f64() + && let Some(v) = get(conn, "player.volume").as_f64() { let _ = player.mpv().set_double("volume", v.clamp(0.0, 150.0)); } @@ -126,8 +125,7 @@ pub fn put(conn: &Connection, key: &str, value: &Value) -> Result<()> { #[tauri::command] pub async fn settings_get(state: State<'_, AppState>) -> Result> { - let conn = state.db.read(); - all(&conn) + read_blocking(state.inner(), all).await } #[tauri::command] @@ -137,11 +135,14 @@ pub async fn settings_set( key: String, value: Value, ) -> Result<()> { - put(&state.db.write(), &key, &value)?; - if key.starts_with("player.") { - apply_player(&app, state.inner(), Some(&key)); - } - Ok(()) + write_blocking(state.inner(), move |conn| { + put(conn, &key, &value)?; + if key.starts_with("player.") { + apply_player(&app, conn, Some(&key)); + } + Ok(()) + }) + .await } #[cfg(test)] diff --git a/src-tauri/src/sources/commands.rs b/src-tauri/src/sources/commands.rs new file mode 100644 index 0000000..7a33dbf --- /dev/null +++ b/src-tauri/src/sources/commands.rs @@ -0,0 +1,244 @@ +//! The Sources page: list, test, add, update and remove sources. + +use super::*; + +#[tauri::command] +pub async fn sources_list(state: State<'_, AppState>) -> Result> { + let syncing = state.syncing.lock().clone(); + read_blocking(state.inner(), move |conn| { + load_all(conn)? + .into_iter() + .map(|s| { + let busy = syncing.contains(&s.id); + view(conn, s, busy) + }) + .collect() + }) + .await +} + +#[derive(Debug, Serialize)] +#[serde( + rename_all = "camelCase", + rename_all_fields = "camelCase", + tag = "kind" +)] +pub enum TestResult { + Xtream { + account: AccountInfo, + }, + M3u { + channels: usize, + movies: usize, + episodes: usize, + epg_urls: Vec, + }, +} + +/// Validates credentials / playlist without saving anything. While editing a +/// saved source (`id`), an empty password field means the stored password. +#[tauri::command] +pub async fn source_test( + state: State<'_, AppState>, + input: SourceInput, + id: Option, +) -> Result { + let mut input = normalize_input(input)?; + if let Some(id) = id + && input.password.as_deref().is_none_or(str::is_empty) + { + let src = read_blocking(state.inner(), move |conn| load(conn, id)).await?; + if src.password_in_keyring && src.password.is_none() { + return Err(Error::msg(crate::secrets::UNAVAILABLE)); + } + input.password = src.password; + } + match input.kind { + SourceKind::Xtream => { + let x = Xtream::new( + &input.url, + &input.alt_urls, + input.username.as_deref().unwrap_or(""), + input.password.as_deref().unwrap_or(""), + http_client(input.user_agent.as_deref()), + ); + Ok(TestResult::Xtream { + account: x.account().await?, + }) + } + SourceKind::M3u => { + let text = download_text(&http_client(input.user_agent.as_deref()), &input.url).await?; + let pl = m3u::parse(&text); + if pl.entries.is_empty() { + return Err(Error::msg("The playlist is empty or not an M3U file")); + } + let mut c = (0, 0, 0); + for e in &pl.entries { + match e.kind() { + m3u::EntryKind::Live => c.0 += 1, + m3u::EntryKind::Movie => c.1 += 1, + m3u::EntryKind::Episode => c.2 += 1, + } + } + Ok(TestResult::M3u { + channels: c.0, + movies: c.1, + episodes: c.2, + epg_urls: pl.epg_urls, + }) + } + } +} + +#[tauri::command] +pub async fn source_add( + app: AppHandle, + state: State<'_, AppState>, + input: SourceInput, +) -> Result { + let input = normalize_input(input)?; + let st = state.inner().clone(); + let name = input + .name + .clone() + .filter(|n| !n.trim().is_empty()) + .unwrap_or_else(|| default_name(&input)); + let id = { + let input = input.clone(); + let name = name.clone(); + write_blocking(&st, move |conn| { + conn.execute( + "INSERT INTO source (kind, name, url, alt_urls, username, password, epg_url, user_agent, created_at, + catchup_shift_minutes) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + params![ + input.kind.as_str(), + name.trim(), + input.url, + serde_json::to_string(&input.alt_urls)?, + input.username.as_deref().map(str::trim), + input.password, + input.epg_url.as_deref().map(str::trim).filter(|s| !s.is_empty()), + input.user_agent.as_deref().map(str::trim).filter(|s| !s.is_empty()), + now(), + input.catchup_shift_minutes.unwrap_or(0) + ], + )?; + Ok(conn.last_insert_rowid()) + }) + .await? + }; + if let Some(password) = input.password.as_deref().filter(|p| !p.is_empty()) { + crate::secrets::move_to_keyring(&st, id, password, crate::secrets::Unlock::Prompt).await; + } + spawn_sync(app, st.clone(), id, SyncScope::Full); + read_blocking(&st, move |conn| view(conn, load(conn, id)?, true)).await +} + +#[tauri::command] +pub async fn source_update( + state: State<'_, AppState>, + id: i64, + input: SourceInput, +) -> Result { + let input = normalize_input(input)?; + let st = state.inner().clone(); + // an empty password field means "keep the stored one" (wherever it lives) + let new_password = input.password.clone().filter(|p| !p.is_empty()); + let (renamed, was_in_keyring) = { + let new_password = new_password.clone(); + write_blocking(&st, move |conn| { + let current = load(conn, id)?; + let name = input + .name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty()) + .unwrap_or(¤t.name); + conn.execute( + "UPDATE source SET kind = ?2, name = ?3, url = ?4, alt_urls = ?5, username = ?6, + password = CASE WHEN ?7 IS NULL THEN password ELSE ?7 END, + password_in_keyring = CASE WHEN ?7 IS NULL THEN password_in_keyring ELSE 0 END, + epg_url = ?8, user_agent = ?9, catchup_shift_minutes = ?10 WHERE id = ?1", + params![ + id, + input.kind.as_str(), + name, + input.url, + serde_json::to_string(&input.alt_urls)?, + input.username.as_deref().map(str::trim), + new_password, + input + .epg_url + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()), + input + .user_agent + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()), + input + .catchup_shift_minutes + .unwrap_or(current.catchup_shift_minutes), + ], + )?; + Ok((name != current.name, current.password_in_keyring)) + }) + .await? + }; + if let Some(password) = &new_password { + // the database copy is the current one until the keyring has it + crate::secrets::uncache(id); + crate::secrets::move_to_keyring(&st, id, password, crate::secrets::Unlock::Prompt).await; + } else if renamed + && was_in_keyring + && let Some(password) = crate::secrets::cached(id) + { + // the keyring entry's label names the source + crate::secrets::move_to_keyring(&st, id, &password, crate::secrets::Unlock::Never).await; + } + let busy = st.syncing.lock().contains(&id); + read_blocking(&st, move |conn| view(conn, load(conn, id)?, busy)).await +} + +#[tauri::command] +pub async fn source_remove(state: State<'_, AppState>, id: i64) -> Result<()> { + let st = state.inner().clone(); + let in_keyring = read_blocking(&st, move |conn| load(conn, id)) + .await? + .password_in_keyring; + write_blocking(&st, move |conn| { + let tx = conn.transaction()?; + tx.execute("DELETE FROM search WHERE source_id = ?1", [id])?; + tx.execute("DELETE FROM source WHERE id = ?1", [id])?; + crate::works::rebuild(&tx)?; + tx.commit()?; + Ok(()) + }) + .await?; + if in_keyring { + // a locked keyring asks first; the source is gone either way + tauri::async_runtime::spawn(async move { crate::secrets::forget(&st, id).await }); + } + Ok(()) +} + +#[tauri::command] +pub async fn source_sync( + app: AppHandle, + state: State<'_, AppState>, + id: i64, + epg_only: Option, +) -> Result<()> { + let scope = if epg_only.unwrap_or(false) { + SyncScope::Epg + } else { + SyncScope::Full + }; + let st = state.inner().clone(); + // the user asked for this: a keyring locked so far may prompt now + crate::secrets::ensure_loaded(&st, Some(id), crate::secrets::Unlock::Prompt).await; + spawn_sync(app, st, id, scope); + Ok(()) +} diff --git a/src-tauri/src/sources/m3u.rs b/src-tauri/src/sources/m3u.rs index 07de58d..a5ff709 100644 --- a/src-tauri/src/sources/m3u.rs +++ b/src-tauri/src/sources/m3u.rs @@ -98,10 +98,11 @@ impl Entry { return None; } static SXXEYY: LazyLock = LazyLock::new(|| { - Regex::new(r"(?i)^(.*?)[\s._-]*\bS(\d{1,3})[\s._-]*E(\d{1,4})\b(.*)$").unwrap() + Regex::new(r"(?i)^(.*?)[\s._-]*\bS(\d{1,3})[\s._-]*E(\d{1,4})\b(.*)$") + .expect("valid regex") }); static NXNN: LazyLock = LazyLock::new(|| { - Regex::new(r"(?i)^(.*?)[\s._-]*\b(\d{1,2})x(\d{2,3})\b(.*)$").unwrap() + Regex::new(r"(?i)^(.*?)[\s._-]*\b(\d{1,2})x(\d{2,3})\b(.*)$").expect("valid regex") }); let name = self.name.trim(); let c = SXXEYY.captures(name).or_else(|| NXNN.captures(name))?; @@ -341,7 +342,7 @@ pub fn catchup_url( fn fill_placeholders(template: &str, start: i64, duration: i64, now: i64, shift: i64) -> String { static PLACEHOLDER: LazyLock = - LazyLock::new(|| Regex::new(r"\$?\{([A-Za-z-]+)(?::([^}]*))?\}").unwrap()); + LazyLock::new(|| Regex::new(r"\$?\{([A-Za-z-]+)(?::([^}]*))?\}").expect("valid regex")); PLACEHOLDER .replace_all(template, |c: &Captures| { let arg = c.get(2).map(|m| m.as_str()); @@ -401,7 +402,7 @@ fn flussonic_url(url: &str, start: i64, duration: i64) -> Option { fn xtream_url(url: &str, start: i64, duration: i64) -> Option { static LIVE: LazyLock = LazyLock::new(|| { Regex::new(r"^(https?://[^/?#]+)/(?:live/)?([^/?#]+)/([^/?#]+)/(\d+)(?:\.[A-Za-z0-9]+)?$") - .unwrap() + .expect("valid regex") }); let c = LIVE.captures(url)?; let minutes = ((duration + 59) / 60).max(1); diff --git a/src-tauri/src/sources/mod.rs b/src-tauri/src/sources/mod.rs index abb4223..61554a2 100644 --- a/src-tauri/src/sources/mod.rs +++ b/src-tauri/src/sources/mod.rs @@ -1,9 +1,16 @@ //! IPTV sources (Xtream Codes accounts and M3U playlists): storage, sync //! into the local catalog, and EPG refresh. +mod commands; pub mod m3u; +mod store; +mod sync; pub mod xtream; +pub use commands::*; +use store::{XtreamLists, write_m3u, write_xtream}; +pub use sync::*; + use std::collections::{HashMap, HashSet}; use std::time::Duration; @@ -14,8 +21,9 @@ use tauri::{AppHandle, Emitter, Runtime, State}; use crate::db::now; use crate::error::{Error, Result}; +use crate::kind::ItemKind; use crate::names; -use crate::state::{AppState, http_client}; +use crate::state::{AppState, http_client, read_blocking, run_blocking, write_blocking}; use crate::util::fnv1a; use crate::util::json::{first_str, i64_of, str_of}; use xtream::{AccountInfo, Xtream, rating_of}; @@ -264,1094 +272,3 @@ fn default_name(input: &SourceInput) -> String { SourceKind::M3u => format!("{host} playlist"), } } - -// ------------------------------------------------------------------ commands - -#[tauri::command] -pub async fn sources_list(state: State<'_, AppState>) -> Result> { - let st = state.inner().clone(); - tokio::task::spawn_blocking(move || { - let conn = st.db.read(); - let syncing = st.syncing.lock().clone(); - load_all(&conn)? - .into_iter() - .map(|s| { - let busy = syncing.contains(&s.id); - view(&conn, s, busy) - }) - .collect() - }) - .await - .map_err(|e| Error::msg(e.to_string()))? -} - -#[derive(Debug, Serialize)] -#[serde( - rename_all = "camelCase", - rename_all_fields = "camelCase", - tag = "kind" -)] -pub enum TestResult { - Xtream { - account: AccountInfo, - }, - M3u { - channels: usize, - movies: usize, - episodes: usize, - epg_urls: Vec, - }, -} - -/// Validates credentials / playlist without saving anything. While editing a -/// saved source (`id`), an empty password field means the stored password. -#[tauri::command] -pub async fn source_test( - state: State<'_, AppState>, - input: SourceInput, - id: Option, -) -> Result { - let mut input = normalize_input(input)?; - if let Some(id) = id - && input.password.as_deref().is_none_or(str::is_empty) - { - let src = load(&state.db.read(), id)?; - if src.password_in_keyring && src.password.is_none() { - return Err(Error::msg(crate::secrets::UNAVAILABLE)); - } - input.password = src.password; - } - match input.kind { - SourceKind::Xtream => { - let x = Xtream::new( - &input.url, - &input.alt_urls, - input.username.as_deref().unwrap_or(""), - input.password.as_deref().unwrap_or(""), - http_client(input.user_agent.as_deref()), - ); - Ok(TestResult::Xtream { - account: x.account().await?, - }) - } - SourceKind::M3u => { - let text = download_text(&http_client(input.user_agent.as_deref()), &input.url).await?; - let pl = m3u::parse(&text); - if pl.entries.is_empty() { - return Err(Error::msg("The playlist is empty or not an M3U file")); - } - let mut c = (0, 0, 0); - for e in &pl.entries { - match e.kind() { - m3u::EntryKind::Live => c.0 += 1, - m3u::EntryKind::Movie => c.1 += 1, - m3u::EntryKind::Episode => c.2 += 1, - } - } - Ok(TestResult::M3u { - channels: c.0, - movies: c.1, - episodes: c.2, - epg_urls: pl.epg_urls, - }) - } - } -} - -#[tauri::command] -pub async fn source_add( - app: AppHandle, - state: State<'_, AppState>, - input: SourceInput, -) -> Result { - let input = normalize_input(input)?; - let st = state.inner().clone(); - let name = input - .name - .clone() - .filter(|n| !n.trim().is_empty()) - .unwrap_or_else(|| default_name(&input)); - let id = { - let conn = st.db.write(); - conn.execute( - "INSERT INTO source (kind, name, url, alt_urls, username, password, epg_url, user_agent, created_at, - catchup_shift_minutes) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", - params![ - input.kind.as_str(), - name.trim(), - input.url, - serde_json::to_string(&input.alt_urls)?, - input.username.as_deref().map(str::trim), - input.password, - input.epg_url.as_deref().map(str::trim).filter(|s| !s.is_empty()), - input.user_agent.as_deref().map(str::trim).filter(|s| !s.is_empty()), - now(), - input.catchup_shift_minutes.unwrap_or(0) - ], - )?; - conn.last_insert_rowid() - }; - if let Some(password) = input.password.as_deref().filter(|p| !p.is_empty()) { - crate::secrets::move_to_keyring(&st, id, password, crate::secrets::Unlock::Prompt).await; - } - spawn_sync(app, st.clone(), id, SyncScope::Full); - let conn = st.db.read(); - view(&conn, load(&conn, id)?, true) -} - -#[tauri::command] -pub async fn source_update( - state: State<'_, AppState>, - id: i64, - input: SourceInput, -) -> Result { - let input = normalize_input(input)?; - let st = state.inner().clone(); - // an empty password field means "keep the stored one" (wherever it lives) - let new_password = input.password.clone().filter(|p| !p.is_empty()); - let (renamed, was_in_keyring) = { - let conn = st.db.write(); - let current = load(&conn, id)?; - let name = input - .name - .as_deref() - .map(str::trim) - .filter(|n| !n.is_empty()) - .unwrap_or(¤t.name); - conn.execute( - "UPDATE source SET kind = ?2, name = ?3, url = ?4, alt_urls = ?5, username = ?6, - password = CASE WHEN ?7 IS NULL THEN password ELSE ?7 END, - password_in_keyring = CASE WHEN ?7 IS NULL THEN password_in_keyring ELSE 0 END, - epg_url = ?8, user_agent = ?9, catchup_shift_minutes = ?10 WHERE id = ?1", - params![ - id, - input.kind.as_str(), - name, - input.url, - serde_json::to_string(&input.alt_urls)?, - input.username.as_deref().map(str::trim), - new_password, - input - .epg_url - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()), - input - .user_agent - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()), - input - .catchup_shift_minutes - .unwrap_or(current.catchup_shift_minutes), - ], - )?; - (name != current.name, current.password_in_keyring) - }; - if let Some(password) = &new_password { - // the database copy is the current one until the keyring has it - crate::secrets::uncache(id); - crate::secrets::move_to_keyring(&st, id, password, crate::secrets::Unlock::Prompt).await; - } else if renamed - && was_in_keyring - && let Some(password) = crate::secrets::cached(id) - { - // the keyring entry's label names the source - crate::secrets::move_to_keyring(&st, id, &password, crate::secrets::Unlock::Never).await; - } - let conn = st.db.read(); - let busy = st.syncing.lock().contains(&id); - view(&conn, load(&conn, id)?, busy) -} - -#[tauri::command] -pub async fn source_remove(state: State<'_, AppState>, id: i64) -> Result<()> { - let st = state.inner().clone(); - let in_keyring = load(&st.db.read(), id)?.password_in_keyring; - let db = st.clone(); - tokio::task::spawn_blocking(move || -> Result<()> { - let mut conn = db.db.write(); - let tx = conn.transaction()?; - tx.execute("DELETE FROM search WHERE source_id = ?1", [id])?; - tx.execute("DELETE FROM source WHERE id = ?1", [id])?; - crate::works::rebuild(&tx)?; - tx.commit()?; - Ok(()) - }) - .await - .map_err(|e| Error::msg(e.to_string()))??; - if in_keyring { - // a locked keyring asks first; the source is gone either way - tauri::async_runtime::spawn(async move { crate::secrets::forget(&st, id).await }); - } - Ok(()) -} - -#[tauri::command] -pub async fn source_sync( - app: AppHandle, - state: State<'_, AppState>, - id: i64, - epg_only: Option, -) -> Result<()> { - let scope = if epg_only.unwrap_or(false) { - SyncScope::Epg - } else { - SyncScope::Full - }; - let st = state.inner().clone(); - // the user asked for this: a keyring locked so far may prompt now - crate::secrets::ensure_loaded(&st, Some(id), crate::secrets::Unlock::Prompt).await; - spawn_sync(app, st, id, scope); - Ok(()) -} - -// ---------------------------------------------------------------------- sync - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SyncScope { - Full, - Epg, -} - -/// Starts a background sync unless one is already running for the source. -pub fn spawn_sync(app: AppHandle, st: AppState, id: i64, scope: SyncScope) { - if !st.syncing.lock().insert(id) { - return; - } - tauri::async_runtime::spawn(async move { - let _ = app.emit(SYNC_EVENT, SyncProgress::Started { source_id: id }); - let result = run_sync(&app, &st, id, scope).await; - st.syncing.lock().remove(&id); - match result { - Ok(counts) => { - let _ = app.emit( - SYNC_EVENT, - SyncProgress::Done { - source_id: id, - counts, - }, - ); - // new titles: their TMDB details (when a key is set) - if scope == SyncScope::Full { - crate::tmdb::spawn(app.clone(), st.clone()); - } - } - Err(e) => { - log::warn!("sync of source {id} failed: {e}"); - if scope == SyncScope::Full { - let conn = st.db.write(); - let _ = conn.execute( - "UPDATE source SET sync_error = ?2 WHERE id = ?1", - params![id, e.to_string()], - ); - } - let _ = app.emit( - SYNC_EVENT, - SyncProgress::Failed { - source_id: id, - error: e.to_string(), - }, - ); - } - } - }); -} - -/// Syncs every source whose catalog/EPG is older than the given ages. -pub fn sync_stale( - app: &AppHandle, - st: &AppState, - catalog_max_age: i64, - epg_max_age: i64, -) { - let sources = { - let conn = st.db.read(); - load_all(&conn).unwrap_or_default() - }; - let t = now(); - for s in sources { - if s.last_sync.is_none_or(|l| t - l > catalog_max_age) { - spawn_sync(app.clone(), st.clone(), s.id, SyncScope::Full); - } else if s.last_epg_sync.is_none_or(|l| t - l > epg_max_age) { - spawn_sync(app.clone(), st.clone(), s.id, SyncScope::Epg); - } - } -} - -fn step(app: &AppHandle, id: i64, msg: &str) { - let _ = app.emit( - SYNC_EVENT, - SyncProgress::Step { - source_id: id, - message: msg.to_owned(), - }, - ); -} - -async fn run_sync( - app: &AppHandle, - st: &AppState, - id: i64, - scope: SyncScope, -) -> Result { - let src = { - let conn = st.db.read(); - load(&conn, id)? - }; - let client = http_client(src.user_agent.as_deref()); - let mut epg_urls: Vec = src.epg_url.iter().cloned().collect(); - - if scope == SyncScope::Full { - match src.kind { - SourceKind::Xtream => { - let x = xtream_for(&src, client.clone())?; - step(app, id, "Signing in…"); - let account = x.account().await?; - if !account.status.eq_ignore_ascii_case("active") { - return Err(Error::msg(format!( - "Account is {}", - account.status.to_lowercase() - ))); - } - { - let conn = st.db.write(); - conn.execute( - "UPDATE source SET account_json = ?2 WHERE id = ?1", - params![id, serde_json::to_string(&account)?], - )?; - } - step(app, id, "Downloading channels, movies and series…"); - let (lc, vc, sc, ls, vs, ss) = tokio::try_join!( - x.list("get_live_categories"), - x.list("get_vod_categories"), - x.list("get_series_categories"), - x.list("get_live_streams"), - x.list("get_vod_streams"), - x.list("get_series"), - )?; - step( - app, - id, - &format!( - "Saving {} channels, {} movies, {} series…", - ls.len(), - vs.len(), - ss.len() - ), - ); - let st2 = st.clone(); - tokio::task::spawn_blocking(move || { - let mut conn = st2.db.write(); - write_xtream( - &mut conn, - id, - XtreamLists { - lc, - vc, - sc, - ls, - vs, - ss, - }, - ) - }) - .await - .map_err(|e| Error::msg(e.to_string()))??; - if epg_urls.is_empty() { - epg_urls.push(x.xmltv_url()); - } - } - SourceKind::M3u => { - step(app, id, "Downloading playlist…"); - let text = download_text(&client, &src.url).await?; - let pl = m3u::parse(&text); - if pl.entries.is_empty() { - return Err(Error::msg("The playlist is empty or not an M3U file")); - } - step(app, id, &format!("Saving {} entries…", pl.entries.len())); - if epg_urls.is_empty() { - epg_urls.extend(pl.epg_urls.iter().cloned()); - } - let st2 = st.clone(); - tokio::task::spawn_blocking(move || { - let mut conn = st2.db.write(); - write_m3u(&mut conn, id, &pl) - }) - .await - .map_err(|e| Error::msg(e.to_string()))??; - } - } - let conn = st.db.write(); - conn.execute( - "UPDATE source SET last_sync = ?2, sync_error = NULL WHERE id = ?1", - params![id, now()], - )?; - } else if epg_urls.is_empty() { - match src.kind { - SourceKind::Xtream => epg_urls.push(xtream_for(&src, client.clone())?.xmltv_url()), - SourceKind::M3u => { - // the playlist header may name a guide - if let Ok(text) = download_text(&client, &src.url).await { - epg_urls.extend(m3u::parse(&text).epg_urls); - } - } - } - } - - // EPG is best effort: a broken guide must not fail the catalog sync. - if !epg_urls.is_empty() { - step(app, id, "Updating TV guide…"); - match sync_epg(st, id, &client, &epg_urls).await { - Ok(n) => log::info!("source {id}: imported {n} programmes"), - Err(e) => { - log::warn!("source {id}: EPG import failed: {e}"); - if scope == SyncScope::Epg { - return Err(e); - } - } - } - } - - let conn = st.db.read(); - counts(&conn, id) -} - -pub fn xtream_for(src: &SourceRow, client: reqwest::Client) -> Result { - if src.password_in_keyring && src.password.is_none() { - return Err(Error::msg(crate::secrets::UNAVAILABLE)); - } - // prefer the mirror that answered last time - let preferred = src.account.as_ref().and_then(|a| str_of(&a["baseUrl"])); - let mut alts = src.alt_urls.clone(); - let mut primary = src.url.clone(); - if let Some(p) = preferred.filter(|p| *p != src.url && alts.contains(p)) { - alts.retain(|a| *a != p); - alts.insert(0, primary); - primary = p; - } - Ok(Xtream::new( - &primary, - &alts, - src.username.as_deref().unwrap_or(""), - src.password.as_deref().unwrap_or(""), - client, - )) -} - -async fn download_text(client: &reqwest::Client, url: &str) -> Result { - let r = client - .get(url) - .timeout(Duration::from_secs(300)) - .send() - .await?; - if !r.status().is_success() { - return Err(Error::msg(format!("server answered {}", r.status()))); - } - let bytes = crate::epg::maybe_gunzip(r.bytes().await?.to_vec())?; - Ok(String::from_utf8_lossy(&bytes).into_owned()) -} - -async fn sync_epg( - st: &AppState, - id: i64, - client: &reqwest::Client, - urls: &[String], -) -> Result { - let mut last_err = None; - // guides reach 70+ MB: stream them to disk and parse from there - let file = st.cache_dir.join(format!("guide-{id}.part")); - for url in urls { - let res = async { - download_to(client, url, &file, Duration::from_secs(600)).await?; - let st2 = st.clone(); - let file2 = file.clone(); - tokio::task::spawn_blocking(move || -> Result { - let (wanted, past_days) = { - let conn = st2.db.read(); - let mut stmt = conn.prepare( - "SELECT DISTINCT epg_id FROM channel WHERE source_id = ?1 AND epg_id IS NOT NULL", - )?; - let wanted: HashSet = stmt.query_map([id], |r| r.get(0))?.collect::>()?; - (wanted, crate::epg::history_days(&conn, id)?) - }; - let guide = crate::epg::open_guide(&file2)?; - let mut conn = st2.db.write(); - let imported = crate::epg::import(&mut conn, id, guide, &wanted, past_days)?; - if let Some(e) = &imported.incomplete { - log::warn!("source {id}: guide document incomplete ({e}); kept {} programmes", imported.programmes); - } - conn.execute("UPDATE source SET last_epg_sync = ?2 WHERE id = ?1", params![id, now()])?; - Ok(imported.programmes) - }) - .await - .map_err(|e| Error::msg(e.to_string()))? - } - .await; - let _ = tokio::fs::remove_file(&file).await; - match res { - Ok(n) => return Ok(n), - Err(e) => last_err = Some(e), - } - } - Err(last_err.unwrap_or_else(|| Error::msg("no guide url"))) -} - -/// Streams a download into `path` (constant memory). -async fn download_to( - client: &reqwest::Client, - url: &str, - path: &std::path::Path, - timeout: Duration, -) -> Result { - use tokio::io::AsyncWriteExt; - let mut r = client.get(url).timeout(timeout).send().await?; - if !r.status().is_success() { - return Err(Error::msg(format!("guide server answered {}", r.status()))); - } - if let Some(dir) = path.parent() { - tokio::fs::create_dir_all(dir).await?; - } - let mut f = tokio::fs::File::create(path).await?; - let mut size = 0u64; - while let Some(chunk) = r.chunk().await? { - f.write_all(&chunk).await?; - size += chunk.len() as u64; - } - f.flush().await?; - Ok(size) -} - -// ------------------------------------------------------------ catalog writes - -struct XtreamLists { - lc: Vec, - vc: Vec, - sc: Vec, - ls: Vec, - vs: Vec, - ss: Vec, -} - -fn is_adult_name(name: &str) -> bool { - let n = name.to_uppercase(); - ["ADULT", "XXX", "18+", "PORN", "FOR ADULTS"] - .iter() - .any(|k| n.contains(k)) -} - -fn clear_catalog(tx: &Transaction, id: i64) -> Result<()> { - for table in ["category", "channel", "movie", "series", "episode"] { - tx.execute(&format!("DELETE FROM {table} WHERE source_id = ?1"), [id])?; - } - tx.execute("DELETE FROM search WHERE source_id = ?1", [id])?; - Ok(()) -} - -/// Provider detail payloads survive re-syncs ("Up next" and resume read the -/// cached series details); only entries whose item left the catalog go. -fn prune_detail_cache(tx: &Transaction, id: i64) -> Result<()> { - tx.execute( - "DELETE FROM detail_cache WHERE source_id = ?1 AND NOT EXISTS ( - SELECT 1 FROM movie m WHERE detail_cache.kind = 'movie' AND m.source_id = ?1 AND m.id = detail_cache.id - UNION ALL - SELECT 1 FROM series s WHERE detail_cache.kind = 'series' AND s.source_id = ?1 AND s.id = detail_cache.id)", - [id], - )?; - Ok(()) -} - -fn insert_categories( - tx: &Transaction, - id: i64, - kind: &str, - cats: &[Value], -) -> Result> { - let mut stmt = tx.prepare( - "INSERT OR REPLACE INTO category (source_id, kind, id, name, title, region, badges, adult, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", - )?; - let mut adult = HashSet::new(); - for (pos, c) in cats.iter().enumerate() { - let Some(cid) = str_of(&c["category_id"]) else { - continue; - }; - let name = names::unescape(&str_of(&c["category_name"]).unwrap_or_default()); - let cleaned = names::category(&name); - let is_adult = is_adult_name(&name); - if is_adult { - adult.insert(cid.clone()); - } - stmt.execute(params![ - id, - kind, - cid, - name, - cleaned.title, - cleaned.region, - names::badges_str(&cleaned.badges), - is_adult, - pos as i64 - ])?; - } - Ok(adult) -} - -fn write_xtream(conn: &mut Connection, id: i64, l: XtreamLists) -> Result<()> { - let tx = conn.transaction()?; - clear_catalog(&tx, id)?; - let adult_live = insert_categories(&tx, id, "live", &l.lc)?; - let adult_vod = insert_categories(&tx, id, "movie", &l.vc)?; - let adult_series = insert_categories(&tx, id, "series", &l.sc)?; - - let mut search = - tx.prepare("INSERT INTO search (title, kind, source_id, item_id) VALUES (?1, ?2, ?3, ?4)")?; - { - let mut stmt = tx.prepare( - "INSERT OR REPLACE INTO channel (source_id, id, num, name, title, logo, epg_id, category_id, - archive, archive_days, separator, badges, adult, added, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", - )?; - for (pos, s) in l.ls.iter().enumerate() { - let Some(sid) = str_of(&s["stream_id"]) else { - continue; - }; - let name = names::unescape(&str_of(&s["name"]).unwrap_or_default()); - let separator = names::is_separator(&name); - let cleaned = names::channel(&name); - let cat = str_of(&s["category_id"]); - let adult = i64_of(&s["is_adult"]) == Some(1) - || cat.as_ref().is_some_and(|c| adult_live.contains(c)); - stmt.execute(params![ - id, - sid, - i64_of(&s["num"]), - name, - cleaned.title, - str_of(&s["stream_icon"]), - str_of(&s["epg_channel_id"]), - cat, - i64_of(&s["tv_archive"]).unwrap_or(0) == 1, - i64_of(&s["tv_archive_duration"]).unwrap_or(0), - separator, - names::badges_str(&cleaned.badges), - adult, - i64_of(&s["added"]), - pos as i64 - ])?; - if !separator { - search.execute(params![cleaned.title, "live", id, sid])?; - } - } - } - { - let mut stmt = tx.prepare( - "INSERT OR REPLACE INTO movie (source_id, id, name, title, tag, year, poster, rating, tmdb, trailer, - added, category_id, ext, adult, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", - )?; - for (pos, m) in l.vs.iter().enumerate() { - let Some(sid) = str_of(&m["stream_id"]) else { - continue; - }; - let name = names::unescape(&str_of(&m["name"]).unwrap_or_default()); - let t = names::title(&name); - let cat = str_of(&m["category_id"]); - let adult = i64_of(&m["is_adult"]) == Some(1) - || cat.as_ref().is_some_and(|c| adult_vod.contains(c)); - stmt.execute(params![ - id, - sid, - name, - t.title, - t.tag, - t.year, - str_of(&m["stream_icon"]), - rating_of(&m["rating"]), - str_of(&m["tmdb"]), - str_of(&m["trailer"]), - i64_of(&m["added"]), - cat, - str_of(&m["container_extension"]), - adult, - pos as i64 - ])?; - search.execute(params![t.title, "movie", id, sid])?; - } - } - { - let mut stmt = tx.prepare( - "INSERT OR REPLACE INTO series (source_id, id, name, title, tag, year, cover, backdrop, plot, cast_list, - director, genre, release_date, rating, tmdb, trailer, last_modified, category_id, adult, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20)", - )?; - for (pos, s) in l.ss.iter().enumerate() { - let Some(sid) = str_of(&s["series_id"]) else { - continue; - }; - let name = names::unescape(&str_of(&s["name"]).unwrap_or_default()); - let t = names::title(&name); - let release = first_str(s, &["releaseDate", "release_date"]); - let year = t - .year - .or_else(|| release.as_deref().and_then(|r| r.get(..4)?.parse().ok())); - let backdrop = match &s["backdrop_path"] { - Value::Array(a) => a.iter().find_map(str_of), - v => str_of(v), - }; - let cat = str_of(&s["category_id"]); - let adult = cat.as_ref().is_some_and(|c| adult_series.contains(c)); - stmt.execute(params![ - id, - sid, - name, - t.title, - t.tag, - year, - str_of(&s["cover"]), - backdrop, - str_of(&s["plot"]), - str_of(&s["cast"]), - str_of(&s["director"]), - str_of(&s["genre"]), - release, - rating_of(&s["rating"]), - str_of(&s["tmdb"]), - str_of(&s["youtube_trailer"]), - i64_of(&s["last_modified"]), - cat, - adult, - pos as i64 - ])?; - search.execute(params![t.title, "series", id, sid])?; - } - } - drop(search); - prune_detail_cache(&tx, id)?; - crate::works::rebuild(&tx)?; - tx.commit()?; - Ok(()) -} - -fn write_m3u(conn: &mut Connection, id: i64, pl: &m3u::Playlist) -> Result<()> { - let tx = conn.transaction()?; - clear_catalog(&tx, id)?; - - // categories come from group-title, separately for live and VOD - let mut cats: HashMap<(&'static str, String), String> = HashMap::new(); - let mut cat_stmt = tx.prepare( - "INSERT OR REPLACE INTO category (source_id, kind, id, name, title, region, badges, adult, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", - )?; - let mut ch_stmt = tx.prepare( - "INSERT OR REPLACE INTO channel (source_id, id, num, name, title, logo, epg_id, category_id, - archive, archive_days, url, separator, badges, adult, position, catchup_mode, catchup_source, - user_agent, referrer) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)", - )?; - let mut mv_stmt = tx.prepare( - "INSERT OR REPLACE INTO movie (source_id, id, name, title, tag, year, poster, category_id, ext, url, adult, position, - user_agent, referrer) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)", - )?; - let mut sr_stmt = tx.prepare( - "INSERT OR REPLACE INTO series (source_id, id, name, title, tag, year, cover, category_id, adult, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", - )?; - let mut ep_stmt = tx.prepare( - "INSERT OR REPLACE INTO episode (source_id, series_id, id, season, episode, title, image, ext, url, - user_agent, referrer, position) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", - )?; - let mut search = - tx.prepare("INSERT INTO search (title, kind, source_id, item_id) VALUES (?1, ?2, ?3, ?4)")?; - let mut seen: HashSet = HashSet::new(); - let mut series_seen: HashSet = HashSet::new(); - - for (pos, e) in pl.entries.iter().enumerate() { - // "Show S01E02" / Xtream `/series/` entries become series + episodes - let episode = e.episode_info(); - let kind = match e.kind() { - m3u::EntryKind::Live => "live", - _ if episode.is_some() => "series", - _ => "movie", - }; - let group = e.group.clone().unwrap_or_else(|| "Uncategorized".into()); - let next_pos = cats.len() as i64; - let cat_id = cats - .entry((kind, group.clone())) - .or_insert_with(|| { - let cid = format!("{:x}", fnv1a(group.as_bytes())); - let c = names::category(&group); - let _ = cat_stmt.execute(params![ - id, - kind, - cid, - group, - c.title, - c.region, - names::badges_str(&c.badges), - is_adult_name(&group), - next_pos - ]); - cid - }) - .clone(); - let adult = is_adult_name(&group); - - // ids must survive re-syncs (favorites/history key on them), and - // tokenized URLs change, so hash the identity rather than the URL - let key = format!( - "{kind}\0{group}\0{}\0{}", - e.name, - e.tvg_id.as_deref().unwrap_or("") - ); - let mut item_id = format!("{:x}", fnv1a(key.as_bytes())); - let mut n = 1; - while !seen.insert(item_id.clone()) { - item_id = format!("{:x}", fnv1a(format!("{key}\0{n}").as_bytes())); - n += 1; - } - - if kind == "live" { - let separator = names::is_separator(&e.name); - let cleaned = names::channel(&e.name); - // offered only when `play` can build the catch-up URL - let days = e.catchup_window(); - ch_stmt.execute(params![ - id, - item_id, - e.chno, - e.name, - cleaned.title, - e.logo, - e.tvg_id, - cat_id, - days > 0, - days, - e.url, - separator, - names::badges_str(&cleaned.badges), - adult, - pos as i64, - e.catchup, - e.catchup_source, - e.user_agent, - e.referrer - ])?; - if !separator { - search.execute(params![cleaned.title, "live", id, item_id])?; - } - } else if let Some(info) = episode { - let t = names::title(&info.series); - let series_id = format!( - "{:x}", - fnv1a(format!("series\0{group}\0{}", t.title.to_lowercase()).as_bytes()) - ); - if series_seen.insert(series_id.clone()) { - sr_stmt.execute(params![ - id, - series_id, - info.series, - t.title, - t.tag, - t.year, - e.logo, - cat_id, - adult, - pos as i64 - ])?; - search.execute(params![t.title, "series", id, series_id])?; - } - let ext = e - .url - .split(['?', '#']) - .next() - .and_then(|p| p.rsplit_once('.')) - .map(|(_, x)| x.to_owned()); - ep_stmt.execute(params![ - id, - series_id, - item_id, - info.season, - info.episode, - info.title, - e.logo, - ext, - e.url, - e.user_agent, - e.referrer, - pos as i64 - ])?; - } else { - let t = names::title(&e.name); - let ext = e - .url - .split(['?', '#']) - .next() - .and_then(|p| p.rsplit_once('.')) - .map(|(_, x)| x.to_owned()); - mv_stmt.execute(params![ - id, - item_id, - e.name, - t.title, - t.tag, - t.year, - e.logo, - cat_id, - ext, - e.url, - adult, - pos as i64, - e.user_agent, - e.referrer - ])?; - search.execute(params![t.title, "movie", id, item_id])?; - } - } - drop((cat_stmt, ch_stmt, mv_stmt, sr_stmt, ep_stmt, search)); - prune_detail_cache(&tx, id)?; - crate::works::rebuild(&tx)?; - tx.commit()?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::db::test_conn; - use serde_json::json; - - fn series_lists(ids: &[&str]) -> XtreamLists { - XtreamLists { - lc: vec![], - vc: vec![], - sc: vec![json!({"category_id": "1", "category_name": "EN| DRAMA"})], - ls: vec![], - vs: vec![], - ss: ids.iter().map(|id| json!({"series_id": id, "name": format!("EN - Show {id} (2024)"), "category_id": "1"})).collect(), - } - } - - #[test] - fn resync_keeps_details_of_items_still_listed() { - let mut c = test_conn(); - write_xtream(&mut c, 1, series_lists(&["10", "11"])).unwrap(); - for id in ["10", "11"] { - c.execute("INSERT INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (1, 'series', ?1, '{}', 0)", [id]) - .unwrap(); - } - // "11" left the provider's catalog - write_xtream(&mut c, 1, series_lists(&["10"])).unwrap(); - let kept: Vec = c - .prepare("SELECT id FROM detail_cache") - .unwrap() - .query_map([], |r| r.get(0)) - .unwrap() - .map(|r| r.unwrap()) - .collect(); - assert_eq!(kept, vec!["10"]); - let title: String = c - .query_row("SELECT title FROM series WHERE id = '10'", [], |r| r.get(0)) - .unwrap(); - assert_eq!(title, "Show 10"); - } - - #[test] - fn m3u_episodes_become_series() { - let mut c = test_conn(); - let pl = m3u::parse(concat!( - "#EXTM3U\n", - "#EXTINF:-1 tvg-logo=\"http://i/slow.jpg\" group-title=\"Series: Apple\",EN - Slow Horses (2022) S01E02 - Failure's Contagious\n", - "http://h/series/u/p/12.mkv\n", - "#EXTINF:-1 group-title=\"Series: Apple\",EN - Slow Horses (2022) S01E01\n", - "http://h/series/u/p/11.mkv\n", - "#EXTINF:-1 group-title=\"Series: Apple\",EN - Slow Horses (2022) S02E01 - Last Stop\n", - "http://h/series/u/p/21.mkv\n", - "#EXTINF:-1 group-title=\"Series: Nordic\",Borgen S01 E01\n", - "http://h/borgen/101.mp4\n", - "#EXTINF:-1 group-title=\"Movies\",Heat (1995)\n", - "http://h/movie/u/p/7.mkv\n", - )); - write_m3u(&mut c, 1, &pl).unwrap(); - fn count(c: &Connection, sql: &str) -> i64 { - c.query_row(sql, [], |r| r.get(0)).unwrap() - } - assert_eq!(count(&c, "SELECT COUNT(*) FROM series"), 2); - assert_eq!(count(&c, "SELECT COUNT(*) FROM episode"), 4); - assert_eq!(count(&c, "SELECT COUNT(*) FROM movie"), 1); - assert_eq!( - count(&c, "SELECT COUNT(*) FROM category WHERE kind = 'series'"), - 2 - ); - let (sid, title, year, cover): (String, String, Option, Option) = c - .query_row( - "SELECT id, title, year, cover FROM series WHERE title = 'Slow Horses'", - [], - |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), - ) - .unwrap(); - assert_eq!( - (title.as_str(), year, cover.as_deref()), - ("Slow Horses", Some(2022), Some("http://i/slow.jpg")) - ); - let eps: Vec<(i64, i64, String)> = c - .prepare("SELECT season, episode, title FROM episode WHERE series_id = ?1 ORDER BY season, episode") - .unwrap() - .query_map([&sid], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) - .unwrap() - .map(|r| r.unwrap()) - .collect(); - assert_eq!( - eps, - [ - (1, 1, "".into()), - (1, 2, "Failure's Contagious".into()), - (2, 1, "Last Stop".into()) - ] - ); - // ids survive a re-sync (history and favorites key on them) - write_m3u(&mut c, 1, &pl).unwrap(); - assert_eq!( - count( - &c, - &format!("SELECT COUNT(*) FROM series WHERE id = '{sid}'") - ), - 1 - ); - } - - #[test] - fn m3u_channels_offer_catchup_only_when_playable() { - let mut c = test_conn(); - let pl = m3u::parse(concat!( - "#EXTM3U\n", - "#EXTINF:-1 catchup-days=\"7\" group-title=\"News\",No scheme\n", - "http://h/news.m3u8\n", - "#EXTINF:-1 catchup=\"append\" catchup-source=\"?utc={utc}\" catchup-days=\"3\" group-title=\"News\",Append\n", - "http://h/sport.m3u8\n", - "#EXTINF:-1 catchup=\"default\" catchup-days=\"3\" group-title=\"News\",No template\n", - "http://h/film.m3u8\n", - )); - write_m3u(&mut c, 1, &pl).unwrap(); - let rows: Vec<(String, bool, i64, Option)> = c - .prepare( - "SELECT name, archive, archive_days, catchup_mode FROM channel ORDER BY position", - ) - .unwrap() - .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))) - .unwrap() - .map(|r| r.unwrap()) - .collect(); - assert_eq!( - rows, - vec![ - ("No scheme".into(), false, 0, None), - ("Append".into(), true, 3, Some("append".into())), - ("No template".into(), false, 0, Some("default".into())), - ] - ); - } -} diff --git a/src-tauri/src/sources/store.rs b/src-tauri/src/sources/store.rs new file mode 100644 index 0000000..697abaa --- /dev/null +++ b/src-tauri/src/sources/store.rs @@ -0,0 +1,537 @@ +//! Writing a downloaded catalog into the database (one transaction per +//! source: replaced wholesale, details of items still listed kept). + +use super::*; + +/// The six lists an Xtream panel serves (`get_*_categories`, `get_*_streams`, +/// `get_series`). +pub(super) struct XtreamLists { + pub live_categories: Vec, + pub movie_categories: Vec, + pub series_categories: Vec, + pub live: Vec, + pub movies: Vec, + pub series: Vec, +} + +fn is_adult_name(name: &str) -> bool { + let n = name.to_uppercase(); + ["ADULT", "XXX", "18+", "PORN", "FOR ADULTS"] + .iter() + .any(|k| n.contains(k)) +} + +pub(super) fn clear_catalog(tx: &Transaction, id: i64) -> Result<()> { + for table in ["category", "channel", "movie", "series", "episode"] { + tx.execute(&format!("DELETE FROM {table} WHERE source_id = ?1"), [id])?; + } + tx.execute("DELETE FROM search WHERE source_id = ?1", [id])?; + Ok(()) +} + +/// Provider detail payloads survive re-syncs ("Up next" and resume read the +/// cached series details); only entries whose item left the catalog go. +fn prune_detail_cache(tx: &Transaction, id: i64) -> Result<()> { + tx.execute( + "DELETE FROM detail_cache WHERE source_id = ?1 AND NOT EXISTS ( + SELECT 1 FROM movie m WHERE detail_cache.kind = 'movie' AND m.source_id = ?1 AND m.id = detail_cache.id + UNION ALL + SELECT 1 FROM series s WHERE detail_cache.kind = 'series' AND s.source_id = ?1 AND s.id = detail_cache.id)", + [id], + )?; + Ok(()) +} + +pub(super) fn insert_categories( + tx: &Transaction, + id: i64, + kind: ItemKind, + cats: &[Value], +) -> Result> { + let mut stmt = tx.prepare( + "INSERT OR REPLACE INTO category (source_id, kind, id, name, title, region, badges, adult, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + )?; + let mut adult = HashSet::new(); + for (pos, c) in cats.iter().enumerate() { + let Some(cid) = str_of(&c["category_id"]) else { + continue; + }; + let name = names::unescape(&str_of(&c["category_name"]).unwrap_or_default()); + let cleaned = names::category(&name); + let is_adult = is_adult_name(&name); + if is_adult { + adult.insert(cid.clone()); + } + stmt.execute(params![ + id, + kind, + cid, + name, + cleaned.title, + cleaned.region, + names::badges_str(&cleaned.badges), + is_adult, + pos as i64 + ])?; + } + Ok(adult) +} + +pub(super) fn write_xtream(conn: &mut Connection, id: i64, l: XtreamLists) -> Result<()> { + let tx = conn.transaction()?; + clear_catalog(&tx, id)?; + let adult_live = insert_categories(&tx, id, ItemKind::Live, &l.live_categories)?; + let adult_vod = insert_categories(&tx, id, ItemKind::Movie, &l.movie_categories)?; + let adult_series = insert_categories(&tx, id, ItemKind::Series, &l.series_categories)?; + + let mut search = + tx.prepare("INSERT INTO search (title, kind, source_id, item_id) VALUES (?1, ?2, ?3, ?4)")?; + { + let mut stmt = tx.prepare( + "INSERT OR REPLACE INTO channel (source_id, id, num, name, title, logo, epg_id, category_id, + archive, archive_days, separator, badges, adult, added, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", + )?; + for (pos, s) in l.live.iter().enumerate() { + let Some(sid) = str_of(&s["stream_id"]) else { + continue; + }; + let name = names::unescape(&str_of(&s["name"]).unwrap_or_default()); + let separator = names::is_separator(&name); + let cleaned = names::channel(&name); + let cat = str_of(&s["category_id"]); + let adult = i64_of(&s["is_adult"]) == Some(1) + || cat.as_ref().is_some_and(|c| adult_live.contains(c)); + stmt.execute(params![ + id, + sid, + i64_of(&s["num"]), + name, + cleaned.title, + str_of(&s["stream_icon"]), + str_of(&s["epg_channel_id"]), + cat, + i64_of(&s["tv_archive"]).unwrap_or(0) == 1, + i64_of(&s["tv_archive_duration"]).unwrap_or(0), + separator, + names::badges_str(&cleaned.badges), + adult, + i64_of(&s["added"]), + pos as i64 + ])?; + if !separator { + search.execute(params![cleaned.title, ItemKind::Live, id, sid])?; + } + } + } + { + let mut stmt = tx.prepare( + "INSERT OR REPLACE INTO movie (source_id, id, name, title, tag, year, poster, rating, tmdb, trailer, + added, category_id, ext, adult, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", + )?; + for (pos, m) in l.movies.iter().enumerate() { + let Some(sid) = str_of(&m["stream_id"]) else { + continue; + }; + let name = names::unescape(&str_of(&m["name"]).unwrap_or_default()); + let t = names::title(&name); + let cat = str_of(&m["category_id"]); + let adult = i64_of(&m["is_adult"]) == Some(1) + || cat.as_ref().is_some_and(|c| adult_vod.contains(c)); + stmt.execute(params![ + id, + sid, + name, + t.title, + t.tag, + t.year, + str_of(&m["stream_icon"]), + rating_of(&m["rating"]), + str_of(&m["tmdb"]), + str_of(&m["trailer"]), + i64_of(&m["added"]), + cat, + str_of(&m["container_extension"]), + adult, + pos as i64 + ])?; + search.execute(params![t.title, ItemKind::Movie, id, sid])?; + } + } + { + let mut stmt = tx.prepare( + "INSERT OR REPLACE INTO series (source_id, id, name, title, tag, year, cover, backdrop, plot, cast_list, + director, genre, release_date, rating, tmdb, trailer, last_modified, category_id, adult, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20)", + )?; + for (pos, s) in l.series.iter().enumerate() { + let Some(sid) = str_of(&s["series_id"]) else { + continue; + }; + let name = names::unescape(&str_of(&s["name"]).unwrap_or_default()); + let t = names::title(&name); + let release = first_str(s, &["releaseDate", "release_date"]); + let year = t + .year + .or_else(|| release.as_deref().and_then(|r| r.get(..4)?.parse().ok())); + let backdrop = match &s["backdrop_path"] { + Value::Array(a) => a.iter().find_map(str_of), + v => str_of(v), + }; + let cat = str_of(&s["category_id"]); + let adult = cat.as_ref().is_some_and(|c| adult_series.contains(c)); + stmt.execute(params![ + id, + sid, + name, + t.title, + t.tag, + year, + str_of(&s["cover"]), + backdrop, + str_of(&s["plot"]), + str_of(&s["cast"]), + str_of(&s["director"]), + str_of(&s["genre"]), + release, + rating_of(&s["rating"]), + str_of(&s["tmdb"]), + str_of(&s["youtube_trailer"]), + i64_of(&s["last_modified"]), + cat, + adult, + pos as i64 + ])?; + search.execute(params![t.title, ItemKind::Series, id, sid])?; + } + } + drop(search); + prune_detail_cache(&tx, id)?; + crate::works::rebuild(&tx)?; + tx.commit()?; + Ok(()) +} + +pub(super) fn write_m3u(conn: &mut Connection, id: i64, pl: &m3u::Playlist) -> Result<()> { + let tx = conn.transaction()?; + clear_catalog(&tx, id)?; + + // categories come from group-title, separately for live and VOD + let mut cats: HashMap<(ItemKind, String), String> = HashMap::new(); + let mut cat_stmt = tx.prepare( + "INSERT OR REPLACE INTO category (source_id, kind, id, name, title, region, badges, adult, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + )?; + let mut ch_stmt = tx.prepare( + "INSERT OR REPLACE INTO channel (source_id, id, num, name, title, logo, epg_id, category_id, + archive, archive_days, url, separator, badges, adult, position, catchup_mode, catchup_source, + user_agent, referrer) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)", + )?; + let mut mv_stmt = tx.prepare( + "INSERT OR REPLACE INTO movie (source_id, id, name, title, tag, year, poster, category_id, ext, url, adult, position, + user_agent, referrer) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)", + )?; + let mut sr_stmt = tx.prepare( + "INSERT OR REPLACE INTO series (source_id, id, name, title, tag, year, cover, category_id, adult, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + )?; + let mut ep_stmt = tx.prepare( + "INSERT OR REPLACE INTO episode (source_id, series_id, id, season, episode, title, image, ext, url, + user_agent, referrer, position) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", + )?; + let mut search = + tx.prepare("INSERT INTO search (title, kind, source_id, item_id) VALUES (?1, ?2, ?3, ?4)")?; + let mut seen: HashSet = HashSet::new(); + let mut series_seen: HashSet = HashSet::new(); + + for (pos, e) in pl.entries.iter().enumerate() { + // "Show S01E02" / Xtream `/series/` entries become series + episodes + let episode = e.episode_info(); + let kind = match e.kind() { + m3u::EntryKind::Live => ItemKind::Live, + _ if episode.is_some() => ItemKind::Series, + _ => ItemKind::Movie, + }; + let group = e.group.clone().unwrap_or_else(|| "Uncategorized".into()); + let cat_id = match cats.get(&(kind, group.clone())) { + Some(cid) => cid.clone(), + None => { + let cid = format!("{:x}", fnv1a(group.as_bytes())); + let c = names::category(&group); + cat_stmt.execute(params![ + id, + kind, + cid, + group, + c.title, + c.region, + names::badges_str(&c.badges), + is_adult_name(&group), + cats.len() as i64 + ])?; + cats.insert((kind, group.clone()), cid.clone()); + cid + } + }; + let adult = is_adult_name(&group); + + // ids must survive re-syncs (favorites/history key on them), and + // tokenized URLs change, so hash the identity rather than the URL + let key = format!( + "{kind}\0{group}\0{}\0{}", + e.name, + e.tvg_id.as_deref().unwrap_or("") + ); + let mut item_id = format!("{:x}", fnv1a(key.as_bytes())); + let mut n = 1; + while !seen.insert(item_id.clone()) { + item_id = format!("{:x}", fnv1a(format!("{key}\0{n}").as_bytes())); + n += 1; + } + + if kind == ItemKind::Live { + let separator = names::is_separator(&e.name); + let cleaned = names::channel(&e.name); + // offered only when `play` can build the catch-up URL + let days = e.catchup_window(); + ch_stmt.execute(params![ + id, + item_id, + e.chno, + e.name, + cleaned.title, + e.logo, + e.tvg_id, + cat_id, + days > 0, + days, + e.url, + separator, + names::badges_str(&cleaned.badges), + adult, + pos as i64, + e.catchup, + e.catchup_source, + e.user_agent, + e.referrer + ])?; + if !separator { + search.execute(params![cleaned.title, ItemKind::Live, id, item_id])?; + } + } else if let Some(info) = episode { + let t = names::title(&info.series); + let series_id = format!( + "{:x}", + fnv1a(format!("series\0{group}\0{}", t.title.to_lowercase()).as_bytes()) + ); + if series_seen.insert(series_id.clone()) { + sr_stmt.execute(params![ + id, + series_id, + info.series, + t.title, + t.tag, + t.year, + e.logo, + cat_id, + adult, + pos as i64 + ])?; + search.execute(params![t.title, ItemKind::Series, id, series_id])?; + } + let ext = e + .url + .split(['?', '#']) + .next() + .and_then(|p| p.rsplit_once('.')) + .map(|(_, x)| x.to_owned()); + ep_stmt.execute(params![ + id, + series_id, + item_id, + info.season, + info.episode, + info.title, + e.logo, + ext, + e.url, + e.user_agent, + e.referrer, + pos as i64 + ])?; + } else { + let t = names::title(&e.name); + let ext = e + .url + .split(['?', '#']) + .next() + .and_then(|p| p.rsplit_once('.')) + .map(|(_, x)| x.to_owned()); + mv_stmt.execute(params![ + id, + item_id, + e.name, + t.title, + t.tag, + t.year, + e.logo, + cat_id, + ext, + e.url, + adult, + pos as i64, + e.user_agent, + e.referrer + ])?; + search.execute(params![t.title, ItemKind::Movie, id, item_id])?; + } + } + drop((cat_stmt, ch_stmt, mv_stmt, sr_stmt, ep_stmt, search)); + prune_detail_cache(&tx, id)?; + crate::works::rebuild(&tx)?; + tx.commit()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::test_conn; + use serde_json::json; + + fn series_lists(ids: &[&str]) -> XtreamLists { + XtreamLists { + live_categories: vec![], + movie_categories: vec![], + series_categories: vec![json!({"category_id": "1", "category_name": "EN| DRAMA"})], + live: vec![], + movies: vec![], + series: ids.iter().map(|id| json!({"series_id": id, "name": format!("EN - Show {id} (2024)"), "category_id": "1"})).collect(), + } + } + + #[test] + fn resync_keeps_details_of_items_still_listed() { + let mut c = test_conn(); + write_xtream(&mut c, 1, series_lists(&["10", "11"])).unwrap(); + for id in ["10", "11"] { + c.execute("INSERT INTO detail_cache (source_id, kind, id, json, fetched_at) VALUES (1, 'series', ?1, '{}', 0)", [id]) + .unwrap(); + } + // "11" left the provider's catalog + write_xtream(&mut c, 1, series_lists(&["10"])).unwrap(); + let kept: Vec = c + .prepare("SELECT id FROM detail_cache") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!(kept, vec!["10"]); + let title: String = c + .query_row("SELECT title FROM series WHERE id = '10'", [], |r| r.get(0)) + .unwrap(); + assert_eq!(title, "Show 10"); + } + + #[test] + fn m3u_episodes_become_series() { + let mut c = test_conn(); + let pl = m3u::parse(concat!( + "#EXTM3U\n", + "#EXTINF:-1 tvg-logo=\"http://i/slow.jpg\" group-title=\"Series: Apple\",EN - Slow Horses (2022) S01E02 - Failure's Contagious\n", + "http://h/series/u/p/12.mkv\n", + "#EXTINF:-1 group-title=\"Series: Apple\",EN - Slow Horses (2022) S01E01\n", + "http://h/series/u/p/11.mkv\n", + "#EXTINF:-1 group-title=\"Series: Apple\",EN - Slow Horses (2022) S02E01 - Last Stop\n", + "http://h/series/u/p/21.mkv\n", + "#EXTINF:-1 group-title=\"Series: Nordic\",Borgen S01 E01\n", + "http://h/borgen/101.mp4\n", + "#EXTINF:-1 group-title=\"Movies\",Heat (1995)\n", + "http://h/movie/u/p/7.mkv\n", + )); + write_m3u(&mut c, 1, &pl).unwrap(); + fn count(c: &Connection, sql: &str) -> i64 { + c.query_row(sql, [], |r| r.get(0)).unwrap() + } + assert_eq!(count(&c, "SELECT COUNT(*) FROM series"), 2); + assert_eq!(count(&c, "SELECT COUNT(*) FROM episode"), 4); + assert_eq!(count(&c, "SELECT COUNT(*) FROM movie"), 1); + assert_eq!( + count(&c, "SELECT COUNT(*) FROM category WHERE kind = 'series'"), + 2 + ); + let (sid, title, year, cover): (String, String, Option, Option) = c + .query_row( + "SELECT id, title, year, cover FROM series WHERE title = 'Slow Horses'", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .unwrap(); + assert_eq!( + (title.as_str(), year, cover.as_deref()), + ("Slow Horses", Some(2022), Some("http://i/slow.jpg")) + ); + let eps: Vec<(i64, i64, String)> = c + .prepare("SELECT season, episode, title FROM episode WHERE series_id = ?1 ORDER BY season, episode") + .unwrap() + .query_map([&sid], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!( + eps, + [ + (1, 1, "".into()), + (1, 2, "Failure's Contagious".into()), + (2, 1, "Last Stop".into()) + ] + ); + // ids survive a re-sync (history and favorites key on them) + write_m3u(&mut c, 1, &pl).unwrap(); + assert_eq!( + count( + &c, + &format!("SELECT COUNT(*) FROM series WHERE id = '{sid}'") + ), + 1 + ); + } + + #[test] + fn m3u_channels_offer_catchup_only_when_playable() { + let mut c = test_conn(); + let pl = m3u::parse(concat!( + "#EXTM3U\n", + "#EXTINF:-1 catchup-days=\"7\" group-title=\"News\",No scheme\n", + "http://h/news.m3u8\n", + "#EXTINF:-1 catchup=\"append\" catchup-source=\"?utc={utc}\" catchup-days=\"3\" group-title=\"News\",Append\n", + "http://h/sport.m3u8\n", + "#EXTINF:-1 catchup=\"default\" catchup-days=\"3\" group-title=\"News\",No template\n", + "http://h/film.m3u8\n", + )); + write_m3u(&mut c, 1, &pl).unwrap(); + let rows: Vec<(String, bool, i64, Option)> = c + .prepare( + "SELECT name, archive, archive_days, catchup_mode FROM channel ORDER BY position", + ) + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!( + rows, + vec![ + ("No scheme".into(), false, 0, None), + ("Append".into(), true, 3, Some("append".into())), + ("No template".into(), false, 0, Some("default".into())), + ] + ); + } +} diff --git a/src-tauri/src/sources/sync.rs b/src-tauri/src/sources/sync.rs new file mode 100644 index 0000000..04b12bc --- /dev/null +++ b/src-tauri/src/sources/sync.rs @@ -0,0 +1,308 @@ +//! Syncing a source: download its lists (or playlist) into the catalog, +//! then its guide; and the periodic refresh of stale sources. + +use super::*; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SyncScope { + Full, + Epg, +} + +/// Starts a background sync unless one is already running for the source. +pub fn spawn_sync(app: AppHandle, st: AppState, id: i64, scope: SyncScope) { + if !st.syncing.lock().insert(id) { + return; + } + tauri::async_runtime::spawn(async move { + let _ = app.emit(SYNC_EVENT, SyncProgress::Started { source_id: id }); + let result = run_sync(&app, &st, id, scope).await; + st.syncing.lock().remove(&id); + match result { + Ok(counts) => { + let _ = app.emit( + SYNC_EVENT, + SyncProgress::Done { + source_id: id, + counts, + }, + ); + // new titles: their TMDB details (when a key is set) + if scope == SyncScope::Full { + crate::tmdb::spawn(app.clone(), st.clone()); + } + } + Err(e) => { + log::warn!("sync of source {id} failed: {e}"); + if scope == SyncScope::Full { + let message = e.to_string(); + let saved = write_blocking(&st, move |conn| { + conn.execute( + "UPDATE source SET sync_error = ?2 WHERE id = ?1", + params![id, message], + )?; + Ok(()) + }) + .await; + if let Err(e) = saved { + log::warn!("source {id}: cannot store the sync error: {e}"); + } + } + let _ = app.emit( + SYNC_EVENT, + SyncProgress::Failed { + source_id: id, + error: e.to_string(), + }, + ); + } + } + }); +} + +/// Syncs every source whose catalog/EPG is older than the given ages. +pub async fn sync_stale( + app: &AppHandle, + st: &AppState, + catalog_max_age: i64, + epg_max_age: i64, +) { + let sources = read_blocking(st, load_all).await.unwrap_or_default(); + let t = now(); + for s in sources { + if s.last_sync.is_none_or(|l| t - l > catalog_max_age) { + spawn_sync(app.clone(), st.clone(), s.id, SyncScope::Full); + } else if s.last_epg_sync.is_none_or(|l| t - l > epg_max_age) { + spawn_sync(app.clone(), st.clone(), s.id, SyncScope::Epg); + } + } +} + +fn step(app: &AppHandle, id: i64, msg: &str) { + let _ = app.emit( + SYNC_EVENT, + SyncProgress::Step { + source_id: id, + message: msg.to_owned(), + }, + ); +} + +async fn run_sync( + app: &AppHandle, + st: &AppState, + id: i64, + scope: SyncScope, +) -> Result { + let src = read_blocking(st, move |conn| load(conn, id)).await?; + let client = http_client(src.user_agent.as_deref()); + let mut epg_urls: Vec = src.epg_url.iter().cloned().collect(); + + if scope == SyncScope::Full { + match src.kind { + SourceKind::Xtream => { + let x = xtream_for(&src, client.clone())?; + step(app, id, "Signing in…"); + let account = x.account().await?; + if !account.status.eq_ignore_ascii_case("active") { + return Err(Error::msg(format!( + "Account is {}", + account.status.to_lowercase() + ))); + } + let account_json = serde_json::to_string(&account)?; + write_blocking(st, move |conn| { + conn.execute( + "UPDATE source SET account_json = ?2 WHERE id = ?1", + params![id, account_json], + )?; + Ok(()) + }) + .await?; + step(app, id, "Downloading channels, movies and series…"); + let (live_categories, movie_categories, series_categories, live, movies, series) = + tokio::try_join!( + x.list("get_live_categories"), + x.list("get_vod_categories"), + x.list("get_series_categories"), + x.list("get_live_streams"), + x.list("get_vod_streams"), + x.list("get_series"), + )?; + step( + app, + id, + &format!( + "Saving {} channels, {} movies, {} series…", + live.len(), + movies.len(), + series.len() + ), + ); + let lists = XtreamLists { + live_categories, + movie_categories, + series_categories, + live, + movies, + series, + }; + write_blocking(st, move |conn| write_xtream(conn, id, lists)).await?; + if epg_urls.is_empty() { + epg_urls.push(x.xmltv_url()); + } + } + SourceKind::M3u => { + step(app, id, "Downloading playlist…"); + let text = download_text(&client, &src.url).await?; + let pl = m3u::parse(&text); + if pl.entries.is_empty() { + return Err(Error::msg("The playlist is empty or not an M3U file")); + } + step(app, id, &format!("Saving {} entries…", pl.entries.len())); + if epg_urls.is_empty() { + epg_urls.extend(pl.epg_urls.iter().cloned()); + } + write_blocking(st, move |conn| write_m3u(conn, id, &pl)).await?; + } + } + write_blocking(st, move |conn| { + conn.execute( + "UPDATE source SET last_sync = ?2, sync_error = NULL WHERE id = ?1", + params![id, now()], + )?; + Ok(()) + }) + .await?; + } else if epg_urls.is_empty() { + match src.kind { + SourceKind::Xtream => epg_urls.push(xtream_for(&src, client.clone())?.xmltv_url()), + SourceKind::M3u => { + // the playlist header may name a guide + if let Ok(text) = download_text(&client, &src.url).await { + epg_urls.extend(m3u::parse(&text).epg_urls); + } + } + } + } + + // EPG is best effort: a broken guide must not fail the catalog sync. + if !epg_urls.is_empty() { + step(app, id, "Updating TV guide…"); + match sync_epg(st, id, &client, &epg_urls).await { + Ok(n) => log::info!("source {id}: imported {n} programmes"), + Err(e) => { + log::warn!("source {id}: EPG import failed: {e}"); + if scope == SyncScope::Epg { + return Err(e); + } + } + } + } + + read_blocking(st, move |conn| counts(conn, id)).await +} + +pub fn xtream_for(src: &SourceRow, client: reqwest::Client) -> Result { + if src.password_in_keyring && src.password.is_none() { + return Err(Error::msg(crate::secrets::UNAVAILABLE)); + } + // prefer the mirror that answered last time + let preferred = src.account.as_ref().and_then(|a| str_of(&a["baseUrl"])); + let mut alts = src.alt_urls.clone(); + let mut primary = src.url.clone(); + if let Some(p) = preferred.filter(|p| *p != src.url && alts.contains(p)) { + alts.retain(|a| *a != p); + alts.insert(0, primary); + primary = p; + } + Ok(Xtream::new( + &primary, + &alts, + src.username.as_deref().unwrap_or(""), + src.password.as_deref().unwrap_or(""), + client, + )) +} + +/// Whole-body limits: playlists and guides of big providers are tens of MB. +const PLAYLIST_TIMEOUT: Duration = Duration::from_secs(300); +const GUIDE_TIMEOUT: Duration = Duration::from_secs(600); + +pub(super) async fn download_text(client: &reqwest::Client, url: &str) -> Result { + let r = client.get(url).timeout(PLAYLIST_TIMEOUT).send().await?; + if !r.status().is_success() { + return Err(Error::msg(format!("server answered {}", r.status()))); + } + let bytes = crate::epg::maybe_gunzip(r.bytes().await?.to_vec())?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +async fn sync_epg( + st: &AppState, + id: i64, + client: &reqwest::Client, + urls: &[String], +) -> Result { + let mut last_err = None; + // guides reach 70+ MB: stream them to disk and parse from there + let file = st.cache_dir.join(format!("guide-{id}.part")); + for url in urls { + let res = async { + download_to(client, url, &file, GUIDE_TIMEOUT).await?; + let st2 = st.clone(); + let file2 = file.clone(); + run_blocking(move || -> Result { + let (wanted, past_days) = { + let conn = st2.db.read(); + let mut stmt = conn.prepare( + "SELECT DISTINCT epg_id FROM channel WHERE source_id = ?1 AND epg_id IS NOT NULL", + )?; + let wanted: HashSet = stmt.query_map([id], |r| r.get(0))?.collect::>()?; + (wanted, crate::epg::history_days(&conn, id)?) + }; + let guide = crate::epg::open_guide(&file2)?; + let mut conn = st2.db.write(); + let imported = crate::epg::import(&mut conn, id, guide, &wanted, past_days)?; + if let Some(e) = &imported.incomplete { + log::warn!("source {id}: guide document incomplete ({e}); kept {} programmes", imported.programmes); + } + conn.execute("UPDATE source SET last_epg_sync = ?2 WHERE id = ?1", params![id, now()])?; + Ok(imported.programmes) + }) + .await? + } + .await; + let _ = tokio::fs::remove_file(&file).await; + match res { + Ok(n) => return Ok(n), + Err(e) => last_err = Some(e), + } + } + Err(last_err.unwrap_or_else(|| Error::msg("no guide url"))) +} + +/// Streams a download into `path` (constant memory). +async fn download_to( + client: &reqwest::Client, + url: &str, + path: &std::path::Path, + timeout: Duration, +) -> Result { + use tokio::io::AsyncWriteExt; + let mut r = client.get(url).timeout(timeout).send().await?; + if !r.status().is_success() { + return Err(Error::msg(format!("guide server answered {}", r.status()))); + } + if let Some(dir) = path.parent() { + tokio::fs::create_dir_all(dir).await?; + } + let mut f = tokio::fs::File::create(path).await?; + let mut size = 0u64; + while let Some(chunk) = r.chunk().await? { + f.write_all(&chunk).await?; + size += chunk.len() as u64; + } + f.flush().await?; + Ok(size) +} diff --git a/src-tauri/src/sources/xtream.rs b/src-tauri/src/sources/xtream.rs index 6cff888..3b6809a 100644 --- a/src-tauri/src/sources/xtream.rs +++ b/src-tauri/src/sources/xtream.rs @@ -10,6 +10,12 @@ use url::Url; use crate::error::{Error, Result}; use crate::util::json::{f64_of, i64_of, str_of}; +/// Per-request limits: account checks and short EPG are quick, the full +/// stream lists of large panels take minutes to generate. +const QUICK_TIMEOUT: Duration = Duration::from_secs(20); +const LIST_TIMEOUT: Duration = Duration::from_secs(180); +const INFO_TIMEOUT: Duration = Duration::from_secs(30); + pub struct Xtream { bases: Vec, current: AtomicUsize, @@ -192,7 +198,7 @@ impl Xtream { } pub async fn account(&self) -> Result { - let v = self.get(None, &[], Duration::from_secs(20)).await?; + let v = self.get(None, &[], QUICK_TIMEOUT).await?; let ui = v.get("user_info").cloned().unwrap_or(Value::Null); let si = v.get("server_info").cloned().unwrap_or(Value::Null); if i64_of(&ui["auth"]) != Some(1) { @@ -228,9 +234,7 @@ impl Xtream { } pub async fn list(&self, action: &str) -> Result> { - let v = self - .get(Some(action), &[], Duration::from_secs(180)) - .await?; + let v = self.get(Some(action), &[], LIST_TIMEOUT).await?; Ok(match v { Value::Array(a) => a, // some panels return {} for empty lists @@ -242,7 +246,7 @@ impl Xtream { self.get( Some("get_vod_info"), &[("vod_id", id.to_owned())], - Duration::from_secs(30), + INFO_TIMEOUT, ) .await } @@ -251,7 +255,7 @@ impl Xtream { self.get( Some("get_series_info"), &[("series_id", id.to_owned())], - Duration::from_secs(30), + INFO_TIMEOUT, ) .await } @@ -263,7 +267,7 @@ impl Xtream { ("stream_id", stream_id.to_owned()), ("limit", limit.to_string()), ], - Duration::from_secs(20), + QUICK_TIMEOUT, ) .await } diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index e2106a3..a4c5d48 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -5,7 +5,10 @@ use std::time::Duration; use parking_lot::Mutex; +use rusqlite::Connection; + use crate::db::Db; +use crate::error::{Error, Result}; pub const DEFAULT_USER_AGENT: &str = concat!("testpattern/", env!("CARGO_PKG_VERSION")); @@ -19,6 +22,34 @@ pub struct App { pub type AppState = Arc; +/// Runs `f` on the blocking pool with a reader connection. Async commands go +/// through this (or `write_blocking`): the database locks are plain mutexes, +/// and the writer is held for a whole catalog sync, so taking them on the +/// async runtime would stall its worker threads meanwhile. +pub async fn read_blocking( + st: &AppState, + f: impl FnOnce(&Connection) -> Result + Send + 'static, +) -> Result { + let st = st.clone(); + run_blocking(move || f(&st.db.read())).await? +} + +/// `read_blocking` with the writer connection. +pub async fn write_blocking( + st: &AppState, + f: impl FnOnce(&mut Connection) -> Result + Send + 'static, +) -> Result { + let st = st.clone(); + run_blocking(move || f(&mut st.db.write())).await? +} + +/// `spawn_blocking` with a join failure (a panic in `f`) as an `Error`. +pub async fn run_blocking(f: impl FnOnce() -> T + Send + 'static) -> Result { + tokio::task::spawn_blocking(f) + .await + .map_err(|e| Error::msg(e.to_string())) +} + pub fn http_client(user_agent: Option<&str>) -> reqwest::Client { reqwest::Client::builder() .user_agent( diff --git a/src-tauri/src/tmdb.rs b/src-tauri/src/tmdb.rs index da67e4f..40ee999 100644 --- a/src-tauri/src/tmdb.rs +++ b/src-tauri/src/tmdb.rs @@ -19,7 +19,8 @@ use tauri::{AppHandle, Emitter, Runtime, State}; use crate::db::now; use crate::error::{Error, Result}; -use crate::state::{AppState, http_client}; +use crate::kind::WorkKind; +use crate::state::{AppState, http_client, read_blocking, write_blocking}; /// Setting holding the API key (v3) or read access token (v4). Kept out of /// `settings_get` and logs. @@ -88,9 +89,9 @@ fn year_of(v: &Value) -> Option { } impl Info { - /// From `GET /movie/{id}` (kind "movie") or `GET /tv/{id}` ("tv"). - pub fn from_details(kind: &str, v: &Value) -> Info { - let tv = kind == "tv"; + /// From `GET /movie/{id}` or `GET /tv/{id}`. + pub fn from_details(kind: WorkKind, v: &Value) -> Info { + let tv = kind == WorkKind::Series; // both kinds have `origin_country` (ISO 3166-1 codes); older movie // records only `production_countries` let mut countries: Vec = v["origin_country"] @@ -126,22 +127,6 @@ impl Info { // ------------------------------------------------------------------ client -/// TMDB's two title types (our "series" are "tv"). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Movie, - Tv, -} - -impl Kind { - pub fn as_str(self) -> &'static str { - match self { - Kind::Movie => "movie", - Kind::Tv => "tv", - } - } -} - enum Auth { /// v4 read access token (a JWT): `Authorization: Bearer …` Bearer(String), @@ -206,7 +191,7 @@ impl Client { let resp = self.get_with(path, extra).await?; match resp.status().as_u16() { 200 => return resp.json().await.map_err(|e| Error::from(e.without_url())), - 401 | 403 => return Err(Error::msg(REJECTED)), + 401 | 403 => return Err(Error::TmdbRejected), 404 => return Ok(Value::Null), 429 => { let wait = resp @@ -225,24 +210,22 @@ impl Client { /// Details of one title; 404 comes back as Fetched::Missing, and the /// shared 429/401/403 handling lives in json(). - async fn details(&self, kind: Kind, id: &str) -> Result { - let v = self.json(&format!("/{}/{id}", kind.as_str()), &[]).await?; + async fn details(&self, kind: WorkKind, id: &str) -> Result { + let v = self.json(&format!("/{}/{id}", kind.tmdb()), &[]).await?; Ok(if v.is_null() { Fetched::Missing } else { - Fetched::Found(Box::new(Info::from_details(kind.as_str(), &v))) + Fetched::Found(Box::new(Info::from_details(kind, &v))) }) } } -const REJECTED: &str = "TMDB did not accept the API key"; - /// Checks a key with one request (`GET /3/authentication`, "validate key"). pub async fn check_key(key: &str) -> Result<()> { let resp = Client::new(key).get("/authentication").await?; match resp.status().as_u16() { 200 => Ok(()), - 401 | 403 => Err(Error::msg(REJECTED)), + 401 | 403 => Err(Error::TmdbRejected), code => Err(Error::Network(format!("TMDB answered {code}"))), } } @@ -330,16 +313,31 @@ pub fn status(conn: &Connection) -> Result { }) } -fn emit(app: &AppHandle, st: &AppState) { - if let Ok(s) = status(&st.db.read()) { +async fn emit(app: &AppHandle, st: &AppState) { + if let Ok(s) = read_blocking(st, status).await { let _ = app.emit(EVENT, s); } } +async fn has_key(st: &AppState) -> bool { + read_blocking(st, |conn| Ok(key(conn).is_some())) + .await + .unwrap_or(false) +} + +async fn save_map(st: &AppState, batch: &[(&'static str, String, String)]) -> Result<()> { + let batch = batch.to_vec(); + write_blocking(st, move |conn| store_map(conn, &batch)).await +} + +async fn save(st: &AppState, batch: Vec<(WorkKind, String, Option)>) -> Result<()> { + write_blocking(st, move |conn| store(conn, &batch)).await +} + // --------------------------------------------------------------------- job /// Titles to fetch: never fetched or older than `MAX_AGE`, newest first. -fn todo(conn: &Connection) -> Result> { +fn todo(conn: &Connection) -> Result> { let rows = conn .prepare( "SELECT CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END, substr(w.key, 6) @@ -356,7 +354,16 @@ fn todo(conn: &Connection) -> Result> { .filter(|(_, id)| { !id.is_empty() && id.len() < 12 && id.bytes().all(|b| b.is_ascii_digit()) && id != "0" }) - .map(|(k, id)| (if k == "movie" { Kind::Movie } else { Kind::Tv }, id)) + .map(|(k, id)| { + ( + if k == "movie" { + WorkKind::Movie + } else { + WorkKind::Series + }, + id, + ) + }) .collect()) } @@ -369,13 +376,13 @@ const CHANGES_MAX_DAYS: i64 = 14; /// Ids TMDB reported changed: fetch their details again (fetched_at = 0); /// only rows present are touched. -pub fn mark_changed(conn: &Connection, kind: Kind, ids: &[String]) -> Result { +pub fn mark_changed(conn: &Connection, kind: WorkKind, ids: &[String]) -> Result { let mut stmt = conn.prepare_cached("UPDATE tmdb SET fetched_at = 0 WHERE kind = ?1 AND id = ?2")?; let mut n = 0; for id in ids { if !id.is_empty() && id.len() < 12 && id.bytes().all(|b| b.is_ascii_digit()) { - n += stmt.execute(params![kind.as_str(), id])?; + n += stmt.execute(params![kind.tmdb(), id])?; } } Ok(n) @@ -409,7 +416,7 @@ fn store_changes_since(conn: &Connection, d: chrono::NaiveDate) -> Result<()> { async fn changes( client: &Client, pace: &std::sync::Arc>, - kind: Kind, + kind: WorkKind, since: chrono::NaiveDate, ) -> Result> { let window = chrono::Utc::now().date_naive() - chrono::Duration::days(CHANGES_MAX_DAYS); @@ -420,7 +427,7 @@ async fn changes( pace.lock().await.tick().await; let v = client .json( - &format!("/{}/changes", kind.as_str()), + &format!("/{}/changes", kind.tmdb()), &[("start_date", start.as_str()), ("page", &page.to_string())], ) .await?; @@ -449,7 +456,7 @@ async fn changes( /// One unidentified work: its own key, a title line and the year to ask /// TMDB's search with. struct Candidate { - kind: Kind, + kind: WorkKind, source_key: String, title: String, year: Option, @@ -482,9 +489,9 @@ fn search_todo(conn: &Connection) -> Result> { .filter(|(_, _, title, _)| !title.trim().is_empty()) .map(|(kind, source_key, title, year)| Candidate { kind: if kind == "movie" { - Kind::Movie + WorkKind::Movie } else { - Kind::Tv + WorkKind::Series }, source_key, title, @@ -497,7 +504,7 @@ fn search_todo(conn: &Connection) -> Result> { /// year identifies the entry; several such candidates settle none. async fn search_id( client: &Client, - kind: Kind, + kind: WorkKind, title: &str, year: Option, ) -> Result> { @@ -506,7 +513,7 @@ async fn search_id( if let Some(y) = year { year_param = y.to_string(); extra.push(( - if kind == Kind::Movie { + if kind == WorkKind::Movie { "primary_release_year" } else { "first_air_date_year" @@ -515,12 +522,12 @@ async fn search_id( )); } let v = client - .json(&format!("/search/{}", kind.as_str()), &extra) + .json(&format!("/search/{}", kind.tmdb()), &extra) .await?; if v.is_null() { return Ok(None); } - let tv = kind == Kind::Tv; + let tv = kind == WorkKind::Series; let asked = crate::works::norm_title(title); let mut found: Option = None; for r in v["results"].as_array().into_iter().flatten() { @@ -564,10 +571,7 @@ async fn identify( st: &AppState, progress: usize, ) -> Result { - let candidates = { - let conn = st.db.read(); - search_todo(&conn)? - }; + let candidates = read_blocking(st, search_todo).await?; if candidates.is_empty() { return Ok(0); } @@ -578,18 +582,18 @@ async fn identify( PROGRESS.lock().total += candidates.len() as i64; let mut found = 0; let mut failures = 0; - let mut batch: Vec<(&str, String, String)> = Vec::new(); + let mut batch: Vec<(&'static str, String, String)> = Vec::new(); for (i, c) in candidates.iter().enumerate() { pace.lock().await.tick().await; - if key(&st.db.read()).is_none() { + if !has_key(st).await { break; // the key was removed meanwhile (Settings) } PROGRESS.lock().done = (progress + i + 1) as i64; let id = match search_id(client, c.kind, &c.title, c.year).await { Ok(id) => id, - Err(e) if e.to_string() == REJECTED => { + Err(e @ Error::TmdbRejected) => { // keep the matches already found: they are real work - store_map(&mut st.db.write(), &batch)?; + save_map(st, &batch).await?; return Err(e); } Err(e) => { @@ -599,7 +603,7 @@ async fn identify( // is sequential so an outage would otherwise pace through the // whole catalog at one slow request per title if failures >= 25 && failures * 2 > found + batch.len() { - store_map(&mut st.db.write(), &batch)?; + save_map(st, &batch).await?; return Err(Error::msg(format!("TMDB search is not reachable ({e})"))); } continue; @@ -608,17 +612,17 @@ async fn identify( let got = id.unwrap_or_default(); if !got.is_empty() { found += 1; - log::debug!("tmdb: {} '{}' -> {got}", c.kind.as_str(), c.title); + log::debug!("tmdb: {} '{}' -> {got}", c.kind.tmdb(), c.title); } - batch.push((c.kind.as_str(), c.source_key.clone(), got)); + batch.push((c.kind.tmdb(), c.source_key.clone(), got)); if batch.len() >= 200 { - store_map(&mut st.db.write(), &batch)?; + save_map(st, &batch).await?; let done = (progress + i + 1) as i64; PROGRESS.lock().done = done; batch.clear(); } } - store_map(&mut st.db.write(), &batch)?; + save_map(st, &batch).await?; Ok(found) } @@ -635,7 +639,7 @@ fn store_map(conn: &mut Connection, rows: &[(&str, String, String)]) -> Result<( Ok(()) } -fn store(conn: &mut Connection, rows: &[(Kind, String, Option)]) -> Result<()> { +fn store(conn: &mut Connection, rows: &[(WorkKind, String, Option)]) -> Result<()> { let tx = conn.transaction()?; { let mut stmt = tx.prepare_cached( @@ -644,25 +648,35 @@ fn store(conn: &mut Connection, rows: &[(Kind, String, Option)]) -> Result let t = now(); for (kind, id, info) in rows { let json = info.as_ref().map(serde_json::to_string).transpose()?; - stmt.execute(params![kind.as_str(), id, json, t])?; + stmt.execute(params![kind.tmdb(), id, json, t])?; } } tx.commit()?; Ok(()) } -fn regroup(st: &AppState) -> Result<()> { - let mut conn = st.db.write(); - let tx = conn.transaction()?; - crate::works::rebuild(&tx)?; - tx.commit()?; - Ok(()) +async fn regroup(st: &AppState) -> Result<()> { + write_blocking(st, |conn| { + let tx = conn.transaction()?; + crate::works::rebuild(&tx)?; + tx.commit()?; + Ok(()) + }) + .await } /// Fetches missing TMDB details in the background (one run at a time; /// no-op without a key). pub fn spawn(app: AppHandle, st: AppState) { - if key(&st.db.read()).is_none() || RUNNING.swap(true, Ordering::SeqCst) { + tauri::async_runtime::spawn(async move { + if has_key(&st).await { + start(app, st); + } + }); +} + +fn start(app: AppHandle, st: AppState) { + if RUNNING.swap(true, Ordering::SeqCst) { return; } { @@ -686,15 +700,12 @@ pub fn spawn(app: AppHandle, st: AppState) { Ok(n) => log::info!("tmdb: {n} titles updated"), Err(e) => log::warn!("tmdb: {e}"), } - emit(&app, &st); + emit(&app, &st).await; }); } async fn run(app: &AppHandle, st: &AppState) -> Result { - let api_key = { - let conn = st.db.read(); - key(&conn) - }; + let api_key = read_blocking(st, |conn| Ok(key(conn))).await?; let Some(api_key) = api_key else { return Ok(0) }; let client = std::sync::Arc::new(Client::new(&api_key)); @@ -709,18 +720,21 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { // the todo() query — with an up-to-date catalog, this phase alone may // make work. The first run ever has no last date: nothing to mark. { - let since = changes_since(&st.db.read()); + let since = read_blocking(st, |conn| Ok(changes_since(conn))).await?; let mut covered = since.is_none(); // no prior date: nothing to cover if let Some(since) = since { let mut marked = 0; let mut fetched = true; - for kind in [Kind::Movie, Kind::Tv] { + for kind in [WorkKind::Movie, WorkKind::Series] { match changes(&client, &pace, kind, since).await { - Ok(ids) => marked += mark_changed(&st.db.write(), kind, &ids)?, + Ok(ids) => { + marked += + write_blocking(st, move |conn| mark_changed(conn, kind, &ids)).await? + } // TMDB down: keep going, the MAX_AGE fallback still works Err(e) => { fetched = false; - log::debug!("tmdb {}/changes: {e}", kind.as_str()); + log::debug!("tmdb {}/changes: {e}", kind.tmdb()); } } } @@ -730,30 +744,28 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { // Only advance the window when the changes phase actually covered // it — otherwise the failed span would never be marked for refetch. if covered { - store_changes_since(&st.db.write(), chrono::Utc::now().date_naive())?; + let today = chrono::Utc::now().date_naive(); + write_blocking(st, move |conn| store_changes_since(conn, today)).await?; } } - let todo = { - let conn = st.db.read(); - todo(&conn)? - }; + let todo = read_blocking(st, todo).await?; if todo.is_empty() { // still: titles without a TMDB id may be searchable let found = identify(&client, &pace, st, 0).await?; if found > 0 { - regroup(st)?; + regroup(st).await?; } return Ok(found); } log::info!("tmdb: fetching {} titles", todo.len()); PROGRESS.lock().total = todo.len() as i64; - emit(app, st); + emit(app, st).await; let mut results = futures_util::stream::iter(todo) .map({ let (client, pace) = (client.clone(), pace.clone()); - move |(kind, id): (Kind, String)| { + move |(kind, id): (WorkKind, String)| { let (client, pace) = (client.clone(), pace.clone()); async move { pace.lock().await.tick().await; @@ -764,17 +776,17 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { }) .buffer_unordered(CONCURRENCY); - let mut batch: Vec<(Kind, String, Option)> = Vec::new(); + let mut batch: Vec<(WorkKind, String, Option)> = Vec::new(); let (mut stored, mut since_regroup, mut failures) = (0usize, 0usize, 0usize); while let Some((kind, id, r)) = results.next().await { PROGRESS.lock().done += 1; match r { Ok(Fetched::Found(info)) => batch.push((kind, id, Some(*info))), Ok(Fetched::Missing) => batch.push((kind, id, None)), - Err(e) if e.to_string() == REJECTED => return Err(e), + Err(e @ Error::TmdbRejected) => return Err(e), Err(e) => { failures += 1; - log::debug!("tmdb {}/{id}: {e}", kind.as_str()); + log::debug!("tmdb {}/{id}: {e}", kind.tmdb()); // offline or TMDB down: stop, the next run continues if failures >= 25 && failures * 2 > stored + batch.len() { return Err(Error::msg(format!("TMDB is not reachable ({e})"))); @@ -784,28 +796,27 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { if batch.len() >= 100 { stored += batch.len(); since_regroup += batch.len(); - store(&mut st.db.write(), &batch)?; - batch.clear(); + save(st, std::mem::take(&mut batch)).await?; // the key was removed meanwhile (Settings) - if key(&st.db.read()).is_none() { - regroup(st)?; + if !has_key(st).await { + regroup(st).await?; return Ok(stored); } if since_regroup >= REGROUP_EVERY { since_regroup = 0; - regroup(st)?; + regroup(st).await?; } - emit(app, st); + emit(app, st).await; } } stored += batch.len(); - store(&mut st.db.write(), &batch)?; + save(st, batch).await?; // 2) unidentified titles: search TMDB, remember hits in tmdb_map, then // the regroup below folds them into the TMDB group (detail rows for // the newly mapped ids are this run's remaining `todo` of the next). let found = identify(&client, &pace, st, stored).await?; - regroup(st)?; + regroup(st).await?; Ok(stored + found) } @@ -813,7 +824,7 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { #[tauri::command] pub async fn tmdb_status(state: State<'_, AppState>) -> Result { - status(&state.db.read()) + read_blocking(state.inner(), status).await } /// Saves (after checking it with TMDB) or, with an empty key, removes the @@ -831,7 +842,7 @@ pub async fn tmdb_set_key( // the system keyring when there is one (it may ask to be unlocked: the // user just typed the key), else the database if key.is_empty() { - crate::secrets::forget_named(state.inner(), KEY_SETTING)?; + crate::secrets::forget_named(state.inner(), KEY_SETTING).await?; } else { crate::secrets::store_named( state.inner(), @@ -843,7 +854,7 @@ pub async fn tmdb_set_key( } PROGRESS.lock().error = None; spawn(app, state.inner().clone()); - status(&state.db.read()) + read_blocking(state.inner(), status).await } #[tauri::command] @@ -854,7 +865,7 @@ pub async fn tmdb_refresh( // the user asked: a keyring locked so far may prompt now crate::secrets::ensure_loaded(state.inner(), None, crate::secrets::Unlock::Prompt).await; spawn(app, state.inner().clone()); - status(&state.db.read()) + read_blocking(state.inner(), status).await } /// What the detail pages show from TMDB. @@ -874,7 +885,7 @@ pub struct Facts { /// TMDB facts of a work, when its details are stored and fit its title. pub fn facts_for( conn: &Connection, - kind: &str, + kind: WorkKind, key: &str, title: &str, year: Option, @@ -898,11 +909,11 @@ pub fn facts_for( } /// TMDB details stored for a work key ("tmdb:603"), if any. -pub fn info_for(conn: &Connection, kind: &str, key: &str) -> Result> { +pub fn info_for(conn: &Connection, kind: WorkKind, key: &str) -> Result> { let Some(id) = key.strip_prefix("tmdb:") else { return Ok(None); }; - let kind = crate::works::tmdb_kind(kind); + let kind = kind.tmdb(); Ok(conn .query_row( "SELECT json FROM tmdb WHERE kind = ?1 AND id = ?2", @@ -927,7 +938,7 @@ mod tests { "production_countries": [{"iso_3166_1": "US", "name": "United States of America"}], "poster_path": "/p.jpg", "backdrop_path": "/b.jpg" }); - let m = Info::from_details("movie", &movie); + let m = Info::from_details(WorkKind::Movie, &movie); assert_eq!( (m.year, m.collection.as_deref(), m.genres.len()), (Some(2022), Some("Top Gun Collection"), 2) @@ -938,7 +949,7 @@ mod tests { "genres": [{"name": "Crime"}, {"name": "Mystery"}], "first_air_date": "2021-09-29", "networks": [{"name": "Netflix"}], "origin_country": ["DK"], "vote_average": 0 }); - let t = Info::from_details("tv", &tv); + let t = Info::from_details(WorkKind::Series, &tv); assert_eq!( (t.title.as_str(), t.language.as_deref(), t.rating), ("Kastanjemanden", Some("da"), None) @@ -992,8 +1003,8 @@ mod tests { assert_eq!( todo(&c).unwrap(), vec![ - (Kind::Movie, "22".to_owned()), - (Kind::Movie, "11".to_owned()) + (WorkKind::Movie, "22".to_owned()), + (WorkKind::Movie, "11".to_owned()) ] ); c.execute( @@ -1001,7 +1012,7 @@ mod tests { [now()], ) .unwrap(); - assert_eq!(todo(&c).unwrap(), vec![(Kind::Movie, "11".to_owned())]); + assert_eq!(todo(&c).unwrap(), vec![(WorkKind::Movie, "11".to_owned())]); } /// GET /3/movie/changes body: `{results:[{id, adult}], total_pages}`. @@ -1038,9 +1049,14 @@ mod tests { ) .unwrap(); assert!(todo(&c).unwrap().is_empty()); - let n = mark_changed(&c, Kind::Movie, &["11".into(), "999".into(), "tt13".into()]).unwrap(); + let n = mark_changed( + &c, + WorkKind::Movie, + &["11".into(), "999".into(), "tt13".into()], + ) + .unwrap(); assert_eq!(n, 1); - assert_eq!(todo(&c).unwrap(), vec![(Kind::Movie, "11".to_owned())]); + assert_eq!(todo(&c).unwrap(), vec![(WorkKind::Movie, "11".to_owned())]); } /// tmdb_map rows upsert; the '' sentinel counts as "searched, no match". diff --git a/src-tauri/src/works/channels.rs b/src-tauri/src/works/channels.rs new file mode 100644 index 0000000..dc20bc6 --- /dev/null +++ b/src-tauri/src/works/channels.rs @@ -0,0 +1,214 @@ +//! Live channels: feeds folded into one group per channel and country. + +use super::*; + +/// Variant preference when nothing was chosen yet: full/regular HD streams +/// first, then RAW, 4K, HEVC-only and SD last. Higher is better. +pub fn channel_rank(badges: &str) -> i32 { + let has = |b: &str| badges.split_whitespace().any(|x| x == b); + let mut r = 0; + if has("FHD") { + r += 50; + } else if has("HD") { + r += 45; + } else if has("RAW") { + r += 40; + } else if has("4K") || has("8K") { + r += 30; + } else if !has("SD") { + r += 35; + } + if has("HEVC") { + r -= 10; + } + if has("SD") { + r -= 20; + } + r +} + +/// Grouping key of a channel within its country: "TV 2 SPORT 1" and +/// "TV2 SPORT 1" are the same channel, and so are its quality feeds +/// ("V Sport Ultra UHD"); East/West feeds and "Sky Sports+" vs "Sky +/// Sports" are not. +pub fn channel_key(country: Option<&str>, title: &str) -> String { + const QUALITY: &[&str] = &[ + "uhd", "fhd", "hd", "sd", "4k", "8k", "hevc", "h265", "raw", "50fps", "60fps", + ]; + let norm = norm_title(&title.replace('+', " plus ")); + let mut t = String::new(); + let mut prev = ""; + for w in norm.split_whitespace() { + // "*MULTI-AUDIO*" = "*MULTI*" + if !QUALITY.contains(&w) && !(w == "audio" && prev == "multi") { + t.push_str(w); + } + prev = w; + } + format!("{}|{}", country.unwrap_or("-"), t) +} + +/// Chip text for one variant of a channel: its own badges ("RAW HEVC"), +/// else its category's, plus the category's extras ("VIP", "Dolby Audio"). +pub fn channel_variant_label(channel_badges: &str, category_badges: &str) -> String { + const EXTRAS: &[&str] = &["VIP", "DOLBY AUDIO", "50FPS", "60FPS"]; + let own = crate::catalog::split_badges(channel_badges.to_owned()); + let cat = crate::catalog::split_badges(category_badges.to_owned()); + let mut parts: Vec = if own.is_empty() { + cat.iter() + .filter(|b| !EXTRAS.contains(&b.as_str())) + .cloned() + .collect() + } else { + own + }; + for b in cat.iter().filter(|b| EXTRAS.contains(&b.as_str())) { + if !parts.contains(b) { + parts.push(b.clone()); + } + } + let nice = |b: &str| match b { + "DOLBY AUDIO" => "Dolby Audio".to_owned(), + "50FPS" | "60FPS" => b.to_lowercase(), + _ => b.to_owned(), + }; + let label = parts + .iter() + .map(|b| nice(b)) + .collect::>() + .join(" · "); + if label.is_empty() { + "Standard".to_owned() + } else { + label + } +} + +pub(super) fn rebuild_channel_groups(conn: &Connection) -> Result { + struct Ch { + source_id: i64, + id: String, + title: String, + logo: Option, + epg_id: Option, + badges: String, + country: Option, + category_title: Option, + adult: bool, + order: i64, + } + let mut stmt = conn.prepare( + "SELECT c.source_id, c.id, c.title, c.logo, c.epg_id, c.badges, k.region, k.title, c.adult, + COALESCE(k.position, 0) * 100000 + c.position + FROM channel c + LEFT JOIN category k ON k.source_id = c.source_id AND k.kind = 'live' AND k.id = c.category_id + WHERE c.separator = 0 + ORDER BY c.source_id, 10", + )?; + let rows: Vec = stmt + .query_map([], |r| { + Ok(Ch { + source_id: r.get(0)?, + id: r.get(1)?, + title: r.get(2)?, + logo: r.get(3)?, + epg_id: r.get(4)?, + badges: r.get(5)?, + country: r.get(6)?, + category_title: r.get(7)?, + adult: r.get(8)?, + order: r.get(9)?, + }) + })? + .collect::>()?; + drop(stmt); + + let mut groups: HashMap> = HashMap::new(); + let mut order: Vec = Vec::new(); + for c in &rows { + let key = channel_key(c.country.as_deref(), &c.title); + let e = groups.entry(key.clone()).or_default(); + if e.is_empty() { + order.push(key); + } + e.push(c); + } + + // the variant that plays: the user's pick, else a favorited one, else the best + let prefs: HashMap = conn + .prepare("SELECT key, source_id, item_id FROM channel_pref")? + .query_map([], |r| Ok((r.get(0)?, (r.get(1)?, r.get(2)?))))? + .collect::>()?; + let favorites: HashMap<(i64, String), i64> = conn + .prepare("SELECT source_id, item_id, added_at FROM favorite WHERE kind = 'live'")? + .query_map([], |r| Ok(((r.get(0)?, r.get(1)?), r.get(2)?)))? + .collect::>()?; + + conn.execute("DELETE FROM channel_group", [])?; + conn.execute( + "UPDATE channel SET group_key = NULL WHERE separator = 1", + [], + )?; + let mut set_key = + conn.prepare("UPDATE channel SET group_key = ?3 WHERE source_id = ?1 AND id = ?2")?; + let mut insert = conn.prepare( + "INSERT INTO channel_group (key, title, country, genre, logo, epg_id, variants, adult, position, source_id, item_id) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + )?; + for (pos, key) in order.iter().enumerate() { + let cs = &groups[key]; + for c in cs { + set_key.execute(params![c.source_id, c.id, key])?; + } + let best = cs + .iter() + .max_by_key(|c| (channel_rank(&c.badges), c.epg_id.is_some() as i32, -c.order)) + .copied() + .expect("groups are never empty"); + let picked = prefs + .get(key) + .and_then(|(sid, id)| cs.iter().find(|c| c.source_id == *sid && c.id == *id)); + let favorite = cs + .iter() + .filter_map(|c| { + favorites + .get(&(c.source_id, c.id.clone())) + .map(|at| (*at, c)) + }) + .max_by_key(|(at, _)| *at) + .map(|(_, c)| c); + let chosen = picked.or(favorite).copied().unwrap_or(best); + let title = most_common(cs.iter().map(|c| (c.title.clone(), 1))) + .unwrap_or_else(|| best.title.clone()); + let category_genre = most_common( + cs.iter() + .filter_map(|c| { + c.category_title + .as_deref() + .and_then(genre::live_from_category) + }) + .map(|g| (g, 1)), + ); + let genre = category_genre.unwrap_or_else(|| genre::live_from_title(&title)); + let epg_id = most_common(cs.iter().filter_map(|c| c.epg_id.clone()).map(|e| (e, 1))); + let logo = chosen + .logo + .clone() + .or_else(|| best.logo.clone()) + .or_else(|| cs.iter().find_map(|c| c.logo.clone())); + insert.execute(params![ + key, + title, + chosen.country, + genre, + logo, + epg_id, + cs.len() as i64, + cs.iter().any(|c| c.adult), + pos as i64, + chosen.source_id, + chosen.id + ])?; + } + Ok(order.len()) +} diff --git a/src-tauri/src/works/grouping.rs b/src-tauri/src/works/grouping.rs new file mode 100644 index 0000000..1167d19 --- /dev/null +++ b/src-tauri/src/works/grouping.rs @@ -0,0 +1,385 @@ +//! Movies and series: copies folded into works, with their browse facets. + +use super::*; + +/// One catalog row as far as grouping cares. +struct Member { + source_id: i64, + id: String, + title: String, + year: Option, + tmdb: Option, + category: Option, + category_id: Option, + poster: Option, + backdrop: Option, + rating: Option, + genre_text: Option, + added: Option, + adult: bool, + variant: Variant, +} + +impl Member { + /// English and streaming-service copies carry the international title and + /// artwork; local-market copies sometimes a translated title. + fn weight(&self) -> i64 { + let v = &self.variant; + if v.origin == variant::Origin::Cam { + 0 + } else if v.language == Some("English") || (v.service.is_some() && v.language.is_none()) { + 3 + } else { + 1 + } + } +} + +/// Group keys: TMDB id; an entry without one joins the TMDB group with the +/// same normalized title + year when that is unambiguous, otherwise groups by +/// title + year; without a year it stays on its own. +fn assign_keys(members: &[Member]) -> Vec { + let mut by_title_year: HashMap<(String, i64), BTreeSet> = HashMap::new(); + for m in members { + if let (Some(t), Some(y)) = (valid_tmdb(m.tmdb.as_deref()), m.year) { + by_title_year + .entry((norm_title(&m.title), y)) + .or_default() + .insert(format!("tmdb:{t}")); + } + } + members + .iter() + .map(|m| { + if let Some(t) = valid_tmdb(m.tmdb.as_deref()) { + return format!("tmdb:{t}"); + } + let norm = norm_title(&m.title); + match m.year { + Some(y) => match by_title_year.get(&(norm.clone(), y)) { + Some(keys) if keys.len() == 1 => keys.iter().next().expect("len is 1").clone(), + _ => format!("title:{norm}|{y}"), + }, + None => format!("item:{}:{}", m.source_id, m.id), + } + }) + .collect() +} + +fn load_members(conn: &Connection, kind: WorkKind) -> Result> { + let table = kind.table(); + let (art, backdrop, genre, added) = match kind { + WorkKind::Movie => ("x.poster", "NULL", "NULL", "x.added"), + WorkKind::Series => ("x.cover", "x.backdrop", "x.genre", "x.last_modified"), + }; + let sql = format!( + "SELECT x.source_id, x.id, x.title, x.year, x.tmdb, x.tag, k.name, x.category_id, {art}, {backdrop}, + x.rating, {genre}, {added}, x.adult + FROM {table} x + LEFT JOIN category k ON k.source_id = x.source_id AND k.kind = ?1 AND k.id = x.category_id" + ); + let mut stmt = conn.prepare(&sql)?; + let rows = stmt + .query_map([kind], |r| { + let tag: Option = r.get(5)?; + let category: Option = r.get(6)?; + Ok(Member { + source_id: r.get(0)?, + id: r.get(1)?, + title: r.get(2)?, + year: r.get(3)?, + tmdb: r.get(4)?, + variant: variant::parse(tag.as_deref(), category.as_deref()), + category, + category_id: r.get(7)?, + poster: r.get(8)?, + backdrop: r.get(9)?, + rating: r.get(10)?, + genre_text: r.get(11)?, + added: r.get(12)?, + adult: r.get(13)?, + }) + })? + .collect::, _>>()?; + Ok(rows) +} + +/// TMDB details stored for the kind's titles (`tmdb.rs`), by TMDB id. +fn load_tmdb(conn: &Connection, kind: WorkKind) -> Result> { + let kind = kind.tmdb(); + let rows: Vec<(String, String)> = conn + .prepare("SELECT id, json FROM tmdb WHERE kind = ?1 AND json IS NOT NULL")? + .query_map([kind], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect::>()?; + Ok(rows + .into_iter() + .filter_map(|(id, j)| serde_json::from_str(&j).ok().map(|i| (id, i))) + .collect()) +} + +/// Is TMDB's title the one the provider means? Providers sometimes attach +/// another title's id (a show's id to a movie): the title or the year must fit. +pub fn tmdb_fits(info: &crate::tmdb::Info, titles: &[&str], year: Option) -> bool { + let names: Vec = [Some(info.title.as_str()), info.original_title.as_deref()] + .into_iter() + .flatten() + .map(norm_title) + .collect(); + let title_fits = titles.iter().map(|t| norm_title(t)).any(|t| { + names.iter().any(|n| { + *n == t + || (t.len() >= 6 + && n.len() >= 6 + && (n.contains(t.as_str()) || t.contains(n.as_str()))) + }) + }); + let year_fits = matches!((year, info.year), (Some(a), Some(b)) if (a - b).abs() <= 1); + title_fits || year_fits +} + +/// Recomputes `work` / `work_facet` and the members' `work_key` for one kind. +pub(super) fn rebuild_works(conn: &Connection, kind: WorkKind) -> Result { + let members = load_members(conn, kind)?; + let mut keys = assign_keys(&members); + let table = kind.table(); + let tmdb = load_tmdb(conn, kind)?; + // titles identified by search (tmdb.rs) join the TMDB group the search + // found — but only when TMDB's stored data actually fits the members, or + // a wrong match would infect the whole group assign_keys merged, and a + // NULL-json row ("not on TMDB") would hide the provider metadata; tmdb is + // pre-filtered to json IS NOT NULL, so a miss means: don't remap + let search = kind.tmdb(); + let mapped = load_tmdb_map(conn)?; + let remap: HashMap = { + let mut by_key: HashMap<&str, Vec<&Member>> = HashMap::new(); + for (m, k) in members.iter().zip(&keys) { + by_key.entry(k.as_str()).or_default().push(m); + } + let mut remap = HashMap::new(); + for (k, ms) in by_key { + if !(k.starts_with("title:") || k.starts_with("item:")) { + continue; + } + let fits = mapped + .get(&(search.to_owned(), k.to_owned())) + .and_then(|id| tmdb.get(id)) + .is_some_and(|info| { + let titles: Vec<&str> = ms.iter().map(|m| m.title.as_str()).collect(); + let year = most_common(ms.iter().filter_map(|m| m.year.map(|y| (y, 1)))); + tmdb_fits(info, &titles, year) + }); + if fits { + let id = mapped[&(search.to_owned(), k.to_owned())].clone(); + remap.insert(k.to_owned(), format!("tmdb:{id}")); + } + } + remap + }; + for k in &mut keys { + if let Some(new) = remap.get(k) { + *k = new.clone(); + } + } + + let mut groups: HashMap<&str, Vec<&Member>> = HashMap::new(); + let mut order: Vec<&str> = Vec::new(); + for (m, k) in members.iter().zip(&keys) { + let e = groups.entry(k.as_str()).or_default(); + if e.is_empty() { + order.push(k.as_str()); + } + e.push(m); + } + + conn.execute("DELETE FROM work WHERE kind = ?1", [kind])?; + conn.execute("DELETE FROM work_facet WHERE kind = ?1", [kind])?; + { + let mut set_key = conn.prepare(&format!( + "UPDATE {table} SET work_key = ?3 WHERE source_id = ?1 AND id = ?2" + ))?; + for (m, k) in members.iter().zip(&keys) { + set_key.execute(params![m.source_id, m.id, k])?; + } + } + let mut insert_work = conn.prepare( + "INSERT INTO work (kind, key, title, year, poster, backdrop, rating, genre, added, versions, badges, services, + adult, source_id, item_id) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", + )?; + let mut insert_facet = conn.prepare( + "INSERT OR IGNORE INTO work_facet (kind, facet, value, key) VALUES (?1, ?2, ?3, ?4)", + )?; + + for key in &order { + let ms = &groups[key]; + // metadata from the best-weighted copy (ties: the one with artwork, newest) + let rep = ms + .iter() + .max_by_key(|m| (m.weight(), m.poster.is_some() as i64, m.added.unwrap_or(0))) + .copied() + .expect("groups are never empty"); + let title = most_common(ms.iter().map(|m| (m.title.clone(), m.weight().max(1)))) + .unwrap_or_else(|| rep.title.clone()); + let year = most_common(ms.iter().filter_map(|m| m.year.map(|y| (y, 1)))); + let by_weight = |f: &dyn Fn(&Member) -> Option| -> Option { + let mut best: Option<(i64, String)> = None; + for m in ms { + if let Some(v) = f(m).filter(|v| !v.is_empty()) + && best.as_ref().is_none_or(|(w, _)| m.weight() > *w) + { + best = Some((m.weight(), v)); + } + } + best.map(|(_, v)| v) + }; + let mut poster = by_weight(&|m| m.poster.clone()); + let mut backdrop = by_weight(&|m| m.backdrop.clone()); + let mut rating = ms + .iter() + .filter_map(|m| m.rating) + .fold(None, |a: Option, r| Some(a.map_or(r, |a| a.max(r)))); + let mut year = year; + let info = key + .strip_prefix("tmdb:") + .and_then(|id| tmdb.get(id)) + .filter(|i| { + let titles: Vec<&str> = ms.iter().map(|m| m.title.as_str()).collect(); + tmdb_fits(i, &titles, year) + }); + if let Some(i) = info { + // the provider's own data wins; TMDB fills the gaps + year = year.or(i.year); + if rating.is_none_or(|r| r <= 0.0) && i.votes >= 20 { + rating = i.rating; + } + poster = poster.or_else(|| { + i.poster + .as_ref() + .map(|p| format!("{}/w500{p}", crate::tmdb::IMAGES)) + }); + backdrop = backdrop.or_else(|| { + i.backdrop + .as_ref() + .map(|p| format!("{}/w1280{p}", crate::tmdb::IMAGES)) + }); + } + + let mut genres: Vec<&'static str> = Vec::new(); + let mut services: Vec<&'static str> = Vec::new(); + let mut languages: Vec<&'static str> = Vec::new(); + let mut quality: Vec<&'static str> = Vec::new(); + for m in ms { + for g in m + .genre_text + .as_deref() + .map(genre::from_text) + .unwrap_or_default() + { + if !genres.contains(&g) { + genres.push(g); + } + } + for g in m + .category + .as_deref() + .map(genre::from_category) + .unwrap_or_default() + { + if !genres.contains(&g) { + genres.push(g); + } + } + if let Some(s) = m.variant.service + && !services.contains(&s) + { + services.push(s); + } + for l in [m.variant.language, m.variant.subtitles] + .into_iter() + .flatten() + { + if !languages.contains(&l) { + languages.push(l); + } + } + for q in &m.variant.quality { + if !quality.contains(q) { + quality.push(q); + } + } + if m.variant.origin == variant::Origin::Bluray && !quality.contains(&"Blu-ray") { + quality.push("Blu-ray"); + } + } + if let Some(i) = info { + for g in genre::from_text(&i.genres.join(", ")) { + if !genres.contains(&g) { + genres.push(g); + } + } + } + genres.sort_by_key(|g| { + genre::GENRES + .iter() + .position(|x| x == g) + .unwrap_or(usize::MAX) + }); + let added = ms.iter().filter_map(|m| m.added).max(); + let adult = ms.iter().any(|m| m.adult); + + insert_work.execute(params![ + kind, + key, + title, + year, + poster, + backdrop, + rating, + (!genres.is_empty()).then(|| genres.join(", ")), + added, + ms.len() as i64, + quality.join("|"), + services.join("|"), + adult, + rep.source_id, + rep.id + ])?; + let mut facet = |facet: &str, value: &str| { + insert_facet + .execute(params![kind, facet, value, key]) + .map(|_| ()) + }; + for g in &genres { + facet("genre", g)?; + } + for s in &services { + facet("service", s)?; + } + for l in &languages { + facet("language", l)?; + } + for q in &quality { + facet("quality", q)?; + } + if let Some(d) = genre::decade(year) { + facet("decade", &d)?; + } + for m in ms { + if let Some(c) = &m.category_id { + facet("collection", &format!("{}:{c}", m.source_id))?; + } + } + if let Some(i) = info { + if let Some(l) = i.language.as_deref().and_then(lang::name) { + facet("original", l)?; + } + if let Some(c) = &i.collection { + facet("franchise", c)?; + } + for n in &i.networks { + facet("network", n)?; + } + } + } + Ok(order.len()) +} diff --git a/src-tauri/src/works/mod.rs b/src-tauri/src/works/mod.rs index 2f9f084..39493c6 100644 --- a/src-tauri/src/works/mod.rs +++ b/src-tauri/src/works/mod.rs @@ -17,16 +17,26 @@ //! transaction, after a source is removed, and at startup whenever //! `RULES_VERSION` changes. +mod channels; pub mod genre; +mod grouping; pub mod lang; pub mod variant; pub mod versions; +#[cfg(test)] +use channels::channel_key; +use channels::rebuild_channel_groups; +pub use channels::{channel_rank, channel_variant_label}; +use grouping::rebuild_works; +pub use grouping::tmdb_fits; + use std::collections::{BTreeSet, HashMap}; use rusqlite::{Connection, params}; use crate::error::Result; +use crate::kind::WorkKind; use variant::Variant; /// Bump whenever grouping/facet rules change: startup then rebuilds. @@ -121,70 +131,6 @@ pub fn tmdb_id_of(conn: &Connection, key: &str) -> Result> { .filter(|id| !id.is_empty())) } -/// One catalog row as far as grouping cares. -struct Member { - source_id: i64, - id: String, - title: String, - year: Option, - tmdb: Option, - category: Option, - category_id: Option, - poster: Option, - backdrop: Option, - rating: Option, - genre_text: Option, - added: Option, - adult: bool, - variant: Variant, -} - -impl Member { - /// English and streaming-service copies carry the international title and - /// artwork; local-market copies sometimes a translated title. - fn weight(&self) -> i64 { - let v = &self.variant; - if v.origin == variant::Origin::Cam { - 0 - } else if v.language == Some("English") || (v.service.is_some() && v.language.is_none()) { - 3 - } else { - 1 - } - } -} - -/// Group keys: TMDB id; an entry without one joins the TMDB group with the -/// same normalized title + year when that is unambiguous, otherwise groups by -/// title + year; without a year it stays on its own. -fn assign_keys(members: &[Member]) -> Vec { - let mut by_title_year: HashMap<(String, i64), BTreeSet> = HashMap::new(); - for m in members { - if let (Some(t), Some(y)) = (valid_tmdb(m.tmdb.as_deref()), m.year) { - by_title_year - .entry((norm_title(&m.title), y)) - .or_default() - .insert(format!("tmdb:{t}")); - } - } - members - .iter() - .map(|m| { - if let Some(t) = valid_tmdb(m.tmdb.as_deref()) { - return format!("tmdb:{t}"); - } - let norm = norm_title(&m.title); - match m.year { - Some(y) => match by_title_year.get(&(norm.clone(), y)) { - Some(keys) if keys.len() == 1 => keys.iter().next().unwrap().clone(), - _ => format!("title:{norm}|{y}"), - }, - None => format!("item:{}:{}", m.source_id, m.id), - } - }) - .collect() -} - fn most_common( items: impl Iterator, ) -> Option { @@ -199,553 +145,12 @@ fn most_common( .map(|(k, _)| k) } -fn load_members(conn: &Connection, kind: &str) -> Result> { - let (table, art, backdrop, genre, added) = match kind { - "movie" => ("movie", "x.poster", "NULL", "NULL", "x.added"), - _ => ( - "series", - "x.cover", - "x.backdrop", - "x.genre", - "x.last_modified", - ), - }; - let sql = format!( - "SELECT x.source_id, x.id, x.title, x.year, x.tmdb, x.tag, k.name, x.category_id, {art}, {backdrop}, - x.rating, {genre}, {added}, x.adult - FROM {table} x - LEFT JOIN category k ON k.source_id = x.source_id AND k.kind = ?1 AND k.id = x.category_id" - ); - let mut stmt = conn.prepare(&sql)?; - let rows = stmt - .query_map([kind], |r| { - let tag: Option = r.get(5)?; - let category: Option = r.get(6)?; - Ok(Member { - source_id: r.get(0)?, - id: r.get(1)?, - title: r.get(2)?, - year: r.get(3)?, - tmdb: r.get(4)?, - variant: variant::parse(tag.as_deref(), category.as_deref()), - category, - category_id: r.get(7)?, - poster: r.get(8)?, - backdrop: r.get(9)?, - rating: r.get(10)?, - genre_text: r.get(11)?, - added: r.get(12)?, - adult: r.get(13)?, - }) - })? - .collect::, _>>()?; - Ok(rows) -} - -/// The tmdb table's spelling of a work kind: our "series" are TMDB's "tv". -pub fn tmdb_kind(kind: &str) -> &str { - if kind == "movie" { "movie" } else { "tv" } -} - -/// Recomputes `work` / `work_facet` and the members' `work_key` for one kind. -/// TMDB details stored for the kind's titles (`tmdb.rs`), by TMDB id. -fn load_tmdb(conn: &Connection, kind: &str) -> Result> { - let kind = tmdb_kind(kind); - let rows: Vec<(String, String)> = conn - .prepare("SELECT id, json FROM tmdb WHERE kind = ?1 AND json IS NOT NULL")? - .query_map([kind], |r| Ok((r.get(0)?, r.get(1)?)))? - .collect::>()?; - Ok(rows - .into_iter() - .filter_map(|(id, j)| serde_json::from_str(&j).ok().map(|i| (id, i))) - .collect()) -} - -/// Is TMDB's title the one the provider means? Providers sometimes attach -/// another title's id (a show's id to a movie): the title or the year must fit. -pub fn tmdb_fits(info: &crate::tmdb::Info, titles: &[&str], year: Option) -> bool { - let names: Vec = [Some(info.title.as_str()), info.original_title.as_deref()] - .into_iter() - .flatten() - .map(norm_title) - .collect(); - let title_fits = titles.iter().map(|t| norm_title(t)).any(|t| { - names.iter().any(|n| { - *n == t - || (t.len() >= 6 - && n.len() >= 6 - && (n.contains(t.as_str()) || t.contains(n.as_str()))) - }) - }); - let year_fits = matches!((year, info.year), (Some(a), Some(b)) if (a - b).abs() <= 1); - title_fits || year_fits -} - -fn rebuild_works(conn: &Connection, kind: &str) -> Result { - let members = load_members(conn, kind)?; - let mut keys = assign_keys(&members); - let table = if kind == "movie" { "movie" } else { "series" }; - let tmdb = load_tmdb(conn, kind)?; - // titles identified by search (tmdb.rs) join the TMDB group the search - // found — but only when TMDB's stored data actually fits the members, or - // a wrong match would infect the whole group assign_keys merged, and a - // NULL-json row ("not on TMDB") would hide the provider metadata; tmdb is - // pre-filtered to json IS NOT NULL, so a miss means: don't remap - let search = tmdb_kind(kind); - let mapped = load_tmdb_map(conn)?; - let remap: HashMap = { - let mut by_key: HashMap<&str, Vec<&Member>> = HashMap::new(); - for (m, k) in members.iter().zip(&keys) { - by_key.entry(k.as_str()).or_default().push(m); - } - let mut remap = HashMap::new(); - for (k, ms) in by_key { - if !(k.starts_with("title:") || k.starts_with("item:")) { - continue; - } - let fits = mapped - .get(&(search.to_owned(), k.to_owned())) - .and_then(|id| tmdb.get(id)) - .is_some_and(|info| { - let titles: Vec<&str> = ms.iter().map(|m| m.title.as_str()).collect(); - let year = most_common(ms.iter().filter_map(|m| m.year.map(|y| (y, 1)))); - tmdb_fits(info, &titles, year) - }); - if fits { - let id = mapped[&(search.to_owned(), k.to_owned())].clone(); - remap.insert(k.to_owned(), format!("tmdb:{id}")); - } - } - remap - }; - for k in &mut keys { - if let Some(new) = remap.get(k) { - *k = new.clone(); - } - } - - let mut groups: HashMap<&str, Vec<&Member>> = HashMap::new(); - let mut order: Vec<&str> = Vec::new(); - for (m, k) in members.iter().zip(&keys) { - let e = groups.entry(k.as_str()).or_default(); - if e.is_empty() { - order.push(k.as_str()); - } - e.push(m); - } - - conn.execute("DELETE FROM work WHERE kind = ?1", [kind])?; - conn.execute("DELETE FROM work_facet WHERE kind = ?1", [kind])?; - { - let mut set_key = conn.prepare(&format!( - "UPDATE {table} SET work_key = ?3 WHERE source_id = ?1 AND id = ?2" - ))?; - for (m, k) in members.iter().zip(&keys) { - set_key.execute(params![m.source_id, m.id, k])?; - } - } - let mut insert_work = conn.prepare( - "INSERT INTO work (kind, key, title, year, poster, backdrop, rating, genre, added, versions, badges, services, - adult, source_id, item_id) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)", - )?; - let mut insert_facet = conn.prepare( - "INSERT OR IGNORE INTO work_facet (kind, facet, value, key) VALUES (?1, ?2, ?3, ?4)", - )?; - - for key in &order { - let ms = &groups[key]; - // metadata from the best-weighted copy (ties: the one with artwork, newest) - let rep = ms - .iter() - .max_by_key(|m| (m.weight(), m.poster.is_some() as i64, m.added.unwrap_or(0))) - .copied() - .unwrap(); - let title = most_common(ms.iter().map(|m| (m.title.clone(), m.weight().max(1)))) - .unwrap_or_else(|| rep.title.clone()); - let year = most_common(ms.iter().filter_map(|m| m.year.map(|y| (y, 1)))); - let by_weight = |f: &dyn Fn(&Member) -> Option| -> Option { - let mut best: Option<(i64, String)> = None; - for m in ms { - if let Some(v) = f(m).filter(|v| !v.is_empty()) - && best.as_ref().is_none_or(|(w, _)| m.weight() > *w) - { - best = Some((m.weight(), v)); - } - } - best.map(|(_, v)| v) - }; - let mut poster = by_weight(&|m| m.poster.clone()); - let mut backdrop = by_weight(&|m| m.backdrop.clone()); - let mut rating = ms - .iter() - .filter_map(|m| m.rating) - .fold(None, |a: Option, r| Some(a.map_or(r, |a| a.max(r)))); - let mut year = year; - let info = key - .strip_prefix("tmdb:") - .and_then(|id| tmdb.get(id)) - .filter(|i| { - let titles: Vec<&str> = ms.iter().map(|m| m.title.as_str()).collect(); - tmdb_fits(i, &titles, year) - }); - if let Some(i) = info { - // the provider's own data wins; TMDB fills the gaps - year = year.or(i.year); - if rating.is_none_or(|r| r <= 0.0) && i.votes >= 20 { - rating = i.rating; - } - poster = poster.or_else(|| { - i.poster - .as_ref() - .map(|p| format!("{}/w500{p}", crate::tmdb::IMAGES)) - }); - backdrop = backdrop.or_else(|| { - i.backdrop - .as_ref() - .map(|p| format!("{}/w1280{p}", crate::tmdb::IMAGES)) - }); - } - - let mut genres: Vec<&'static str> = Vec::new(); - let mut services: Vec<&'static str> = Vec::new(); - let mut languages: Vec<&'static str> = Vec::new(); - let mut quality: Vec<&'static str> = Vec::new(); - for m in ms { - for g in m - .genre_text - .as_deref() - .map(genre::from_text) - .unwrap_or_default() - { - if !genres.contains(&g) { - genres.push(g); - } - } - for g in m - .category - .as_deref() - .map(genre::from_category) - .unwrap_or_default() - { - if !genres.contains(&g) { - genres.push(g); - } - } - if let Some(s) = m.variant.service - && !services.contains(&s) - { - services.push(s); - } - for l in [m.variant.language, m.variant.subtitles] - .into_iter() - .flatten() - { - if !languages.contains(&l) { - languages.push(l); - } - } - for q in &m.variant.quality { - if !quality.contains(q) { - quality.push(q); - } - } - if m.variant.origin == variant::Origin::Bluray && !quality.contains(&"Blu-ray") { - quality.push("Blu-ray"); - } - } - if let Some(i) = info { - for g in genre::from_text(&i.genres.join(", ")) { - if !genres.contains(&g) { - genres.push(g); - } - } - } - genres.sort_by_key(|g| { - genre::GENRES - .iter() - .position(|x| x == g) - .unwrap_or(usize::MAX) - }); - let added = ms.iter().filter_map(|m| m.added).max(); - let adult = ms.iter().any(|m| m.adult); - - insert_work.execute(params![ - kind, - key, - title, - year, - poster, - backdrop, - rating, - (!genres.is_empty()).then(|| genres.join(", ")), - added, - ms.len() as i64, - quality.join("|"), - services.join("|"), - adult, - rep.source_id, - rep.id - ])?; - let mut facet = |facet: &str, value: &str| { - insert_facet - .execute(params![kind, facet, value, key]) - .map(|_| ()) - }; - for g in &genres { - facet("genre", g)?; - } - for s in &services { - facet("service", s)?; - } - for l in &languages { - facet("language", l)?; - } - for q in &quality { - facet("quality", q)?; - } - if let Some(d) = genre::decade(year) { - facet("decade", &d)?; - } - for m in ms { - if let Some(c) = &m.category_id { - facet("collection", &format!("{}:{c}", m.source_id))?; - } - } - if let Some(i) = info { - if let Some(l) = i.language.as_deref().and_then(lang::name) { - facet("original", l)?; - } - if let Some(c) = &i.collection { - facet("franchise", c)?; - } - for n in &i.networks { - facet("network", n)?; - } - } - } - Ok(order.len()) -} - -// ----------------------------------------------------------- live channels - -/// Variant preference when nothing was chosen yet: full/regular HD streams -/// first, then RAW, 4K, HEVC-only and SD last. Higher is better. -pub fn channel_rank(badges: &str) -> i32 { - let has = |b: &str| badges.split_whitespace().any(|x| x == b); - let mut r = 0; - if has("FHD") { - r += 50; - } else if has("HD") { - r += 45; - } else if has("RAW") { - r += 40; - } else if has("4K") || has("8K") { - r += 30; - } else if !has("SD") { - r += 35; - } - if has("HEVC") { - r -= 10; - } - if has("SD") { - r -= 20; - } - r -} - -/// Grouping key of a channel within its country: "TV 2 SPORT 1" and -/// "TV2 SPORT 1" are the same channel, and so are its quality feeds -/// ("V Sport Ultra UHD"); East/West feeds and "Sky Sports+" vs "Sky -/// Sports" are not. -pub fn channel_key(country: Option<&str>, title: &str) -> String { - const QUALITY: &[&str] = &[ - "uhd", "fhd", "hd", "sd", "4k", "8k", "hevc", "h265", "raw", "50fps", "60fps", - ]; - let norm = norm_title(&title.replace('+', " plus ")); - let mut t = String::new(); - let mut prev = ""; - for w in norm.split_whitespace() { - // "*MULTI-AUDIO*" = "*MULTI*" - if !QUALITY.contains(&w) && !(w == "audio" && prev == "multi") { - t.push_str(w); - } - prev = w; - } - format!("{}|{}", country.unwrap_or("-"), t) -} - -/// Chip text for one variant of a channel: its own badges ("RAW HEVC"), -/// else its category's, plus the category's extras ("VIP", "Dolby Audio"). -pub fn channel_variant_label(channel_badges: &str, category_badges: &str) -> String { - const EXTRAS: &[&str] = &["VIP", "DOLBY AUDIO", "50FPS", "60FPS"]; - let own = crate::catalog::split_badges(channel_badges.to_owned()); - let cat = crate::catalog::split_badges(category_badges.to_owned()); - let mut parts: Vec = if own.is_empty() { - cat.iter() - .filter(|b| !EXTRAS.contains(&b.as_str())) - .cloned() - .collect() - } else { - own - }; - for b in cat.iter().filter(|b| EXTRAS.contains(&b.as_str())) { - if !parts.contains(b) { - parts.push(b.clone()); - } - } - let nice = |b: &str| match b { - "DOLBY AUDIO" => "Dolby Audio".to_owned(), - "50FPS" | "60FPS" => b.to_lowercase(), - _ => b.to_owned(), - }; - let label = parts - .iter() - .map(|b| nice(b)) - .collect::>() - .join(" · "); - if label.is_empty() { - "Standard".to_owned() - } else { - label - } -} - -fn rebuild_channel_groups(conn: &Connection) -> Result { - struct Ch { - source_id: i64, - id: String, - title: String, - logo: Option, - epg_id: Option, - badges: String, - country: Option, - category_title: Option, - adult: bool, - order: i64, - } - let mut stmt = conn.prepare( - "SELECT c.source_id, c.id, c.title, c.logo, c.epg_id, c.badges, k.region, k.title, c.adult, - COALESCE(k.position, 0) * 100000 + c.position - FROM channel c - LEFT JOIN category k ON k.source_id = c.source_id AND k.kind = 'live' AND k.id = c.category_id - WHERE c.separator = 0 - ORDER BY c.source_id, 10", - )?; - let rows: Vec = stmt - .query_map([], |r| { - Ok(Ch { - source_id: r.get(0)?, - id: r.get(1)?, - title: r.get(2)?, - logo: r.get(3)?, - epg_id: r.get(4)?, - badges: r.get(5)?, - country: r.get(6)?, - category_title: r.get(7)?, - adult: r.get(8)?, - order: r.get(9)?, - }) - })? - .collect::>()?; - drop(stmt); - - let mut groups: HashMap> = HashMap::new(); - let mut order: Vec = Vec::new(); - for c in &rows { - let key = channel_key(c.country.as_deref(), &c.title); - let e = groups.entry(key.clone()).or_default(); - if e.is_empty() { - order.push(key); - } - e.push(c); - } - - // the variant that plays: the user's pick, else a favorited one, else the best - let prefs: HashMap = conn - .prepare("SELECT key, source_id, item_id FROM channel_pref")? - .query_map([], |r| Ok((r.get(0)?, (r.get(1)?, r.get(2)?))))? - .collect::>()?; - let favorites: HashMap<(i64, String), i64> = conn - .prepare("SELECT source_id, item_id, added_at FROM favorite WHERE kind = 'live'")? - .query_map([], |r| Ok(((r.get(0)?, r.get(1)?), r.get(2)?)))? - .collect::>()?; - - conn.execute("DELETE FROM channel_group", [])?; - conn.execute( - "UPDATE channel SET group_key = NULL WHERE separator = 1", - [], - )?; - let mut set_key = - conn.prepare("UPDATE channel SET group_key = ?3 WHERE source_id = ?1 AND id = ?2")?; - let mut insert = conn.prepare( - "INSERT INTO channel_group (key, title, country, genre, logo, epg_id, variants, adult, position, source_id, item_id) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", - )?; - for (pos, key) in order.iter().enumerate() { - let cs = &groups[key]; - for c in cs { - set_key.execute(params![c.source_id, c.id, key])?; - } - let best = cs - .iter() - .max_by_key(|c| (channel_rank(&c.badges), c.epg_id.is_some() as i32, -c.order)) - .copied() - .unwrap(); - let picked = prefs - .get(key) - .and_then(|(sid, id)| cs.iter().find(|c| c.source_id == *sid && c.id == *id)); - let favorite = cs - .iter() - .filter_map(|c| { - favorites - .get(&(c.source_id, c.id.clone())) - .map(|at| (*at, c)) - }) - .max_by_key(|(at, _)| *at) - .map(|(_, c)| c); - let chosen = picked.or(favorite).copied().unwrap_or(best); - let title = most_common(cs.iter().map(|c| (c.title.clone(), 1))) - .unwrap_or_else(|| best.title.clone()); - let category_genre = most_common( - cs.iter() - .filter_map(|c| { - c.category_title - .as_deref() - .and_then(genre::live_from_category) - }) - .map(|g| (g, 1)), - ); - let genre = category_genre.unwrap_or_else(|| genre::live_from_title(&title)); - let epg_id = most_common(cs.iter().filter_map(|c| c.epg_id.clone()).map(|e| (e, 1))); - let logo = chosen - .logo - .clone() - .or_else(|| best.logo.clone()) - .or_else(|| cs.iter().find_map(|c| c.logo.clone())); - insert.execute(params![ - key, - title, - chosen.country, - genre, - logo, - epg_id, - cs.len() as i64, - cs.iter().any(|c| c.adult), - pos as i64, - chosen.source_id, - chosen.id - ])?; - } - Ok(order.len()) -} - /// Recomputes all derived grouping data. Call inside the writer's /// transaction after the catalog changed. pub fn rebuild(conn: &Connection) -> Result<()> { let t = std::time::Instant::now(); - let movies = rebuild_works(conn, "movie")?; - let series = rebuild_works(conn, "series")?; + let movies = rebuild_works(conn, WorkKind::Movie)?; + let series = rebuild_works(conn, WorkKind::Series)?; let channels = rebuild_channel_groups(conn)?; conn.execute( "INSERT INTO setting (key, value) VALUES ('works.rules', ?1) diff --git a/src-tauri/src/works/versions.rs b/src-tauri/src/works/versions.rs index a25bc28..d3d670b 100644 --- a/src-tauri/src/works/versions.rs +++ b/src-tauri/src/works/versions.rs @@ -9,8 +9,9 @@ use tauri::State; use super::variant::{self, Origin, Variant}; use crate::db::now; use crate::error::{Error, Result}; +use crate::kind::{ItemKind, WorkKind}; use crate::settings; -use crate::state::AppState; +use crate::state::{AppState, write_blocking}; /// One copy of a work as the detail pages show it. #[derive(Debug, Clone, Serialize)] @@ -88,8 +89,13 @@ impl Member { } /// Work key of one copy. -pub fn work_key(conn: &Connection, kind: &str, source_id: i64, id: &str) -> Result> { - let table = if kind == "movie" { "movie" } else { "series" }; +pub fn work_key( + conn: &Connection, + kind: WorkKind, + source_id: i64, + id: &str, +) -> Result> { + let table = kind.table(); Ok(conn .query_row( &format!("SELECT work_key FROM {table} WHERE source_id = ?1 AND id = ?2"), @@ -101,22 +107,20 @@ pub fn work_key(conn: &Connection, kind: &str, source_id: i64, id: &str) -> Resu } /// All copies of a work (just the given one when it isn't grouped yet). -pub fn members(conn: &Connection, kind: &str, source_id: i64, id: &str) -> Result> { +pub fn members(conn: &Connection, kind: WorkKind, source_id: i64, id: &str) -> Result> { let key = work_key(conn, kind, source_id, id)?; - let (table, ext, played) = if kind == "movie" { - ( - "movie", + let table = kind.table(); + let (ext, played) = match kind { + WorkKind::Movie => ( "x.ext", "(SELECT h.position || '|' || h.duration || '|' || h.watched || '|' || h.updated_at FROM history h WHERE h.source_id = x.source_id AND h.kind = 'movie' AND h.item_id = x.id)", - ) - } else { - ( - "series", + ), + WorkKind::Series => ( "NULL", "(SELECT '0|0|0|' || MAX(h.updated_at) FROM history h WHERE h.source_id = x.source_id AND h.kind = 'episode' AND h.series_id = x.id)", - ) + ), }; let filter = if key.is_some() { "x.work_key = ?1" @@ -162,7 +166,7 @@ pub fn members(conn: &Connection, kind: &str, source_id: i64, id: &str) -> Resul Ok(rows) } -pub fn preference(conn: &Connection, kind: &str, key: &str) -> Result> { +pub fn preference(conn: &Connection, kind: WorkKind, key: &str) -> Result> { Ok(conn .query_row( "SELECT source_id, item_id FROM work_pref WHERE kind = ?1 AND key = ?2", @@ -229,7 +233,7 @@ pub fn choose( pub fn tracks( conn: &Connection, source_id: i64, - kind: &str, + kind: ItemKind, item_id: &str, ) -> Result> { Ok(conn @@ -275,7 +279,7 @@ pub fn summarize_tracks(track_list: &Value, hdr: bool) -> Option { pub fn save_tracks( conn: &Connection, source_id: i64, - kind: &str, + kind: ItemKind, item_id: &str, json: &str, ) -> Result<()> { @@ -291,23 +295,22 @@ pub fn save_tracks( #[tauri::command] pub async fn work_prefer( state: State<'_, AppState>, - kind: String, + kind: WorkKind, source_id: i64, id: String, ) -> Result<()> { - if kind != "movie" && kind != "series" { - return Err(Error::msg(format!("no versions for {kind}"))); - } - let conn = state.db.write(); - let key = work_key(&conn, &kind, source_id, &id)? - .ok_or_else(|| Error::NotFound(format!("{kind} {id}")))?; - conn.execute( - "INSERT INTO work_pref (kind, key, source_id, item_id, updated_at) VALUES (?1, ?2, ?3, ?4, ?5) - ON CONFLICT(kind, key) DO UPDATE SET source_id = excluded.source_id, item_id = excluded.item_id, - updated_at = excluded.updated_at", - params![kind, key, source_id, id, now()], - )?; - Ok(()) + write_blocking(state.inner(), move |conn| { + let key = work_key(conn, kind, source_id, &id)? + .ok_or_else(|| Error::NotFound(format!("{kind} {id}")))?; + conn.execute( + "INSERT INTO work_pref (kind, key, source_id, item_id, updated_at) VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(kind, key) DO UPDATE SET source_id = excluded.source_id, item_id = excluded.item_id, + updated_at = excluded.updated_at", + params![kind, key, source_id, id, now()], + )?; + Ok(()) + }) + .await } #[cfg(test)] @@ -351,10 +354,10 @@ mod tests { [], ) .unwrap(); - save_tracks(&c, 1, "movie", "m", &s.to_string()).unwrap(); - save_tracks(&c, 1, "movie", "m", &s.to_string()).unwrap(); + save_tracks(&c, 1, ItemKind::Movie, "m", &s.to_string()).unwrap(); + save_tracks(&c, 1, ItemKind::Movie, "m", &s.to_string()).unwrap(); assert_eq!( - tracks(&c, 1, "movie", "m").unwrap().unwrap()["audio"][0]["lang"], + tracks(&c, 1, ItemKind::Movie, "m").unwrap().unwrap()["audio"][0]["lang"], "eng" ); } diff --git a/src/app/Layout.test.ts b/src/app/Layout.test.ts new file mode 100644 index 0000000..465ae6c --- /dev/null +++ b/src/app/Layout.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { offPageKey } from "./Layout"; + +const key = (k: string, mods: Partial<{ ctrlKey: boolean; metaKey: boolean; altKey: boolean }> = {}) => ({ + key: k, + ctrlKey: false, + metaKey: false, + altKey: false, + ...mods, +}); + +describe("offPageKey (Layout off-page gating, PL-101)", () => { + it.each([ + ["Space on the body plays", key(" "), { pathname: "/live", onBody: true, playing: true }, "play"], + ["K on the body plays", key("K"), { pathname: "/live", onBody: true, playing: true }, "play"], + ["Space belongs to a focused control", key(" "), { pathname: "/live", onBody: false, playing: true }, null], + ["M mutes even with a control focused", key("m"), { pathname: "/live", onBody: false, playing: true }, "mute"], + ["the player page handles its own keys", key(" "), { pathname: "/player", onBody: true, playing: true }, null], + ["modifiers are not ours", key("m", { ctrlKey: true }), { pathname: "/live", onBody: true, playing: true }, null], + ["nothing plays", key(" "), { pathname: "/live", onBody: true, playing: false }, null], + ["other keys", key("x"), { pathname: "/live", onBody: true, playing: true }, null], + ] as const)("%s", (_name, e, opts, expected) => { + expect(offPageKey(e, opts)).toBe(expected); + }); +}); diff --git a/src/app/Layout.tsx b/src/app/Layout.tsx index ac4590e..6db2c76 100644 --- a/src/app/Layout.tsx +++ b/src/app/Layout.tsx @@ -4,7 +4,8 @@ import { useEffect } from "react"; import { NavLink, Outlet, useLocation, useMatches, useNavigate } from "react-router"; import { useQuery } from "@tanstack/react-query"; import { api } from "../lib/api"; -import { useSync } from "../stores/sync"; +import { ROUTES } from "../lib/routes"; +import { runningSync, useSync } from "../stores/sync"; import { control, usePlayer } from "../stores/player"; import { Artwork } from "../components/media"; import { IconButton, LiveDot } from "../components/ui"; @@ -24,13 +25,17 @@ const NAV = [ ]; /** - * Should an off-page keydown go to the (hidden) player? Space/K/M only, no - * modifiers, not while a control has focus (spatial nav activates on Space), - * and not on the player page (its own handler owns the keys there). + * Should an off-page keydown go to the (hidden) player? Only while something + * plays; Space/K/M only, no modifiers, not while a control has focus (spatial + * nav activates on Space), and not on the player page (its own handler owns + * the keys there). */ -export function offPageKey(e: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }, opts: { pathname: string; onBody: boolean }): "play" | "mute" | null { - if (usePlayer.getState().now === null) return null; - if (opts.pathname === "/player") return null; +export function offPageKey( + e: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }, + opts: { pathname: string; onBody: boolean; playing: boolean }, +): "play" | "mute" | null { + if (!opts.playing) return null; + if (opts.pathname === ROUTES.player) return null; if (e.ctrlKey || e.metaKey || e.altKey) return null; if (e.key === " " || e.key === "k" || e.key === "K") return opts.onBody ? "play" : null; if (e.key === "m" || e.key === "M") return "mute"; @@ -62,10 +67,10 @@ export function Layout() { // straight to that player instead of doing nothing. Space with a // focused control belongs to it (spatial nav activates on Space). const onBody = !(document.activeElement instanceof HTMLElement) || document.activeElement === document.body; - const action = offPageKey(e, { pathname: location.pathname, onBody }); + const action = offPageKey(e, { pathname: location.pathname, onBody, playing: usePlayer.getState().now !== null }); if (action === "play") { e.preventDefault(); - navigate("/player"); + navigate(ROUTES.player); } else if (action === "mute") { e.preventDefault(); void control.setMute(!usePlayer.getState().props.mute); @@ -160,7 +165,7 @@ function NowPlayingCard() { } return ( diff --git a/src/pages/Player.tsx b/src/pages/Player.tsx index e56039c..512a7fc 100644 --- a/src/pages/Player.tsx +++ b/src/pages/Player.tsx @@ -26,34 +26,27 @@ import { } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useNavigate } from "react-router"; -import { getCurrentWindow } from "@tauri-apps/api/window"; import { api } from "../lib/api"; -import { inTauri } from "../lib/bridge"; import { clock, elapsed, hhmm, nowUnix } from "../lib/format"; -import { channelNowPlaying, playEpisode } from "../lib/play"; -import type { Channel, Episode, Track } from "../lib/types"; -import { control, usePlayer, setSubsEnabled, subKeyAction, subKeyHint } from "../stores/player"; +import { itemKey, sameItem, type ItemRef } from "../lib/item"; +import { playEpisode } from "../lib/play"; +import { playerWrite } from "../lib/playerWrite"; +import { SETTINGS_KEY, writeSetting } from "../lib/settings"; +import type { Channel, Settings, Track } from "../lib/types"; +import { control, MAX_VOLUME_CAST, MAX_VOLUME_LOCAL, maxVolume, usePlayer, setSubsEnabled, subKeyAction, subKeyHint } from "../stores/player"; import { CastingBackdrop, CastMenu } from "../components/CastMenu"; import { queryClient } from "../lib/queryClient"; +import { useChannelEpg } from "../hooks/useChannelEpg"; import { ChannelLogo } from "../components/media"; import { Badge, Button, IconButton, LiveDot, ProgressBar } from "../components/ui"; +import { useFullscreen } from "./player/fullscreen"; +import { nextEpisode } from "./player/logic"; +import { useChromeAutoHide } from "./player/useChromeAutoHide"; +import { usePlayerKeys, type KeyBinding } from "./player/usePlayerKeys"; +import { useRecording } from "./player/useRecording"; +import { useZapping } from "./player/useZapping"; -const HIDE_AFTER = 3000; - -async function toggleFullscreen() { - if (inTauri) { - const w = getCurrentWindow(); - await w.setFullscreen(!(await w.isFullscreen())); - } else if (document.fullscreenElement) { - await document.exitFullscreen(); - } else { - await document.documentElement.requestFullscreen(); - } -} - -async function isFullscreen() { - return inTauri ? getCurrentWindow().isFullscreen() : !!document.fullscreenElement; -} +const DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; export function PlayerPage() { const navigate = useNavigate(); @@ -64,12 +57,9 @@ export function PlayerPage() { const reconnectAttempt = usePlayer((s) => s.reconnectAttempt); const casting = usePlayer((s) => !!s.cast); - const [chrome, setChrome] = useState(true); const [panel, setPanel] = useState(null); const [info, setInfo] = useState(false); - const [fullscreen, setFullscreen] = useState(false); const [flash, setFlash] = useState(null); - const [digits, setDigits] = useState(""); const [notice, setNotice] = useState(null); const noticeTimer = useRef(0); const say = useCallback((text: string) => { @@ -77,27 +67,22 @@ export function PlayerPage() { window.clearTimeout(noticeTimer.current); noticeTimer.current = window.setTimeout(() => setNotice(null), 4000); }, []); - const hideTimer = useRef(0); - const digitTimer = useRef(0); + const { chrome, poke } = useChromeAutoHide(() => setPanel(null)); + const { fullscreen, flipFullscreen, leaveFullscreen } = useFullscreen(); // PL-100: subtitles are persisted-off but a subtitle track is selected and - // hidden — tell the first-run user once how to bring them up instead of - // leaving them clueless. Baselines on the persisted setting so a user whose - // subs are on doesn't the hint during the start-up gap before mpv pushes - // sub-visibility. + // hidden — tell the first-run user once how to bring them up. Only for users + // whose persisted setting is off, so the start-up gap before mpv pushes + // sub-visibility doesn't fire the hint for users whose subs are on. const sid = p.sid; const subVisible = p.subVisible; useEffect(() => { - const settings = queryClient.getQueryData | undefined>(["settings"]); - // only for users whose persisted setting is off — the gap between - // start-up and mpv's sub-visibility push must not fire the hint when - // subs are on + const settings = queryClient.getQueryData(SETTINGS_KEY); if (settings?.["player.subsEnabled"] !== false) return; if (typeof sid !== "number" || subVisible || usePlayer.getState().cast) return; - if (settings?.["ui.subHintSeen"] === true) return; + if (settings["ui.subHintSeen"] === true) return; say(subKeyHint(usePlayer.getState().props) === "cycle" ? "Subtitles are off — press S to switch" : "Subtitles are off — press S to turn them on"); - queryClient.setQueryData(["settings"], (cur: Record | undefined) => ({ ...cur, "ui.subHintSeen": true })); - void api.setSetting("ui.subHintSeen", true).catch(() => {}); + void playerWrite(writeSetting(queryClient, "ui.subHintSeen", true)); }, [sid, subVisible, say]); const live = now?.kind === "live"; @@ -112,57 +97,33 @@ export function PlayerPage() { } }, [now, navigate]); - useEffect(() => { - void isFullscreen().then(setFullscreen); - // this is the full-screen player: no picture-in-picture while it's open - usePlayer.getState().setPip(false); - }, []); + // this is the full-screen player: no picture-in-picture while it's open + useEffect(() => usePlayer.getState().setPip(false), []); - const poke = useCallback(() => { - setChrome(true); - window.clearTimeout(hideTimer.current); - hideTimer.current = window.setTimeout(() => { - if (!usePlayer.getState().props.pause) { - setChrome(false); - setPanel(null); - } - }, HIDE_AFTER); - }, []); - useEffect(() => { - poke(); - return () => window.clearTimeout(hideTimer.current); - }, [poke]); // keep chrome up while paused / failing const pinned = p.pause || status !== "playing" || panel !== null; const visible = chrome || pinned; const exit = useCallback(async () => { - if (await isFullscreen()) { - await toggleFullscreen(); - setFullscreen(false); - return; - } + if (await leaveFullscreen()) return; exiting.current = true; const cur = usePlayer.getState().now; navigate(-1); // live keeps playing (preview on the Live TV page); VOD saves & stops — // unless it plays on a TV, which goes on until casting is stopped if (cur && cur.kind !== "live" && !usePlayer.getState().cast) await usePlayer.getState().stop(); - }, [navigate]); + }, [navigate, leaveFullscreen]); // Picture-in-picture (T-034): keep playing in a small window while browsing const toPip = useCallback(async () => { - if (await isFullscreen()) { - await toggleFullscreen(); - setFullscreen(false); - } + await leaveFullscreen(); exiting.current = true; usePlayer.getState().setPip(true); // back to where the user came from (react-router keeps the history index) const idx = (window.history.state as { idx?: number } | null)?.idx ?? 0; if (idx > 0) navigate(-1); else navigate("/", { replace: true }); - }, [navigate]); + }, [navigate, leaveFullscreen]); // Live TV can be paused (mpv keeps buffering). The normal read-ahead gap // between playback and buffer end is noted at pause time, so "behind" only @@ -187,131 +148,58 @@ export function PlayerPage() { const nudgeVolume = useCallback((delta: number) => { const st = usePlayer.getState(); - const target = Math.max(0, Math.min(st.cast ? 100 : 150, st.props.volume + delta)); - if (st.cast) { - void control.setVolume(target).then(() => say(`TV volume ${Math.round(target)}`)); - poke(); - return; - } - void api.set("volume", target).then(() => { + const target = Math.max(0, Math.min(maxVolume(), st.props.volume + delta)); + void control.setVolume(target).then((ok) => { + if (!ok) return; + if (st.cast) { + say(`TV volume ${Math.round(target)}`); + return; + } // mpv applies async; read what it has a moment later so the chip shows // the real level, not the pre-clamp guess. window.setTimeout(() => { - void api.get("volume").then((v) => { - if (typeof v === "number") say(`Volume ${Math.round(v)}`); - }).catch(() => {}); + void playerWrite( + api.get("volume").then((v) => { + if (typeof v === "number") say(`Volume ${Math.round(v)}`); + }), + ); }, 60); - }).catch(() => {}); + }); poke(); }, [say, poke]); const toggleMute = useCallback(() => { const st = usePlayer.getState(); - void control.setMute(!st.props.mute).then(() => say(st.props.mute ? "Sound on" : "Muted")); + void control.setMute(!st.props.mute).then((ok) => ok && say(st.props.mute ? "Sound on" : "Muted")); poke(); }, [say, poke]); - // ---- live zapping - const zapList = now?.zapList ?? []; - // by feed, else by channel (another feed of it may be playing) - const groupKey = now?.channel?.group?.key; - let zapIndex = live ? zapList.findIndex((c) => c.sourceId === now?.sourceId && c.id === now?.id) : -1; - if (live && zapIndex < 0 && groupKey) zapIndex = zapList.findIndex((c) => c.group?.key === groupKey); - const zapTo = useCallback( - (c: Channel) => { - void usePlayer.getState().play(channelNowPlaying(c, usePlayer.getState().now?.zapList)); - poke(); - }, - [poke], - ); - const zap = useCallback( - (dir: number) => { - if (!zapList.length) return; - const i = zapIndex < 0 ? 0 : (zapIndex + dir + zapList.length) % zapList.length; - zapTo(zapList[i]); - }, - [zapList, zapIndex, zapTo], - ); - - // ---- recording (live TV, T-035) - const recordingFile = p.recording; - const lastRecording = useRef(""); - const [recordingSince, setRecordingSince] = useState(0); - useEffect(() => { - if (recordingFile && !lastRecording.current) setRecordingSince(Date.now()); - // ended by the user, a channel change or a failed stream: say where it went - if (!recordingFile && lastRecording.current) say(`Recording saved: ${lastRecording.current.split("/").pop()}`); - lastRecording.current = recordingFile; - }, [recordingFile, say]); - const toggleRecord = useCallback(() => { - const on = !usePlayer.getState().props.recording; - api.record(on).catch((e) => say(`Can't record: ${String(e)}`)); - }, [say]); - - // ---- keyboard - useEffect(() => { - const onKey = (e: KeyboardEvent) => { - if ((e.target as HTMLElement)?.tagName === "INPUT") return; - const k = e.key; - let handled = true; - if (k === " " || k === "k" || k === "K") togglePause(); - else if (k === "ArrowLeft" && !live) seekBy(e.shiftKey ? -60 : -10); - else if (k === "ArrowRight" && !live) seekBy(e.shiftKey ? 60 : 30); - else if ((k === "ArrowUp" && live) || k === "PageUp") zap(-1); - else if ((k === "ArrowDown" && live) || k === "PageDown") zap(1); - else if (k === "ArrowUp" && !live) nudgeVolume(5); - else if (k === "ArrowDown" && !live) nudgeVolume(-5); - else if (k === "f" || k === "F") void toggleFullscreen().then(() => isFullscreen().then(setFullscreen)); - else if (k === "m" || k === "M") toggleMute(); - else if (k === "Escape") { - if (panel) setPanel(null); - else void exit(); - } else if ((k === "a" || k === "A") && !casting) void api.command("cycle", "audio"); - else if ((k === "s" || k === "S") && !casting) { - const action = subKeyAction(usePlayer.getState().props); - if (!action) { - handled = false; - return; - } - if ("cycle" in action) { - void api - .set("sid", action.cycle) - .then(() => { - if (action.cycle !== false) void setSubsEnabled(true).catch(() => {}); - say(action.cycle === false ? "Subtitles off" : "Subtitles on"); - }) - .catch(() => {}); - } else if (action.toggle) { - // turning on: only claim it when the write landed - void setSubsEnabled(true) - .then(() => say("Subtitles on")) - .catch(() => {}); - } else { - void setSubsEnabled(false).catch(() => {}); - say("Subtitles off"); - } - } else if ((k === "i" || k === "I") && !casting) setInfo((v) => !v); - else if ((k === "r" || k === "R") && live && !casting) toggleRecord(); - else if ((k === "p" || k === "P") && !casting) void toPip(); - else if ((k === "l" || k === "L" || k === "c" || k === "C") && live) setPanel((v) => (v === "channels" ? null : "channels")); - else if (/^[0-9]$/.test(k) && live) { - const next = (digits + k).slice(-4); - setDigits(next); - window.clearTimeout(digitTimer.current); - digitTimer.current = window.setTimeout(() => { - const target = zapList.find((c) => String(c.num) === next); - if (target) zapTo(target); - setDigits(""); - }, 1400); - } else handled = false; - if (handled) { - e.preventDefault(); - poke(); - } - }; - window.addEventListener("keydown", onKey); - return () => window.removeEventListener("keydown", onKey); - }, [togglePause, seekBy, zap, zapList, zapTo, exit, panel, digits, live, poke, toggleRecord, toPip, nudgeVolume, toggleMute, casting]); + const { zapList, zap, zapTo, digits, enterDigit } = useZapping(poke); + const { recordingFile, recordingSince, toggleRecord } = useRecording(say); + + // ---- keyboard (first matching entry wins) + const keys: KeyBinding[] = [ + { keys: [" ", "k", "K"], run: togglePause }, + { keys: ["ArrowLeft"], when: !live, run: (e) => seekBy(e.shiftKey ? -60 : -10) }, + { keys: ["ArrowRight"], when: !live, run: (e) => seekBy(e.shiftKey ? 60 : 30) }, + { keys: ["ArrowUp"], when: live, run: () => zap(-1) }, + { keys: ["ArrowDown"], when: live, run: () => zap(1) }, + { keys: ["PageUp"], run: () => zap(-1) }, + { keys: ["PageDown"], run: () => zap(1) }, + { keys: ["ArrowUp"], when: !live, run: () => nudgeVolume(5) }, + { keys: ["ArrowDown"], when: !live, run: () => nudgeVolume(-5) }, + { keys: ["f", "F"], run: flipFullscreen }, + { keys: ["m", "M"], run: toggleMute }, + { keys: ["Escape"], run: () => (panel ? setPanel(null) : void exit()) }, + { keys: ["a", "A"], when: !casting, run: () => void playerWrite(api.command("cycle", "audio")) }, + { keys: ["s", "S"], when: !casting, run: () => subtitleKey(say) }, + { keys: ["i", "I"], when: !casting, run: () => setInfo((v) => !v) }, + { keys: ["r", "R"], when: live && !casting, run: toggleRecord }, + { keys: ["p", "P"], when: !casting, run: () => void toPip() }, + { keys: ["l", "L", "c", "C"], when: live, run: () => setPanel((v) => (v === "channels" ? null : "channels")) }, + { keys: DIGITS, when: live, run: (e) => enterDigit(e.key) }, + ]; + usePlayerKeys(keys, poke); if (!now) return null; const busy = status === "loading" || status === "reconnecting" || (p.buffering && status === "playing"); @@ -327,7 +215,7 @@ export function PlayerPage() { } }} onDoubleClick={(e) => { - if (e.target === e.currentTarget) void toggleFullscreen().then(() => isFullscreen().then(setFullscreen)); + if (e.target === e.currentTarget) flipFullscreen(); }} > @@ -492,7 +380,7 @@ export function PlayerPage() { )} void toggleFullscreen().then(() => isFullscreen().then(setFullscreen))} + onClick={flipFullscreen} className="text-white" > {fullscreen ? : } @@ -500,11 +388,33 @@ export function PlayerPage() { - {live && panel === "channels" && } + {live && panel === "channels" && } ); } +/** + * The S key (PL-100): cycles through several subtitle tracks, or toggles the + * only one. False (unhandled) when there is nothing to switch. + */ +function subtitleKey(say: (text: string) => void): void | false { + const action = subKeyAction(usePlayer.getState().props); + if (!action) return false; + if ("cycle" in action) { + void playerWrite(api.set("sid", action.cycle)).then((ok) => { + if (!ok) return; + if (action.cycle !== false) void playerWrite(setSubsEnabled(true)); + say(action.cycle === false ? "Subtitles off" : "Subtitles on"); + }); + } else if (action.toggle) { + // turning on: only claim it when the write landed + void playerWrite(setSubsEnabled(true)).then((ok) => ok && say("Subtitles on")); + } else { + void playerWrite(setSubsEnabled(false)); + say("Subtitles off"); + } +} + // ------------------------------------------------------------------ parts function Clock() { @@ -611,13 +521,7 @@ function SeekBar({ onSeek }: { onSeek: () => void }) { } function LiveInfo({ channel }: { channel?: Channel }) { - const t = nowUnix(); - const epg = useQuery({ - queryKey: ["epg", channel?.sourceId, channel?.id], - queryFn: () => api.epg(channel!.sourceId, channel!.id, t - 3600, t + 6 * 3600), - enabled: !!channel, - refetchInterval: 5 * 60_000, - }); + const epg = useChannelEpg(channel); const [, tick] = useState(0); useEffect(() => { const i = window.setInterval(() => tick((x) => x + 1), 30_000); @@ -676,7 +580,7 @@ function Volume() { { @@ -739,18 +643,18 @@ function TrackMenu({ type, onDone }: { type: "audio" | "sub"; onDone: () => void const current = usePlayer((s) => (type === "audio" ? s.props.aid : s.props.sid)); const subVisible = usePlayer((s) => s.props.subVisible); const pick = (v: number | "no") => { - void api.set(type === "audio" ? "aid" : "sid", v); + void playerWrite(api.set(type === "audio" ? "aid" : "sid", v)); // picking a track while subtitles are hidden must show it (PL-100); // "Off" persists the disabling so it survives the next session - if (type === "sub") void setSubsEnabled(v !== "no").catch(() => {}); + if (type === "sub") void playerWrite(setSubsEnabled(v !== "no")); onDone(); }; // turning visibility on with no track selected: select the first one so // something actually shows (visibility and selection are separate in mpv) const toggleVisible = () => { const on = !subVisible; - void setSubsEnabled(on).catch(() => {}); - if (on && (current === false || current === null) && tracks.length > 0) void api.set("sid", tracks[0].id); + void playerWrite(setSubsEnabled(on)); + if (on && (current === false || current === null) && tracks.length > 0) void playerWrite(api.set("sid", tracks[0].id)); onDone(); }; return ( @@ -814,8 +718,8 @@ function AspectMenu({ onDone }: { onDone: () => void }) { key={o.label} active={(aspect === o.aspect || (o.aspect === "no" && (aspect === "-1" || aspect === "no"))) && Math.abs(panscan - o.panscan) < 0.01} onClick={() => { - void api.set("video-aspect-override", o.aspect); - void api.set("panscan", o.panscan); + void playerWrite(api.set("video-aspect-override", o.aspect)); + void playerWrite(api.set("panscan", o.panscan)); onDone(); }} > @@ -835,7 +739,7 @@ function SpeedMenu({ onDone }: { onDone: () => void }) { key={v} active={Math.abs(speed - v) < 0.01} onClick={() => { - void api.set("speed", v); + void playerWrite(api.set("speed", v)); onDone(); }} > @@ -846,7 +750,7 @@ function SpeedMenu({ onDone }: { onDone: () => void }) { ); } -function ChannelPanel({ channels, current, onPick }: { channels: Channel[]; current: string; onPick: (c: Channel) => void }) { +function ChannelPanel({ channels, current, onPick }: { channels: Channel[]; current: ItemRef; onPick: (c: Channel) => void }) { const ref = useRef(null); useEffect(() => { ref.current?.querySelector("[data-current=true]")?.scrollIntoView({ block: "center" }); @@ -855,24 +759,27 @@ function ChannelPanel({ channels, current, onPick }: { channels: Channel[]; curr
e.stopPropagation()}>
Channels
- {channels.map((c) => ( + {channels.map((c) => { + const isCurrent = sameItem(c, current); + return ( - ))} + ); + })}
); @@ -907,13 +814,10 @@ function NextEpisode() { queryFn: () => api.seriesDetail(now!.sourceId, now!.seriesId!), enabled: !!now?.seriesId, }); - const next: Episode | undefined = useMemo(() => { - const eps = (detail.data?.seasons ?? []).filter((s) => s.season > 0).flatMap((s) => s.episodes); - // the list merges every copy of the show: find ours by its number - let i = eps.findIndex((e) => e.season === now?.season && e.episode === now?.episode); - if (i < 0) i = eps.findIndex((e) => e.id === now?.id); - return i >= 0 ? eps[i + 1] : undefined; - }, [detail.data, now?.id, now?.season, now?.episode]); + const id = now?.id; + const season = now?.season; + const episode = now?.episode; + const next = useMemo(() => nextEpisode(detail.data?.seasons ?? [], { id, season, episode }), [detail.data, id, season, episode]); const [left, setLeft] = useState(10); const [cancelled, setCancelled] = useState(false); useEffect(() => { diff --git a/src/pages/Search.tsx b/src/pages/Search.tsx index 35c1280..3e62197 100644 --- a/src/pages/Search.tsx +++ b/src/pages/Search.tsx @@ -3,8 +3,10 @@ import { History, Search as SearchIcon, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { useNavigate, useSearchParams } from "react-router"; import { api } from "../lib/api"; +import { itemKey } from "../lib/item"; import { elapsed } from "../lib/format"; import { playChannel } from "../lib/play"; +import { loadJson, saveJson } from "../lib/storage"; import { ChannelLogo, PosterCard, Shelf, ShelfItem } from "../components/media"; import { QualityBadges, workSubtitle } from "../components/LibraryBrowser"; import { EmptyState, LiveDot, ProgressBar, Spinner } from "../components/ui"; @@ -12,19 +14,10 @@ import { EmptyState, LiveDot, ProgressBar, Spinner } from "../components/ui"; const RECENT_KEY = "search.recent"; function loadRecent(): string[] { - try { - return JSON.parse(localStorage.getItem(RECENT_KEY) ?? "[]"); - } catch { - return []; - } + return loadJson(RECENT_KEY, []); } function saveRecent(q: string) { - const list = [q, ...loadRecent().filter((x) => x.toLowerCase() !== q.toLowerCase())].slice(0, 8); - try { - localStorage.setItem(RECENT_KEY, JSON.stringify(list)); - } catch { - /* ignore */ - } + saveJson(RECENT_KEY, [q, ...loadRecent().filter((x) => x.toLowerCase() !== q.toLowerCase())].slice(0, 8)); } export function SearchPage() { @@ -111,7 +104,7 @@ export function SearchPage() {
{r.channels.slice(0, 12).map((c) => (
- +
@@ -215,7 +223,7 @@ function PlaybackSettings() { label="Hardware decoding" description="Uses the GPU when the driver supports the codec; falls back to software automatically." checked={s["player.hwdec"] !== "no"} - onChange={(v) => void set("player.hwdec", v ? "auto-safe" : "no")} + onChange={(v) => set("player.hwdec", v ? "auto-safe" : "no")} />
@@ -228,19 +236,19 @@ function PlaybackSettings() { { value: "ts", label: "MPEG-TS" }, { value: "m3u8", label: "HLS" }, ]} - onChange={(v) => void set("player.liveFormat", v)} + onChange={(v) => set("player.liveFormat", v)} />
void set("player.subsEnabled", v)} + onChange={(v) => set("player.subsEnabled", v)} />
{/* keyed so the fields pick up the stored value once settings load */} - void set("player.audioLang", v)} /> - void set("player.subLang", v)} /> + set("player.audioLang", v)} /> + set("player.subLang", v)} />
@@ -250,10 +258,16 @@ function PlaybackSettings() { label="Show adult content" description="Categories flagged as adult by the provider stay hidden unless this is on." checked={s["content.showAdult"] === true} - onChange={(v) => void set("content.showAdult", v)} + onChange={(v) => set("content.showAdult", v)} /> + {error && ( +

+ + {error} +

+ )} ); @@ -403,7 +417,7 @@ function About() { return (
-

testpattern 0.1.0

+

testpattern {__APP_VERSION__}

Playback engine: {versions.data?.mpv ?? "mpv"} · FFmpeg {versions.data?.ffmpeg ?? ""} (built in, statically linked).

diff --git a/src/pages/player/fullscreen.ts b/src/pages/player/fullscreen.ts new file mode 100644 index 0000000..f93e03e --- /dev/null +++ b/src/pages/player/fullscreen.ts @@ -0,0 +1,34 @@ +import { useCallback, useEffect, useState } from "react"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { inTauri } from "../../lib/bridge"; +import { playerWrite } from "../../lib/playerWrite"; + +async function toggleFullscreen() { + if (inTauri) { + const w = getCurrentWindow(); + await w.setFullscreen(!(await w.isFullscreen())); + } else if (document.fullscreenElement) { + await document.exitFullscreen(); + } else { + await document.documentElement.requestFullscreen(); + } +} + +async function isFullscreen() { + return inTauri ? getCurrentWindow().isFullscreen() : !!document.fullscreenElement; +} + +/** The window's fullscreen state, a toggle (F, double-click) and a way out. */ +export function useFullscreen() { + const [fullscreen, setFullscreen] = useState(false); + useEffect(() => void isFullscreen().then(setFullscreen), []); + const flipFullscreen = useCallback(() => void playerWrite(toggleFullscreen().then(() => isFullscreen().then(setFullscreen))), []); + /** Leaves fullscreen; true when it was. */ + const leaveFullscreen = useCallback(async () => { + if (!(await isFullscreen())) return false; + await toggleFullscreen(); + setFullscreen(false); + return true; + }, []); + return { fullscreen, flipFullscreen, leaveFullscreen }; +} diff --git a/src/pages/player/logic.test.ts b/src/pages/player/logic.test.ts new file mode 100644 index 0000000..e000e6b --- /dev/null +++ b/src/pages/player/logic.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "vitest"; +import type { Channel, Episode, Season } from "../../lib/types"; +import type { NowPlaying } from "../../stores/player"; +import { nextEpisode, zapIndex, zapStep } from "./logic"; +import { findBinding, type KeyBinding } from "./usePlayerKeys"; + +const channel = (sourceId: number, id: string, groupKey?: string): Channel => ({ + sourceId, + id, + title: id, + badges: [], + archive: false, + archiveDays: 0, + favorite: false, + group: groupKey ? { key: groupKey, variants: 2, genre: "News" } : null, +}); + +describe("zapIndex", () => { + const list = [channel(1, "a", "ga"), channel(1, "b", "gb"), channel(2, "b", "gc")]; + const live = (c: Channel): NowPlaying => ({ kind: "live", sourceId: c.sourceId, id: c.id, title: c.title, channel: c }); + + it("finds the playing feed by source and id", () => { + expect(zapIndex(list, live(channel(2, "b")))).toBe(2); + }); + it("falls back to another feed of the same channel", () => { + expect(zapIndex(list, live(channel(3, "x", "gb")))).toBe(1); + }); + it("is -1 off the list and for anything but live TV", () => { + expect(zapIndex(list, live(channel(3, "x")))).toBe(-1); + expect(zapIndex(list, { kind: "movie", sourceId: 1, id: "a", title: "A" })).toBe(-1); + expect(zapIndex(list, null)).toBe(-1); + }); +}); + +describe("zapStep", () => { + it("wraps around both ends", () => { + expect(zapStep(0, -1, 3)).toBe(2); + expect(zapStep(2, 1, 3)).toBe(0); + expect(zapStep(1, 1, 3)).toBe(2); + }); + it("starts at the first channel when the current one is not in the list", () => { + expect(zapStep(-1, 1, 3)).toBe(0); + expect(zapStep(-1, -1, 3)).toBe(0); + }); +}); + +describe("nextEpisode", () => { + const ep = (season: number, episode: number, id = `s${season}e${episode}`): Episode => ({ + id, season, episode, title: id, position: 0, watched: false, sourceId: 1, seriesId: "s", + }); + const seasons: Season[] = [ + { season: 0, name: "Specials", episodes: [ep(0, 1)] }, + { season: 1, name: "S1", episodes: [ep(1, 1), ep(1, 2)] }, + { season: 2, name: "S2", episodes: [ep(2, 1)] }, + ]; + + it("continues within the season and into the next one", () => { + expect(nextEpisode(seasons, { id: "x", season: 1, episode: 1 })?.id).toBe("s1e2"); + expect(nextEpisode(seasons, { id: "x", season: 1, episode: 2 })?.id).toBe("s2e1"); + }); + it("finds the episode by id when the numbers are unknown", () => { + expect(nextEpisode(seasons, { id: "s1e1" })?.id).toBe("s1e2"); + }); + it("has nothing after the last episode, and skips specials", () => { + expect(nextEpisode(seasons, { id: "s2e1", season: 2, episode: 1 })).toBeUndefined(); + expect(nextEpisode(seasons, { id: "s0e1", season: 0, episode: 1 })).toBeUndefined(); + }); +}); + +describe("player key table", () => { + const bindings: KeyBinding[] = [ + { keys: ["ArrowUp"], when: true, run: () => {} }, + { keys: ["ArrowUp", "x"], run: () => {} }, + { keys: ["y"], when: false, run: () => {} }, + ]; + it("takes the first entry that applies", () => { + expect(findBinding(bindings, "ArrowUp")).toBe(bindings[0]); + expect(findBinding([{ ...bindings[0], when: false }, bindings[1]], "ArrowUp")).toBe(bindings[1]); + }); + it("skips entries that don't apply right now", () => { + expect(findBinding(bindings, "y")).toBeUndefined(); + expect(findBinding(bindings, "z")).toBeUndefined(); + }); +}); diff --git a/src/pages/player/logic.ts b/src/pages/player/logic.ts new file mode 100644 index 0000000..d599a37 --- /dev/null +++ b/src/pages/player/logic.ts @@ -0,0 +1,29 @@ +import { sameItem } from "../../lib/item"; +import type { Channel, Episode, Season } from "../../lib/types"; +import type { NowPlaying } from "../../stores/player"; + +/** + * Where the playing channel sits in its zap list: by feed, else by channel + * (another feed of it may be playing); -1 when not live or not in the list. + */ +export function zapIndex(zapList: Channel[], now: NowPlaying | null | undefined): number { + if (now?.kind !== "live") return -1; + const i = zapList.findIndex((c) => sameItem(c, now)); + const groupKey = now.channel?.group?.key; + if (i < 0 && groupKey) return zapList.findIndex((c) => c.group?.key === groupKey); + return i; +} + +/** One channel up (-1) or down (+1), wrapping around; the first when not in the list. */ +export function zapStep(index: number, dir: number, length: number): number { + return index < 0 ? 0 : (index + dir + length) % length; +} + +/** The episode after the playing one (specials, season 0, are skipped). */ +export function nextEpisode(seasons: Season[], now: { id?: string; season?: number; episode?: number } | null | undefined): Episode | undefined { + const eps = seasons.filter((s) => s.season > 0).flatMap((s) => s.episodes); + // the list merges every copy of the show: find ours by its number + let i = eps.findIndex((e) => e.season === now?.season && e.episode === now?.episode); + if (i < 0) i = eps.findIndex((e) => e.id === now?.id); + return i >= 0 ? eps[i + 1] : undefined; +} diff --git a/src/pages/player/useChromeAutoHide.ts b/src/pages/player/useChromeAutoHide.ts new file mode 100644 index 0000000..3e77f50 --- /dev/null +++ b/src/pages/player/useChromeAutoHide.ts @@ -0,0 +1,32 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { usePlayer } from "../../stores/player"; + +const HIDE_AFTER = 3000; + +/** + * The player chrome shows on activity (`poke`) and hides again after a few + * quiet seconds — not while paused. `onHide` runs as it hides (closes menus). + */ +export function useChromeAutoHide(onHide: () => void) { + const [chrome, setChrome] = useState(true); + const timer = useRef(0); + const hide = useRef(onHide); + useEffect(() => { + hide.current = onHide; + }); + const poke = useCallback(() => { + setChrome(true); + window.clearTimeout(timer.current); + timer.current = window.setTimeout(() => { + if (!usePlayer.getState().props.pause) { + setChrome(false); + hide.current(); + } + }, HIDE_AFTER); + }, []); + useEffect(() => { + poke(); + return () => window.clearTimeout(timer.current); + }, [poke]); + return { chrome, poke }; +} diff --git a/src/pages/player/usePlayerKeys.ts b/src/pages/player/usePlayerKeys.ts new file mode 100644 index 0000000..5e44243 --- /dev/null +++ b/src/pages/player/usePlayerKeys.ts @@ -0,0 +1,36 @@ +import { useEffect, useRef } from "react"; + +/** + * One keyboard shortcut: the keys (`KeyboardEvent.key`) it takes, whether it + * applies right now, and what it does — returning false leaves the key + * unhandled (no preventDefault, no chrome poke). + */ +export interface KeyBinding { + keys: readonly string[]; + when?: boolean; + run: (e: KeyboardEvent) => void | false; +} + +/** The first binding that takes `key` right now; later ones are fallbacks. */ +export function findBinding(bindings: readonly KeyBinding[], key: string): KeyBinding | undefined { + return bindings.find((b) => b.when !== false && b.keys.includes(key)); +} + +/** Window-wide shortcuts (not while typing in an input); `onHandled` after each. */ +export function usePlayerKeys(bindings: readonly KeyBinding[], onHandled: () => void) { + const latest = useRef({ bindings, onHandled }); + useEffect(() => { + latest.current = { bindings, onHandled }; + }); + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if ((e.target as HTMLElement)?.tagName === "INPUT") return; + const b = findBinding(latest.current.bindings, e.key); + if (!b || b.run(e) === false) return; + e.preventDefault(); + latest.current.onHandled(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); +} diff --git a/src/pages/player/useRecording.ts b/src/pages/player/useRecording.ts new file mode 100644 index 0000000..f1f83f8 --- /dev/null +++ b/src/pages/player/useRecording.ts @@ -0,0 +1,22 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { api } from "../../lib/api"; +import { playerWrite } from "../../lib/playerWrite"; +import { usePlayer } from "../../stores/player"; + +/** Recording live TV (T-035): the file being written, since when, and a toggle. */ +export function useRecording(say: (text: string) => void) { + const recordingFile = usePlayer((s) => s.props.recording); + const lastRecording = useRef(""); + const [recordingSince, setRecordingSince] = useState(0); + useEffect(() => { + if (recordingFile && !lastRecording.current) setRecordingSince(Date.now()); + // ended by the user, a channel change or a failed stream: say where it went + if (!recordingFile && lastRecording.current) say(`Recording saved: ${lastRecording.current.split("/").pop()}`); + lastRecording.current = recordingFile; + }, [recordingFile, say]); + const toggleRecord = useCallback(() => { + const on = !usePlayer.getState().props.recording; + void playerWrite(api.record(on), (e) => say(`Can't record: ${e}`)); + }, [say]); + return { recordingFile, recordingSince, toggleRecord }; +} diff --git a/src/pages/player/useZapping.ts b/src/pages/player/useZapping.ts new file mode 100644 index 0000000..28971b2 --- /dev/null +++ b/src/pages/player/useZapping.ts @@ -0,0 +1,48 @@ +import { useCallback, useRef, useState } from "react"; +import { channelNowPlaying } from "../../lib/play"; +import type { Channel } from "../../lib/types"; +import { usePlayer } from "../../stores/player"; +import { zapIndex, zapStep } from "./logic"; + +/** Live zapping: up/down through the channel list, or a typed channel number. */ +export function useZapping(poke: () => void) { + const now = usePlayer((s) => s.now); + const zapList = now?.zapList ?? []; + const index = zapIndex(zapList, now); + const zapTo = useCallback( + (c: Channel) => { + void usePlayer.getState().play(channelNowPlaying(c, usePlayer.getState().now?.zapList)); + poke(); + }, + [poke], + ); + const zap = useCallback( + (dir: number) => { + if (!zapList.length) return; + zapTo(zapList[zapStep(index, dir, zapList.length)]); + }, + [zapList, index, zapTo], + ); + + // number keys: up to 4 digits, tuned once typing pauses + const [digits, setDigits] = useState(""); + const typed = useRef(""); + const digitTimer = useRef(0); + const enterDigit = useCallback( + (d: string) => { + const next = (typed.current + d).slice(-4); + typed.current = next; + setDigits(next); + window.clearTimeout(digitTimer.current); + digitTimer.current = window.setTimeout(() => { + const target = zapList.find((c) => String(c.num) === next); + if (target) zapTo(target); + typed.current = ""; + setDigits(""); + }, 1400); + }, + [zapList, zapTo], + ); + + return { zapList, zap, zapTo, digits, enterDigit }; +} diff --git a/src/stores/player.test.ts b/src/stores/player.test.ts index 1655c77..33ba297 100644 --- a/src/stores/player.test.ts +++ b/src/stores/player.test.ts @@ -10,10 +10,28 @@ vi.mock("../lib/api", () => ({ errorMessage: (e: unknown) => String(e), })); -import { applyProp, saveProgress, setSubsEnabled, subKeyAction, subKeyHint, toggleSubs, trackId, usePlayer, type NowPlaying } from "./player"; +import type { CastStatus } from "../lib/types"; +import { applyProp, saveProgress, setSubsEnabled, subKeyAction, subKeyHint, trackId, usePlayer, type NowPlaying } from "./player"; const props = () => usePlayer.getState().props; +// every test starts from a fresh store +const initial = usePlayer.getState(); +beforeEach(() => usePlayer.setState(initial, true)); + +const castStatus = (overrides: Partial = {}): CastStatus => ({ + deviceId: "d", + deviceName: "TV", + state: "playing", + position: 0, + duration: 0, + live: true, + volume: 1, + muted: false, + error: null, + ...overrides, +}); + describe("applyProp", () => { it("maps mpv properties to store fields", () => { expect(applyProp(props(), "time-pos", 12.5)).toEqual({ timePos: 12.5 }); @@ -69,42 +87,27 @@ describe("saveProgress", () => { }); }); -describe("offPageKey (Layout off-page gating, PL-101)", () => { - it("fires Space/K only when body is focused; M toggles mute; ignored on /player and with modifiers", async () => { - const { offPageKey } = await import("../app/Layout"); - const np: NowPlaying = { kind: "live", sourceId: 1, id: "c1", title: "BBC" }; - usePlayer.setState({ now: np }); - expect(offPageKey({ key: " ", ctrlKey: false, metaKey: false, altKey: false }, { pathname: "/live", onBody: true })).toBe("play"); - expect(offPageKey({ key: " ", ctrlKey: false, metaKey: false, altKey: false }, { pathname: "/live", onBody: false })).toBeNull(); - expect(offPageKey({ key: "m", ctrlKey: false, metaKey: false, altKey: false }, { pathname: "/live", onBody: false })).toBe("mute"); - expect(offPageKey({ key: " ", ctrlKey: false, metaKey: false, altKey: false }, { pathname: "/player", onBody: true })).toBeNull(); - expect(offPageKey({ key: "m", ctrlKey: true, metaKey: false, altKey: false }, { pathname: "/live", onBody: true })).toBeNull(); - usePlayer.setState({ now: null }); - expect(offPageKey({ key: " ", ctrlKey: false, metaKey: false, altKey: false }, { pathname: "/live", onBody: true })).toBeNull(); - }); -}); - describe("subtitles toggle (PL-99)", () => { it("persists the setting and patches the settings cache", async () => { const { queryClient } = await import("../lib/queryClient"); + const { SETTINGS_KEY } = await import("../lib/settings"); const api = (await import("../lib/api")).api as unknown as { setSetting: ReturnType }; - queryClient.setQueryData(["settings"], { "player.subsEnabled": false }); + queryClient.setQueryData(SETTINGS_KEY, { "player.subsEnabled": false }); api.setSetting.mockClear(); api.setSetting.mockResolvedValue(undefined); void setSubsEnabled(true); expect(api.setSetting).toHaveBeenCalledWith("player.subsEnabled", true); - expect(queryClient.getQueryData(["settings"])).toMatchObject({ "player.subsEnabled": true }); - toggleSubs(); // store says subVisible=false → turns on - expect(api.setSetting).toHaveBeenLastCalledWith("player.subsEnabled", true); + expect(queryClient.getQueryData(SETTINGS_KEY)).toMatchObject({ "player.subsEnabled": true }); }); it("rolls the cache back when the write fails", async () => { const { queryClient } = await import("../lib/queryClient"); + const { SETTINGS_KEY } = await import("../lib/settings"); const api = (await import("../lib/api")).api as unknown as { setSetting: ReturnType }; - queryClient.setQueryData(["settings"], { "player.subsEnabled": false }); + queryClient.setQueryData(SETTINGS_KEY, { "player.subsEnabled": false }); api.setSetting.mockRejectedValueOnce(new Error("backend down")); await expect(setSubsEnabled(true)).rejects.toThrow("backend down"); - expect(queryClient.getQueryData(["settings"])).toMatchObject({ "player.subsEnabled": false }); + expect(queryClient.getQueryData(SETTINGS_KEY)).toMatchObject({ "player.subsEnabled": false }); }); }); @@ -137,9 +140,10 @@ describe("subKeyAction (S key, PL-100)", () => { describe("cast", () => { it("castProps maps the TV status onto mpv-shaped props", async () => { const { castProps } = await import("./player"); - const p = castProps({ ...usePlayer.getState().props, tracks: [{ id: 1, type: "audio" }] }, { - deviceId: "d", deviceName: "TV", state: "paused", position: 42, duration: 100, live: false, volume: 0.7, muted: true, error: null, - }); + const p = castProps( + { ...usePlayer.getState().props, tracks: [{ id: 1, type: "audio" }] }, + castStatus({ state: "paused", position: 42, duration: 100, live: false, volume: 0.7, muted: true }), + ); expect(p.pause).toBe(true); expect(p.timePos).toBe(42); expect(p.duration).toBe(100); @@ -151,18 +155,19 @@ describe("cast", () => { it("castPlayerStatus maps TV states to player states", async () => { const { castPlayerStatus } = await import("./player"); - expect(castPlayerStatus({ deviceId: "d", deviceName: "TV", state: "loading", position: 0, duration: 0, live: true, volume: 1, muted: false, error: null })).toEqual({ status: "loading", error: null }); - expect(castPlayerStatus({ deviceId: "d", deviceName: "TV", state: "error", position: 0, duration: 0, live: true, volume: 1, muted: false, error: "boom" })).toEqual({ status: "error", error: "boom" }); - expect(castPlayerStatus({ deviceId: "d", deviceName: "TV", state: "ended", position: 0, duration: 0, live: false, volume: 1, muted: false, error: null }).status).toBe("ended"); + expect(castPlayerStatus(castStatus({ state: "loading" }))).toEqual({ status: "loading", error: null }); + expect(castPlayerStatus(castStatus({ state: "error", error: "boom" }))).toEqual({ status: "error", error: "boom" }); + expect(castPlayerStatus(castStatus({ state: "ended", live: false })).status).toBe("ended"); }); it("onCastStatus ignores other devices and ended sessions", () => { - usePlayer.setState({ now: { kind: "live", sourceId: 1, id: "c", title: "C" }, status: "playing", cast: { deviceId: "a", deviceName: "A", state: "playing", position: 0, duration: 0, live: true, volume: 1, muted: false, error: null } }); - usePlayer.getState().onCastStatus({ deviceId: "b", deviceName: "B", state: "playing", position: 5, duration: 0, live: true, volume: 1, muted: false, error: null }); + const a = { deviceId: "a", deviceName: "A" }; + usePlayer.setState({ now: { kind: "live", sourceId: 1, id: "c", title: "C" }, status: "playing", cast: castStatus(a) }); + usePlayer.getState().onCastStatus(castStatus({ deviceId: "b", deviceName: "B", position: 5 })); expect(usePlayer.getState().cast?.position).toBe(0); - usePlayer.getState().onCastStatus({ deviceId: "a", deviceName: "A", state: "playing", position: 9, duration: 0, live: true, volume: 1, muted: false, error: null }); + usePlayer.getState().onCastStatus(castStatus({ ...a, position: 9 })); expect(usePlayer.getState().cast?.position).toBe(9); - usePlayer.getState().onCastStatus({ deviceId: "a", deviceName: "A", state: "stopped", position: 9, duration: 0, live: true, volume: 1, muted: false, error: null }); + usePlayer.getState().onCastStatus(castStatus({ ...a, state: "stopped", position: 9 })); expect(usePlayer.getState().cast).toBeNull(); expect(usePlayer.getState().castNotice).toContain("ended"); }); diff --git a/src/stores/player.ts b/src/stores/player.ts index a571377..adfa764 100644 --- a/src/stores/player.ts +++ b/src/stores/player.ts @@ -1,6 +1,8 @@ import { create } from "zustand"; import { api, errorMessage } from "../lib/api"; +import { playerWrite } from "../lib/playerWrite"; import { invalidateWatchState, queryClient } from "../lib/queryClient"; +import { writeSetting } from "../lib/settings"; import type { CastDevice, CastMeta, CastStatus, Channel, PlayKind, PlayRequest, PlayerEvent, Track } from "../lib/types"; /** What is (or is about to be) playing, with enough context for the UI. */ @@ -291,7 +293,7 @@ export const usePlayer = create((set, get) => ({ const { now, props, cast } = get(); const saved = !!now && (await saveProgress(now, props)); set({ now: null, status: "idle", error: null, pip: false, cast: null }); - await (cast ? api.castStop() : api.stop()).catch(() => {}); + await playerWrite(cast ? api.castStop() : api.stop()); // the page we return to may show this item's progress if (saved) invalidateWatchState(); }, @@ -329,7 +331,7 @@ export const usePlayer = create((set, get) => ({ stopCasting: async () => { if (!get().cast) return; set({ cast: null }); - await api.castStop().catch(() => {}); + await playerWrite(api.castStop()); continueHere(); }, @@ -377,15 +379,23 @@ export const usePlayer = create((set, get) => ({ }, })); +/** + * Re-reads this computer's volume + mute from mpv into the store: at startup + * (mpv applied the saved volume before the UI was listening) and after + * casting (the TV's volume was showing). + */ +export function syncLocalVolume(): Promise { + return playerWrite( + Promise.all([api.get("volume"), api.get("mute")]).then(([volume, mute]) => + usePlayer.setState((s) => ({ props: { ...s.props, volume: volume ?? s.props.volume, mute: mute ?? s.props.mute } })), + ), + ); +} + /** After casting: a movie or episode continues here (paused), live TV stops. */ function continueHere() { const { now, props } = usePlayer.getState(); - // the TV's volume was showing: back to this computer's - void Promise.all([api.get("volume"), api.get("mute")]) - .then(([volume, mute]) => - usePlayer.setState((s) => ({ props: { ...s.props, volume: volume ?? s.props.volume, mute: mute ?? s.props.mute } })), - ) - .catch(() => {}); + void syncLocalVolume(); if (!now) return; if (now.kind === "live") { usePlayer.setState({ now: null, status: "idle", error: null, props: { ...props, eof: false } }); @@ -394,56 +404,55 @@ function continueHere() { void usePlayer.getState().play({ ...now, start: props.timePos || now.start, paused: true }); } +/** mpv's volume ceiling (`volume-max`, player/mod.rs; the saved volume is clamped the same in settings.rs). */ +export const MAX_VOLUME_LOCAL = 150; +/** The TV's scale (its 0…1 level as percent). */ +export const MAX_VOLUME_CAST = 100; +/** The volume ceiling of whichever side is playing. */ +export const maxVolume = () => (usePlayer.getState().cast ? MAX_VOLUME_CAST : MAX_VOLUME_LOCAL); + /** * Playback controls for whichever side is playing: this computer (mpv) or - * the TV being cast to. + * the TV being cast to. Fire-and-forget: each resolves true when the write + * landed; a failure is logged and handed to `onError`. */ export const control = { - setPause(pause: boolean) { - if (usePlayer.getState().cast) return api.castControl(pause ? "pause" : "play").catch(() => {}); - return api.set("pause", pause).catch(() => {}); + setPause(pause: boolean, onError?: (message: string) => void) { + if (usePlayer.getState().cast) return playerWrite(api.castControl(pause ? "pause" : "play"), onError); + return playerWrite(api.set("pause", pause), onError); }, - seekTo(seconds: number) { + seekTo(seconds: number, onError?: (message: string) => void) { const { cast, props } = usePlayer.getState(); - if (!cast) return api.command("seek", seconds.toFixed(2), "absolute").catch(() => {}); + if (!cast) return playerWrite(api.command("seek", seconds.toFixed(2), "absolute"), onError); const t = Math.max(0, props.duration > 0 ? Math.min(seconds, props.duration - 1) : seconds); usePlayer.setState({ props: { ...props, timePos: t } }); - return api.castControl("seek", t).catch(() => {}); + return playerWrite(api.castControl("seek", t), onError); }, - seekBy(seconds: number) { + seekBy(seconds: number, onError?: (message: string) => void) { const { cast, props } = usePlayer.getState(); - if (!cast) return api.command("seek", seconds, "relative").catch(() => {}); - return control.seekTo(props.timePos + seconds); + if (!cast) return playerWrite(api.command("seek", seconds, "relative"), onError); + return control.seekTo(props.timePos + seconds, onError); }, - /** mpv scale: 0…150 (the TV's 0…100) */ - setVolume(volume: number) { - if (usePlayer.getState().cast) return api.castControl("volume", Math.min(100, volume) / 100).catch(() => {}); - return api.set("volume", volume).catch(() => {}); + /** 0…MAX_VOLUME_LOCAL here, 0…MAX_VOLUME_CAST on the TV; clamped to the side's range */ + setVolume(volume: number, onError?: (message: string) => void) { + const v = Math.max(0, Math.min(maxVolume(), volume)); + if (usePlayer.getState().cast) return playerWrite(api.castControl("volume", v / 100), onError); + return playerWrite(api.set("volume", v), onError); }, - setMute(mute: boolean) { - if (usePlayer.getState().cast) return api.castControl("mute", mute ? 1 : 0).catch(() => {}); - return api.set("mute", mute).catch(() => {}); + setMute(mute: boolean, onError?: (message: string) => void) { + if (usePlayer.getState().cast) return playerWrite(api.castControl("mute", mute ? 1 : 0), onError); + return playerWrite(api.set("mute", mute), onError); }, }; /** * Subtitles on/off from the player chrome (PL-99): persists the setting and - * settings.rs applies mpv `sub-visibility` right away. The settings cache is - * patched so both toggles (player + Settings page) stay in sync; a failed - * write rolls the patch back instead of diverging from the backend. + * settings.rs applies mpv `sub-visibility` right away. Through writeSetting, + * so both toggles (player + Settings page) stay in sync and a failed write + * rolls back; rejects on failure. */ export function setSubsEnabled(v: boolean): Promise { - const cur = queryClient.getQueryData>(["settings"]); - queryClient.setQueryData(["settings"], { ...cur, "player.subsEnabled": v }); - return api.setSetting("player.subsEnabled", v).catch((e) => { - queryClient.setQueryData(["settings"], (c: Record | undefined) => ({ ...c, "player.subsEnabled": cur?.["player.subsEnabled"] })); - throw e; - }); -} - -/** Toggle-the-subtitles helper shared by Player.tsx ("S" key) and its menu. */ -export function toggleSubs(): void { - void setSubsEnabled(!usePlayer.getState().props.subVisible).catch(() => {}); + return writeSetting(queryClient, "player.subsEnabled", v); } /** @@ -476,7 +485,7 @@ let volumeTimer = 0; /** Persists the volume (applied at startup, settings.rs) once it settles. */ function rememberVolume(volume: number) { window.clearTimeout(volumeTimer); - volumeTimer = window.setTimeout(() => void api.setSetting("player.volume", Math.round(volume)).catch(() => {}), 1000); + volumeTimer = window.setTimeout(() => void playerWrite(api.setSetting("player.volume", Math.round(volume))), 1000); } /** @@ -487,8 +496,8 @@ function rememberVolume(volume: number) { export async function saveProgress(np: NowPlaying, p: PlaybackProps): Promise { if (np.kind !== "movie" && np.kind !== "episode") return false; if (p.duration <= 0) return false; - return api - .updateHistory({ + return playerWrite( + api.updateHistory({ kind: np.kind, sourceId: np.sourceId, itemId: np.id, @@ -502,9 +511,8 @@ export async function saveProgress(np: NowPlaying, p: PlaybackProps): Promise true) - .catch(() => false); + }), + ); } /** @@ -519,6 +527,6 @@ export async function setVideoViewport(rect: DOMRect | null): Promise { ? { left: rect.left / W, right: (W - rect.right) / W, top: rect.top / H, bottom: (H - rect.bottom) / H } : { left: 0, right: 0, top: 0, bottom: 0 }; await Promise.all( - Object.entries(m).map(([side, v]) => api.set(`video-margin-ratio-${side}`, clamp(v)).catch(() => {})), + Object.entries(m).map(([side, v]) => playerWrite(api.set(`video-margin-ratio-${side}`, clamp(v)))), ); } diff --git a/src/stores/sync.test.ts b/src/stores/sync.test.ts index 4331910..d8afc6a 100644 --- a/src/stores/sync.test.ts +++ b/src/stores/sync.test.ts @@ -1,17 +1,17 @@ import { describe, expect, it } from "vitest"; -import { anySyncRunning, useSync } from "./sync"; +import { runningSync, useSync } from "./sync"; describe("sync progress", () => { it("follows a sync from start to finish", () => { const { apply } = useSync.getState(); apply({ stage: "started", sourceId: 7 }); expect(useSync.getState().bySource[7]).toMatchObject({ running: true, error: null }); - expect(anySyncRunning(useSync.getState())).toBe(true); + expect(runningSync(useSync.getState())).toMatchObject({ running: true, message: "Starting…" }); apply({ stage: "step", sourceId: 7, message: "Saving…" }); expect(useSync.getState().bySource[7].message).toBe("Saving…"); apply({ stage: "done", sourceId: 7, counts: { channels: 1, movies: 0, series: 0, programmes: 0 } }); expect(useSync.getState().bySource[7]).toMatchObject({ running: false, message: "Up to date" }); - expect(anySyncRunning(useSync.getState())).toBe(false); + expect(runningSync(useSync.getState())).toBeUndefined(); }); it("keeps the error of a failed sync until the next one starts", () => { const { apply } = useSync.getState(); diff --git a/src/stores/sync.ts b/src/stores/sync.ts index a7f28d7..69d4283 100644 --- a/src/stores/sync.ts +++ b/src/stores/sync.ts @@ -39,4 +39,5 @@ export const useSync = create((set) => ({ }), })); -export const anySyncRunning = (s: SyncStore) => Object.values(s.bySource).some((v) => v.running); +/** A sync in progress (any source), for the sidebar's status line; undefined when none. */ +export const runningSync = (s: SyncStore): SyncState | undefined => Object.values(s.bySource).find((v) => v.running); diff --git a/vite.config.ts b/vite.config.ts index e0daa44..08cbc86 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,12 +1,17 @@ +/// import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; +import pkg from "./package.json" with { type: "json" }; const host = process.env.TAURI_DEV_HOST; export default defineConfig({ plugins: [react(), tailwindcss()], clearScreen: false, + // the About section's version (also in tests and the browser preview, where + // Tauri's getVersion() is unavailable) + define: { __APP_VERSION__: JSON.stringify(pkg.version) }, // Only VITE_* variables reach the bundle; TP_* test credentials stay local. envPrefix: ["VITE_"], server: { @@ -21,4 +26,6 @@ export default defineConfig({ sourcemap: false, chunkSizeWarningLimit: 1500, }, + // only this checkout's tests: .deps/ holds gitignored copies of src/ + test: { include: ["src/**/*.test.{ts,tsx}"] }, });