1use music_dht::device_sync::{PlaybackSource, PlaybackTrack};
5use music_dht::podcast::{EpisodeId, PodcastEpisodeRef};
6use serde::{Deserialize, Serialize};
7
8#[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#[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#[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 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#[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 pub file_path: String,
189 pub content_id: Option<String>,
191 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 pub play_count: i64,
200 pub fed: Option<FederatedTrack>,
204 pub podcast: Option<PodcastEpisodeRef>,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
231pub enum TrackItemKey {
232 Library(i64),
234 Federated { owner: String, item_id: String },
238 PodcastEpisode(EpisodeId),
240 Transient(i64),
244}
245
246#[derive(Debug, Clone)]
249pub enum PlaybackItem {
250 Music,
253 PodcastEpisode(Box<TrackItem>),
255 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 pub const NOT_A_LIBRARY_ROW: i64 = -1;
280
281 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 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 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 pub fn is_podcast(&self) -> bool {
377 self.podcast.is_some()
378 }
379
380 pub fn podcast_episode_ref(&self) -> Option<&PodcastEpisodeRef> {
382 self.podcast.as_ref()
383 }
384
385 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 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
435fn year_of_unix_ms(ms: i64) -> i32 {
437 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 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 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#[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 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 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 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 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 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 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 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 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 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}