Skip to main content

spoolframe_protocol/
search.rs

1//! Scoped, grouped search: `Request::Search` and its reply.
2
3use serde::{Deserialize, Serialize};
4use spoolframe_types::{Item, LibraryId, LibraryServer, MediaId, Person, SearchKind, SearchScope};
5
6/// A search. On the wire, `{"type": "search", "query": …, "scope": …}`.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct SearchRequest {
9    /// What was typed. A year at its end ("dune 2021") narrows the search
10    /// to that year and is not itself searched for; the reply says which
11    /// year it took.
12    pub query: String,
13    /// The most items (or people) a group holds.
14    pub limit: u32,
15    pub scope: SearchScope,
16    /// One group only, for "See all": up to `limit` of its items and no
17    /// top match. It overrides `scope`, since people, artists, albums and
18    /// tracks have no scope of their own.
19    pub kind: Option<SearchKind>,
20    /// Only this library's items, and the people found in it, each with
21    /// their count there. A person's items (`PersonItems`) are still all
22    /// of theirs.
23    pub library: Option<LibraryId>,
24}
25
26/// What a search found: `Item`s, or for a client that names the
27/// experimental `federation` feature [`SearchHit`]s.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct SearchResults<T = Item> {
30    /// The single best match: an exact title, else a title that starts
31    /// with the query (case and a leading "the", "a" or "an" aside), else
32    /// the first result; on a tie a show before a movie, then artist,
33    /// album, track and episode, so a show beats its own episodes. A
34    /// person is the top match only when their name matches better than
35    /// every title (an exact "keanu reeves" over titles that start with
36    /// it), or when only people are found: on a tie the item wins. Not
37    /// repeated in its group. `None` for a `kind` search.
38    pub top: Option<TopResult<T>>,
39    /// The groups that have something to show, in the order they are
40    /// shown: shows, movies, people, artists, albums, tracks, episodes. A
41    /// `kind` search has that one group, even when it is empty.
42    pub groups: Vec<SearchGroup<T>>,
43    pub counts: SearchCounts,
44    /// The year taken from the end of the query as a filter, to show as a
45    /// removable token.
46    pub year: Option<u16>,
47    /// With a `year`: up to 3 items the query matches in other years, for
48    /// "also matching without the year".
49    pub without_year: Vec<T>,
50}
51
52impl<T> Default for SearchResults<T> {
53    fn default() -> Self {
54        Self {
55            top: None,
56            groups: Vec::new(),
57            counts: SearchCounts::default(),
58            year: None,
59            without_year: Vec::new(),
60        }
61    }
62}
63
64impl<T> SearchResults<T> {
65    /// The same results with each item made `f` of it, in place.
66    pub fn map<U>(self, mut f: impl FnMut(T) -> U) -> SearchResults<U> {
67        SearchResults {
68            top: self.top.map(|top| match top {
69                TopResult::Item(item) => TopResult::Item(f(item)),
70                TopResult::Person(person) => TopResult::Person(person),
71            }),
72            groups: self
73                .groups
74                .into_iter()
75                .map(|g| SearchGroup {
76                    kind: g.kind,
77                    items: g.items.into_iter().map(&mut f).collect(),
78                    people: g.people,
79                    more: g.more,
80                    total: g.total,
81                    hidden: g.hidden,
82                })
83                .collect(),
84            counts: self.counts,
85            year: self.year,
86            without_year: self.without_year.into_iter().map(f).collect(),
87        }
88    }
89}
90
91/// Experimental (`federation`): a search's item for a client that
92/// names the feature. A title on several servers (the same TMDB, IMDb,
93/// TVDB, MusicBrainz or Plex id; an episode by its show's, season and
94/// number) is one hit: this server's copy when it has one, else the copy
95/// the user plays from or last played, else the first online.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
98pub struct SearchHit {
99    pub item: Item,
100    /// The paired server `item` is from; `None` for this server's own.
101    #[serde(default)]
102    pub origin: Option<LibraryServer>,
103    /// The title's copies on other servers ("also on Bob's Media"), in
104    /// the order a Play from list shows them; empty for a title on one
105    /// server.
106    #[serde(default)]
107    pub also_on: Vec<TitleCopy>,
108    /// The copy that plays: the one on the server the user chose for the
109    /// title (`SetPlayFrom`) while it has one, else `item`'s own id.
110    pub play_from: MediaId,
111}
112
113impl SearchHit {
114    pub fn new(item: Item, copies: Copies) -> Self {
115        Self {
116            item,
117            origin: copies.origin,
118            also_on: copies.also_on,
119            play_from: copies.play_from,
120        }
121    }
122}
123
124/// Experimental (`federation`): where an item is from, and its
125/// title's copies on other servers, as a [`SearchHit`] and an `Item`
126/// reply have them.
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
129pub struct Copies {
130    /// The paired server the item is from; `None` for this server's own.
131    #[serde(default)]
132    pub origin: Option<LibraryServer>,
133    /// The title's copies on other servers: this server's first, then the
134    /// paired servers online by name, then those offline (greyed: browsed,
135    /// not played).
136    #[serde(default)]
137    pub also_on: Vec<TitleCopy>,
138    /// The copy that plays: on the server the user chose for the title
139    /// (`SetPlayFrom`) while it has one, else the item's own id.
140    pub play_from: MediaId,
141}
142
143/// One copy of a title, on one server.
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
146pub struct TitleCopy {
147    /// The copy's id here: a `fed:` id for a paired server's.
148    pub id: MediaId,
149    /// Its paired server; `None` for this server's own.
150    #[serde(default)]
151    pub server: Option<LibraryServer>,
152}
153
154/// The top match: an item, or a person. On the wire, `{"item": {...}}`
155/// or `{"person": {...}}`. A person's items are listed with
156/// `Request::PersonItems`.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(rename_all = "snake_case")]
159pub enum TopResult<T = Item> {
160    Item(T),
161    Person(Person),
162}
163
164/// One kind's results.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub struct SearchGroup<T = Item> {
167    pub kind: SearchKind,
168    /// The items, best first; empty for [`SearchKind::People`].
169    pub items: Vec<T>,
170    /// The people, for [`SearchKind::People`] only.
171    pub people: Vec<Person>,
172    /// There are more than are here: a `kind` search for this group
173    /// finds them.
174    pub more: bool,
175    /// How many a `kind` search for this group finds, for "See all 23":
176    /// the top match and the episodes under their show (`hidden`)
177    /// included. For items it is the catalog's exact count. People are
178    /// counted only when every one of them is here (`more` is false):
179    /// Plex lists them only up to the limit.
180    pub total: Option<u32>,
181    /// Episodes left out because their show is in the shows group (only
182    /// in `All`, where episodes are quiet), for "3 from Severance are
183    /// under the show". A group may be here with only this.
184    pub hidden: u32,
185}
186
187/// How many results each scope has, for the scope chips and the empty
188/// state. A count is what the catalog says, not a promise: the scope's
189/// own search may find a few more or fewer. `None` where it is not known
190/// without asking again; a search that finds nothing in its scope counts
191/// the others.
192#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
193#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
194pub struct SearchCounts {
195    /// Every group, people included.
196    pub all: Option<u32>,
197    pub movies: Option<u32>,
198    pub shows: Option<u32>,
199    /// Every matching episode, quiet ones included: what the Episodes
200    /// scope shows.
201    pub episodes: Option<u32>,
202    /// Artists, albums and tracks together.
203    pub music: Option<u32>,
204}
205
206impl SearchCounts {
207    /// The count for `scope`.
208    pub fn of(&self, scope: SearchScope) -> Option<u32> {
209        match scope {
210            SearchScope::All => self.all,
211            SearchScope::Movies => self.movies,
212            SearchScope::Shows => self.shows,
213            SearchScope::Episodes => self.episodes,
214            SearchScope::Music => self.music,
215        }
216    }
217}