//! `shell.player` — the one player, answered by the core (boundary review //! move, 5 Nov 2026: the core decides, a platform shell only draws and plays). //! A song and a film (or a series' episode) are its two //! kinds (6 Nov 2026), each played by its platform's instrument. //! //! ```json //! shell.player { op?: play|next|previous|queue_next|queue_add|shuffle|clear|seek|resume|rate|sleep|settings|refresh_link|cast|subtitles|subtitle_timing|route|use_frame|original_picture, //! table?, id?, from?, at_s?, rate?, minutes?, settings?, face?, choice?, step?, to?, paused?, path?, //! listened?: { table, id, seconds, ended?, at_s?, duration_s?, device? } } //! → { now: { kind: song|film, table, id, title, artist?, cover?, duration_s, //! song: file, gain_db, album?, album_title? //! otherwise: file? | bundle? | stream?, resume_at_s, skip_s, save_every_s, //! played_after, next_after_s, caption?, series? (a film), //! tracks? (a film: { subtitles, subtitle_language, audio_language, //! choice: {language, name} | "off" | null, offset_ms, //! timing: { title, earlier, later, reset, said } }), //! more? (a film: { title, choices: [{ id: subtitle_timing|use_frame|original_picture, //! label, needs?: subtitles, failed? }] }) }?, //! queue: [{ kind, table, id, title, artist, duration_s, cover?, caption?, file? (a song), gain_db }], //! at: { index, of }, //! position_s?, resting?, //! played_after_s, //! settings: { crossfade_s, gapless, replay_gain, speed, sleep_minutes, sleep_until?, shuffle }, //! face, faces: [{ id, label }], //! words: { nothing, offline, refused, locked }, //! cast?: { url, content_type, hls_segments?, poster?, title, caption?, expires_at } (op cast), //! route?: { to: receiver|phone, stream?, check_after_s?, said? } (op route), //! said? (use_frame, original_picture: the toast's words), //! refusal?, platform_action? } //! ``` //! //! **The queue** is the core's, one per phone (this client's folder), held //! in memory for the life of the process: what plays (`now`), what was //! queued by hand (Play next in front, Add to queue after), the rest of where //! it came from, and what played before. `play { table, id }` deals a //! song (on through its album from it), an album (disc and track order), an //! artist (albums by year, then the songs on none) or a list (the song //! table's group, in its order); an episode, a film or a series' episode //! (`shell_player_kinds`: the rest of the show, the rest of the series); //! `shuffle` with a song's record deals it shuffled, //! without one turns the rest of the run shuffled or back in its order; //! `queue_next` and `queue_add` take the same songs' records. `next` moves on (the //! first queued by hand, else the run). At the end of the queue a Next the //! person pressed (a report `skipped`, or none) moves nothing: what plays //! plays on, its report waits, and the answer's `refusal` is the kit's line //! (`player.end_of_queue`), never a silent stop; a play that `finished` or //! could not play (`stopped`) at the end ends the run. `previous` at //! `at_s` under [`RESTART_AFTER_S`] goes back one, else it starts //! again (the answer's `at` unchanged: the instrument seeks to nought, and //! the report the op carried is no play's end: nothing is written). //! `clear` stops. Nothing playing, a play to queue starts. `refresh_link` //! signs the film playing's address again (a 403 from its stream). `cast` //! hands the film playing to a receiver (a TV): the core answers `cast`, the //! address the object signs for it whether or not this phone keeps it (a //! receiver reads no file of the phone's and holds no bearer: the signed //! address is the film's folder alone, for its hours), or a refusal in the //! film's words (`shell_player_kinds::cast`). `route { to }` is the player's //! route as Apple's player sees it (cinemas-airplay, 18 Nov 2026): a sealed //! film playing to an AirPlay TV is offered on the phone's Wi-Fi address for //! as long as it plays there, or plays through the phone //! (`shell_player_kinds::route`). Every film on a TV must be seen to advance //! there (airplay-refused, 18 Nov 2026): each route says where the phone's //! player stands (`at_s`) and whether it is `paused`, and a film never seen //! playing, or one that stands still, plays through the phone //! (`shell_player_kinds::judge`). //! //! **The player is kept** (music-player-gone, 6 Nov 2026: Music always has a //! player). Whenever a song is `now` the queue is written beside the copy //! (`player.json` in this client's folder): what plays, the hand's queue, the //! run, what played before and where the song stands (`position_s`, moved by //! `seek`, which records where the instrument is without moving it). A new //! process finds it there: the last song played is `now`, `resting` at its //! place, and the instrument loads it paused; `resume` sets it playing. A run //! that ends rests on its last song, at nought. //! //! **A player before any tap** (music-player-first, 7 Nov 2026): with no //! player kept, or its song gone, and nothing playing, the player offers a //! song resting at nought: the newest listen's song still here, its run as //! its Play from its album deals it; else the first song of the first album //! in the Albums view's order, the album its run. It is the queue like any //! other (`next` moves on, `resume` plays it), but nothing is kept until a //! play begins, and a play or a queued song from elsewhere starts in its //! place. Only a copy that holds no song that can play has no player. `play { table: list, id, from }` deals a list from //! the song `from`. //! //! **A film's own subtitles** (17 Nov 2026): the //! track the owner chooses in a film's player and the timing they give it are //! that film's, kept on its row (`subtitle_choice`, `subtitle_offset`) so they //! follow it to every device. `subtitles { choice }` writes the choice (a //! rendition's `{language, name}`, or `off`) as the player reports it; //! `subtitle_timing { step }` moves the timing a tenth of a second earlier //! (-1) or later (1), or back in time (0), within half a minute either way. //! `tracks` carries both over the cinema's settings, with the control's words; //! the core owns the value and the words, the players only shift the cues. //! //! **The picture a film wears** (18 Nov 2026): the //! player's "more" choices are the core's (`more`). `use_frame { path, at_s }` //! keeps the frame the player wrote at `path` through the sealed media path //! and wears it as the film's poster (an episode's still), remembering the //! picture it replaced and where the frame was taken (`poster_before`, //! `poster_from`; `still_before`, `still_from`). `original_picture` puts the //! remembered one back. A picture found later fills only an empty column, so //! it never lands over a picked frame. //! //! **The listen** of a song is reported once, by the shell, as its play //! ends: `listened { table: song, id, seconds, ended }` rides on the op that //! leaves it (or alone, with no op, after an act moved the player). //! `seconds` is heard forward, scrubbing aside (the instrument's clock). At //! [`counts_after`] seconds (thirty, or half the song when that is less) it //! is a `listen` row (`played_at` when the song began, `from` where its play //! came from) and the song's `play_count` is one more, its and its album's //! `last_played_at` the play's, and a listen that `ended: skipped` makes its //! `skip_count` one more too; short of it and `ended: skipped`, the song's //! `skip_count` is one more; short of it otherwise, nothing is written. A //! `next` whose report names another than `now` is a late one: the listen is //! written and the player does not move again. An episode and a film report //! where they stand (`at_s`) every `save_every_s`, at a pause and as they //! leave, and the core writes their place, state and watch row by kind //! (`shell_player_kinds`); `played_after_s` is the kind's rule. //! //! **The settings** are the `face_settings` row keyed `player`, shared by //! every phone: the face worn (`song.hifi` and the four after it, the hand's //! ring in `faces`), crossfade, gapless, ReplayGain (`off`, by `song`, by //! `album`: the row's `loudness` off, track, album), speed (`rate` sets it) //! and the sleep timer's default. `sleep { minutes }` is this phone's: the //! player stops at `sleep_until` (nought clears it); a play with none set //! and a default sets it. Each song's `gain_db` is its ReplayGain by the //! setting, never lifting its peak past full scale. A film's `tracks` are //! the row keyed `cinema`'s. //! //! An act (`song`, `music_album`, `artist`: Play, Play shuffled, Play next, //! Add to queue; `film`, `film_episode`: Play, Play from the start) is this //! method too, and its answer says `platform_action: play` so the phone's //! instrument of the kind playing takes it. use std::collections::BTreeMap; use std::sync::{Mutex, MutexGuard}; use rand::seq::SliceRandom; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{iso_of_ms, now_ms}; use super::songs::{line, made, patched, rows_where, text_of, Row, ALBUM_TABLE, ARTIST_TABLE, SONG_TABLE}; use crate::methods::MethodError; use crate::shell::client::ClientController; pub const METHODS: [&str; 1] = ["shell.player"]; pub const OPS: [&str; 22] = ["prepare", "unprepare", "release", "play", "next", "previous", "queue_next", "queue_add", "shuffle", "clear", "seek", "resume", "rate", "sleep", "settings", "refresh_link", "cast", "subtitles", "subtitle_timing", "route", "use_frame", "original_picture"]; /// The file the player is kept in, in this client's folder. pub const KEPT_FILE: &str = "player.json"; /// The most songs kept as played before, when the player is written. const MOST_KEPT_BEHIND: usize = 50; /// A list a play deals: one of the song table's groups, in its order. pub const LIST: &str = "list"; pub const LISTEN_TABLE: &str = "listen"; /// How a play ended (`listen.ended`). pub const ENDED: [&str; 3] = ["finished", "skipped", "stopped"]; /// Heard this long, a song counts however long it is. pub const ENOUGH_S: f64 = 30.0; /// Back this far in, Previous starts it again instead of going back. pub const RESTART_AFTER_S: f64 = 3.0; /// The faces a song plays on, the hand's ring in order, each with its line. pub const FACES: [(&str, &str); 6] = [ ("song.hifi", "player.face_hifi"), ("song.turntable", "player.face_turntable"), ("song.amp", "player.face_amp"), ("song.party", "player.face_party"), ("song.tray", "player.face_tray"), ("song.cassette", "player.face_cassette"), ]; /// The `face_settings` row the player keeps. pub const SETTINGS_ROW: &str = "player"; pub const REPLAY_GAIN: [&str; 3] = ["off", "song", "album"]; pub const SPEEDS: (f64, f64) = (0.5, 2.0); pub const MOST_CROSSFADE_S: f64 = 12.0; /// The seconds a song `duration_s` long counts after: thirty, or half of it /// when that is less. pub fn counts_after(duration_s: f64) -> f64 { if duration_s > 0.0 { ENOUGH_S.min(duration_s / 2.0) } else { ENOUGH_S } } const SONG_COLUMNS: &str = "id, file, title, artist_name, album, duration, track_gain, track_peak, disc_number, track_number"; const ALBUM_COLUMNS: &str = "id, title, cover, album_gain, album_peak, year"; /// What plays: a song, or a film or a series' episode. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub(crate) enum Kind { #[default] Song, Film, } impl Kind { fn said(self) -> &'static str { match self { Kind::Song => "song", Kind::Film => "film", } } } /// One thing as the queue holds it. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] struct Held { kind: Kind, table: String, id: String, /// A song's and a film's media key; an episode's publisher's address. file: String, title: String, artist: String, album: Option, album_title: Option, cover: Option, duration_s: f64, track_gain: Option, track_peak: Option, album_gain: Option, album_peak: Option, /// Where an episode or a film starts. resume_at_s: f64, /// A series' episode's marquee words, and its series (an episode's show). caption: Option, series: Option, /// An episode's `played` as it was dealt. played: Option, /// A hidden title, played from inside Hidden (HIDE FROM SCREEN, owner 27 Nov 2026): wherever the phone shows what /// plays outside the app (the lock screen, the system's now playing, a TV), it says "Cinemas" and shows no picture. discreet: bool, } /// A play that began: when, and where it came from; an episode's or a /// film's watch row and whether it was played or watched already. #[derive(Debug, Clone, Default)] struct Began { id: String, at: String, from: Option, watch: Option, done: bool, } #[derive(Debug, Default)] struct Queue { now: Option, /// Queued by hand: Play next and Add to queue. queued: Vec, /// The rest of where the music came from, in the order it plays. upcoming: Vec, /// What played before, the last one last. played: Vec, /// The rest of the run in its own order, while shuffled. unshuffled: Option>, /// Where the music came from (`listen.from`). from: Option, /// The play of `now`, and the plays left whose report has not come yet. began: Option, left: Vec, /// Where `now` stood at the shell's last report. at_s: f64, /// This phone's sleep timer, as milliseconds. sleep_until: Option, /// The film playing's signed address. link: Option, /// The Wi-Fi door the film playing on a TV is offered at; shut as it goes. lan: Option, /// The watch on the film playing on a TV: it must be seen to advance there. watch: Option, /// `now` stands loaded by no instrument: kept from before this process, /// or the end of its run; the instrument holds it paused until `resume`. resting: bool, /// `now` was never played here: the song offered while no player is /// kept ([`Queue::offered`]). Nothing is kept until a play begins, and a /// play from elsewhere starts in its place. offered: bool, } /// The player as it is kept beside the copy: a song's queue and where it stands. #[derive(Debug, Default, Serialize, Deserialize)] #[serde(default)] struct Kept { now: Option, queued: Vec, upcoming: Vec, played: Vec, unshuffled: Option>, from: Option, at_s: f64, } /// The most plays left kept waiting for their report. const MOST_LEFT: usize = 8; impl Queue { /// A song becomes `now`, stamped `at`. fn hold(&mut self, song: Option, at: i64) { if let Some(began) = self.began.take() { self.left.push(began); let over = self.left.len().saturating_sub(MOST_LEFT); self.left.drain(..over); } self.began = song.as_ref().map(|song| Began { id: song.id.clone(), at: iso_of_ms(at), from: self.from.clone(), ..Began::default() }); self.now = song; self.at_s = 0.0; self.resting = false; self.offered = false; } /// The run is over: the player rests on its last song, at nought, its play /// left waiting for a report; with none played, nothing plays. fn rest(&mut self, now: i64) { let Some(last) = self.now.clone().filter(|held| held.kind == Kind::Song) else { return self.hold(None, now) }; self.hold(Some(last), now); self.resting = true; } /// The player from the file beside the copy: the last song resting where /// it stood, while that song is still here. fn restored(client: &ClientController, now: i64) -> Result { let path = client.layout().client_dir().join(KEPT_FILE); let Some(kept) = std::fs::read(&path).ok().and_then(|bytes| serde_json::from_slice::(&bytes).ok()) else { return Ok(Queue::default()) }; let Some(song) = kept.now.filter(|held| held.kind == Kind::Song && !held.id.is_empty()) else { return Ok(Queue::default()) }; let id = song.id.clone(); let here = client .read_rows("shell.player", &mut |ctx| Ok(json!(playable(ctx)?.iter().any(|(song, _)| *song == id)))) .map_err(|why| MethodError::new("unreadable", why))?; if here != json!(true) { return Ok(Queue::default()); } let mut queue = Queue { queued: kept.queued, upcoming: kept.upcoming, played: kept.played, unshuffled: kept.unshuffled, from: kept.from, ..Queue::default() }; queue.hold(Some(song), now); queue.at_s = kept.at_s.max(0.0); queue.resting = true; Ok(queue) } /// With no player kept (or its song gone), the song offered resting at /// nought: the newest listen's song still here, its run dealt as its /// Play from its album deals it; else the first song of the first album /// in the Albums view's order, its album the run ([`first_offered`]). /// No song here, no player. fn offered(client: &ClientController, now: i64) -> Result, MethodError> { let first = client.read_rows("shell.player", &mut |ctx| first_offered(ctx)).map_err(|why| MethodError::new("unreadable", why))?; let (Some(table), Some(id)) = (first["table"].as_str(), first["id"].as_str()) else { return Ok(None) }; let dealt = deal(client, table, id, "here")?; if dealt.songs.is_empty() { return Ok(None); } let mut queue = Queue { from: dealt.from, ..Queue::default() }; queue.play(dealt.songs, dealt.at, now); queue.resting = true; queue.offered = true; Ok(Some(queue)) } /// The player written beside the copy while a song is `now`; anything /// else playing leaves the last song's as it was. fn keep(&self, client: &ClientController) -> Result<(), MethodError> { let Some(now) = self.now.as_ref().filter(|held| held.kind == Kind::Song && !self.offered) else { return Ok(()) }; let behind = self.played.len().saturating_sub(MOST_KEPT_BEHIND); let kept = Kept { now: Some(now.clone()), queued: self.queued.clone(), upcoming: self.upcoming.clone(), played: self.played[behind..].to_vec(), unshuffled: self.unshuffled.clone(), from: self.from.clone(), at_s: self.at_s, }; let dir = client.layout().client_dir(); let bytes = serde_json::to_vec(&kept).map_err(|why| MethodError::new("unwritable", why.to_string()))?; // not a copy: the player's kept list. cotton_client::whole_file::replace(&dir.join(KEPT_FILE), &bytes) .map_err(|why| MethodError::new("unwritable", format!("the player could not be kept: {why}"))) } /// Play from here: `songs` are where it came from, `at` the one asked. fn play(&mut self, songs: Vec, at: usize, now: i64) { if let Some(current) = self.now.as_ref().filter(|_| !self.offered) { self.played.push(current.clone()); } let mut songs = songs; let rest = songs.split_off(at.min(songs.len().saturating_sub(1)) + 1); self.upcoming = rest; self.unshuffled = None; self.hold(songs.pop(), now); } /// The whole of `songs` in a new order, from its first. fn shuffle_play(&mut self, songs: Vec, now: i64) { let mut dealt = songs.clone(); dealt.shuffle(&mut rand::thread_rng()); self.play(dealt, 0, now); self.unshuffled = Some(songs); } /// The rest of the run in a new order, or back in its own from just /// after the song playing. fn shuffle_rest(&mut self) { if let Some(own) = self.unshuffled.take() { let at = self.now.as_ref().and_then(|song| own.iter().position(|one| one.id == song.id)); self.upcoming = match at { Some(at) => own[at + 1..].to_vec(), None => own, }; return; } self.unshuffled = Some(self.upcoming.clone()); self.upcoming.shuffle(&mut rand::thread_rng()); } fn queue_next(&mut self, songs: Vec, now: i64) { if self.now.is_none() || self.offered { return self.play(songs, 0, now); } self.queued.splice(0..0, songs); } fn queue_add(&mut self, songs: Vec, now: i64) { if self.now.is_none() || self.offered { return self.play(songs, 0, now); } self.queued.extend(songs); } /// The song after: the first queued by hand, else the run's next; none /// at the end, and nothing plays. fn advance(&mut self, now: i64) { let following = if !self.queued.is_empty() { Some(self.queued.remove(0)) } else if !self.upcoming.is_empty() { Some(self.upcoming.remove(0)) } else { None }; if let Some(current) = self.now.clone() { self.played.push(current); } self.hold(following, now); } /// Previous at `at_s` into the song: back a song when it has played less /// than [`RESTART_AFTER_S`] and one played before, else nothing moves. fn back(&mut self, at_s: f64, now: i64) -> bool { if at_s >= RESTART_AFTER_S || self.played.is_empty() { self.at_s = 0.0; return false; } let before = self.played.pop(); if let Some(current) = self.now.clone() { self.upcoming.insert(0, current); } self.hold(before, now); true } fn clear(&mut self, now: i64) { let sleep_until = self.sleep_until; self.hold(None, now); let left = std::mem::take(&mut self.left); *self = Queue { left, sleep_until, ..Queue::default() }; } /// What plays after `now`, in order. fn after(&self) -> impl Iterator { self.queued.iter().chain(self.upcoming.iter()) } /// The play a report names: `now`'s, else one left. fn began_of(&mut self, id: &str) -> Option { if self.began.as_ref().is_some_and(|began| began.id == id) { return self.began.clone(); } let at = self.left.iter().rposition(|began| began.id == id)?; Some(self.left.remove(at)) } } static QUEUES: Mutex> = Mutex::new(BTreeMap::new()); /// HIDE FROM SCREEN (coordinator's review, 27 Nov 2026): whether a film or an episode in the queue is discreet is /// worked out now, from the categories as they stand (THE predicate), never remembered from how its play began: a /// category hidden mid-film, here or on another phone, veils what plays at the next answer, and one shown again /// lifts it. Read only when a film or an episode is in the queue. fn veil(client: &ClientController, key: &str) -> Result<(), MethodError> { let films = |queue: &Queue| queue.now.iter().chain(queue.after()).chain(queue.played.iter()).any(|held| held.kind != Kind::Song); if !queues().get(key).is_some_and(films) { return Ok(()); } let shut = crate::phone::cinemas_home::hidden_titles_of(client)?; if let Some(queue) = queues().get_mut(key) { let Queue { now, queued, upcoming, played, unshuffled, .. } = queue; for held in now.iter_mut().chain(queued.iter_mut()).chain(upcoming.iter_mut()).chain(played.iter_mut()).chain(unshuffled.iter_mut().flatten()) { held.discreet = held.kind != Kind::Song && shut.contains(&held.id); } } Ok(()) } fn queues() -> MutexGuard<'static, BTreeMap> { QUEUES.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } /// One phone's queue key: the client's own folder, so two cores in one /// process (a test, a share extension) never share a queue. fn queue_key(client: &ClientController) -> String { client.layout().client_dir().display().to_string() } fn bad(why: impl Into) -> MethodError { MethodError::new("bad_request", why.into()) } pub fn call(client: &ClientController, request: &Value) -> Result { let fields = request.as_object().ok_or_else(|| bad("shell.player takes an object"))?; const KNOWN: [&str; 18] = ["op", "table", "id", "from", "at_s", "rate", "minutes", "settings", "face", "listened", "choice", "step", "phone_language", "to", "paused", "path", "network", "hidden"]; if let Some(unknown) = fields.keys().find(|key| !KNOWN.contains(&key.as_str())) { return Err(bad(format!("shell.player has no field `{unknown}`"))); } let op = match fields.get("op") { None | Some(Value::Null) => None, Some(Value::String(op)) if OPS.contains(&op.as_str()) => Some(op.as_str()), Some(_) => return Err(bad(format!("an op is one of {}", OPS.join(", ")))), }; let listened = fields.get("listened").filter(|value| !value.is_null()).map(Listened::read).transpose()?; let number = |key: &str| fields.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()); let (table, id) = (fields.get("table").and_then(Value::as_str), fields.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty())); // The film playing now, by its file: what RELAY 2's window store keeps beside the one prepared. let playing_file = || queues().get(&queue_key(client)).and_then(|queue| queue.now.clone()).filter(|held| held.kind == Kind::Film).map(|held| held.file); match op { Some("prepare") => { // A page opened: its film's first window fetched ahead of Play, the queue untouched (PLAYER START). let table = table.filter(|table| KIND_TABLES.contains(table)).ok_or_else(|| bad("prepare names an episode, a film or a series: table"))?; let id = id.ok_or_else(|| bad("prepare names the record's id"))?; let network = fields.get("network").and_then(Value::as_str); return Ok(json!({ "prepared": kinds::prepare(client, table, id, network, playing_file().as_deref(), fields.get("hidden") == Some(&Value::Bool(true)))? })); } Some("unprepare") => { kinds::unprepare(client, playing_file().as_deref()); return Ok(json!({ "prepared": false })); } Some("release") => { // The app gone to the background, or the player closed: every film's windows let go (RELAY 2). kinds::settle(client, None, true); return Ok(json!({ "released": true })); } _ => {} } let now_ms = clock(client)?; let mut settings = Settings::read(client)?; let key = queue_key(client); // The player kept beside the copy, read once a process; with none, or // nothing playing since, the song offered (music-player-first, 7 Nov // 2026: Music always has a player, before any tap). if !queues().contains_key(&key) { let restored = Queue::restored(client, now_ms)?; queues().entry(key.clone()).or_insert(restored); } if queues().get(&key).is_some_and(|queue| queue.now.is_none()) { if let Some(offered) = Queue::offered(client, now_ms)? { let mut all = queues(); let queue = all.entry(key.clone()).or_default(); if queue.now.is_none() { let (left, sleep_until) = (std::mem::take(&mut queue.left), queue.sleep_until); *queue = Queue { left, sleep_until, ..offered }; } } } let from = fields.get("from").and_then(Value::as_str).map(str::trim).filter(|from| !from.is_empty()); // The record a play names, dealt before the queue is held. let dealt = match (op, table) { (Some("play"), Some(table)) if KIND_TABLES.contains(&table) => { let id = id.ok_or_else(|| bad("a play names the record's id"))?; // A film or an episode played from inside Hidden (`hidden: true`): found among the hidden titles, only while // this account's Hidden is open (refused `locked` otherwise, as every hidden call). let hidden = fields.get("hidden") == Some(&Value::Bool(true)); let dealt = kinds::deal(client, table, id, number("at_s"), hidden)?; Some(Dealt { songs: dealt.items, at: 0, from: None, refusal: dealt.refusal }) } (Some("shuffle" | "queue_next" | "queue_add"), Some(table)) if KIND_TABLES.contains(&table) => { return Err(bad("an episode or a film plays; only songs shuffle and queue")); } (Some("play" | "shuffle" | "queue_next" | "queue_add"), Some(table)) => { let id = id.ok_or_else(|| bad("a play names the record's id"))?; let how = if matches!(op, Some("queue_next" | "queue_add")) { "queue" } else { "here" }; let mut dealt = deal(client, table, id, how)?; // A list played from one of its songs starts there. if let Some(from) = from.filter(|_| table == LIST && op == Some("play")) { dealt.at = dealt.songs.iter().position(|song| song.id == from).ok_or_else(|| bad("that song is not on the list"))?; } Some(dealt) } (Some("play" | "queue_next" | "queue_add"), None) => return Err(bad("a play names a song, an album, an artist, a list, an episode or a film")), _ => None, }; // The play the report names, found before the queue moves. let began = listened.as_ref().and_then(|report| queues().entry(key.clone()).or_default().began_of(&report.id)); let mut refusal = None; // A Previous that starts the song again, or a Next at the end of the // queue, leaves no play: its report waits. let mut stayed = false; let mut acted = false; { let mut all = queues(); let queue = all.entry(key.clone()).or_default(); match op { None => {} Some("play" | "shuffle" | "queue_next" | "queue_add") if dealt.is_some() => { let dealt = dealt.expect("a dealt play"); acted = true; if dealt.songs.is_empty() { refusal = Some(match dealt.refusal { Some(said) => said, None => line("player.nothing", &[])?, }); } else { let starts = queue.now.is_none() || queue.offered || matches!(op, Some("play" | "shuffle")); if starts { queue.from = dealt.from.clone(); } match op { Some("play") => queue.play(dealt.songs, dealt.at, now_ms), Some("shuffle") => queue.shuffle_play(dealt.songs, now_ms), Some("queue_next") => queue.queue_next(dealt.songs, now_ms), _ => queue.queue_add(dealt.songs, now_ms), } if starts && queue.sleep_until.is_none() && settings.sleep_minutes > 0.0 { queue.sleep_until = Some(now_ms + (settings.sleep_minutes * 60_000.0) as i64); } } } Some("shuffle") => queue.shuffle_rest(), Some("next") => { let late = listened.as_ref().is_some_and(|report| queue.now.as_ref().is_some_and(|now| now.id != report.id)); // The play ran out or could not play: the run moves on, or ends. let ran_out = listened.as_ref().is_some_and(|report| report.ended.as_deref().is_some_and(|ended| ended != "skipped")); if !late && queue.now.is_some() { let last = queue.queued.is_empty() && queue.upcoming.is_empty(); if last && !ran_out { stayed = true; refusal = Some(line("player.end_of_queue", &[])?); } else if last { queue.rest(now_ms); } else { queue.advance(now_ms); } } } Some("previous") => { if queue.now.is_some() { let at = number("at_s").unwrap_or(queue.at_s); stayed = !queue.back(at, now_ms); } } Some("clear") => queue.clear(now_ms), Some("seek") => queue.at_s = number("at_s").filter(|at| *at >= 0.0).ok_or_else(|| bad("a seek says at_s, the seconds into the song"))?, Some("resume") => { // A song resting begins its play now, not when it was laid down. if let Some(began) = queue.began.as_mut().filter(|_| queue.resting) { began.at = iso_of_ms(now_ms); } queue.resting = false; queue.offered = false; } Some("sleep") => { let minutes = number("minutes").filter(|minutes| *minutes >= 0.0).ok_or_else(|| bad("a sleep says its minutes; nought stops the timer"))?; queue.sleep_until = (minutes > 0.0).then(|| now_ms + (minutes * 60_000.0) as i64); } Some(_) => {} } if queue.sleep_until.is_some_and(|until| until <= now_ms) { queue.sleep_until = None; } // A link is the film's it was signed for. if queue.link.as_ref().is_some_and(|link| queue.now.as_ref().is_none_or(|now| now.id != link.id)) { queue.link = None; } // And so is a Wi-Fi door: the play it was opened for is over. if queue.lan.as_ref().is_some_and(|lan| queue.now.as_ref().is_none_or(|now| now.id != lan.id)) { queue.lan = None; } if queue.watch.as_ref().is_some_and(|watch| queue.now.as_ref().is_none_or(|now| now.id != watch.id)) { queue.watch = None; } } // RELAY 2: what the play left behind lets go: only the film playing now, and one prepared, keep their windows // (a stop, a clear, a play run out or moved on frees the rest). if op.is_some() || listened.is_some() { kinds::settle(client, playing_file().as_deref(), false); } // An episode's or a film's place is written however the op went; a // song's listen waits for the play's end. if let Some(report) = listened.as_ref().filter(|report| !stayed || report.table != SONG_TABLE) { if report.table == SONG_TABLE { write_listen(client, report, began, now_ms)?; } else { let wrote = kinds::write(client, report, began.as_ref())?; let mut all = queues(); let queue = all.entry(key.clone()).or_default(); if let Some(began) = queue.began.as_mut().filter(|began| began.id == report.id) { began.watch = wrote.watch; began.done = wrote.done; } } } let mut said = None; match op { Some("rate") => { let rate = number("rate").ok_or_else(|| bad("a rate says how fast"))?; settings = settings.write(client, &json!({ "speed": rate }), None)?; } Some("settings") => { let face = fields.get("face").filter(|face| !face.is_null()).map(|face| face.as_str().ok_or_else(|| bad("a face is named by its id"))).transpose()?; let asked = fields.get("settings").cloned().unwrap_or(Value::Null); if face.is_none() && asked.is_null() { return Err(bad("settings writes a face, its settings, or both")); } settings = settings.write(client, &asked, face)?; } Some("subtitles" | "subtitle_timing") => { let held = queues().get(&key).and_then(|queue| queue.now.clone()).filter(|held| held.kind == Kind::Film).ok_or_else(|| bad("only a film playing chooses or times its subtitles"))?; if op == Some("subtitles") { kinds::choose_subtitles(client, &held, fields.get("choice").unwrap_or(&Value::Null))?; } else { let step = number("step").filter(|step| [-1.0, 0.0, 1.0].contains(step)).ok_or_else(|| bad("a subtitle timing step is -1 (earlier), 1 (later) or 0 (back in time)"))?; kinds::step_timing(client, &held, step as i64)?; } } Some("use_frame" | "original_picture") => { let held = queues().get(&key).and_then(|queue| queue.now.clone()).filter(|held| held.kind == Kind::Film).ok_or_else(|| bad("only a film playing picks its picture"))?; let cover = if op == Some("use_frame") { let path = fields.get("path").and_then(Value::as_str).map(str::trim).filter(|path| !path.is_empty()).ok_or_else(|| bad("use_frame names the frame's file (path)"))?; let at = number("at_s").filter(|at| *at >= 0.0).ok_or_else(|| bad("use_frame says where in the film the frame was taken (at_s)"))?; let (kept, words) = kinds::use_frame(client, &held, std::path::Path::new(path), at)?; said = Some(words); Some(kept) } else { let (back, words) = kinds::original_picture(client, &held)?; said = Some(words); back }; if let Some(now) = queues().get_mut(&key).and_then(|queue| queue.now.as_mut()).filter(|now| now.id == held.id) { now.cover = cover; } } _ => {} } // What plays is discreet when it is hidden now, wherever its play began: worked out before any word of it is said. veil(client, &key)?; // A film this phone does not keep plays from the address the object // signs: signed as it starts, and again when its stream refused it. let playing = queues().get(&key).and_then(|queue| queue.now.clone().map(|now| (now, queue.link.clone()))); if let Some((held, link)) = playing.as_ref().filter(|(held, _)| held.kind != Kind::Song && refusal.is_none()) { let words = words(Some(held))?; let asked = op == Some("refresh_link"); if asked && held.kind != Kind::Film { return Err(bad("only a film's stream is signed again")); } // A link to the phone's own door (a sealed whole film, R6) is good // only while that door stands: an iPhone takes a suspended app's // listener back, and the film is then offered again at the door // opened in its place, however new the link is. let stands = link.as_ref().is_none_or(|link| cotton_client::media::loopback::stands(&link.url)); let fresh = stands && link.as_ref().is_some_and(|link| now_ms - link.minted_ms < kinds::RELINK_AFTER_MS); if (asked || link.is_none() || !stands) && kinds::needs_link(client, held)? { if asked && fresh { refusal = words["refused"].as_str().map(str::to_string); } else { match kinds::mint(client, held, now_ms, words.as_object().expect("the words")) { Ok(minted) => { if let Some(queue) = queues().get_mut(&key).filter(|queue| queue.now.as_ref().is_some_and(|now| now.id == held.id)) { queue.link = Some(minted); } } Err(said) => refusal = Some(said), } } } } // Handed to a receiver: the signed address, minted for it even when the // film is kept here. let mut cast = None; if op == Some("cast") { let playing = queues().get(&key).and_then(|queue| queue.now.clone().map(|now| (now, queue.link.clone()))); let (held, link) = playing.filter(|(held, _)| held.kind == Kind::Film).ok_or_else(|| bad("only a film playing is cast"))?; let words = words(Some(&held))?; match kinds::cast(client, &held, link.as_ref(), now_ms, words.as_object().expect("the words")) { Ok((said, minted)) => { if let Some(queue) = queues().get_mut(&key).filter(|queue| queue.now.as_ref().is_some_and(|now| now.id == held.id)) { queue.link = Some(minted); } cast = Some(said); } Err(said) => refusal = Some(said), } } // The film playing's route, as Apple's player sees it. let mut route = None; if op == Some("route") { let to = fields.get("to").and_then(Value::as_str).filter(|to| kinds::ROUTES.contains(to)).ok_or_else(|| bad(format!("a route is to one of {}", kinds::ROUTES.join(", "))))?; let mut all = queues(); let queue = all.get_mut(&key).expect("the queue held"); let held = queue.now.clone().filter(|held| held.kind == Kind::Film).ok_or_else(|| bad("only a film playing is routed"))?; let paused = fields.get("paused").and_then(Value::as_bool).unwrap_or(false); route = Some(kinds::route(to, &held, queue.link.as_ref(), &mut queue.lan, &mut queue.watch, number("at_s"), paused, wifi(), instant())?); } let (queue_now, link) = queues().get(&key).map(|queue| (queue.now.clone(), queue.link.clone())).expect("the queue held"); let mut playing_now = Map::new(); if let Some(held) = queue_now.as_ref().filter(|held| held.kind != Kind::Song) { playing_now = kinds::source(client, held, link.as_ref())?; if held.kind == Kind::Film { let phone = fields.get("phone_language").and_then(Value::as_str); playing_now.insert("tracks".into(), kinds::tracks(client, held, phone)?); playing_now.insert("more".into(), kinds::more(client, held)?); } } let all = queues(); let queue = all.get(&key).expect("the queue held"); if op.is_some() || listened.is_some() { queue.keep(client)?; } let mut answer = answer(queue, &settings, playing_now)?; if let Some(refusal) = refusal { answer["refusal"] = json!(refusal); } if let Some(cast) = cast { answer["cast"] = cast; } if let Some(route) = route { answer["route"] = route; } if let Some(said) = said { answer["said"] = json!(said); } if acted { answer["platform_action"] = json!("play"); } Ok(answer) } #[cfg(test)] thread_local! { /// A test's Wi-Fi address, in place of this machine's. pub(super) static WIFI: std::cell::Cell>> = const { std::cell::Cell::new(None) }; } #[cfg(test)] thread_local! { /// How far a test's clock stands past this machine's. pub(super) static LATER: std::cell::Cell = const { std::cell::Cell::new(std::time::Duration::ZERO) }; } /// The instant a film on a TV is watched by (`kinds::judge`). fn instant() -> std::time::Instant { #[cfg(test)] return std::time::Instant::now() + LATER.with(std::cell::Cell::get); #[cfg(not(test))] std::time::Instant::now() } /// This phone's Wi-Fi address now (`cotton_client::media::lan`). fn wifi() -> Option { #[cfg(test)] if let Some(set) = WIFI.with(std::cell::Cell::get) { return set; } cotton_client::media::lan::wifi_address() } /// The phone's clock, as the core reads it for a write. fn clock(client: &ClientController) -> Result { client .read_rows("shell.player", &mut |ctx| Ok(json!(now_ms(ctx)))) .map_err(|why| MethodError::new("unreadable", why))? .as_i64() .ok_or_else(|| MethodError::new("unreadable", "the clock said nothing")) } // ── the answer ────────────────────────────────────────────────────────────── fn answer(queue: &Queue, settings: &Settings, playing: Map) -> Result { let faces: Vec = FACES.iter().map(|(id, said)| Ok(json!({ "id": id, "label": line(said, &[])? }))).collect::>()?; let mut held_settings = json!({ "crossfade_s": settings.crossfade_s, "gapless": settings.gapless, "replay_gain": settings.replay_gain, "speed": settings.speed, "sleep_minutes": settings.sleep_minutes, "shuffle": queue.unshuffled.is_some(), }); if let Some(until) = queue.sleep_until { held_settings["sleep_until"] = json!(iso_of_ms(until)); } let mut answer = json!({ "queue": queue.after().map(|song| queued(song, settings)).collect::>(), "at": { "index": queue.played.len(), "of": queue.played.len() + usize::from(queue.now.is_some()) + queue.queued.len() + queue.upcoming.len() }, "played_after_s": queue.now.as_ref().map_or(counts_after(0.0), played_after_s), "settings": held_settings, "face": settings.face, "faces": faces, "words": words(queue.now.as_ref())?, }); if queue.now.is_some() { answer["position_s"] = json!(queue.at_s); if queue.resting { answer["resting"] = json!(true); } } if let Some(song) = &queue.now { let mut now = queued(song, settings); if song.kind == Kind::Song { for (key, value) in [("album", &song.album), ("album_title", &song.album_title)] { if let Some(value) = value { now[key] = json!(value); } } } else { now["resume_at_s"] = json!(song.resume_at_s); now["skip_s"] = json!(kinds::SKIP_S); now["save_every_s"] = json!(kinds::save_every(song.kind)); now["played_after"] = json!(kinds::played_share(song.kind)); // A series' next episode plays itself after a count; the show's after none. let next_after = if song.table == kinds::FILM_EPISODE_TABLE && queue.after().next().is_some() { kinds::NEXT_COUNT_S } else { 0.0 }; now["next_after_s"] = json!(next_after); // What it belongs to: a series' episode's series. if let Some(series) = &song.series { now["series"] = json!(series); } for (key, value) in playing { now[key] = value; } } answer["now"] = now; } Ok(answer) } /// The seconds past which a play of `held` counts: a song's rule, else its /// kind's share of what it lasts (nought while that is not known). fn played_after_s(held: &Held) -> f64 { match held.kind { Kind::Song => counts_after(held.duration_s), kind => kinds::played_share(kind) * held.duration_s.max(0.0), } } /// What the instrument says when it cannot play, in the words of the kind /// playing (a song's when nothing does). fn words(now: Option<&Held>) -> Result { let discreet = kinds::discreet_title(); let title = now.map(|held| if held.discreet { discreet.as_str() } else { held.title.as_str() }).unwrap_or_default(); match now.map(|held| held.kind) { Some(Kind::Film) => { let refused = kinds::card_line("film.could_not_play", &[])?; let offline = crate::phone::film_player::line("player.offline", &[("title", title)])?; Ok(json!({ "nothing": refused, "offline": offline, "refused": refused, "locked": refused })) } _ => Ok(json!({ "nothing": line("player.nothing", &[])?, "offline": line("player.offline", &[("title", title)])?, "refused": line("player.could_not_play", &[("title", title)])?, "locked": line("player.locked", &[("title", title)])?, })), } } fn queued(song: &Held, settings: &Settings) -> Value { if song.discreet { // A hidden title: its kind and id for the player's own work, never its name, its show or its picture. return json!({ "kind": song.kind.said(), "table": song.table, "id": song.id, "title": kinds::discreet_title(), "artist": "", "duration_s": song.duration_s, "gain_db": settings.gain_db(song), "discreet": true, }); } let mut said = json!({ "kind": song.kind.said(), "table": song.table, "id": song.id, "title": song.title, "artist": song.artist, "duration_s": song.duration_s, "gain_db": settings.gain_db(song), }); // A song's file is the key the instrument opens; an episode's and a // film's source is `now`'s alone. if song.kind == Kind::Song { said["file"] = json!(song.file); } if let Some(cover) = &song.cover { said["cover"] = json!(cover); } if let Some(caption) = &song.caption { said["caption"] = json!(caption); } said } // ── dealing ───────────────────────────────────────────────────────────────── struct Dealt { songs: Vec, at: usize, from: Option, /// The person's words when nothing could be dealt. refusal: Option, } /// The songs here that can play (a song with a file), with their albums. fn playable(ctx: &Ctx<'_>) -> Result, String> { if !super::songs::holds_table(ctx, SONG_TABLE)? { return Ok(vec![]); } let songs = rows_where(ctx, SONG_TABLE, "id, album", "file IS NOT NULL AND trim(file) != ''", &[])?; Ok(songs.iter().map(|song| (text_of(song, "id"), text_of(song, "album"))).collect()) } /// What the player offers while none is kept, as `{table, id}` to deal from /// `here` (null when no song can play): the song of the newest listen whose /// song is still here; else the first album, in the Albums view's own order, /// holding a song that can play; else the first such song on no album. fn first_offered(ctx: &Ctx<'_>) -> Result { let songs = playable(ctx)?; if songs.is_empty() { return Ok(Value::Null); } if super::songs::holds_table(ctx, LISTEN_TABLE)? { let mut listens = rows_where(ctx, LISTEN_TABLE, "song, played_at", "song IS NOT NULL", &[])?; listens.sort_by(|one, other| text_of(other, "played_at").cmp(&text_of(one, "played_at"))); if let Some(song) = listens.iter().map(|listen| text_of(listen, "song")).find(|song| songs.iter().any(|(id, _)| id == song)) { return Ok(json!({ "table": SONG_TABLE, "id": song })); } } let mut albums = rows_where(ctx, ALBUM_TABLE, "*", "1", &[])?; let tools = cotton_tools::definitions::tool_definitions(ctx).map_err(|why| why.to_string())?.definitions; let sort = tools .iter() .flat_map(|tool| tool.views.iter()) .find(|view| view.id == ALBUMS_VIEW && view.read.get("table").and_then(Value::as_str) == Some(ALBUM_TABLE)) .and_then(|view| view.sort.clone()); if let Some(sort) = sort { albums.sort_by(|one, other| super::business::compare(one, other, &sort).then_with(|| text_of(one, "id").cmp(&text_of(other, "id")))); } if let Some(album) = albums.iter().map(|album| text_of(album, "id")).find(|album| songs.iter().any(|(_, on)| on == album)) { return Ok(json!({ "table": ALBUM_TABLE, "id": album })); } let mut loose: Vec = rows_where(ctx, SONG_TABLE, "id, title, disc_number, track_number", "file IS NOT NULL AND trim(file) != ''", &[])?; loose.retain(|song| songs.iter().any(|(id, album)| *id == text_of(song, "id") && album.is_empty())); Ok(in_order(loose).first().map_or(Value::Null, |song| json!({ "table": SONG_TABLE, "id": text_of(song, "id") }))) } /// The Albums view, whose order the player offers from. const ALBUMS_VIEW: &str = "albums"; /// The tables whose records play as films. const KIND_TABLES: [&str; 2] = [crate::phone::film_player::FILM_TABLE, kinds::FILM_EPISODE_TABLE]; /// The songs a record deals, the one asked, and where the play came from /// (`listen.from`). A song played from `here` plays on through its album /// from it; queued it is the song alone. A song with no file is left out. fn deal(client: &ClientController, table: &str, id: &str, how: &str) -> Result { if ![SONG_TABLE, ALBUM_TABLE, ARTIST_TABLE, LIST].contains(&table) { return Err(bad("a play names a song, an album, an artist, a list, an episode or a film")); } if table != LIST { crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?; } let (table, id, how) = (table.to_string(), id.to_string(), how.to_string()); let read = client .read_rows("shell.player", &mut |ctx| { let (songs, at, through) = dealt(ctx, &table, &id, &how)?; Ok(json!({ "songs": songs, "at": at, "through": through })) }) .map_err(|why| MethodError::new("unreadable", why))?; let songs: Vec = read["songs"].as_array().into_iter().flatten().map(held_of).collect(); let from = match (how.as_str(), table.as_str()) { ("queue", _) => "queue", (_, ARTIST_TABLE) => "artist", (_, ALBUM_TABLE) => "album", (_, LIST) => "playlist", _ if read["through"].as_bool() == Some(true) => "album", _ => "songs", }; Ok(Dealt { songs, at: read["at"].as_u64().unwrap_or(0) as usize, from: Some(from.to_string()), refusal: None }) } fn dealt(ctx: &Ctx<'_>, table: &str, id: &str, how: &str) -> Result<(Vec, usize, bool), String> { let text = |value: &str| rusqlite::types::Value::Text(value.to_string()); let (songs, at) = match table { SONG_TABLE => { let Some(song) = rows_where(ctx, SONG_TABLE, SONG_COLUMNS, "id = ?", &[text(id)])?.into_iter().next() else { return Ok((vec![], 0, false)) }; let album = text_of(&song, "album"); if how == "here" && !album.is_empty() { let songs = in_order(rows_where(ctx, SONG_TABLE, SONG_COLUMNS, "album = ?", &[text(&album)])?); let at = songs.iter().position(|one| text_of(one, "id") == id).unwrap_or(0); (songs, at) } else { (vec![song], 0) } } ALBUM_TABLE => (in_order(rows_where(ctx, SONG_TABLE, SONG_COLUMNS, "album = ?", &[text(id)])?), 0), ARTIST_TABLE => { let mut albums = rows_where(ctx, ALBUM_TABLE, ALBUM_COLUMNS, "artist = ?", &[text(id)])?; albums.sort_by_key(|one| (year(one), text_of(one, "title"))); let ids: Vec = albums.iter().map(|album| text_of(album, "id")).collect(); let mut songs = Vec::new(); for album in &ids { songs.extend(in_order(rows_where(ctx, SONG_TABLE, SONG_COLUMNS, "album = ?", &[text(album)])?)); } let loose = rows_where(ctx, SONG_TABLE, SONG_COLUMNS, "artist = ?", &[text(id)])?; songs.extend(in_order(loose.into_iter().filter(|song| !ids.contains(&text_of(song, "album"))).collect())); (songs, 0) } _ => (list_songs(ctx, id)?, 0), }; let albums = albums_of(ctx, &songs)?; let mut held = Vec::new(); let mut start = 0; for (index, song) in songs.iter().enumerate() { if text_of(song, "file").trim().is_empty() { continue; } if index == at { start = held.len(); } let mut song = song.clone(); if let Some(album) = albums.get(&text_of(&song, "album")) { for (to, from) in [("album_title", "title"), ("cover", "cover"), ("album_gain", "album_gain"), ("album_peak", "album_peak")] { song.insert(to.into(), album.get(from).cloned().unwrap_or(Value::Null)); } } held.push(Value::Object(song)); } let through = table == SONG_TABLE && songs.len() > 1; Ok((held, start, through)) } /// A list's songs in its order: the song table's group, its members by place. fn list_songs(ctx: &Ctx<'_>, group: &str) -> Result, String> { let workspace = rusqlite::types::Value::Text(ctx.workspace_id.to_string()); let group = rusqlite::types::Value::Text(group.to_string()); let held = ctx .db() .get("SELECT table_id FROM cotton_groups WHERE id = ? AND workspace_id = ? AND deleted_at IS NULL", &[group.clone(), workspace.clone()]) .map_err(|error| error.to_string())?; match held.as_ref().and_then(|row| row.text("table_id").map(str::to_string)) { Some(table) if table == SONG_TABLE => {} Some(_) => return Err("that list is not a list of songs".into()), None => return Err("no such list is here".into()), } let members = ctx .db() .all("SELECT record_id FROM cotton_group_members WHERE group_id = ? AND workspace_id = ? ORDER BY place", &[group, workspace]) .map_err(|error| error.to_string())?; let ids: Vec = members.iter().filter_map(|row| row.text("record_id").map(str::to_string)).collect(); if ids.is_empty() { return Ok(vec![]); } let marks = vec!["?"; ids.len()].join(", "); let args: Vec = ids.iter().cloned().map(rusqlite::types::Value::Text).collect(); let mut found: BTreeMap = rows_where(ctx, SONG_TABLE, SONG_COLUMNS, &format!("id IN ({marks})"), &args)?.into_iter().map(|song| (text_of(&song, "id"), song)).collect(); Ok(ids.iter().filter_map(|id| found.remove(id)).collect()) } fn albums_of(ctx: &Ctx<'_>, songs: &[Row]) -> Result, String> { let mut ids: Vec = songs.iter().map(|song| text_of(song, "album")).filter(|album| !album.is_empty()).collect(); ids.sort(); ids.dedup(); if ids.is_empty() { return Ok(BTreeMap::new()); } let marks = vec!["?"; ids.len()].join(", "); let args: Vec = ids.into_iter().map(rusqlite::types::Value::Text).collect(); Ok(rows_where(ctx, ALBUM_TABLE, ALBUM_COLUMNS, &format!("id IN ({marks})"), &args)?.into_iter().map(|album| (text_of(&album, "id"), album)).collect()) } /// Songs in disc and track order, the title after. fn in_order(mut songs: Vec) -> Vec { let place = |song: &Row, key: &str| song.get(key).and_then(Value::as_f64).unwrap_or(f64::MAX); songs.sort_by(|one, other| { (place(one, "disc_number"), place(one, "track_number")) .partial_cmp(&(place(other, "disc_number"), place(other, "track_number"))) .unwrap_or(std::cmp::Ordering::Equal) .then_with(|| text_of(one, "title").cmp(&text_of(other, "title"))) }); songs } fn year(album: &Row) -> String { match album.get("year") { Some(Value::String(year)) => year.clone(), Some(Value::Number(year)) => year.to_string(), _ => "9999".to_string(), } } fn held_of(row: &Value) -> Held { let text = |key: &str| row.get(key).and_then(Value::as_str).map(str::trim).filter(|said| !said.is_empty()).map(str::to_string); let number = |key: &str| row.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()); Held { kind: Kind::Song, table: SONG_TABLE.to_string(), id: text("id").unwrap_or_default(), file: text("file").unwrap_or_default(), title: text("title").unwrap_or_default(), artist: text("artist_name").unwrap_or_default(), album: text("album"), album_title: text("album_title"), cover: text("cover"), duration_s: number("duration").unwrap_or(0.0), track_gain: number("track_gain"), track_peak: number("track_peak"), album_gain: number("album_gain"), album_peak: number("album_peak"), ..Held::default() } } // ── the listen ────────────────────────────────────────────────────────────── /// The shell's report of a play: a song's once, as it ends; an episode's /// and a film's where it stands, while it plays and as it ends. #[derive(Debug, Clone)] struct Listened { table: String, id: String, seconds: f64, ended: Option, at_s: Option, duration_s: Option, device: Option, } impl Listened { fn read(value: &Value) -> Result { let fields = value.as_object().ok_or_else(|| bad("listened is an object: table, id, seconds, ended or at_s"))?; if let Some(unknown) = fields.keys().find(|key| !matches!(key.as_str(), "table" | "id" | "seconds" | "ended" | "at_s" | "duration_s" | "device")) { return Err(bad(format!("listened has no field `{unknown}`"))); } let text = |key: &str| fields.get(key).and_then(Value::as_str).map(str::trim).filter(|said| !said.is_empty()).map(str::to_string); let seconds_of = |field: &str| fields.get(field).filter(|value| !value.is_null()).map(|value| value.as_f64().filter(|seconds| seconds.is_finite() && *seconds >= 0.0).ok_or_else(|| bad(format!("listened's {field} is seconds, nought or more")))).transpose(); let table = text("table").filter(|table| table == SONG_TABLE || KIND_TABLES.contains(&table.as_str())).ok_or_else(|| bad("listened names its table: song, episode, film or film_episode"))?; let id = text("id").ok_or_else(|| bad("listened names its record"))?; let seconds = seconds_of("seconds")?.ok_or_else(|| bad("listened says how many seconds were heard"))?; let ended = match text("ended") { Some(ended) if ENDED.contains(&ended.as_str()) => Some(ended), Some(_) => return Err(bad("listened ended finished, skipped or stopped")), None => None, }; let at_s = seconds_of("at_s")?; if table == SONG_TABLE && ended.is_none() { return Err(bad("a song's listen ended finished, skipped or stopped")); } if table != SONG_TABLE && at_s.is_none() { return Err(bad("an episode's or a film's report says at_s, where it stands")); } Ok(Listened { table, id, seconds, ended, at_s, duration_s: seconds_of("duration_s")?, device: text("device") }) } } /// The report written: a listen row and the counts, a skip, or nothing. fn write_listen(client: &ClientController, report: &Listened, began: Option, now_ms: i64) -> Result<(), MethodError> { let report = report.clone(); let whole = |n: f64| json!(n.round() as i64); client .write_rows("shell.player", &mut |ctx| { let song = rows_where(ctx, SONG_TABLE, "id, album, duration, play_count, skip_count", "id = ?", &[rusqlite::types::Value::Text(report.id.clone())])? .into_iter() .next() .ok_or_else(|| format!("no song {} is here to have been heard", report.id))?; let ended = report.ended.clone().unwrap_or_default(); let duration = song.get("duration").and_then(Value::as_f64).unwrap_or(0.0); if report.seconds < counts_after(duration) { if ended == "skipped" { let count = song.get("skip_count").and_then(Value::as_i64).unwrap_or(0); patched(ctx, SONG_TABLE, &report.id, Map::from_iter([("skip_count".to_string(), json!(count + 1))]))?; } return Ok(Value::Null); } let played_at = began.as_ref().map_or_else(|| iso_of_ms(now_ms - (report.seconds * 1000.0) as i64), |began| began.at.clone()); let mut data = Map::new(); data.insert("song".into(), json!(report.id)); data.insert("played_at".into(), json!(played_at)); data.insert("seconds".into(), whole(report.seconds)); data.insert("ended".into(), json!(ended)); if let Some(from) = began.as_ref().and_then(|began| began.from.clone()) { data.insert("from".into(), json!(from)); } if let Some(device) = &report.device { data.insert("device".into(), json!(device)); } made(ctx, LISTEN_TABLE, data)?; // The listen row is what the counts follow: each makes play_count // one more, and one that ended skipped skip_count one more too. let count = |column: &str| song.get(column).and_then(Value::as_i64).unwrap_or(0) + 1; let mut counts = Map::from_iter([("play_count".to_string(), json!(count("play_count"))), ("last_played_at".to_string(), json!(played_at))]); if ended == "skipped" { counts.insert("skip_count".to_string(), json!(count("skip_count"))); } patched(ctx, SONG_TABLE, &report.id, counts)?; // The album's last play, unless this play already stands there. let album = text_of(&song, "album"); let stands = rows_where(ctx, ALBUM_TABLE, "id, last_played_at", "id = ?", &[rusqlite::types::Value::Text(album.clone())])? .first() .is_some_and(|held| text_of(held, "last_played_at") == played_at); if !album.is_empty() && !stands { patched(ctx, ALBUM_TABLE, &album, Map::from_iter([("last_played_at".to_string(), json!(played_at))]))?; } Ok(Value::Null) }) .map_err(|why| MethodError::new("listen_refused", why))?; Ok(()) } // ── the settings row ──────────────────────────────────────────────────────── #[derive(Debug, Clone, PartialEq)] struct Settings { /// The table of face choices and its row key, where the database keeps one. table: Option<(String, String)>, face: String, crossfade_s: f64, gapless: bool, replay_gain: String, speed: f64, sleep_minutes: f64, } impl Settings { fn read(client: &ClientController) -> Result { let mut table = None; client .read_rows("shell.player", &mut |ctx| { let listed = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?; table = super::catalogue::FaceChoiceTable::of(&listed.definitions).map(|choices| (choices.table, choices.row_key)); Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; let row = match &table { Some((id, _)) => match crate::phone::records::call(client, "records.get", &json!({"table": id, "id": SETTINGS_ROW})) { Ok(read) => read["data"].as_object().cloned().unwrap_or_default(), Err(error) if crate::phone::copy_standing::absent(&error.code) => Map::new(), Err(error) => return Err(error), }, None => Map::new(), }; Ok(Settings::of(table, &row)) } /// The row as it stands: an empty column is the default, a face this /// build does not offer the hi-fi. fn of(table: Option<(String, String)>, row: &Map) -> Settings { let number = |key: &str| row.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()); let face = row.get("face").and_then(Value::as_str).map(|face| format!("song.{face}")).filter(|face| FACES.iter().any(|(id, _)| id == face)); Settings { table, face: face.unwrap_or_else(|| FACES[0].0.to_string()), crossfade_s: number("crossfade_seconds").map_or(0.0, |seconds| seconds.clamp(0.0, MOST_CROSSFADE_S)), gapless: row.get("gapless").and_then(Value::as_bool).unwrap_or(true), replay_gain: match row.get("loudness").and_then(Value::as_str) { Some("track") => "song", Some("album") => "album", _ => "off", } .to_string(), speed: number("speed").filter(|speed| *speed > 0.0).map_or(1.0, |speed| speed.clamp(SPEEDS.0, SPEEDS.1)), sleep_minutes: number("sleep_timer_minutes").map_or(0.0, |minutes| minutes.max(0.0)), } } /// `asked`'s settings and `face` written on the row (the object's upsert /// by the row's key, the face riding with every write); the settings as /// they then stand. Nothing changed is nothing written. fn write(&self, client: &ClientController, asked: &Value, face: Option<&str>) -> Result { let mut patch = Map::new(); if let Some(face) = face { let worn = FACES.iter().find(|(id, _)| *id == face).ok_or_else(|| bad("a player's face is song.hifi, song.turntable, song.amp, song.party, song.tray or song.cassette"))?; patch.insert("face".into(), json!(worn.0.trim_start_matches("song."))); } if !asked.is_null() { let asked = asked.as_object().ok_or_else(|| bad("settings is an object"))?; for (key, value) in asked { let number = value.as_f64().filter(|value| value.is_finite()); match key.as_str() { "crossfade_s" => { let seconds = number.filter(|seconds| (0.0..=MOST_CROSSFADE_S).contains(seconds)).ok_or_else(|| bad("a crossfade is nought to twelve seconds"))?; patch.insert("crossfade_seconds".into(), json!(seconds)); } "gapless" => { patch.insert("gapless".into(), json!(value.as_bool().ok_or_else(|| bad("gapless is on or off"))?)); } "replay_gain" => { let loudness = match value.as_str() { Some("off") => "off", Some("song") => "track", Some("album") => "album", _ => return Err(bad("replay_gain is off, song or album")), }; patch.insert("loudness".into(), json!(loudness)); } "speed" => { let speed = number.filter(|speed| (SPEEDS.0..=SPEEDS.1).contains(speed)).ok_or_else(|| bad("a speed is half to twice the song's own"))?; patch.insert("speed".into(), json!(speed)); } "sleep_minutes" => { let minutes = number.filter(|minutes| *minutes >= 0.0).ok_or_else(|| bad("the sleep timer's default is its minutes, nought for none"))?; patch.insert("sleep_timer_minutes".into(), json!(minutes)); } other => return Err(bad(format!("the player has no setting `{other}`"))), } } } let mut row = self.row(); row.extend(patch.clone()); let next = Settings::of(self.table.clone(), &row); if next == *self { return Ok(next); } let (table, row_key) = self.table.clone().ok_or_else(|| MethodError::new("unwritable", "this database keeps no face choices"))?; let mut data = patch; data.insert(row_key, json!(SETTINGS_ROW)); data.insert("face".into(), json!(next.face.trim_start_matches("song."))); crate::phone::records::call(client, "records.create", &json!({"table": table, "data": data}))?; Ok(next) } fn row(&self) -> Map { let mut row = Map::new(); row.insert("face".into(), json!(self.face.trim_start_matches("song."))); row.insert("crossfade_seconds".into(), json!(self.crossfade_s)); row.insert("gapless".into(), json!(self.gapless)); row.insert("loudness".into(), json!(if self.replay_gain == "song" { "track" } else { self.replay_gain.as_str() })); row.insert("speed".into(), json!(self.speed)); row.insert("sleep_timer_minutes".into(), json!(self.sleep_minutes)); row } /// The gain, in decibels, `song` plays at: its ReplayGain by the song or /// by the album (the song's own where the album has none), never lifting /// its peak past full scale; nought with ReplayGain off or no tag. fn gain_db(&self, song: &Held) -> f64 { let (gain, peak) = match self.replay_gain.as_str() { "song" => (song.track_gain, song.track_peak), "album" if song.album_gain.is_some() => (song.album_gain, song.album_peak), "album" => (song.track_gain, song.track_peak), _ => return 0.0, }; let Some(gain) = gain else { return 0.0 }; match peak.filter(|peak| *peak > 0.0) { Some(peak) => gain.min(-20.0 * peak.log10()), None => gain, } } } /// The ISO instant `text` says, as milliseconds (a test's reading of `sleep_until`). #[cfg(test)] fn ms_of(text: &str) -> Option { cotton_tools::mcp::handlers::common::parse_ms(text) } #[path = "shell_player_kinds.rs"] pub(crate) mod kinds; #[cfg(test)] #[path = "shell_player_tests.rs"] mod tests;