Skip to main content

furumi_library/
models.rs

1//! Data shapes the views render. They mirror what the furumusic API used to
2//! return, but every field is now filled from the local SQLite library.
3
4use music_dht::device_sync::{PlaybackSource, PlaybackTrack};
5use music_dht::podcast::{EpisodeId, PodcastEpisodeRef};
6use serde::{Deserialize, Serialize};
7
8/// Which catalog sources a client wants library queries to include.
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum LibrarySourceMode {
12    Local,
13    My,
14    #[default]
15    Global,
16}
17
18impl LibrarySourceMode {
19    pub fn label(self) -> &'static str {
20        match self {
21            Self::Local => "Local",
22            Self::My => "My",
23            Self::Global => "Global",
24        }
25    }
26
27    pub fn includes_network(self) -> bool {
28        !matches!(self, Self::Local)
29    }
30
31    pub fn includes_global_peers(self) -> bool {
32        matches!(self, Self::Global)
33    }
34
35    pub fn next(self) -> Self {
36        match self {
37            Self::Local => Self::My,
38            Self::My => Self::Global,
39            Self::Global => Self::Local,
40        }
41    }
42}
43
44/// Client-neutral filters accepted by library browse/search operations.
45#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
46pub struct LibraryFilters {
47    #[serde(default)]
48    pub hide_featured_only: bool,
49    #[serde(default)]
50    pub source_mode: LibrarySourceMode,
51}
52
53/// Durable metadata for a track known through federation but not necessarily
54/// materialized as a local audio file. Networking remains a client concern.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct FederatedTrack {
57    pub item_id: String,
58    pub owner: String,
59    pub own: bool,
60    pub title: String,
61    pub artist_names: Vec<String>,
62    pub featured_artist_names: Vec<String>,
63    pub year: Option<i32>,
64    pub duration_seconds: Option<i64>,
65    pub content_id: Option<String>,
66    pub release_title: Option<String>,
67    pub track_number: Option<i32>,
68    pub disc_number: Option<i32>,
69}
70
71impl FederatedTrack {
72    pub fn artist_line(&self) -> String {
73        let mut line = self.artist_names.join(", ");
74        if !self.featured_artist_names.is_empty() {
75            if !line.is_empty() {
76                line.push_str(" feat. ");
77            }
78            line.push_str(&self.featured_artist_names.join(", "));
79        }
80        line
81    }
82
83    pub fn owner_short(&self) -> String {
84        self.owner.chars().take(10).collect()
85    }
86
87    pub fn duration_label(&self) -> String {
88        self.duration_seconds.map_or_else(String::new, |total| {
89            format!("{}:{:02}", total / 60, total % 60)
90        })
91    }
92}
93
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
95pub enum Availability {
96    #[default]
97    Local,
98    Mixed,
99    Remote,
100}
101
102impl Availability {
103    pub fn is_remoteish(self) -> bool {
104        matches!(self, Availability::Mixed | Availability::Remote)
105    }
106}
107
108#[derive(Debug, Clone)]
109pub struct ArtistCard {
110    pub id: i64,
111    pub name: String,
112    /// Path to a local image file, if one is set for the artist.
113    pub image_path: Option<String>,
114    pub release_count: i64,
115    pub track_count: i64,
116    pub availability: Availability,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct ArtistRef {
121    pub id: i64,
122    pub name: String,
123}
124
125/// A playable queue item: a library track, a pending federated track or a
126/// podcast episode.
127///
128/// # Identity
129///
130/// What an item *is* comes from its explicit source fields, never from the
131/// numeric `id` alone; [`TrackItem::key`] returns it as a typed
132/// [`TrackItemKey`]:
133///
134/// * a library track is a library row: `id >= 0`, `fed` and `podcast` are
135///   `None`;
136/// * a federated track is identified by [`TrackItem::fed`] (owner and item
137///   id). While it is not in the library its `id` is a negative,
138///   process-local counter value (pending federated tracks count down from
139///   -1) and `release_id` / artist ids are -1;
140/// * a podcast episode is identified **only** by [`TrackItem::podcast`] (its
141///   [`EpisodeId`]). Its `id`, `release_id` and artist id are the fixed
142///   sentinel [`TrackItem::NOT_A_LIBRARY_ROW`] (-1), shared by every episode.
143///
144/// A negative `id` therefore means "not a library row" and nothing else: it
145/// carries no identity and must never be decoded, compared across items or
146/// used as a key. The -1 sentinel only keeps music-only code that predates
147/// podcasts (`id >= 0` / `release_id < 0` checks) from treating an episode
148/// as library track, release or artist 0.
149///
150/// [`TrackItem::key`] is the *source* identity. It does not merge a pending
151/// federated item with its imported library copy, which share a content id
152/// but have different keys (`fed:` and `lib:`). Clients that key playback
153/// items content-first (content id, then federated source, then id) keep
154/// doing so for music; what they must add is a podcast branch
155/// ([`TrackItem::podcast`], or [`TrackItemKey::PodcastEpisode`]) checked
156/// before any fallback to `id`. An episode must never be keyed by `id`: a
157/// `local:{id}` key would merge all episodes into one. On the wire the item
158/// kind is `music_dht::device_sync::PlaybackSource`; convert received items
159/// with [`TrackItem::from_playback_track`], never by copying wire ids.
160///
161/// # Podcast episodes
162///
163/// Podcast episodes carry their [`PodcastEpisodeRef`] in
164/// [`TrackItem::podcast`]: `file_path` is empty, `content_id`, `fed` and
165/// `cover_path` are `None`, and the display fields mirror the reference
166/// (episode title, podcast title as artist and release). The audio URL is
167/// only in the reference: it is never a local path, never content-addressed
168/// and never offered for P2P transfer.
169///
170/// **Music-only code paths must check [`TrackItem::is_podcast`]** (or
171/// `podcast.is_none()`) before treating an item as music: likes, playlists,
172/// listening history, content-id lookups, federation downloads, similarity
173/// and file operations do not apply to episodes. Library queries never
174/// return podcast items; the library database stores none.
175#[derive(Debug, Clone)]
176pub struct TrackItem {
177    pub id: i64,
178    pub title: String,
179    pub track_number: Option<i32>,
180    pub disc_number: Option<i32>,
181    pub duration_seconds: f64,
182    pub artists: Vec<ArtistRef>,
183    pub featured_artists: Vec<ArtistRef>,
184    pub release_id: i64,
185    pub release_title: String,
186    pub release_year: Option<i32>,
187    /// Absolute path to the local audio file.
188    pub file_path: String,
189    /// Stable audio content id (`b3:<64 hex>`) when known.
190    pub content_id: Option<String>,
191    /// Path to a local cover image (the release cover).
192    pub cover_path: Option<String>,
193    pub audio_format: Option<String>,
194    pub audio_bitrate: Option<i32>,
195    pub audio_sample_rate: Option<i32>,
196    pub audio_bit_depth: Option<i32>,
197    pub file_size_bytes: Option<i64>,
198    /// Completed local plays, from the history table.
199    pub play_count: i64,
200    /// Set for federated tracks that are not in the local library (yet):
201    /// carries everything needed to download them from the owning peer.
202    /// With an empty `file_path` the player resolves the track on demand.
203    pub fed: Option<FederatedTrack>,
204    /// Set for podcast episodes (see the type documentation); `None` for music.
205    pub podcast: Option<PodcastEpisodeRef>,
206}
207
208/// Typed source identity of a [`TrackItem`], from [`TrackItem::key`].
209///
210/// Two items with equal keys are the same track or episode; the same track
211/// may still appear more than once in a queue. The key has no content-id
212/// equivalence: a pending federated item and its library copy differ. Use it
213/// where the source matters (and always for podcast episodes, which have no
214/// other identity); code that matches music by content id keeps doing that
215/// and checks the podcast variant first (see [`TrackItem`]).
216///
217/// The [`Display`](std::fmt::Display) form is stable and suitable as a map
218/// key or in logs:
219///
220/// | Variant | String form |
221/// | --- | --- |
222/// | `Library(123)` | `lib:123` |
223/// | `Federated { owner, item_id }` | `fed:<owner>:<item_id>` |
224/// | `PodcastEpisode(id)` | `ep:<episode id>`, e.g. `ep:ep1:...` |
225/// | `Transient(-5)` | `tmp:-5` |
226///
227/// `owner` is a peer endpoint id and contains no `:`, so the federated form
228/// is unambiguous. Keys are not persisted by this crate; a `Transient` key is
229/// only meaningful inside the process that built the item.
230#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
231pub enum TrackItemKey {
232    /// A row of the local music library (`TrackItem::id >= 0`).
233    Library(i64),
234    /// A federated track that is not a library row, identified by its owner
235    /// peer and DHT item id ([`FederatedTrack::owner`] /
236    /// [`FederatedTrack::item_id`]), not by its process-local negative `id`.
237    Federated { owner: String, item_id: String },
238    /// A podcast episode, identified by its [`EpisodeId`] only.
239    PodcastEpisode(EpisodeId),
240    /// A non-library item with no explicit source (negative `id`, no `fed`,
241    /// no `podcast`). furumi-library never builds one; clients that do must
242    /// keep its `id` unique within the process.
243    Transient(i64),
244}
245
246/// What a received `music_dht::device_sync::PlaybackTrack` is locally, from
247/// [`TrackItem::from_playback_track`].
248#[derive(Debug, Clone)]
249pub enum PlaybackItem {
250    /// A music track. Convert it with the client's music path (content id,
251    /// then federated source); its wire ids are the sender's.
252    Music,
253    /// A podcast episode, built with [`TrackItem::podcast_episode`].
254    PodcastEpisode(Box<TrackItem>),
255    /// A Jam private placeholder: not playable and without identity. Show it
256    /// as `music_dht::device_sync::PRIVATE_ITEM_TITLE` where the queue is
257    /// displayed; never insert it as a library or queue track, never key it.
258    Private,
259}
260
261impl std::fmt::Display for TrackItemKey {
262    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263        match self {
264            Self::Library(id) => write!(f, "lib:{id}"),
265            Self::Federated { owner, item_id } => write!(f, "fed:{owner}:{item_id}"),
266            Self::PodcastEpisode(episode_id) => write!(f, "ep:{}", episode_id.as_str()),
267            Self::Transient(id) => write!(f, "tmp:{id}"),
268        }
269    }
270}
271
272impl TrackItem {
273    /// The `id`, `release_id` and artist id of items that are not library
274    /// rows and have no numeric identity: every podcast episode uses it.
275    ///
276    /// It is a sentinel, not an identifier: it is shared by all episodes
277    /// (and can coincide with the first pending federated track's id), so it
278    /// must never be decoded or used as a key. See [`TrackItem::key`].
279    pub const NOT_A_LIBRARY_ROW: i64 = -1;
280
281    /// The typed identity of this item; see [`TrackItemKey`].
282    ///
283    /// Precedence: [`TrackItem::podcast`] makes it a podcast episode; else a
284    /// non-negative `id` is a library row; else [`TrackItem::fed`] makes it
285    /// a federated track; anything else is [`TrackItemKey::Transient`].
286    pub fn key(&self) -> TrackItemKey {
287        if let Some(episode) = &self.podcast {
288            return TrackItemKey::PodcastEpisode(episode.episode_id.clone());
289        }
290        if self.id >= 0 {
291            return TrackItemKey::Library(self.id);
292        }
293        match &self.fed {
294            Some(fed) => TrackItemKey::Federated {
295                owner: fed.owner.clone(),
296                item_id: fed.item_id.clone(),
297            },
298            None => TrackItemKey::Transient(self.id),
299        }
300    }
301
302    /// Queue item for a podcast episode streamed from the publisher.
303    ///
304    /// Title, artist and release follow `PlaybackTrack::podcast_episode` of
305    /// `music_dht::device_sync` (the episode title, the podcast title as
306    /// artist and release, the announced duration; no track or disc number).
307    /// The other fields differ from that wire form on purpose:
308    ///
309    /// * `id`, `release_id` and the artist id are the sentinel
310    ///   [`TrackItem::NOT_A_LIBRARY_ROW`] (-1) for every episode, where the
311    ///   wire form carries `0`; the item's identity is [`TrackItem::podcast`]
312    ///   alone ([`TrackItem::key`]);
313    /// * `release_year` is the publication year (`None` on the wire);
314    /// * `audio_format` is `None` (the wire form carries the MIME type, which
315    ///   stays in the reference).
316    ///
317    /// Season and episode number stay in the reference.
318    pub fn podcast_episode(episode: PodcastEpisodeRef) -> Self {
319        Self {
320            id: Self::NOT_A_LIBRARY_ROW,
321            title: episode.episode_title.clone(),
322            track_number: None,
323            disc_number: None,
324            duration_seconds: episode
325                .duration_ms
326                .map_or(0.0, |ms| ms.max(0) as f64 / 1_000.0),
327            artists: vec![ArtistRef {
328                id: Self::NOT_A_LIBRARY_ROW,
329                name: episode.podcast_title.clone(),
330            }],
331            featured_artists: Vec::new(),
332            release_id: Self::NOT_A_LIBRARY_ROW,
333            release_title: episode.podcast_title.clone(),
334            release_year: episode.published_at_ms.map(year_of_unix_ms),
335            file_path: String::new(),
336            content_id: None,
337            cover_path: None,
338            audio_format: None,
339            audio_bitrate: None,
340            audio_sample_rate: None,
341            audio_bit_depth: None,
342            file_size_bytes: None,
343            play_count: 0,
344            fed: None,
345            podcast: Some(episode),
346        }
347    }
348
349    /// Classifies a received `music_dht::device_sync::PlaybackTrack` and
350    /// builds the local queue item for non-music sources.
351    ///
352    /// The wire `id` and `release_id` of podcast episodes and of Jam private
353    /// placeholders are `0`, and those of music items are the sender's local
354    /// ids. None of them identifies anything on this device, so they are
355    /// never copied:
356    ///
357    /// * a podcast episode becomes [`TrackItem::podcast_episode`] of its
358    ///   [`PlaybackSource::PodcastEpisode`] reference (sentinel ids, key
359    ///   `ep:`), whatever the legacy display fields say;
360    /// * a private placeholder ([`PlaybackSource::Private`]) is not playable
361    ///   and has no identity, so no `TrackItem` exists for it;
362    /// * music (no source, or [`PlaybackSource::Music`]) is left to the
363    ///   client's music path, which resolves it by content id or federated
364    ///   source.
365    pub fn from_playback_track(track: &PlaybackTrack) -> PlaybackItem {
366        match &track.source {
367            None | Some(PlaybackSource::Music) => PlaybackItem::Music,
368            Some(PlaybackSource::PodcastEpisode(episode)) => PlaybackItem::PodcastEpisode(
369                Box::new(Self::podcast_episode(episode.as_ref().clone())),
370            ),
371            Some(PlaybackSource::Private) => PlaybackItem::Private,
372        }
373    }
374
375    /// Whether this item is a podcast episode (not music).
376    pub fn is_podcast(&self) -> bool {
377        self.podcast.is_some()
378    }
379
380    /// The episode reference of a podcast item.
381    pub fn podcast_episode_ref(&self) -> Option<&PodcastEpisodeRef> {
382        self.podcast.as_ref()
383    }
384
385    /// A federated track that still needs downloading before playback.
386    pub fn is_fed_pending(&self) -> bool {
387        self.fed.is_some() && self.file_path.is_empty()
388    }
389
390    pub fn artist_line(&self) -> String {
391        let artists = self
392            .artists
393            .iter()
394            .map(|a| a.name.as_str())
395            .collect::<Vec<_>>()
396            .join(", ");
397        let featured = self
398            .featured_artists
399            .iter()
400            .map(|a| a.name.as_str())
401            .collect::<Vec<_>>()
402            .join(", ");
403        match (artists.is_empty(), featured.is_empty()) {
404            (false, false) => format!("{artists} feat. {featured}"),
405            (false, true) => artists,
406            (true, false) => format!("feat. {featured}"),
407            (true, true) => String::new(),
408        }
409    }
410
411    pub fn duration_label(&self) -> String {
412        let total = self.duration_seconds.round() as i64;
413        format!("{}:{:02}", total / 60, total % 60)
414    }
415
416    /// Full tech line for the status bar, including the sample rate.
417    pub fn tech_label_full(&self) -> String {
418        let mut parts = Vec::new();
419        if let Some(format) = &self.audio_format {
420            parts.push(format.to_uppercase());
421        }
422        if let Some(bitrate) = self.audio_bitrate {
423            parts.push(format!("{bitrate}kbps"));
424        }
425        if let Some(rate) = self.audio_sample_rate {
426            parts.push(format!("{:.1}kHz", f64::from(rate) / 1000.0));
427        }
428        if let Some(bytes) = self.file_size_bytes {
429            parts.push(format!("{:.1}MB", bytes as f64 / 1_048_576.0));
430        }
431        parts.join(" ยท ")
432    }
433}
434
435/// Proleptic Gregorian year of a unix timestamp in milliseconds (UTC).
436fn year_of_unix_ms(ms: i64) -> i32 {
437    // Howard Hinnant's civil_from_days.
438    let days = ms.div_euclid(86_400_000);
439    let z = days + 719_468;
440    let era = z.div_euclid(146_097);
441    let doe = z - era * 146_097;
442    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
443    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
444    let mp = (5 * doy + 2) / 153;
445    let month = if mp < 10 { mp + 3 } else { mp - 9 };
446    let year = yoe + era * 400 + i64::from(month <= 2);
447    i32::try_from(year).unwrap_or(if year < 0 { i32::MIN } else { i32::MAX })
448}
449
450#[derive(Debug, Clone)]
451pub struct ReleaseCard {
452    pub id: i64,
453    pub title: String,
454    pub release_type: String,
455    pub year: Option<i32>,
456    pub cover_path: Option<String>,
457    pub track_count: i64,
458    pub availability: Availability,
459}
460
461#[derive(Debug)]
462pub struct ArtistDetail {
463    #[allow(dead_code, reason = "cache key is held by the caller")]
464    pub id: i64,
465    pub name: String,
466    pub image_path: Option<String>,
467    pub total_track_count: i64,
468    pub total_play_count: i64,
469    pub top_tracks: Vec<TrackItem>,
470    pub releases: Vec<ReleaseCard>,
471    /// Tracks where this artist is featured (the only content for artists
472    /// without own releases).
473    pub featured_tracks: Vec<TrackItem>,
474}
475
476#[derive(Debug)]
477pub struct ReleaseDetail {
478    #[allow(dead_code, reason = "cache key is held by the caller")]
479    pub id: i64,
480    pub title: String,
481    pub release_type: String,
482    pub year: Option<i32>,
483    pub cover_path: Option<String>,
484    pub artists: Vec<ArtistRef>,
485    pub tracks: Vec<TrackItem>,
486}
487
488#[derive(Debug, Clone)]
489pub struct PlaylistCard {
490    pub id: i64,
491    pub title: String,
492    pub track_count: i64,
493    /// "normal" for user playlists, "likes" for the virtual Likes playlist.
494    pub kind: String,
495}
496
497#[derive(Debug)]
498pub struct PlaylistDetail {
499    #[allow(dead_code, reason = "cache key is held by the caller")]
500    pub id: i64,
501    pub title: String,
502    #[allow(dead_code, reason = "shown in a detail header later")]
503    pub description: Option<String>,
504    pub tracks: Vec<TrackItem>,
505}
506
507#[derive(Debug, Default)]
508pub struct SearchResults {
509    pub artists: Vec<ArtistCard>,
510    pub releases: Vec<ReleaseCard>,
511    pub tracks: Vec<TrackItem>,
512}
513
514impl SearchResults {
515    pub fn len(&self) -> usize {
516        self.artists.len() + self.releases.len() + self.tracks.len()
517    }
518
519    pub fn is_empty(&self) -> bool {
520        self.artists.is_empty() && self.releases.is_empty() && self.tracks.is_empty()
521    }
522}
523
524#[derive(Debug)]
525pub struct ArtistsPage {
526    pub items: Vec<ArtistCard>,
527    pub total: i64,
528    pub page: i64,
529    pub has_more: bool,
530}
531
532/// Edited values submitted from the track edit form. `None` numbers clear
533/// the column.
534#[derive(Debug, Clone)]
535pub struct TrackEdit {
536    pub title: String,
537    pub artists: Vec<String>,
538    pub featured_artists: Vec<String>,
539    pub track_number: Option<i32>,
540    pub disc_number: Option<i32>,
541    /// Cover image path; the cover lives on the track's release (the same
542    /// image every view shows for the track). None clears it.
543    pub cover_path: Option<String>,
544}
545
546#[derive(Debug, Clone)]
547pub struct ReleaseEdit {
548    pub title: String,
549    pub release_type: String,
550    pub year: Option<i32>,
551    pub artists: Vec<String>,
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    fn artist(name: &str) -> ArtistRef {
559        ArtistRef {
560            id: 1,
561            name: name.to_string(),
562        }
563    }
564
565    #[test]
566    fn artist_line_formats_featured_artists() {
567        let track = TrackItem {
568            id: 1,
569            title: "Track".into(),
570            track_number: None,
571            disc_number: None,
572            duration_seconds: 1.0,
573            artists: vec![artist("Main")],
574            featured_artists: vec![artist("Guest"), artist("Other")],
575            release_id: 1,
576            release_title: "Release".into(),
577            release_year: None,
578            file_path: "/tmp/track.mp3".into(),
579            content_id: None,
580            cover_path: None,
581            audio_format: None,
582            audio_bitrate: None,
583            audio_sample_rate: None,
584            audio_bit_depth: None,
585            file_size_bytes: None,
586            play_count: 0,
587            fed: None,
588            podcast: None,
589        };
590
591        assert_eq!(track.artist_line(), "Main feat. Guest, Other");
592        assert!(!track.is_podcast());
593    }
594
595    #[test]
596    fn year_of_unix_ms_handles_epoch_and_leap_years() {
597        assert_eq!(year_of_unix_ms(0), 1970);
598        assert_eq!(year_of_unix_ms(-1), 1969);
599        // 2024-02-29T12:00:00Z and 2024-12-31T23:59:59Z.
600        assert_eq!(year_of_unix_ms(1_709_208_000_000), 2024);
601        assert_eq!(year_of_unix_ms(1_735_689_599_000), 2024);
602        assert_eq!(year_of_unix_ms(1_735_689_600_000), 2025);
603    }
604
605    fn episode_ref(guid: &str) -> PodcastEpisodeRef {
606        use music_dht::podcast::{FeedUrl, PodcastId};
607        let feed_url = FeedUrl::parse("https://example.test/feed.xml").unwrap();
608        let podcast_id = PodcastId::from_feed_url(&feed_url);
609        PodcastEpisodeRef {
610            episode_id: EpisodeId::from_guid(&podcast_id, guid).unwrap(),
611            podcast_id,
612            feed_url,
613            podcast_title: "Show".into(),
614            episode_title: "Pilot".into(),
615            audio_url: "https://cdn.example.test/1.mp3".into(),
616            mime: Some("audio/mpeg".into()),
617            duration_ms: Some(90_500),
618            published_at_ms: Some(1_709_208_000_000),
619            season: Some(2),
620            episode_number: Some(7),
621            image_url: None,
622            progress_generation: None,
623        }
624    }
625
626    fn library_track(id: i64) -> TrackItem {
627        TrackItem {
628            id,
629            title: "Track".into(),
630            track_number: None,
631            disc_number: None,
632            duration_seconds: 1.0,
633            artists: vec![artist("Main")],
634            featured_artists: Vec::new(),
635            release_id: 1,
636            release_title: "Release".into(),
637            release_year: None,
638            file_path: "/tmp/track.mp3".into(),
639            content_id: None,
640            cover_path: None,
641            audio_format: None,
642            audio_bitrate: None,
643            audio_sample_rate: None,
644            audio_bit_depth: None,
645            file_size_bytes: None,
646            play_count: 0,
647            fed: None,
648            podcast: None,
649        }
650    }
651
652    fn federated(owner: &str, item_id: &str) -> FederatedTrack {
653        FederatedTrack {
654            item_id: item_id.into(),
655            owner: owner.into(),
656            own: false,
657            title: "Remote".into(),
658            artist_names: vec!["Someone".into()],
659            featured_artist_names: Vec::new(),
660            year: None,
661            duration_seconds: None,
662            content_id: None,
663            release_title: None,
664            track_number: None,
665            disc_number: None,
666        }
667    }
668
669    #[test]
670    fn podcast_track_mirrors_the_episode_reference() {
671        let episode = episode_ref("e1");
672        let track = TrackItem::podcast_episode(episode.clone());
673        assert!(track.is_podcast());
674        assert_eq!(track.podcast_episode_ref(), Some(&episode));
675        // The sentinel marks "not a library row, release or artist" and
676        // carries no identity.
677        assert_eq!(TrackItem::NOT_A_LIBRARY_ROW, -1);
678        assert_eq!(track.id, -1);
679        assert_eq!(track.release_id, -1);
680        assert!(track.artists.iter().all(|artist| artist.id == -1));
681        assert!(track.featured_artists.is_empty());
682        assert!(track.file_path.is_empty());
683        assert!(track.content_id.is_none() && track.fed.is_none());
684        assert!(!track.is_fed_pending());
685        assert_eq!(track.title, "Pilot");
686        assert_eq!(track.artist_line(), "Show");
687        assert_eq!(track.release_title, "Show");
688        assert_eq!(track.release_year, Some(2024));
689        assert_eq!(track.duration_label(), "1:31");
690    }
691
692    #[test]
693    fn key_is_typed_by_source() {
694        let library = library_track(123);
695        assert_eq!(library.key(), TrackItemKey::Library(123));
696        assert_eq!(library.key().to_string(), "lib:123");
697        assert_eq!(library_track(0).key(), TrackItemKey::Library(0));
698
699        let mut pending = library_track(-5);
700        pending.release_id = -1;
701        pending.file_path.clear();
702        pending.fed = Some(federated("peer1", "item-9"));
703        let fed_key = TrackItemKey::Federated {
704            owner: "peer1".into(),
705            item_id: "item-9".into(),
706        };
707        assert_eq!(pending.key(), fed_key);
708        assert_eq!(pending.key().to_string(), "fed:peer1:item-9");
709        // The process-local negative id is not part of a federated identity.
710        let mut renumbered = pending.clone();
711        renumbered.id = -6;
712        assert_eq!(renumbered.key(), pending.key());
713
714        let episode = episode_ref("e1");
715        let track = TrackItem::podcast_episode(episode.clone());
716        let ep_key = TrackItemKey::PodcastEpisode(episode.episode_id.clone());
717        assert_eq!(track.key(), ep_key);
718        assert_eq!(
719            track.key().to_string(),
720            format!("ep:{}", episode.episode_id.as_str())
721        );
722        assert!(track.key().to_string().starts_with("ep:ep1:"));
723
724        let transient = library_track(-7);
725        assert_eq!(transient.key(), TrackItemKey::Transient(-7));
726        assert_eq!(transient.key().to_string(), "tmp:-7");
727
728        // The source wins over the numeric id: a podcast item is never keyed
729        // as a library row, a federated item never by its counter value.
730        let mut odd = TrackItem::podcast_episode(episode);
731        odd.id = 42;
732        assert_eq!(odd.key(), ep_key);
733        let mut pending_minus_one = pending.clone();
734        pending_minus_one.id = TrackItem::NOT_A_LIBRARY_ROW;
735        assert_eq!(pending_minus_one.key(), fed_key);
736        assert_ne!(pending_minus_one.key(), track.key());
737    }
738
739    #[test]
740    fn received_playback_tracks_never_copy_wire_ids() {
741        // F1 wire form of an episode: id 0, release_id 0.
742        let episode = episode_ref("e1");
743        let wire = PlaybackTrack::podcast_episode(episode.clone());
744        assert_eq!((wire.id, wire.release_id), (0, 0));
745        let PlaybackItem::PodcastEpisode(item) = TrackItem::from_playback_track(&wire) else {
746            panic!("an episode is not music");
747        };
748        assert_eq!(item.id, TrackItem::NOT_A_LIBRARY_ROW);
749        assert_eq!(item.release_id, TrackItem::NOT_A_LIBRARY_ROW);
750        assert!(item.artists.iter().all(|artist| artist.id < 0));
751        assert_eq!(
752            item.key(),
753            TrackItemKey::PodcastEpisode(episode.episode_id.clone())
754        );
755        assert_eq!(item.podcast_episode_ref(), Some(&episode));
756        // Legacy display fields an older sender filled in do not matter.
757        let mut odd = wire.clone();
758        odd.id = 42;
759        odd.release_id = 7;
760        odd.title = "Something else".into();
761        let PlaybackItem::PodcastEpisode(odd) = TrackItem::from_playback_track(&odd) else {
762            panic!("the source decides");
763        };
764        assert_eq!(odd.key(), item.key());
765        assert_eq!(odd.id, TrackItem::NOT_A_LIBRARY_ROW);
766
767        // A private placeholder (also id 0) never becomes library row 0.
768        let private = PlaybackTrack::private_placeholder();
769        assert_eq!(private.id, 0);
770        assert!(matches!(
771            TrackItem::from_playback_track(&private),
772            PlaybackItem::Private
773        ));
774
775        // Music is left to the client's music path.
776        let mut music = wire;
777        music.source = None;
778        assert!(matches!(
779            TrackItem::from_playback_track(&music),
780            PlaybackItem::Music
781        ));
782        music.source = Some(PlaybackSource::Music);
783        assert!(matches!(
784            TrackItem::from_playback_track(&music),
785            PlaybackItem::Music
786        ));
787    }
788
789    #[test]
790    fn episodes_share_the_sentinel_id_but_not_the_key() {
791        let first = TrackItem::podcast_episode(episode_ref("e1"));
792        let second = TrackItem::podcast_episode(episode_ref("e2"));
793        assert_eq!(first.id, TrackItem::NOT_A_LIBRARY_ROW);
794        assert_eq!(second.id, TrackItem::NOT_A_LIBRARY_ROW);
795        assert_eq!(first.id, second.id);
796        assert_eq!(first.release_id, second.release_id);
797        assert_ne!(first.key(), second.key());
798        assert_ne!(first.key().to_string(), second.key().to_string());
799        assert_eq!(
800            TrackItem::podcast_episode(episode_ref("e1")).key(),
801            first.key()
802        );
803        let keys: std::collections::HashSet<TrackItemKey> =
804            [first.key(), second.key(), first.key()]
805                .into_iter()
806                .collect();
807        assert_eq!(keys.len(), 2);
808        let mut ordered = [second.key(), first.key(), TrackItemKey::Library(1)];
809        ordered.sort();
810        assert_eq!(ordered[0], TrackItemKey::Library(1));
811    }
812}