use std::collections::{HashMap, HashSet};
use std::time::{SystemTime, UNIX_EPOCH};
use spoolframe_types::{Item, MediaId, Person, SearchKind, SearchScope};
use crate::search::{SearchCounts, SearchGroup, SearchRequest, SearchResults, TopResult};
pub const QUIET_EPISODES: usize = 3;
pub const WITHOUT_YEAR: usize = 3;
pub const MEDIA: [SearchKind; 6] = [
SearchKind::Shows,
SearchKind::Movies,
SearchKind::Artists,
SearchKind::Albums,
SearchKind::Tracks,
SearchKind::Episodes,
];
const MUSIC: [SearchKind; 3] = [SearchKind::Artists, SearchKind::Albums, SearchKind::Tracks];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Parsed {
pub text: String,
pub year: Option<u16>,
}
pub fn parse(query: &str, this_year: u16) -> Parsed {
let query = query.trim();
if let Some((text, last)) = query.rsplit_once(char::is_whitespace) {
let text = text.trim_end();
let year = (last.len() == 4 && last.bytes().all(|b| b.is_ascii_digit()))
.then(|| last.parse::<u16>().ok())
.flatten()
.filter(|y| (1900..=this_year.saturating_add(1)).contains(y));
if let Some(year) = year.filter(|_| !text.is_empty()) {
return Parsed {
text: text.to_owned(),
year: Some(year),
};
}
}
Parsed {
text: query.to_owned(),
year: None,
}
}
pub fn this_year() -> u16 {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or_default();
u16::try_from(1970 + secs / 31_556_952).unwrap_or(u16::MAX)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Matched {
pub kind: SearchKind,
pub items: Vec<Item>,
pub people: Vec<Person>,
pub total: u32,
}
#[derive(Debug, Clone, Copy)]
pub struct Ranker {
normalize: fn(&str) -> String,
}
impl Default for Ranker {
fn default() -> Self {
Self::new(normalized)
}
}
impl Ranker {
pub fn new(normalize: fn(&str) -> String) -> Self {
Self { normalize }
}
pub fn group(
&self,
request: &SearchRequest,
query: &Parsed,
mut found: Vec<Matched>,
totals: &HashMap<SearchKind, u32>,
without_year: Vec<Item>,
copies: &HashMap<MediaId, Vec<MediaId>>,
) -> SearchResults {
let year = query.year;
let limit = usize::try_from(request.limit).unwrap_or(usize::MAX);
let see_all = request.kind.is_some();
let quiet = !see_all && request.scope == SearchScope::All;
let text = (self.normalize)(&query.text);
found.sort_by_key(|g| g.kind);
let top = match see_all {
true => None,
false => self.top(&found, &text),
};
let top_item = match &top {
Some(TopResult::Item(item)) => Some(item.id()),
_ => None,
};
let top_person = match &top {
Some(TopResult::Person(person)) => Some(&person.id),
_ => None,
};
let shows: HashSet<MediaId> = found
.iter()
.filter(|g| g.kind == SearchKind::Shows)
.flat_map(|g| self.listed(&g.items, top_item, &text, limit))
.flat_map(|id| {
let more = copies.get(id).cloned().unwrap_or_default();
std::iter::once(id.clone()).chain(more)
})
.collect();
let mut groups = Vec::new();
for Matched {
kind,
mut items,
mut people,
total,
} in found
{
let before = items.len() + people.len();
items.retain(|i| Some(i.id()) != top_item);
people.retain(|p| Some(&p.id) != top_person);
let removed = before - items.len() - people.len();
let mut hidden = 0;
if quiet && kind == SearchKind::Episodes {
let before = items.len();
items.retain(|i| !matches!(i, Item::Episode(e) if shows.contains(&e.show_id)));
hidden = before - items.len();
}
items.sort_by_cached_key(|i| self.tier(i, &text));
let cap = match quiet && kind == SearchKind::Episodes {
true => limit.min(QUIET_EPISODES),
false => limit,
};
items.truncate(cap);
people.truncate(cap);
let shown = items.len() + people.len();
let available = usize::try_from(total)
.unwrap_or(usize::MAX)
.saturating_sub(removed + hidden);
if shown == 0 && !see_all {
continue;
}
let more = available > shown;
let total = match kind {
SearchKind::People if more => None,
_ => Some(total),
};
groups.push(SearchGroup {
kind,
items,
people,
more,
total,
hidden: u32::try_from(hidden).unwrap_or(u32::MAX),
});
}
SearchResults {
top,
groups,
counts: counts(totals),
year,
without_year,
}
}
fn listed<'a>(
&self,
items: &'a [Item],
top: Option<&MediaId>,
text: &str,
cap: usize,
) -> Vec<&'a MediaId> {
let mut kept: Vec<&Item> = items.iter().filter(|i| Some(i.id()) != top).collect();
kept.sort_by_cached_key(|i| self.tier(i, text));
kept.into_iter().take(cap).map(Item::id).collect()
}
pub fn without_year(
&self,
text: &str,
year: u16,
found: &[Matched],
mut any_year: Vec<Matched>,
) -> Vec<Item> {
let matched: HashSet<&MediaId> =
found.iter().flat_map(|g| &g.items).map(Item::id).collect();
any_year.sort_by_key(|g| g.kind);
let others = any_year
.iter()
.flat_map(|g| &g.items)
.filter(|i| year_of(i) != Some(year) && !matched.contains(i.id()));
let mut ranked: Vec<_> = others.enumerate().collect();
let text = (self.normalize)(text);
ranked.sort_by_cached_key(|&(at, item)| (self.tier(item, &text), at));
ranked
.into_iter()
.take(WITHOUT_YEAR)
.map(|(_, item)| item.clone())
.collect()
}
fn top(&self, found: &[Matched], text: &str) -> Option<TopResult> {
let item = self.best(found.iter().flat_map(|g| &g.items), text);
let person = found
.iter()
.flat_map(|g| &g.people)
.enumerate()
.min_by_key(|&(at, person)| (self.tier_of(&person.name, text), at))
.map(|(_, person)| person);
match (item, person) {
(Some(item), Some(person))
if self.tier_of(&person.name, text) < self.tier(item, text) =>
{
Some(TopResult::Person(person.clone()))
}
(Some(item), _) => Some(TopResult::Item(item.clone())),
(None, Some(person)) => Some(TopResult::Person(person.clone())),
(None, None) => None,
}
}
fn best<'a>(&self, items: impl Iterator<Item = &'a Item>, text: &str) -> Option<&'a Item> {
items
.enumerate()
.min_by_key(|&(at, item)| (self.tier(item, text), at))
.map(|(_, item)| item)
}
fn tier(&self, item: &Item, text: &str) -> u8 {
self.tier_of(item.title(), text)
}
pub fn tier_of(&self, title: &str, text: &str) -> u8 {
let title = (self.normalize)(title);
if title == text {
0
} else if title.starts_with(text) {
1
} else {
2
}
}
}
pub fn counts(totals: &HashMap<SearchKind, u32>) -> SearchCounts {
let of = |kind| totals.get(&kind).copied();
let sum = |kinds: &[SearchKind]| kinds.iter().map(|&k| of(k)).sum::<Option<u32>>();
SearchCounts {
all: sum(&MEDIA).map(|media| media.saturating_add(of(SearchKind::People).unwrap_or(0))),
movies: of(SearchKind::Movies),
shows: of(SearchKind::Shows),
episodes: of(SearchKind::Episodes),
music: sum(&MUSIC),
}
}
pub fn normalized(s: &str) -> String {
let s = s
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase();
strip_article(&s).to_owned()
}
pub fn strip_article(s: &str) -> &str {
["the ", "a ", "an "]
.iter()
.find_map(|article| s.strip_prefix(article))
.unwrap_or(s)
}
pub fn year_of(item: &Item) -> Option<u16> {
match item {
Item::Movie(v) => v.year,
Item::Show(v) => v.year,
Item::Album(v) => v.year,
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_ranker_compares_titles_as_its_normalize_says() {
fn ascii(s: &str) -> String {
normalized(&s.replace('é', "e"))
}
let amelie = "Amélie";
assert_eq!(Ranker::default().tier_of(amelie, "amelie"), 2);
assert_eq!(Ranker::new(ascii).tier_of(amelie, "amelie"), 0);
}
#[test]
fn only_a_leading_article_is_dropped() {
assert_eq!(normalized("The Cure"), "cure");
assert_eq!(normalized("Theory"), "theory");
assert_eq!(normalized("Cure for the Itch"), "cure for the itch");
}
}