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/// An item a search found, as a client shows both a plain search's and a
144/// federated one's: the item, and where it is from with its title's
145/// other copies when the search was across paired servers.
146#[derive(Debug, Clone, PartialEq, Eq)]
147#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
148pub struct SearchResult {
149    pub item: Item,
150    /// Where it is from, its other copies and the copy that plays; `None`
151    /// from a search of this server alone, where it is this server's own.
152    pub copies: Option<Copies>,
153}
154
155impl SearchResult {
156    /// The paired server it is from, by its server id; `None` for this
157    /// server's own.
158    pub fn origin(&self) -> Option<&str> {
159        let origin = self.copies.as_ref()?.origin.as_ref()?;
160        Some(origin.server_id.as_str())
161    }
162}
163
164impl From<Item> for SearchResult {
165    fn from(item: Item) -> Self {
166        Self { item, copies: None }
167    }
168}
169
170impl From<SearchHit> for SearchResult {
171    fn from(hit: SearchHit) -> Self {
172        Self {
173            item: hit.item,
174            copies: Some(Copies {
175                origin: hit.origin,
176                also_on: hit.also_on,
177                play_from: hit.play_from,
178            }),
179        }
180    }
181}
182
183/// One copy of a title, on one server.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
186pub struct TitleCopy {
187    /// The copy's id here: a `fed:` id for a paired server's.
188    pub id: MediaId,
189    /// Its paired server; `None` for this server's own.
190    #[serde(default)]
191    pub server: Option<LibraryServer>,
192}
193
194/// The top match: an item, or a person. On the wire, `{"item": {...}}`
195/// or `{"person": {...}}`. A person's items are listed with
196/// `Request::PersonItems`.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "snake_case")]
199pub enum TopResult<T = Item> {
200    Item(T),
201    Person(Person),
202}
203
204/// One kind's results.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
206pub struct SearchGroup<T = Item> {
207    pub kind: SearchKind,
208    /// The items, best first; empty for [`SearchKind::People`].
209    pub items: Vec<T>,
210    /// The people, for [`SearchKind::People`] only.
211    pub people: Vec<Person>,
212    /// There are more than are here: a `kind` search for this group
213    /// finds them.
214    pub more: bool,
215    /// How many a `kind` search for this group finds, for "See all 23":
216    /// the top match and the episodes under their show (`hidden`)
217    /// included. For items it is the catalog's exact count. People are
218    /// counted only when every one of them is here (`more` is false):
219    /// Plex lists them only up to the limit.
220    pub total: Option<u32>,
221    /// Episodes left out because their show is in the shows group (only
222    /// in `All`, where episodes are quiet), for "3 from Severance are
223    /// under the show". A group may be here with only this.
224    pub hidden: u32,
225}
226
227/// How many results each scope has, for the scope chips and the empty
228/// state. A count is what the catalog says, not a promise: the scope's
229/// own search may find a few more or fewer. `None` where it is not known
230/// without asking again; a search that finds nothing in its scope counts
231/// the others.
232#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
233#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
234pub struct SearchCounts {
235    /// Every group, people included.
236    pub all: Option<u32>,
237    pub movies: Option<u32>,
238    pub shows: Option<u32>,
239    /// Every matching episode, quiet ones included: what the Episodes
240    /// scope shows.
241    pub episodes: Option<u32>,
242    /// Artists, albums and tracks together.
243    pub music: Option<u32>,
244}
245
246impl SearchCounts {
247    /// The count for `scope`.
248    pub fn of(&self, scope: SearchScope) -> Option<u32> {
249        match scope {
250            SearchScope::All => self.all,
251            SearchScope::Movies => self.movies,
252            SearchScope::Shows => self.shows,
253            SearchScope::Episodes => self.episodes,
254            SearchScope::Music => self.music,
255        }
256    }
257}