1use std::collections::{HashMap, HashSet};
14use std::time::{SystemTime, UNIX_EPOCH};
15
16use spoolframe_types::{Item, MediaId, Person, SearchKind, SearchScope};
17
18use crate::search::{SearchCounts, SearchGroup, SearchRequest, SearchResults, TopResult};
19
20pub const QUIET_EPISODES: usize = 3;
22
23pub const WITHOUT_YEAR: usize = 3;
25
26pub const MEDIA: [SearchKind; 6] = [
28 SearchKind::Shows,
29 SearchKind::Movies,
30 SearchKind::Artists,
31 SearchKind::Albums,
32 SearchKind::Tracks,
33 SearchKind::Episodes,
34];
35
36const MUSIC: [SearchKind; 3] = [SearchKind::Artists, SearchKind::Albums, SearchKind::Tracks];
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Parsed {
41 pub text: String,
42 pub year: Option<u16>,
43}
44
45pub fn parse(query: &str, this_year: u16) -> Parsed {
49 let query = query.trim();
50 if let Some((text, last)) = query.rsplit_once(char::is_whitespace) {
51 let text = text.trim_end();
52 let year = (last.len() == 4 && last.bytes().all(|b| b.is_ascii_digit()))
53 .then(|| last.parse::<u16>().ok())
54 .flatten()
55 .filter(|y| (1900..=this_year.saturating_add(1)).contains(y));
56 if let Some(year) = year.filter(|_| !text.is_empty()) {
57 return Parsed {
58 text: text.to_owned(),
59 year: Some(year),
60 };
61 }
62 }
63 Parsed {
64 text: query.to_owned(),
65 year: None,
66 }
67}
68
69pub fn this_year() -> u16 {
73 let secs = SystemTime::now()
74 .duration_since(UNIX_EPOCH)
75 .map(|d| d.as_secs())
76 .unwrap_or_default();
77 u16::try_from(1970 + secs / 31_556_952).unwrap_or(u16::MAX)
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct Matched {
84 pub kind: SearchKind,
85 pub items: Vec<Item>,
87 pub people: Vec<Person>,
89 pub total: u32,
92}
93
94#[derive(Debug, Clone, Copy)]
98pub struct Ranker {
99 normalize: fn(&str) -> String,
100}
101
102impl Default for Ranker {
103 fn default() -> Self {
105 Self::new(normalized)
106 }
107}
108
109impl Ranker {
110 pub fn new(normalize: fn(&str) -> String) -> Self {
113 Self { normalize }
114 }
115
116 pub fn group(
124 &self,
125 request: &SearchRequest,
126 query: &Parsed,
127 mut found: Vec<Matched>,
128 totals: &HashMap<SearchKind, u32>,
129 without_year: Vec<Item>,
130 copies: &HashMap<MediaId, Vec<MediaId>>,
131 ) -> SearchResults {
132 let year = query.year;
133 let limit = usize::try_from(request.limit).unwrap_or(usize::MAX);
134 let see_all = request.kind.is_some();
135 let quiet = !see_all && request.scope == SearchScope::All;
136 let text = (self.normalize)(&query.text);
137 found.sort_by_key(|g| g.kind);
138
139 let top = match see_all {
140 true => None,
141 false => self.top(&found, &text),
142 };
143 let top_item = match &top {
144 Some(TopResult::Item(item)) => Some(item.id()),
145 _ => None,
146 };
147 let top_person = match &top {
148 Some(TopResult::Person(person)) => Some(&person.id),
149 _ => None,
150 };
151 let shows: HashSet<MediaId> = found
155 .iter()
156 .filter(|g| g.kind == SearchKind::Shows)
157 .flat_map(|g| self.listed(&g.items, top_item, &text, limit))
158 .flat_map(|id| {
159 let more = copies.get(id).cloned().unwrap_or_default();
160 std::iter::once(id.clone()).chain(more)
161 })
162 .collect();
163
164 let mut groups = Vec::new();
165 for Matched {
166 kind,
167 mut items,
168 mut people,
169 total,
170 } in found
171 {
172 let before = items.len() + people.len();
173 items.retain(|i| Some(i.id()) != top_item);
174 people.retain(|p| Some(&p.id) != top_person);
175 let removed = before - items.len() - people.len();
176 let mut hidden = 0;
177 if quiet && kind == SearchKind::Episodes {
178 let before = items.len();
179 items.retain(|i| !matches!(i, Item::Episode(e) if shows.contains(&e.show_id)));
180 hidden = before - items.len();
181 }
182 items.sort_by_cached_key(|i| self.tier(i, &text));
184 let cap = match quiet && kind == SearchKind::Episodes {
185 true => limit.min(QUIET_EPISODES),
186 false => limit,
187 };
188 items.truncate(cap);
189 people.truncate(cap);
190 let shown = items.len() + people.len();
191 let available = usize::try_from(total)
192 .unwrap_or(usize::MAX)
193 .saturating_sub(removed + hidden);
194 if shown == 0 && !see_all {
197 continue;
198 }
199 let more = available > shown;
200 let total = match kind {
201 SearchKind::People if more => None,
202 _ => Some(total),
203 };
204 groups.push(SearchGroup {
205 kind,
206 items,
207 people,
208 more,
209 total,
210 hidden: u32::try_from(hidden).unwrap_or(u32::MAX),
211 });
212 }
213
214 SearchResults {
215 top,
216 groups,
217 counts: counts(totals),
218 year,
219 without_year,
220 }
221 }
222
223 fn listed<'a>(
227 &self,
228 items: &'a [Item],
229 top: Option<&MediaId>,
230 text: &str,
231 cap: usize,
232 ) -> Vec<&'a MediaId> {
233 let mut kept: Vec<&Item> = items.iter().filter(|i| Some(i.id()) != top).collect();
234 kept.sort_by_cached_key(|i| self.tier(i, text));
235 kept.into_iter().take(cap).map(Item::id).collect()
236 }
237
238 pub fn without_year(
241 &self,
242 text: &str,
243 year: u16,
244 found: &[Matched],
245 mut any_year: Vec<Matched>,
246 ) -> Vec<Item> {
247 let matched: HashSet<&MediaId> =
248 found.iter().flat_map(|g| &g.items).map(Item::id).collect();
249 any_year.sort_by_key(|g| g.kind);
250 let others = any_year
251 .iter()
252 .flat_map(|g| &g.items)
253 .filter(|i| year_of(i) != Some(year) && !matched.contains(i.id()));
254 let mut ranked: Vec<_> = others.enumerate().collect();
255 let text = (self.normalize)(text);
256 ranked.sort_by_cached_key(|&(at, item)| (self.tier(item, &text), at));
257 ranked
258 .into_iter()
259 .take(WITHOUT_YEAR)
260 .map(|(_, item)| item.clone())
261 .collect()
262 }
263
264 fn top(&self, found: &[Matched], text: &str) -> Option<TopResult> {
270 let item = self.best(found.iter().flat_map(|g| &g.items), text);
271 let person = found
272 .iter()
273 .flat_map(|g| &g.people)
274 .enumerate()
275 .min_by_key(|&(at, person)| (self.tier_of(&person.name, text), at))
276 .map(|(_, person)| person);
277 match (item, person) {
278 (Some(item), Some(person))
279 if self.tier_of(&person.name, text) < self.tier(item, text) =>
280 {
281 Some(TopResult::Person(person.clone()))
282 }
283 (Some(item), _) => Some(TopResult::Item(item.clone())),
284 (None, Some(person)) => Some(TopResult::Person(person.clone())),
285 (None, None) => None,
286 }
287 }
288
289 fn best<'a>(&self, items: impl Iterator<Item = &'a Item>, text: &str) -> Option<&'a Item> {
293 items
294 .enumerate()
295 .min_by_key(|&(at, item)| (self.tier(item, text), at))
296 .map(|(_, item)| item)
297 }
298
299 fn tier(&self, item: &Item, text: &str) -> u8 {
301 self.tier_of(item.title(), text)
302 }
303
304 pub fn tier_of(&self, title: &str, text: &str) -> u8 {
307 let title = (self.normalize)(title);
308 if title == text {
309 0
310 } else if title.starts_with(text) {
311 1
312 } else {
313 2
314 }
315 }
316}
317
318pub fn counts(totals: &HashMap<SearchKind, u32>) -> SearchCounts {
321 let of = |kind| totals.get(&kind).copied();
322 let sum = |kinds: &[SearchKind]| kinds.iter().map(|&k| of(k)).sum::<Option<u32>>();
323 SearchCounts {
324 all: sum(&MEDIA).map(|media| media.saturating_add(of(SearchKind::People).unwrap_or(0))),
325 movies: of(SearchKind::Movies),
326 shows: of(SearchKind::Shows),
327 episodes: of(SearchKind::Episodes),
328 music: sum(&MUSIC),
329 }
330}
331
332pub fn normalized(s: &str) -> String {
336 let s = s
337 .split_whitespace()
338 .collect::<Vec<_>>()
339 .join(" ")
340 .to_lowercase();
341 strip_article(&s).to_owned()
342}
343
344pub fn strip_article(s: &str) -> &str {
347 ["the ", "a ", "an "]
348 .iter()
349 .find_map(|article| s.strip_prefix(article))
350 .unwrap_or(s)
351}
352
353pub fn year_of(item: &Item) -> Option<u16> {
355 match item {
356 Item::Movie(v) => v.year,
357 Item::Show(v) => v.year,
358 Item::Album(v) => v.year,
359 _ => None,
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 #[test]
370 fn a_ranker_compares_titles_as_its_normalize_says() {
371 fn ascii(s: &str) -> String {
372 normalized(&s.replace('é', "e"))
373 }
374 let amelie = "Amélie";
375 assert_eq!(Ranker::default().tier_of(amelie, "amelie"), 2);
376 assert_eq!(Ranker::new(ascii).tier_of(amelie, "amelie"), 0);
377 }
378
379 #[test]
380 fn only_a_leading_article_is_dropped() {
381 assert_eq!(normalized("The Cure"), "cure");
382 assert_eq!(normalized("Theory"), "theory");
383 assert_eq!(normalized("Cure for the Itch"), "cure for the itch");
384 }
385}