Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion src/category/step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ fn has_row(conn: &Connection, id: i64) -> rusqlite::Result<bool> {
Ok(found.is_some())
}

/// The kind and subcategories of release `id`'s spot, when it was saved from one (`spotnet::store::SPOTS`).
fn spot_of(conn: &Connection, id: i64) -> rusqlite::Result<Option<(crate::spotnet::Kind, crate::spotnet::Subcats)>> {
let row: Option<(String, String)> = conn
.prepare_cached("select kind, coalesce(subcats, '') from spots where release_id = ?1")?
.query_row([id], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?;
Ok(row.and_then(|(kind, subcats)| {
let kind = match kind.as_str() {
"movie" => crate::spotnet::Kind::Movie,
"series" => crate::spotnet::Kind::Series,
_ => return None,
};
Some((kind, crate::spotnet::header::subcats(&subcats)))
}))
}

/// The category step's id, for a rerun of it alone.
pub const STEP: StepId = StepId(24);

pub struct CategoryStep {
options: RwLock<Options>,
}
Expand All @@ -50,7 +69,7 @@ impl Default for CategoryStep {

impl Step for CategoryStep {
fn id(&self) -> StepId {
StepId(24)
STEP
}
fn name(&self) -> &'static str {
"category"
Expand All @@ -72,6 +91,15 @@ impl Step for CategoryStep {
fn run(&self, ctx: &mut StepCtx<'_>) -> Result<Outcome, StepError> {
let id = ctx.release().id;
let mut d = classify_release(ctx.release(), &self.options.read().unwrap());
// a release saved from a spot: the spotter said movie or series, which wins over a pick elsewhere
if let Some((kind, subcats)) = spot_of(ctx.conn(), id).map_err(|e| StepError::Retry(e.to_string()))? {
let release = ctx.release();
let name = release.display_name.as_deref().unwrap_or(&release.name);
let picked = if stores(&d) { d.category } else { 0 };
if let Some(category) = crate::spotnet::category::hint(kind, &subcats, name, picked) {
d = super::Decision { category, confidence: 900, rule: "spot_kind" };
}
}
// there is no PC category: a PC match is junk, unless it has video, which then goes uncategorized
if crate::junk::is_pc(d.category) {
let files = ctx.files().map_err(|e| StepError::Retry(e.to_string()))?;
Expand Down Expand Up @@ -102,3 +130,24 @@ impl Step for CategoryStep {
})
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn reads_a_releases_spot() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(crate::spotnet::store::SPOTS.create).unwrap();
conn.execute(
"insert into spots (release_id, message_id, kind, title, subcats) values (8, 'a', 'series', 'A', 'a9|d18|z1|'), (16, 'b', 'book', 'B', '')",
[],
)
.unwrap();
let (kind, subcats) = spot_of(&conn, 8).unwrap().unwrap();
assert_eq!(kind, crate::spotnet::Kind::Series);
assert_eq!(subcats.d, [18]);
assert!(spot_of(&conn, 16).unwrap().is_none(), "not a kind Atlas takes");
assert!(spot_of(&conn, 24).unwrap().is_none());
}
}
143 changes: 143 additions & 0 deletions src/spotnet/category.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
//! A spot's kind as a hint for its release's category. The spotter says whether a post is a movie or a series,
//! which the name alone often doesn't: `Hard labeur (1985)` names no episode, a Moto3 qualifying session reads like
//! a movie. When the category step's pick (`category::classify`) isn't under the spot's root, the spot wins: its
//! kind gives the root, and the name's resolution or the spot's format gives the leaf.

use super::{Kind, Subcats};

/// The genre (`d`) Spotweb calls Sport.
const SPORT: u16 = 18;

/// How sharp a spot's video is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Quality {
Uhd,
Hd,
Sd,
BluRay,
Dvd,
ThreeD,
}

/// The category release `name` gets from its spot, or None to keep `classified`, the category step's pick (0 for
/// none), when it is already under the spot's root.
pub fn hint(kind: Kind, subcats: &Subcats, name: &str, classified: i64) -> Option<i64> {
let root = match kind {
Kind::Movie => 2000,
Kind::Series => 5000,
};
if crate::category::root_of(classified) == root {
return None;
}
if kind == Kind::Series && subcats.d.contains(&SPORT) {
return Some(5060);
}
let quality = from_name(name).or_else(|| from_format(&subcats.a));
Some(match (kind, quality) {
(Kind::Movie, Some(Quality::Uhd)) => 2045,
(Kind::Movie, Some(Quality::Hd)) => 2040,
(Kind::Movie, Some(Quality::Sd)) => 2030,
(Kind::Movie, Some(Quality::BluRay)) => 2060,
(Kind::Movie, Some(Quality::Dvd)) => 2070,
(Kind::Movie, Some(Quality::ThreeD)) => 2050,
(Kind::Movie, None) => 2999,
(Kind::Series, Some(Quality::Uhd)) => 5045,
(Kind::Series, Some(Quality::Hd | Quality::BluRay | Quality::ThreeD)) => 5040,
(Kind::Series, Some(Quality::Sd | Quality::Dvd)) => 5030,
(Kind::Series, None) => 5999,
})
}

/// The resolution a release name states, when it states one.
fn from_name(name: &str) -> Option<Quality> {
let lower = name.to_ascii_lowercase();
let words: Vec<&str> = lower.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).collect();
let has = |list: &[&str]| words.iter().any(|w| list.contains(w));
if has(&["2160p", "4k", "uhd"]) {
Some(Quality::Uhd)
} else if has(&["1080p", "1080i", "720p"]) {
Some(Quality::Hd)
} else if has(&["480p", "576p", "xvid", "divx", "dvdrip"]) {
Some(Quality::Sd)
} else {
None
}
}

/// What the spot's format (`a`, `names::FORMAT`) says: the sharpest one it lists.
fn from_format(formats: &[u16]) -> Option<Quality> {
let of = |a: u16| match a {
15 => Some(Quality::Uhd),
14 => Some(Quality::ThreeD),
6 => Some(Quality::BluRay),
4 | 7 | 8 | 9 => Some(Quality::Hd),
3 | 10 => Some(Quality::Dvd),
0..=2 => Some(Quality::Sd),
_ => None,
};
let rank = |q: &Quality| match q {
Quality::Uhd => 0,
Quality::ThreeD => 1,
Quality::BluRay => 2,
Quality::Hd => 3,
Quality::Dvd => 4,
Quality::Sd => 5,
};
formats.iter().filter_map(|a| of(*a)).min_by_key(rank)
}

#[cfg(test)]
mod tests {
use super::*;
use crate::spotnet::header::subcats;

#[test]
fn a_pick_under_the_spots_root_stays() {
let s = subcats("a9|b12|c6|z0|");
assert_eq!(hint(Kind::Movie, &s, "Toy.Story.5.2026.DUTCH.1080p.WEB.h264-TRIPEL", 2010), None);
assert_eq!(hint(Kind::Series, &subcats("a9|b4|z1|"), "Show S01E01 1080p", 5040), None);
}

#[test]
fn the_spots_kind_gives_the_root() {
// releases on prod the category step put elsewhere, or nowhere
let movie = subcats("a9|b12|c6|c10|d21|z0|");
assert_eq!(hint(Kind::Movie, &movie, "Landship.2026.1080p.x264.AAC5.1-GP-M-NLsubs", 0), Some(2040));
assert_eq!(
hint(Kind::Movie, &subcats("a15|b3|c6|d0|z0|"), "MCU 05. Captain America 2160p UHD", 3020),
Some(2045)
);
assert_eq!(
hint(Kind::Movie, &subcats("a9|b12|d7|d21|z0|"), "The Hunley (1999) - 1080p TVrip FHD", 5040),
Some(2040)
);
assert_eq!(
hint(Kind::Movie, &subcats("a4|b3|d0|z0|"), "Dirty Deeds (2002) - AV1 - Topaz Enhanced DVD", 0),
Some(2040)
);
let series = subcats("a9|b4|b3|c0|d11|d7|z1|");
assert_eq!(hint(Kind::Series, &series, "Hard labeur (1985)", 0), Some(5040));
let flemish = subcats("a9|b4|b11|c6|d11|z1|");
assert_eq!(
hint(Kind::Series, &flemish, "Ze.Zeggen.Dat.Terug.Naar.School.2026.FLEMISH.1080p.WEB.h264-TRIPEL", 2010),
Some(5040)
);
assert_eq!(hint(Kind::Series, &subcats("a9|b4|c1|d11|d7|z1|"), "Morfeusz 2026", 8010), Some(5040));
}

#[test]
fn sport_and_the_leaves() {
let sport = subcats("a9|b4|b11|c0|c10|d11|d18|z1|");
assert_eq!(
hint(Kind::Series, &sport, "Moto3.2026.Qatar.Qualifying.Two.1080p.WEB.h264-BILLIE", 2040),
Some(5060)
);
assert_eq!(hint(Kind::Movie, &subcats("a6|z0|"), "Landship.2026.COMPLETE.BLURAY-CBGB", 0), Some(2060));
assert_eq!(hint(Kind::Movie, &subcats("a3|z0|"), "Old film", 0), Some(2070));
assert_eq!(hint(Kind::Movie, &subcats("a14|a9|z0|"), "Avatar 3D", 0), Some(2050));
assert_eq!(hint(Kind::Series, &subcats("a10|z1|"), "Show box", 0), Some(5030));
assert_eq!(hint(Kind::Movie, &subcats("a0|z0|"), "Old film 2160p", 0), Some(2045), "the name first");
assert_eq!(hint(Kind::Movie, &subcats("z0|"), "No idea", 0), Some(2999));
assert_eq!(hint(Kind::Series, &subcats(""), "No idea", 0), Some(5999));
}
}
7 changes: 7 additions & 0 deletions src/spotnet/ingest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ pub async fn run(pool: Arc<Pool>, db: Db, config: SpotsConfig, stopping: impl Fn
eprintln!("spots: {e:#}");
return;
}
for shard in 0..crate::store::SHARDS {
match on_shard(&db, shard, store::recategorize_all).await {
Ok(0) => {}
Ok(n) => println!("spots: {n} releases of shard {shard} queued for their category, with their spot's kind"),
Err(e) => eprintln!("spots: queueing shard {shard}'s spot releases for their category: {e:#}"),
}
}
while !stopping() {
match pass(&pool, &db, &config, &stopping).await {
Ok(p) if p.noted + p.saved + p.skipped + p.retry + p.pending > 0 => println!(
Expand Down
1 change: 1 addition & 0 deletions src/spotnet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! spot's signatures.

pub mod binary;
pub mod category;
pub mod comments;
pub mod full;
pub mod header;
Expand Down
76 changes: 70 additions & 6 deletions src/spotnet/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ pub fn placement(
/// newest first, so an older copy of a spot comes after the edit that replaced it.
fn put(conn: &Connection, release_id: i64, row: &SpotRow) -> Result<()> {
let spot = &row.spot;
conn.execute(
let changed = conn.execute(
"insert into spots (release_id, message_id, kind, title, poster, tag, spotter_id, category,
subcats, size, imdb_id, created, nzb_key, xml) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
on conflict(release_id) do update set message_id = excluded.message_id, kind = excluded.kind,
Expand All @@ -456,9 +456,35 @@ fn put(conn: &Connection, release_id: i64, row: &SpotRow) -> Result<()> {
row.xml,
],
)?;
// the spot's kind is a hint for the release's category (`spotnet::category`): the step looks again
if changed > 0 {
recategorize(conn, release_id)?;
}
Ok(())
}

/// Queues release `id` for the category step again, on its shard's writer.
fn recategorize(conn: &Connection, id: i64) -> Result<()> {
let now = chrono::Utc::now().timestamp();
crate::postprocess::rerun_on(conn, id, crate::postprocess::step::mask(crate::category::step::STEP), now)
}

/// Once per shard: queues every release saved from a spot before the spot's kind was a category hint for the
/// category step again. Returns how many.
pub fn recategorize_all(conn: &Connection) -> Result<usize> {
const DONE: &str = "spot_category_hint";
if crate::store::get_meta(conn, DONE)?.is_some() {
return Ok(0);
}
let ids: Vec<i64> =
conn.prepare("select release_id from spots")?.query_map([], |r| r.get(0))?.collect::<Result<_>>()?;
for id in &ids {
recategorize(conn, *id)?;
}
crate::store::set_meta(conn, DONE, 1)?;
Ok(ids.len())
}

/// What a release's spot says, for its page, its row and the API.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Tagged {
Expand Down Expand Up @@ -672,10 +698,30 @@ mod tests {
assert_eq!(state, GAVE_UP);
}

/// A shard's tables: tagging a release touches its row and the stage's queue (`recategorize`).
fn tagging_shard(conn: &Connection) {
conn.execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT, group_name TEXT)").unwrap();
for table in [&crate::postprocess::schema::PP_STATE, &crate::postprocess::schema::PP_QUEUE] {
conn.execute_batch(table.create).unwrap();
for (column, kind) in table.added {
conn.execute_batch(&format!("alter table {} add column {column} {kind}", table.name)).unwrap();
}
}
}

fn queued(conn: &Connection) -> Vec<i64> {
conn.prepare("select release_id from pp_queue order by release_id")
.unwrap()
.query_map([], |r| r.get(0))
.unwrap()
.collect::<Result<_>>()
.unwrap()
}

#[test]
fn tags_the_release_by_name_and_group_and_copies_by_nzb() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT, group_name TEXT)").unwrap();
tagging_shard(&conn);
conn.execute("insert into releases values (5, 'Movie (2026)', 'alt.binaries.x')", []).unwrap();
conn.execute_batch(SPOTS.create).unwrap();
let spot = FullSpot {
Expand All @@ -695,6 +741,8 @@ mod tests {
assert_eq!(tag_copy(&conn, &row).unwrap(), None);
assert_eq!(tag(&conn, "Movie (2026)", "alt.binaries.y", &row).unwrap(), None);
assert_eq!(tag(&conn, "Movie (2026)", "alt.binaries.x", &row).unwrap(), Some(5));
assert_eq!(queued(&conn), [5], "the category step looks again, with the spot's kind");
conn.execute("delete from pp_queue", []).unwrap();
// an edit of the spot, retitled, with the same NZB: the same release, the newer spot
let edited = FullSpot { title: "Movie (2026) edited".into(), ..spot.clone() };
let again = SpotRow { message_id: "m2@spot.net".into(), spot: edited, ..row.clone() };
Expand All @@ -711,14 +759,30 @@ mod tests {
("m2@spot.net", "Movie (2026) edited", "tt1234567", 1)
);
// a release that went (junk) leaves its spot row behind for the trigger, not for copies
assert_eq!(queued(&conn), [5]);
conn.execute("delete from releases where id = 5", []).unwrap();
assert_eq!(tag_copy(&conn, &row).unwrap(), None);
}

#[test]
fn spot_releases_are_queued_for_their_category_once() {
let conn = Connection::open_in_memory().unwrap();
tagging_shard(&conn);
conn.execute_batch(SPOTS.create).unwrap();
conn.execute_batch("create table meta (key TEXT PRIMARY KEY, value INTEGER)").unwrap();
conn.execute("insert into releases values (8, 'A', 'g'), (16, 'B', 'g'), (24, 'C', 'g')", []).unwrap();
conn.execute("insert into spots (release_id, message_id, kind, title) values (8, 'a', 'movie', 'A'), (24, 'c', 'series', 'C')", []).unwrap();
assert_eq!(recategorize_all(&conn).unwrap(), 2);
assert_eq!(queued(&conn), [8, 24]);
conn.execute("delete from pp_queue", []).unwrap();
assert_eq!(recategorize_all(&conn).unwrap(), 0, "once");
assert!(queued(&conn).is_empty());
}

#[test]
fn an_older_copy_keeps_the_newer_spot() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT, group_name TEXT)").unwrap();
tagging_shard(&conn);
conn.execute("insert into releases values (5, 'Movie (2026)', 'g')", []).unwrap();
conn.execute_batch(SPOTS.create).unwrap();
let spot = |title: &str, created| FullSpot { title: title.into(), created, ..FullSpot::default() };
Expand Down Expand Up @@ -799,7 +863,7 @@ mod tests {
#[test]
fn a_frozen_release_keeps_its_row_when_a_copy_comes() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT, group_name TEXT)").unwrap();
tagging_shard(&conn);
conn.execute_batch(SPOTS.create).unwrap();
let row = SpotRow {
message_id: "m@spot.net".into(),
Expand Down Expand Up @@ -958,7 +1022,7 @@ mod tests {
#[test]
fn a_frozen_release_with_the_title_counts_as_another_post() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT, group_name TEXT)").unwrap();
tagging_shard(&conn);
conn.execute_batch(SPOTS.create).unwrap();
let files = vec![("a.mkv".to_string(), vec!["a@x".to_string()])];
assert_eq!(placement(&conn, "Title", "g", "k", &files).unwrap(), Placement::Free);
Expand All @@ -974,7 +1038,7 @@ mod tests {
#[test]
fn a_name_is_in_use_live_or_frozen() {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT, group_name TEXT)").unwrap();
tagging_shard(&conn);
conn.execute("insert into releases values (1, 'Live', 'g')", []).unwrap();
assert!(name_in_use(&conn, "Live", "g").unwrap());
assert!(!name_in_use(&conn, "Frozen", "g").unwrap());
Expand Down