diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml new file mode 100644 index 0000000..c242ab0 --- /dev/null +++ b/.github/actions/setup/action.yml @@ -0,0 +1,56 @@ +name: Build environment +description: > + System build tools, the pinned Rust toolchain and Bun, and the static media + engine (FFmpeg/mpv & co., scripts/build-media.sh) restored from cache or + built — everything the check and bundle jobs share. Runs on the Ubuntu + 24.04 and macOS 26 runners. + +runs: + using: composite + steps: + - name: System packages + if: runner.os == 'Linux' + shell: bash + run: | + sudo apt-get update + mapfile -t pkgs < <(sed -e 's/#.*//' packaging/ubuntu/packages.txt) + sudo apt-get install -y --no-install-recommends "${pkgs[@]}" + + # build-media.sh needs bash 4+ (assoc arrays); macOS ships 3.2 as + # /bin/bash. meson, nasm and pkg-config are not on the runner image. + - name: Build tools (Homebrew bash 5, meson, nasm, pkg-config) + if: runner.os == 'macOS' + shell: bash + run: brew install bash meson nasm pkg-config + + - name: Rust (rust-toolchain.toml) + shell: bash + run: rustup toolchain install + + - uses: oven-sh/setup-bun@v2 + with: + bun-version-file: package.json + + # FFmpeg/mpv & co. sources and static build, redone only when + # build-media.sh (tags, options) or the system packages change + - name: Media engine cache + uses: actions/cache@v6 + with: + path: | + third_party/src + third_party/prefix + key: ${{ runner.os == 'Linux' && format('media-ubuntu24.04-{0}', hashFiles('.github/workflows/ci.yml.bump', 'scripts/build-media.sh', 'packaging/ubuntu/packages.txt')) || format('media-macos-{0}-{1}', runner.arch, hashFiles('.github/workflows/ci.yml.bump', 'scripts/build-media.sh')) }} + + - name: Media engine + if: runner.os == 'Linux' + shell: bash + run: scripts/build-media.sh + + - name: Media engine (incl. the macOS static tail) + if: runner.os == 'macOS' + shell: bash + run: '"$(brew --prefix)/bin/bash" scripts/build-media.sh' + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: src-tauri diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0a4c751..8950644 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,35 +38,7 @@ jobs: steps: - uses: actions/checkout@v7 - - name: System packages - run: | - sudo apt-get update - mapfile -t pkgs < <(sed -e 's/#.*//' packaging/ubuntu/packages.txt) - sudo apt-get install -y --no-install-recommends "${pkgs[@]}" - - - name: Rust (rust-toolchain.toml) - run: rustup toolchain install - - - uses: oven-sh/setup-bun@v2 - with: - bun-version-file: package.json - - # FFmpeg/mpv & co. sources and static build, redone only when - # build-media.sh (tags, options) or the system packages change - - name: Media engine cache - uses: actions/cache@v6 - with: - path: | - third_party/src - third_party/prefix - key: media-ubuntu24.04-${{ hashFiles('.github/workflows/ci.yml.bump', 'scripts/build-media.sh', 'packaging/ubuntu/packages.txt') }} - - - name: Media engine - run: scripts/build-media.sh - - - uses: Swatinem/rust-cache@v2 - with: - workspaces: src-tauri + - uses: ./.github/actions/setup - name: Frontend run: | @@ -85,32 +57,7 @@ jobs: steps: - uses: actions/checkout@v7 - # build-media.sh needs bash 4+ (assoc arrays); macOS ships 3.2 as - # /bin/bash. meson, nasm and pkg-config are not on the runner image. - - name: Build tools (Homebrew bash 5, meson, nasm, pkg-config) - run: brew install bash meson nasm pkg-config - - - name: Rust (rust-toolchain.toml) - run: rustup toolchain install - - - uses: oven-sh/setup-bun@v2 - with: - bun-version-file: package.json - - - name: Media engine cache - uses: actions/cache@v6 - with: - path: | - third_party/src - third_party/prefix - key: media-macos-${{ runner.arch }}-${{ hashFiles('.github/workflows/ci.yml.bump', 'scripts/build-media.sh') }} - - - name: Media engine (incl. the macOS static tail) - run: '"$(brew --prefix)/bin/bash" scripts/build-media.sh' - - - uses: Swatinem/rust-cache@v2 - with: - workspaces: src-tauri + - uses: ./.github/actions/setup - name: Frontend run: | @@ -148,40 +95,15 @@ jobs: wait "$testpid" bundle: - if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main') + # version tags, pushes to main and manual runs + if: &bundle-trigger startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main') needs: check runs-on: ubuntu-24.04 timeout-minutes: 60 steps: - uses: actions/checkout@v7 - - name: System packages - run: | - sudo apt-get update - mapfile -t pkgs < <(sed -e 's/#.*//' packaging/ubuntu/packages.txt) - sudo apt-get install -y --no-install-recommends "${pkgs[@]}" - - - name: Rust (rust-toolchain.toml) - run: rustup toolchain install - - - uses: oven-sh/setup-bun@v2 - with: - bun-version-file: package.json - - - name: Media engine cache - uses: actions/cache@v6 - with: - path: | - third_party/src - third_party/prefix - key: media-ubuntu24.04-${{ hashFiles('.github/workflows/ci.yml.bump', 'scripts/build-media.sh', 'packaging/ubuntu/packages.txt') }} - - - name: Media engine - run: scripts/build-media.sh - - - uses: Swatinem/rust-cache@v2 - with: - workspaces: src-tauri + - uses: ./.github/actions/setup # one binary (glibc 2.39) as .deb, AppImage and .rpm — like # scripts/ubuntu-build.sh; the AppImage tools run without FUSE @@ -206,39 +128,14 @@ jobs: if-no-files-found: error bundle-macos: - if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main') + if: *bundle-trigger needs: check-macos runs-on: macos-26 timeout-minutes: 90 steps: - uses: actions/checkout@v7 - # build-media.sh needs bash 4+ (assoc arrays); macOS ships 3.2 as - # /bin/bash. meson, nasm and pkg-config are not on the runner image. - - name: Build tools (Homebrew bash 5, meson, nasm, pkg-config) - run: brew install bash meson nasm pkg-config - - - name: Rust (rust-toolchain.toml) - run: rustup toolchain install - - - uses: oven-sh/setup-bun@v2 - with: - bun-version-file: package.json - - - name: Media engine cache - uses: actions/cache@v6 - with: - path: | - third_party/src - third_party/prefix - key: media-macos-${{ runner.arch }}-${{ hashFiles('.github/workflows/ci.yml.bump', 'scripts/build-media.sh') }} - - - name: Media engine (incl. the macOS static tail) - run: '"$(brew --prefix)/bin/bash" scripts/build-media.sh' - - - uses: Swatinem/rust-cache@v2 - with: - workspaces: src-tauri + - uses: ./.github/actions/setup # Apple signing: import the certificate when the secrets are set; # otherwise fall back to ad-hoc signing so the app runs at all on @@ -407,7 +304,7 @@ jobs: # the same triggers as the other bundles; the action uploads # testpattern.flatpak as an artifact, which the release job picks up. flatpak: - if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main') + if: *bundle-trigger needs: check runs-on: ubuntu-24.04 timeout-minutes: 90 diff --git a/src-tauri/src/cast/commands.rs b/src-tauri/src/cast/commands.rs index fb691c5..9bb28db 100644 --- a/src-tauri/src/cast/commands.rs +++ b/src-tauri/src/cast/commands.rs @@ -1,6 +1,23 @@ //! The `cast_*` commands the UI drives casting with. -use super::*; +use std::sync::Arc; + +use parking_lot::Mutex; +use tauri::{AppHandle, Emitter, Manager, Runtime, State}; +use tokio::sync::mpsc; + +use crate::error::{Error, Result}; +use crate::playback::PlayRequest; +use crate::player::Player; +use crate::state::{AppState, read_blocking}; +use crate::{playback, settings}; + +use super::discovery::{search, start_browsing}; +use super::session::run; +use super::{ + Cast, CastState, Cmd, Device, Devices, Item, Meta, STATUS_EVENT, Session, Status, emit_devices, + probe, relay, remember, +}; /// The cast devices found so far; the first call starts looking /// (updates follow as `cast://devices`). @@ -8,7 +25,7 @@ use super::*; 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", + "Casting is unavailable: no network port could be opened".into(), )); } // mDNS is optional: the search by address finds TVs without it @@ -28,7 +45,7 @@ pub async fn cast_add_device( 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"))?; + .ok_or_else(|| Error::msg("Enter the TV's IP address, like 192.168.1.20".into()))?; 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." @@ -84,7 +101,7 @@ pub async fn cast_play( 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")), + (None, None) => return Err(Error::msg("Not casting".into())), (Some(_), None) => false, }; if reuse { @@ -99,7 +116,7 @@ pub async fn cast_play( return s .tx .send(Cmd::Load(item)) - .map_err(|_| Error::msg("The cast session has ended")); + .map_err(|_| Error::msg("The cast session has ended".into())); } let id = device_id.unwrap_or_default(); @@ -108,7 +125,7 @@ pub async fn cast_play( .lock() .get(&id) .cloned() - .ok_or_else(|| Error::msg("That TV is no longer on the network"))?; + .ok_or_else(|| Error::msg("That TV is no longer on the network".into()))?; if let Some(old) = session.take() { let _ = old.tx.send(Cmd::Stop); } @@ -116,7 +133,7 @@ pub async fn cast_play( let status = Arc::new(Mutex::new(Status { device_id: device.id.clone(), device_name: device.name.clone(), - state: "connecting", + state: CastState::Connecting, live: item.source.live, volume: 1.0, ..Default::default() diff --git a/src-tauri/src/cast/discovery.rs b/src-tauri/src/cast/discovery.rs index d816be9..ae0a8ee 100644 --- a/src-tauri/src/cast/discovery.rs +++ b/src-tauri/src/cast/discovery.rs @@ -1,7 +1,16 @@ //! Finding TVs: mDNS browsing, the remembered ones, and a sweep of the //! local networks by address. -use super::*; +use std::net::{IpAddr, SocketAddr}; +use std::sync::atomic::Ordering; +use std::time::Instant; + +use tauri::{AppHandle, Manager, Runtime}; + +use crate::error::{Error, Result}; +use crate::state::{AppState, read_blocking}; + +use super::{Cast, Device, SERVICE, SWEEP_EVERY, emit_devices, probe, remembered}; fn device_from(s: &mdns_sd::ResolvedService) -> Option { // capabilities bit 0: video out (speakers and speaker groups lack it) diff --git a/src-tauri/src/cast/mod.rs b/src-tauri/src/cast/mod.rs index cd6f821..ffc29ce 100644 --- a/src-tauri/src/cast/mod.rs +++ b/src-tauri/src/cast/mod.rs @@ -15,237 +15,8 @@ mod discovery; mod probe; mod relay; mod session; +mod types; pub use commands::*; -use discovery::{search, start_browsing}; -use session::run; -use std::collections::BTreeMap; -use std::net::{IpAddr, SocketAddr}; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::{Duration, Instant}; - -use parking_lot::Mutex; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use tauri::{AppHandle, Emitter, Manager, Runtime, State}; -use tokio::sync::mpsc; - -use crate::error::{Error, Result}; -use crate::playback::{self, PlayRequest}; -use crate::player::Player; -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"; -/// TVs that worked before (`[{id, name, ip}]`), checked first next time. -const REMEMBERED: &str = "cast.devices"; -/// The network sweep runs at most this often. -const SWEEP_EVERY: Duration = Duration::from_secs(60); -pub const STATUS_EVENT: &str = "cast://status"; - -/// Google's Default Media Receiver: no registration, plays MP4 by URL. -const DEFAULT_RECEIVER: &str = "CC1AD845"; -const SERVICE: &str = "_googlecast._tcp.local."; -/// The TV never asked for the stream within this time: it can't reach us. -const UNREACHABLE_AFTER: Duration = Duration::from_secs(20); -/// A live channel paused longer than this restarts at "now" on resume. -const LIVE_PAUSE_LIMIT: Duration = Duration::from_secs(20); - -/// The TV list and whether a search is still running (`cast://devices`). -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Devices { - pub devices: Vec, - pub searching: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct Remembered { - id: String, - name: String, - ip: IpAddr, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Device { - pub id: String, - pub name: String, - pub model: String, - #[serde(skip)] - addr: SocketAddr, - #[serde(skip)] - fullname: String, -} - -/// What the TV shows about the item. -#[derive(Debug, Clone, Default, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Meta { - pub title: Option, - pub subtitle: Option, - /// artwork URL (http/https only) - pub image: Option, -} - -#[derive(Debug, Clone, Default, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Status { - pub device_id: String, - pub device_name: String, - /// connecting | loading | buffering | playing | paused | ended | error (this - /// item failed, the session goes on) | stopped (the session is over; `error` - /// says why when it wasn't the user) - pub state: &'static str, - /// seconds into the item - pub position: f64, - /// 0 when unknown (live) - pub duration: f64, - pub live: bool, - /// the TV's volume, 0…1 - pub volume: f64, - pub muted: bool, - pub error: Option, -} - -impl Status { - fn finished(&self) -> bool { - self.state == "stopped" - } -} - -enum Cmd { - Load(Box), - Play, - Pause, - Seek(f64), - Volume(f64), - Mute(bool), - Stop, - /// the relay's first packet of item `generation`, URL `n` - Started(u64, u32, relay::Started), -} - -struct Item { - source: relay::Source, - meta: Meta, - start: f64, -} - -struct Session { - id: u64, - device: Device, - tx: mpsc::UnboundedSender, - status: Arc>, -} - -pub struct Cast { - relay: Option, - devices: Arc>>, - browser: Mutex>, - searching: Arc, - last_sweep: Mutex>, - session: Mutex>, - next_id: Mutex, -} - -pub fn init(app: &AppHandle) { - let relay = relay::Relay::start() - .map_err(|e| log::error!("cast relay unavailable: {e}")) - .ok(); - app.manage(Cast { - relay, - devices: Arc::default(), - browser: Mutex::new(None), - searching: Arc::default(), - last_sweep: Mutex::new(None), - session: Mutex::new(None), - next_id: Mutex::new(0), - }); -} - -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()) - } - - /// Ends the session, if one runs. - pub fn stop(&self) { - if let Some(s) = self.session.lock().take() { - let _ = s.tx.send(Cmd::Stop); - } - } - - 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")) - } - - 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), - } - } - - /// Adds or updates a device; true when the list changed. - fn found(&self, d: Device) -> bool { - let mut map = self.devices.lock(); - match map.get_mut(&d.id) { - // an mDNS entry keeps its service name (for its removal event) - Some(old) if old.name == d.name && old.addr == d.addr => false, - Some(old) => { - log::info!("cast: {} is now at {}", d.name, d.addr); - old.name = d.name; - old.addr = d.addr; - true - } - None => { - log::info!("cast: found {} at {}", d.name, d.addr); - map.insert(d.id.clone(), d); - true - } - } - } -} - -fn emit_devices(app: &AppHandle) { - if let Some(cast) = app.try_state::() { - let _ = app.emit(DEVICES_EVENT, cast.list()); - } -} - -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. -async fn remember(st: &AppState, d: &Device) { - let entry = Remembered { - id: d.id.clone(), - name: d.name.clone(), - ip: d.addr.ip(), - }; - 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); - } -} +pub use types::*; diff --git a/src-tauri/src/cast/session.rs b/src-tauri/src/cast/session.rs index 743a648..e9fa26d 100644 --- a/src-tauri/src/cast/session.rs +++ b/src-tauri/src/cast/session.rs @@ -1,7 +1,22 @@ //! 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::*; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use parking_lot::Mutex; +use serde_json::{Value, json}; +use tauri::{AppHandle, Emitter, Manager, Runtime}; +use tokio::sync::mpsc; + +use crate::state::AppState; + +use super::castv2::{Message, NS_CONNECTION, NS_HEARTBEAT, NS_MEDIA, NS_RECEIVER, RECEIVER}; +use super::{ + Cast, CastState, Cmd, DEFAULT_RECEIVER, Device, Item, LIVE_PAUSE_LIMIT, Meta, STATUS_EVENT, + Status, UNREACHABLE_AFTER, castv2, relay, remember, +}; struct Current { generation: u64, @@ -112,7 +127,6 @@ impl Conn { 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, @@ -183,10 +197,9 @@ impl Conn { "metadata": metadata, }, }); - let _ = &cast; self.media_time = 0.0; self.update(|s| { - s.state = "loading"; + s.state = CastState::Loading; s.position = start; }); self.request(&transport, NS_MEDIA, payload).await @@ -221,7 +234,7 @@ impl Conn { } (NS_CONNECTION, "CLOSE") if Some(&m.source) == self.transport.as_ref() => { self.update(|s| { - s.state = "stopped"; + s.state = CastState::Stopped; s.error = None; }); return Ok(Flow::End); @@ -258,7 +271,7 @@ impl Conn { // another app took over the TV, or the remote closed ours (None, Some(_)) => { self.update(|s| { - s.state = "stopped"; + s.state = CastState::Stopped; s.error = None; }); return Ok(Flow::End); @@ -268,7 +281,7 @@ impl Conn { } (NS_RECEIVER, "LAUNCH_ERROR") => { self.update(|s| { - s.state = "stopped"; + s.state = CastState::Stopped; s.error = Some("The TV could not start its media player".into()); }); return Ok(Flow::End); @@ -283,7 +296,7 @@ impl Conn { .relay_error() .unwrap_or_else(|| "The TV could not play this stream".into()); self.update(|s| { - s.state = "error"; + s.state = CastState::Error; s.error = Some(error); }); } @@ -299,72 +312,75 @@ impl Conn { 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", _) => { + let (live, reloads) = self + .current + .as_ref() + .map_or((false, 0), |c| (c.live, c.reloads)); + let player_state = ms["playerState"].as_str().unwrap_or(""); + let reason = ms["idleReason"].as_str().unwrap_or(""); + match media_transition(player_state, reason, live, reloads) { + Transition::None => {} + Transition::Playing => { if let Some(c) = self.current.as_mut() { c.paused_at = None; } self.update(|s| { - s.state = "playing"; + s.state = CastState::Playing; s.position = position; s.error = None; }); } - ("PAUSED", _) => { + Transition::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.state = CastState::Paused; s.position = position; }); } - ("BUFFERING", _) => self.update(|s| { - s.state = "buffering"; + Transition::Buffering => self.update(|s| { + s.state = CastState::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| { + Transition::ReloadLive => { + if let Some(c) = self.current.as_mut() { + c.reloads += 1; + } + self.load_at(0.0).await?; + } + Transition::LiveGaveUp => { + if let Some(c) = self.current.as_mut() { 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; - } - }); } + // 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 = CastState::Error; + s.error = Some(e); + } + None => { + s.state = CastState::Playing; + s.error = None; + } + }); } - ("IDLE", "FINISHED") => self.update(|s| { - s.state = "ended"; + Transition::Ended => self.update(|s| { + s.state = CastState::Ended; s.position = s.duration.max(position); }), - ("IDLE", "ERROR") => { + Transition::Failed => { let error = self .relay_error() .unwrap_or_else(|| "The TV could not play this stream".into()); self.update(|s| { - s.state = "error"; + s.state = CastState::Error; s.error = Some(error); }); } - _ => {} } Ok(Flow::Continue) } @@ -382,7 +398,7 @@ impl Conn { 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"; + let ended = self.status.lock().state == CastState::Ended; if stale || ended { // live: back to "now"; VOD at the end: from the start self.load_at(0.0).await?; @@ -433,7 +449,7 @@ impl Conn { .await; } self.update(|s| { - s.state = "stopped"; + s.state = CastState::Stopped; s.error = None; }); return Ok(Flow::End); @@ -462,11 +478,11 @@ impl Conn { async fn on_tick(&mut self) -> std::io::Result { let state = self.status.lock().state; - if matches!(state, "playing" | "buffering") { + if matches!(state, CastState::Playing | CastState::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 + !c.started && state == CastState::Loading && c.loaded_at.elapsed() > UNREACHABLE_AFTER }); if unreachable { let error = self.relay_error().unwrap_or_else(|| { @@ -475,7 +491,7 @@ impl Conn { .into() }); self.update(|s| { - s.state = "error"; + s.state = CastState::Error; s.error = Some(error); }); if let Some(c) = self.current.as_mut() { @@ -505,7 +521,7 @@ pub(super) async fn run( device.addr ); let mut s = status.lock(); - s.state = "stopped"; + s.state = CastState::Stopped; s.error = Some(format!("Can't connect to {}", device.name)); emit(&s); return; @@ -578,7 +594,7 @@ pub(super) async fn run( log::warn!("cast: connection to {} lost: {e}", c.device.name); c.update(|s| { if !s.finished() { - s.state = "stopped"; + s.state = CastState::Stopped; s.error = Some(format!("Lost the connection to {}", c.device.name)); } }); @@ -601,3 +617,97 @@ pub(super) async fn run( .await; log::info!("cast: session with {} ended", c.device.name); } + +/// Times a live channel that dropped is tuned in again before giving up. +const LIVE_RELOADS: u32 = 3; + +/// What a receiver `MEDIA_STATUS` means for the session. +#[derive(Debug, PartialEq, Eq)] +enum Transition { + None, + Playing, + Paused, + Buffering, + /// the live stream dropped: tune in again + ReloadLive, + /// the live stream dropped once too often + LiveGaveUp, + Ended, + Failed, +} + +/// `playerState`/`idleReason` of a media status → what to do. `reloads` is +/// how often the current live item was tuned in again already. +fn media_transition(player_state: &str, idle_reason: &str, live: bool, reloads: u32) -> Transition { + match (player_state, idle_reason) { + ("PLAYING", _) => Transition::Playing, + ("PAUSED", _) => Transition::Paused, + ("BUFFERING", _) => Transition::Buffering, + ("IDLE", "FINISHED" | "CANCELLED") if live => { + if reloads < LIVE_RELOADS { + Transition::ReloadLive + } else { + Transition::LiveGaveUp + } + } + ("IDLE", "FINISHED") => Transition::Ended, + ("IDLE", "ERROR") => Transition::Failed, + _ => Transition::None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn media_status_transitions() { + assert_eq!( + media_transition("PLAYING", "", false, 0), + Transition::Playing + ); + assert_eq!(media_transition("PAUSED", "", true, 0), Transition::Paused); + assert_eq!( + media_transition("BUFFERING", "", false, 0), + Transition::Buffering + ); + assert_eq!( + media_transition("IDLE", "FINISHED", false, 0), + Transition::Ended + ); + assert_eq!( + media_transition("IDLE", "CANCELLED", false, 0), + Transition::None + ); + assert_eq!( + media_transition("IDLE", "ERROR", false, 0), + Transition::Failed + ); + assert_eq!( + media_transition("IDLE", "ERROR", true, 0), + Transition::Failed + ); + assert_eq!(media_transition("", "", false, 0), Transition::None); + } + + #[test] + fn a_dropped_live_stream_is_reloaded_three_times() { + let attempts: Vec = (0..=LIVE_RELOADS) + .map(|reloads| media_transition("IDLE", "FINISHED", true, reloads)) + .collect(); + assert_eq!( + attempts, + vec![ + Transition::ReloadLive, + Transition::ReloadLive, + Transition::ReloadLive, + Transition::LiveGaveUp + ] + ); + assert_eq!( + media_transition("IDLE", "CANCELLED", true, 0), + Transition::ReloadLive, + "a receiver that cancels a live stream is retried too" + ); + } +} diff --git a/src-tauri/src/cast/types.rs b/src-tauri/src/cast/types.rs new file mode 100644 index 0000000..31d6321 --- /dev/null +++ b/src-tauri/src/cast/types.rs @@ -0,0 +1,245 @@ +//! The cast session's shared shapes: devices, status, the commands the +//! session task takes, and the managed `Cast` state. + +use crate::error::{Error, Result}; +use crate::settings; +use crate::state::{AppState, write_blocking}; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::collections::BTreeMap; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; +use tauri::{AppHandle, Emitter, Manager, Runtime}; +use tokio::sync::mpsc; + +use super::relay; + +pub const DEVICES_EVENT: &str = "cast://devices"; +/// TVs that worked before (`[{id, name, ip}]`), checked first next time. +pub(super) const REMEMBERED: &str = "cast.devices"; +/// The network sweep runs at most this often. +pub(super) const SWEEP_EVERY: Duration = Duration::from_secs(60); +pub const STATUS_EVENT: &str = "cast://status"; + +/// Google's Default Media Receiver: no registration, plays MP4 by URL. +pub(super) const DEFAULT_RECEIVER: &str = "CC1AD845"; +pub(super) const SERVICE: &str = "_googlecast._tcp.local."; +/// The TV never asked for the stream within this time: it can't reach us. +pub(super) const UNREACHABLE_AFTER: Duration = Duration::from_secs(20); +/// A live channel paused longer than this restarts at "now" on resume. +pub(super) const LIVE_PAUSE_LIMIT: Duration = Duration::from_secs(20); + +/// The TV list and whether a search is still running (`cast://devices`). +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Devices { + pub devices: Vec, + pub searching: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(super) struct Remembered { + pub(super) id: String, + pub(super) name: String, + pub(super) ip: IpAddr, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Device { + pub id: String, + pub name: String, + pub model: String, + #[serde(skip)] + pub(super) addr: SocketAddr, + #[serde(skip)] + pub(super) fullname: String, +} + +/// What the TV shows about the item. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Meta { + pub title: Option, + pub subtitle: Option, + /// artwork URL (http/https only) + pub image: Option, +} + +/// Where a cast session is (`cast://status`). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum CastState { + #[default] + Connecting, + Loading, + Buffering, + Playing, + Paused, + Ended, + /// this item failed; the session goes on + Error, + /// the session is over; `Status::error` says why when it wasn't the user + Stopped, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Status { + pub device_id: String, + pub device_name: String, + pub state: CastState, + /// seconds into the item + pub position: f64, + /// 0 when unknown (live) + pub duration: f64, + pub live: bool, + /// the TV's volume, 0…1 + pub volume: f64, + pub muted: bool, + pub error: Option, +} + +impl Status { + pub(super) fn finished(&self) -> bool { + self.state == CastState::Stopped + } +} + +pub(super) enum Cmd { + Load(Box), + Play, + Pause, + Seek(f64), + Volume(f64), + Mute(bool), + Stop, + /// the relay's first packet of item `generation`, URL `n` + Started(u64, u32, relay::Started), +} + +pub(super) struct Item { + pub(super) source: relay::Source, + pub(super) meta: Meta, + pub(super) start: f64, +} + +pub(super) struct Session { + pub(super) id: u64, + pub(super) device: Device, + pub(super) tx: mpsc::UnboundedSender, + pub(super) status: Arc>, +} + +pub struct Cast { + pub(super) relay: Option, + pub(super) devices: Arc>>, + pub(super) browser: Mutex>, + pub(super) searching: Arc, + pub(super) last_sweep: Mutex>, + pub(super) session: Mutex>, + pub(super) next_id: Mutex, +} + +pub fn init(app: &AppHandle) { + let relay = relay::Relay::start() + .map_err(|e| log::error!("cast relay unavailable: {e}")) + .ok(); + app.manage(Cast { + relay, + devices: Arc::default(), + browser: Mutex::new(None), + searching: Arc::default(), + last_sweep: Mutex::new(None), + session: Mutex::new(None), + next_id: Mutex::new(0), + }); +} + +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()) + } + + /// Ends the session, if one runs. + pub fn stop(&self) { + if let Some(s) = self.session.lock().take() { + let _ = s.tx.send(Cmd::Stop); + } + } + + pub(super) fn send(&self, cmd: Cmd) -> Result<()> { + let guard = self.session.lock(); + let s = guard + .as_ref() + .ok_or_else(|| Error::msg("Not casting".into()))?; + s.tx.send(cmd) + .map_err(|_| Error::msg("The cast session has ended".into())) + } + + pub(super) 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), + } + } + + /// Adds or updates a device; true when the list changed. + pub(super) fn found(&self, d: Device) -> bool { + let mut map = self.devices.lock(); + match map.get_mut(&d.id) { + // an mDNS entry keeps its service name (for its removal event) + Some(old) if old.name == d.name && old.addr == d.addr => false, + Some(old) => { + log::info!("cast: {} is now at {}", d.name, d.addr); + old.name = d.name; + old.addr = d.addr; + true + } + None => { + log::info!("cast: found {} at {}", d.name, d.addr); + map.insert(d.id.clone(), d); + true + } + } + } +} + +pub(super) fn emit_devices(app: &AppHandle) { + if let Some(cast) = app.try_state::() { + let _ = app.emit(DEVICES_EVENT, cast.list()); + } +} + +pub(super) 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. +pub(super) async fn remember(st: &AppState, d: &Device) { + let entry = Remembered { + id: d.id.clone(), + name: d.name.clone(), + ip: d.addr.ip(), + }; + 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); + } +} diff --git a/src-tauri/src/catalog/categories.rs b/src-tauri/src/catalog/categories.rs index b4a1612..b50d98d 100644 --- a/src-tauri/src/catalog/categories.rs +++ b/src-tauri/src/catalog/categories.rs @@ -1,11 +1,19 @@ //! Category lists of each kind (the browse sidebars). -use super::*; +use rusqlite::params; +use tauri::State; + +use crate::error::{Error, Result}; +use crate::kind::ItemKind; +use crate::settings; +use crate::state::{AppState, read_blocking}; + +use super::{CategoryItem, split_badges}; #[tauri::command] pub async fn categories(state: State<'_, AppState>, kind: ItemKind) -> Result> { if kind == ItemKind::Episode { - return Err(Error::msg("episodes have no categories")); + return Err(Error::msg("episodes have no categories".into())); } let table = kind.table(); read_blocking(state.inner(), move |conn| { diff --git a/src-tauri/src/catalog/channels.rs b/src-tauri/src/catalog/channels.rs index c18697a..dfbe96f 100644 --- a/src-tauri/src/catalog/channels.rs +++ b/src-tauri/src/catalog/channels.rs @@ -1,7 +1,22 @@ //! Live channels: listings with now/next, channel groups and their feeds, and //! the Live page's country/genre navigation. -use super::*; +use std::collections::HashMap; +use std::time::Instant; + +use rusqlite::types::Value as Sql; +use rusqlite::{Connection, OptionalExtension, Row}; +use serde::Serialize; +use tauri::State; + +use crate::db::now; +use crate::error::{Error, Result}; +use crate::settings; +use crate::state::{AppState, read_blocking}; +use crate::works::versions; + +use super::types::like_pattern; +use super::{Brief, ChannelItem, ChannelQuery, GroupInfo, Page, split_badges}; /// Channel rows with now/next. `grouped`: one row per channel group, /// titled as the group and playing its chosen variant (`g.source_id`/ @@ -444,6 +459,7 @@ pub async fn channel_variants( #[cfg(test)] mod tests { use super::*; + use rusqlite::params; #[test] fn a_country_lists_its_guide_channels_first() { diff --git a/src-tauri/src/catalog/details.rs b/src-tauri/src/catalog/details.rs index 464a16b..3542770 100644 --- a/src-tauri/src/catalog/details.rs +++ b/src-tauri/src/catalog/details.rs @@ -1,7 +1,27 @@ //! Movie and series detail pages: every copy's provider details, the chosen //! version, episodes and where to resume; plus "up next". -use super::*; +use std::collections::{BTreeMap, HashMap}; + +use rusqlite::{Connection, OptionalExtension, params}; +use serde::Serialize; +use serde_json::Value; +use tauri::State; + +use crate::db::now; +use crate::error::{Error, Result}; +use crate::kind::{ItemKind, ItemRef, WorkKind}; +use crate::sources; +use crate::sources::SourceKind; +use crate::state::{AppState, read_blocking, write_blocking}; +use crate::util::json::{f64_of, first_str, i64_of, str_of}; +use crate::works::versions; +use crate::works::versions::VersionInfo; + +use super::{ + MovieItem, SeriesItem, episode_history_filter, movie_by_item, movie_by_key, series_by_item, + series_by_key, +}; const MOVIE_DETAIL_TTL: i64 = 7 * 86400; const SERIES_DETAIL_TTL: i64 = 12 * 3600; @@ -128,7 +148,7 @@ async fn provider_detail( { return Ok(Some(c.json.clone())); } - let fetched = match sources::xtream_for(&src, http_client(src.user_agent.as_deref())) { + let fetched = match sources::xtream_for(&src, st.client(src.user_agent.as_deref())) { Ok(x) => match kind { WorkKind::Movie => x.vod_info(id).await, WorkKind::Series => x.series_info(id).await, @@ -167,16 +187,11 @@ const DETAIL_DEADLINE: std::time::Duration = std::time::Duration::from_millis(25 /// 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) { +async fn details_of(st: &AppState, kind: WorkKind, copies: &[ItemRef], ttl: i64) -> Details { let mut handles: Vec>>>> = copies .iter() - .map(|(sid, id)| { - let (st, sid, id) = (st.clone(), *sid, id.clone()); + .map(|c| { + let (st, sid, id) = (st.clone(), c.source_id, c.id.clone()); Some(tokio::spawn(async move { match provider_detail(&st, sid, kind, &id, ttl).await { // M3U series: episodes come from the playlist @@ -198,8 +213,8 @@ async fn details_of( 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), + Ok(Err(e)) => log::warn!("{kind} {}: no provider detail ({e})", copies[i].id), + Err(e) => log::warn!("{kind} {}: detail task failed ({e})", copies[i].id), } } } @@ -218,18 +233,37 @@ async fn details_of( } // the others keep filling the cache in the background drop(rest); - return (out, idx.len() > 1); + return Details { + per_copy: out, + pending: idx.len() > 1, + }; } } - let pending = handles.iter().any(Option::is_some); - (out, pending) + Details { + pending: handles.iter().any(Option::is_some), + per_copy: out, + } +} + +/// What `details_of` got: one provider payload per copy (None: none yet). +struct Details { + per_copy: Vec>, + /// some copies are still loading in the background + pending: bool, +} + +fn copies_of(members: &[versions::Member]) -> Vec { + members + .iter() + .map(|m| ItemRef::new(m.source_id, m.id.clone())) + .collect() } /// 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)>, + pref: Option, langs: Vec<&'static str>, key: Option, } @@ -279,13 +313,7 @@ pub async fn movie_detail( 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()?, + Some(k) => movie_by_key(conn, k)?, None => None, }; let facts = match (&ctx.key, &work) { @@ -304,44 +332,24 @@ pub async fn movie_detail( .await? }; // provider details of every copy at once (cached for a week) - let copies: Vec<(i64, String)> = members + let details = details_of(&st, WorkKind::Movie, &copies_of(&members), MOVIE_DETAIL_TTL).await; + let infos: Vec = details + .per_copy .iter() - .map(|m| (m.source_id, m.id.clone())) + .map(|d| d.as_ref().map_or(Value::Null, |d| d["info"].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 sel = choose_movie_copy(&members, pref.as_ref(), &langs, &infos, &tracks); let chosen = members[sel].clone(); - let info = info_of(sel); + let info = &infos[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))) + first_str(info, keys).or_else(|| infos.iter().find_map(|i| first_str(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}"))) + movie_by_item(conn, sid, &mid)?.ok_or_else(|| Error::NotFound(format!("movie {mid}"))) }) .await? }; @@ -359,30 +367,18 @@ pub async fn movie_detail( 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() + .zip(&infos) + .zip(&tracks) .enumerate() - .map(|(i, m)| { + .map(|(i, ((m, inf), tracks))| { 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.duration = duration_of(inf); + v.tracks = tracks.clone(); v }) .collect(); @@ -404,27 +400,65 @@ pub async fn movie_detail( } }; Ok(MovieDetail { - versions_pending: pending, + versions_pending: details.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), + duration: duration_of(info), backdrop: first_url(&info["backdrop_path"]) - .or_else(|| (0..members.len()).find_map(|i| first_url(&info_of(i)["backdrop_path"]))), + .or_else(|| infos.iter().find_map(|i| first_url(&i["backdrop_path"]))), trailer, age_rating: pick(&["mpaa_rating", "age"]), video: tech(&info["video"]), audio: tech(&info["audio"]), - position, + position: movie_resume_position(&members, &chosen), versions, tmdb: facts, item, }) } +/// A copy's running time from its provider `info`, when it has one. +fn duration_of(info: &Value) -> Option { + i64_of(&info["duration_secs"]).filter(|d| *d > 0) +} + +/// Which copy of a movie plays: the user's pick, else the best fit. A copy +/// much shorter than the others is a trailer or cut off, and one that failed +/// to play is ruled out. +fn choose_movie_copy( + members: &[versions::Member], + pref: Option<&ItemRef>, + langs: &[&'static str], + infos: &[Value], + tracks: &[Option], +) -> usize { + let durations: Vec> = infos.iter().map(duration_of).collect(); + let longest = durations.iter().flatten().copied().max().unwrap_or(0); + versions::choose(members, pref, langs, |i| match durations[i] { + _ if versions::unavailable(tracks[i].as_ref()) => versions::BROKEN, + Some(d) if longest > 0 => d as f64 / longest as f64, + _ => 1.0, + }) +} + +/// Where a movie resumes: the chosen copy's own position, else where any +/// copy was left off unfinished (versions are the same film). +fn movie_resume_position(members: &[versions::Member], chosen: &versions::Member) -> f64 { + if chosen.position > 0.0 { + return chosen.position; + } + members + .iter() + .filter(|m| m.played_at > 0) + .max_by_key(|m| m.played_at) + .filter(|m| !m.watched) + .map_or(0.0, |m| m.position) +} + #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct Episode { @@ -687,18 +721,8 @@ fn up_next_rows(conn: &Connection, limit: usize) -> Result> { } 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()?, + Some(k) => series_by_key(conn, k)?, + None => series_by_item(conn, sid, &series_id)?, }; let Some(series) = series else { continue }; let per_copy: Vec<_> = members @@ -745,10 +769,12 @@ fn up_next_rows(conn: &Connection, limit: usize) -> Result> { } 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))", + &format!( + "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 {}", + episode_history_filter(3, 4, 5) + ), params![next.season, next.episode, key, sid, series_id], |r| r.get::<_, Option>(0), )? @@ -842,62 +868,20 @@ pub async fn series_detail( 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()?, + Some(k) => series_by_key(conn, k)?, 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()? + None => series_by_item(conn, source_id, &id)? .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 text = series_text(conn, source_id, &id)?; + let history = watch_history(conn, key.as_deref(), source_id, &id)?; let facts = match &key { - Some(k) => crate::tmdb::facts_for(conn, WorkKind::Series, k, &work.title, work.year)?, + Some(k) => { + crate::tmdb::facts_for(conn, WorkKind::Series, k, &work.title, work.year)? + } None => None, }; Ok((ctx, work, text, history, facts)) @@ -906,12 +890,15 @@ pub async fn series_detail( }; // 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 + let fetched = details_of( + &st, + WorkKind::Series, + &copies_of(&members), + SERIES_DETAIL_TTL, + ) + .await; + let details: Vec = fetched + .per_copy .into_iter() .map(|d| d.unwrap_or(Value::Null)) .collect(); @@ -922,47 +909,12 @@ pub async fn series_detail( .collect(); let counts: Vec = per_copy .iter() - .map(|seasons| { - seasons - .iter() - .filter(|(n, _)| *n > 0) - .map(|(_, e)| e.len()) - .sum() - }) + .map(|seasons| episode_count(seasons)) .collect(); + let tracks = copy_tracks(&st, &members, &per_copy).await?; 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]) { + if versions::unavailable(tracks[i].as_ref()) { versions::BROKEN } else { counts[i] as f64 / most as f64 @@ -980,31 +932,197 @@ pub async fn series_detail( ) }); let union = union_episodes(&per_copy, &order); + let state_of = latest_watch_state(&history, &per_copy); + let seasons = build_seasons(&union, &state_of, &members, sel, &order, &details); + let resume = resume_point(&seasons, &history, &per_copy); + + 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(); - // 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 + let mut item = work; + if item.backdrop.is_none() { + item.backdrop = order .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, + .find_map(|&i| first_url(&details[i]["info"]["backdrop_path"])); + } + let info = &details[sel]["info"]; + Ok(SeriesDetail { + versions_pending: fetched.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, + }) +} + +/// Long texts of a series: the requested copy, else any copy that has them. +fn series_text(conn: &Connection, source_id: i64, id: &str) -> Result { + Ok(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)?, }) - }; + }, + )?) +} + +/// Watch state of every episode of a show, across all its copies. +fn watch_history( + conn: &Connection, + key: Option<&str>, + source_id: i64, + id: &str, +) -> Result> { + Ok(conn + .prepare_cached(&format!( + "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 {}", + episode_history_filter(1, 2, 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::>()?) +} + +/// Regular episodes of one copy (specials, season 0, don't count). +fn episode_count(seasons: &[(i64, Vec)]) -> usize { + seasons + .iter() + .filter(|(n, _)| *n > 0) + .map(|(_, e)| e.len()) + .sum() +} + +/// Episodes probed per copy when looking for its stored tracks. +const TRACK_LOOKUP_EPISODES: usize = 40; + +/// Tracks seen in each copy (the first of its episodes with any). +async fn copy_tracks( + st: &AppState, + members: &[versions::Member], + per_copy: &[Vec<(i64, Vec)>], +) -> Result>> { + 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(TRACK_LOOKUP_EPISODES) + .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 +} + +/// A history row's (season, episode): by the episode id in its copy, else +/// the numbers stored with it. +fn number_of(w: &Watched, per_copy: &[Vec<(i64, Vec)>]) -> 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, + }) +} + +/// The newest history row per (season, episode). +fn latest_watch_state<'h>( + history: &'h [Watched], + per_copy: &[Vec<(i64, Vec)>], +) -> HashMap<(i64, i64), &'h Watched> { let mut state_of: HashMap<(i64, i64), &Watched> = HashMap::new(); - for w in &history { - if let Some(k) = number_of(w) + for w in history { + if let Some(k) = number_of(w, per_copy) && state_of.get(&k).is_none_or(|prev| w.at > prev.at) { state_of.insert(k, w); } } + state_of +} +/// The episode union as seasons, with watch state and, for episodes that +/// play from another copy, that copy's label. Season names and art come +/// from the selected copy, else any copy (in `order`). +fn build_seasons( + union: &BTreeMap<(i64, i64), (usize, Episode)>, + state_of: &HashMap<(i64, i64), &Watched>, + members: &[versions::Member], + sel: usize, + order: &[usize], + details: &[Value], +) -> Vec { let mut seasons: Vec = Vec::new(); - for ((s_no, _), (copy, e)) in &union { + 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; @@ -1016,7 +1134,6 @@ pub async fn series_detail( 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() @@ -1040,95 +1157,45 @@ pub async fn series_detail( } } } + seasons +} - // Resume: the most recent unfinished episode, else the one after the - // most recently finished, else S1E1 — across all copies. +/// Resume: the most recent unfinished episode, else the one after the most +/// recently finished, else S1E1 — across all copies. +fn resume_point( + seasons: &[Season], + history: &[Watched], + per_copy: &[Vec<(i64, Vec)>], +) -> Option { let flat: Vec<&Episode> = seasons .iter() .filter(|s| s.season > 0) .flat_map(|s| &s.episodes) .collect(); + let at = |e: &Episode, position: f64, started: bool| Resume { + episode_id: e.id.clone(), + season: e.season, + episode: e.episode, + position, + started, + }; let latest = history .iter() - .filter_map(|w| number_of(w).map(|k| (k, w))) + .filter_map(|w| number_of(w, per_copy).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, - }) - } + match latest { + Some((k, w)) if !w.watched => flat + .iter() + .find(|e| (e.season, e.episode) == k) + .map(|e| at(e, w.position, 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, - }), + .map(|e| at(e, 0.0, 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, - }) + .or_else(|| flat.first().map(|e| at(e, 0.0, false))) } #[cfg(test)] @@ -1352,4 +1419,80 @@ pub(super) mod tests { finish(5, 300); assert!(next(&c).is_empty()); } + + fn ep(id: &str, season: i64, episode: i64) -> Episode { + Episode { + id: id.into(), + season, + episode, + title: String::new(), + plot: None, + duration: None, + image: None, + ext: None, + rating: None, + air_date: None, + video: None, + position: 0.0, + watched: false, + source_id: 1, + series_id: "s".into(), + version: None, + } + } + + fn watched(id: &str, season: i64, episode: i64, position: f64, done: bool, at: i64) -> Watched { + Watched { + source_id: 1, + id: id.into(), + season: Some(season), + episode: Some(episode), + position, + watched: done, + at, + } + } + + #[test] + fn resume_point_picks_unfinished_then_next_then_first() { + let season = |n: i64, eps: Vec| Season { + season: n, + name: String::new(), + cover: None, + overview: None, + air_date: None, + episodes: eps, + }; + // specials never count as "the first episode" + let seasons = vec![ + season(0, vec![ep("sp", 0, 1)]), + season(1, vec![ep("a", 1, 1), ep("b", 1, 2), ep("c", 1, 3)]), + ]; + let resume = |history: &[Watched]| { + resume_point(&seasons, history, &[]).map(|r| (r.episode_id, r.position, r.started)) + }; + assert_eq!( + resume(&[]), + Some(("a".into(), 0.0, false)), + "nothing watched: S1E1" + ); + assert_eq!( + resume(&[watched("b", 1, 2, 42.0, false, 10)]), + Some(("b".into(), 42.0, true)), + "the latest episode is unfinished: resume it" + ); + assert_eq!( + resume(&[ + watched("b", 1, 2, 0.0, true, 10), + watched("a", 1, 1, 5.0, false, 5) + ]), + Some(("c".into(), 0.0, true)), + "the latest episode was finished: the one after it" + ); + assert_eq!( + resume(&[watched("c", 1, 3, 0.0, true, 10)]), + Some(("a".into(), 0.0, false)), + "the last episode was finished: back to the start" + ); + } } diff --git a/src-tauri/src/catalog/guide.rs b/src-tauri/src/catalog/guide.rs index 5565b9f..a7428be 100644 --- a/src-tauri/src/catalog/guide.rs +++ b/src-tauri/src/catalog/guide.rs @@ -1,6 +1,19 @@ //! Programme guide: one channel's programmes and the guide grid. -use super::*; +use base64::Engine; +use rusqlite::{OptionalExtension, params}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tauri::State; + +use crate::epg::ProgrammeRow; +use crate::error::Result; +use crate::sources::SourceKind; +use crate::state::{AppState, read_blocking}; +use crate::util::json::{i64_of, str_of}; +use crate::{epg, sources}; + +use super::{ChannelItem, ChannelQuery, Page, query_channels}; #[tauri::command] pub async fn epg_channel( @@ -39,7 +52,7 @@ pub async fn epg_channel( if src.kind != SourceKind::Xtream { return Ok(rows); } - let Ok(x) = sources::xtream_for(&src, http_client(src.user_agent.as_deref())) else { + let Ok(x) = sources::xtream_for(&src, st.client(src.user_agent.as_deref())) else { return Ok(rows); }; let v = match x.short_epg(&channel_id, 24).await { diff --git a/src-tauri/src/catalog/mod.rs b/src-tauri/src/catalog/mod.rs index 59ffe78..6fcc095 100644 --- a/src-tauri/src/catalog/mod.rs +++ b/src-tauri/src/catalog/mod.rs @@ -6,6 +6,7 @@ mod channels; mod details; mod guide; mod search; +mod types; mod works; pub use categories::*; @@ -13,251 +14,5 @@ pub use channels::*; pub use details::*; pub use guide::*; pub use search::*; +pub use types::*; 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 index 4ca7cf5..f7ef270 100644 --- a/src-tauri/src/catalog/search.rs +++ b/src-tauri/src/catalog/search.rs @@ -1,6 +1,20 @@ //! Full-text search over channels, movies and series. -use super::*; +use std::time::Instant; + +use rusqlite::{OptionalExtension, params}; +use serde::Serialize; +use tauri::State; + +use crate::error::Result; +use crate::kind::{ItemKind, WorkKind}; +use crate::settings; +use crate::state::{AppState, read_blocking}; + +use super::{ + ChannelItem, MovieItem, SeriesItem, channel_by_id, channel_group_by_key, movie_by_key, + series_by_key, +}; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -93,22 +107,12 @@ pub async fn search( 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); - } - } + for key in works(WorkKind::Movie)? { + movies.extend(movie_by_key(conn, &key)?); } 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); - } - } + for key in works(WorkKind::Series)? { + series.extend(series_by_key(conn, &key)?); } log::debug!("search {q:?}: {}/{}/{} in {:?}", channels.len(), movies.len(), series.len(), t.elapsed()); Ok(SearchResults { channels, movies, series }) diff --git a/src-tauri/src/catalog/types.rs b/src-tauri/src/catalog/types.rs new file mode 100644 index 0000000..906c83a --- /dev/null +++ b/src-tauri/src/catalog/types.rs @@ -0,0 +1,231 @@ +//! Shapes the catalog commands share (list items, queries, pages) and +//! small helpers over them. + +use serde::{Deserialize, Serialize}; + +#[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, +} + +pub(super) 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, +} + +pub(super) 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 +} + +pub(super) 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/works.rs b/src-tauri/src/catalog/works.rs index 85bdcd0..ffaa8a3 100644 --- a/src-tauri/src/catalog/works.rs +++ b/src-tauri/src/catalog/works.rs @@ -1,6 +1,19 @@ //! Movie and series listings (one row per work) and their browse facets. -use super::*; +use std::time::Instant; + +use rusqlite::types::Value as Sql; +use rusqlite::{Connection, OptionalExtension, Row, params, params_from_iter}; +use serde::Serialize; +use tauri::State; + +use crate::error::{Error, Result}; +use crate::kind::WorkKind; +use crate::settings; +use crate::state::{AppState, read_blocking}; + +use super::types::{FACETS, like_pattern, work_info}; +use super::{MediaQuery, MovieItem, Page, SeriesItem}; /// One movie copy with its work's grouping info. pub(super) const MOVIE_SELECT: &str = " @@ -93,6 +106,64 @@ pub(super) fn row_to_series(r: &Row) -> rusqlite::Result { }) } +/// The movie work `key` (browse-list shape). +pub(super) fn movie_by_key(conn: &Connection, key: &str) -> Result> { + Ok(conn + .prepare_cached(&format!( + "{} WHERE w.kind = 'movie' AND w.key = ?1", + movie_work_select() + ))? + .query_row([key], row_to_movie) + .optional()?) +} + +/// One movie copy. +pub(super) fn movie_by_item( + conn: &Connection, + source_id: i64, + id: &str, +) -> Result> { + Ok(conn + .prepare_cached(&format!( + "{MOVIE_SELECT} WHERE m.source_id = ?1 AND m.id = ?2" + ))? + .query_row(params![source_id, id], row_to_movie) + .optional()?) +} + +/// The series work `key` (browse-list shape). +pub(super) fn series_by_key(conn: &Connection, key: &str) -> Result> { + Ok(conn + .prepare_cached(&format!( + "{SERIES_WORK_SELECT} WHERE w.kind = 'series' AND w.key = ?1" + ))? + .query_row([key], row_to_series) + .optional()?) +} + +/// One series copy. +pub(super) fn series_by_item( + conn: &Connection, + source_id: i64, + id: &str, +) -> Result> { + Ok(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()?) +} + +/// Episode history rows of a show, all copies counted as one: `?{k}` is the +/// work key (may be NULL), `?{s}`/`?{i}` the copy's source id and series id. +/// Expects `history h` joined to `series s` on the episode's series. +pub(super) fn episode_history_filter(k: usize, s: usize, i: usize) -> String { + format!( + "((?{k} IS NOT NULL AND s.work_key = ?{k}) OR (h.source_id = ?{s} AND h.series_id = ?{i}))" + ) +} + /// 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 @@ -424,6 +495,7 @@ pub fn facets_for(conn: &Connection, kind: WorkKind, q: &MediaQuery) -> Result 0); + assert!(n > 0, "no programmes parsed from the file"); } } diff --git a/src-tauri/src/error.rs b/src-tauri/src/error.rs index 5eb819c..e2564f1 100644 --- a/src-tauri/src/error.rs +++ b/src-tauri/src/error.rs @@ -23,6 +23,11 @@ pub enum Error { /// one failed title. #[error("TMDB did not accept the API key")] TmdbRejected, + /// The macOS keychain is locked (or can't prompt); callers skip it + /// instead of failing. + #[cfg(target_os = "macos")] + #[error("keyring: the keychain is locked")] + KeyringLocked, } impl From for Error { @@ -43,8 +48,8 @@ impl From for Error { } impl Error { - pub fn msg(m: impl Into) -> Self { - Error::Msg(m.into()) + pub fn msg(m: String) -> Self { + Error::Msg(m) } } diff --git a/src-tauri/src/images.rs b/src-tauri/src/images.rs index bfb5683..6fe4ef9 100644 --- a/src-tauri/src/images.rs +++ b/src-tauri/src/images.rs @@ -380,7 +380,14 @@ mod tests { bytes: 80 * 1024 } ); - assert!(!dir.join("old").exists() && dir.join("mid").exists() && dir.join("new").exists()); + assert!( + !dir.join("old").exists(), + "the oldest file is evicted first" + ); + assert!( + dir.join("mid").exists() && dir.join("new").exists(), + "newer files stay" + ); // clear assert_eq!(prune(&dir, 0, now).unwrap(), CacheStats::default()); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/src-tauri/src/kind.rs b/src-tauri/src/kind.rs index d28b981..769a25b 100644 --- a/src-tauri/src/kind.rs +++ b/src-tauri/src/kind.rs @@ -75,6 +75,19 @@ impl From for ItemKind { } } +/// One catalog row: the source it came from and the provider's id there. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ItemRef { + pub source_id: i64, + pub id: String, +} + +impl ItemRef { + pub fn new(source_id: i64, id: String) -> Self { + ItemRef { source_id, id } + } +} + /// 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")] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f884906..b7bef92 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -33,6 +33,12 @@ 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); +/// Starts the app and blocks until it quits. +/// +/// # Panics +/// +/// When the Tauri runtime fails to start, or `tauri.conf.json` has no +/// "main" window. pub fn run() { env_logger::Builder::from_env( env_logger::Env::default().default_filter_or("info,testpattern_lib=debug"), @@ -68,12 +74,7 @@ pub fn run() { if let Err(e) = works::rebuild_if_stale(&mut db.write()) { log::error!("regrouping the catalog failed: {e}"); } - let st: state::AppState = Arc::new(state::App { - db, - http: state::http_client(None), - cache_dir, - syncing: Default::default(), - }); + let st: state::AppState = Arc::new(state::App::new(db, cache_dir)); app.manage(st.clone()); app.manage(Arc::new(probe::Probe::default())); @@ -87,39 +88,7 @@ pub fn run() { #[cfg(debug_assertions)] dev_hooks(app); - // 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(CACHE_LIMIT_DELAY).await; - let mut tick = tokio::time::interval(CACHE_LIMIT_EVERY); - loop { - tick.tick().await; - images::enforce_limit(cache_state.clone()).await; - } - }); - - // 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(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(STALE_CHECK_EVERY); - tick.tick().await; - loop { - 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; - } - }); + spawn_background_jobs(app.handle(), st); window.show()?; Ok(()) @@ -182,6 +151,44 @@ pub fn run() { .expect("error while running testpattern"); } +/// Long-running upkeep: the artwork cache limit, TMDB details and fresh +/// catalogs/guides. +fn spawn_background_jobs(app: &tauri::AppHandle, st: state::AppState) { + // 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(CACHE_LIMIT_DELAY).await; + let mut tick = tokio::time::interval(CACHE_LIMIT_EVERY); + loop { + tick.tick().await; + images::enforce_limit(cache_state.clone()).await; + } + }); + + // TMDB details of titles added since the last run (tmdb.rs), after + // startup settled; syncs start further runs. + let (tmdb_app, tmdb_state) = (app.clone(), st.clone()); + tauri::async_runtime::spawn(async move { + 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.clone(); + tauri::async_runtime::spawn(async move { + secrets::startup(&st).await; + let mut tick = tokio::time::interval(STALE_CHECK_EVERY); + tick.tick().await; + loop { + 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; + } + }); +} + #[cfg(debug_assertions)] fn dev_hooks(app: &mut tauri::App) { devtools::start(app.handle()); diff --git a/src-tauri/src/library.rs b/src-tauri/src/library.rs index fcc90f8..721d2fc 100644 --- a/src-tauri/src/library.rs +++ b/src-tauri/src/library.rs @@ -37,7 +37,7 @@ pub fn toggle_favorite( "DELETE FROM favorite WHERE source_id = ?1 AND kind = ?2 AND item_id = ?3", params![source_id, kind, item_id], )?, - ItemKind::Episode => return Err(Error::msg("cannot favorite an episode")), + ItemKind::Episode => return Err(Error::msg("cannot favorite an episode".into())), ItemKind::Movie | ItemKind::Series => conn.execute( &format!( "DELETE FROM favorite WHERE kind = ?2 AND ( diff --git a/src-tauri/src/playback.rs b/src-tauri/src/playback.rs index 2eb1df4..f41dc1a 100644 --- a/src-tauri/src/playback.rs +++ b/src-tauri/src/playback.rs @@ -12,7 +12,7 @@ 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, read_blocking, write_blocking}; +use crate::state::{AppState, read_blocking, write_blocking}; use crate::util::json::i64_of; use crate::{library, settings}; @@ -74,7 +74,7 @@ pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { 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::Xtream => Some(sources::xtream_url_builder(&src)?), SourceKind::M3u => None, }; @@ -99,7 +99,7 @@ pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { 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")), + (None, None) => return Err(Error::msg("channel has no stream url".into())), }; (url, row) } @@ -121,7 +121,7 @@ pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { 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")), + (None, None) => return Err(Error::msg("movie has no stream url".into())), }; (url, row) } @@ -141,14 +141,14 @@ pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { let url = row .url .clone() - .ok_or_else(|| Error::msg("episode has no stream url"))?; + .ok_or_else(|| Error::msg("episode has no stream url".into()))?; (url, row) } }, PlayKind::Catchup => { let start = req .catchup_start - .ok_or_else(|| Error::msg("missing catch-up start"))?; + .ok_or_else(|| Error::msg("missing catch-up start".into()))?; let minutes = req.catchup_minutes.unwrap_or(60).max(1); match &x { Some(x) => { @@ -161,7 +161,7 @@ pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { start + offset + src.catchup_shift_minutes * 60, 0, ) - .ok_or_else(|| Error::msg("bad catch-up time"))? + .ok_or_else(|| Error::msg("bad catch-up time".into()))? .naive_utc(); (x.timeshift_url(&req.id, local, minutes), ItemRow::default()) } @@ -196,7 +196,7 @@ pub fn resolve(conn: &Connection, req: &PlayRequest) -> Result { src.catchup_shift_minutes * 60, ) }) - .ok_or_else(|| Error::msg("This channel does not offer catch-up"))?; + .ok_or_else(|| Error::msg("This channel does not offer catch-up".into()))?; (url, row) } } diff --git a/src-tauri/src/player/mod.rs b/src-tauri/src/player/mod.rs index 030ff0f..7a330f5 100644 --- a/src-tauri/src/player/mod.rs +++ b/src-tauri/src/player/mod.rs @@ -13,6 +13,7 @@ mod render; use std::path::{Path, PathBuf}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; use parking_lot::Mutex; @@ -29,7 +30,7 @@ use mpv_sys::{ }; pub const EVENT: &str = "player://event"; -pub const USER_AGENT: &str = concat!("testpattern/", env!("CARGO_PKG_VERSION")); +pub use crate::state::DEFAULT_USER_AGENT as USER_AGENT; /// `time-pos` changes every frame; ~5 Hz is plenty for the UI. const TIME_POS_INTERVAL: Duration = Duration::from_millis(200); @@ -99,6 +100,9 @@ pub struct LoadOptions { #[derive(Default)] struct Session { + /// Which `load` opened this session; a delayed reconnect only reloads + /// while the session it was scheduled for is still the current one. + generation: u64, url: String, options: LoadOptions, /// Same stream on mirror servers, tried if the first open fails. @@ -163,6 +167,8 @@ pub fn file_name_for(title: &str) -> String { pub struct Player { mpv: Arc, session: Arc>>, + /// Source of `Session::generation`. + generations: AtomicU64, } const OBSERVED: &[(&str, mpv_format)] = &[ @@ -247,6 +253,7 @@ impl Player { let player = Player { mpv, session: Arc::new(Mutex::new(None)), + generations: AtomicU64::new(0), }; player.spawn_event_loop(app.clone()); Ok(player) @@ -377,7 +384,7 @@ impl Player { /// Live streams drop all the time; transparently re-open them a few times. fn maybe_reconnect( mpv: &Arc, - session: &Mutex>, + session: &Arc>>, reason: EndReason, ) -> Option { if !matches!(reason, EndReason::Eof | EndReason::Error) { @@ -420,13 +427,19 @@ impl Player { let _ = mpv.set_string("stream-record", &rec.file().to_string_lossy()); } let attempt = s.reconnects; + let generation = s.generation; let url = s.url.clone(); let opts = file_options(&s.options); drop(guard); - let mpv = mpv.clone(); + let (mpv, session) = (mpv.clone(), session.clone()); std::thread::spawn(move || { std::thread::sleep(RECONNECT_BACKOFF_STEP * attempt); - let _ = mpv.command_async(&["loadfile", &url, "replace", "-1", &opts]); + // the user may have switched channel or stopped meanwhile; hold + // the lock while loading so a new `load` can't slip in between + let guard = session.lock(); + if guard.as_ref().is_some_and(|s| s.generation == generation) { + let _ = mpv.command_async(&["loadfile", &url, "replace", "-1", &opts]); + } }); Some(attempt) } @@ -445,6 +458,7 @@ impl Player { // a new stream ends any recording (mpv would record it into the same file) let _ = self.mpv.set_string("stream-record", ""); *self.session.lock() = Some(Session { + generation: self.generations.fetch_add(1, Ordering::Relaxed) + 1, url: url.to_owned(), options, alternates, @@ -640,7 +654,7 @@ pub fn player_load( options: Option, ) -> crate::error::Result<()> { if !(url.starts_with("http://") || url.starts_with("https://")) { - return Err(Error::msg("only http(s) streams can be loaded")); + return Err(Error::msg("only http(s) streams can be loaded".into())); } player .load(&url, options.unwrap_or_default()) diff --git a/src-tauri/src/probe.rs b/src-tauri/src/probe.rs index d9280bc..5df4d8c 100644 --- a/src-tauri/src/probe.rs +++ b/src-tauri/src/probe.rs @@ -207,7 +207,7 @@ pub async fn version_probe( }; if player.busy() || casting() { return Err(Error::msg( - "Stop playback first: the account allows one stream at a time", + "Stop playback first: the account allows one stream at a time".into(), )); } let st = state.inner().clone(); @@ -242,7 +242,7 @@ pub async fn version_probe( }) .collect(); if reqs.is_empty() { - return Err(Error::msg("This version has no episodes yet")); + return Err(Error::msg("This version has no episodes yet".into())); } (reqs, ItemKind::Episode) } diff --git a/src-tauri/src/secrets.rs b/src-tauri/src/secrets.rs index 5087c2e..2636585 100644 --- a/src-tauri/src/secrets.rs +++ b/src-tauri/src/secrets.rs @@ -30,6 +30,10 @@ pub const UNAVAILABLE: &str = "The password is stored in the system keyring, whi /// setting that holds one when there is no keyring → the entry's label. pub const NAMED: &[(&str, &str)] = &[(crate::tmdb::KEY_SETTING, "TMDB API key")]; +// The two caches mirror the system keyring, which is process-wide itself; +// they're read deep inside database closures (`sources::load`, `tmdb::key`) +// that only get a connection, so they stay statics rather than `App` fields. + /// Passwords read from the keyring, by source id. static CACHE: LazyLock>> = LazyLock::new(Default::default); /// `NAMED` secrets read from the keyring, by setting key. @@ -80,7 +84,7 @@ impl Unlock { async fn timed(unlock: Unlock, call: impl Future>) -> Result { tokio::time::timeout(unlock.timeout(), call) .await - .map_err(|_| Error::msg("keyring: no answer in time"))? + .map_err(|_| Error::msg("keyring: no answer in time".into()))? } /// A random id per profile, so two profiles (e.g. the test one) never share @@ -193,7 +197,7 @@ mod backend { let item = match (found.unlocked.first(), found.locked.first()) { (Some(item), _) => item, (None, Some(_)) if unlock == Unlock::Never => { - return Err(Error::msg("keyring: locked")); + return Err(Error::msg("keyring: locked".into())); } (None, Some(item)) => { ss.unlock_all(&[item]).await.map_err(err)?; @@ -214,7 +218,7 @@ mod backend { .map_err(err)?; if !found.locked.is_empty() { if unlock == Unlock::Never { - return Err(Error::msg("keyring: locked")); + return Err(Error::msg("keyring: locked".into())); } ss.unlock_all(&found.locked.iter().collect::>()) .await @@ -239,6 +243,7 @@ mod backend { use super::{Entry, Unlock}; use crate::error::{Error, Result}; + use crate::state::run_blocking; fn err(e: impl std::fmt::Display) -> Error { Error::msg(format!("keyring: {e}")) @@ -280,7 +285,7 @@ mod backend { /// Is this error one we returned for a locked keychain? fn is_error_locked(e: &Error) -> bool { - e.to_string().contains("keychain is locked") + matches!(e, Error::KeyringLocked) } fn not_found(stderr: &str) -> bool { @@ -322,7 +327,7 @@ mod backend { return Ok(None); } if is_locked(out.status.code(), &stderr) { - return Err(err("the keychain is locked")); + return Err(Error::KeyringLocked); } Err(err(stderr.trim())) } @@ -344,11 +349,15 @@ mod backend { return Ok(false); } if is_locked(out.status.code(), &stderr) { - return Err(err("the keychain is locked")); + return Err(Error::KeyringLocked); } Err(err(stderr.trim())) } + // `security` is a blocking subprocess (and `unlock-keychain` may wait on + // the user): every call runs on the blocking pool, so the runtime keeps + // going and `timed()` can actually give up on it. + pub async fn store( profile: &str, entry: Entry<'_>, @@ -365,17 +374,20 @@ mod backend { } add.push("-w".into()); add.push(password.into()); - // unlock-keychain prompts when locked; skip it for Unlock::Never - if unlock == Unlock::Never { - match run(vec!["show-keychain-info".into()]) { - Ok(_) => {} - Err(e) if is_error_locked(&e) => return Ok(false), - Err(e) => return Err(e), // a real failure, not "locked" + run_blocking(move || { + // unlock-keychain prompts when locked; skip it for Unlock::Never + if unlock == Unlock::Never { + match run(vec!["show-keychain-info".into()]) { + Ok(_) => {} + Err(e) if is_error_locked(&e) => return Ok(false), + Err(e) => return Err(e), // a real failure, not "locked" + } + } else { + let _ = run(vec!["unlock-keychain".into()]); // may prompt; ignore outcome } - } else { - let _ = run(vec!["unlock-keychain".into()]); // may prompt; ignore outcome - } - run(add) + run(add) + }) + .await? } pub async fn load(profile: &str, entry: Entry<'_>, unlock: Unlock) -> Result> { @@ -384,7 +396,7 @@ mod backend { .into_iter() .filter(|(k, _)| *k != "-l") .collect(); - match sec(&a, "find-generic-password") { + run_blocking(move || match sec(&a, "find-generic-password") { Err(e) if unlock == Unlock::Prompt && is_error_locked(&e) => { // only now that a lookup failed on a locked keychain: unlock // (may prompt once), then retry @@ -392,20 +404,23 @@ mod backend { sec(&a, "find-generic-password") } r => r, - } + }) + .await? } pub async fn delete(profile: &str, entry: Entry<'_>, unlock: Unlock) -> Result<()> { - if unlock != Unlock::Never { - let _ = run(vec!["unlock-keychain".into()]); - } - let a = attrs(profile, entry, ""); let mut d: Vec = vec!["delete-generic-password".into()]; - for (k, v) in a.iter().filter(|(k, _)| *k != "-l") { + for (k, v) in attrs(profile, entry, "").iter().filter(|(k, _)| *k != "-l") { d.push((*k).to_string()); d.push(v.to_string()); } - run(d).map(|_| ()) + run_blocking(move || { + if unlock != Unlock::Never { + let _ = run(vec!["unlock-keychain".into()]); + } + run(d).map(|_| ()) + }) + .await? } } @@ -416,10 +431,10 @@ mod backend { use crate::error::{Error, Result}; pub async fn store(_: &str, _: Entry<'_>, _: &str, _: &str, _: Unlock) -> Result { - Err(Error::msg("keyring: not supported on this platform")) + Err(Error::msg("keyring: not supported on this platform".into())) } pub async fn load(_: &str, _: Entry<'_>, _: Unlock) -> Result> { - Err(Error::msg("keyring: not supported on this platform")) + Err(Error::msg("keyring: not supported on this platform".into())) } pub async fn delete(_: &str, _: Entry<'_>, _: Unlock) -> Result<()> { Ok(()) @@ -877,7 +892,8 @@ mod tests { // runner alike — every `security` call that has to open a locked // keychain (even `show-keychain-info`) routes through a // SecurityAgent password dialog and blocks the run until a human - // answers; tokio's timeout cannot preempt it (PL-113). Which + // answers; a timeout only abandons the `security` child, which + // still holds the runtime's shutdown (PL-113). Which // failures map to "locked" is covered by // keychain_locked_marker_classification below. }); diff --git a/src-tauri/src/sources/commands.rs b/src-tauri/src/sources/commands.rs index 7a33dbf..30b01fd 100644 --- a/src-tauri/src/sources/commands.rs +++ b/src-tauri/src/sources/commands.rs @@ -1,6 +1,18 @@ //! The Sources page: list, test, add, update and remove sources. -use super::*; +use rusqlite::params; +use serde::Serialize; +use tauri::{AppHandle, Runtime, State}; + +use crate::db::now; +use crate::error::{Error, Result}; +use crate::state::{AppState, read_blocking, write_blocking}; + +use super::xtream::{AccountInfo, Xtream}; +use super::{ + SourceInput, SourceKind, SourceView, SyncScope, default_name, download_text, load, load_all, + m3u, normalize_input, spawn_sync, view, +}; #[tauri::command] pub async fn sources_list(state: State<'_, AppState>) -> Result> { @@ -49,7 +61,7 @@ pub async fn source_test( { 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)); + return Err(Error::msg(crate::secrets::UNAVAILABLE.into())); } input.password = src.password; } @@ -60,17 +72,20 @@ pub async fn source_test( &input.alt_urls, input.username.as_deref().unwrap_or(""), input.password.as_deref().unwrap_or(""), - http_client(input.user_agent.as_deref()), + state.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 text = + download_text(&state.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")); + return Err(Error::msg( + "The playlist is empty or not an M3U file".into(), + )); } let mut c = (0, 0, 0); for e in &pl.entries { @@ -112,7 +127,7 @@ pub async fn source_add( catchup_shift_minutes) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", params![ - input.kind.as_str(), + input.kind, name.trim(), input.url, serde_json::to_string(&input.alt_urls)?, @@ -162,7 +177,7 @@ pub async fn source_update( epg_url = ?8, user_agent = ?9, catchup_shift_minutes = ?10 WHERE id = ?1", params![ id, - input.kind.as_str(), + input.kind, name, input.url, serde_json::to_string(&input.alt_urls)?, diff --git a/src-tauri/src/sources/mod.rs b/src-tauri/src/sources/mod.rs index 61554a2..1796d65 100644 --- a/src-tauri/src/sources/mod.rs +++ b/src-tauri/src/sources/mod.rs @@ -5,270 +5,10 @@ mod commands; pub mod m3u; mod store; mod sync; +mod types; 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; - -use rusqlite::{Connection, OptionalExtension, Transaction, params}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; -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, 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}; - -pub const SYNC_EVENT: &str = "sync://progress"; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum SourceKind { - Xtream, - M3u, -} - -impl SourceKind { - fn as_str(self) -> &'static str { - match self { - SourceKind::Xtream => "xtream", - SourceKind::M3u => "m3u", - } - } - fn parse(s: &str) -> Self { - if s == "m3u" { - SourceKind::M3u - } else { - SourceKind::Xtream - } - } -} - -/// Full source row (backend only — includes the password). -#[derive(Debug, Clone)] -pub struct SourceRow { - pub id: i64, - pub kind: SourceKind, - pub name: String, - pub url: String, - pub alt_urls: Vec, - pub username: Option, - pub password: Option, - pub epg_url: Option, - pub user_agent: Option, - pub created_at: i64, - pub last_sync: Option, - pub last_epg_sync: Option, - pub sync_error: Option, - pub account: Option, - /// Catch-up time correction (T-048). - pub catchup_shift_minutes: i64, - /// The password lives in the desktop keyring (secrets.rs), not here. - pub password_in_keyring: bool, -} - -/// What the UI sees (no password). -#[derive(Debug, Clone, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct SourceView { - pub id: i64, - pub kind: SourceKind, - pub name: String, - pub url: String, - pub alt_urls: Vec, - pub username: Option, - pub has_password: bool, - pub epg_url: Option, - pub user_agent: Option, - pub created_at: i64, - pub last_sync: Option, - pub last_epg_sync: Option, - pub sync_error: Option, - pub account: Option, - pub catchup_shift_minutes: i64, - pub password_in_keyring: bool, - /// In the keyring, but the keyring was locked or unavailable so far. - pub password_locked: bool, - pub syncing: bool, - pub counts: Counts, -} - -#[derive(Debug, Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Counts { - pub channels: i64, - pub movies: i64, - pub series: i64, - pub programmes: i64, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SourceInput { - pub kind: SourceKind, - pub name: Option, - pub url: String, - #[serde(default)] - pub alt_urls: Vec, - pub username: Option, - pub password: Option, - pub epg_url: Option, - pub user_agent: Option, - /// Catch-up time correction in minutes; `None` keeps the stored value. - pub catchup_shift_minutes: Option, -} - -#[derive(Debug, Clone, Serialize)] -#[serde( - rename_all = "camelCase", - rename_all_fields = "camelCase", - tag = "stage" -)] -pub enum SyncProgress { - Started { source_id: i64 }, - Step { source_id: i64, message: String }, - Done { source_id: i64, counts: Counts }, - Failed { source_id: i64, error: String }, -} - -const SOURCE_COLS: &str = "id, kind, name, url, alt_urls, username, password, epg_url, user_agent, \ - created_at, last_sync, last_epg_sync, sync_error, account_json, catchup_shift_minutes, password_in_keyring"; - -fn row_to_source(r: &rusqlite::Row) -> rusqlite::Result { - let alt: String = r.get(4)?; - let account: Option = r.get(13)?; - let id: i64 = r.get(0)?; - let password_in_keyring: bool = r.get(15)?; - Ok(SourceRow { - id, - kind: SourceKind::parse(&r.get::<_, String>(1)?), - name: r.get(2)?, - url: r.get(3)?, - alt_urls: serde_json::from_str(&alt).unwrap_or_default(), - username: r.get(5)?, - // keyring passwords come from the cache secrets::startup filled - password: if password_in_keyring { - crate::secrets::cached(id) - } else { - r.get(6)? - }, - epg_url: r.get(7)?, - user_agent: r.get(8)?, - created_at: r.get(9)?, - last_sync: r.get(10)?, - last_epg_sync: r.get(11)?, - sync_error: r.get(12)?, - account: account.and_then(|a| serde_json::from_str(&a).ok()), - catchup_shift_minutes: r.get(14)?, - password_in_keyring, - }) -} - -pub fn load(conn: &Connection, id: i64) -> Result { - conn.query_row( - &format!("SELECT {SOURCE_COLS} FROM source WHERE id = ?1"), - [id], - row_to_source, - ) - .optional()? - .ok_or_else(|| Error::NotFound(format!("source {id}"))) -} - -pub fn load_all(conn: &Connection) -> Result> { - let mut stmt = conn.prepare(&format!("SELECT {SOURCE_COLS} FROM source ORDER BY id"))?; - let rows = stmt - .query_map([], row_to_source)? - .collect::, _>>()?; - Ok(rows) -} - -fn counts(conn: &Connection, id: i64) -> Result { - let one = |sql: &str| -> Result { Ok(conn.query_row(sql, [id], |r| r.get(0))?) }; - Ok(Counts { - channels: one("SELECT COUNT(*) FROM channel WHERE source_id = ?1 AND separator = 0")?, - movies: one("SELECT COUNT(*) FROM movie WHERE source_id = ?1")?, - series: one("SELECT COUNT(*) FROM series WHERE source_id = ?1")?, - programmes: one("SELECT COUNT(*) FROM programme WHERE source_id = ?1")?, - }) -} - -fn view(conn: &Connection, s: SourceRow, syncing: bool) -> Result { - let counts = counts(conn, s.id)?; - Ok(SourceView { - id: s.id, - kind: s.kind, - name: s.name, - url: s.url, - alt_urls: s.alt_urls, - username: s.username, - has_password: s.password_in_keyring || s.password.as_deref().is_some_and(|p| !p.is_empty()), - epg_url: s.epg_url, - user_agent: s.user_agent, - created_at: s.created_at, - last_sync: s.last_sync, - last_epg_sync: s.last_epg_sync, - sync_error: s.sync_error, - account: s.account, - catchup_shift_minutes: s.catchup_shift_minutes, - password_in_keyring: s.password_in_keyring, - password_locked: s.password_in_keyring && s.password.is_none(), - syncing, - counts, - }) -} - -/// Xtream playlist links pasted as "M3U" are upgraded to full Xtream sources. -fn normalize_input(mut input: SourceInput) -> Result { - input.url = input.url.trim().to_owned(); - if input.url.is_empty() { - return Err(Error::msg("Please enter a server or playlist URL")); - } - if input.kind == SourceKind::M3u - && let Some((base, user, pass)) = xtream::parse_playlist_url(&input.url) - { - input.kind = SourceKind::Xtream; - input.url = base; - input.username = Some(user); - input.password = Some(pass); - } - if input.kind == SourceKind::Xtream { - input.url = xtream::normalize_base(&input.url); - if input.username.as_deref().unwrap_or("").trim().is_empty() { - return Err(Error::msg("Username is required")); - } - } - input.alt_urls = input - .alt_urls - .iter() - .map(|u| u.trim()) - .filter(|u| !u.is_empty()) - .map(|u| { - if input.kind == SourceKind::Xtream { - xtream::normalize_base(u) - } else { - u.to_owned() - } - }) - .collect(); - Ok(input) -} - -fn default_name(input: &SourceInput) -> String { - let host = url::Url::parse(&input.url) - .ok() - .and_then(|u| u.host_str().map(str::to_owned)) - .unwrap_or_else(|| input.url.clone()); - match input.kind { - SourceKind::Xtream => host, - SourceKind::M3u => format!("{host} playlist"), - } -} +pub use types::*; diff --git a/src-tauri/src/sources/store.rs b/src-tauri/src/sources/store.rs index 697abaa..1677a21 100644 --- a/src-tauri/src/sources/store.rs +++ b/src-tauri/src/sources/store.rs @@ -1,7 +1,19 @@ //! Writing a downloaded catalog into the database (one transaction per //! source: replaced wholesale, details of items still listed kept). -use super::*; +use std::collections::{HashMap, HashSet}; + +use rusqlite::{Connection, Transaction, params}; +use serde_json::Value; + +use crate::error::Result; +use crate::kind::ItemKind; +use crate::names; +use crate::util::fnv1a; +use crate::util::json::{first_str, i64_of, str_of}; + +use super::m3u; +use super::xtream::rating_of; /// The six lists an Xtream panel serves (`get_*_categories`, `get_*_streams`, /// `get_series`). diff --git a/src-tauri/src/sources/sync.rs b/src-tauri/src/sources/sync.rs index 04b12bc..4a69cc4 100644 --- a/src-tauri/src/sources/sync.rs +++ b/src-tauri/src/sources/sync.rs @@ -1,7 +1,20 @@ //! Syncing a source: download its lists (or playlist) into the catalog, //! then its guide; and the periodic refresh of stale sources. -use super::*; +use std::collections::HashSet; +use std::time::Duration; + +use rusqlite::params; +use tauri::{AppHandle, Emitter, Runtime}; + +use crate::db::now; +use crate::error::{Error, Result}; +use crate::state::{AppState, read_blocking, run_blocking, write_blocking}; +use crate::util::json::str_of; + +use super::store::{XtreamLists, write_m3u, write_xtream}; +use super::xtream::Xtream; +use super::{Counts, SYNC_EVENT, SourceKind, SourceRow, SyncProgress, counts, load, load_all, m3u}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SyncScope { @@ -95,7 +108,7 @@ async fn run_sync( scope: SyncScope, ) -> Result { let src = read_blocking(st, move |conn| load(conn, id)).await?; - let client = http_client(src.user_agent.as_deref()); + let client = st.client(src.user_agent.as_deref()); let mut epg_urls: Vec = src.epg_url.iter().cloned().collect(); if scope == SyncScope::Full { @@ -157,7 +170,9 @@ async fn run_sync( 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")); + return Err(Error::msg( + "The playlist is empty or not an M3U file".into(), + )); } step(app, id, &format!("Saving {} entries…", pl.entries.len())); if epg_urls.is_empty() { @@ -203,9 +218,17 @@ async fn run_sync( read_blocking(st, move |conn| counts(conn, id)).await } +/// An `Xtream` that only builds stream URLs (playback), never fetches: +/// shares one idle client instead of building one per play. +pub fn xtream_url_builder(src: &SourceRow) -> Result { + static IDLE: std::sync::LazyLock = + std::sync::LazyLock::new(reqwest::Client::new); + xtream_for(src, IDLE.clone()) +} + 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)); + return Err(Error::msg(crate::secrets::UNAVAILABLE.into())); } // prefer the mirror that answered last time let preferred = src.account.as_ref().and_then(|a| str_of(&a["baseUrl"])); @@ -279,7 +302,7 @@ async fn sync_epg( Err(e) => last_err = Some(e), } } - Err(last_err.unwrap_or_else(|| Error::msg("no guide url"))) + Err(last_err.unwrap_or_else(|| Error::msg("no guide url".into()))) } /// Streams a download into `path` (constant memory). diff --git a/src-tauri/src/sources/types.rs b/src-tauri/src/sources/types.rs new file mode 100644 index 0000000..5bbc283 --- /dev/null +++ b/src-tauri/src/sources/types.rs @@ -0,0 +1,265 @@ +//! Source rows and what the UI sees of them; loading and validating them. + +use crate::error::{Error, Result}; +use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; +use rusqlite::{Connection, OptionalExtension}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::xtream; + +pub const SYNC_EVENT: &str = "sync://progress"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SourceKind { + Xtream, + M3u, +} + +impl SourceKind { + pub(super) fn as_str(self) -> &'static str { + match self { + SourceKind::Xtream => "xtream", + SourceKind::M3u => "m3u", + } + } +} + +impl ToSql for SourceKind { + fn to_sql(&self) -> rusqlite::Result> { + Ok(ToSqlOutput::from(self.as_str())) + } +} + +impl FromSql for SourceKind { + fn column_result(v: ValueRef<'_>) -> FromSqlResult { + match v.as_str()? { + "xtream" => Ok(SourceKind::Xtream), + "m3u" => Ok(SourceKind::M3u), + other => Err(FromSqlError::Other( + format!("unknown source kind {other:?}").into(), + )), + } + } +} + +/// Full source row (backend only — includes the password). +#[derive(Debug, Clone)] +pub struct SourceRow { + pub id: i64, + pub kind: SourceKind, + pub name: String, + pub url: String, + pub alt_urls: Vec, + pub username: Option, + pub password: Option, + pub epg_url: Option, + pub user_agent: Option, + pub created_at: i64, + pub last_sync: Option, + pub last_epg_sync: Option, + pub sync_error: Option, + pub account: Option, + /// Catch-up time correction (T-048). + pub catchup_shift_minutes: i64, + /// The password lives in the desktop keyring (secrets.rs), not here. + pub password_in_keyring: bool, +} + +/// What the UI sees (no password). +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceView { + pub id: i64, + pub kind: SourceKind, + pub name: String, + pub url: String, + pub alt_urls: Vec, + pub username: Option, + pub has_password: bool, + pub epg_url: Option, + pub user_agent: Option, + pub created_at: i64, + pub last_sync: Option, + pub last_epg_sync: Option, + pub sync_error: Option, + pub account: Option, + pub catchup_shift_minutes: i64, + pub password_in_keyring: bool, + /// In the keyring, but the keyring was locked or unavailable so far. + pub password_locked: bool, + pub syncing: bool, + pub counts: Counts, +} + +#[derive(Debug, Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Counts { + pub channels: i64, + pub movies: i64, + pub series: i64, + pub programmes: i64, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceInput { + pub kind: SourceKind, + pub name: Option, + pub url: String, + #[serde(default)] + pub alt_urls: Vec, + pub username: Option, + pub password: Option, + pub epg_url: Option, + pub user_agent: Option, + /// Catch-up time correction in minutes; `None` keeps the stored value. + pub catchup_shift_minutes: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde( + rename_all = "camelCase", + rename_all_fields = "camelCase", + tag = "stage" +)] +pub enum SyncProgress { + Started { source_id: i64 }, + Step { source_id: i64, message: String }, + Done { source_id: i64, counts: Counts }, + Failed { source_id: i64, error: String }, +} + +pub(super) const SOURCE_COLS: &str = "id, kind, name, url, alt_urls, username, password, epg_url, user_agent, \ + created_at, last_sync, last_epg_sync, sync_error, account_json, catchup_shift_minutes, password_in_keyring"; + +pub(super) fn row_to_source(r: &rusqlite::Row) -> rusqlite::Result { + let alt: String = r.get(4)?; + let account: Option = r.get(13)?; + let id: i64 = r.get(0)?; + let password_in_keyring: bool = r.get(15)?; + Ok(SourceRow { + id, + kind: r.get(1)?, + name: r.get(2)?, + url: r.get(3)?, + alt_urls: serde_json::from_str(&alt).unwrap_or_default(), + username: r.get(5)?, + // keyring passwords come from the cache secrets::startup filled + password: if password_in_keyring { + crate::secrets::cached(id) + } else { + r.get(6)? + }, + epg_url: r.get(7)?, + user_agent: r.get(8)?, + created_at: r.get(9)?, + last_sync: r.get(10)?, + last_epg_sync: r.get(11)?, + sync_error: r.get(12)?, + account: account.and_then(|a| serde_json::from_str(&a).ok()), + catchup_shift_minutes: r.get(14)?, + password_in_keyring, + }) +} + +pub fn load(conn: &Connection, id: i64) -> Result { + conn.query_row( + &format!("SELECT {SOURCE_COLS} FROM source WHERE id = ?1"), + [id], + row_to_source, + ) + .optional()? + .ok_or_else(|| Error::NotFound(format!("source {id}"))) +} + +pub fn load_all(conn: &Connection) -> Result> { + let mut stmt = conn.prepare(&format!("SELECT {SOURCE_COLS} FROM source ORDER BY id"))?; + let rows = stmt + .query_map([], row_to_source)? + .collect::, _>>()?; + Ok(rows) +} + +pub(super) fn counts(conn: &Connection, id: i64) -> Result { + let one = |sql: &str| -> Result { Ok(conn.query_row(sql, [id], |r| r.get(0))?) }; + Ok(Counts { + channels: one("SELECT COUNT(*) FROM channel WHERE source_id = ?1 AND separator = 0")?, + movies: one("SELECT COUNT(*) FROM movie WHERE source_id = ?1")?, + series: one("SELECT COUNT(*) FROM series WHERE source_id = ?1")?, + programmes: one("SELECT COUNT(*) FROM programme WHERE source_id = ?1")?, + }) +} + +pub(super) fn view(conn: &Connection, s: SourceRow, syncing: bool) -> Result { + let counts = counts(conn, s.id)?; + Ok(SourceView { + id: s.id, + kind: s.kind, + name: s.name, + url: s.url, + alt_urls: s.alt_urls, + username: s.username, + has_password: s.password_in_keyring || s.password.as_deref().is_some_and(|p| !p.is_empty()), + epg_url: s.epg_url, + user_agent: s.user_agent, + created_at: s.created_at, + last_sync: s.last_sync, + last_epg_sync: s.last_epg_sync, + sync_error: s.sync_error, + account: s.account, + catchup_shift_minutes: s.catchup_shift_minutes, + password_in_keyring: s.password_in_keyring, + password_locked: s.password_in_keyring && s.password.is_none(), + syncing, + counts, + }) +} + +/// Xtream playlist links pasted as "M3U" are upgraded to full Xtream sources. +pub(super) fn normalize_input(mut input: SourceInput) -> Result { + input.url = input.url.trim().to_owned(); + if input.url.is_empty() { + return Err(Error::msg("Please enter a server or playlist URL".into())); + } + if input.kind == SourceKind::M3u + && let Some((base, user, pass)) = xtream::parse_playlist_url(&input.url) + { + input.kind = SourceKind::Xtream; + input.url = base; + input.username = Some(user); + input.password = Some(pass); + } + if input.kind == SourceKind::Xtream { + input.url = xtream::normalize_base(&input.url); + if input.username.as_deref().unwrap_or("").trim().is_empty() { + return Err(Error::msg("Username is required".into())); + } + } + input.alt_urls = input + .alt_urls + .iter() + .map(|u| u.trim()) + .filter(|u| !u.is_empty()) + .map(|u| { + if input.kind == SourceKind::Xtream { + xtream::normalize_base(u) + } else { + u.to_owned() + } + }) + .collect(); + Ok(input) +} + +pub(super) fn default_name(input: &SourceInput) -> String { + let host = url::Url::parse(&input.url) + .ok() + .and_then(|u| u.host_str().map(str::to_owned)) + .unwrap_or_else(|| input.url.clone()); + match input.kind { + SourceKind::Xtream => host, + SourceKind::M3u => format!("{host} playlist"), + } +} diff --git a/src-tauri/src/sources/xtream.rs b/src-tauri/src/sources/xtream.rs index 3b6809a..f8be1ec 100644 --- a/src-tauri/src/sources/xtream.rs +++ b/src-tauri/src/sources/xtream.rs @@ -194,7 +194,7 @@ impl Xtream { Err(e) => last_err = Some(e.into()), } } - Err(last_err.unwrap_or_else(|| Error::msg("no server configured"))) + Err(last_err.unwrap_or_else(|| Error::msg("no server configured".into()))) } pub async fn account(&self) -> Result { @@ -202,7 +202,9 @@ impl Xtream { 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) { - return Err(Error::msg("Login failed — check the username and password")); + return Err(Error::msg( + "Login failed — check the username and password".into(), + )); } let status = str_of(&ui["status"]).unwrap_or_else(|| "Unknown".into()); let offset = match (str_of(&si["time_now"]), i64_of(&si["timestamp_now"])) { diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index a4c5d48..8a44858 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -14,10 +14,15 @@ pub const DEFAULT_USER_AGENT: &str = concat!("testpattern/", env!("CARGO_PKG_VER pub struct App { pub db: Db, + /// Client with the app's own user agent (TMDB, artwork, Chromecasts). pub http: reqwest::Client, + /// Clients for providers' custom user agents (`App::client`). + clients: Mutex>, pub cache_dir: PathBuf, /// Sources with a sync currently running. pub syncing: Mutex>, + /// The background TMDB run (tmdb.rs). + pub tmdb: crate::tmdb::Progress, } pub type AppState = Arc; @@ -50,15 +55,39 @@ pub async fn run_blocking(f: impl FnOnce() -> T + Send + 'sta .map_err(|e| Error::msg(e.to_string())) } -pub fn http_client(user_agent: Option<&str>) -> reqwest::Client { +impl App { + pub fn new(db: Db, cache_dir: PathBuf) -> Self { + App { + db, + http: build_client(DEFAULT_USER_AGENT), + clients: Mutex::default(), + cache_dir, + syncing: Mutex::default(), + tmdb: crate::tmdb::Progress::default(), + } + } + + /// The HTTP client for a provider's user agent (none: the app's own). + /// One per agent, so requests share its connection pool and TLS + /// sessions instead of building a client per call. + pub fn client(&self, user_agent: Option<&str>) -> reqwest::Client { + match user_agent.map(str::trim).filter(|u| !u.is_empty()) { + None => self.http.clone(), + Some(ua) => self + .clients + .lock() + .entry(ua.to_owned()) + .or_insert_with(|| build_client(ua)) + .clone(), + } + } +} + +fn build_client(user_agent: &str) -> reqwest::Client { reqwest::Client::builder() - .user_agent( - user_agent - .filter(|u| !u.trim().is_empty()) - .unwrap_or(DEFAULT_USER_AGENT), - ) + .user_agent(user_agent) .connect_timeout(Duration::from_secs(12)) .pool_idle_timeout(Duration::from_secs(60)) .build() - .expect("http client") + .expect("TLS backend and user agent are valid") } diff --git a/src-tauri/src/tmdb.rs b/src-tauri/src/tmdb.rs index 40ee999..11c3462 100644 --- a/src-tauri/src/tmdb.rs +++ b/src-tauri/src/tmdb.rs @@ -6,8 +6,6 @@ //! //! "This product uses the TMDB API but is not endorsed or certified by TMDB." -use std::sync::LazyLock; -use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use futures_util::StreamExt; @@ -20,7 +18,7 @@ use tauri::{AppHandle, Emitter, Runtime, State}; use crate::db::now; use crate::error::{Error, Result}; use crate::kind::WorkKind; -use crate::state::{AppState, http_client, read_blocking, write_blocking}; +use crate::state::{AppState, read_blocking, write_blocking}; /// Setting holding the API key (v3) or read access token (v4). Kept out of /// `settings_get` and logs. @@ -155,9 +153,9 @@ struct Client { } impl Client { - fn new(key: &str) -> Self { + fn new(http: reqwest::Client, key: &str) -> Self { Client { - http: http_client(None), + http, auth: auth(key), } } @@ -221,8 +219,8 @@ impl Client { } /// 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?; +pub async fn check_key(http: reqwest::Client, key: &str) -> Result<()> { + let resp = Client::new(http, key).get("/authentication").await?; match resp.status().as_u16() { 200 => Ok(()), 401 | 403 => Err(Error::TmdbRejected), @@ -260,8 +258,14 @@ pub struct Status { pub last_run: Option, } +/// The background run's progress (`App::tmdb`): one run at a time, and +/// `running` is only set and cleared under the lock, so two starts can't +/// both win. #[derive(Default)] -struct Progress { +pub struct Progress(Mutex); + +#[derive(Default)] +struct RunState { running: bool, done: i64, total: i64, @@ -269,34 +273,47 @@ struct Progress { last_run: Option, } -static PROGRESS: LazyLock> = LazyLock::new(Default::default); -static RUNNING: AtomicBool = AtomicBool::new(false); +impl Progress { + fn with(&self, f: impl FnOnce(&mut RunState) -> T) -> T { + f(&mut self.0.lock()) + } +} -pub fn status(conn: &Connection) -> Result { +/// Status from the database plus the run's progress. +async fn status_of(st: &AppState) -> Result { + let st2 = st.clone(); + read_blocking(st, move |conn| status(conn, &st2.tmdb)).await +} + +pub fn status(conn: &Connection, progress: &Progress) -> Result { let (titles, known): (i64, i64) = conn.query_row( - "SELECT COUNT(*), COUNT(t.id) FROM work w - LEFT JOIN tmdb t ON t.kind = CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END + &format!( + "SELECT COUNT(*), COUNT(t.id) FROM work w + LEFT JOIN tmdb t ON t.kind = {TMDB_KIND} AND t.id = substr(w.key, 6) AND t.json IS NOT NULL - WHERE w.key LIKE 'tmdb:%'", + WHERE w.key LIKE 'tmdb:%'" + ), [], |r| Ok((r.get(0)?, r.get(1)?)), )?; // unidentified titles, minus the ones search matching already folded // into a TMDB group (their mapped key) or the searches ruled out let unmapped: i64 = conn.query_row( - "SELECT COUNT(*) FROM work w + &format!( + "SELECT COUNT(*) FROM work w WHERE (w.key LIKE 'title:%' OR w.key LIKE 'item:%') AND w.kind IN ('movie', 'series') AND trim(w.title) != '' AND COALESCE(NULLIF((SELECT tmdb_id FROM tmdb_map m - WHERE m.kind = CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END - AND m.source_key = w.key), ''), 'x') = 'x'", + WHERE m.kind = {TMDB_KIND} + AND m.source_key = w.key), ''), 'x') = 'x'" + ), [], |r| r.get(0), )?; let configured = crate::secrets::named_configured(conn, KEY_SETTING); let locked = configured && key(conn).is_none(); - let p = PROGRESS.lock(); + let p = progress.0.lock(); Ok(Status { configured, running: p.running, @@ -314,7 +331,7 @@ pub fn status(conn: &Connection) -> Result { } async fn emit(app: &AppHandle, st: &AppState) { - if let Ok(s) = read_blocking(st, status).await { + if let Ok(s) = status_of(st).await { let _ = app.emit(EVENT, s); } } @@ -334,19 +351,25 @@ async fn save(st: &AppState, batch: Vec<(WorkKind, String, Option)>) -> Re write_blocking(st, move |conn| store(conn, &batch)).await } +/// SQL: the tmdb table's kind for `work w` (our "series" are TMDB's "tv", +/// as `WorkKind::tmdb`). +const TMDB_KIND: &str = "CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END"; + // --------------------------------------------------------------------- job /// Titles to fetch: never fetched or older than `MAX_AGE`, newest first. fn todo(conn: &Connection) -> Result> { let rows = conn - .prepare( - "SELECT CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END, substr(w.key, 6) + .prepare(&format!( + "SELECT {TMDB_KIND}, substr(w.key, 6) FROM work w - LEFT JOIN tmdb t ON t.kind = CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END AND t.id = substr(w.key, 6) + LEFT JOIN tmdb t ON t.kind = {TMDB_KIND} AND t.id = substr(w.key, 6) WHERE w.key LIKE 'tmdb:%' AND (t.id IS NULL OR t.fetched_at < ?1) - ORDER BY w.added IS NULL, w.added DESC", - )? - .query_map([now() - MAX_AGE], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? + ORDER BY w.added IS NULL, w.added DESC" + ))? + .query_map([now() - MAX_AGE], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) + })? .collect::, _>>()?; Ok(rows .into_iter() @@ -466,15 +489,15 @@ struct Candidate { /// year-less 'item:*' entries, not searched again within `MAX_AGE`. fn search_todo(conn: &Connection) -> Result> { let rows = conn - .prepare( - "SELECT CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END, w.key, w.title, w.year + .prepare(&format!( + "SELECT {TMDB_KIND}, w.key, w.title, w.year FROM work w - LEFT JOIN tmdb_map m ON m.kind = CASE w.kind WHEN 'movie' THEN 'movie' ELSE 'tv' END + LEFT JOIN tmdb_map m ON m.kind = {TMDB_KIND} AND m.source_key = w.key WHERE (w.key LIKE 'title:%' OR w.key LIKE 'item:%') AND w.kind IN ('movie', 'series') - AND (m.searched_at IS NULL OR m.searched_at < ?1)", - )? + AND (m.searched_at IS NULL OR m.searched_at < ?1)" + ))? .query_map([now() - MAX_AGE], |r| { Ok(( r.get::<_, String>(0)?, @@ -579,7 +602,7 @@ async fn identify( "tmdb: searching for {} unidentified titles", candidates.len() ); - PROGRESS.lock().total += candidates.len() as i64; + st.tmdb.with(|p| p.total += candidates.len() as i64); let mut found = 0; let mut failures = 0; let mut batch: Vec<(&'static str, String, String)> = Vec::new(); @@ -588,7 +611,7 @@ async fn identify( if !has_key(st).await { break; // the key was removed meanwhile (Settings) } - PROGRESS.lock().done = (progress + i + 1) as i64; + st.tmdb.with(|p| p.done = (progress + i + 1) as i64); let id = match search_id(client, c.kind, &c.title, c.year).await { Ok(id) => id, Err(e @ Error::TmdbRejected) => { @@ -618,7 +641,7 @@ async fn identify( if batch.len() >= 200 { save_map(st, &batch).await?; let done = (progress + i + 1) as i64; - PROGRESS.lock().done = done; + st.tmdb.with(|p| p.done = done); batch.clear(); } } @@ -676,26 +699,27 @@ pub fn spawn(app: AppHandle, st: AppState) { } fn start(app: AppHandle, st: AppState) { - if RUNNING.swap(true, Ordering::SeqCst) { - return; - } - { - let mut p = PROGRESS.lock(); - *p = Progress { + let started = st.tmdb.with(|p| { + if p.running { + return false; + } + *p = RunState { running: true, last_run: p.last_run, ..Default::default() }; + true + }); + if !started { + return; } tauri::async_runtime::spawn(async move { let result = run(&app, &st).await; - { - let mut p = PROGRESS.lock(); + st.tmdb.with(|p| { p.running = false; p.last_run = Some(now()); p.error = result.as_ref().err().map(|e| e.to_string()); - } - RUNNING.store(false, Ordering::SeqCst); + }); match &result { Ok(n) => log::info!("tmdb: {n} titles updated"), Err(e) => log::warn!("tmdb: {e}"), @@ -708,7 +732,7 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { 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)); + let client = std::sync::Arc::new(Client::new(st.http.clone(), &api_key)); let pace = std::sync::Arc::new(tokio::sync::Mutex::new({ let mut i = tokio::time::interval(Duration::from_millis(1000 / RATE)); i.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); @@ -759,7 +783,7 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { return Ok(found); } log::info!("tmdb: fetching {} titles", todo.len()); - PROGRESS.lock().total = todo.len() as i64; + st.tmdb.with(|p| p.total = todo.len() as i64); emit(app, st).await; let mut results = futures_util::stream::iter(todo) @@ -779,7 +803,7 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { 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; + st.tmdb.with(|p| p.done += 1); match r { Ok(Fetched::Found(info)) => batch.push((kind, id, Some(*info))), Ok(Fetched::Missing) => batch.push((kind, id, None)), @@ -824,7 +848,7 @@ async fn run(app: &AppHandle, st: &AppState) -> Result { #[tauri::command] pub async fn tmdb_status(state: State<'_, AppState>) -> Result { - read_blocking(state.inner(), status).await + status_of(state.inner()).await } /// Saves (after checking it with TMDB) or, with an empty key, removes the @@ -837,7 +861,7 @@ pub async fn tmdb_set_key( ) -> Result { let key = key.trim().to_owned(); if !key.is_empty() { - check_key(&key).await?; + check_key(state.http.clone(), &key).await?; } // the system keyring when there is one (it may ask to be unlocked: the // user just typed the key), else the database @@ -852,9 +876,9 @@ pub async fn tmdb_set_key( ) .await?; } - PROGRESS.lock().error = None; + state.tmdb.with(|p| p.error = None); spawn(app, state.inner().clone()); - read_blocking(state.inner(), status).await + status_of(state.inner()).await } #[tauri::command] @@ -865,7 +889,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()); - read_blocking(state.inner(), status).await + status_of(state.inner()).await } /// What the detail pages show from TMDB. @@ -965,13 +989,13 @@ mod tests { #[test] fn a_key_in_a_locked_keyring_is_reported() { let c = crate::db::test_conn(); - assert!(!status(&c).unwrap().configured); + assert!(!status(&c, &Progress::default()).unwrap().configured); c.execute( "INSERT INTO setting (key, value) VALUES ('tmdb.key.inKeyring', 'true')", [], ) .unwrap(); - let s = status(&c).unwrap(); + let s = status(&c, &Progress::default()).unwrap(); assert!(s.configured); assert_eq!(s.error.as_deref(), Some(KEY_LOCKED)); assert_eq!(key(&c), None); @@ -1150,7 +1174,7 @@ mod tests { .collect(); assert_eq!(keys, ["item:1:no-year".to_string()]); // unmapped count matches: both still without an accepted match - assert_eq!(status(&c).unwrap().unmapped, 2); + assert_eq!(status(&c, &Progress::default()).unwrap().unmapped, 2); } /// Status reports the still-unmatched works: mapped and miss-sentinel @@ -1167,7 +1191,7 @@ mod tests { .unwrap(); } crate::works::rebuild(&c).unwrap(); - assert_eq!(status(&c).unwrap().unmapped, 3); + assert_eq!(status(&c, &Progress::default()).unwrap().unmapped, 3); c.execute( "INSERT INTO tmdb_map (kind, source_key, tmdb_id, searched_at) VALUES ('movie', 'title:film a|2001', '10', 1)", [], @@ -1177,6 +1201,6 @@ mod tests { crate::works::rebuild(&c).unwrap(); // Film A joined a TMDB group; B (never searched) and C (searched, // no match) are both still without a TMDB id - assert_eq!(status(&c).unwrap().unmapped, 2); + assert_eq!(status(&c, &Progress::default()).unwrap().unmapped, 2); } } diff --git a/src-tauri/src/works/channels.rs b/src-tauri/src/works/channels.rs index dc20bc6..3fd9025 100644 --- a/src-tauri/src/works/channels.rs +++ b/src-tauri/src/works/channels.rs @@ -1,6 +1,12 @@ //! Live channels: feeds folded into one group per channel and country. -use super::*; +use std::collections::HashMap; + +use rusqlite::{Connection, params}; + +use crate::error::Result; + +use super::{genre, most_common, norm_title}; /// Variant preference when nothing was chosen yet: full/regular HD streams /// first, then RAW, 4K, HEVC-only and SD last. Higher is better. diff --git a/src-tauri/src/works/grouping.rs b/src-tauri/src/works/grouping.rs index 1167d19..be8d5cc 100644 --- a/src-tauri/src/works/grouping.rs +++ b/src-tauri/src/works/grouping.rs @@ -1,6 +1,14 @@ //! Movies and series: copies folded into works, with their browse facets. -use super::*; +use std::collections::{BTreeSet, HashMap}; + +use rusqlite::{Connection, params}; + +use crate::error::Result; +use crate::kind::WorkKind; + +use super::variant::Variant; +use super::{genre, lang, load_tmdb_map, most_common, norm_title, valid_tmdb, variant}; /// One catalog row as far as grouping cares. struct Member { @@ -140,44 +148,12 @@ pub fn tmdb_fits(info: &crate::tmdb::Info, titles: &[&str], year: Option) - /// 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 - }; + let mut keys = assign_keys(&members); + let remap = remap_search_matches(&members, &keys, &tmdb, kind, &load_tmdb_map(conn)?); for k in &mut keys { if let Some(new) = remap.get(k) { - *k = new.clone(); + k.clone_from(new); } } @@ -191,6 +167,7 @@ pub(super) fn rebuild_works(conn: &Connection, kind: WorkKind) -> Result e.push(m); } + let table = kind.table(); conn.execute("DELETE FROM work WHERE kind = ?1", [kind])?; conn.execute("DELETE FROM work_facet WHERE kind = ?1", [kind])?; { @@ -212,156 +189,43 @@ pub(super) fn rebuild_works(conn: &Connection, kind: WorkKind) -> Result 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); - + let w = work_row(key, ms, &tmdb); + let f = collect_facets(ms, w.info); insert_work.execute(params![ kind, key, - title, - year, - poster, - backdrop, - rating, - (!genres.is_empty()).then(|| genres.join(", ")), - added, + w.title, + w.year, + w.poster, + w.backdrop, + w.rating, + (!f.genres.is_empty()).then(|| f.genres.join(", ")), + ms.iter().filter_map(|m| m.added).max(), ms.len() as i64, - quality.join("|"), - services.join("|"), - adult, - rep.source_id, - rep.id + f.quality.join("|"), + f.services.join("|"), + ms.iter().any(|m| m.adult), + w.rep.source_id, + w.rep.id ])?; let mut facet = |facet: &str, value: &str| { insert_facet .execute(params![kind, facet, value, key]) .map(|_| ()) }; - for g in &genres { + for g in &f.genres { facet("genre", g)?; } - for s in &services { + for s in &f.services { facet("service", s)?; } - for l in &languages { + for l in &f.languages { facet("language", l)?; } - for q in &quality { + for q in &f.quality { facet("quality", q)?; } - if let Some(d) = genre::decade(year) { + if let Some(d) = genre::decade(w.year) { facet("decade", &d)?; } for m in ms { @@ -369,7 +233,7 @@ pub(super) fn rebuild_works(conn: &Connection, kind: WorkKind) -> Result facet("collection", &format!("{}:{c}", m.source_id))?; } } - if let Some(i) = info { + if let Some(i) = w.info { if let Some(l) = i.language.as_deref().and_then(lang::name) { facet("original", l)?; } @@ -383,3 +247,185 @@ pub(super) fn rebuild_works(conn: &Connection, kind: WorkKind) -> Result } Ok(order.len()) } + +/// 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. +/// Returns old key → `tmdb:` key. +fn remap_search_matches( + members: &[Member], + keys: &[String], + tmdb: &HashMap, + kind: WorkKind, + mapped: &HashMap<(String, String), String>, +) -> 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 Some(id) = mapped.get(&(kind.tmdb().to_owned(), k.to_owned())) else { + continue; + }; + let fits = 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 { + remap.insert(k.to_owned(), format!("tmdb:{id}")); + } + } + remap +} + +/// What a work row shows, from its copies and (when it fits) TMDB. +struct WorkRow<'a> { + /// the copy whose metadata is used and that plays by default + rep: &'a Member, + /// TMDB details, when the work is a TMDB group whose data fits + info: Option<&'a crate::tmdb::Info>, + title: String, + year: Option, + poster: Option, + backdrop: Option, + rating: Option, +} + +/// TMDB ratings with fewer votes than this don't replace a missing one. +const TMDB_MIN_VOTES: i64 = 20; + +fn work_row<'a>( + key: &str, + ms: &[&'a Member], + tmdb: &'a HashMap, +) -> WorkRow<'a> { + // 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 mut 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 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 >= TMDB_MIN_VOTES { + 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)) + }); + } + WorkRow { + rep, + info, + title, + year, + poster, + backdrop, + rating, + } +} + +/// Browse facets of one work, each list in first-seen order without repeats +/// (genres in `genre::GENRES` order). +struct Facets { + genres: Vec<&'static str>, + services: Vec<&'static str>, + languages: Vec<&'static str>, + quality: Vec<&'static str>, +} + +fn push_unique(list: &mut Vec, items: impl IntoIterator) { + for item in items { + if !list.contains(&item) { + list.push(item); + } + } +} + +fn collect_facets(ms: &[&Member], info: Option<&crate::tmdb::Info>) -> Facets { + let mut f = Facets { + genres: Vec::new(), + services: Vec::new(), + languages: Vec::new(), + quality: Vec::new(), + }; + for m in ms { + push_unique( + &mut f.genres, + m.genre_text + .as_deref() + .map(genre::from_text) + .unwrap_or_default(), + ); + push_unique( + &mut f.genres, + m.category + .as_deref() + .map(genre::from_category) + .unwrap_or_default(), + ); + push_unique(&mut f.services, m.variant.service); + push_unique( + &mut f.languages, + [m.variant.language, m.variant.subtitles] + .into_iter() + .flatten(), + ); + push_unique(&mut f.quality, m.variant.quality.iter().copied()); + if m.variant.origin == variant::Origin::Bluray { + push_unique(&mut f.quality, ["Blu-ray"]); + } + } + if let Some(i) = info { + push_unique(&mut f.genres, genre::from_text(&i.genres.join(", "))); + } + f.genres.sort_by_key(|g| { + genre::GENRES + .iter() + .position(|x| x == g) + .unwrap_or(usize::MAX) + }); + f +} diff --git a/src-tauri/src/works/keys.rs b/src-tauri/src/works/keys.rs new file mode 100644 index 0000000..bda7e64 --- /dev/null +++ b/src-tauri/src/works/keys.rs @@ -0,0 +1,109 @@ +//! Group keys: title normalization, TMDB ids and the search-match map. + +use std::collections::HashMap; + +use rusqlite::Connection; + +use crate::error::Result; + +/// Title for grouping: lower case, diacritics folded, `&` = "and", +/// punctuation dropped ("Love & Anarchy" = "love and anarchy"). +pub fn norm_title(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut gap = false; + let push_word_char = |out: &mut String, c: char, gap: &mut bool| { + if *gap && !out.is_empty() { + out.push(' '); + } + *gap = false; + out.push(c); + }; + for ch in s.chars() { + if ch == '&' { + gap = true; + for c in "and".chars() { + push_word_char(&mut out, c, &mut gap); + } + gap = true; + continue; + } + for lower in ch.to_lowercase() { + let folded: &str = match lower { + 'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' => "a", + 'æ' => "ae", + 'ç' | 'č' | 'ć' => "c", + 'è' | 'é' | 'ê' | 'ë' | 'ě' | 'ē' => "e", + 'ì' | 'í' | 'î' | 'ï' | 'ı' => "i", + 'ñ' | 'ń' => "n", + 'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ő' => "o", + 'œ' => "oe", + 'ù' | 'ú' | 'û' | 'ü' | 'ů' | 'ű' => "u", + 'ý' | 'ÿ' => "y", + 'ß' => "ss", + 'ğ' => "g", + 'ş' | 'š' | 'ś' => "s", + 'ł' => "l", + 'ž' | 'ź' | 'ż' => "z", + 'ř' => "r", + 'đ' => "d", + _ => "", + }; + if !folded.is_empty() { + for c in folded.chars() { + push_word_char(&mut out, c, &mut gap); + } + } else if lower.is_alphanumeric() { + push_word_char(&mut out, lower, &mut gap); + } else { + gap = true; + } + } + } + out +} + +pub(super) fn valid_tmdb(t: Option<&str>) -> Option<&str> { + let t = t?.trim(); + (!t.is_empty() && t != "0" && !t.eq_ignore_ascii_case("null")).then_some(t) +} + +/// TMDB ids found by title search (db.rs v9, tmdb.rs): (kind, source key) → +/// TMDB id. `kind` is the tmdb table's spelling ('movie' | 'tv'); ids stored +/// as '' are remembered misses, not mappings. +pub fn load_tmdb_map(conn: &Connection) -> Result> { + let rows: Vec<(String, String, String)> = conn + .prepare("SELECT kind, source_key, tmdb_id FROM tmdb_map WHERE tmdb_id != ''")? + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? + .collect::>()?; + Ok(rows + .into_iter() + .map(|(kind, key, id)| ((kind, key), id)) + .collect()) +} + +/// The mapped TMDB id of a search-matched work key ('title:*' | 'item:*'). +#[cfg(test)] +pub fn tmdb_id_of(conn: &Connection, key: &str) -> Result> { + Ok(conn + .query_row( + "SELECT tmdb_id FROM tmdb_map WHERE source_key = ?1", + [key], + |r| r.get::<_, String>(0), + ) + .ok() + .filter(|id| !id.is_empty())) +} + +pub(super) fn most_common( + items: impl Iterator, +) -> Option { + let mut counts: HashMap = HashMap::new(); + for (i, (item, w)) in items.enumerate() { + let e = counts.entry(item).or_insert((0, i)); + e.0 += w; + } + counts + .into_iter() + .max_by(|a, b| a.1.0.cmp(&b.1.0).then(b.1.1.cmp(&a.1.1))) + .map(|(k, _)| k) +} diff --git a/src-tauri/src/works/mod.rs b/src-tauri/src/works/mod.rs index 39493c6..41233ef 100644 --- a/src-tauri/src/works/mod.rs +++ b/src-tauri/src/works/mod.rs @@ -20,6 +20,7 @@ mod channels; pub mod genre; mod grouping; +mod keys; pub mod lang; pub mod variant; pub mod versions; @@ -30,121 +31,20 @@ use channels::rebuild_channel_groups; pub use channels::{channel_rank, channel_variant_label}; use grouping::rebuild_works; pub use grouping::tmdb_fits; +#[cfg(test)] +pub use keys::tmdb_id_of; +pub use keys::{load_tmdb_map, norm_title}; +use keys::{most_common, valid_tmdb}; -use std::collections::{BTreeSet, HashMap}; - -use rusqlite::{Connection, params}; +use rusqlite::Connection; use crate::error::Result; use crate::kind::WorkKind; -use variant::Variant; /// Bump whenever grouping/facet rules change: startup then rebuilds. /// v5: `tmdb_map` folds search-matched unidentified titles into TMDB groups. pub const RULES_VERSION: i64 = 5; -/// Title for grouping: lower case, diacritics folded, `&` = "and", -/// punctuation dropped ("Love & Anarchy" = "love and anarchy"). -pub fn norm_title(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut gap = false; - let push_word_char = |out: &mut String, c: char, gap: &mut bool| { - if *gap && !out.is_empty() { - out.push(' '); - } - *gap = false; - out.push(c); - }; - for ch in s.chars() { - if ch == '&' { - gap = true; - for c in "and".chars() { - push_word_char(&mut out, c, &mut gap); - } - gap = true; - continue; - } - for lower in ch.to_lowercase() { - let folded: &str = match lower { - 'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' => "a", - 'æ' => "ae", - 'ç' | 'č' | 'ć' => "c", - 'è' | 'é' | 'ê' | 'ë' | 'ě' | 'ē' => "e", - 'ì' | 'í' | 'î' | 'ï' | 'ı' => "i", - 'ñ' | 'ń' => "n", - 'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ő' => "o", - 'œ' => "oe", - 'ù' | 'ú' | 'û' | 'ü' | 'ů' | 'ű' => "u", - 'ý' | 'ÿ' => "y", - 'ß' => "ss", - 'ğ' => "g", - 'ş' | 'š' | 'ś' => "s", - 'ł' => "l", - 'ž' | 'ź' | 'ż' => "z", - 'ř' => "r", - 'đ' => "d", - _ => "", - }; - if !folded.is_empty() { - for c in folded.chars() { - push_word_char(&mut out, c, &mut gap); - } - } else if lower.is_alphanumeric() { - push_word_char(&mut out, lower, &mut gap); - } else { - gap = true; - } - } - } - out -} - -fn valid_tmdb(t: Option<&str>) -> Option<&str> { - let t = t?.trim(); - (!t.is_empty() && t != "0" && !t.eq_ignore_ascii_case("null")).then_some(t) -} - -/// TMDB ids found by title search (db.rs v9, tmdb.rs): (kind, source key) → -/// TMDB id. `kind` is the tmdb table's spelling ('movie' | 'tv'); ids stored -/// as '' are remembered misses, not mappings. -pub fn load_tmdb_map(conn: &Connection) -> Result> { - let rows: Vec<(String, String, String)> = conn - .prepare("SELECT kind, source_key, tmdb_id FROM tmdb_map WHERE tmdb_id != ''")? - .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? - .collect::>()?; - Ok(rows - .into_iter() - .map(|(kind, key, id)| ((kind, key), id)) - .collect()) -} - -/// The mapped TMDB id of a search-matched work key ('title:*' | 'item:*'). -#[cfg(test)] -pub fn tmdb_id_of(conn: &Connection, key: &str) -> Result> { - Ok(conn - .query_row( - "SELECT tmdb_id FROM tmdb_map WHERE source_key = ?1", - [key], - |r| r.get::<_, String>(0), - ) - .ok() - .filter(|id| !id.is_empty())) -} - -fn most_common( - items: impl Iterator, -) -> Option { - let mut counts: HashMap = HashMap::new(); - for (i, (item, w)) in items.enumerate() { - let e = counts.entry(item).or_insert((0, i)); - e.0 += w; - } - counts - .into_iter() - .max_by(|a, b| a.1.0.cmp(&b.1.0).then(b.1.1.cmp(&a.1.1))) - .map(|(k, _)| k) -} - /// Recomputes all derived grouping data. Call inside the writer's /// transaction after the catalog changed. pub fn rebuild(conn: &Connection) -> Result<()> { @@ -185,6 +85,7 @@ pub fn rebuild_if_stale(conn: &mut Connection) -> Result<()> { #[cfg(test)] mod tests { use super::*; + use rusqlite::params; #[test] fn normalizes_titles_for_grouping() { diff --git a/src-tauri/src/works/versions.rs b/src-tauri/src/works/versions.rs index d3d670b..1778db7 100644 --- a/src-tauri/src/works/versions.rs +++ b/src-tauri/src/works/versions.rs @@ -9,7 +9,7 @@ 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::kind::{ItemKind, ItemRef, WorkKind}; use crate::settings; use crate::state::{AppState, write_blocking}; @@ -166,12 +166,12 @@ pub fn members(conn: &Connection, kind: WorkKind, source_id: i64, id: &str) -> R Ok(rows) } -pub fn preference(conn: &Connection, kind: WorkKind, 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", params![kind, key], - |r| Ok((r.get(0)?, r.get(1)?)), + |r| Ok(ItemRef::new(r.get(0)?, r.get(1)?)), ) .optional()?) } @@ -188,10 +188,8 @@ pub fn language_prefs(conn: &Connection) -> Vec<&'static str> { pub const BROKEN: f64 = -50.0; /// Tracks entry of a copy whose check failed. -pub fn unavailable(tracks: &Option) -> bool { - tracks - .as_ref() - .is_some_and(|t| t["unavailable"] == Value::Bool(true)) +pub fn unavailable(tracks: Option<&Value>) -> bool { + tracks.is_some_and(|t| t["unavailable"] == Value::Bool(true)) } /// Which copy plays: the one the user picked, else the one they were last @@ -200,14 +198,14 @@ pub fn unavailable(tracks: &Option) -> bool { /// open — then picture quality; never CAM). pub fn choose( members: &[Member], - pref: Option<&(i64, String)>, + pref: Option<&ItemRef>, langs: &[&str], completeness: impl Fn(usize) -> f64, ) -> usize { - if let Some((sid, id)) = pref + if let Some(pref) = pref && let Some(i) = members .iter() - .position(|m| m.source_id == *sid && m.id == *id) + .position(|m| m.source_id == pref.source_id && m.id == pref.id) { return i; } @@ -419,14 +417,14 @@ mod tests { watching[2].played_at = 100; assert_eq!(choose(&watching, None, &danish, full), 2); // an explicit choice wins over everything - let pick = (1, v[0].id.clone()); + let pick = ItemRef::new(1, v[0].id.clone()); assert_eq!(choose(&watching, Some(&pick), &danish, full), 0); // a copy the server can't open loses to anything else assert_eq!( choose(&v, None, &danish, |i| if i == 1 { BROKEN } else { 1.0 }), 3 ); - assert!(unavailable(&Some(serde_json::json!({"unavailable": true})))); - assert!(!unavailable(&None)); + assert!(unavailable(Some(&serde_json::json!({"unavailable": true})))); + assert!(!unavailable(None)); } } diff --git a/src/app/Layout.tsx b/src/app/Layout.tsx index 6db2c76..883ad95 100644 --- a/src/app/Layout.tsx +++ b/src/app/Layout.tsx @@ -2,8 +2,7 @@ import clsx from "clsx"; import { CalendarRange, Cast, Clapperboard, Film, House, RefreshCw, Search, Settings, Tv, VolumeX, X } from "lucide-react"; 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 { useSources } from "../lib/queries"; import { ROUTES } from "../lib/routes"; import { runningSync, useSync } from "../stores/sync"; import { control, usePlayer } from "../stores/player"; @@ -16,12 +15,12 @@ import { pipClipPath, usePipVisible, useViewportSize } from "../components/PipPl import type { RouteHandle } from "./router"; const NAV = [ - { to: "/", label: "Home", icon: House, end: true }, - { to: "/live", label: "Live TV", icon: Tv }, - { to: "/guide", label: "TV Guide", icon: CalendarRange }, - { to: "/movies", label: "Movies", icon: Film }, - { to: "/series", label: "Series", icon: Clapperboard }, - { to: "/search", label: "Search", icon: Search }, + { to: ROUTES.home, label: "Home", icon: House, end: true }, + { to: ROUTES.live, label: "Live TV", icon: Tv }, + { to: ROUTES.guide, label: "TV Guide", icon: CalendarRange }, + { to: ROUTES.movieList, label: "Movies", icon: Film }, + { to: ROUTES.seriesList, label: "Series", icon: Clapperboard }, + { to: ROUTES.search, label: "Search", icon: Search }, ]; /** @@ -59,7 +58,7 @@ export function Layout() { if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return; if (e.key === "/" || ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k")) { e.preventDefault(); - navigate("/search"); + navigate(ROUTES.search); return; } // PL-101: playback may run without the player page open (preview on @@ -138,7 +137,7 @@ function Sidebar() { clsx( "mx-3 mb-4 flex h-10 items-center gap-3 rounded-xl px-3 text-[14.5px] font-medium transition-colors", @@ -224,7 +223,7 @@ function CastNotice({ text }: { text: string }) { function SyncStatus() { const running = useSync(runningSync); - const sources = useQuery({ queryKey: ["sources"], queryFn: api.sources }); + const sources = useSources(); const backendRunning = sources.data?.find((s) => s.syncing); if (!running && !backendRunning) return null; const message = running?.message || "Updating library…"; diff --git a/src/app/Root.tsx b/src/app/Root.tsx index b4b046b..78cc1fd 100644 --- a/src/app/Root.tsx +++ b/src/app/Root.tsx @@ -1,8 +1,7 @@ -import { useQuery } from "@tanstack/react-query"; import { useEffect } from "react"; import { Navigate, Outlet, useLocation, useNavigate } from "react-router"; -import { api } from "../lib/api"; -import { ROUTES } from "../lib/routes"; +import { useSources } from "../lib/queries"; +import { ROUTES, START_PAGES } from "../lib/routes"; import { useSettings } from "../lib/settings"; import { useBackendEvents } from "../hooks/useBackendEvents"; import { useProgressSaver } from "../hooks/useProgressSaver"; @@ -10,10 +9,6 @@ import { Spinner } from "../components/ui"; import { setVideoViewport, usePlayer } from "../stores/player"; import { PipPlayer } from "../components/PipPlayer"; -/** Start pages the "ui.startPage" setting can choose (settings.rs). */ -export const START_PAGES = { home: "/", live: "/live", guide: "/guide" } as const; -export type StartPage = keyof typeof START_PAGES; - // once per launch, not every time the user comes back to Home let startPageApplied = false; @@ -23,7 +18,7 @@ export function Root() { useProgressSaver(); const location = useLocation(); const navigate = useNavigate(); - const sources = useQuery({ queryKey: ["sources"], queryFn: api.sources }); + const sources = useSources(); const settings = useSettings(); // Leaving the live preview / player: video goes back to full size, and @@ -39,8 +34,9 @@ export function Root() { useEffect(() => { if (startPageApplied || !settings.data || !sources.data?.length) return; startPageApplied = true; - const page = START_PAGES[settings.data["ui.startPage"] as StartPage]; - if (page && page !== "/" && location.pathname === "/") navigate(page, { replace: true }); + const choice = settings.data["ui.startPage"]; + const page = choice && START_PAGES[choice]; + if (page && page !== ROUTES.home && location.pathname === ROUTES.home) navigate(page, { replace: true }); }, [settings.data, sources.data, location.pathname, navigate]); if (sources.isLoading) { @@ -50,8 +46,8 @@ export function Root() { ); } - if (sources.data && sources.data.length === 0 && location.pathname !== "/onboarding") { - return ; + if (sources.data && sources.data.length === 0 && location.pathname !== ROUTES.onboarding) { + return ; } return ( <> diff --git a/src/app/router.tsx b/src/app/router.tsx index 9312825..1f38ea6 100644 --- a/src/app/router.tsx +++ b/src/app/router.tsx @@ -23,20 +23,20 @@ export const router = createHashRouter([ { element: , children: [ - { path: "/onboarding", element: }, + { path: ROUTES.onboarding, element: }, { path: ROUTES.player, element: , handle: { transparent: true } satisfies RouteHandle }, { element: , children: [ { index: true, element: }, { path: ROUTES.live, element: , handle: { transparent: true } satisfies RouteHandle }, - { path: "/guide", element: }, - { path: "/movies", element: }, + { path: ROUTES.guide, element: }, + { path: ROUTES.movieList, element: }, { path: "/movies/:sourceId/:id", element: }, - { path: "/series", element: }, + { path: ROUTES.seriesList, element: }, { path: "/series/:sourceId/:id", element: }, - { path: "/search", element: }, - { path: "/settings", element: }, + { path: ROUTES.search, element: }, + { path: ROUTES.settings, element: }, ], }, ], diff --git a/src/components/LibraryBrowser.tsx b/src/components/LibraryBrowser.tsx index ab5ec0d..050e400 100644 --- a/src/components/LibraryBrowser.tsx +++ b/src/components/LibraryBrowser.tsx @@ -1,17 +1,24 @@ import clsx from "clsx"; import { keepPreviousData, useQuery } from "@tanstack/react-query"; -import { ChevronDown, Film, Heart, LayoutGrid, Search, X } from "lucide-react"; +import { Film, Heart, LayoutGrid, X } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { useNavigate, useSearchParams } from "react-router"; import { api } from "../lib/api"; import { itemKey } from "../lib/item"; -import { loadJson, saveJson } from "../lib/storage"; -import type { FacetFilter, FacetName, Facets, FacetValue, MediaQuery, MediaSort, Movie, Series } from "../lib/types"; +import { ROUTES } from "../lib/routes"; +import { groupBy } from "../lib/groupBy"; +import { queryKeys } from "../lib/queryKeys"; +import type { FacetFilter, FacetName, Facets, FacetValue, MediaQuery, MediaSort, Movie, Series, WorkKind } from "../lib/types"; +import { useFolds } from "../hooks/useFolds"; import { PosterCard } from "./media"; import { PosterGrid } from "./PosterGrid"; -import { Badge, EmptyState, Segmented, Spinner } from "./ui"; +import { Badge, EmptyState, FoldHeader, NavRow, SearchInput, Segmented, Spinner } from "./ui"; -type Kind = "movie" | "series"; +/** How each kind is named in the browser. */ +const KIND_TEXT: Record = { + movie: { title: "Movies", plural: "movies", singular: "movie" }, + series: { title: "Series", plural: "series", singular: "series" }, +}; const SORTS: { value: MediaSort; label: string }[] = [ { value: "added", label: "Recent" }, @@ -55,7 +62,7 @@ function filtersFromParams(params: URLSearchParams): FacetFilter[] { }); } -export function LibraryBrowser({ kind }: { kind: Kind }) { +export function LibraryBrowser({ kind }: { kind: WorkKind }) { const navigate = useNavigate(); const [params, setParams] = useSearchParams(); const sort = (params.get("sort") as MediaSort) ?? "added"; @@ -82,12 +89,12 @@ export function LibraryBrowser({ kind }: { kind: Kind }) { const query: MediaQuery = { favorites: favorites || undefined, q: debounced || undefined, sort, facets }; const facetQuery = useQuery({ - queryKey: [kind === "movie" ? "movies" : "series", "facets", { favorites, q: debounced, facets }], + queryKey: [...queryKeys.works(kind), "facets", { favorites, q: debounced, facets }], queryFn: () => api.workFacets(kind, { favorites: favorites || undefined, q: debounced || undefined, facets }), placeholderData: keepPreviousData, }); - const title = kind === "movie" ? "Movies" : "Series"; + const title = KIND_TEXT[kind].title; const labelOf = (f: FacetFilter) => facetQuery.data?.[f.facet].find((v) => v.value === f.value)?.label ?? f.value; const clearAll = () => { @@ -105,15 +112,7 @@ export function LibraryBrowser({ kind }: { kind: Kind }) { {facetQuery.data && {facetQuery.data.total.toLocaleString()}}
- + update({ sort: v === "added" ? null : v })} />
@@ -138,7 +137,7 @@ export function LibraryBrowser({ kind }: { kind: Kind }) { ); const empty = favorites && !facets.length && !debounced ? ( - } title="No favorites yet" text={`Tap the heart on any ${kind === "movie" ? "movie" : "series"} to collect it here.`} /> + } title="No favorites yet" text={`Tap the heart on any ${KIND_TEXT[kind].singular} to collect it here.`} /> ) : ( } title="Nothing found" text="No title matches all of these filters." /> ); @@ -158,7 +157,7 @@ export function LibraryBrowser({ kind }: { kind: Kind }) {
{kind === "movie" ? ( - queryKey={["movies", "grid", query]} + queryKey={[...queryKeys.works("movie"), "grid", query]} fetchPage={(offset, limit) => api.movies({ ...query, offset, limit })} itemKey={(m) => m.key ?? itemKey(m)} header={header} @@ -174,13 +173,13 @@ export function LibraryBrowser({ kind }: { kind: Kind }) { favorite={m.favorite} badge={} width={w} - onClick={() => navigate(`/movies/${m.sourceId}/${m.id}`)} + onClick={() => navigate(ROUTES.movie(m))} /> )} /> ) : ( - queryKey={["series", "grid", query]} + queryKey={[...queryKeys.works("series"), "grid", query]} fetchPage={(offset, limit) => api.series({ ...query, offset, limit })} itemKey={(s) => s.key ?? itemKey(s)} header={header} @@ -194,7 +193,7 @@ export function LibraryBrowser({ kind }: { kind: Kind }) { favorite={s.favorite} badge={} width={w} - onClick={() => navigate(`/series/${s.sourceId}/${s.id}`)} + onClick={() => navigate(ROUTES.series(s))} /> )} /> @@ -239,17 +238,6 @@ function FilterChip({ children, onRemove }: { children: React.ReactNode; onRemov // ------------------------------------------------------------ facet panel -function usePersistedFlags(key: string, initial: Record) { - const [flags, setFlags] = useState>(() => ({ ...initial, ...loadJson>(key, {}) })); - const toggle = (name: string) => - setFlags((f) => { - const next = { ...f, [name]: !f[name] }; - saveJson(key, next); - return next; - }); - return [flags, toggle] as const; -} - function FacetPanel({ kind, facets, @@ -260,7 +248,7 @@ function FacetPanel({ onFavorites, onToggle, }: { - kind: Kind; + kind: WorkKind; facets?: Facets; loading: boolean; active: FacetFilter[]; @@ -270,37 +258,31 @@ function FacetPanel({ onToggle: (facet: FacetName, value: string) => void; }) { // collapsed sections; provider categories start collapsed (there are ~80) - const [collapsed, toggleCollapsed] = usePersistedFlags(`library.collapsed.${kind}`, { collection: true }); + const folds = useFolds(`library.collapsed.${kind}`, (facet) => facet === "collection"); const [expanded, setExpanded] = useState>({}); const isActive = (facet: FacetName, value: string) => active.some((f) => f.facet === facet && f.value === value); return (
diff --git a/src/pages/Live.tsx b/src/pages/Live.tsx index 08a404a..384e425 100644 --- a/src/pages/Live.tsx +++ b/src/pages/Live.tsx @@ -1,26 +1,36 @@ import clsx from "clsx"; -import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useVirtualizer } from "@tanstack/react-virtual"; -import { Cast, ChevronDown, Clock, Heart, History, Layers, LayoutList, Maximize2, Search, Tv } from "lucide-react"; +import { Cast, ChevronDown, Clock, Heart, History, Layers, LayoutList, Maximize2, Tv } from "lucide-react"; import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useNavigate, useSearchParams } from "react-router"; import { api } from "../lib/api"; +import { backgroundWrite } from "../lib/backgroundWrite"; import { browserPreview } from "../lib/bridge"; -import { elapsed, hhmm, nowUnix } from "../lib/format"; +import { currentAndUpcoming, elapsed, hhmm, nowUnix } from "../lib/format"; +import { groupBy } from "../lib/groupBy"; import { itemKey, sameItem } from "../lib/item"; import { keyString, parseKey, queryFor, titleFor, type ListKey } from "../lib/liveLists"; import { playChannel } from "../lib/play"; +import { queryKeys } from "../lib/queryKeys"; import { ROUTES } from "../lib/routes"; import { loadJson, saveJson } from "../lib/storage"; import type { Category, Channel, LiveNav } from "../lib/types"; import { usePlayer } from "../stores/player"; import { useChannelEpg } from "../hooks/useChannelEpg"; +import { useFolds } from "../hooks/useFolds"; +import { usePagedQuery } from "../hooks/usePagedQuery"; +import { useTimeout } from "../hooks/useTimeout"; import { useVideoViewport } from "../hooks/useVideoViewport"; import { ChannelLogo } from "../components/media"; -import { Badge, Button, EmptyState, IconButton, LiveDot, ProgressBar, Segmented, Spinner } from "../components/ui"; +import { Badge, Button, EmptyState, FoldHeader, IconButton, LiveDot, NavRow, ProgressBar, SearchInput, Segmented, Spinner } from "../components/ui"; const PAGE = 1000; const ROW = 68; +/** Selecting a channel previews it once the selection rests this long (ms). */ +const PREVIEW_DELAY = 350; +/** Channel lists refresh for the "now" line (ms). */ +const LIST_REFRESH = 60_000; type Mode = "countries" | "genres" | "provider"; @@ -79,24 +89,19 @@ function ListPane({ saveJson("live.mode", m); }; const [q, setQ] = useState(""); - const [collapsed, setCollapsed] = useState>(() => loadJson("live.collapsed", {})); - const toggle = (name: string) => - setCollapsed((c) => { - const next = { ...c, [name]: !(c[name] ?? defaultCollapsed(name)) }; - saveJson("live.collapsed", next); - return next; - }); // countries/genres start folded, except the first country and the open list's const firstCountry = nav?.countries[0]?.code ?? ""; const openCountry = active.type === "nav" && active.country !== undefined ? `country:${active.country}` : null; const openGenre = active.type === "nav" && active.genre ? `genre:${active.genre}` : null; - const defaultCollapsed = (name: string) => + const folds = useFolds("live.collapsed", (name) => name === openCountry || name === openGenre ? false : name.startsWith("country:") ? name !== `country:${firstCountry}` - : name.startsWith("genre:"); - const isCollapsed = (name: string) => !q && (collapsed[name] ?? defaultCollapsed(name)); + : name.startsWith("genre:"), + ); + // a filter shows every match unfolded + const isCollapsed = (name: string) => !q && folds.isCollapsed(name); const needle = q.trim().toLowerCase(); const matches = (...texts: (string | null | undefined)[]) => !needle || texts.some((t) => t?.toLowerCase().includes(needle)); @@ -108,20 +113,15 @@ function ListPane({ { key: { type: "all" }, label: "All channels", icon: LayoutList, count: nav?.cells.reduce((n, c) => n + c.count, 0) }, ]; - const providerGroups = useMemo(() => { - const map = new Map(); - for (const c of categories) { - if (needle && !`${c.region ?? ""} ${c.title}`.toLowerCase().includes(needle)) continue; - const g = c.region ?? "Other"; - if (!map.has(g)) map.set(g, []); - map.get(g)!.push(c); - } - return [...map.entries()]; - }, [categories, needle]); + const providerGroups = useMemo( + () => [...groupBy(categories.filter((c) => !needle || `${c.region ?? ""} ${c.title}`.toLowerCase().includes(needle)), (c) => c.region ?? "Other")], + [categories, needle], + ); const cell = (country: string, genre: string) => nav?.cells.find((c) => (c.country ?? "") === country && c.genre === genre)?.count ?? 0; const genreTotal = (genre: string) => nav?.cells.filter((c) => c.genre === genre).reduce((n, c) => n + c.count, 0) ?? 0; + const tree = { isCollapsed, toggle: folds.toggle, isActive, onSelect, cell }; return (
@@ -137,108 +137,66 @@ function ListPane({ { value: "provider", label: "Provider" }, ]} /> - +
{special.map(({ key, label, icon: Icon, count }) => ( - onSelect(key)} count={count}> - - {label} - + onSelect(key)} count={count} icon={}> + {label} + ))} {loading && } + {/* countries → their genres, or genres → their countries */} {mode === "countries" && nav?.countries .filter((c) => matches(c.name, c.code)) - .map((c) => { - const code = c.code ?? ""; - const fold = `country:${code}`; - return ( -
- toggle(fold)} - active={isActive({ type: "nav", country: code })} - onClick={() => onSelect({ type: "nav", country: code })} - count={c.count} - > - {c.name} - - {!isCollapsed(fold) && - nav.genres - .filter((g) => cell(code, g) > 0) - .map((g) => { - const k: ListKey = { type: "nav", country: code, genre: g }; - return ( - onSelect(k)} count={cell(code, g)}> - {g} - - ); - })} -
- ); - })} + .map((c) => ( + ({ key: g, label: g, list: { type: "nav", country: c.code ?? "", genre: g } }))} + /> + ))} {mode === "genres" && nav?.genres .filter((g) => matches(g)) - .map((g) => { - const fold = `genre:${g}`; - return ( -
- toggle(fold)} - active={isActive({ type: "nav", genre: g })} - onClick={() => onSelect({ type: "nav", genre: g })} - count={genreTotal(g)} - > - {g} - - {!isCollapsed(fold) && - nav.countries - .filter((c) => cell(c.code ?? "", g) > 0) - .map((c) => { - const k: ListKey = { type: "nav", country: c.code ?? "", genre: g }; - return ( - onSelect(k)} count={cell(c.code ?? "", g)}> - {c.name} - - ); - })} -
- ); - })} + .map((g) => ( + ({ key: c.code ?? "-", label: c.name, list: { type: "nav", country: c.code ?? "", genre: g } }))} + /> + ))} {mode === "provider" && providerGroups.map(([region, cats]) => { const fold = `region:${region}`; return (
- + {!isCollapsed(fold) && cats.map((c) => { const k: ListKey = { type: "cat", sourceId: c.sourceId, id: c.id }; return ( - onSelect(k)} count={c.count}> - {c.title} - + onSelect(k)} count={c.count}> + {c.title} + ); })}
@@ -249,32 +207,46 @@ function ListPane({ ); } -function ListRow({ - active, - onClick, +/** One country (or genre) with its genres (or countries) that have channels. */ +function TreeSection({ + fold, + title, count, - inset, - children, + list, + items, + isCollapsed, + toggle, + isActive, + onSelect, + cell, }: { - active: boolean; - onClick: () => void; - count?: number; - inset?: boolean; - children: React.ReactNode; + fold: string; + title: string; + count: number; + list: ListKey; + items: { key: string; label: string; list: ListKey & { type: "nav" } }[]; + isCollapsed: (fold: string) => boolean; + toggle: (fold: string) => void; + isActive: (k: ListKey) => boolean; + onSelect: (k: ListKey) => void; + cell: (country: string, genre: string) => number; }) { + const open = !isCollapsed(fold); + const countOf = (k: ListKey & { type: "nav" }) => cell(k.country ?? "", k.genre ?? ""); return ( - +
+ toggle(fold)} active={isActive(list)} onClick={() => onSelect(list)} count={count}> + {title} + + {open && + items + .filter((c) => countOf(c.list) > 0) + .map((c) => ( + onSelect(c.list)} count={countOf(c.list)}> + {c.label} + + ))} +
); } @@ -319,39 +291,29 @@ function TreeHeader({ // -------------------------------------------------------------- channels +/** "Recently watched" comes in one piece. */ +const noMore = () => {}; + function useChannelList(key: ListKey, filter: string) { const q = filter.trim() || undefined; - const infinite = useInfiniteQuery({ + const paged = usePagedQuery({ queryKey: ["channels", "list", keyString(key), q], enabled: key.type !== "recent", - initialPageParam: 0, - refetchInterval: 60_000, - queryFn: ({ pageParam }) => api.channels({ ...queryFor(key), q, offset: pageParam, limit: PAGE }), - getNextPageParam: (last, pages) => { - const loaded = pages.reduce((n, p) => n + p.items.length, 0); - return loaded < last.total ? loaded : undefined; - }, + refetchInterval: LIST_REFRESH, + pageSize: PAGE, + fetchPage: (offset, limit) => api.channels({ ...queryFor(key), q, offset, limit }), }); const recent = useQuery({ queryKey: ["recent-channels", "live-page"], queryFn: () => api.recentChannels(60), enabled: key.type === "recent", - refetchInterval: 60_000, + refetchInterval: LIST_REFRESH, }); if (key.type === "recent") { const items = (recent.data ?? []).filter((c) => !q || c.title.toLowerCase().includes(q.toLowerCase())); - return { items, total: items.length, loading: recent.isLoading, fetchMore: () => {}, hasMore: false }; + return { items, total: items.length, loading: recent.isLoading, fetchMoreNear: noMore }; } - const items = infinite.data?.pages.flatMap((p) => p.items) ?? []; - return { - items, - total: infinite.data?.pages[0]?.total ?? 0, - loading: infinite.isLoading, - fetchMore: () => { - if (infinite.hasNextPage && !infinite.isFetchingNextPage) void infinite.fetchNextPage(); - }, - hasMore: !!infinite.hasNextPage, - }; + return { items: paged.items, total: paged.total, loading: paged.isLoading, fetchMoreNear: paged.fetchMoreNear }; } function ChannelPane({ @@ -371,10 +333,11 @@ function ChannelPane({ }) { const navigate = useNavigate(); const qc = useQueryClient(); - const { items, total, loading, fetchMore } = useChannelList(listKey, filter); + const { items, total, loading, fetchMoreNear } = useChannelList(listKey, filter); const playing = usePlayer((s) => (s.now?.kind === "live" ? itemKey(s.now) : null)); const scrollRef = useRef(null); - const previewTimer = useRef(0); + // cleared on unmount: a pending preview must not start after leaving /live + const previewTimer = useTimeout(); // channel rows (one per channel) vs. the provider's own feeds const grouped = listKey.type !== "cat"; @@ -389,9 +352,7 @@ function ChannelPane({ // lazy-load further pages as the user scrolls ("All channels") const virtualItems = virtualizer.getVirtualItems(); const lastIndex = virtualItems.length ? virtualItems[virtualItems.length - 1].index : 0; - useEffect(() => { - if (lastIndex >= items.length - 20) fetchMore(); - }, [lastIndex, items.length, fetchMore]); + useEffect(() => fetchMoreNear(lastIndex, 20), [lastIndex, fetchMoreNear]); // a new list starts at the top useEffect(() => { @@ -401,35 +362,39 @@ function ChannelPane({ const select = useCallback( (c: Channel, preview = true) => { onSelect(c); - window.clearTimeout(previewTimer.current); + previewTimer.clear(); if (!preview) return; // while casting, browsing the list must not zap the TV (Enter does) if (usePlayer.getState().cast) return; - previewTimer.current = window.setTimeout(() => { + previewTimer.start(() => { const now = usePlayer.getState().now; if (now?.kind === "live" && sameItem(now, c)) return; void playChannel(c, undefined, items, false); - }, 350); + }, PREVIEW_DELAY); }, - [onSelect, items], + [onSelect, items, previewTimer], ); const openFullscreen = useCallback( (c: Channel) => { - window.clearTimeout(previewTimer.current); + previewTimer.clear(); const now = usePlayer.getState().now; if (now?.kind === "live" && sameItem(now, c)) navigate(ROUTES.player); else void playChannel(c, navigate, items); }, - [navigate, items], + [navigate, items, previewTimer], ); const toggleFavorite = useCallback( - async (c: Channel) => { + (c: Channel) => { // a channel row stands for all of its feeds - const fav = grouped && c.group ? await api.toggleChannelFavorite(c.group.key) : await api.toggleFavorite("live", c.sourceId, c.id); - if (selected && sameItem(selected, c)) onSelect({ ...selected, favorite: fav }); - void qc.invalidateQueries({ queryKey: ["channels"] }); + const toggled = grouped && c.group ? api.toggleChannelFavorite(c.group.key) : api.toggleFavorite("live", c.sourceId, c.id); + void backgroundWrite( + toggled.then((fav) => { + if (selected && sameItem(selected, c)) onSelect({ ...selected, favorite: fav }); + void qc.invalidateQueries({ queryKey: queryKeys.channels }); + }), + ); }, [qc, selected, onSelect, grouped], ); @@ -448,7 +413,7 @@ function ChannelPane({ else if (e.key === "PageDown") move(idx + 10); else if (e.key === "PageUp") move(idx - 10); else if (e.key === "Enter" && selected) openFullscreen(selected); - else if ((e.key === "f" || e.key === "F") && selected) void toggleFavorite(selected); + else if ((e.key === "f" || e.key === "F") && selected) toggleFavorite(selected); }; return ( @@ -461,15 +426,7 @@ function ChannelPane({

{loading ? "Loading…" : `${total.toLocaleString()} channels`}

- +
{!loading && total === 0 ? ( @@ -591,14 +548,16 @@ function Feeds({ channel, playing, onChannel }: { channel: Channel; playing: boo const qc = useQueryClient(); const key = channel.group!.key; const variants = useQuery({ queryKey: ["channels", "variants", key], queryFn: () => api.channelVariants(key) }); - const pick = async (v: Channel & { label: string }) => { - await api.channelPrefer(key, v.sourceId, v.id); - // keep the channel's name; play the feed if the channel is on - const next: Channel = { ...v, title: channel.title, group: channel.group }; - onChannel(next); - if (playing) void playChannel(next, undefined, usePlayer.getState().now?.zapList, false); - void qc.invalidateQueries({ queryKey: ["channels"] }); - }; + const pick = (v: Channel & { label: string }) => + backgroundWrite( + api.channelPrefer(key, v.sourceId, v.id).then(() => { + // keep the channel's name; play the feed if the channel is on + const next: Channel = { ...v, title: channel.title, group: channel.group }; + onChannel(next); + if (playing) void playChannel(next, undefined, usePlayer.getState().now?.zapList, false); + void qc.invalidateQueries({ queryKey: queryKeys.channels }); + }), + ); return (

Feeds

@@ -641,11 +600,9 @@ function PreviewPane({ channel, onChannel }: { channel: Channel | null; onChanne const shown = channel ?? (previewing ? (now?.channel ?? null) : null); const isPlaying = previewing && sameItem(now, shown); - const t = nowUnix(); const epg = useChannelEpg(shown); - const programmes = (epg.data ?? []).filter((p) => p.stop > t); - const current = programmes.find((p) => p.start <= t); - const upcoming = programmes.filter((p) => p.start > t).slice(0, 6); + const { current, upcoming: next } = currentAndUpcoming(epg.data ?? [], nowUnix()); + const upcoming = next.slice(0, 6); return ( // The hole's giant box-shadow paints this column's background, leaving diff --git a/src/pages/MovieDetail.tsx b/src/pages/MovieDetail.tsx index 8fdf2ea..996360f 100644 --- a/src/pages/MovieDetail.tsx +++ b/src/pages/MovieDetail.tsx @@ -2,9 +2,14 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Check, Heart, Play, RotateCcw, Star, MonitorPlay } from "lucide-react"; import { useNavigate, useParams } from "react-router"; import { api } from "../lib/api"; -import { clock, duration, resolutionLabel } from "../lib/format"; +import { backgroundWrite } from "../lib/backgroundWrite"; +import { channelsLabel, clock, duration, resolutionLabel } from "../lib/format"; import { openExternal, youtubeUrl } from "../lib/open"; import { playMovie } from "../lib/play"; +import { pollWhileVersionsPending } from "../lib/queries"; +import { invalidateWatchState } from "../lib/queryClient"; +import { queryKeys } from "../lib/queryKeys"; +import { ROUTES } from "../lib/routes"; import { DetailHero, Facts, MetaDot } from "../components/DetailHero"; import { VersionPill, Versions } from "../components/Versions"; import { Badge, Button, EmptyState, IconButton, ProgressBar, Spinner } from "../components/ui"; @@ -15,11 +20,10 @@ export function MovieDetailPage() { const qc = useQueryClient(); const sid = Number(sourceId); const q = useQuery({ - queryKey: ["movie-detail", sid, id], + queryKey: queryKeys.workDetail("movie", { sourceId: sid, id }), queryFn: () => api.movieDetail(sid, id!), enabled: !!id, - // other versions' details still loading: ask again a few times - refetchInterval: (query) => (query.state.data?.versionsPending && query.state.dataUpdateCount < 6 ? 3000 : false), + refetchInterval: pollWhileVersionsPending, }); if (q.isLoading) return ; @@ -30,11 +34,8 @@ export function MovieDetailPage() { const res = resolutionLabel(m.video?.width, m.video?.height); const channels = m.audio?.channels; - const refresh = () => { - void qc.invalidateQueries({ queryKey: ["movie-detail", sid, id] }); - void qc.invalidateQueries({ queryKey: ["movies"] }); - void qc.invalidateQueries({ queryKey: ["continue"] }); - }; + // favorite / watched: this page, the grids and continue watching + const refresh = (ok: boolean) => ok && invalidateWatchState(); return (
@@ -74,7 +75,7 @@ export function MovieDetailPage() { {res && {res}} {m.video?.hdr && HDR} {m.video?.codec && {m.video.codec}} - {channels && channels > 2 && {channels === 6 ? "5.1" : channels === 8 ? "7.1" : `${channels}ch`}} + {channels && channels > 2 && {channelsLabel(channels)}} {m.ext && {m.ext}} {m.watched && Watched} @@ -99,10 +100,7 @@ export function MovieDetailPage() { label={m.favorite ? "Remove from favorites" : "Add to favorites"} variant="glass" size="lg" - onClick={async () => { - await api.toggleFavorite("movie", m.sourceId, m.id); - refresh(); - }} + onClick={() => void backgroundWrite(api.toggleFavorite("movie", m.sourceId, m.id)).then(refresh)} > @@ -110,17 +108,18 @@ export function MovieDetailPage() { label={m.watched ? "Mark as unwatched" : "Mark as watched"} variant="glass" size="lg" - onClick={async () => { - await api.markWatched("movie", m.sourceId, m.id, !m.watched, { - title: m.title, - subtitle: m.year ? String(m.year) : null, - image: m.poster, - backdrop: m.backdrop, - ext: m.ext, - duration: m.duration, - }); - refresh(); - }} + onClick={() => + void backgroundWrite( + api.markWatched("movie", m.sourceId, m.id, !m.watched, { + title: m.title, + subtitle: m.year ? String(m.year) : null, + image: m.poster, + backdrop: m.backdrop, + ext: m.ext, + duration: m.duration, + }), + ).then(refresh) + } > @@ -141,8 +140,8 @@ export function MovieDetailPage() { versions={m.versions} pending={m.versionsPending} onPicked={() => { - void qc.invalidateQueries({ queryKey: ["movie-detail", sid, id] }); - void qc.invalidateQueries({ queryKey: ["movies"] }); + void qc.invalidateQueries({ queryKey: queryKeys.workDetail("movie", { sourceId: sid, id }) }); + void qc.invalidateQueries({ queryKey: queryKeys.works("movie") }); }} />
@@ -157,7 +156,7 @@ export function MovieDetailPage() { [ "Collection", m.tmdb?.collection && ( - ), diff --git a/src/pages/Onboarding.tsx b/src/pages/Onboarding.tsx index 8d29328..38ada06 100644 --- a/src/pages/Onboarding.tsx +++ b/src/pages/Onboarding.tsx @@ -3,6 +3,7 @@ import { CircleAlert, Loader2 } from "lucide-react"; import { useEffect, useState } from "react"; import { useNavigate, useSearchParams } from "react-router"; import { api, errorMessage } from "../lib/api"; +import { ROUTES } from "../lib/routes"; import type { Source } from "../lib/types"; import { useSync } from "../stores/sync"; import { SourceForm } from "../components/SourceForm"; @@ -43,7 +44,7 @@ export function OnboardingPage() { source={source} onDone={() => { void qc.invalidateQueries(); - navigate("/", { replace: true }); + navigate(ROUTES.home, { replace: true }); }} onRetry={() => setSource(null)} /> diff --git a/src/pages/Player.tsx b/src/pages/Player.tsx index 512a7fc..66e4695 100644 --- a/src/pages/Player.tsx +++ b/src/pages/Player.tsx @@ -1,5 +1,4 @@ import clsx from "clsx"; -import { useQuery } from "@tanstack/react-query"; import { AudioLines, ChevronLeft, @@ -26,14 +25,15 @@ import { } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useNavigate } from "react-router"; -import { api } from "../lib/api"; -import { clock, elapsed, hhmm, nowUnix } from "../lib/format"; +import { channelsLabel, clock, currentAndUpcoming, elapsed, hhmm, languageName, nowUnix, resolutionLabel } from "../lib/format"; import { itemKey, sameItem, type ItemRef } from "../lib/item"; import { playEpisode } from "../lib/play"; -import { playerWrite } from "../lib/playerWrite"; +import { backgroundWrite } from "../lib/backgroundWrite"; +import { useSeriesDetail } from "../lib/queries"; +import { ROUTES } from "../lib/routes"; 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 { control, MAX_VOLUME_CAST, MAX_VOLUME_LOCAL, usePlayer, setSubsEnabled, subKeyAction, subKeyHint, type NowPlaying } from "../stores/player"; import { CastingBackdrop, CastMenu } from "../components/CastMenu"; import { queryClient } from "../lib/queryClient"; import { useChannelEpg } from "../hooks/useChannelEpg"; @@ -43,11 +43,15 @@ import { useFullscreen } from "./player/fullscreen"; import { nextEpisode } from "./player/logic"; import { useChromeAutoHide } from "./player/useChromeAutoHide"; import { usePlayerKeys, type KeyBinding } from "./player/usePlayerKeys"; +import { useNotice } from "./player/useNotice"; import { useRecording } from "./player/useRecording"; +import { SEEK_BACK, SEEK_BIG, SEEK_FWD, useTransport, VOLUME_STEP } from "./player/useTransport"; import { useZapping } from "./player/useZapping"; const DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; +type Panel = "channels" | "audio" | "subs" | "aspect" | "speed"; + export function PlayerPage() { const navigate = useNavigate(); const now = usePlayer((s) => s.now); @@ -57,17 +61,13 @@ export function PlayerPage() { const reconnectAttempt = usePlayer((s) => s.reconnectAttempt); const casting = usePlayer((s) => !!s.cast); - const [panel, setPanel] = useState(null); + const [panel, setPanel] = useState(null); + const togglePanel = useCallback((name: Panel) => setPanel((v) => (v === name ? null : name)), []); + const closePanel = useCallback(() => setPanel(null), []); const [info, setInfo] = useState(false); - const [flash, setFlash] = useState(null); - const [notice, setNotice] = useState(null); - const noticeTimer = useRef(0); - const say = useCallback((text: string) => { - setNotice(text); - window.clearTimeout(noticeTimer.current); - noticeTimer.current = window.setTimeout(() => setNotice(null), 4000); - }, []); - const { chrome, poke } = useChromeAutoHide(() => setPanel(null)); + const toggleInfo = useCallback(() => setInfo((v) => !v), []); + const { notice, say } = useNotice(); + const { chrome, poke } = useChromeAutoHide(closePanel); const { fullscreen, flipFullscreen, leaveFullscreen } = useFullscreen(); // PL-100: subtitles are persisted-off but a subtitle track is selected and @@ -82,7 +82,7 @@ export function PlayerPage() { if (typeof sid !== "number" || subVisible || usePlayer.getState().cast) 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"); - void playerWrite(writeSetting(queryClient, "ui.subHintSeen", true)); + void backgroundWrite(writeSetting(queryClient, "ui.subHintSeen", true)); }, [sid, subVisible, say]); const live = now?.kind === "live"; @@ -122,81 +122,35 @@ export function PlayerPage() { // 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 }); + else navigate(ROUTES.home, { replace: true }); }, [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 - // counts real delay. - const [liveGap, setLiveGap] = useState(null); - useEffect(() => setLiveGap(null), [now?.id]); - - const togglePause = useCallback(() => { - const { props: cur, now: np } = usePlayer.getState(); - const paused = cur.pause; - if (!paused && np?.kind === "live" && !usePlayer.getState().cast) setLiveGap((g) => g ?? Math.max(0, cur.cacheTime - cur.timePos)); - void control.setPause(!paused); - setFlash(paused ? "play" : "pause"); - window.setTimeout(() => setFlash(null), 500); - }, []); - - const seekBy = useCallback((secs: number) => { - void control.seekBy(secs); - say(secs < 0 ? `« ${secs} s` : `» +${secs} s`); - poke(); - }, [poke, say]); - - const nudgeVolume = useCallback((delta: number) => { - const st = usePlayer.getState(); - 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 playerWrite( - api.get("volume").then((v) => { - if (typeof v === "number") say(`Volume ${Math.round(v)}`); - }), - ); - }, 60); - }); - poke(); - }, [say, poke]); - - const toggleMute = useCallback(() => { - const st = usePlayer.getState(); - void control.setMute(!st.props.mute).then((ok) => ok && say(st.props.mute ? "Sound on" : "Muted")); - poke(); - }, [say, poke]); - - const { zapList, zap, zapTo, digits, enterDigit } = useZapping(poke); - const { recordingFile, recordingSince, toggleRecord } = useRecording(say); + const transport = useTransport(say, poke); + const { flash, togglePause, seekBy, nudgeVolume, toggleMute } = transport; + const zapping = useZapping(poke); + const { zapList, zap, zapTo, digits, enterDigit } = zapping; + const recording = 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: ["ArrowLeft"], when: !live, run: (e) => seekBy(e.shiftKey ? -SEEK_BIG : -SEEK_BACK) }, + { keys: ["ArrowRight"], when: !live, run: (e) => seekBy(e.shiftKey ? SEEK_BIG : SEEK_FWD) }, { 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: ["ArrowUp"], when: !live, run: () => nudgeVolume(VOLUME_STEP) }, + { keys: ["ArrowDown"], when: !live, run: () => nudgeVolume(-VOLUME_STEP) }, { 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: ["a", "A"], when: !casting, run: () => void control.cycleAudio() }, { 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: ["i", "I"], when: !casting, run: toggleInfo }, + { keys: ["r", "R"], when: live && !casting, run: recording.toggleRecord }, { keys: ["p", "P"], when: !casting, run: () => void toPip() }, - { keys: ["l", "L", "c", "C"], when: live, run: () => setPanel((v) => (v === "channels" ? null : "channels")) }, + { keys: ["l", "L", "c", "C"], when: live, run: () => togglePanel("channels") }, { keys: DIGITS, when: live, run: (e) => enterDigit(e.key) }, ]; usePlayerKeys(keys, poke); @@ -256,31 +210,11 @@ export function PlayerPage() { last frame and sets eof-reached instead of ending the file */} {(status === "ended" || p.eof) && now.kind === "episode" && } - {/* top bar */} -
- void exit()}> - - - {live && now.image && } -
-

{now.title}

- {now.subtitle &&

{now.subtitle}

} -
-
- {recordingFile && } - {!casting && } - -
-
+ void exit()} /> {/* the REC light stays on when the controls hide */} - {recordingFile && !visible && ( + {recording.recordingFile && !visible && (
- +
)} @@ -291,104 +225,199 @@ export function PlayerPage() {
)} - {/* bottom bar */} -
void toPip()} + fullscreen={fullscreen} + flipFullscreen={flipFullscreen} + /> + + {live && panel === "channels" && } +
+ ); +} + +/** Title, channel logo, REC light, stream badges and the clock. */ +function TopBar({ + now, + visible, + live, + casting, + recording, + onBack, +}: { + now: NowPlaying; + visible: boolean; + live: boolean; + casting: boolean; + recording: ReturnType; + onBack: () => void; +}) { + return ( +
+ + + + {live && now.image && } +
+

{now.title}

+ {now.subtitle &&

{now.subtitle}

} +
+
+ {recording.recordingFile && } + {!casting && } + +
+
+ ); +} + +/** Live info or the seek bar, then the transport and menu buttons. */ +function BottomBar({ + channel, + visible, + live, + vod, + casting, + poke, + transport, + zapping, + recording, + panel, + togglePanel, + closePanel, + info, + toggleInfo, + onPip, + fullscreen, + flipFullscreen, +}: { + channel?: Channel; + visible: boolean; + live: boolean; + vod: boolean; + casting: boolean; + poke: () => void; + transport: ReturnType; + zapping: ReturnType; + recording: ReturnType; + panel: Panel | null; + togglePanel: (name: Panel) => void; + closePanel: () => void; + info: boolean; + toggleInfo: () => void; + onPip: () => void; + fullscreen: boolean; + flipFullscreen: () => void; +}) { + const paused = usePlayer((s) => s.props.pause); + const { togglePause, seekBy, liveGap, goLive } = transport; + const { zapList, zap } = zapping; + const { recordingFile, toggleRecord } = recording; + return ( +
+ {live ? : vod ? : null} +
+ + {paused ? : } + + {vod && ( + <> + seekBy(-SEEK_BACK)} className="text-white"> + + + seekBy(SEEK_FWD)} className="text-white"> + + + )} - > - {live ? : vod ? : null} -
- - {p.pause ? : } - - {vod && ( - <> - seekBy(-10)} className="text-white"> - - - seekBy(30)} className="text-white"> - - - - )} - {live && zapList.length > 1 && ( - <> - zap(-1)} className="text-white"> - - - zap(1)} className="text-white"> - - - - )} - {live && !casting && ( - - + {live && zapList.length > 1 && ( + <> + zap(-1)} className="text-white"> + - )} - {live && liveGap !== null && ( - { - setLiveGap(null); - const cur = usePlayer.getState().now; - if (cur) void usePlayer.getState().play(cur); - }} - /> - )} -
- - - {!casting && ( - <> - } open={panel === "audio"} onToggle={() => setPanel(panel === "audio" ? null : "audio")}> - setPanel(null)} /> - - } open={panel === "subs"} onToggle={() => setPanel(panel === "subs" ? null : "subs")}> - setPanel(null)} /> - - } open={panel === "aspect"} onToggle={() => setPanel(panel === "aspect" ? null : "aspect")}> - setPanel(null)} /> - - {vod && ( - } open={panel === "speed"} onToggle={() => setPanel(panel === "speed" ? null : "speed")}> - setPanel(null)} /> - - )} - - )} - {live && ( - setPanel(panel === "channels" ? null : "channels")} className="text-white"> - + zap(1)} className="text-white"> + - )} - {!casting && ( - <> - void toPip()} className="text-white"> - - - setInfo((v) => !v)} className="text-white"> - - - - )} + + )} + {live && !casting && ( - {fullscreen ? : } + -
+ )} + {live && liveGap !== null && } +
+ + + {!casting && ( + <> + } open={panel === "audio"} onToggle={() => togglePanel("audio")}> + + + } open={panel === "subs"} onToggle={() => togglePanel("subs")}> + + + } open={panel === "aspect"} onToggle={() => togglePanel("aspect")}> + + + {vod && ( + } open={panel === "speed"} onToggle={() => togglePanel("speed")}> + + + )} + + )} + {live && ( + togglePanel("channels")} className="text-white"> + + + )} + {!casting && ( + <> + + + + + + + + )} + + {fullscreen ? : } +
- - {live && panel === "channels" && }
); } @@ -401,16 +430,16 @@ 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) => { + void control.setTrack("sub", action.cycle).then((ok) => { if (!ok) return; - if (action.cycle !== false) void playerWrite(setSubsEnabled(true)); + if (action.cycle !== false) void backgroundWrite(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")); + void backgroundWrite(setSubsEnabled(true)).then((ok) => ok && say("Subtitles on")); } else { - void playerWrite(setSubsEnabled(false)); + void backgroundWrite(setSubsEnabled(false)); say("Subtitles off"); } } @@ -442,14 +471,15 @@ function RecordingBadge({ since }: { since: number }) { function TechBadges() { const p = usePlayer((s) => s.props); - const res = p.videoH >= 2000 ? "4K" : p.videoH >= 1000 ? "1080p" : p.videoH >= 700 ? "720p" : p.videoH > 0 ? `${p.videoH}p` : null; + // no badge until the size is known (resolutionLabel says "SD" for small ones) + const res = p.videoH > 0 ? resolutionLabel(p.videoW, p.videoH) : null; const audio = p.tracks.find((t) => t.type === "audio" && t.selected); const ch = audio?.["demux-channel-count"]; return (
{res && {res}} {p.fps > 45 && {Math.round(p.fps)}fps} - {ch && ch > 2 && {ch === 6 ? "5.1" : ch === 8 ? "7.1" : `${ch}ch`}} + {ch && ch > 2 && {channelsLabel(ch)}}
); } @@ -527,9 +557,8 @@ function LiveInfo({ channel }: { channel?: Channel }) { const i = window.setInterval(() => tick((x) => x + 1), 30_000); return () => window.clearInterval(i); }, []); - const list = epg.data ?? []; - const cur = list.find((p) => p.start <= nowUnix() && p.stop > nowUnix()); - const next = list.find((p) => p.start >= (cur?.stop ?? nowUnix())); + const { current: cur, upcoming } = currentAndUpcoming(epg.data ?? [], nowUnix()); + const next = upcoming[0]; return (
@@ -623,17 +652,8 @@ function MenuItem({ active, onClick, children, hint }: { active: boolean; onClic ); } -const LANGS: Record = { - eng: "English", en: "English", dan: "Danish", da: "Danish", swe: "Swedish", sv: "Swedish", nor: "Norwegian", nob: "Norwegian", - no: "Norwegian", fin: "Finnish", fi: "Finnish", ger: "German", deu: "German", de: "German", fre: "French", fra: "French", - fr: "French", spa: "Spanish", es: "Spanish", ita: "Italian", it: "Italian", dut: "Dutch", nld: "Dutch", nl: "Dutch", - pol: "Polish", pl: "Polish", por: "Portuguese", pt: "Portuguese", tur: "Turkish", tr: "Turkish", ara: "Arabic", ar: "Arabic", - rus: "Russian", ru: "Russian", jpn: "Japanese", ja: "Japanese", kor: "Korean", ko: "Korean", chi: "Chinese", zho: "Chinese", - hin: "Hindi", hun: "Hungarian", ces: "Czech", cze: "Czech", gre: "Greek", ell: "Greek", heb: "Hebrew", ice: "Icelandic", -}; - function trackLabel(t: Track): string { - const lang = t.lang ? (LANGS[t.lang.toLowerCase()] ?? t.lang.toUpperCase()) : null; + const lang = languageName(t.lang); const title = t.title && t.title !== lang ? t.title : null; return [lang, title].filter(Boolean).join(" · ") || `Track ${t.id}`; } @@ -643,18 +663,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 playerWrite(api.set(type === "audio" ? "aid" : "sid", v)); + void control.setTrack(type, 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 playerWrite(setSubsEnabled(v !== "no")); + if (type === "sub") void backgroundWrite(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 playerWrite(setSubsEnabled(on)); - if (on && (current === false || current === null) && tracks.length > 0) void playerWrite(api.set("sid", tracks[0].id)); + void backgroundWrite(setSubsEnabled(on)); + if (on && (current === false || current === null) && tracks.length > 0) void control.setTrack("sub", tracks[0].id); onDone(); }; return ( @@ -718,8 +738,7 @@ 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 playerWrite(api.set("video-aspect-override", o.aspect)); - void playerWrite(api.set("panscan", o.panscan)); + void control.setAspect(o.aspect, o.panscan); onDone(); }} > @@ -739,7 +758,7 @@ function SpeedMenu({ onDone }: { onDone: () => void }) { key={v} active={Math.abs(speed - v) < 0.01} onClick={() => { - void playerWrite(api.set("speed", v)); + void control.setSpeed(v); onDone(); }} > @@ -762,22 +781,22 @@ function ChannelPanel({ channels, current, onPick }: { channels: Channel[]; curr {channels.map((c) => { const isCurrent = sameItem(c, current); return ( - + ); })}
@@ -809,11 +828,7 @@ function StatsOverlay() { /** At the end of an episode: count down and continue with the next one. */ function NextEpisode() { const now = usePlayer((s) => s.now); - const detail = useQuery({ - queryKey: ["series-detail", now?.sourceId, now?.seriesId], - queryFn: () => api.seriesDetail(now!.sourceId, now!.seriesId!), - enabled: !!now?.seriesId, - }); + const detail = useSeriesDetail(now?.seriesId ? { sourceId: now.sourceId, id: now.seriesId } : null); const id = now?.id; const season = now?.season; const episode = now?.episode; diff --git a/src/pages/Search.tsx b/src/pages/Search.tsx index 3e62197..a826637 100644 --- a/src/pages/Search.tsx +++ b/src/pages/Search.tsx @@ -6,6 +6,7 @@ import { api } from "../lib/api"; import { itemKey } from "../lib/item"; import { elapsed } from "../lib/format"; import { playChannel } from "../lib/play"; +import { ROUTES } from "../lib/routes"; import { loadJson, saveJson } from "../lib/storage"; import { ChannelLogo, PosterCard, Shelf, ShelfItem } from "../components/media"; import { QualityBadges, workSubtitle } from "../components/LibraryBrowser"; @@ -145,7 +146,7 @@ export function SearchPage() { width={160} onClick={() => { remember(); - navigate(`/movies/${m.sourceId}/${m.id}`); + navigate(ROUTES.movie(m)); }} /> @@ -165,7 +166,7 @@ export function SearchPage() { width={160} onClick={() => { remember(); - navigate(`/series/${s.sourceId}/${s.id}`); + navigate(ROUTES.series(s)); }} /> diff --git a/src/pages/SeriesDetail.tsx b/src/pages/SeriesDetail.tsx index 53bc842..f7c14a9 100644 --- a/src/pages/SeriesDetail.tsx +++ b/src/pages/SeriesDetail.tsx @@ -1,12 +1,17 @@ import clsx from "clsx"; -import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useQueryClient } from "@tanstack/react-query"; import { Check, CircleCheck, Heart, MonitorPlay, Play, Star } from "lucide-react"; import { useEffect, useState } from "react"; import { useNavigate, useParams, useSearchParams } from "react-router"; import { api } from "../lib/api"; +import { backgroundWrite } from "../lib/backgroundWrite"; import { duration, resolutionLabel } from "../lib/format"; import { openExternal, youtubeUrl } from "../lib/open"; import { playEpisode } from "../lib/play"; +import { pollWhileVersionsPending, useSeriesDetail } from "../lib/queries"; +import { invalidateWatchState } from "../lib/queryClient"; +import { queryKeys } from "../lib/queryKeys"; +import { ROUTES } from "../lib/routes"; import type { Episode, SeriesDetail } from "../lib/types"; import { DetailHero, Facts, MetaDot } from "../components/DetailHero"; import { VersionPill, Versions } from "../components/Versions"; @@ -19,13 +24,7 @@ export function SeriesDetailPage() { const navigate = useNavigate(); const qc = useQueryClient(); const sid = Number(sourceId); - const q = useQuery({ - queryKey: ["series-detail", sid, id], - queryFn: () => api.seriesDetail(sid, id!), - enabled: !!id, - // other versions' episode lists still loading: ask again a few times - refetchInterval: (query) => (query.state.data?.versionsPending && query.state.dataUpdateCount < 6 ? 3000 : false), - }); + const q = useSeriesDetail(id ? { sourceId: sid, id } : null, { refetchInterval: pollWhileVersionsPending }); const s = q.data; const [season, setSeason] = useState(() => (params.get("season") ? Number(params.get("season")) : null)); @@ -40,10 +39,11 @@ export function SeriesDetailPage() { const current = s.seasons.find((x) => x.season === season) ?? s.seasons[0]; const allEpisodes = s.seasons.flatMap((x) => x.episodes); const resumeEp = s.resume ? allEpisodes.find((e) => e.id === s.resume!.episodeId) : undefined; - const refresh = () => { - void qc.invalidateQueries({ queryKey: ["series-detail", sid, id] }); - void qc.invalidateQueries({ queryKey: ["series"] }); - void qc.invalidateQueries({ queryKey: ["continue"] }); + // favorite / watched: this page, continue watching and the series grids + const refresh = (ok: boolean) => { + if (!ok) return; + invalidateWatchState(); + void qc.invalidateQueries({ queryKey: queryKeys.works("series") }); }; const pickSeason = (n: number) => { setSeason(n); @@ -101,10 +101,7 @@ export function SeriesDetailPage() { label={s.favorite ? "Remove from favorites" : "Add to favorites"} variant="glass" size="lg" - onClick={async () => { - await api.toggleFavorite("series", s.sourceId, s.id); - refresh(); - }} + onClick={() => void backgroundWrite(api.toggleFavorite("series", s.sourceId, s.id)).then(refresh)} > @@ -140,22 +137,23 @@ export function SeriesDetailPage() { episode={e} highlighted={e.id === s.resume?.episodeId} onPlay={() => void playEpisode(s, e, navigate)} - onToggleWatched={async () => { + onToggleWatched={() => // same fields as a playback save (stores/player.ts saveProgress); // the episode's own copy of the series - await api.markWatched("episode", e.sourceId, e.id, !e.watched, { - seriesId: e.seriesId, - season: e.season, - episode: e.episode, - title: s.title, - subtitle: e.title, - image: s.cover, - backdrop: s.backdrop ?? e.image, - ext: e.ext, - duration: e.duration, - }); - refresh(); - }} + void backgroundWrite( + api.markWatched("episode", e.sourceId, e.id, !e.watched, { + seriesId: e.seriesId, + season: e.season, + episode: e.episode, + title: s.title, + subtitle: e.title, + image: s.cover, + backdrop: s.backdrop ?? e.image, + ext: e.ext, + duration: e.duration, + }), + ).then(refresh) + } /> ))}
@@ -166,10 +164,7 @@ export function SeriesDetailPage() { kind="series" versions={s.versions} pending={s.versionsPending} - onPicked={() => { - void qc.invalidateQueries({ queryKey: ["series-detail", sid, id] }); - void qc.invalidateQueries({ queryKey: ["continue"] }); - }} + onPicked={invalidateWatchState} />
@@ -184,7 +179,7 @@ export function SeriesDetailPage() { s.tmdb?.networks.length ? ( {s.tmdb.networks.map((n) => ( - ))} diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index 815c70a..431b74b 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,21 +1,26 @@ import clsx from "clsx"; -import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { CalendarSync, CircleAlert, Pencil, Plus, RefreshCw, Trash2, X } from "lucide-react"; import { useEffect, useState, type ReactNode } from "react"; import { useNavigate } from "react-router"; import { api, errorMessage } from "../lib/api"; import { ago, date } from "../lib/format"; -import { playerWrite } from "../lib/playerWrite"; +import { backgroundWrite } from "../lib/backgroundWrite"; +import { useSources } from "../lib/queries"; +import { queryKeys } from "../lib/queryKeys"; +import { ROUTES, type StartPage } from "../lib/routes"; import { useSettings, writeSetting } from "../lib/settings"; import type { Settings, Source } from "../lib/types"; import { useSync } from "../stores/sync"; import { SourceForm } from "../components/SourceForm"; -import type { StartPage } from "../app/Root"; import { Badge, Button, IconButton, ProgressBar, Segmented, Spinner, Switch, TextField } from "../components/ui"; +/** Sync counts and states change in the background (ms). */ +const SOURCES_REFRESH = 5000; + export function SettingsPage() { const navigate = useNavigate(); - const sources = useQuery({ queryKey: ["sources"], queryFn: api.sources, refetchInterval: 5000 }); + const sources = useSources({ refetchInterval: SOURCES_REFRESH }); return (

Settings

@@ -23,7 +28,7 @@ export function SettingsPage() {
} onClick={() => navigate("/onboarding?add=1")}> + } @@ -70,7 +75,12 @@ function SourceCard({ source: s }: { source: Source }) { return s.url; } })(); - const refresh = () => void qc.invalidateQueries({ queryKey: ["sources"] }); + const refresh = () => void qc.invalidateQueries({ queryKey: queryKeys.sources }); + // a failed start is said on the card (progress and failures of a running sync come as events) + const startSync = (epgOnly: boolean) => { + setError(null); + void backgroundWrite(api.syncSource(s.id, epgOnly), (e) => setError(`Couldn't sync: ${e}`)).then(refresh); + }; if (editing) { return ( @@ -107,10 +117,10 @@ function SourceCard({ source: s }: { source: Source }) {

- - + + + {clear.isError && {errorMessage(clear.error)}} +
); } diff --git a/src/pages/player/fullscreen.ts b/src/pages/player/fullscreen.ts index f93e03e..9ff92f2 100644 --- a/src/pages/player/fullscreen.ts +++ b/src/pages/player/fullscreen.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useState } from "react"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { inTauri } from "../../lib/bridge"; -import { playerWrite } from "../../lib/playerWrite"; +import { backgroundWrite } from "../../lib/backgroundWrite"; async function toggleFullscreen() { if (inTauri) { @@ -22,7 +22,7 @@ async function isFullscreen() { export function useFullscreen() { const [fullscreen, setFullscreen] = useState(false); useEffect(() => void isFullscreen().then(setFullscreen), []); - const flipFullscreen = useCallback(() => void playerWrite(toggleFullscreen().then(() => isFullscreen().then(setFullscreen))), []); + const flipFullscreen = useCallback(() => void backgroundWrite(toggleFullscreen().then(() => isFullscreen().then(setFullscreen))), []); /** Leaves fullscreen; true when it was. */ const leaveFullscreen = useCallback(async () => { if (!(await isFullscreen())) return false; diff --git a/src/pages/player/useNotice.ts b/src/pages/player/useNotice.ts new file mode 100644 index 0000000..8a742e0 --- /dev/null +++ b/src/pages/player/useNotice.ts @@ -0,0 +1,19 @@ +import { useCallback, useState } from "react"; +import { useTimeout } from "../../hooks/useTimeout"; + +/** How long a player notice ("Volume 80", "Muted") stays up (ms). */ +const NOTICE_DURATION = 4000; + +/** A short-lived message over the video; `say` replaces the one showing. */ +export function useNotice() { + const [notice, setNotice] = useState(null); + const timer = useTimeout(); + const say = useCallback( + (text: string) => { + setNotice(text); + timer.start(() => setNotice(null), NOTICE_DURATION); + }, + [timer], + ); + return { notice, say }; +} diff --git a/src/pages/player/useRecording.ts b/src/pages/player/useRecording.ts index f1f83f8..733419f 100644 --- a/src/pages/player/useRecording.ts +++ b/src/pages/player/useRecording.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { api } from "../../lib/api"; -import { playerWrite } from "../../lib/playerWrite"; +import { backgroundWrite } from "../../lib/backgroundWrite"; import { usePlayer } from "../../stores/player"; /** Recording live TV (T-035): the file being written, since when, and a toggle. */ @@ -16,7 +16,7 @@ export function useRecording(say: (text: string) => void) { }, [recordingFile, say]); const toggleRecord = useCallback(() => { const on = !usePlayer.getState().props.recording; - void playerWrite(api.record(on), (e) => say(`Can't record: ${e}`)); + void backgroundWrite(api.record(on), (e) => say(`Can't record: ${e}`)); }, [say]); return { recordingFile, recordingSince, toggleRecord }; } diff --git a/src/pages/player/useTransport.ts b/src/pages/player/useTransport.ts new file mode 100644 index 0000000..2b28056 --- /dev/null +++ b/src/pages/player/useTransport.ts @@ -0,0 +1,85 @@ +import { useCallback, useEffect, useState } from "react"; +import { useTimeout } from "../../hooks/useTimeout"; +import { control, maxVolume, usePlayer } from "../../stores/player"; + +/** Seek steps (seconds): back, forward, and either way with Shift. */ +export const SEEK_BACK = 10; +export const SEEK_FWD = 30; +export const SEEK_BIG = 60; +/** Volume change per arrow key (percent). */ +export const VOLUME_STEP = 5; +/** How long the play/pause symbol flashes (ms). */ +const FLASH_DURATION = 500; +/** mpv applies volume async: read it back this much later (ms). */ +const VOLUME_READBACK = 60; + +/** + * Play/pause, seeking, volume and mute from the player chrome and keys, with + * the feedback they give (`say`, the play/pause flash). + */ +export function useTransport(say: (text: string) => void, poke: () => void) { + const [flash, setFlash] = useState(null); + const flashTimer = useTimeout(); + const volumeTimer = useTimeout(); + + // 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 + // counts real delay. + const nowId = usePlayer((s) => s.now?.id); + const [liveGap, setLiveGap] = useState(null); + useEffect(() => setLiveGap(null), [nowId]); + + const togglePause = useCallback(() => { + const { props: cur, now: np } = usePlayer.getState(); + const paused = cur.pause; + if (!paused && np?.kind === "live" && !usePlayer.getState().cast) setLiveGap((g) => g ?? Math.max(0, cur.cacheTime - cur.timePos)); + void control.setPause(!paused); + setFlash(paused ? "play" : "pause"); + flashTimer.start(() => setFlash(null), FLASH_DURATION); + }, [flashTimer]); + + /** Back to the live edge: retunes the channel. */ + const goLive = useCallback(() => { + setLiveGap(null); + const cur = usePlayer.getState().now; + if (cur) void usePlayer.getState().play(cur); + }, []); + + const seekBy = useCallback( + (secs: number) => { + void control.seekBy(secs); + say(secs < 0 ? `« ${secs} s` : `» +${secs} s`); + poke(); + }, + [poke, say], + ); + + const nudgeVolume = useCallback( + (delta: number) => { + const st = usePlayer.getState(); + 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. + volumeTimer.start(() => { + void control.readVolume().then((v) => v !== null && say(`Volume ${Math.round(v)}`)); + }, VOLUME_READBACK); + }); + poke(); + }, + [say, poke, volumeTimer], + ); + + const toggleMute = useCallback(() => { + const st = usePlayer.getState(); + void control.setMute(!st.props.mute).then((ok) => ok && say(st.props.mute ? "Sound on" : "Muted")); + poke(); + }, [say, poke]); + + return { flash, liveGap, goLive, togglePause, seekBy, nudgeVolume, toggleMute }; +} diff --git a/src/pages/player/useZapping.ts b/src/pages/player/useZapping.ts index 28971b2..b3368e1 100644 --- a/src/pages/player/useZapping.ts +++ b/src/pages/player/useZapping.ts @@ -1,9 +1,13 @@ import { useCallback, useRef, useState } from "react"; +import { useTimeout } from "../../hooks/useTimeout"; import { channelNowPlaying } from "../../lib/play"; import type { Channel } from "../../lib/types"; import { usePlayer } from "../../stores/player"; import { zapIndex, zapStep } from "./logic"; +/** A typed channel number tunes once no digit came for this long (ms). */ +const DIGIT_WAIT = 1400; + /** Live zapping: up/down through the channel list, or a typed channel number. */ export function useZapping(poke: () => void) { const now = usePlayer((s) => s.now); @@ -27,21 +31,20 @@ export function useZapping(poke: () => void) { // number keys: up to 4 digits, tuned once typing pauses const [digits, setDigits] = useState(""); const typed = useRef(""); - const digitTimer = useRef(0); + const digitTimer = useTimeout(); 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(() => { + digitTimer.start(() => { const target = zapList.find((c) => String(c.num) === next); if (target) zapTo(target); typed.current = ""; setDigits(""); - }, 1400); + }, DIGIT_WAIT); }, - [zapList, zapTo], + [zapList, zapTo, digitTimer], ); return { zapList, zap, zapTo, digits, enterDigit }; diff --git a/src/stores/player.test.ts b/src/stores/player.test.ts index 33ba297..8fae557 100644 --- a/src/stores/player.test.ts +++ b/src/stores/player.test.ts @@ -10,8 +10,11 @@ vi.mock("../lib/api", () => ({ errorMessage: (e: unknown) => String(e), })); +import { api } from "../lib/api"; +import { queryClient } from "../lib/queryClient"; +import { SETTINGS_KEY } from "../lib/settings"; import type { CastStatus } from "../lib/types"; -import { applyProp, saveProgress, setSubsEnabled, subKeyAction, subKeyHint, trackId, usePlayer, type NowPlaying } from "./player"; +import { applyProp, castPlayerStatus, castProps, saveProgress, setSubsEnabled, subKeyAction, subKeyHint, trackId, usePlayer, type NowPlaying } from "./player"; const props = () => usePlayer.getState().props; @@ -89,23 +92,18 @@ describe("saveProgress", () => { 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 }; + const setSetting = vi.mocked(api.setSetting); queryClient.setQueryData(SETTINGS_KEY, { "player.subsEnabled": false }); - api.setSetting.mockClear(); - api.setSetting.mockResolvedValue(undefined); + setSetting.mockClear(); + setSetting.mockResolvedValue(undefined); void setSubsEnabled(true); - expect(api.setSetting).toHaveBeenCalledWith("player.subsEnabled", true); + expect(setSetting).toHaveBeenCalledWith("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_KEY, { "player.subsEnabled": false }); - api.setSetting.mockRejectedValueOnce(new Error("backend down")); + vi.mocked(api.setSetting).mockRejectedValueOnce(new Error("backend down")); await expect(setSubsEnabled(true)).rejects.toThrow("backend down"); expect(queryClient.getQueryData(SETTINGS_KEY)).toMatchObject({ "player.subsEnabled": false }); }); @@ -138,23 +136,16 @@ describe("subKeyAction (S key, PL-100)", () => { }); describe("cast", () => { - it("castProps maps the TV status onto mpv-shaped props", async () => { - const { castProps } = await import("./player"); + it("castProps maps the TV status onto mpv-shaped props", () => { 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); - expect(p.seekable).toBe(true); - expect(p.volume).toBe(70); - expect(p.mute).toBe(true); - expect(p.tracks).toEqual([]); // the TV picks its own tracks + // volume as percent; no tracks: the TV picks its own + expect(p).toMatchObject({ pause: true, timePos: 42, duration: 100, seekable: true, volume: 70, mute: true, tracks: [] }); }); - it("castPlayerStatus maps TV states to player states", async () => { - const { castPlayerStatus } = await import("./player"); + it("castPlayerStatus maps TV states to player states", () => { 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"); @@ -172,3 +163,41 @@ describe("cast", () => { expect(usePlayer.getState().castNotice).toContain("ended"); }); }); + +describe("onEvent", () => { + const movie: NowPlaying = { kind: "movie", sourceId: 1, id: "m1", title: "Heat" }; + const onEvent = (e: Parameters["onEvent"]>[0]) => usePlayer.getState().onEvent(e); + + it("ends on eof and fails on errors, with mpv's reason", () => { + usePlayer.setState({ now: movie, status: "playing" }); + onEvent({ type: "end-file", reason: "eof" }); + expect(usePlayer.getState().status).toBe("ended"); + onEvent({ type: "end-file", reason: "error", error: "no such file" }); + expect(usePlayer.getState()).toMatchObject({ status: "error", error: "Playback failed: no such file" }); + onEvent({ type: "end-file", reason: "error" }); + expect(usePlayer.getState().error).toBe("Playback failed"); + }); + + it("ignores ends while nothing plays, and stops other than eof/error", () => { + usePlayer.setState({ now: movie, status: "playing" }); + onEvent({ type: "end-file", reason: "stop" }); + expect(usePlayer.getState().status).toBe("playing"); + usePlayer.setState({ now: null, status: "idle" }); + onEvent({ type: "end-file", reason: "error", error: "x" }); + expect(usePlayer.getState()).toMatchObject({ status: "idle", error: null }); + }); + + it("counts reconnect attempts until the stream is back", () => { + usePlayer.setState({ now: movie, status: "playing" }); + onEvent({ type: "reconnecting", attempt: 2 }); + expect(usePlayer.getState()).toMatchObject({ status: "reconnecting", reconnectAttempt: 2 }); + onEvent({ type: "file-loaded" }); + expect(usePlayer.getState()).toMatchObject({ status: "playing", reconnectAttempt: 0 }); + }); + + it("leaves the TV's state alone while casting", () => { + usePlayer.setState({ now: movie, status: "playing", cast: castStatus() }); + onEvent({ type: "end-file", reason: "error", error: "mpv stopped" }); + expect(usePlayer.getState().status).toBe("playing"); + }); +}); diff --git a/src/stores/player.ts b/src/stores/player.ts index adfa764..8507391 100644 --- a/src/stores/player.ts +++ b/src/stores/player.ts @@ -1,6 +1,6 @@ import { create } from "zustand"; import { api, errorMessage } from "../lib/api"; -import { playerWrite } from "../lib/playerWrite"; +import { backgroundWrite } from "../lib/backgroundWrite"; import { invalidateWatchState, queryClient } from "../lib/queryClient"; import { writeSetting } from "../lib/settings"; import type { CastDevice, CastMeta, CastStatus, Channel, PlayKind, PlayRequest, PlayerEvent, Track } from "../lib/types"; @@ -33,7 +33,7 @@ export interface NowPlaying { catchupMinutes?: number; } -export interface Chapter { +interface Chapter { title?: string; time: number; } @@ -72,7 +72,7 @@ export interface PlaybackProps { recording: string; } -export type PlayerStatus = "idle" | "loading" | "playing" | "reconnecting" | "ended" | "error"; +type PlayerStatus = "idle" | "loading" | "playing" | "reconnecting" | "ended" | "error"; const initialProps: PlaybackProps = { pause: false, @@ -216,7 +216,7 @@ function playRequest(np: NowPlaying): PlayRequest { } /** What the TV shows about the item. */ -export function castMeta(np: NowPlaying): CastMeta { +function castMeta(np: NowPlaying): CastMeta { return { title: np.title, subtitle: np.subtitle ?? null, image: np.backdrop ?? np.image ?? null }; } @@ -293,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 playerWrite(cast ? api.castStop() : api.stop()); + await backgroundWrite(cast ? api.castStop() : api.stop()); // the page we return to may show this item's progress if (saved) invalidateWatchState(); }, @@ -331,7 +331,7 @@ export const usePlayer = create((set, get) => ({ stopCasting: async () => { if (!get().cast) return; set({ cast: null }); - await playerWrite(api.castStop()); + await backgroundWrite(api.castStop()); continueHere(); }, @@ -385,7 +385,7 @@ export const usePlayer = create((set, get) => ({ * casting (the TV's volume was showing). */ export function syncLocalVolume(): Promise { - return playerWrite( + return backgroundWrite( 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 } })), ), @@ -418,30 +418,61 @@ export const maxVolume = () => (usePlayer.getState().cast ? MAX_VOLUME_CAST : MA */ export const control = { 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); + if (usePlayer.getState().cast) return backgroundWrite(api.castControl(pause ? "pause" : "play"), onError); + return backgroundWrite(api.set("pause", pause), onError); }, seekTo(seconds: number, onError?: (message: string) => void) { const { cast, props } = usePlayer.getState(); - if (!cast) return playerWrite(api.command("seek", seconds.toFixed(2), "absolute"), onError); + if (!cast) return backgroundWrite(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 playerWrite(api.castControl("seek", t), onError); + return backgroundWrite(api.castControl("seek", t), onError); }, seekBy(seconds: number, onError?: (message: string) => void) { const { cast, props } = usePlayer.getState(); - if (!cast) return playerWrite(api.command("seek", seconds, "relative"), onError); + if (!cast) return backgroundWrite(api.command("seek", seconds, "relative"), onError); return control.seekTo(props.timePos + seconds, onError); }, /** 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); + if (usePlayer.getState().cast) return backgroundWrite(api.castControl("volume", v / 100), onError); + return backgroundWrite(api.set("volume", v), onError); }, 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); + if (usePlayer.getState().cast) return backgroundWrite(api.castControl("mute", mute ? 1 : 0), onError); + return backgroundWrite(api.set("mute", mute), onError); + }, + + // The rest exist only here: the TV picks its own tracks, picture and speed, + // so while casting they refuse (resolve false) without touching mpv. + + /** Selects an audio or subtitle track ("no" / false: none). */ + setTrack(type: "audio" | "sub", id: number | "no" | false, onError?: (message: string) => void) { + if (usePlayer.getState().cast) return Promise.resolve(false); + return backgroundWrite(api.set(type === "audio" ? "aid" : "sid", id), onError); + }, + /** Next audio track, like mpv's `cycle audio`. */ + cycleAudio(onError?: (message: string) => void) { + if (usePlayer.getState().cast) return Promise.resolve(false); + return backgroundWrite(api.command("cycle", "audio"), onError); + }, + /** Aspect override ("no" = the video's own, "16:9", …) and pan-and-scan crop (0…1). */ + setAspect(aspect: string, panscan: number, onError?: (message: string) => void) { + if (usePlayer.getState().cast) return Promise.resolve(false); + return Promise.all([backgroundWrite(api.set("video-aspect-override", aspect), onError), backgroundWrite(api.set("panscan", panscan), onError)]).then( + (oks) => oks.every(Boolean), + ); + }, + setSpeed(speed: number, onError?: (message: string) => void) { + if (usePlayer.getState().cast) return Promise.resolve(false); + return backgroundWrite(api.set("speed", speed), onError); + }, + /** mpv's volume as it applied it (clamped, async); null while casting or unknown. */ + readVolume(): Promise { + if (usePlayer.getState().cast) return Promise.resolve(null); + let volume: number | null = null; + return backgroundWrite(api.get("volume").then((v) => void (volume = typeof v === "number" ? v : null))).then(() => volume); }, }; @@ -481,11 +512,13 @@ export function subKeyHint(props: PlaybackProps): "cycle" | "on" | "off" | null return a.toggle ? "on" : "off"; } +/** The volume is saved once it has not changed for this long (ms). */ +const VOLUME_SAVE_DELAY = 1000; 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 playerWrite(api.setSetting("player.volume", Math.round(volume))), 1000); + volumeTimer = window.setTimeout(() => void backgroundWrite(api.setSetting("player.volume", Math.round(volume))), VOLUME_SAVE_DELAY); } /** @@ -496,7 +529,7 @@ 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 playerWrite( + return backgroundWrite( api.updateHistory({ kind: np.kind, sourceId: np.sourceId, @@ -527,6 +560,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]) => playerWrite(api.set(`video-margin-ratio-${side}`, clamp(v)))), + Object.entries(m).map(([side, v]) => backgroundWrite(api.set(`video-margin-ratio-${side}`, clamp(v)))), ); } diff --git a/src/stores/sync.ts b/src/stores/sync.ts index 69d4283..5687d97 100644 --- a/src/stores/sync.ts +++ b/src/stores/sync.ts @@ -1,7 +1,7 @@ import { create } from "zustand"; import type { SyncProgress } from "../lib/types"; -export interface SyncState { +interface SyncState { running: boolean; message: string; error: string | null;