diff --git a/docs/local-control.md b/docs/local-control.md index 838ab9c..02d863a 100644 --- a/docs/local-control.md +++ b/docs/local-control.md @@ -96,6 +96,23 @@ support. API transfers back to this computer preserve pause. Existing TUI "play here" behavior is unchanged. Jam volume keeps its existing local semantics. Commands use the same playback transitions/effects as media keys. +## Likes + +`track.liked` is the current music track's state in the user's library. +Furumi omits the field while likes are loading and for items such as podcast +episodes. Older servers also omit it. Clients enable the heart when they +receive a boolean and send the exact `track.key` from that snapshot. + +```json +{"type":"command","id":"deck-42","command":{"type":"set_liked","track_key":"lib:17","liked":true}} +``` + +Both `true` and `false` set the requested state. Furumi rejects a key for a +track that is no longer current and acknowledges a successful save after +reading the state back from the library. Control and Jam clients edit their +own personal library. Content-addressed likes use the normal trusted-device +replication path. + ## Artwork The optional track `artwork_id` is opaque. Request it with diff --git a/integrations/control-protocol/src/lib.rs b/integrations/control-protocol/src/lib.rs index 4a33fa5..848d747 100644 --- a/integrations/control-protocol/src/lib.rs +++ b/integrations/control-protocol/src/lib.rs @@ -107,6 +107,10 @@ pub struct Track { pub artist: String, pub album: String, pub year: Option, + /// Personal library state for this track. Absent on older servers and + /// when the current item cannot be liked. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub liked: Option, /// Opaque reference; clients cannot ask the server to read arbitrary paths. pub artwork_id: Option, } @@ -154,6 +158,10 @@ pub enum Command { ToggleShuffle, CycleRepeat, StartRadio, + SetLiked { + track_key: String, + liked: bool, + }, Transfer { device_id: String, }, diff --git a/integrations/opendeck/README.md b/integrations/opendeck/README.md index 98aba40..f280d90 100644 --- a/integrations/opendeck/README.md +++ b/integrations/opendeck/README.md @@ -62,8 +62,17 @@ the full release cover and opens Functions. A music-note icon appears when a cov is unavailable. The Devices key inside Functions shows the role and current audio owner. -Functions has **Radio** at the top left, **Devices** beside it, and a compact back caret -at the bottom right. Other cells are blank. Radio starts Furumi's similarity +The top row of Functions starts with **Like**, **Devices**, and **Radio**. +The back caret is at the bottom right. The Like key sits directly under the +album-cover key, so two taps on that physical key like the playing track. +A filled heart marks a liked track. To remove the like, tap the heart and let +the fill fade for three seconds, or tap again during the fade to remove it +immediately. Leaving Functions or changing tracks cancels a pending fade. +After Furumi saves the change, the heart shows the new state for half a second +and the deck returns to playback. The heart is dimmed for podcast episodes +and when the connected player does not supply a liked state. + +Radio starts Furumi's similarity radio; its key shows an animated spinner while local/federation results are collected and the first track is prepared. It returns to the player only for a new radio operation that Furumi reports as actually playing, never merely on diff --git a/integrations/opendeck/assets/icons/README.md b/integrations/opendeck/assets/icons/README.md index e8587f0..1382b06 100644 --- a/integrations/opendeck/assets/icons/README.md +++ b/integrations/opendeck/assets/icons/README.md @@ -1,4 +1,4 @@ -# Embedded Phosphor Fill icon atlas +# Embedded Phosphor icon atlas The Rust runtime decodes `phosphor-atlas.png` once and uses its alpha channel as colourable masks. It does not require Node, an SVG parser, system icons or @@ -6,6 +6,8 @@ network access. - `phosphor-fill/`: unmodified original SVGs from the official [Phosphor core repository](https://github.com/phosphor-icons/core/tree/main/assets/fill). +- `phosphor-regular/heart.svg`: the matching outline for the Like key. Its + silhouette aligns with the filled heart throughout the removal animation. - `phosphor-atlas.svg`: editable named elements at their production placement. - `phosphor-atlas.json`: tile names, offsets, source URLs and original SHA-256. - `../PHOSPHOR-LICENSE.txt`: unmodified MIT license for the source icons. diff --git a/integrations/opendeck/assets/icons/build-atlas.cjs b/integrations/opendeck/assets/icons/build-atlas.cjs index 332f33a..b8b7224 100644 --- a/integrations/opendeck/assets/icons/build-atlas.cjs +++ b/integrations/opendeck/assets/icons/build-atlas.cjs @@ -28,12 +28,14 @@ const specs = [ ['Album', 'music-note-simple', 56, 48, 48], ['Check', 'check', 20, 80, 13], ['Unavailable', 'prohibit', 20, 80, 13], + ['Heart', 'heart', 56, 48, 48, 'regular'], + ['HeartFill', 'heart', 56, 48, 48], ['CoverFrame', null, 0, 0, 0], ['EnabledFrame', null, 0, 0, 0], ]; -function glyph(name, size, centreX, centreY) { - const filename = path.join(__dirname, 'phosphor-fill', `${name}.svg`); +function glyph(name, size, centreX, centreY, weight = 'fill') { + const filename = path.join(__dirname, `phosphor-${weight}`, `${name}.svg`); const original = fs.readFileSync(filename, 'utf8'); // Preserve the official paths. Only set viewport, placement and colour. @@ -48,11 +50,11 @@ function glyph(name, size, centreX, centreY) { }); } -const tiles = specs.map(([id, name, size, centreX, centreY]) => ({ +const tiles = specs.map(([id, name, size, centreX, centreY, weight]) => ({ id, // The frame is custom: 4 px outside inset, 4 px stroke, outside radius 10 px. content: name - ? glyph(name, size, centreX, centreY) + ? glyph(name, size, centreX, centreY, weight) : id === 'CoverFrame' ? '' : '', @@ -67,8 +69,8 @@ for (let step = 0; step < 8; step++) { let svg = [ '', - 'Furumi / Phosphor Fill alpha atlas', - '96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill SVG geometry. Custom enabled frame.', + 'Furumi / Phosphor alpha atlas', + '96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill and Regular SVG geometry. Custom frames.', ].join(''); const metadata = []; @@ -122,18 +124,20 @@ for (let position = 0; position < tileSize; position++) { } } -const sourceDirectory = path.join(__dirname, 'phosphor-fill'); -const filenames = fs.readdirSync(sourceDirectory) - .filter(name => name.endsWith('.svg')) - .sort(); -const sources = filenames.map(filename => { - const data = fs.readFileSync(path.join(sourceDirectory, filename)); - const name = filename.slice(0, -4); - return { - file: `phosphor-fill/${filename}`, - url: `https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/${name}-fill.svg`, - sha256: crypto.createHash('sha256').update(data).digest('hex'), - }; +const sources = ['fill', 'regular'].flatMap(weight => { + const directory = `phosphor-${weight}`; + const files = fs.readdirSync(path.join(__dirname, directory)) + .filter(name => name.endsWith('.svg')) + .sort(); + return files.map(filename => { + const file = `${directory}/${filename}`; + const upstream = weight === 'regular' ? filename : filename.replace('.svg', '-fill.svg'); + return { + file, + url: `https://raw.githubusercontent.com/phosphor-icons/core/main/assets/${weight}/${upstream}`, + sha256: crypto.createHash('sha256').update(fs.readFileSync(path.join(__dirname, file))).digest('hex'), + }; + }); }); const atlasMetadata = { diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.json b/integrations/opendeck/assets/icons/phosphor-atlas.json index d9ece71..f722005 100644 --- a/integrations/opendeck/assets/icons/phosphor-atlas.json +++ b/integrations/opendeck/assets/icons/phosphor-atlas.json @@ -133,7 +133,7 @@ "height": 96 }, { - "name": "CoverFrame", + "name": "Heart", "index": 16, "x": 0, "y": 192, @@ -141,7 +141,7 @@ "height": 96 }, { - "name": "EnabledFrame", + "name": "HeartFill", "index": 17, "x": 96, "y": 192, @@ -149,7 +149,7 @@ "height": 96 }, { - "name": "Spinner0", + "name": "CoverFrame", "index": 18, "x": 192, "y": 192, @@ -157,7 +157,7 @@ "height": 96 }, { - "name": "Spinner1", + "name": "EnabledFrame", "index": 19, "x": 288, "y": 192, @@ -165,7 +165,7 @@ "height": 96 }, { - "name": "Spinner2", + "name": "Spinner0", "index": 20, "x": 384, "y": 192, @@ -173,7 +173,7 @@ "height": 96 }, { - "name": "Spinner3", + "name": "Spinner1", "index": 21, "x": 480, "y": 192, @@ -181,7 +181,7 @@ "height": 96 }, { - "name": "Spinner4", + "name": "Spinner2", "index": 22, "x": 576, "y": 192, @@ -189,7 +189,7 @@ "height": 96 }, { - "name": "Spinner5", + "name": "Spinner3", "index": 23, "x": 672, "y": 192, @@ -197,7 +197,7 @@ "height": 96 }, { - "name": "Spinner6", + "name": "Spinner4", "index": 24, "x": 0, "y": 288, @@ -205,12 +205,28 @@ "height": 96 }, { - "name": "Spinner7", + "name": "Spinner5", "index": 25, "x": 96, "y": 288, "width": 96, "height": 96 + }, + { + "name": "Spinner6", + "index": 26, + "x": 192, + "y": 288, + "width": 96, + "height": 96 + }, + { + "name": "Spinner7", + "index": 27, + "x": 288, + "y": 288, + "width": 96, + "height": 96 } ], "sources": [ @@ -239,6 +255,11 @@ "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/fast-forward-fill.svg", "sha256": "8be39d806d46384a635c53ffef51e9c19f91fcbb54901fc52c59ee290edbaf8b" }, + { + "file": "phosphor-fill/heart.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/heart-fill.svg", + "sha256": "d90560d4f762f1b345bd2322cd1ef696926ffa74b0c1396933b6d926faf8341e" + }, { "file": "phosphor-fill/music-note-simple.svg", "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/music-note-simple-fill.svg", @@ -303,6 +324,11 @@ "file": "phosphor-fill/vinyl-record.svg", "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/fill/vinyl-record-fill.svg", "sha256": "92552f12cb4dd696977bd7fe04e2a7d35f57fb5e265de8091a817d45433e2296" + }, + { + "file": "phosphor-regular/heart.svg", + "url": "https://raw.githubusercontent.com/phosphor-icons/core/main/assets/regular/heart.svg", + "sha256": "312dee73d1d969631d5498012f619ccf4edbdf31e1be3e65af4f4f1b3ac1b2dd" } ], "license": "MIT", diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.png b/integrations/opendeck/assets/icons/phosphor-atlas.png index 602c81b..216b4d6 100644 Binary files a/integrations/opendeck/assets/icons/phosphor-atlas.png and b/integrations/opendeck/assets/icons/phosphor-atlas.png differ diff --git a/integrations/opendeck/assets/icons/phosphor-atlas.svg b/integrations/opendeck/assets/icons/phosphor-atlas.svg index 78bff5f..9137d6a 100644 --- a/integrations/opendeck/assets/icons/phosphor-atlas.svg +++ b/integrations/opendeck/assets/icons/phosphor-atlas.svg @@ -1 +1 @@ -Furumi / Phosphor Fill alpha atlas96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill SVG geometry. Custom enabled frame. +Furumi / Phosphor alpha atlas96px cells, eight columns. White alpha masks recoloured by the Rust renderer. Original Phosphor Fill and Regular SVG geometry. Custom frames. diff --git a/integrations/opendeck/assets/icons/phosphor-fill/heart.svg b/integrations/opendeck/assets/icons/phosphor-fill/heart.svg new file mode 100644 index 0000000..21b6fb7 --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-fill/heart.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/assets/icons/phosphor-regular/heart.svg b/integrations/opendeck/assets/icons/phosphor-regular/heart.svg new file mode 100644 index 0000000..c7248cb --- /dev/null +++ b/integrations/opendeck/assets/icons/phosphor-regular/heart.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/integrations/opendeck/src/heart.rs b/integrations/opendeck/src/heart.rs new file mode 100644 index 0000000..deb003c --- /dev/null +++ b/integrations/opendeck/src/heart.rs @@ -0,0 +1,86 @@ +use furumi_control_protocol::Command; +use std::time::{Duration, Instant}; + +pub const REMOVE_DELAY: Duration = Duration::from_secs(3); +pub const SAVED_DISPLAY: Duration = Duration::from_millis(500); +pub const RESULT_TIMEOUT: Duration = Duration::from_secs(10); + +#[derive(Clone)] +pub enum Phase { + Fading(Instant), + Sending, + Waiting(String, Instant), + Confirmed(Instant), +} +#[derive(Clone)] +pub struct Heart { + pub key: String, + pub liked: bool, + pub phase: Phase, +} + +impl Heart { + pub fn press(&mut self) -> Option { + if matches!(self.phase, Phase::Fading(_)) { + self.phase = Phase::Sending; + Some(self.command()) + } else { + None + } + } + + pub fn command(&self) -> Command { + Command::SetLiked { + track_key: self.key.clone(), + liked: self.liked, + } + } + + pub fn due(&mut self, now: Instant) -> Option { + if let Phase::Fading(start) = self.phase + && now.saturating_duration_since(start) >= REMOVE_DELAY + { + return self.press(); + } + None + } + + pub fn fill(&self, now: Instant) -> f32 { + match self.phase { + Phase::Fading(start) => { + 1.0 - (now.saturating_duration_since(start).as_secs_f32() + / REMOVE_DELAY.as_secs_f32()) + .clamp(0.0, 1.0) + } + Phase::Confirmed(_) if self.liked => 1.0, + _ => 0.0, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn removal_waits_three_seconds_and_repeat_press_sends_once() { + let now = Instant::now(); + let mut h = Heart { + key: "a".into(), + liked: false, + phase: Phase::Fading(now), + }; + assert!(h.due(now + Duration::from_millis(2999)).is_none()); + assert!((h.fill(now + Duration::from_millis(1500)) - 0.5).abs() < 0.001); + assert!(h.due(now + Duration::from_secs(3)).is_some()); + assert_eq!(h.fill(now + REMOVE_DELAY), 0.0); + assert!(h.press().is_none()); + h.phase = Phase::Fading(now); + assert!(h.press().is_some()); + assert_eq!(h.fill(now), 0.0); + h.phase = Phase::Waiting("request".into(), now); + assert_eq!(h.fill(now), 0.0); + h.phase = Phase::Confirmed(now); + assert_eq!(h.fill(now), 0.0); + assert!(h.press().is_none()); + } +} diff --git a/integrations/opendeck/src/icons.rs b/integrations/opendeck/src/icons.rs index 8cad269..47f85a6 100644 --- a/integrations/opendeck/src/icons.rs +++ b/integrations/opendeck/src/icons.rs @@ -1,4 +1,4 @@ -//! Genuine Phosphor Fill masks, rasterised at authoring time from the bundled +//! Phosphor masks, rasterised at authoring time from the bundled //! source SVGs. No SVG/Node dependency or OS-specific font is needed at runtime. use std::sync::LazyLock; @@ -9,7 +9,7 @@ const COLUMNS: u32 = 8; static ATLAS: LazyLock = LazyLock::new(|| { let image = image::load_from_memory(include_bytes!("../assets/icons/phosphor-atlas.png")) - .expect("bundled Phosphor Fill alpha atlas must decode") + .expect("bundled Phosphor alpha atlas must decode") .into_rgba8(); assert_eq!( image.dimensions(), @@ -39,6 +39,8 @@ pub enum Icon { Album, Check, Unavailable, + Heart, + HeartFill, CoverFrame, EnabledFrame, } @@ -148,7 +150,7 @@ pub fn cover_glyph( #[cfg(test)] mod tests { use super::*; - const ALL: [Icon; 18] = [ + const ALL: [Icon; 20] = [ Icon::Previous, Icon::Play, Icon::Pause, @@ -165,6 +167,8 @@ mod tests { Icon::Album, Icon::Check, Icon::Unavailable, + Icon::Heart, + Icon::HeartFill, Icon::CoverFrame, Icon::EnabledFrame, ]; diff --git a/integrations/opendeck/src/main.rs b/integrations/opendeck/src/main.rs index 232f5ff..76acbb0 100644 --- a/integrations/opendeck/src/main.rs +++ b/integrations/opendeck/src/main.rs @@ -1,6 +1,7 @@ #![cfg_attr(target_os = "windows", windows_subsystem = "windows")] mod artwork; mod client; +mod heart; mod host; mod icons; mod model; @@ -76,6 +77,8 @@ impl Surface { self.sequence += 1; let kind = if matches!(command, Command::Artwork { .. }) { "art" + } else if matches!(command, Command::SetLiked { .. }) { + "like" } else { "command" }; @@ -91,6 +94,7 @@ impl Surface { self.keys_dirty = true; for deck in self.decks.values_mut() { deck.presses.clear(); + deck.heart = None; deck.pending = None; deck.radio = None; deck.remote = RemoteGate::default(); @@ -137,6 +141,29 @@ impl Surface { id.starts_with(&format!("{}-art-", self.session_id)) } + fn finish_heart(&mut self, id: &str, accepted: bool, error: Option<&str>) -> bool { + if !id.starts_with(&format!("{}-like-", self.session_id)) { + return false; + } + for deck in self.decks.values_mut() { + let Some(heart) = &mut deck.heart else { + continue; + }; + if !matches!(&heart.phase, heart::Phase::Waiting(request, _) if request == id) { + continue; + } + let now = Instant::now(); + if accepted { + heart.phase = heart::Phase::Confirmed(now); + } else { + deck.heart = None; + deck.notice = Some((error.unwrap_or("Could not update like").to_owned(), now)); + } + self.keys_dirty = true; + } + true + } + fn host_event(&mut self, event: host::Event) -> Option { self.keys_dirty = true; match event.event.as_str() { @@ -179,6 +206,14 @@ impl Surface { if let Some(instance) = self.instances.remove(&event.context) { if let Some(deck) = self.decks.get_mut(&instance.device) { deck.presses.remove(&event.context); + if instance.slot == Some(0) + && deck + .heart + .as_ref() + .is_some_and(|h| matches!(h.phase, heart::Phase::Fading(_))) + { + deck.heart = None; + } } self.sent.remove(&event.context); if !self.instances.values().any(|i| i.device == instance.device) { @@ -208,6 +243,16 @@ impl Surface { let instance = self.instances.get(&event.context)?.clone(); let deck = self.decks.get_mut(&instance.device)?; let binding = deck.presses.remove(&event.context)?; + if matches!(binding, model::Binding::Heart { .. }) + && self.decks.values().any(|d| { + d.heart.as_ref().is_some_and(|h| { + matches!(h.phase, heart::Phase::Waiting(..) | heart::Phase::Sending) + }) + }) + { + return None; + } + let deck = self.decks.get_mut(&instance.device)?; let command = deck.release(binding, self.snapshot.as_ref())?; let transfer = if let Command::Transfer { device_id } = &command { Some(device_id.clone()) @@ -221,6 +266,11 @@ impl Surface { let wait_remote = conflicts_with_remote_playback(&command) && !radio; let radio_baseline = self.snapshot.as_ref().map_or(0, |s| s.radio.id); let (id, message) = self.request(command); + if let Some(h) = self.decks.get_mut(&instance.device)?.heart.as_mut() + && matches!(h.phase, heart::Phase::Sending) + { + h.phase = heart::Phase::Waiting(id.clone(), Instant::now()); + } if wait_remote && let Some(snapshot) = &self.snapshot { self.remote.begin(snapshot, id.clone(), Instant::now()); for deck in self.decks.values_mut() { @@ -247,6 +297,71 @@ impl Surface { } } + fn heart_tick(&mut self, now: Instant) -> Vec { + let track = self.snapshot.as_ref().and_then(|s| s.track.as_ref()); + let mut commands = Vec::new(); + for (device, deck) in &mut self.decks { + let Some(h) = deck.heart.as_mut() else { + continue; + }; + if !matches!(deck.screen, model::Screen::Functions) + || track.is_none_or(|t| t.key != h.key || t.liked.is_none()) + || now.saturating_duration_since(self.snapshot_at) > Duration::from_secs(3) + { + deck.heart = None; + self.keys_dirty = true; + continue; + } + if matches!(h.phase, heart::Phase::Fading(_)) + && track.is_some_and(|t| t.liked == Some(h.liked)) + { + h.phase = heart::Phase::Confirmed(now); + self.keys_dirty = true; + } + if let heart::Phase::Confirmed(start) = h.phase { + if now.saturating_duration_since(start) >= heart::SAVED_DISPLAY { + deck.heart = None; + deck.screen = model::Screen::Player; + self.keys_dirty = true; + } + continue; + } + if let heart::Phase::Waiting(_, start) = h.phase + && now.saturating_duration_since(start) >= heart::RESULT_TIMEOUT + { + deck.heart = None; + deck.notice = Some(("Like update timed out".into(), now)); + self.keys_dirty = true; + continue; + } + if let Some(command) = h.due(now) { + commands.push((device.clone(), command)); + } + } + let mut messages = Vec::new(); + for (device, command) in commands { + if self.decks.iter().any(|(other, d)| { + other != &device + && d.heart + .as_ref() + .is_some_and(|h| matches!(h.phase, heart::Phase::Waiting(..))) + }) { + self.decks.get_mut(&device).unwrap().heart = None; + continue; + } + let (id, message) = self.request(command); + if let Some(heart) = self + .decks + .get_mut(&device) + .and_then(|deck| deck.heart.as_mut()) + { + heart.phase = heart::Phase::Waiting(id, now); + messages.push(message); + } + } + messages + } + fn write_settings(&mut self, value: Value) { self.host_outbox.push( serde_json::json!({"event":"setGlobalSettings","context":host::PLUGIN,"payload":value}), @@ -326,6 +441,9 @@ impl Surface { accepted, error, } => { + if self.finish_heart(&id, accepted, error.as_deref()) { + return None; + } if self.artwork_request_id(&id) { if !accepted { self.artwork.reject(&id); @@ -463,7 +581,10 @@ impl Surface { (slot == 0 && deck.artwork_loading.is_some()) || (slot == 2 && deck.remote.waiting(self.snapshot.as_ref())) } - model::Screen::Functions => slot == 0 && deck.radio.is_some(), + model::Screen::Functions => { + (slot == 2 && deck.radio.is_some()) + || (slot == 0 && deck.heart.is_some()) + } model::Screen::Devices { .. } => slot < 6, }; if !self.keys_dirty && !animated { @@ -637,7 +758,13 @@ async fn run_host(args: &[String], endpoint_path: Option) -> Result<()> } let artwork = surface.artwork_request(Instant::now()); let spectrum = surface.spectrum_request(); - for command in command.into_iter().chain(artwork).chain(spectrum) { + let hearts = surface.heart_tick(Instant::now()); + for command in command + .into_iter() + .chain(artwork) + .chain(spectrum) + .chain(hearts) + { if let Err(error) = command_tx.try_send(command) { match error.into_inner() { ClientMessage::SubscribeSpectrum { enabled } => { @@ -645,6 +772,9 @@ async fn run_host(args: &[String], endpoint_path: Option) -> Result<()> continue; } ClientMessage::Command { id, .. } => { + if surface.finish_heart(&id, false, Some("Command not sent")) { + continue; + } if surface.artwork_request_id(&id) { surface.artwork.reject(&id); surface.keys_dirty = true; @@ -704,6 +834,208 @@ mod tests { surface } + #[test] + fn heart_result_is_correlated_and_confirmed_display_returns_after_half_second() { + let mut surface = Surface::new(); + surface.update(snapshot_update(preview::fixture())); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface.host_event(event("keyDown", 0)); + let Some(ClientMessage::Command { + id, + command: + Command::SetLiked { + track_key, + liked: true, + }, + }) = surface.host_event(event("keyUp", 0)) + else { + panic!("heart should like immediately") + }; + assert_eq!(track_key, "preview-track"); + surface.host_event(event("keyDown", 0)); + assert!(surface.host_event(event("keyUp", 0)).is_none()); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id: "stale".into(), + accepted: true, + error: None, + }))); + assert!(matches!( + surface.decks["deck-1"].heart.as_ref().unwrap().phase, + heart::Phase::Waiting(..) + )); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id: id.clone(), + accepted: true, + error: None, + }))); + let heart::Phase::Confirmed(start) = surface.decks["deck-1"].heart.as_ref().unwrap().phase + else { + panic!() + }; + surface.heart_tick(start + Duration::from_millis(499)); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Functions + )); + surface.heart_tick(start + Duration::from_millis(500)); + assert!(matches!( + surface.decks["deck-1"].screen, + model::Screen::Player + )); + } + + #[test] + fn fading_unlike_observes_external_save_and_hidden_cover_cancels_before_send() { + for hidden in [false, true] { + let mut surface = Surface::new(); + let mut snapshot = preview::fixture(); + snapshot.track.as_mut().unwrap().liked = Some(true); + surface.update(snapshot_update(snapshot.clone())); + surface.host_event(event("willAppear", 0)); + surface.host_event(serde_json::from_value(json!({"event":"willAppear","action":host::INFOBAR,"context":"infobar","device":"deck-1","payload":{"controller":"Infobar","coordinates":{"row":0,"column":0}}})).unwrap()); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + let now = Instant::now(); + if hidden { + surface.host_event(event("willDisappear", 0)); + assert!(surface.decks["deck-1"].heart.is_none()); + } else { + snapshot.track.as_mut().unwrap().liked = Some(false); + surface.update(snapshot_update(snapshot)); + } + assert!(surface.heart_tick(now).is_empty()); + if !hidden { + assert!(matches!( + surface.decks["deck-1"].heart.as_ref().unwrap().phase, + heart::Phase::Confirmed(_) + )); + } + surface.snapshot_at = now + Duration::from_secs(4); + assert!(surface.heart_tick(now + Duration::from_secs(4)).is_empty()); + } + } + + #[test] + fn likes_are_independent_of_control_transport_gate() { + let command = Command::SetLiked { + track_key: "preview-track".into(), + liked: true, + }; + assert!(!conflicts_with_remote_playback(&command)); + let mut surface = Surface::new(); + let mut snapshot = preview::fixture(); + snapshot.role = furumi_control_protocol::Role::Control; + snapshot.active_device_id = Some("laptop".into()); + surface + .remote + .begin(&snapshot, "transport".into(), Instant::now()); + surface.update(snapshot_update(snapshot)); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface.host_event(event("keyDown", 0)); + let Some(ClientMessage::Command { id, command: sent }) = + surface.host_event(event("keyUp", 0)) + else { + panic!("expected a like request") + }; + assert_eq!(sent, command); + assert!(surface.finish_heart(&id, false, Some("Command not sent"))); + assert!(surface.decks["deck-1"].heart.is_none()); + assert!(surface.remote.waiting(surface.snapshot.as_ref())); + } + + #[test] + fn heart_unlike_timer_is_drained_once_by_runtime_and_other_decks_cannot_duplicate() { + let mut surface = Surface::new(); + let mut snapshot = preview::fixture(); + snapshot.track.as_mut().unwrap().liked = Some(true); + surface.update(snapshot_update(snapshot)); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + let heart::Phase::Fading(start) = surface.decks["deck-1"].heart.as_ref().unwrap().phase + else { + panic!() + }; + let due = start + Duration::from_secs(3); + surface.snapshot_at = due; + let other = model::Deck { + screen: model::Screen::Functions, + heart: surface.decks["deck-1"].heart.clone(), + ..Default::default() + }; + surface.decks.insert("other".into(), other); + let messages = surface.heart_tick(due); + assert_eq!(messages.len(), 1); + assert!(surface.heart_tick(due).is_empty()); + let ClientMessage::Command { + id, + command: Command::SetLiked { liked: false, .. }, + } = messages.into_iter().next().unwrap() + else { + panic!() + }; + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id: id.clone(), + accepted: false, + error: Some("Save failed".into()), + }))); + assert!(surface.decks.values().all(|d| d.heart.is_none())); + surface.update(client::Update::Message(Box::new(ServerMessage::Result { + id, + accepted: true, + error: None, + }))); + assert!(surface.decks.values().all(|d| d.heart.is_none())); + let mut legacy = preview::fixture(); + legacy.track.as_mut().unwrap().liked = None; + assert_eq!( + surface.decks["deck-1"].binding(0, Some(&legacy)), + model::Binding::Disabled + ); + } + + #[test] + fn delayed_unlike_cancels_on_track_change_navigation_and_disconnect() { + for cancel in 0..3 { + let mut surface = Surface::new(); + let mut snapshot = preview::fixture(); + snapshot.track.as_mut().unwrap().liked = Some(true); + surface.update(snapshot_update(snapshot.clone())); + surface.host_event(event("willAppear", 0)); + surface.host_event(event("willAppear", 7)); + surface.host_event(event("keyDown", 0)); + surface.host_event(event("keyUp", 0)); + surface.host_event(event("keyDown", 0)); + assert!(surface.host_event(event("keyUp", 0)).is_none()); + assert!(surface.decks["deck-1"].heart.is_some()); + match cancel { + 0 => { + snapshot.track.as_mut().unwrap().key = "new".into(); + surface.update(snapshot_update(snapshot)); + } + 1 => { + surface.host_event(event("keyDown", 7)); + surface.host_event(event("keyUp", 7)); + } + _ => surface.disconnect(), + } + assert!( + surface + .heart_tick(Instant::now() + Duration::from_secs(3)) + .is_empty() + ); + assert!(surface.decks["deck-1"].heart.is_none()); + } + } + #[test] fn switching_spectrum_modes_preserves_history_and_existing_subscription() { let mut surface = spectrum_surface(); diff --git a/integrations/opendeck/src/model.rs b/integrations/opendeck/src/model.rs index 446cb30..73f04a2 100644 --- a/integrations/opendeck/src/model.rs +++ b/integrations/opendeck/src/model.rs @@ -9,7 +9,10 @@ pub const DEVICES_PER_PAGE: usize = 6; const REMOTE_FALLBACK: Duration = Duration::from_secs(45); pub fn conflicts_with_remote_playback(command: &Command) -> bool { - !matches!(command, Command::Transfer { .. } | Command::Artwork { .. }) + !matches!( + command, + Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. } + ) } #[derive(Clone, Debug)] @@ -183,6 +186,7 @@ fn remote_error(error: Option<&str>) -> String { #[derive(Clone, Debug, PartialEq, Eq)] pub enum Binding { + Heart { key: String, liked: bool }, Command(Command), Functions, Devices, @@ -216,6 +220,7 @@ pub struct PendingRadio { } pub struct Deck { + pub heart: Option, pub screen: Screen, pub presses: BTreeMap, pub pending: Option, @@ -229,6 +234,7 @@ pub struct Deck { impl Default for Deck { fn default() -> Self { Self { + heart: None, screen: Screen::Player, presses: BTreeMap::new(), pending: None, @@ -275,7 +281,16 @@ impl Deck { _ => Binding::Disabled, }, Screen::Functions => match slot { - 0 if self.radio.is_none() => Binding::Command(Command::StartRadio), + 0 => snapshot + .and_then(|s| s.track.as_ref()) + .and_then(|t| { + t.liked.map(|liked| Binding::Heart { + key: t.key.clone(), + liked, + }) + }) + .unwrap_or(Binding::Disabled), + 2 if self.radio.is_none() => Binding::Command(Command::StartRadio), 1 => Binding::Devices, 7 => Binding::Back, _ => Binding::Disabled, @@ -344,7 +359,35 @@ impl Deck { if binding != Binding::Disabled { self.notice = None; } + if !matches!(binding, Binding::Heart { .. } | Binding::Disabled) { + self.heart = None; + } match binding { + Binding::Heart { key, liked } => { + if !matches!(self.screen, Screen::Functions) + || snapshot + .track + .as_ref() + .is_none_or(|t| t.key != key || t.liked != Some(liked)) + { + return None; + } + if let Some(heart) = &mut self.heart { + return heart.press(); + } + let heart = crate::heart::Heart { + key, + liked: !liked, + phase: if liked { + crate::heart::Phase::Fading(Instant::now()) + } else { + crate::heart::Phase::Sending + }, + }; + let command = (!liked).then(|| heart.command()); + self.heart = Some(heart); + command + } Binding::Functions => { self.screen = Screen::Functions; None @@ -534,7 +577,7 @@ mod tests { .is_none() ); deck.release(Binding::Functions, Some(&snapshot)); - assert_eq!(deck.binding(0, Some(&snapshot)), Binding::Disabled); + assert_eq!(deck.binding(2, Some(&snapshot)), Binding::Disabled); assert_eq!(deck.binding(1, Some(&snapshot)), Binding::Devices); deck.release(Binding::Devices, Some(&snapshot)); assert!(matches!( @@ -741,7 +784,7 @@ mod tests { ); deck.release(Binding::Functions, Some(&snapshot)); assert_eq!( - deck.binding(0, Some(&snapshot)), + deck.binding(2, Some(&snapshot)), Binding::Command(Command::StartRadio) ); deck.release(Binding::Devices, Some(&snapshot)); diff --git a/integrations/opendeck/src/preview.rs b/integrations/opendeck/src/preview.rs index 460abd9..81c4be9 100644 --- a/integrations/opendeck/src/preview.rs +++ b/integrations/opendeck/src/preview.rs @@ -58,6 +58,7 @@ pub fn fixture() -> Snapshot { album: "Hurry Up, We're Dreaming".into(), year: Some(2011), artwork_id: None, + liked: Some(false), }), devices, } @@ -369,6 +370,34 @@ pub fn write(directory: &Path) -> Result<()> { } sheet.save(directory.join("all-screens.png"))?; appearance(directory, &prepared)?; + let now = Instant::now(); + let mut hearts = RgbImage::from_pixel(4 * 112 + 16, 132, Rgb([24, 27, 32])); + for (index, label) in ["Not liked", "Liked", "Unlike fade", "Saved"] + .into_iter() + .enumerate() + { + let mut snapshot = fixture(); + snapshot.track.as_mut().unwrap().liked = Some(index > 0); + let mut deck = Deck { + screen: Screen::Functions, + ..Default::default() + }; + if index >= 2 { + deck.heart = Some(crate::heart::Heart { + key: "preview-track".into(), + liked: false, + phase: if index == 2 { + crate::heart::Phase::Fading(now - Duration::from_millis(1500)) + } else { + crate::heart::Phase::Confirmed(now) + }, + }); + } + let key = render::key_prepared(0, &deck, Some(&snapshot), Some(&prepared), now); + render::preview_label(&mut hearts, label, 16 + index as i32 * 112, 5, 104); + image::imageops::overlay(&mut hearts, &key, 16 + index as i64 * 112, 28); + } + hearts.save(directory.join("heart-states.png"))?; infobar_backgrounds(directory)?; let mut covers = RgbImage::from_pixel(856, 168, Rgb([24, 27, 32])); render::preview_label( diff --git a/integrations/opendeck/src/render.rs b/integrations/opendeck/src/render.rs index 6e532ef..70ea289 100644 --- a/integrations/opendeck/src/render.rs +++ b/integrations/opendeck/src/render.rs @@ -358,6 +358,24 @@ pub fn key_prepared( }, Screen::Functions => match slot { 0 => { + let liked = snapshot + .and_then(|s| s.track.as_ref()) + .and_then(|t| t.liked); + let fill = deck + .heart + .as_ref() + .map_or(if liked == Some(true) { 1.0 } else { 0.0 }, |h| h.fill(now)); + let color = if liked.is_some() { fg } else { [88, 101, 112] }; + if fill > 0.0 { + let interior = std::array::from_fn(|c| { + (f32::from(role.background[c]) * (1.0 - fill) + f32::from(color[c]) * fill) + .round() as u8 + }); + icons::draw(&mut im, Icon::HeartFill, interior); + } + icons::draw(&mut im, Icon::Heart, color); + } + 2 => { if let Some(radio) = &deck.radio { let step = (now.saturating_duration_since(radio.started).as_millis() / 100 % 8) as usize; @@ -656,6 +674,29 @@ mod tests { use super::*; use crate::preview::fixture; + #[test] + fn inverted_heart_fade_keeps_black_background_and_stable_outline_after_send() { + let now = Instant::now(); + let mut snapshot = fixture(); + snapshot.track.as_mut().unwrap().liked = Some(true); + let mut deck = Deck { + screen: Screen::Functions, + ..Default::default() + }; + deck.preferences.invert_colors = true; + deck.heart = Some(crate::heart::Heart { + key: "preview-track".into(), + liked: false, + phase: crate::heart::Phase::Fading(now - crate::heart::REMOVE_DELAY), + }); + let faded = key(0, &deck, Some(&snapshot), None, now); + assert_eq!(faded.get_pixel(0, 0).0, [0, 0, 0]); + deck.heart.as_mut().unwrap().phase = crate::heart::Phase::Waiting("like".into(), now); + assert_eq!(key(0, &deck, Some(&snapshot), None, now), faded); + deck.heart.as_mut().unwrap().phase = crate::heart::Phase::Confirmed(now); + assert_eq!(key(0, &deck, Some(&snapshot), None, now), faded); + } + #[test] fn two_by_two_cover_preserves_real_gap_and_original_bindings() { use crate::model::Binding; diff --git a/src/app/control.rs b/src/app/control.rs index 75aef30..9079a4a 100644 --- a/src/app/control.rs +++ b/src/app/control.rs @@ -15,6 +15,7 @@ pub(crate) fn published(state: &AppState, revision: u64) -> crate::control::Publ artist: track.artist_line(), album: track.release_title.clone(), year: track.release_year, + liked: super::likes::status(state, track), artwork_id: artwork.id(&track.key().to_string()), }); let has_episodes = state.player.queue.iter().any(|track| track.is_podcast()) @@ -135,10 +136,17 @@ pub(super) enum Intent { Action(Action), Transfer(Device), Radio, + SetLiked { + track: Box, + liked: bool, + }, } pub(super) fn intent(state: &AppState, command: Command) -> Result { - if !matches!(command, Command::Transfer { .. } | Command::Artwork { .. }) { + if !matches!( + command, + Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. } + ) { super::remote_playback::available(state)?; } Ok(match command { @@ -155,6 +163,10 @@ pub(super) fn intent(state: &AppState, command: Command) -> Result Intent::Action(Action::ToggleShuffle), Command::CycleRepeat => Intent::Action(Action::CycleRepeat), Command::StartRadio => Intent::Radio, + Command::SetLiked { track_key, liked } => Intent::SetLiked { + track: Box::new(super::likes::target(state, &track_key)?), + liked, + }, Command::Seek { seconds } => { if state.player.current.is_none() { return Err("nothing playing".into()); @@ -204,47 +216,51 @@ pub(super) fn dispatch( let _ = request.reply.send(Err(reason)); return; } - let result = intent(state, request.command).and_then(|intent| { - match intent { - Intent::Radio => return super::radio::start(state, runtime), - Intent::Action(action) => { - // Same state transitions, remote targeting and podcast checks as media keys. - let id = state.device_playback.control.status.id; - if let Some(effect) = update(state, action) { - perform_effect(state, runtime, effect); - } - if state.device_playback.role == DevicePlaybackRole::Control - && state.device_playback.control.status.id == id - { - return Err(state - .status_message - .clone() - .unwrap_or_else(|| "No playback change to send".into())); - } + let result = match intent(state, request.command) { + Err(error) => Err(error), + Ok(Intent::SetLiked { track, liked }) => { + super::likes::set(runtime, *track, liked, request.reply); + return; + } + Ok(Intent::Radio) => super::radio::start(state, runtime), + Ok(Intent::Action(action)) => { + // Same state transitions, remote targeting and podcast checks as media keys. + let id = state.device_playback.control.status.id; + if let Some(effect) = update(state, action) { + perform_effect(state, runtime, effect); } - Intent::Transfer(device) => { - if device.active { - return Ok(()); - } - if device.is_self { - super::transfer_active_to_this_device_inner(state, runtime, true); - } else { - super::transfer_active_to_remote_device( - state, - runtime, - device.id.clone(), - device.name, - ); - } - if state.device_playback.active_device_id.as_ref() != Some(&device.id) { - return Err(state - .status_message - .clone() - .unwrap_or_else(|| "handoff failed".into())); - } + if state.device_playback.role == DevicePlaybackRole::Control + && state.device_playback.control.status.id == id + { + Err(state + .status_message + .clone() + .unwrap_or_else(|| "No playback change to send".into())) + } else { + Ok(()) } } - Ok(()) - }); + Ok(Intent::Transfer(device)) if device.active => Ok(()), + Ok(Intent::Transfer(device)) => { + if device.is_self { + super::transfer_active_to_this_device_inner(state, runtime, true); + } else { + super::transfer_active_to_remote_device( + state, + runtime, + device.id.clone(), + device.name, + ); + } + if state.device_playback.active_device_id.as_ref() == Some(&device.id) { + Ok(()) + } else { + Err(state + .status_message + .clone() + .unwrap_or_else(|| "handoff failed".into())) + } + } + }; let _ = request.reply.send(result); } diff --git a/src/app/event.rs b/src/app/event.rs index 770ab73..6053275 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -86,8 +86,8 @@ pub enum AppEvent { id: i64, result: Result, }, - /// Liked local content ids for the ♥ markers. - LikesLoaded(Result, String>), + /// Local and federated identities from a completed library like refresh. + LikesLoaded(Result), /// Local-library content ids for availability markers. LocalContentIdsLoaded(Result, String>), /// Counts and storage footprint of the local library/database. @@ -103,8 +103,6 @@ pub enum AppEvent { content_id: String, liked: bool, }, - /// Liked federated item ids and content ids for the ♥ markers. - FedLikesLoaded(Result, String>), FedLikeToggled { item_id: String, content_id: Option, diff --git a/src/app/likes.rs b/src/app/likes.rs new file mode 100644 index 0000000..ea0e0e5 --- /dev/null +++ b/src/app/likes.rs @@ -0,0 +1,247 @@ +//! Personal library likes shared by the TUI and local control surfaces. +use std::collections::HashSet; + +use anyhow::{Result, ensure}; +use tokio::sync::{mpsc, oneshot}; + +use super::event::AppEvent; +use super::state::{self, AppState}; +use super::{Runtime, err_string, update}; +use crate::devices::DeviceSync; +use crate::federation::FedTrack; +use crate::library::{Library, models::TrackItem}; + +#[derive(Debug)] +pub(crate) struct LikeIds { + pub local: HashSet, + pub federated: HashSet, +} + +impl LikeIds { + fn load(library: &Library) -> Result { + Ok(Self { + local: library.liked_content_ids()?.into_iter().collect(), + federated: library.fed_like_ids()?.into_iter().collect(), + }) + } + + fn contains(&self, track: &FedTrack) -> bool { + self.federated.contains(&track.item_id) + || track + .content_id + .as_ref() + .is_some_and(|id| self.local.contains(id) || self.federated.contains(id)) + } +} + +// Serialize library reads and edits from the keyboard and control clients. +// In particular, old federated entries without a content ID have only a local +// toggle operation and cannot be changed by a trusted-device sync. +pub(super) fn in_background( + runtime: &Runtime, + work: impl FnOnce(&Library, &DeviceSync, &mpsc::UnboundedSender) + Send + 'static, +) { + let (library, devices, tx, gate) = ( + runtime.library.clone(), + runtime.devices.clone(), + runtime.event_tx.clone(), + runtime.like_io.clone(), + ); + tokio::task::spawn_blocking(move || { + let _guard = gate.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + work(&library, &devices, &tx); + }); +} + +pub(super) fn reload(library: &Library, tx: &mpsc::UnboundedSender) { + let _ = tx.send(AppEvent::LikesLoaded( + LikeIds::load(library).map_err(err_string), + )); +} + +pub(super) fn status(state: &AppState, track: &TrackItem) -> Option { + let identifiable = state::track_content_id(track).is_some() + || track + .fed + .as_ref() + .is_some_and(|fed| !fed.item_id.is_empty()); + (state.likes_ready && !track.is_podcast() && identifiable).then(|| state.track_liked(track)) +} + +pub(super) fn target(state: &AppState, key: &str) -> Result { + let track = state + .player + .current + .as_ref() + .filter(|track| track.key().to_string() == key) + .ok_or("Track is no longer current")?; + status(state, track).ok_or("Likes are unavailable for this track")?; + let mut fed = update::fed_track_for_download(track).ok_or("Track has no music identity")?; + fed.content_id = state::track_content_id(track); + if fed.item_id.is_empty() { + // A controller may only know the content hash and the owner's playback + // metadata. Keep distinct playlist entries and resolve by hash on play. + fed.item_id = fed + .content_id + .clone() + .ok_or("Track has no music identity")?; + } + Ok(fed) +} + +pub(super) fn set( + runtime: &Runtime, + track: FedTrack, + liked: bool, + reply: oneshot::Sender>, +) { + in_background(runtime, move |library, devices, tx| { + let write = set_in_library(library, devices, &track, liked, tx).map_err(err_string); + // Refresh both kinds of markers even after a partial storage failure. + // Only confirm a state that the library can actually read back. + let ids = LikeIds::load(library).map_err(err_string); + let saved = match &ids { + Ok(ids) if ids.contains(&track) == liked => Ok(()), + Ok(_) => Err("Liked state changed during the update".into()), + Err(error) => Err(error.clone()), + }; + let _ = tx.send(AppEvent::LikesLoaded(ids)); + let _ = reply.send(write.and(saved)); + }); +} + +fn set_in_library( + library: &Library, + devices: &DeviceSync, + track: &FedTrack, + liked: bool, + tx: &mpsc::UnboundedSender, +) -> Result<()> { + let previous = LikeIds::load(library)?; + if previous.contains(track) == liked { + return Ok(()); + } + let event = if let Some(id) = &track.content_id + && library.track_id_by_content_id(id)?.is_some() + { + // This absolute sync operation also updates the local library offline. + devices.record_content_like(id, liked)?; + if !liked && previous.federated.contains(id) { + library.remove_fed_like_by_content_id(id)?; + } + AppEvent::LikeToggled { + content_id: id.clone(), + liked, + } + } else { + if track.content_id.is_some() { + devices.record_fed_like(track, liked)?; + } else { + // Keyboard and control requests share the library's item-ID-only toggle. + ensure!( + library.toggle_fed_like(track)? == liked, + "Liked state changed during the update" + ); + } + AppEvent::FedLikeToggled { + item_id: track.item_id.clone(), + content_id: track.content_id.clone(), + liked, + } + }; + // A federated like saved before its hash was known can still have a + // separate item-ID-only row. Remove that old identity as well. + if !liked + && let Some(id) = &track.content_id + && previous.federated.contains(&track.item_id) + && !previous.federated.contains(id) + && library.fed_like_ids()?.contains(&track.item_id) + { + ensure!( + !library.toggle_fed_like(track)?, + "Liked state changed during the update" + ); + } + let _ = tx.send(event); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn explicit_sets_are_idempotent_in_local_federated_and_legacy_libraries() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("library.sqlite3"); + let library = Arc::new(Library::open(&path).unwrap()); + let devices = DeviceSync::with_test_library(library.clone()); + let (tx, mut events) = mpsc::unbounded_channel(); + let local_id = format!("b3:{:064x}", 1); + let remote_id = format!("b3:{:064x}", 2); + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute("INSERT INTO releases (id, title) VALUES (1, 'Test')", []) + .unwrap(); + db.execute("INSERT INTO tracks (title, release_id, file_path, content_id) VALUES ('One', 1, 'one.wav', ?1)", [&local_id]).unwrap(); + drop(db); + + for (key, content_id) in [ + (local_id.clone(), Some(local_id.clone())), + (remote_id.clone(), Some(remote_id.clone())), + ("legacy-item".into(), None), + ] { + let track = FedTrack { + item_id: key, + content_id, + owner: String::new(), + own: false, + title: "Track".into(), + artist_names: vec!["Artist".into()], + featured_artist_names: vec![], + release_title: None, + year: None, + duration_seconds: None, + track_number: None, + disc_number: None, + }; + for liked in [true, false] { + set_in_library(&library, &devices, &track, liked, &tx).unwrap(); + let event = events.try_recv().unwrap(); + if track.content_id.as_ref() == Some(&local_id) { + assert!( + matches!(event, AppEvent::LikeToggled { liked: actual, .. } if actual == liked) + ); + } else { + assert!( + matches!(event, AppEvent::FedLikeToggled { liked: actual, .. } if actual == liked) + ); + } + set_in_library(&library, &devices, &track, liked, &tx).unwrap(); + assert!( + events.try_recv().is_err(), + "a retry must not toggle the like again" + ); + let reopened = Library::open(&path).unwrap(); + assert_eq!(LikeIds::load(&reopened).unwrap().contains(&track), liked); + assert_eq!( + reopened + .playlist(furumi_library::LIKES_PLAYLIST_ID) + .unwrap() + .tracks + .len(), + usize::from(liked) + ); + } + if track.content_id.is_none() { + set_in_library(&library, &devices, &track, true, &tx).unwrap(); + let identified = FedTrack { + content_id: Some(remote_id.clone()), + ..track + }; + set_in_library(&library, &devices, &identified, false, &tx).unwrap(); + assert!(!LikeIds::load(&library).unwrap().contains(&identified)); + } + } + } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index df70952..1ff6d96 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -5,6 +5,7 @@ pub(crate) mod control; mod enrichment; pub mod event; pub mod input; +mod likes; pub(crate) mod lyrics; #[cfg(test)] pub(crate) mod podcast_fixtures; @@ -47,6 +48,7 @@ const VISUALIZER_TICK_INTERVAL: Duration = Duration::from_millis(50); pub struct Runtime { pub event_tx: mpsc::UnboundedSender, pub library: Arc, + like_io: Arc>, pub devices: Arc, pub jam: Arc, pub federation: Arc, @@ -468,6 +470,7 @@ pub async fn run( let mut runtime = Runtime { event_tx, library, + like_io: Arc::default(), devices, jam, federation, @@ -1307,14 +1310,7 @@ fn maintenance(state: &mut AppState, runtime: &mut Runtime) { // Liked ids load once per session — markers are shown everywhere. if !state.likes_loaded { state.likes_loaded = true; - let library = Arc::clone(&runtime.library); - let tx = runtime.event_tx.clone(); - tokio::task::spawn_blocking(move || { - let result = library.liked_content_ids().map_err(err_string); - let _ = tx.send(AppEvent::LikesLoaded(result)); - let result = library.fed_like_ids().map_err(err_string); - let _ = tx.send(AppEvent::FedLikesLoaded(result)); - }); + likes::in_background(runtime, |library, _, tx| likes::reload(library, tx)); } if !state.local_content_ids_loaded { state.local_content_ids_loaded = true; @@ -1875,10 +1871,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { if track_ids.is_empty() && fed_tracks.is_empty() { return; } - let library = Arc::clone(&runtime.library); - let devices = Arc::clone(&runtime.devices); - let tx = runtime.event_tx.clone(); - tokio::task::spawn_blocking(move || { + likes::in_background(runtime, move |library, devices, tx| { for track_id in track_ids { let content_id = match library.track_content_id_by_id(track_id) { Ok(Some(content_id)) => content_id, @@ -1931,12 +1924,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { } } } - let _ = tx.send(AppEvent::LikesLoaded( - library.liked_content_ids().map_err(err_string), - )); - let _ = tx.send(AppEvent::FedLikesLoaded( - library.fed_like_ids().map_err(err_string), - )); + likes::reload(library, tx); }); } Effect::RemoveFromPlaylist { @@ -4521,7 +4509,9 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } AppEvent::LikesLoaded(result) => match result { Ok(ids) => { - state.likes = ids.into_iter().collect(); + state.likes = ids.local; + state.fed_likes = ids.federated; + state.likes_ready = true; } Err(message) => tracing::warn!(%message, "likes load failed"), }, @@ -4550,10 +4540,6 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent state.local_content_ids.insert(content_id); } } - AppEvent::FedLikesLoaded(result) => match result { - Ok(ids) => state.fed_likes = ids.into_iter().collect(), - Err(message) => tracing::warn!(%message, "federated likes load failed"), - }, AppEvent::FedLikeToggled { item_id, content_id, diff --git a/src/app/state.rs b/src/app/state.rs index 1dc03ad..d815e1d 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -2016,6 +2016,8 @@ pub struct AppState { /// Content ids that currently have a local playable file. pub local_content_ids: HashSet, pub likes_loaded: bool, + /// The local and federated markers have both loaded successfully at least once. + pub(super) likes_ready: bool, pub local_content_ids_loaded: bool, pub local_library_stats: Option>, pub listen_history: Option>>, @@ -2120,13 +2122,12 @@ impl AppState { } pub fn track_liked(&self, track: &TrackItem) -> bool { - if let Some(content_id) = track_content_id(track) { - return self.likes.contains(&content_id) || self.fed_likes.contains(&content_id); - } - track - .fed - .as_ref() - .is_some_and(|fed| self.fed_track_liked(fed)) + track_content_id(track) + .is_some_and(|id| self.likes.contains(&id) || self.fed_likes.contains(&id)) + || track + .fed + .as_ref() + .is_some_and(|fed| self.fed_likes.contains(&fed.item_id)) } } diff --git a/src/app/update.rs b/src/app/update.rs index 2e17070..a3bd8e7 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -2871,7 +2871,7 @@ fn selected_downloadable_fed_tracks(state: &AppState) -> Vec Option { +pub(super) fn fed_track_for_download(track: &TrackItem) -> Option { if let Some(fed) = &track.fed { return Some(fed.clone()); } diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 479e34e..a0b2c9e 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -132,6 +132,64 @@ fn test_track(id: i64) -> TrackItem { } } +#[test] +fn control_heart_follows_the_playing_music_track_and_uses_personal_likes_in_all_roles() { + use crate::app::{control, state::DevicePlaybackRole}; + use furumi_control_protocol::Command; + + let mut state = AppState::default(); + let a = test_track(7); + let b = test_track(8); + let key = a.key().to_string(); + let heart = |state: &AppState| control::published(state, 1).snapshot.track.unwrap().liked; + let set = || Command::SetLiked { + track_key: key.clone(), + liked: true, + }; + state.player.current = Some(a.clone()); + assert_eq!(heart(&state), None); + assert!(control::intent(&state, set()).is_err()); + state.likes_ready = true; + state.player.queue = vec![b.clone(), a.clone()]; + for role in [ + DevicePlaybackRole::Active, + DevicePlaybackRole::Control, + DevicePlaybackRole::Jam, + ] { + state.device_playback.role = role; + assert_eq!(heart(&state), Some(false)); + let control::Intent::SetLiked { track, liked: true } = + control::intent(&state, set()).unwrap() + else { + panic!("expected a personal library edit") + }; + assert_eq!(track.content_id, a.content_id); + } + state.likes.insert(a.content_id.unwrap()); + assert_eq!(heart(&state), Some(true)); + state.player.current = Some(b); + assert_eq!(heart(&state), Some(false)); + assert!(control::intent(&state, set()).is_err()); + for unavailable in [ + crate::app::podcast_fixtures::episode_track(1), + crate::devices::private_track_item(0), + ] { + let key = unavailable.key().to_string(); + state.player.current = Some(unavailable); + assert_eq!(heart(&state), None); + assert!( + control::intent( + &state, + Command::SetLiked { + track_key: key, + liked: true + } + ) + .is_err() + ); + } +} + #[test] fn control_snapshot_keeps_idle_devices_and_hides_revoked_members() { let mut state = AppState::default(); diff --git a/src/control_tests.rs b/src/control_tests.rs index cdf2a57..5416af5 100644 --- a/src/control_tests.rs +++ b/src/control_tests.rs @@ -266,6 +266,7 @@ async fn slow_federated_art_is_opt_in_and_playback_commands_still_work() { artist: "Artist".into(), album: "Album".into(), year: None, + liked: None, artwork_id: Some("cover".into()), }) }); diff --git a/src/devices/tests.rs b/src/devices/tests.rs index 69d33d1..07844ad 100644 --- a/src/devices/tests.rs +++ b/src/devices/tests.rs @@ -459,8 +459,6 @@ fn queued_command_loses_its_fence_when_another_owner_wins() { static NEXT_TEST_DB: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); fn test_sync() -> DeviceSync { - let conn = Connection::open_in_memory().unwrap(); - init_schema(&conn).unwrap(); let unique = NEXT_TEST_DB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let library_path = std::env::temp_dir().join(format!( "furumi-devices-test-{}-{}-{}.sqlite3", @@ -468,16 +466,24 @@ fn test_sync() -> DeviceSync { now_ms(), unique )); - let sync = DeviceSync { - _identity_lock: None, - conn: Arc::new(std::sync::Mutex::new(conn)), - library: Arc::new(Library::open(&library_path).unwrap()), - event_tx: Arc::new(std::sync::Mutex::new(None)), - playback: Arc::new(std::sync::Mutex::new(PlaybackShared::default())), - podcasts: Default::default(), - }; - sync.ensure_identity().unwrap(); - sync + DeviceSync::with_test_library(Arc::new(Library::open(&library_path).unwrap())) +} + +impl DeviceSync { + pub(crate) fn with_test_library(library: Arc) -> Self { + let conn = Connection::open_in_memory().unwrap(); + init_schema(&conn).unwrap(); + let sync = Self { + _identity_lock: None, + conn: Arc::new(std::sync::Mutex::new(conn)), + library, + event_tx: Default::default(), + playback: Default::default(), + podcasts: Default::default(), + }; + sync.ensure_identity().unwrap(); + sync + } } #[test]