mirror of
https://github.com/narrrl/proton-stream.git
synced 2026-11-03 16:41:26 +01:00
feat(core,meta,app,android,cli): sort, group and shelve the library
The AniList query now keeps the start date, season, banner, popularity, status, next airing episode, tags, main studios, director and story relations, as TitleDetails in one JSON column (schema v10). Matches stored without them are fetched again by id, never searched, so hand-picked matches stay; refreshing the same entry keeps its episodes and fanart. Enrichment records the entries it walked. node_first_seen remembers when each file appeared, across recrawls. pstr_core::franchise groups titles that share a provider id. The grid folds each franchise into its lead with a +N badge, and the title page lists the whole franchise in release order. pstr_core::shelves picks rows by airing status, director, studio and genre. A row needs three franchises, so one franchise's titles never make a row on their own. Desktop: - Covers are the default grid (Settings > Appearance > Library tiles). - The hero and title band use fanart or banner decoded at 1920 px. - New sorts: recently added, newest, highest rated, most popular. - Titles can show the share's, English or romaji name; search matches all of them. Android carries TitleDetails through a hand-picked match; its screens are unchanged.
This commit is contained in:
1 parent
4c80076762
commit
6853725ca0
22 files changed
+2239
-187
No files matched your search
@@ -123,6 +123,30 @@ impl Accent {
|
||||
}
|
||||
}
|
||||
|
||||
/// What shape the library's grid is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Tiles {
|
||||
/// 2:3 covers. The default, because the art a provider has for every
|
||||
/// title is a cover; a 16:9 still exists for fewer of them, and a grid of
|
||||
/// letterboxed covers was the desktop's weakest page.
|
||||
#[default]
|
||||
Posters,
|
||||
/// 16:9 stills: the provider's fanart, else a frame from the file.
|
||||
Stills,
|
||||
}
|
||||
|
||||
impl Tiles {
|
||||
pub const ALL: [Self; 2] = [Self::Posters, Self::Stills];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Posters => "Posters",
|
||||
Self::Stills => "Stills",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole of the choice.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
// An older or hand-edited file is missing fields rather than invalid.
|
||||
@@ -138,6 +162,10 @@ pub struct Appearance {
|
||||
/// slow ramp across a wide bar bands visibly, and flat is better than
|
||||
/// striped.
|
||||
pub gradients: bool,
|
||||
/// The library grid's shape.
|
||||
pub tiles: Tiles,
|
||||
/// Which name a title goes by.
|
||||
pub names: crate::metadata::TitleNames,
|
||||
}
|
||||
|
||||
impl Default for Appearance {
|
||||
@@ -146,6 +174,8 @@ impl Default for Appearance {
|
||||
flavor: Flavor::default(),
|
||||
accent: Accent::default(),
|
||||
gradients: true,
|
||||
tiles: Tiles::default(),
|
||||
names: crate::metadata::TitleNames::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -615,6 +645,7 @@ mod tests {
|
||||
flavor: Flavor::Mocha,
|
||||
accent: Accent::PinkSky,
|
||||
gradients: false,
|
||||
..Appearance::default()
|
||||
};
|
||||
save(&dirs, &appearance).unwrap();
|
||||
assert_eq!(load(&dirs).unwrap(), appearance);
|
||||
@@ -652,6 +683,7 @@ mod tests {
|
||||
flavor,
|
||||
accent,
|
||||
gradients: true,
|
||||
..Appearance::default()
|
||||
});
|
||||
let ratio = worst_contrast(palette.accent, palette.accent_alt, palette.on_accent);
|
||||
assert!(
|
||||
@@ -681,6 +713,7 @@ mod tests {
|
||||
flavor: Flavor::Persona5,
|
||||
accent: Accent::Red,
|
||||
gradients: false,
|
||||
..Appearance::default()
|
||||
});
|
||||
assert_eq!(palette.accent, PERSONA5.red);
|
||||
assert!(!palette.light);
|
||||
@@ -697,6 +730,7 @@ mod tests {
|
||||
flavor,
|
||||
accent: Accent::Red,
|
||||
gradients: true,
|
||||
..Appearance::default()
|
||||
});
|
||||
// The accent is the flavour's red — deepened on the light flavour,
|
||||
// where it would otherwise be too bright to put a label on.
|
||||
|
||||
+227
-12
@@ -18,12 +18,13 @@ use rusqlite::{Connection, OptionalExtension, params};
|
||||
use crate::error::Result;
|
||||
use crate::library::TitleKind;
|
||||
use crate::metadata::{
|
||||
Enrichment, EpisodeGuide, EpisodeMetadata, MetadataRecord, ProviderId, TitleMetadata,
|
||||
Enrichment, EpisodeGuide, EpisodeMetadata, MetadataRecord, ProviderId, TitleDetails,
|
||||
TitleMetadata,
|
||||
};
|
||||
use crate::naming::{self, ParsedName};
|
||||
|
||||
/// Bump when adding a migration.
|
||||
pub const SCHEMA_VERSION: i64 = 9;
|
||||
pub const SCHEMA_VERSION: i64 = 10;
|
||||
|
||||
const MIGRATION_V1: &str = r#"
|
||||
CREATE TABLE nodes (
|
||||
@@ -179,6 +180,33 @@ DELETE FROM episode_metadata WHERE provider = 'anilist';
|
||||
UPDATE title_metadata SET backdrop_url = NULL WHERE provider = 'anilist';
|
||||
"#;
|
||||
|
||||
/// What the library is sorted, grouped and shelved by, and when each file
|
||||
/// first appeared.
|
||||
///
|
||||
/// `details` is [`TitleDetails`] as JSON — see there for why one column.
|
||||
/// `NULL` means it was never fetched, which a match run reads as "fetch it"
|
||||
/// rather than as "there is none"; every existing match starts that way.
|
||||
/// `chain` is the provider ids enrichment walked, newline-separated; every
|
||||
/// title is marked un-enriched so the next run records it.
|
||||
///
|
||||
/// `node_first_seen` is kept apart from `nodes` because a recrawl replaces
|
||||
/// every node row and "recently added" has to survive that. Files already in
|
||||
/// the catalog are recorded as seen at 0 — when they arrived is not known, and
|
||||
/// pretending it was today would put the whole library at the top.
|
||||
const MIGRATION_V10: &str = r#"
|
||||
ALTER TABLE title_metadata ADD COLUMN details TEXT;
|
||||
ALTER TABLE title_metadata ADD COLUMN chain TEXT;
|
||||
CREATE TABLE node_first_seen (
|
||||
share_id TEXT NOT NULL,
|
||||
link_id TEXT NOT NULL,
|
||||
seen_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (share_id, link_id)
|
||||
);
|
||||
INSERT OR IGNORE INTO node_first_seen (share_id, link_id, seen_at)
|
||||
SELECT share_id, link_id, 0 FROM nodes WHERE is_folder = 0;
|
||||
UPDATE title_metadata SET enriched_at = NULL;
|
||||
"#;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OfflineFile {
|
||||
pub revision_id: String,
|
||||
@@ -364,6 +392,12 @@ impl Catalog {
|
||||
tx.pragma_update(None, "user_version", 9)?;
|
||||
tx.commit()?;
|
||||
}
|
||||
if version < 10 {
|
||||
let tx = self.conn.transaction()?;
|
||||
tx.execute_batch(MIGRATION_V10)?;
|
||||
tx.pragma_update(None, "user_version", 10)?;
|
||||
tx.commit()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -424,6 +458,13 @@ impl Catalog {
|
||||
}
|
||||
}
|
||||
|
||||
// Only files: a folder appearing is not something anyone watches.
|
||||
tx.execute(
|
||||
"INSERT OR IGNORE INTO node_first_seen (share_id, link_id, seen_at)
|
||||
SELECT share_id, link_id, ?2 FROM nodes WHERE share_id = ?1 AND is_folder = 0",
|
||||
params![share_id, unix_now()],
|
||||
)?;
|
||||
|
||||
if !retain_offline {
|
||||
tx.execute("DELETE FROM offline_files WHERE share_id = ?1 AND NOT EXISTS (SELECT 1 FROM nodes WHERE nodes.share_id = offline_files.share_id AND nodes.link_id = offline_files.link_id AND nodes.active_revision_id = offline_files.revision_id)", params![share_id])?;
|
||||
}
|
||||
@@ -460,6 +501,18 @@ impl Catalog {
|
||||
Ok(rows.collect::<std::result::Result<Vec<_>, _>>()?)
|
||||
}
|
||||
|
||||
/// When each file first appeared in a crawl, keyed `(share_id, link_id)`.
|
||||
/// `0` for a file that was already there before this was recorded.
|
||||
pub fn first_seen(&self) -> Result<HashMap<(String, String), i64>> {
|
||||
let mut statement = self
|
||||
.conn
|
||||
.prepare("SELECT share_id, link_id, seen_at FROM node_first_seen")?;
|
||||
let rows = statement.query_map([], |row| {
|
||||
Ok(((row.get(0)?, row.get(1)?), row.get::<_, i64>(2)?))
|
||||
})?;
|
||||
Ok(rows.collect::<std::result::Result<_, _>>()?)
|
||||
}
|
||||
|
||||
/// Drop everything a share contributed, watch positions included.
|
||||
///
|
||||
/// Unlike a recrawl — which replaces rows and deliberately leaves watch
|
||||
@@ -477,6 +530,10 @@ impl Catalog {
|
||||
"DELETE FROM offline_files WHERE share_id = ?1",
|
||||
params![share_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"DELETE FROM node_first_seen WHERE share_id = ?1",
|
||||
params![share_id],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -697,7 +754,7 @@ impl Catalog {
|
||||
let mut statement = self.conn.prepare(
|
||||
"SELECT title_key, provider, matched, fetched_at, remote_id, name, original_name,
|
||||
overview, year, kind, poster_url, backdrop_url, rating, genres, episodes, url,
|
||||
manual
|
||||
manual, details, chain
|
||||
FROM title_metadata",
|
||||
)?;
|
||||
let rows = statement.query_map([], row_to_metadata)?;
|
||||
@@ -718,7 +775,7 @@ impl Catalog {
|
||||
.query_row(
|
||||
"SELECT title_key, provider, matched, fetched_at, remote_id, name, original_name,
|
||||
overview, year, kind, poster_url, backdrop_url, rating, genres, episodes,
|
||||
url, manual
|
||||
url, manual, details, chain
|
||||
FROM title_metadata WHERE title_key = ?1",
|
||||
params![title_key],
|
||||
row_to_metadata,
|
||||
@@ -750,12 +807,22 @@ impl Catalog {
|
||||
data.map(|data| data.remote_id.as_str()),
|
||||
],
|
||||
)?;
|
||||
let details = data
|
||||
.and_then(|data| data.details.as_ref())
|
||||
.map(serde_json::to_string)
|
||||
.transpose()
|
||||
.map_err(|error| crate::error::Error::Config(error.to_string()))?;
|
||||
// `same` below is whether the row already describes this entry. When
|
||||
// it does, what enrichment added — the fanart, the chain, the record
|
||||
// that it was asked — still describes it and is kept: refreshing a
|
||||
// match's details must not cost the library its episode lists.
|
||||
self.conn.execute(
|
||||
"INSERT INTO title_metadata (
|
||||
&"INSERT INTO title_metadata (
|
||||
title_key, provider, matched, fetched_at, remote_id, name, original_name,
|
||||
overview, year, kind, poster_url, backdrop_url, rating, genres, episodes, url,
|
||||
manual
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
|
||||
manual, details
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16,
|
||||
?17, ?18)
|
||||
ON CONFLICT (title_key) DO UPDATE SET
|
||||
provider = excluded.provider,
|
||||
matched = excluded.matched,
|
||||
@@ -767,13 +834,23 @@ impl Catalog {
|
||||
year = excluded.year,
|
||||
kind = excluded.kind,
|
||||
poster_url = excluded.poster_url,
|
||||
backdrop_url = excluded.backdrop_url,
|
||||
backdrop_url = CASE WHEN same THEN COALESCE(excluded.backdrop_url,
|
||||
title_metadata.backdrop_url)
|
||||
ELSE excluded.backdrop_url END,
|
||||
rating = excluded.rating,
|
||||
genres = excluded.genres,
|
||||
episodes = excluded.episodes,
|
||||
url = excluded.url,
|
||||
manual = excluded.manual,
|
||||
enriched_at = NULL",
|
||||
details = excluded.details,
|
||||
chain = CASE WHEN same THEN title_metadata.chain END,
|
||||
enriched_at = CASE WHEN same THEN title_metadata.enriched_at END"
|
||||
.replace(
|
||||
"same",
|
||||
"(title_metadata.provider = excluded.provider
|
||||
AND title_metadata.remote_id IS excluded.remote_id
|
||||
AND excluded.matched = 1)",
|
||||
),
|
||||
params![
|
||||
record.title_key,
|
||||
record.provider.as_str(),
|
||||
@@ -792,6 +869,7 @@ impl Catalog {
|
||||
data.and_then(|data| data.episodes),
|
||||
data.and_then(|data| data.url.as_deref()),
|
||||
record.manual as i64,
|
||||
details,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
@@ -859,13 +937,14 @@ impl Catalog {
|
||||
replace_episodes(&tx, title_key, provider, fetched_at, &enrichment.episodes)?;
|
||||
tx.execute(
|
||||
"UPDATE title_metadata
|
||||
SET enriched_at = ?3, backdrop_url = COALESCE(?4, backdrop_url)
|
||||
SET enriched_at = ?3, backdrop_url = COALESCE(?4, backdrop_url), chain = ?5
|
||||
WHERE title_key = ?1 AND provider = ?2",
|
||||
params![
|
||||
title_key,
|
||||
provider.as_str(),
|
||||
fetched_at,
|
||||
enrichment.backdrop_url.as_deref(),
|
||||
enrichment.chain.join("\n"),
|
||||
],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
@@ -982,6 +1061,28 @@ fn replace_episodes(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `details` and `chain` columns, read back.
|
||||
///
|
||||
/// JSON that will not parse is treated as never fetched rather than failing
|
||||
/// the read: the next match run fetches it again, where an error here would
|
||||
/// take the whole grid down over one row.
|
||||
fn details_column(details: Option<String>, chain: Option<String>) -> Option<TitleDetails> {
|
||||
let mut details: TitleDetails = serde_json::from_str(&details?).ok()?;
|
||||
details.chain = chain
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
Some(details)
|
||||
}
|
||||
|
||||
fn unix_now() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |since| since.as_secs() as i64)
|
||||
}
|
||||
|
||||
/// `None` for a row whose provider column this build does not recognise.
|
||||
fn row_to_metadata(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<MetadataRecord>> {
|
||||
let title_key: String = row.get(0)?;
|
||||
@@ -1014,6 +1115,7 @@ fn row_to_metadata(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<MetadataR
|
||||
.collect(),
|
||||
episodes: row.get(14)?,
|
||||
url: row.get(15)?,
|
||||
details: details_column(row.get(17)?, row.get(18)?),
|
||||
})
|
||||
};
|
||||
|
||||
@@ -1298,6 +1400,7 @@ mod tests {
|
||||
genres: vec!["Action".into(), "Drama".into()],
|
||||
episodes: Some(25),
|
||||
url: Some("https://anilist.co/anime/16498".into()),
|
||||
details: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1651,7 +1754,7 @@ mod tests {
|
||||
/// Enrichment adds a backdrop when it found one and otherwise leaves the
|
||||
/// match's own alone; a new match makes the title un-enriched again.
|
||||
#[test]
|
||||
fn enrichment_keeps_the_backdrop_it_did_not_replace_and_a_new_match_resets_it() {
|
||||
fn enrichment_keeps_the_backdrop_it_did_not_replace_and_a_different_match_resets_it() {
|
||||
let mut catalog = Catalog::in_memory().expect("open");
|
||||
let record = MetadataRecord {
|
||||
title_key: "attack on titan".into(),
|
||||
@@ -1691,10 +1794,122 @@ mod tests {
|
||||
.expect("enrich again");
|
||||
assert_eq!(backdrop(&catalog).as_deref(), Some("fanart.jpg"));
|
||||
|
||||
catalog.set_metadata(&record).expect("match again");
|
||||
catalog
|
||||
.set_metadata(&MetadataRecord {
|
||||
metadata: Some(TitleMetadata {
|
||||
remote_id: "99147".into(),
|
||||
..found()
|
||||
}),
|
||||
..record
|
||||
})
|
||||
.expect("match something else");
|
||||
assert!(catalog.enrichment_ages().expect("ages").is_empty());
|
||||
}
|
||||
|
||||
/// Details round-trip, and refreshing a match's details — the same entry
|
||||
/// stored again — keeps what enrichment found for it.
|
||||
#[test]
|
||||
fn refreshing_the_same_match_keeps_its_enrichment_and_a_new_one_does_not() {
|
||||
let mut catalog = Catalog::in_memory().expect("open");
|
||||
let record = MetadataRecord {
|
||||
title_key: "mushishi".into(),
|
||||
provider: ProviderId::AniList,
|
||||
metadata: Some(found()),
|
||||
fetched_at: 1,
|
||||
manual: true,
|
||||
};
|
||||
catalog.set_metadata(&record).expect("store");
|
||||
let enrichment = Enrichment {
|
||||
episodes: vec![EpisodeMetadata {
|
||||
season: Some(1),
|
||||
number: 1,
|
||||
absolute: Some(1),
|
||||
entry_season: Some(1),
|
||||
entry_number: Some(1),
|
||||
name: Some("The Green Seat".into()),
|
||||
overview: None,
|
||||
still_url: None,
|
||||
air_date: None,
|
||||
}],
|
||||
backdrop_url: Some("fanart.jpg".into()),
|
||||
chain: vec!["457".into(), "20595".into()],
|
||||
};
|
||||
catalog
|
||||
.set_enrichment("mushishi", ProviderId::AniList, 2, &enrichment)
|
||||
.expect("enrich");
|
||||
|
||||
let refreshed = MetadataRecord {
|
||||
metadata: Some(TitleMetadata {
|
||||
details: Some(TitleDetails {
|
||||
studios: vec!["Artland".into()],
|
||||
..TitleDetails::default()
|
||||
}),
|
||||
..found()
|
||||
}),
|
||||
fetched_at: 3,
|
||||
..record.clone()
|
||||
};
|
||||
catalog.set_metadata(&refreshed).expect("refresh");
|
||||
let read = catalog.metadata("mushishi").expect("read").expect("a row");
|
||||
let data = read.metadata.expect("matched");
|
||||
assert_eq!(data.backdrop_url.as_deref(), Some("fanart.jpg"));
|
||||
let details = data.details.expect("details");
|
||||
assert_eq!(details.studios, vec!["Artland"]);
|
||||
assert_eq!(details.chain, vec!["457", "20595"]);
|
||||
assert!(
|
||||
catalog
|
||||
.enrichment_ages()
|
||||
.expect("ages")
|
||||
.contains_key("mushishi")
|
||||
);
|
||||
assert_eq!(
|
||||
catalog.all_episode_metadata().expect("read")["mushishi"].len(),
|
||||
1
|
||||
);
|
||||
|
||||
// A different entry is a different answer: nothing carries over.
|
||||
catalog
|
||||
.set_metadata(&MetadataRecord {
|
||||
metadata: Some(TitleMetadata {
|
||||
remote_id: "20526".into(),
|
||||
..found()
|
||||
}),
|
||||
..record
|
||||
})
|
||||
.expect("repin");
|
||||
let read = catalog.metadata("mushishi").expect("read").expect("a row");
|
||||
assert_eq!(read.metadata.and_then(|data| data.backdrop_url), None);
|
||||
assert!(catalog.enrichment_ages().expect("ages").is_empty());
|
||||
}
|
||||
|
||||
/// A file keeps the moment it first appeared across recrawls, and one
|
||||
/// that was there before this was recorded reads as 0.
|
||||
#[test]
|
||||
fn a_file_remembers_when_it_first_appeared() {
|
||||
let mut catalog = Catalog::in_memory().expect("open");
|
||||
catalog
|
||||
.replace_share("s", &[file("s", "a", "Show S01E01.mkv")])
|
||||
.expect("crawl");
|
||||
let first = catalog.first_seen().expect("read")[&("s".to_string(), "a".to_string())];
|
||||
assert!(first > 0);
|
||||
catalog
|
||||
.conn
|
||||
.execute("UPDATE node_first_seen SET seen_at = 5", [])
|
||||
.expect("age it");
|
||||
catalog
|
||||
.replace_share(
|
||||
"s",
|
||||
&[
|
||||
file("s", "a", "Show S01E01.mkv"),
|
||||
file("s", "b", "Show S01E02.mkv"),
|
||||
],
|
||||
)
|
||||
.expect("recrawl");
|
||||
let seen = catalog.first_seen().expect("read");
|
||||
assert_eq!(seen[&("s".to_string(), "a".to_string())], 5);
|
||||
assert!(seen[&("s".to_string(), "b".to_string())] > 5);
|
||||
}
|
||||
|
||||
/// Schema v9 repairs what AniList's first episode source wrote: its
|
||||
/// episode rows and its banners go, and the matches — hand-picked ones
|
||||
/// included — stay.
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Which titles in a library are one story.
|
||||
//!
|
||||
//! A share files a franchise however its uploader did: Made in Abyss as a
|
||||
//! series folder and three film folders, Evangelion as a series, two films and
|
||||
//! a folder of four more. The provider knows they belong together — AniList
|
||||
//! records prequels, sequels, side stories, recaps and retellings as relations
|
||||
//! — so the library can show one tile for the lot and the parts on its page.
|
||||
//!
|
||||
//! Grouping is by shared provider id, not by name. Two titles are one
|
||||
//! franchise when one names the other as related, or when both name the same
|
||||
//! entry: Mushishi's *Suzu no Shizuku* film relates to *Zoku Shou 2*, which the
|
||||
//! library does not hold as a title of its own but which the series' episode
|
||||
//! walk passed through (see [`crate::metadata::TitleDetails::chain`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::library::{Title, TitleKind};
|
||||
use crate::metadata::MetadataRecord;
|
||||
|
||||
/// One franchise: indices into the titles it was built from, in release order.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Franchise {
|
||||
pub members: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Franchise {
|
||||
/// The member that stands for the rest: the first series to air, or the
|
||||
/// first film when there is no series. What a viewer means by "Made in
|
||||
/// Abyss" is the show, not the recap film that came out after it.
|
||||
pub fn lead(&self, titles: &[&Title]) -> usize {
|
||||
self.members
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|&index| titles[index].kind == TitleKind::Series)
|
||||
.unwrap_or(self.members[0])
|
||||
}
|
||||
}
|
||||
|
||||
/// Group `titles` into franchises, every title in exactly one.
|
||||
///
|
||||
/// Titles with no match are franchises of one. The groups come back in the
|
||||
/// order of their first member in `titles`, so a sorted list stays sorted.
|
||||
pub fn group(titles: &[&Title], metadata: &HashMap<String, MetadataRecord>) -> Vec<Franchise> {
|
||||
let mut sets = DisjointSets::new(titles.len());
|
||||
// The first title to name each provider id, for later titles naming it too.
|
||||
let mut named: HashMap<(crate::metadata::ProviderId, &str), usize> = HashMap::new();
|
||||
for (index, title) in titles.iter().enumerate() {
|
||||
let Some(found) = metadata
|
||||
.get(&title.key)
|
||||
.and_then(|record| record.metadata.as_ref())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let details = found.details.as_ref();
|
||||
let ids = std::iter::once(found.remote_id.as_str())
|
||||
.chain(details.into_iter().flat_map(|details| {
|
||||
details
|
||||
.related
|
||||
.iter()
|
||||
.chain(&details.chain)
|
||||
.map(String::as_str)
|
||||
}))
|
||||
.filter(|id| !id.is_empty());
|
||||
for id in ids {
|
||||
match named.get(&(found.provider, id)) {
|
||||
Some(&other) => sets.union(index, other),
|
||||
None => {
|
||||
named.insert((found.provider, id), index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut groups: Vec<Franchise> = Vec::new();
|
||||
let mut slot: HashMap<usize, usize> = HashMap::new();
|
||||
for index in 0..titles.len() {
|
||||
let root = sets.find(index);
|
||||
match slot.get(&root) {
|
||||
Some(&at) => groups[at].members.push(index),
|
||||
None => {
|
||||
slot.insert(root, groups.len());
|
||||
groups.push(Franchise {
|
||||
members: vec![index],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for franchise in &mut groups {
|
||||
franchise
|
||||
.members
|
||||
.sort_by_cached_key(|&index| release_key(titles[index], metadata));
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// What release order sorts on: the provider's start date, else the year the
|
||||
/// files state, else last.
|
||||
pub fn release_key(title: &Title, metadata: &HashMap<String, MetadataRecord>) -> String {
|
||||
let found = metadata
|
||||
.get(&title.key)
|
||||
.and_then(|record| record.metadata.as_ref());
|
||||
found
|
||||
.and_then(|found| found.details.as_ref())
|
||||
.and_then(|details| details.start_date.clone())
|
||||
.or_else(|| {
|
||||
found
|
||||
.and_then(|found| found.year)
|
||||
.map(|year| year.to_string())
|
||||
})
|
||||
.or_else(|| title.year.map(|year| year.to_string()))
|
||||
// `~` sorts after every digit: undated goes last.
|
||||
.unwrap_or_else(|| "~".to_string())
|
||||
}
|
||||
|
||||
struct DisjointSets {
|
||||
parent: Vec<usize>,
|
||||
}
|
||||
|
||||
impl DisjointSets {
|
||||
fn new(size: usize) -> Self {
|
||||
Self {
|
||||
parent: (0..size).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn find(&mut self, mut index: usize) -> usize {
|
||||
while self.parent[index] != index {
|
||||
self.parent[index] = self.parent[self.parent[index]];
|
||||
index = self.parent[index];
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
fn union(&mut self, left: usize, right: usize) {
|
||||
let (left, right) = (self.find(left), self.find(right));
|
||||
if left != right {
|
||||
// The earlier title stays the root, which keeps `group` stable.
|
||||
let (root, child) = (left.min(right), left.max(right));
|
||||
self.parent[child] = root;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::metadata::{ProviderId, TitleDetails, TitleMetadata};
|
||||
|
||||
fn title(key: &str, kind: TitleKind) -> Title {
|
||||
Title {
|
||||
key: key.into(),
|
||||
name: key.into(),
|
||||
year: None,
|
||||
kind,
|
||||
seasons: Vec::new(),
|
||||
share_ids: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn matched(
|
||||
key: &str,
|
||||
id: &str,
|
||||
start: &str,
|
||||
related: &[&str],
|
||||
chain: &[&str],
|
||||
) -> MetadataRecord {
|
||||
MetadataRecord {
|
||||
title_key: key.into(),
|
||||
provider: ProviderId::AniList,
|
||||
metadata: Some(TitleMetadata {
|
||||
provider: ProviderId::AniList,
|
||||
remote_id: id.into(),
|
||||
name: key.into(),
|
||||
original_name: None,
|
||||
overview: None,
|
||||
year: None,
|
||||
kind: TitleKind::Series,
|
||||
poster_url: None,
|
||||
backdrop_url: None,
|
||||
rating: None,
|
||||
genres: Vec::new(),
|
||||
episodes: None,
|
||||
url: None,
|
||||
details: Some(TitleDetails {
|
||||
start_date: Some(start.into()),
|
||||
related: related.iter().map(|id| id.to_string()).collect(),
|
||||
chain: chain.iter().map(|id| id.to_string()).collect(),
|
||||
..TitleDetails::default()
|
||||
}),
|
||||
}),
|
||||
fetched_at: 0,
|
||||
manual: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn keys(groups: &[Franchise], titles: &[&Title]) -> Vec<Vec<String>> {
|
||||
groups
|
||||
.iter()
|
||||
.map(|group| {
|
||||
group
|
||||
.members
|
||||
.iter()
|
||||
.map(|&index| titles[index].key.clone())
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Made in Abyss: the films name the series, the series names the films.
|
||||
/// Paprika names nothing in the library and stays alone.
|
||||
#[test]
|
||||
fn titles_that_name_each_other_are_one_franchise_in_release_order() {
|
||||
let owned = [
|
||||
title("dawn of the deep soul", TitleKind::Film),
|
||||
title("made in abyss", TitleKind::Series),
|
||||
title("paprika", TitleKind::Film),
|
||||
];
|
||||
let titles: Vec<&Title> = owned.iter().collect();
|
||||
let metadata = HashMap::from([
|
||||
(
|
||||
"dawn of the deep soul".to_string(),
|
||||
matched(
|
||||
"dawn of the deep soul",
|
||||
"100643",
|
||||
"2020-01-17",
|
||||
&["97986"],
|
||||
&[],
|
||||
),
|
||||
),
|
||||
(
|
||||
"made in abyss".to_string(),
|
||||
matched("made in abyss", "97986", "2017-07-07", &["100643"], &[]),
|
||||
),
|
||||
(
|
||||
"paprika".to_string(),
|
||||
matched("paprika", "1943", "2006-11-25", &[], &[]),
|
||||
),
|
||||
]);
|
||||
|
||||
let groups = group(&titles, &metadata);
|
||||
assert_eq!(
|
||||
keys(&groups, &titles),
|
||||
vec![
|
||||
vec!["made in abyss", "dawn of the deep soul"],
|
||||
vec!["paprika"]
|
||||
]
|
||||
);
|
||||
assert_eq!(titles[groups[0].lead(&titles)].key, "made in abyss");
|
||||
}
|
||||
|
||||
/// Mushishi: the special names an entry the series only reached by
|
||||
/// walking its sequels for episodes. That is still the same story.
|
||||
#[test]
|
||||
fn an_entry_the_series_walked_through_joins_what_names_it() {
|
||||
let owned = [
|
||||
title("mushishi", TitleKind::Series),
|
||||
title("suzu no shizuku", TitleKind::Film),
|
||||
];
|
||||
let titles: Vec<&Title> = owned.iter().collect();
|
||||
let metadata = HashMap::from([
|
||||
(
|
||||
"mushishi".to_string(),
|
||||
matched(
|
||||
"mushishi",
|
||||
"457",
|
||||
"2005-10-23",
|
||||
&["20526"],
|
||||
&["457", "20595", "20751"],
|
||||
),
|
||||
),
|
||||
(
|
||||
"suzu no shizuku".to_string(),
|
||||
matched("suzu no shizuku", "21008", "2015-05-16", &["20751"], &[]),
|
||||
),
|
||||
]);
|
||||
assert_eq!(group(&titles, &metadata).len(), 1);
|
||||
}
|
||||
|
||||
/// Nothing matched, nothing to group by — and two unmatched titles are
|
||||
/// not one franchise because they share an empty id.
|
||||
#[test]
|
||||
fn unmatched_titles_stand_alone() {
|
||||
let owned = [
|
||||
title("game of thrones", TitleKind::Series),
|
||||
title("something else", TitleKind::Series),
|
||||
];
|
||||
let titles: Vec<&Title> = owned.iter().collect();
|
||||
assert_eq!(group(&titles, &HashMap::new()).len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,13 @@ pub mod catalog;
|
||||
pub mod chapters;
|
||||
pub mod config;
|
||||
pub mod error;
|
||||
pub mod franchise;
|
||||
pub mod library;
|
||||
pub mod metadata;
|
||||
pub mod naming;
|
||||
pub mod prefs;
|
||||
pub mod shares;
|
||||
pub mod shelves;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
#[cfg(not(target_os = "android"))]
|
||||
|
||||
@@ -389,6 +389,27 @@ impl Library {
|
||||
played
|
||||
}
|
||||
|
||||
/// When each title last gained a file, Unix seconds — the newest
|
||||
/// [`crate::catalog::Catalog::first_seen`] among its episodes. `0` for a
|
||||
/// title whose files were all there before that was recorded.
|
||||
pub fn added_at(&self, first_seen: &HashMap<(String, String), i64>) -> HashMap<String, i64> {
|
||||
self.titles
|
||||
.iter()
|
||||
.map(|title| {
|
||||
let newest = title
|
||||
.episodes()
|
||||
.filter_map(|episode| {
|
||||
first_seen
|
||||
.get(&(episode.node.share_id.clone(), episode.node.link_id.clone()))
|
||||
})
|
||||
.copied()
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
(title.key.clone(), newest)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Substring match over the display name and every filename under it, so
|
||||
/// searching for a release group or an episode name finds its title.
|
||||
pub fn search(&self, query: &str) -> Vec<&Title> {
|
||||
@@ -438,7 +459,7 @@ pub fn title_key(title: &str) -> String {
|
||||
|
||||
/// Sort key for the shelf: case-insensitive, and a leading article ignored, so
|
||||
/// `The Expanse` files under E where a viewer looks for it.
|
||||
fn sort_name(name: &str) -> String {
|
||||
pub fn sort_name(name: &str) -> String {
|
||||
let lower = name.to_lowercase();
|
||||
for article in ["the ", "a ", "an "] {
|
||||
if let Some(rest) = lower.strip_prefix(article) {
|
||||
|
||||
@@ -31,7 +31,7 @@ use crate::library::TitleKind;
|
||||
/// Stored as a string in the catalog rather than an integer: a row whose
|
||||
/// provider this build does not recognise should read as "some other provider",
|
||||
/// which is a re-match, not a parse failure.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProviderId {
|
||||
/// AniList. Anime only, no API key, no account.
|
||||
@@ -112,6 +112,154 @@ pub struct TitleMetadata {
|
||||
pub episodes: Option<u32>,
|
||||
/// The title's page, for a viewer who wants the rest of it.
|
||||
pub url: Option<String>,
|
||||
/// Everything else the provider said: what the library is sorted, grouped
|
||||
/// and shelved by. `None` on a record stored before there was any of it,
|
||||
/// which is what tells a match run to fetch it — see
|
||||
/// `pstr_meta::service::plan`.
|
||||
pub details: Option<TitleDetails>,
|
||||
}
|
||||
|
||||
/// What a provider says about a title beyond what a tile draws.
|
||||
///
|
||||
/// Stored whole as one JSON column rather than a column each: nothing here is
|
||||
/// ever queried by SQLite, every field is optional at every provider, and a
|
||||
/// field added later has to read as absent from a row written before it, not
|
||||
/// fail the row. TMDB fills none of it yet.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct TitleDetails {
|
||||
/// The title in romaji — `Sousou no Frieren` — for a viewer who would
|
||||
/// rather see that than the English one.
|
||||
pub romaji: Option<String>,
|
||||
/// AniList's ultra-wide banner, around 4.75:1. Never drawn into a 16:9
|
||||
/// tile — it is what a strip that shape falls back to when there is no
|
||||
/// fanart.
|
||||
pub banner_url: Option<String>,
|
||||
/// As the provider writes it: `TV`, `TV_SHORT`, `MOVIE`, `SPECIAL`, `OVA`,
|
||||
/// `ONA`, `MUSIC`. [`TitleDetails::format_label`] is what is shown.
|
||||
pub format: Option<String>,
|
||||
/// The broadcast season: `WINTER`, `SPRING`, `SUMMER` or `FALL`.
|
||||
pub season: Option<String>,
|
||||
/// When it first aired, `YYYY-MM-DD` with whatever parts are known —
|
||||
/// `2013-04`, `2013`. Sorts as text, which is why it is kept that way.
|
||||
pub start_date: Option<String>,
|
||||
/// The main animation studios.
|
||||
pub studios: Vec<String>,
|
||||
pub directors: Vec<String>,
|
||||
/// The provider's descriptive tags, most relevant first, spoilers left out.
|
||||
pub tags: Vec<String>,
|
||||
/// How many people follow it at the provider. Only ever compared with
|
||||
/// other titles from the same provider.
|
||||
pub popularity: Option<u32>,
|
||||
/// `FINISHED`, `RELEASING`, `NOT_YET_RELEASED`, `CANCELLED` or `HIATUS`.
|
||||
pub status: Option<String>,
|
||||
/// The next episode to air, and when — Unix seconds. As of when the
|
||||
/// answer was fetched, so a time in the past means nothing.
|
||||
pub next_episode: Option<u32>,
|
||||
pub next_airing_at: Option<i64>,
|
||||
/// The provider ids of entries in the same story — prequels, sequels,
|
||||
/// side stories, recaps, retellings. What the library groups a franchise
|
||||
/// by; see `crate::franchise`.
|
||||
pub related: Vec<String>,
|
||||
/// The entries enrichment walked through to find the title's episodes —
|
||||
/// its own sequels, by provider id. Stored apart from the rest, because
|
||||
/// it is enrichment's answer rather than the match's.
|
||||
#[serde(skip)]
|
||||
pub chain: Vec<String>,
|
||||
}
|
||||
|
||||
impl TitleDetails {
|
||||
/// `TV` → `TV`, `MOVIE` → `Film`, `TV_SHORT` → `TV short`.
|
||||
pub fn format_label(&self) -> Option<&'static str> {
|
||||
Some(match self.format.as_deref()? {
|
||||
"TV" => "TV",
|
||||
"TV_SHORT" => "TV short",
|
||||
"MOVIE" => "Film",
|
||||
"SPECIAL" => "Special",
|
||||
"OVA" => "OVA",
|
||||
"ONA" => "ONA",
|
||||
"MUSIC" => "Music video",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Spring 2013`, or just the year.
|
||||
pub fn season_label(&self) -> Option<String> {
|
||||
let year = self.start_date.as_deref()?.get(..4)?;
|
||||
let season = match self.season.as_deref() {
|
||||
Some("WINTER") => "Winter",
|
||||
Some("SPRING") => "Spring",
|
||||
Some("SUMMER") => "Summer",
|
||||
Some("FALL") => "Fall",
|
||||
_ => return Some(year.to_string()),
|
||||
};
|
||||
Some(format!("{season} {year}"))
|
||||
}
|
||||
|
||||
/// Whether it is still airing.
|
||||
pub fn is_airing(&self) -> bool {
|
||||
self.status.as_deref() == Some("RELEASING")
|
||||
}
|
||||
|
||||
/// The next episode and when it airs, when that is still after `now`.
|
||||
pub fn next_airing(&self, now: i64) -> Option<(u32, i64)> {
|
||||
let at = self.next_airing_at.filter(|at| *at > now)?;
|
||||
Some((self.next_episode?, at))
|
||||
}
|
||||
}
|
||||
|
||||
impl TitleMetadata {
|
||||
/// Ultra-wide art: the backdrop where there is one, else the banner.
|
||||
///
|
||||
/// For the library's hero and the title page's band, which are much wider
|
||||
/// than 16:9 — a backdrop cropped to them loses some sky, a banner fits
|
||||
/// them as drawn.
|
||||
pub fn wide_art(&self) -> Option<&str> {
|
||||
self.backdrop_url.as_deref().or_else(|| {
|
||||
self.details
|
||||
.as_ref()
|
||||
.and_then(|details| details.banner_url.as_deref())
|
||||
})
|
||||
}
|
||||
|
||||
/// The name to show, as the viewer asked for it.
|
||||
pub fn display_name(&self, names: TitleNames) -> Option<&str> {
|
||||
match names {
|
||||
TitleNames::Library => None,
|
||||
TitleNames::English => Some(&self.name),
|
||||
TitleNames::Romaji => self
|
||||
.details
|
||||
.as_ref()
|
||||
.and_then(|details| details.romaji.as_deref())
|
||||
.or(Some(&self.name)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which name a title goes by in the library.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum TitleNames {
|
||||
/// The folder's — what the share calls it. The default, because it is the
|
||||
/// one name that is there whether or not anything matched.
|
||||
#[default]
|
||||
Library,
|
||||
/// The provider's English title, where it has one.
|
||||
English,
|
||||
/// The provider's romaji title.
|
||||
Romaji,
|
||||
}
|
||||
|
||||
impl TitleNames {
|
||||
pub const ALL: [Self; 3] = [Self::Library, Self::English, Self::Romaji];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Library => "As in the share",
|
||||
Self::English => "English",
|
||||
Self::Romaji => "Romaji",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TitleMetadata {
|
||||
@@ -181,6 +329,9 @@ pub struct Enrichment {
|
||||
/// A 16:9 picture of the whole title, when one was found. `None` leaves
|
||||
/// whatever backdrop the match already had.
|
||||
pub backdrop_url: Option<String>,
|
||||
/// Every provider entry the episodes were taken from, the match's own
|
||||
/// included. See [`TitleDetails::chain`].
|
||||
pub chain: Vec<String>,
|
||||
}
|
||||
|
||||
/// Every episode a provider listed for one title, ready to look up.
|
||||
@@ -401,6 +552,7 @@ mod tests {
|
||||
genres: Vec::new(),
|
||||
episodes: Some(26),
|
||||
url: None,
|
||||
details: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Rows of titles that share something, for the top of the library.
|
||||
//!
|
||||
//! A grid sorted one way answers one question. Shelves answer the ones a
|
||||
//! viewer did not think to ask: what is still airing, what else that studio
|
||||
//! made, the director whose four films happen to be in the share. They are
|
||||
//! picked from what the provider said, and only where there is enough of
|
||||
//! something to be worth a row — three titles from one studio is a shelf, one
|
||||
//! is a fact on its page.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use crate::library::Title;
|
||||
use crate::metadata::MetadataRecord;
|
||||
|
||||
/// How many franchises a person or studio needs before it earns a row.
|
||||
///
|
||||
/// Franchises, not titles: Made in Abyss and its three films are four titles
|
||||
/// with one director, and a "Directed by" row holding nothing but them says
|
||||
/// what the franchise's own tile already does.
|
||||
const MIN_TITLES: usize = 3;
|
||||
|
||||
/// A genre on more than this share of the matched titles says nothing: an
|
||||
/// "Action" row in an anime library is half the library again — which is what
|
||||
/// it was, at 0.6, in the library this was tuned on.
|
||||
const MAX_GENRE_SHARE: f32 = 0.4;
|
||||
|
||||
/// One row: a heading, and the keys of the titles under it, in library order.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Shelf {
|
||||
pub label: String,
|
||||
pub keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// Up to `limit` shelves for `titles`, most specific first: what is airing,
|
||||
/// then directors, studios and genres, each by how many titles it holds.
|
||||
///
|
||||
/// Two shelves holding exactly the same titles are one shelf — the first,
|
||||
/// which is the more specific.
|
||||
pub fn pick(
|
||||
titles: &[Title],
|
||||
metadata: &HashMap<String, MetadataRecord>,
|
||||
limit: usize,
|
||||
) -> Vec<Shelf> {
|
||||
let mut airing = Vec::new();
|
||||
let mut directors: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
let mut studios: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
let mut genres: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
let mut matched = 0usize;
|
||||
let refs: Vec<&Title> = titles.iter().collect();
|
||||
let franchise_of: HashMap<&str, usize> = crate::franchise::group(&refs, metadata)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.flat_map(|(at, franchise)| {
|
||||
franchise
|
||||
.members
|
||||
.into_iter()
|
||||
.map(move |member| (titles[member].key.as_str(), at))
|
||||
})
|
||||
.collect();
|
||||
let franchises = |keys: &[String]| {
|
||||
keys.iter()
|
||||
.filter_map(|key| franchise_of.get(key.as_str()))
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.len()
|
||||
};
|
||||
|
||||
for title in titles {
|
||||
let Some(found) = metadata
|
||||
.get(&title.key)
|
||||
.and_then(|record| record.metadata.as_ref())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
matched += 1;
|
||||
for genre in &found.genres {
|
||||
genres.entry(genre).or_default().push(title.key.clone());
|
||||
}
|
||||
let Some(details) = &found.details else {
|
||||
continue;
|
||||
};
|
||||
if details.is_airing() {
|
||||
airing.push(title.key.clone());
|
||||
}
|
||||
for director in &details.directors {
|
||||
directors
|
||||
.entry(director)
|
||||
.or_default()
|
||||
.push(title.key.clone());
|
||||
}
|
||||
for studio in &details.studios {
|
||||
studios.entry(studio).or_default().push(title.key.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let ranked = |groups: BTreeMap<&str, Vec<String>>, label: &dyn Fn(&str) -> String| {
|
||||
let mut rows: Vec<Shelf> = groups
|
||||
.into_iter()
|
||||
.filter(|(_, keys)| franchises(keys) >= MIN_TITLES)
|
||||
.map(|(name, keys)| Shelf {
|
||||
label: label(name),
|
||||
keys,
|
||||
})
|
||||
.collect();
|
||||
// Stable, so equal counts keep their alphabetical order.
|
||||
rows.sort_by_key(|shelf| std::cmp::Reverse(shelf.keys.len()));
|
||||
rows
|
||||
};
|
||||
|
||||
let genre_ceiling = (matched as f32 * MAX_GENRE_SHARE).floor() as usize;
|
||||
let genres: BTreeMap<&str, Vec<String>> = genres
|
||||
.into_iter()
|
||||
.filter(|(_, keys)| keys.len() <= genre_ceiling)
|
||||
.collect();
|
||||
|
||||
let mut shelves = Vec::new();
|
||||
if !airing.is_empty() {
|
||||
shelves.push(Shelf {
|
||||
label: "Airing now".into(),
|
||||
keys: airing,
|
||||
});
|
||||
}
|
||||
shelves.extend(ranked(directors, &|name| format!("Directed by {name}")));
|
||||
shelves.extend(ranked(studios, &|name| format!("From {name}")));
|
||||
shelves.extend(ranked(genres, &|name| name.to_string()));
|
||||
|
||||
let mut picked: Vec<Shelf> = Vec::new();
|
||||
for shelf in shelves {
|
||||
if picked.len() == limit {
|
||||
break;
|
||||
}
|
||||
if !picked.iter().any(|other| other.keys == shelf.keys) {
|
||||
picked.push(shelf);
|
||||
}
|
||||
}
|
||||
picked
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::library::TitleKind;
|
||||
use crate::metadata::{ProviderId, TitleDetails, TitleMetadata};
|
||||
|
||||
fn title(key: &str) -> Title {
|
||||
Title {
|
||||
key: key.into(),
|
||||
name: key.into(),
|
||||
year: None,
|
||||
kind: TitleKind::Film,
|
||||
seasons: Vec::new(),
|
||||
share_ids: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record(key: &str, genres: &[&str], details: TitleDetails) -> (String, MetadataRecord) {
|
||||
(
|
||||
key.to_string(),
|
||||
MetadataRecord {
|
||||
title_key: key.into(),
|
||||
provider: ProviderId::AniList,
|
||||
metadata: Some(TitleMetadata {
|
||||
provider: ProviderId::AniList,
|
||||
remote_id: key.into(),
|
||||
name: key.into(),
|
||||
original_name: None,
|
||||
overview: None,
|
||||
year: None,
|
||||
kind: TitleKind::Film,
|
||||
poster_url: None,
|
||||
backdrop_url: None,
|
||||
rating: None,
|
||||
genres: genres.iter().map(|genre| genre.to_string()).collect(),
|
||||
episodes: None,
|
||||
url: None,
|
||||
details: Some(details),
|
||||
}),
|
||||
fetched_at: 0,
|
||||
manual: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn kon(studio: &str) -> TitleDetails {
|
||||
TitleDetails {
|
||||
directors: vec!["Satoshi Kon".into()],
|
||||
studios: vec![studio.into()],
|
||||
..TitleDetails::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The case this exists for: four Satoshi Kon films in one share.
|
||||
#[test]
|
||||
fn a_director_with_enough_titles_gets_a_shelf_ahead_of_a_studio() {
|
||||
let titles: Vec<Title> = [
|
||||
"perfect blue",
|
||||
"millennium actress",
|
||||
"tokyo godfathers",
|
||||
"paprika",
|
||||
]
|
||||
.map(title)
|
||||
.to_vec();
|
||||
let metadata = HashMap::from([
|
||||
record("perfect blue", &["Drama"], kon("Madhouse")),
|
||||
record("millennium actress", &["Drama"], kon("Madhouse")),
|
||||
record("tokyo godfathers", &["Drama"], kon("Madhouse")),
|
||||
record("paprika", &["Sci-Fi"], kon("Madhouse")),
|
||||
]);
|
||||
let shelves = pick(&titles, &metadata, 5);
|
||||
assert_eq!(shelves[0].label, "Directed by Satoshi Kon");
|
||||
assert_eq!(shelves[0].keys.len(), 4);
|
||||
// Madhouse holds exactly the same four, so it is not a second row.
|
||||
assert!(!shelves.iter().any(|shelf| shelf.label == "From Madhouse"));
|
||||
// Drama is three of four: past the share a genre may cover.
|
||||
assert!(!shelves.iter().any(|shelf| shelf.label == "Drama"));
|
||||
}
|
||||
|
||||
/// Made in Abyss: four titles, one director, one story. Not a shelf.
|
||||
#[test]
|
||||
fn one_franchise_is_not_a_shelf_however_many_titles_it_has() {
|
||||
let titles: Vec<Title> = ["abyss", "film one", "film two", "film three"]
|
||||
.map(title)
|
||||
.to_vec();
|
||||
let kojima = |related: &[&str]| TitleDetails {
|
||||
directors: vec!["Masayuki Kojima".into()],
|
||||
related: related.iter().map(|id| id.to_string()).collect(),
|
||||
..TitleDetails::default()
|
||||
};
|
||||
let metadata = HashMap::from([
|
||||
record(
|
||||
"abyss",
|
||||
&[],
|
||||
kojima(&["film one", "film two", "film three"]),
|
||||
),
|
||||
record("film one", &[], kojima(&["abyss"])),
|
||||
record("film two", &[], kojima(&["abyss"])),
|
||||
record("film three", &[], kojima(&["abyss"])),
|
||||
]);
|
||||
assert!(pick(&titles, &metadata, 5).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_airing_comes_first_and_too_few_titles_make_no_shelf() {
|
||||
let titles: Vec<Title> = ["a", "b"].map(title).to_vec();
|
||||
let metadata = HashMap::from([
|
||||
record(
|
||||
"a",
|
||||
&[],
|
||||
TitleDetails {
|
||||
status: Some("RELEASING".into()),
|
||||
studios: vec!["MAPPA".into()],
|
||||
..TitleDetails::default()
|
||||
},
|
||||
),
|
||||
record("b", &[], TitleDetails::default()),
|
||||
]);
|
||||
let shelves = pick(&titles, &metadata, 5);
|
||||
assert_eq!(shelves.len(), 1);
|
||||
assert_eq!(shelves[0].label, "Airing now");
|
||||
assert_eq!(shelves[0].keys, vec!["a"]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user