diff --git a/docs/administration.md b/docs/administration.md index 023f7c5..7f74742 100644 --- a/docs/administration.md +++ b/docs/administration.md @@ -122,6 +122,18 @@ the user to sign in again and then continues without fetching the playlists it already has. In Development Mode Spotify reads only the user's own and collaborative playlists; others are imported from the data export. +Entries are matched against the local library first, then against federated +tracks this server already knows from searches and from the user's synced likes +and playlists; neither step uses the network. A match needs the same title, an +artist in common and the same version markers (live, remix, edit and similar, +also when they appear only in the album title). Remastered, mono, stereo, +explicit and clean versions are never treated as equal automatically, and a +match without a comparable duration needs the same album; doubtful entries are +left for the user to choose. Matched local tracks are hashed for their +federation content id even when federation is disabled, which requires +**Settings → Agent → Storage directory** (`FURU_AGENT_STORAGE_DIR`); without it +they wait as "no content id" and later passes try again. + ## Federation Federation is optional. Independent Furumusic and Furumi players that use the diff --git a/docs/development.md b/docs/development.md index 1d5add4..ddda461 100644 --- a/docs/development.md +++ b/docs/development.md @@ -158,8 +158,15 @@ FURU_LIBRARY_IMPORT_TEST_DATABASE_URL=postgresql://... cargo test library_import The database tests cover per-user isolation, repeated and similar source playlists, storing a 5000-entry export, exclusive claims, lease ownership, cancellation, history deletion that keeps target playlists, resumption after a worker stops -without a server restart once its lease expires, and continuing the same Spotify -API import after the user signs in again. +without a server restart once its lease expires, continuing the same Spotify +API import after the user signs in again, and resolving a small library with +federation disabled: local matches get content ids from `agent_storage_dir`, +known federated tracks match without the network, and a federation stub that +panics proves no network access without consent. The database needs the +`pg_trgm` extension; the tests install it into `public`. + +The matcher's reference table (`src/library_import/matcher/tests.rs`) runs +without a database and documents the matching rules case by case. The Spotify export fixture in `src/library_import/adapters/fixtures/spotify_export/` is synthetic. Add a fresh anonymized real export next to it before relying on the diff --git a/src/federation/mod.rs b/src/federation/mod.rs index bbfc00d..3306135 100644 --- a/src/federation/mod.rs +++ b/src/federation/mod.rs @@ -702,6 +702,11 @@ impl Federation { stop_running(guard.take()).await; } + /// Whether the node runs and can search the network. + pub(crate) async fn is_running(&self) -> bool { + self.running.lock().await.is_some() + } + async fn service(&self) -> Result> { self.running .lock() @@ -1325,6 +1330,51 @@ async fn similarity_route_sync_loop( } } +/// The content id of a local audio file. A cached id with the file's current +/// hash is returned as is; otherwise the file is hashed off the async runtime +/// and stored in the shared cache, as the federation warmer does. Only +/// `storage_dir` (`agent_storage_dir`) is needed: the node does not have to +/// run. `None` when the storage directory is not set or the file is unreadable. +pub(crate) async fn ensure_local_content_id( + pool: &PgPool, + storage_dir: &str, + media_file_id: i64, +) -> Result> { + let Some(row) = sqlx::query( + "SELECT m.file_path, m.sha256_hash, c.content_id + FROM furumusic__media_file m + LEFT JOIN furumusic__federation_content_id_cache c + ON c.media_file_id = m.id AND c.sha256_hash = m.sha256_hash + WHERE m.id = $1", + ) + .bind(media_file_id) + .fetch_optional(pool) + .await? + else { + return Ok(None); + }; + let cached: Option = row.get(2); + if let Some(content_id) = cached.as_deref().and_then(music_dht::normalize_content_id) { + return Ok(Some(content_id)); + } + if storage_dir.trim().is_empty() { + return Ok(None); + } + let file_path: String = row.get(0); + let sha256_hash: String = row.get(1); + let storage_dir = storage_dir.to_owned(); + let content_id = + tokio::task::spawn_blocking(move || audio_content_id(&storage_dir, &file_path)) + .await + .ok() + .flatten(); + let Some(content_id) = content_id else { + return Ok(None); + }; + persist_content_id(pool, media_file_id, &sha256_hash, &content_id).await?; + Ok(Some(content_id)) +} + async fn persist_content_id( pool: &PgPool, media_file_id: i64, diff --git a/src/library_import/job.rs b/src/library_import/job.rs index 53c59a1..929ff7b 100644 --- a/src/library_import/job.rs +++ b/src/library_import/job.rs @@ -14,8 +14,10 @@ use anyhow::Result; use sqlx::PgPool; use super::model::Phase; +use super::model::ResolutionStatus; use super::providers::{FetchError, LibraryFetcher, ProviderFetchers, TokenVault}; -use super::store::{self, ClaimedImport, Control, FinishOutcome, NewItem}; +use super::resolver::{FederationAccess, NodeFederation, Resolver}; +use super::store::{self, ClaimedImport, Control, FinishOutcome, NewItem, Resolution}; use crate::config::AppConfig; use crate::scheduler::{Job, JobContext, JobLog, SchedulerHandle}; @@ -76,16 +78,25 @@ pub async fn run_worker( run_id: i64, log: &mut JobLog, ) -> Result<()> { - run_worker_with(pool, config, run_id, log, Arc::new(ProviderFetchers)).await + run_worker_with( + pool, + config, + run_id, + log, + Arc::new(ProviderFetchers), + Arc::new(NodeFederation), + ) + .await } -/// [`run_worker`] with the provider API client given by the caller. +/// [`run_worker`] with the provider API client and the federation given by the caller. pub async fn run_worker_with( pool: &PgPool, config: Arc, run_id: i64, log: &mut JobLog, fetcher: Arc, + federation: Arc, ) -> Result<()> { let Some(_slot) = WorkerSlot::acquire() else { log.info("Library import workers are busy; queued imports will be taken by them"); @@ -96,6 +107,7 @@ pub async fn run_worker_with( config, run_id, fetcher, + federation, }; let mut processed = 0usize; while let Some(import) = store::claim_next(pool, run_id, LEASE).await? { @@ -118,6 +130,7 @@ struct Worker { config: Arc, run_id: i64, fetcher: Arc, + federation: Arc, } /// Renews the lease in the background while the worker owns an import. @@ -274,7 +287,11 @@ impl Worker { return Ok(Some(stop)); } } - Phase::ResolveLocal => self.resolve_local(import, log).await?, + Phase::ResolveLocal => { + if let Some(stop) = self.resolve_local(import, heartbeat, log).await? { + return Ok(Some(stop)); + } + } Phase::ResolveFederation => self.resolve_federation(import, log).await?, Phase::Publish => self.publish(import, log).await?, } @@ -356,19 +373,113 @@ impl Worker { Ok(None) } - /// Matches pending entries against the local library (resolver stage 1–2). - async fn resolve_local(&self, _import: &ClaimedImport, _log: &mut JobLog) -> Result<()> { - Ok(()) + /// Matches pending entries against the local library and the federated + /// tracks this server already knows (resolver stages 1–2), without the + /// network. Decisions are written after each artist group; a group that + /// fails is marked failed and the import continues. + async fn resolve_local( + &self, + import: &ClaimedImport, + heartbeat: &Heartbeat, + log: &mut JobLog, + ) -> Result> { + let entries = store::pending_entries(&self.pool, import.id).await?; + if entries.is_empty() { + return Ok(None); + } + let prepared = Resolver::prepare( + &self.pool, + import.user_id, + entries, + self.config.agent_storage_dir.clone(), + ) + .await?; + let mut counts = ResolveCounts::default(); + if !prepared.invalid.is_empty() { + if !self.store_resolutions(import, &prepared.invalid).await? { + return Ok(Some(Stop::LeaseLost)); + } + counts.add(&prepared.invalid); + } + for group in &prepared.groups { + if heartbeat.lost() { + return Ok(Some(Stop::LeaseLost)); + } + match store::control(&self.pool, import.id, self.run_id).await? { + Control::Continue => {} + Control::Cancel => return Ok(Some(Stop::Cancelled)), + Control::LeaseLost => return Ok(Some(Stop::LeaseLost)), + } + let resolutions = match prepared.resolver.resolve_group(&self.pool, group).await { + Ok(resolutions) => resolutions, + Err(error) => { + tracing::warn!( + import_id = import.id, + entries = group.len(), + %error, + "library import group failed" + ); + group + .iter() + .map(|entry| Resolution::failed(entry.id, "resolve_failed")) + .collect() + } + }; + if !self.store_resolutions(import, &resolutions).await? { + return Ok(Some(Stop::LeaseLost)); + } + counts.add(&resolutions); + } + log.info(&format!( + "Library import {}: resolved {} entries locally ({} matched, {} ambiguous, {} unmatched, {} failed)", + import.id, counts.total, counts.matched, counts.ambiguous, counts.unmatched, counts.failed + )); + Ok(None) } - /// Searches artist catalogues on the network, only with the user's consent - /// and a running federation. + /// Writes decisions; a write that fails marks the entries failed instead. + async fn store_resolutions( + &self, + import: &ClaimedImport, + resolutions: &[Resolution], + ) -> Result { + match store::store_resolutions(&self.pool, import.id, self.run_id, resolutions).await { + Ok(owned) => Ok(owned), + Err(error) => { + tracing::warn!( + import_id = import.id, + entries = resolutions.len(), + %error, + "library import could not store decisions" + ); + let failed: Vec = resolutions + .iter() + .map(|resolution| Resolution::failed(resolution.item_id, "write_failed")) + .collect(); + Ok(store::store_resolutions(&self.pool, import.id, self.run_id, &failed).await?) + } + } + } + + /// Searches artist catalogues on the network (resolver stage 3), only + /// with the user's consent and a running federation. Without consent the + /// federation is not even asked whether it runs. async fn resolve_federation(&self, import: &ClaimedImport, log: &mut JobLog) -> Result<()> { - if import.federated_search && !self.config.federation_enabled { + if !import.federated_search { + return Ok(()); + } + if !self.config.federation_enabled { log.info(&format!( "Library import {}: federation is disabled; network search skipped", import.id )); + return Ok(()); + } + if !self.federation.is_running().await { + log.info(&format!( + "Library import {}: federation is not running; network search skipped", + import.id + )); } Ok(()) } @@ -379,6 +490,30 @@ impl Worker { } } +/// Decisions of one resolver pass, for the job log. +#[derive(Default)] +struct ResolveCounts { + total: usize, + matched: usize, + ambiguous: usize, + unmatched: usize, + failed: usize, +} + +impl ResolveCounts { + fn add(&mut self, resolutions: &[Resolution]) { + for resolution in resolutions { + self.total += 1; + match resolution.status { + ResolutionStatus::Matched => self.matched += 1, + ResolutionStatus::Ambiguous => self.ambiguous += 1, + ResolutionStatus::Failed => self.failed += 1, + _ => self.unmatched += 1, + } + } + } +} + // --------------------------------------------------------------------------- // Boot hook and sweeper // --------------------------------------------------------------------------- diff --git a/src/library_import/matcher/mod.rs b/src/library_import/matcher/mod.rs new file mode 100644 index 0000000..3823897 --- /dev/null +++ b/src/library_import/matcher/mod.rs @@ -0,0 +1,18 @@ +//! Matching of source entries against library and federation candidates +//! (plan §5). +//! +//! This module is pure: it does not depend on the database, the web framework +//! or the async runtime. The resolver collects candidates, prepares them once +//! and asks [`decide`] for a decision. + +mod normalize; +mod score; +#[cfg(test)] +mod tests; + +pub use normalize::{ + KnownArtists, NameKey, artist_name_variants, folded, parse_title, split_artists, +}; +pub use score::{ + Candidate, Decision, Origin, PreparedCandidate, PreparedSource, Ranked, Source, decide, +}; diff --git a/src/library_import/matcher/normalize.rs b/src/library_import/matcher/normalize.rs new file mode 100644 index 0000000..ab2f7b9 --- /dev/null +++ b/src/library_import/matcher/normalize.rs @@ -0,0 +1,545 @@ +//! Comparison keys, artist splitting and version tags of titles and albums. + +use std::collections::{BTreeSet, HashSet}; + +use unicode_normalization::UnicodeNormalization; + +/// The comparison key shared with the federation and the player search: +/// NFKC, lowercase, non-alphanumerics collapsed to single spaces, `ё` = `е`. +pub fn key(text: &str) -> String { + music_dht::normalize_name(text).replace('ё', "е") +} + +/// The fallback key without diacritics: `Beyoncé` = `Beyonce`. Only the +/// combining diacritical marks block is dropped, so kana keep their voicing +/// marks and Cyrillic and Japanese text keeps its letters. +pub fn folded(text: &str) -> String { + let stripped: String = text + .nfkd() + .filter(|ch| !('\u{300}'..='\u{36f}').contains(ch)) + .collect(); + key(&stripped) +} + +/// A name or title with its primary and fallback key. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct NameKey { + pub key: String, + pub folded: String, +} + +impl NameKey { + pub fn new(text: &str) -> Self { + let primary = key(text); + if primary.is_empty() { + // Titles made only of symbols still compare by their text. + let raw = text.trim().to_lowercase(); + return Self { + key: raw.clone(), + folded: raw, + }; + } + Self { + key: primary, + folded: folded(text), + } + } + + pub fn is_empty(&self) -> bool { + self.key.is_empty() + } + + /// Equal by the primary key, then by the key without diacritics. + pub fn matches(&self, other: &Self) -> bool { + (!self.key.is_empty() && self.key == other.key) + || (!self.folded.is_empty() && self.folded == other.folded) + } +} + +/// Artist names known to the library, the known federated tracks and the +/// fetched catalogues. Only known names are split into several artists. +#[derive(Debug, Clone, Default)] +pub struct KnownArtists { + names: HashSet, +} + +impl KnownArtists { + pub fn insert(&mut self, name: &str) { + let name = NameKey::new(name); + if name.is_empty() { + return; + } + self.names.insert(name.folded); + self.names.insert(name.key); + } + + pub fn contains(&self, name: &str) -> bool { + let name = NameKey::new(name); + !name.is_empty() && (self.names.contains(&name.key) || self.names.contains(&name.folded)) + } +} + +/// Markers that always separate featured artists, in an artist string or a title. +const FEATURING: [&str; 5] = [" featuring ", " feat. ", " feat ", " ft. ", " ft "]; +/// Bracketed featuring prefixes. `with` is accepted in titles only. +const BRACKET_FEATURING: [&str; 5] = ["featuring ", "feat. ", "feat ", "ft. ", "ft "]; +/// Separators of collaborations, applied only when every part is a known artist. +const SEPARATORS: [&str; 4] = [", ", " & ", " x ", " and "]; +/// Collaborations with more parts are kept whole. +const MAX_PARTS: usize = 8; + +/// Splits an unbracketed `A feat. B` into `A` and `B`. +fn split_featuring(text: &str) -> (&str, Option<&str>) { + let lower = text.to_ascii_lowercase(); + FEATURING + .iter() + .filter_map(|marker| lower.find(marker).map(|index| (index, marker.len()))) + .filter(|(index, _)| *index > 0) + .min_by_key(|(index, _)| *index) + .map_or((text, None), |(index, len)| { + (&text[..index], Some(&text[index + len..])) + }) +} + +/// Removes bracketed featuring groups such as `(feat. X)` and collects their artists. +fn take_bracket_featuring(text: &str, with: bool, featured: &mut Vec) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(open) = rest.find(['(', '[']) { + let close_char = if rest.as_bytes()[open] == b'(' { + ')' + } else { + ']' + }; + let Some(close) = rest[open + 1..] + .find(close_char) + .map(|index| open + 1 + index) + else { + break; + }; + let inner = rest[open + 1..close].trim(); + let lower = inner.to_ascii_lowercase(); + let prefix = BRACKET_FEATURING + .iter() + .copied() + .chain(with.then_some("with ")) + .find(|prefix| lower.starts_with(prefix)); + match prefix { + Some(prefix) if inner.len() > prefix.len() => { + featured.push(inner[prefix.len()..].trim().to_owned()); + out.push_str(rest[..open].trim_end()); + } + _ => out.push_str(&rest[..=close]), + } + rest = &rest[close + 1..]; + } + out.push_str(rest); + out.trim().to_owned() +} + +/// Byte ranges of the parts of `text` between collaboration separators. +fn separator_parts(text: &str) -> Vec<(usize, usize)> { + let lower = text.to_ascii_lowercase(); + let mut parts = Vec::new(); + let mut start = 0; + loop { + let next = SEPARATORS + .iter() + .filter_map(|separator| { + lower[start..] + .find(separator) + .map(|index| (start + index, separator.len())) + }) + .min_by_key(|(index, _)| *index); + match next { + Some((index, len)) => { + parts.push((start, index)); + start = index + len; + } + None => { + parts.push((start, text.len())); + return parts; + } + } + } +} + +/// Contiguous groups of parts, each a known artist, with the fewest groups. +fn known_segments( + text: &str, + parts: &[(usize, usize)], + known: &KnownArtists, +) -> Option> { + let count = parts.len(); + // best[j]: fewest known segments covering parts[..j], and where the last one starts. + let mut best: Vec> = vec![None; count + 1]; + best[0] = Some((0, 0)); + for end in 1..=count { + for start in 0..end { + let Some((segments, _)) = best[start] else { + continue; + }; + let segment = text[parts[start].0..parts[end - 1].1].trim(); + if !known.contains(segment) { + continue; + } + if best[end].is_none_or(|(current, _)| segments + 1 < current) { + best[end] = Some((segments + 1, start)); + } + } + } + best[count]?; + let mut names = Vec::new(); + let mut end = count; + while end > 0 { + let (_, start) = best[end]?; + names.push(text[parts[start].0..parts[end - 1].1].trim().to_owned()); + end = start; + } + names.reverse(); + Some(names) +} + +fn push_collaboration(text: &str, known: &KnownArtists, names: &mut Vec) { + let text = text.trim(); + if text.is_empty() { + return; + } + if !known.contains(text) { + let parts = separator_parts(text); + if (2..=MAX_PARTS).contains(&parts.len()) + && let Some(segments) = known_segments(text, &parts, known) + { + names.extend(segments); + return; + } + } + names.push(text.to_owned()); +} + +/// Splits a source artist string. `feat.`, `ft.` and `featuring` always +/// separate artists. A string known as a whole stays one artist (`Tyler, The +/// Creator`); otherwise it is split at `, `, ` & `, ` x ` and ` and ` only when +/// every part is a known artist. The main artist comes first. +pub fn split_artists(raw: &str, known: &KnownArtists) -> Vec { + let mut featured = Vec::new(); + let text = take_bracket_featuring(raw, false, &mut featured); + let (main, after) = split_featuring(&text); + let mut names = Vec::new(); + push_collaboration(main, known, &mut names); + if let Some(after) = after { + push_collaboration(after, known, &mut names); + } + for name in &featured { + push_collaboration(name, known, &mut names); + } + dedupe_names(names) +} + +/// Drops repeated names, keeping the first spelling. +pub fn dedupe_names(names: Vec) -> Vec { + let mut seen = HashSet::new(); + names + .into_iter() + .filter(|name| { + let key = NameKey::new(name); + !key.is_empty() && seen.insert(key.key) + }) + .collect() +} + +/// Every name an artist string may resolve to: the whole string, its +/// featured artists and each contiguous group of its collaboration parts. +/// The resolver looks these up to build [`KnownArtists`]. +pub fn artist_name_variants(raw: &str) -> Vec { + let mut featured = Vec::new(); + let text = take_bracket_featuring(raw, false, &mut featured); + let (main, after) = split_featuring(&text); + let mut variants = vec![raw.trim().to_owned()]; + for text in std::iter::once(main) + .chain(after) + .chain(featured.iter().map(String::as_str)) + { + let text = text.trim(); + let parts = separator_parts(text); + let parts = if parts.len() > MAX_PARTS { + &parts[..1] + } else { + &parts[..] + }; + for start in 0..parts.len() { + for end in start + 1..=parts.len() { + variants.push(text[parts[start].0..parts[end - 1].1].trim().to_owned()); + } + } + } + variants.retain(|name| !name.is_empty()); + variants.sort(); + variants.dedup(); + variants +} + +// --------------------------------------------------------------------------- +// Version tags +// --------------------------------------------------------------------------- + +/// Version markers of a title or album, by class. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct VersionTags { + /// Must be equal on both sides: live, remixes, edits, covers, versions. + pub hard: BTreeSet, + /// Never equivalent automatically: remaster (with year), mono, stereo, explicit, clean. + pub editorial: BTreeSet, + /// Lower the score slightly: deluxe, bonus track, album or single version. + pub soft: BTreeSet, +} + +impl VersionTags { + pub fn is_empty(&self) -> bool { + self.hard.is_empty() && self.editorial.is_empty() && self.soft.is_empty() + } + + pub fn extend(&mut self, other: VersionTags) { + self.hard.extend(other.hard); + self.editorial.extend(other.editorial); + self.soft.extend(other.soft); + // A dated remaster names the plain one more precisely. + if self + .editorial + .iter() + .any(|tag| tag.starts_with("remaster:")) + { + self.editorial.remove("remaster"); + } + } +} + +fn is_year(token: &str) -> bool { + token.len() == 4 + && token.bytes().all(|byte| byte.is_ascii_digit()) + && (token.starts_with("19") || token.starts_with("20")) +} + +/// Tags of one part of a decoration such as `Live at Wembley` or `2011 Remaster`. +fn classify_part(tokens: &[&str], tags: &mut VersionTags) { + let Some(&last) = tokens.last() else { + return; + }; + let has = |word: &str| tokens.contains(&word); + // A remix names its remixer; the name is not scanned for other markers. + if let Some(index) = tokens + .iter() + .position(|token| matches!(*token, "remix" | "remixed" | "rmx")) + { + let name = if tokens[index] == "remixed" && tokens.get(index + 1) == Some(&"by") { + tokens[index + 2..].join(" ") + } else { + tokens[..index].join(" ") + }; + tags.hard.insert(if name.is_empty() { + "remix".to_owned() + } else { + format!("remix:{name}") + }); + return; + } + if last == "mix" { + let name = tokens[..tokens.len() - 1].join(" "); + match name.as_str() { + "original" | "album" => tags.soft.insert("original_mix".to_owned()), + "radio" | "single" => tags.hard.insert("edit".to_owned()), + _ if has("extended") => tags.hard.insert("extended".to_owned()), + "" => tags.hard.insert("mix".to_owned()), + _ => tags.hard.insert(format!("mix:{name}")), + }; + return; + } + let before = tags.clone(); + let mut hard = |tag: &str| { + tags.hard.insert(tag.to_owned()); + }; + if has("live") || has("unplugged") || tokens.windows(2).any(|pair| pair == ["in", "concert"]) { + hard("live"); + } + for word in [ + "acoustic", + "instrumental", + "karaoke", + "demo", + "extended", + "slowed", + "cover", + ] { + if has(word) { + hard(word); + } + } + if has("edit") { + hard("edit"); + } + if ((has("sped") || has("speed")) && has("up")) || has("spedup") || has("nightcore") { + hard("sped_up"); + } + if tokens.iter().any(|token| token.starts_with("remaster")) { + tags.editorial + .insert(match tokens.iter().find(|token| is_year(token)) { + Some(year) => format!("remaster:{year}"), + None => "remaster".to_owned(), + }); + } + for word in ["mono", "stereo", "explicit", "clean"] { + if has(word) { + tags.editorial.insert(word.to_owned()); + } + } + if has("deluxe") { + tags.soft.insert("deluxe".to_owned()); + } + if has("bonus") { + tags.soft.insert("bonus".to_owned()); + } + if has("edition") { + tags.soft.insert("edition".to_owned()); + } + // `From "Film"` and similar soundtrack notes. + if tokens[0] == "from" && tokens.len() > 1 { + tags.soft.insert("from".to_owned()); + } + if *tags == before + && let Some(index) = tokens.iter().position(|token| *token == "version") + { + let name = tokens[..index].join(" "); + match name.as_str() { + "" | "album" | "single" | "original" | "lp" | "studio" => { + tags.soft.insert("version".to_owned()); + } + "radio" => { + tags.hard.insert("edit".to_owned()); + } + _ => { + tags.hard.insert(format!("version:{name}")); + } + } + } +} + +/// Tags of a decoration, or `None` when it carries no known marker and +/// belongs to the title itself (`Part 2`). +fn classify(decoration: &str) -> Option { + let mut tags = VersionTags::default(); + for part in decoration + .split(['/', ';', ',']) + .flat_map(|part| part.split(" - ")) + { + let part = key(part); + let tokens: Vec<&str> = part.split(' ').filter(|token| !token.is_empty()).collect(); + classify_part(&tokens, &mut tags); + } + (!tags.is_empty()).then_some(tags) +} + +/// `(inner)` or `[inner]` at the end of `text`, with the text before it. +fn trailing_group(text: &str) -> Option<(&str, &str)> { + let open = match text.chars().last()? { + ')' => '(', + ']' => '[', + _ => return None, + }; + let inner = &text[..text.len() - 1]; + let index = inner.rfind(open)?; + Some((&inner[..index], &inner[index + 1..])) +} + +/// The text after the last ` - `, ` – ` or ` — `. +fn trailing_dash(text: &str) -> Option<(&str, &str)> { + [" - ", " – ", " — "] + .iter() + .filter_map(|dash| text.rfind(dash).map(|index| (index, dash.len()))) + .max_by_key(|(index, _)| *index) + .map(|(index, len)| (&text[..index], &text[index + len..])) +} + +/// Strips trailing decorations with known markers: `Song (Live) - Remastered 2011`. +fn strip_decorations(text: &str) -> (String, VersionTags) { + let mut core = text.trim(); + let mut tags = VersionTags::default(); + loop { + let stripped = [trailing_group(core), trailing_dash(core)] + .into_iter() + .flatten() + .find_map(|(base, decoration)| { + let base = base.trim(); + if base.is_empty() { + return None; + } + classify(decoration).map(|found| (base, found)) + }); + match stripped { + Some((base, found)) => { + tags.extend(found); + core = base; + } + None => return (core.to_owned(), tags), + } + } +} + +/// A track title split into its core, featured artists and version tags. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ParsedTitle { + /// The title without featuring groups and known decorations. + pub core: String, + pub key: NameKey, + /// Raw featured artist strings found in the title. + pub featured: Vec, + pub tags: VersionTags, +} + +pub fn parse_title(title: &str) -> ParsedTitle { + let mut featured = Vec::new(); + let text = take_bracket_featuring(title, true, &mut featured); + let (mut core, tags) = strip_decorations(&text); + if let (main, Some(after)) = split_featuring(&core) + && !main.trim().is_empty() + { + featured.push(after.trim().to_owned()); + core = main.trim().to_owned(); + } + featured.retain(|name| !name.is_empty()); + ParsedTitle { + key: NameKey::new(&core), + core, + featured, + tags, + } +} + +/// An album title split into its core and version tags. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ParsedAlbum { + pub key: NameKey, + pub tags: VersionTags, +} + +/// Albums carry version markers too: `Abbey Road (Remastered 2009)` or a +/// concert album such as `Live at Leeds` or `MTV Unplugged`. +pub fn parse_album(album: &str) -> ParsedAlbum { + let (core, mut tags) = strip_decorations(album); + let key = NameKey::new(&core); + let tokens: Vec<&str> = key.key.split(' ').collect(); + let concert = match tokens.as_slice() { + ["live"] => true, + ["live", next, ..] => { + matches!( + *next, + "at" | "in" | "from" | "on" | "aus" | "au" | "à" | "en" + ) || is_year(next) + } + _ => false, + } || tokens.contains(&"unplugged") + || tokens.windows(2).any(|pair| pair == ["in", "concert"]); + if concert { + tags.hard.insert("live".to_owned()); + } + ParsedAlbum { key, tags } +} diff --git a/src/library_import/matcher/score.rs b/src/library_import/matcher/score.rs new file mode 100644 index 0000000..9ebb08b --- /dev/null +++ b/src/library_import/matcher/score.rs @@ -0,0 +1,406 @@ +//! Candidate scores and the decision for one source entry. + +use std::borrow::Borrow; +use std::cmp::Ordering; + +use serde::Serialize; + +use super::normalize::{ + KnownArtists, NameKey, VersionTags, dedupe_names, parse_album, parse_title, split_artists, +}; + +/// Where a candidate comes from. Local tracks win over federated copies of +/// the same recording. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Origin { + Local, + Federation, +} + +impl Origin { + pub fn as_str(self) -> &'static str { + match self { + Self::Local => "local", + Self::Federation => "federation", + } + } +} + +/// How well a candidate fits. Only `Strong` and `Exact` are chosen automatically. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Level { + Reject, + Weak, + Strong, + Exact, +} + +/// Why a candidate was rejected. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum RejectReason { + Title, + Artist, + Version, + Duration, +} + +impl RejectReason { + /// The `resolution_note` of an entry whose candidates were all rejected. + pub fn note(self) -> &'static str { + match self { + Self::Title | Self::Artist => NOT_FOUND, + Self::Version => "version_mismatch", + Self::Duration => "duration_mismatch", + } + } +} + +/// `resolution_note` of an entry without any usable candidate. +pub const NOT_FOUND: &str = "not_found"; +/// Ambiguous entries keep this many candidates for manual selection. +pub const MAX_CANDIDATES: usize = 5; + +/// A source entry as the matcher sees it. +#[derive(Debug, Clone, Default)] +pub struct Source { + pub title: String, + pub artists: Vec, + pub album: Option, + pub duration_ms: Option, +} + +/// A library or federated track that may be the source entry. +#[derive(Debug, Clone)] +pub struct Candidate { + pub origin: Origin, + pub title: String, + pub artists: Vec, + pub featured_artists: Vec, + pub album: Option, + /// Federated durations are whole seconds. + pub duration_seconds: Option, + pub content_id: Option, + /// Federation peers offering the track. + pub owners: u32, +} + +/// Normalized fields shared by sources and candidates. +#[derive(Debug, Clone)] +struct Prepared { + title: NameKey, + artists: Vec, + album: Option, + tags: VersionTags, + duration: Option, +} + +impl Prepared { + fn new( + title: &str, + artists: &[String], + album: Option<&str>, + duration: Option, + known: &KnownArtists, + ) -> (Self, Vec, String) { + let parsed = parse_title(title); + let names = dedupe_names( + artists + .iter() + .chain(&parsed.featured) + .flat_map(|raw| split_artists(raw, known)) + .collect(), + ); + let mut tags = parsed.tags; + let album = album + .map(str::trim) + .filter(|album| !album.is_empty()) + .map(|album| { + let parsed = parse_album(album); + tags.extend(parsed.tags); + parsed.key + }); + let prepared = Self { + title: parsed.key, + artists: names.iter().map(|name| NameKey::new(name)).collect(), + album: album.filter(|album| !album.is_empty()), + tags, + duration: duration.filter(|seconds| seconds.is_finite() && *seconds > 0.0), + }; + (prepared, names, parsed.core) + } + + fn album_matches(&self, other: &Self) -> bool { + matches!((&self.album, &other.album), (Some(a), Some(b)) if a.matches(b)) + } +} + +/// A source entry prepared once for scoring against many candidates. +#[derive(Debug, Clone)] +pub struct PreparedSource { + inner: Prepared, + artist_names: Vec, + search_title: String, +} + +impl PreparedSource { + pub fn new(source: &Source, known: &KnownArtists) -> Self { + let (inner, artist_names, core) = Prepared::new( + &source.title, + &source.artists, + source.album.as_deref(), + source.duration_ms.map(|ms| ms as f64 / 1000.0), + known, + ); + Self { + inner, + artist_names, + search_title: core.to_lowercase(), + } + } + + /// Artists after featuring extraction and splitting, the main one first. + pub fn artist_names(&self) -> &[String] { + &self.artist_names + } + + pub fn title_key(&self) -> &NameKey { + &self.inner.title + } + + /// Lowercase title core for a trigram search of the library. + pub fn search_title(&self) -> &str { + &self.search_title + } +} + +/// A candidate prepared once for scoring. +#[derive(Debug, Clone)] +pub struct PreparedCandidate { + inner: Prepared, + origin: Origin, + owners: u32, + content_id: Option, +} + +impl PreparedCandidate { + pub fn new(candidate: &Candidate, known: &KnownArtists) -> Self { + let artists: Vec = candidate + .artists + .iter() + .chain(&candidate.featured_artists) + .cloned() + .collect(); + let (inner, _, _) = Prepared::new( + &candidate.title, + &artists, + candidate.album.as_deref(), + candidate.duration_seconds, + known, + ); + Self { + inner, + origin: candidate.origin, + owners: candidate.owners, + content_id: candidate.content_id.clone(), + } + } + + pub fn title_key(&self) -> &NameKey { + &self.inner.title + } + + /// Whole-second durations are compared with one extra second. + fn tolerance(&self) -> f64 { + match self.origin { + Origin::Local => 0.0, + Origin::Federation => 1.0, + } + } +} + +/// The score of one candidate. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Scored { + pub level: Level, + pub score: f32, + pub reason: Option, +} + +impl Scored { + fn reject(reason: RejectReason) -> Self { + Self { + level: Level::Reject, + score: 0.0, + reason: Some(reason), + } + } +} + +/// Scores a candidate against a source entry (plan §5). +pub fn score(source: &PreparedSource, candidate: &PreparedCandidate) -> Scored { + let src = &source.inner; + let cand = &candidate.inner; + if !src.title.matches(&cand.title) { + return Scored::reject(RejectReason::Title); + } + if !src + .artists + .iter() + .any(|artist| cand.artists.iter().any(|other| artist.matches(other))) + { + return Scored::reject(RejectReason::Artist); + } + if src.tags.hard != cand.tags.hard { + return Scored::reject(RejectReason::Version); + } + let album = src.album_matches(cand); + let mut penalty = 0.0f32; + let mut level = match (src.duration, cand.duration) { + (Some(a), Some(b)) => { + let delta = ((a - b).abs() - candidate.tolerance()).max(0.0); + penalty += (delta as f32 * 0.01).min(0.1); + if delta <= 3.0 { + if album { Level::Exact } else { Level::Strong } + } else if delta <= 10.0 { + if album { Level::Strong } else { Level::Weak } + } else { + return Scored::reject(RejectReason::Duration); + } + } + // A unique candidate is not a confirmation: without durations only + // the album confirms the recording. + _ if album => Level::Strong, + _ => Level::Weak, + }; + if src.tags.editorial != cand.tags.editorial { + level = level.min(Level::Weak); + } + let soft = src.tags.soft.symmetric_difference(&cand.tags.soft).count(); + penalty += (soft as f32 * 0.05).min(0.15); + let base = match level { + Level::Exact => 1.0, + Level::Strong => 0.8, + _ => 0.5, + }; + Scored { + level, + score: (base - penalty).max(0.05), + reason: None, + } +} + +/// A scored candidate in decision order. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Ranked { + pub index: usize, + pub level: Level, + pub score: f32, +} + +/// The decision for one source entry. +#[derive(Debug, Clone, PartialEq)] +pub enum Decision { + /// One recording fits; `index` is the chosen candidate. + Matched(Ranked), + /// Several recordings, or only weak candidates: the user chooses. + Ambiguous(Vec), + Unmatched { + reason: &'static str, + }, +} + +/// Preference among candidates of one recording: local, more owners, then +/// the smallest content id; candidates without a content id come last. +fn preference(a: &PreparedCandidate, b: &PreparedCandidate) -> Ordering { + (a.origin != Origin::Local) + .cmp(&(b.origin != Origin::Local)) + .then_with(|| b.owners.cmp(&a.owners)) + .then_with(|| match (&a.content_id, &b.content_id) { + (Some(x), Some(y)) => x.cmp(y), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => Ordering::Equal, + }) +} + +/// Whether two accepted candidates are the same recording: durations within +/// 2 s, or, without durations, the same album and editorial tags. +fn same_recording(a: &PreparedCandidate, b: &PreparedCandidate) -> bool { + match (a.inner.duration, b.inner.duration) { + (Some(x), Some(y)) => (x - y).abs() - a.tolerance().max(b.tolerance()) <= 2.0, + _ => a.inner.album_matches(&b.inner) && a.inner.tags.editorial == b.inner.tags.editorial, + } +} + +fn find(parent: &mut [usize], mut node: usize) -> usize { + while parent[node] != node { + parent[node] = parent[parent[node]]; + node = parent[node]; + } + node +} + +/// Decides an entry from its candidates (plan §5, «Решение по записи»). +pub fn decide>(source: &PreparedSource, candidates: &[C]) -> Decision { + let mut accepted = Vec::new(); + let mut reason: Option = None; + for (index, candidate) in candidates.iter().enumerate() { + let scored = score(source, candidate.borrow()); + match scored.reason { + Some(rejected) => reason = reason.max(Some(rejected)), + None => accepted.push(Ranked { + index, + level: scored.level, + score: scored.score, + }), + } + } + if accepted.is_empty() { + return Decision::Unmatched { + reason: reason.map_or(NOT_FOUND, RejectReason::note), + }; + } + accepted.sort_by(|a, b| { + b.level + .cmp(&a.level) + .then_with(|| b.score.total_cmp(&a.score)) + .then_with(|| preference(candidates[a.index].borrow(), candidates[b.index].borrow())) + .then_with(|| a.index.cmp(&b.index)) + }); + let strong: Vec = accepted + .iter() + .copied() + .filter(|ranked| ranked.level >= Level::Strong) + .collect(); + if !strong.is_empty() { + let mut parent: Vec = (0..strong.len()).collect(); + for a in 0..strong.len() { + for b in a + 1..strong.len() { + if same_recording( + candidates[strong[a].index].borrow(), + candidates[strong[b].index].borrow(), + ) { + let (root_a, root_b) = (find(&mut parent, a), find(&mut parent, b)); + parent[root_a] = root_b; + } + } + } + let root = find(&mut parent, 0); + if (1..strong.len()).all(|node| find(&mut parent, node) == root) { + let chosen = strong + .iter() + .copied() + .min_by(|a, b| { + preference(candidates[a.index].borrow(), candidates[b.index].borrow()) + .then_with(|| b.level.cmp(&a.level)) + .then_with(|| a.index.cmp(&b.index)) + }) + .expect("a group has members"); + return Decision::Matched(chosen); + } + } + accepted.truncate(MAX_CANDIDATES); + Decision::Ambiguous(accepted) +} diff --git a/src/library_import/matcher/tests.rs b/src/library_import/matcher/tests.rs new file mode 100644 index 0000000..f05e113 --- /dev/null +++ b/src/library_import/matcher/tests.rs @@ -0,0 +1,568 @@ +//! Reference table of the matcher (plan §5) and the extra acceptance cases. + +use super::normalize::*; +use super::score::*; + +fn known(names: &[&str]) -> KnownArtists { + let mut known = KnownArtists::default(); + for name in names { + known.insert(name); + } + known +} + +fn source(title: &str, artist: &str, album: Option<&str>, seconds: Option) -> Source { + Source { + title: title.into(), + artists: vec![artist.into()], + album: album.map(Into::into), + duration_ms: seconds.map(|seconds| (seconds * 1000.0) as u64), + } +} + +fn local(title: &str, artist: &str, album: &str, seconds: Option) -> Candidate { + Candidate { + origin: Origin::Local, + title: title.into(), + artists: vec![artist.into()], + featured_artists: Vec::new(), + album: Some(album.into()), + duration_seconds: seconds, + content_id: None, + owners: 0, + } +} + +fn federated(title: &str, artist: &str, album: &str, seconds: Option, id: &str) -> Candidate { + Candidate { + origin: Origin::Federation, + content_id: Some(id.into()), + owners: 1, + ..local(title, artist, album, seconds) + } +} + +#[derive(Debug, PartialEq)] +enum Outcome { + Matched(usize), + Ambiguous, + Unmatched(&'static str), +} + +fn outcome(source: &Source, known: &KnownArtists, candidates: &[Candidate]) -> Outcome { + let prepared = PreparedSource::new(source, known); + let candidates: Vec = candidates + .iter() + .map(|candidate| PreparedCandidate::new(candidate, known)) + .collect(); + match decide(&prepared, &candidates) { + Decision::Matched(ranked) => Outcome::Matched(ranked.index), + Decision::Ambiguous(ranked) => { + assert!(!ranked.is_empty() && ranked.len() <= MAX_CANDIDATES); + Outcome::Ambiguous + } + Decision::Unmatched { reason } => Outcome::Unmatched(reason), + } +} + +/// One candidate against one source entry, both with the same album unless given. +fn single(source: Source, candidate: Candidate) -> Outcome { + outcome(&source, &KnownArtists::default(), &[candidate]) +} + +#[test] +fn keys_ignore_case_punctuation_and_yo() { + assert_eq!(key("AC/DC"), key("ac-dc")); + assert_eq!(key(" Hello, WORLD! "), "hello world"); + assert_eq!(key("Ёлка"), key("Елка")); + assert_ne!(key("Beyoncé"), key("Beyonce")); + assert_eq!(folded("Beyoncé"), folded("Beyonce")); + assert!(NameKey::new("Beyoncé").matches(&NameKey::new("BEYONCE"))); + // Folding keeps Cyrillic and kana letters. + assert_eq!(folded("Звезда по имени Солнце"), "звезда по имени солнце"); + assert_eq!(key("ガーゴイル"), "ガーゴイル"); + assert_eq!(folded("が"), "が"); + assert!(!NameKey::new("ガーゴイル").matches(&NameKey::new("カーゴイル"))); +} + +#[test] +fn reference_table() { + let none = KnownArtists::default(); + let cases: Vec<(&str, Source, Vec, Outcome)> = vec![ + ( + "case and punctuation", + source( + "HIGHWAY TO HELL!", + "AC/DC", + Some("Highway to Hell"), + Some(208.0), + ), + vec![local( + "Highway to Hell", + "AC-DC", + "Highway To Hell", + Some(208.4), + )], + Outcome::Matched(0), + ), + ( + "ё equals е", + source("Ёлка", "Ёлка", Some("Ёлка"), Some(180.0)), + vec![local("Елка", "Елка", "Елка", Some(180.0))], + Outcome::Matched(0), + ), + ( + "diacritics fold", + source("Formation", "Beyonce", Some("Lemonade"), Some(206.0)), + vec![local("Formation", "Beyoncé", "Lemonade", Some(206.0))], + Outcome::Matched(0), + ), + ( + "featured artist in the title", + source("Song (feat. X)", "A", Some("Album"), Some(200.0)), + vec![Candidate { + featured_artists: vec!["X".into()], + ..local("Song", "A", "Album", Some(200.0)) + }], + Outcome::Matched(0), + ), + ( + "live rejects the studio version", + source("Song - Live", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Unmatched("version_mismatch"), + ), + ( + "remix rejects the original", + source("Song (X Remix)", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Unmatched("version_mismatch"), + ), + ( + "radio edit rejects the album version", + source("Song - Radio Edit", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Unmatched("version_mismatch"), + ), + ( + "other remixer", + source("Song (X Remix)", "A", Some("Album"), Some(200.0)), + vec![local("Song - Y Remix", "A", "Album", Some(200.0))], + Outcome::Unmatched("version_mismatch"), + ), + ( + "same remix spelled differently", + source("Song - X Remix", "A", Some("Album"), Some(200.0)), + vec![local("Song (X Remix)", "A", "Album", Some(200.0))], + Outcome::Matched(0), + ), + ( + "remaster only on one side", + source("Song - Remastered 2011", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Ambiguous, + ), + ( + "mono against stereo", + source("Song (Mono)", "A", Some("Album"), Some(200.0)), + vec![local("Song (Stereo)", "A", "Album", Some(200.0))], + Outcome::Ambiguous, + ), + ( + "remaster years differ", + source("Song - Remastered 2009", "A", Some("Album"), Some(200.0)), + vec![local("Song - 2011 Remaster", "A", "Album", Some(200.0))], + Outcome::Ambiguous, + ), + ( + "same remaster year", + source("Song - Remastered 2009", "A", Some("Album"), Some(200.0)), + vec![local("Song (2009 Remaster)", "A", "Album", Some(200.0))], + Outcome::Matched(0), + ), + ( + "remaster marker only in the album title", + source( + "Come Together", + "The Beatles", + Some("Abbey Road (Remastered 2009)"), + Some(259.0), + ), + vec![local( + "Come Together", + "The Beatles", + "Abbey Road", + Some(259.0), + )], + Outcome::Ambiguous, + ), + ( + "remaster marker in both album titles", + source( + "Come Together", + "The Beatles", + Some("Abbey Road (Remastered 2009)"), + Some(259.0), + ), + vec![local( + "Come Together - 2009 Remaster", + "The Beatles", + "Abbey Road", + Some(259.0), + )], + Outcome::Matched(0), + ), + ( + "concert album marks the track live", + source("Song", "A", Some("Live at Wembley"), Some(200.0)), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Unmatched("version_mismatch"), + ), + ( + "live marker in the album title on both sides", + source("Song", "A", Some("MTV Unplugged in New York"), Some(200.0)), + vec![local("Song (Live)", "A", "Unplugged", Some(200.0))], + Outcome::Matched(0), + ), + ( + "delta 2 s", + source("Song", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Other album", Some(202.0))], + Outcome::Matched(0), + ), + ( + "delta 7 s with another album", + source("Song", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Other album", Some(207.0))], + Outcome::Ambiguous, + ), + ( + "delta 7 s with the same album", + source("Song", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(207.0))], + Outcome::Matched(0), + ), + ( + "delta 30 s", + source("Song", "A", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(230.0))], + Outcome::Unmatched("duration_mismatch"), + ), + ( + "federated whole seconds get one more second", + source("Song", "A", Some("Other"), Some(203.9)), + vec![federated("Song", "A", "Album", Some(200.0), "b3:1")], + Outcome::Matched(0), + ), + ( + "two copies of one recording prefer the local file", + source("Song", "A", Some("Album"), Some(200.0)), + vec![ + federated("Song", "A", "Album", Some(200.0), "b3:1"), + local("Song", "A", "Album", Some(200.4)), + ], + Outcome::Matched(1), + ), + ( + "two recordings are ambiguous", + source("Song", "A", Some("Album"), Some(200.0)), + vec![ + local("Song", "A", "Album", Some(200.0)), + local("Song", "A", "Album", Some(206.0)), + ], + Outcome::Ambiguous, + ), + ( + "without duration the album confirms", + source("Song", "A", Some("Album (Deluxe Edition)"), None), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Matched(0), + ), + ( + "without duration another album is ambiguous", + source("Song", "A", Some("Album"), None), + vec![ + local("Song", "A", "Greatest Hits", Some(200.0)), + local("Other", "A", "Album", Some(200.0)), + ], + Outcome::Ambiguous, + ), + ( + "a single candidate with another album is not a match", + source("Song", "A", Some("Album"), None), + vec![local("Song", "A", "Greatest Hits", Some(200.0))], + Outcome::Ambiguous, + ), + ( + "without album nothing confirms", + source("Song", "A", None, None), + vec![local("Song", "A", "Album", None)], + Outcome::Ambiguous, + ), + ( + "other artist", + source("Song", "B", Some("Album"), Some(200.0)), + vec![local("Song", "A", "Album", Some(200.0))], + Outcome::Unmatched(NOT_FOUND), + ), + ( + "other title", + source("Song", "A", Some("Album"), Some(200.0)), + vec![local("Song 2", "A", "Album", Some(200.0))], + Outcome::Unmatched(NOT_FOUND), + ), + ( + "parts stay in the title", + source("Song (Part 1)", "A", Some("Album"), Some(200.0)), + vec![local("Song (Part 2)", "A", "Album", Some(200.0))], + Outcome::Unmatched(NOT_FOUND), + ), + ( + "Cyrillic", + source( + "Звезда по имени Солнце", + "Кино", + Some("Звезда по имени Солнце"), + Some(225.0), + ), + vec![local( + "Звезда по имени солнце", + "КИНО", + "Звезда по имени Солнце", + Some(225.3), + )], + Outcome::Matched(0), + ), + ( + "Japanese", + source("夜に駆ける", "YOASOBI", Some("THE BOOK"), Some(261.0)), + vec![local("夜に駆ける", "YOASOBI", "THE BOOK", Some(261.0))], + Outcome::Matched(0), + ), + ( + "Japanese titles differ", + source("夜に駆ける", "YOASOBI", Some("THE BOOK"), Some(261.0)), + vec![local("群青", "YOASOBI", "THE BOOK", Some(261.0))], + Outcome::Unmatched(NOT_FOUND), + ), + ( + "no candidates", + source("Song", "A", None, None), + Vec::new(), + Outcome::Unmatched(NOT_FOUND), + ), + ]; + for (name, source, candidates, expected) in cases { + assert_eq!(outcome(&source, &none, &candidates), expected, "{name}"); + } +} + +#[test] +fn collaborations_split_only_into_known_artists() { + let dictionary = known(&[ + "A", + "B", + "Tyler, The Creator", + "Tyler", + "Frank Ocean", + "Foo", + ]); + assert_eq!(split_artists("A & B", &dictionary), ["A", "B"]); + assert_eq!(split_artists("A x B", &dictionary), ["A", "B"]); + // Known as a whole: never split, even when its parts are known. + assert_eq!( + split_artists("Tyler, The Creator", &dictionary), + ["Tyler, The Creator"] + ); + assert_eq!( + split_artists("Tyler, The Creator & Frank Ocean", &dictionary), + ["Tyler, The Creator", "Frank Ocean"] + ); + // An unknown part keeps the string whole. + assert_eq!(split_artists("Foo, Bar", &dictionary), ["Foo, Bar"]); + assert_eq!( + split_artists("Tyler, The Creator", &KnownArtists::default()), + ["Tyler, The Creator"] + ); + // Featuring always separates. + assert_eq!( + split_artists("A feat. Somebody", &KnownArtists::default()), + ["A", "Somebody"] + ); + assert_eq!( + split_artists("A (ft. B)", &KnownArtists::default()), + ["A", "B"] + ); + assert_eq!( + split_artists("Simon & Garfunkel", &dictionary), + ["Simon & Garfunkel"] + ); + + let variants = artist_name_variants("Tyler, The Creator & Frank Ocean"); + for expected in [ + "Tyler", + "Tyler, The Creator", + "The Creator & Frank Ocean", + "Frank Ocean", + ] { + assert!(variants.iter().any(|name| name == expected), "{expected}"); + } +} + +#[test] +fn collaborations_match_main_and_featured_artists() { + let dictionary = known(&["A", "B"]); + let candidate = Candidate { + featured_artists: vec!["B".into()], + ..local("Song", "A", "Album", Some(200.0)) + }; + assert_eq!( + outcome( + &source("Song", "A & B", Some("Album"), Some(200.0)), + &dictionary, + std::slice::from_ref(&candidate) + ), + Outcome::Matched(0) + ); + // B alone also identifies the track through the featured credit. + let b_only = known(&["B", "C"]); + assert_eq!( + outcome( + &source("Song", "C & B", Some("Album"), Some(200.0)), + &b_only, + &[candidate] + ), + Outcome::Matched(0) + ); + + // Known as a whole: "Tyler, The Creator" is one artist and matches as such. + let tyler = known(&["Tyler, The Creator", "Tyler"]); + let song = |artist: &str| local("EARFQUAKE", artist, "IGOR", Some(190.0)); + let src = source("EARFQUAKE", "Tyler, The Creator", Some("IGOR"), Some(190.0)); + assert_eq!( + outcome(&src, &tyler, &[song("Tyler, The Creator")]), + Outcome::Matched(0) + ); + assert_eq!( + outcome(&src, &tyler, &[song("Tyler")]), + Outcome::Unmatched(NOT_FOUND) + ); + + // An unknown part keeps "Foo, Bar" whole, so it does not match Foo. + let foo = known(&["Foo"]); + assert_eq!( + outcome( + &source("Song", "Foo, Bar", Some("Album"), Some(200.0)), + &foo, + &[local("Song", "Foo", "Album", Some(200.0))] + ), + Outcome::Unmatched(NOT_FOUND) + ); +} + +#[test] +fn single_candidates_follow_the_same_rules() { + assert_eq!( + single( + source("Song", "A", Some("Album"), Some(200.0)), + local("Song", "A", "Album", Some(200.0)) + ), + Outcome::Matched(0) + ); + assert_eq!( + single( + source("Song", "A", Some("Album"), None), + federated("Song", "A", "Other", None, "b3:1") + ), + Outcome::Ambiguous + ); +} + +#[test] +fn titles_split_into_core_featured_and_tags() { + let parsed = parse_title("Song (feat. X & Y) - Remastered 2011"); + assert_eq!(parsed.core, "Song"); + assert_eq!(parsed.featured, ["X & Y"]); + assert_eq!( + parsed.tags.editorial.iter().collect::>(), + ["remaster:2011"] + ); + + let parsed = parse_title("Song (with Somebody) [Live at Wembley / 1986 Remaster]"); + assert_eq!(parsed.core, "Song"); + assert_eq!(parsed.featured, ["Somebody"]); + assert!(parsed.tags.hard.contains("live")); + assert!(parsed.tags.editorial.contains("remaster:1986")); + + let parsed = parse_title("Song feat. X - Club Mix"); + assert_eq!( + (parsed.core.as_str(), parsed.featured.as_slice()), + ("Song", &["X".to_owned()][..]) + ); + assert!(parsed.tags.hard.contains("mix:club")); + + for (title, tag) in [ + ("Song - Acoustic Version", "acoustic"), + ("Song (Instrumental)", "instrumental"), + ("Song - Demo", "demo"), + ("Song (Extended Mix)", "extended"), + ("Song (Sped Up)", "sped_up"), + ("Song (Slowed + Reverb)", "slowed"), + ("Song - Radio Version", "edit"), + ("Song (Taylor's Version)", "version:taylor s"), + ] { + assert!(parse_title(title).tags.hard.contains(tag), "{title}"); + } + for (title, tag) in [ + ("Song - Single Version", "version"), + ("Song (Bonus Track)", "bonus"), + ("Song - Original Mix", "original_mix"), + ("Song - From \"Some Film\"", "from"), + ] { + let parsed = parse_title(title); + assert!( + parsed.tags.soft.contains(tag) && parsed.tags.hard.is_empty(), + "{title}" + ); + } + // Unknown decorations and markers inside the title stay in the core. + assert_eq!(parse_title("Live and Let Die").core, "Live and Let Die"); + assert_eq!( + parse_title("Movement I - Allegro").core, + "Movement I - Allegro" + ); + assert_eq!(parse_title("(Live)").core, "(Live)"); + assert_eq!( + parse_title("Song (Clean Bandit Remix)") + .tags + .editorial + .len(), + 0 + ); +} + +#[test] +fn album_titles_carry_version_markers() { + let album = parse_album("Abbey Road (Remastered 2009)"); + assert_eq!(album.key.key, "abbey road"); + assert!(album.tags.editorial.contains("remaster:2009")); + for title in [ + "Live at Leeds", + "Live", + "Live 1975-85", + "MTV Unplugged", + "Queen in Concert", + "Album (Live)", + ] { + assert!(parse_album(title).tags.hard.contains("live"), "{title}"); + } + for title in ["Live Through This", "Alive 2007", "Abbey Road"] { + assert!(parse_album(title).tags.hard.is_empty(), "{title}"); + } + assert!( + parse_album("Album (Super Deluxe Edition)") + .tags + .soft + .contains("deluxe") + ); +} diff --git a/src/library_import/mod.rs b/src/library_import/mod.rs index 7056093..ecd6b9b 100644 --- a/src/library_import/mod.rs +++ b/src/library_import/mod.rs @@ -11,9 +11,11 @@ pub mod adapters; mod handlers; pub mod job; +pub mod matcher; #[allow(dead_code)] pub mod model; pub mod providers; +pub mod resolver; #[allow(dead_code)] pub mod store; diff --git a/src/library_import/resolver.rs b/src/library_import/resolver.rs new file mode 100644 index 0000000..420e45f --- /dev/null +++ b/src/library_import/resolver.rs @@ -0,0 +1,752 @@ +//! Resolver stages 1–2 (plan §6): the local library and the federated tracks +//! this server already knows. Neither stage touches the network. The network +//! (stage 3, artist catalogues of peers) is reached only through +//! [`FederationAccess`], so an import without consent provably makes no +//! network calls. +//! +//! Library SQL lives here; the import tables are written by `store.rs`. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use anyhow::Result; +use music_dht::device_sync::SyncedFedTrack; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::{PgPool, Row}; + +use super::matcher::{ + self, Candidate, Decision, KnownArtists, NameKey, Origin, PreparedCandidate, PreparedSource, + Ranked, Source, +}; +use super::model::{ItemMetadata, PublicationStatus, ResolutionStatus}; +use super::store::{PendingEntry, Resolution}; + +/// The network side of the resolver. +#[async_trait::async_trait] +pub trait FederationAccess: Send + Sync { + /// Whether the federation node runs and can search the network. + async fn is_running(&self) -> bool; +} + +/// The process-wide federation node. +pub struct NodeFederation; + +#[async_trait::async_trait] +impl FederationAccess for NodeFederation { + async fn is_running(&self) -> bool { + crate::federation::handle().is_running().await + } +} + +/// Up to this many artist names are looked up by name patterns. +const ARTIST_PATTERNS: usize = 300; +/// Library tracks found by title for an entry whose artist is not in the library. +const TITLE_CANDIDATES: i64 = 20; +/// Entries resolved and written together. +const MAX_GROUP: usize = 500; +/// Drops combining diacritical marks in SQL, like [`matcher::folded`]. +const FOLD_SQL: &str = "'[\\u0300-\\u036f]'"; + +/// A pending entry with its prepared source. +pub struct Entry { + pub id: i64, + source: PreparedSource, +} + +/// Entries of one resolver pass, grouped by their main artist. +pub struct Prepared { + pub resolver: Resolver, + pub groups: Vec>, + /// Entries whose stored metadata cannot be read. + pub invalid: Vec, +} + +#[derive(Debug, Clone)] +struct LocalTrack { + track_id: i64, + media_file_id: i64, + content_id: Option, + candidate: Candidate, +} + +struct KnownTrack { + fed: SyncedFedTrack, + candidate: Candidate, + prepared: PreparedCandidate, +} + +/// Lookups shared by all groups of one pass. +pub struct Resolver { + known: KnownArtists, + /// Library artist ids by name key and folded key. + artist_ids: HashMap>, + federated: Vec, + /// Indexes into `federated` by artist key and folded key. + federated_by_artist: HashMap>, + storage_dir: String, +} + +fn keys_of(name: &str) -> impl Iterator { + let name = NameKey::new(name); + let folded = (name.folded != name.key).then_some(name.folded); + std::iter::once(name.key).chain(folded) +} + +impl Resolver { + /// Reads the pending entries and loads the library artists and the known + /// federated tracks of their artists. + pub async fn prepare( + pool: &PgPool, + user_id: i64, + entries: Vec, + storage_dir: String, + ) -> Result { + let mut parsed = Vec::with_capacity(entries.len()); + let mut invalid = Vec::new(); + for entry in entries { + match serde_json::from_value::(entry.metadata) { + Ok(metadata) if !metadata.title.trim().is_empty() => { + parsed.push((entry.id, entry.artist_key, metadata)); + } + _ => invalid.push(Resolution::failed(entry.id, "invalid_metadata")), + } + } + let mut names = BTreeSet::new(); + for (_, _, metadata) in &parsed { + let featured = matcher::parse_title(&metadata.title).featured; + for raw in metadata.artists.iter().chain(&featured) { + names.extend(matcher::artist_name_variants(raw)); + } + } + let wanted: HashSet = names + .iter() + .flat_map(|name| keys_of(name)) + .filter(|key| !key.is_empty()) + .collect(); + let names: Vec = names.into_iter().collect(); + + let mut known = KnownArtists::default(); + let mut artist_ids: HashMap> = HashMap::new(); + for (id, name) in load_artists(pool, &names, &wanted).await? { + known.insert(&name); + for key in keys_of(&name) { + artist_ids.entry(key).or_default().push(id); + } + } + let tracks = load_known_federated(pool, user_id, &wanted).await?; + for (fed, _) in &tracks { + for name in fed.artist_names.iter().chain(&fed.featured_artist_names) { + known.insert(name); + } + } + let mut federated = Vec::with_capacity(tracks.len()); + let mut federated_by_artist: HashMap> = HashMap::new(); + for (fed, owners) in tracks { + let candidate = Candidate { + origin: Origin::Federation, + title: fed.title.clone(), + artists: fed.artist_names.clone(), + featured_artists: fed.featured_artist_names.clone(), + album: fed.release_title.clone(), + duration_seconds: fed.duration_seconds.map(|seconds| seconds as f64), + content_id: Some(fed.content_id.clone()), + owners, + }; + let prepared = PreparedCandidate::new(&candidate, &known); + let index = federated.len(); + for name in fed.artist_names.iter().chain(&fed.featured_artist_names) { + for name in matcher::split_artists(name, &known) { + for key in keys_of(&name) { + let indexes = federated_by_artist.entry(key).or_default(); + if indexes.last() != Some(&index) { + indexes.push(index); + } + } + } + } + federated.push(KnownTrack { + fed, + candidate, + prepared, + }); + } + + let mut groups: Vec> = Vec::new(); + let mut current_key: Option> = None; + for (id, artist_key, metadata) in parsed { + let source = PreparedSource::new( + &Source { + title: metadata.title, + artists: metadata.artists, + album: metadata.album, + duration_ms: metadata.duration_ms, + }, + &known, + ); + let same_group = current_key.as_ref() == Some(&artist_key) + && groups.last().is_some_and(|group| group.len() < MAX_GROUP); + if !same_group { + groups.push(Vec::new()); + current_key = Some(artist_key); + } + groups + .last_mut() + .expect("a group was just pushed") + .push(Entry { id, source }); + } + Ok(Prepared { + resolver: Self { + known, + artist_ids, + federated, + federated_by_artist, + storage_dir, + }, + groups, + invalid, + }) + } + + fn library_artists(&self, entry: &Entry) -> Vec { + entry + .source + .artist_names() + .iter() + .flat_map(|name| keys_of(name)) + .filter_map(|key| self.artist_ids.get(&key)) + .flatten() + .copied() + .collect() + } + + fn federated_candidates(&self, entry: &Entry, exclude: &HashSet<&str>) -> Vec<&KnownTrack> { + let mut indexes: Vec = entry + .source + .artist_names() + .iter() + .flat_map(|name| keys_of(name)) + .filter_map(|key| self.federated_by_artist.get(&key)) + .flatten() + .copied() + .collect(); + indexes.sort_unstable(); + indexes.dedup(); + indexes + .into_iter() + .map(|index| &self.federated[index]) + .filter(|track| track.prepared.title_key().matches(entry.source.title_key())) + .filter(|track| !exclude.contains(track.fed.content_id.as_str())) + .collect() + } + + /// Decides every entry of a group: the local library first (stage 1), + /// then together with the known federated tracks (stage 2). + pub async fn resolve_group(&self, pool: &PgPool, group: &[Entry]) -> Result> { + let mut artist_ids = BTreeSet::new(); + let mut by_title = Vec::new(); + for entry in group { + let found = self.library_artists(entry); + if found.is_empty() && !entry.source.search_title().trim().is_empty() { + by_title.push(entry.source.search_title().to_owned()); + } + artist_ids.extend(found); + } + let mut track_ids: BTreeSet = BTreeSet::new(); + if !artist_ids.is_empty() { + let ids: Vec = artist_ids.into_iter().collect(); + track_ids.extend(artist_track_ids(pool, &ids).await?); + } + if !by_title.is_empty() { + track_ids.extend(title_track_ids(pool, &by_title).await?); + } + let ids: Vec = track_ids.into_iter().collect(); + let tracks = if ids.is_empty() { + Vec::new() + } else { + local_tracks(pool, &ids).await? + }; + let prepared: Vec = tracks + .iter() + .map(|track| PreparedCandidate::new(&track.candidate, &self.known)) + .collect(); + let mut by_key: HashMap<&str, Vec> = HashMap::new(); + for (index, candidate) in prepared.iter().enumerate() { + let title = candidate.title_key(); + by_key.entry(title.key.as_str()).or_default().push(index); + if title.folded != title.key { + by_key.entry(title.folded.as_str()).or_default().push(index); + } + } + + let mut resolutions = Vec::with_capacity(group.len()); + for entry in group { + let title = entry.source.title_key(); + let mut local: Vec = [title.key.as_str(), title.folded.as_str()] + .iter() + .filter_map(|key| by_key.get(key)) + .flatten() + .copied() + .collect(); + local.sort_unstable(); + local.dedup(); + let local_prepared: Vec<&PreparedCandidate> = + local.iter().map(|index| &prepared[*index]).collect(); + let mut decision = matcher::decide(&entry.source, &local_prepared); + let mut federated = Vec::new(); + if !matches!(decision, Decision::Matched(_)) { + let exclude: HashSet<&str> = local + .iter() + .filter_map(|index| tracks[*index].content_id.as_deref()) + .collect(); + federated = self.federated_candidates(entry, &exclude); + if !federated.is_empty() { + let combined: Vec<&PreparedCandidate> = local_prepared + .iter() + .copied() + .chain(federated.iter().map(|track| &track.prepared)) + .collect(); + decision = matcher::decide(&entry.source, &combined); + } + } + let chosen = |index: usize| Chosen::pick(&local, &tracks, &federated, index); + resolutions.push(match decision { + Decision::Matched(ranked) => { + self.matched(pool, entry.id, ranked, chosen(ranked.index)) + .await + } + Decision::Ambiguous(ranked) => Resolution { + score: ranked.first().map(|best| best.score), + candidates: Some(Value::Array( + ranked + .iter() + .map(|ranked| candidate_json(ranked, chosen(ranked.index))) + .collect(), + )), + ..Resolution::new(entry.id, ResolutionStatus::Ambiguous) + }, + Decision::Unmatched { reason } => Resolution { + note: Some(reason.to_owned()), + ..Resolution::new(entry.id, ResolutionStatus::Unmatched) + }, + }); + } + Ok(resolutions) + } + + async fn matched( + &self, + pool: &PgPool, + item_id: i64, + ranked: Ranked, + chosen: Chosen<'_>, + ) -> Resolution { + let base = Resolution { + score: Some(ranked.score), + publication: PublicationStatus::Pending, + ..Resolution::new(item_id, ResolutionStatus::Matched) + }; + match chosen { + Chosen::Local(track) => { + let content_id = match &track.content_id { + Some(content_id) => Some(content_id.clone()), + // Only the chosen track is hashed, one file at a time. + None => match crate::federation::ensure_local_content_id( + pool, + &self.storage_dir, + track.media_file_id, + ) + .await + { + Ok(content_id) => content_id, + Err(error) => { + tracing::warn!( + item_id, + media_file_id = track.media_file_id, + %error, + "library import could not compute a content id" + ); + return Resolution::failed(item_id, "content_id_failed"); + } + }, + }; + Resolution { + origin: Some(Origin::Local.as_str()), + track_id: Some(track.track_id), + publication: if content_id.is_some() { + PublicationStatus::Pending + } else { + PublicationStatus::NoContentId + }, + content_id, + ..base + } + } + Chosen::Federated(track) => Resolution { + origin: Some(Origin::Federation.as_str()), + content_id: Some(track.fed.content_id.clone()), + fed: serde_json::to_value(&track.fed).ok(), + ..base + }, + } + } +} + +/// The track behind a candidate index: local candidates come first. +enum Chosen<'a> { + Local(&'a LocalTrack), + Federated(&'a KnownTrack), +} + +impl<'a> Chosen<'a> { + fn pick( + local: &[usize], + tracks: &'a [LocalTrack], + federated: &[&'a KnownTrack], + index: usize, + ) -> Self { + match local.get(index) { + Some(local_index) => Self::Local(&tracks[*local_index]), + None => Self::Federated(federated[index - local.len()]), + } + } +} + +/// A candidate offered for manual selection. +fn candidate_json(ranked: &Ranked, chosen: Chosen<'_>) -> Value { + let (candidate, track_id, fed) = match chosen { + Chosen::Local(track) => (&track.candidate, Some(track.track_id), None), + Chosen::Federated(track) => ( + &track.candidate, + None, + serde_json::to_value(&track.fed).ok(), + ), + }; + json!({ + "origin": candidate.origin, + "level": ranked.level, + "score": ranked.score, + "title": candidate.title, + "artists": candidate.artists, + "featured_artists": candidate.featured_artists, + "album": candidate.album, + "duration_seconds": candidate.duration_seconds, + "content_id": candidate.content_id, + "track_id": track_id, + "fed": fed, + }) +} + +fn longest_token(key: &str) -> Option<&str> { + key.split(' ') + .filter(|token| !token.is_empty()) + .max_by_key(|token| token.chars().count()) +} + +/// Library artists named like any of `names` (stage 1a). As in the +/// federation's local catalogue, a literal token narrows the rows and the +/// Unicode comparison happens in Rust. A large import compares every visible +/// artist instead: one scan is cheaper than hundreds of patterns per row. +async fn load_artists( + pool: &PgPool, + names: &[String], + wanted: &HashSet, +) -> sqlx::Result> { + let rows = if names.len() > ARTIST_PATTERNS { + sqlx::query("SELECT id, name::text FROM furumusic__artist WHERE NOT is_hidden") + .fetch_all(pool) + .await? + } else { + let mut patterns = BTreeSet::new(); + let mut folded_patterns = BTreeSet::new(); + for name in names { + if let Some(token) = longest_token(&music_dht::normalize_name(name)) { + patterns.insert(format!("%{token}%")); + } + if let Some(token) = longest_token(&matcher::folded(name)) { + folded_patterns.insert(format!("%{token}%")); + } + } + if patterns.is_empty() && folded_patterns.is_empty() { + return Ok(Vec::new()); + } + sqlx::query(&format!( + "SELECT id, name::text FROM furumusic__artist + WHERE NOT is_hidden + AND (name_sort LIKE ANY($1) OR name IS NOT NFKC NORMALIZED + OR regexp_replace(normalize(name_sort::text, NFD), {FOLD_SQL}, '', 'g') + LIKE ANY($2))" + )) + .bind(patterns.into_iter().collect::>()) + .bind(folded_patterns.into_iter().collect::>()) + .fetch_all(pool) + .await? + }; + Ok(rows + .into_iter() + .filter_map(|row| { + let name: String = row.get(1); + let key = NameKey::new(&name); + (wanted.contains(&key.key) || wanted.contains(&key.folded)).then(|| (row.get(0), name)) + }) + .collect()) +} + +/// Tracks credited to the artists, as main or featured, and tracks of their +/// releases (stage 1b). +async fn artist_track_ids(pool: &PgPool, artist_ids: &[i64]) -> sqlx::Result> { + sqlx::query_scalar( + "SELECT track_id FROM furumusic__track_artist + WHERE artist_id = ANY($1) AND role IN ('main', 'featuring') + UNION + SELECT t.id FROM furumusic__track t + JOIN furumusic__release_artist ra ON ra.release_id = t.release_id + WHERE ra.artist_id = ANY($1)", + ) + .bind(artist_ids) + .fetch_all(pool) + .await +} + +/// Tracks with a similar title for entries whose artist is not in the +/// library (stage 1c), up to [`TITLE_CANDIDATES`] per title. +async fn title_track_ids(pool: &PgPool, titles: &[String]) -> sqlx::Result> { + sqlx::query_scalar( + "SELECT DISTINCT hit.id + FROM unnest($1::text[]) AS query(title) + CROSS JOIN LATERAL ( + SELECT t.id FROM furumusic__track t + WHERE NOT t.is_hidden AND query.title <% t.title_sort::text + ORDER BY word_similarity(query.title, t.title_sort::text) DESC, t.id + LIMIT $2) hit", + ) + .bind(titles) + .bind(TITLE_CANDIDATES) + .fetch_all(pool) + .await +} + +async fn local_tracks(pool: &PgPool, ids: &[i64]) -> sqlx::Result> { + let rows = sqlx::query( + "SELECT t.id, m.id, c.content_id, t.title::text, r.title::text, t.duration_seconds, + ARRAY(SELECT a.name::text FROM furumusic__track_artist ta + JOIN furumusic__artist a ON a.id = ta.artist_id + WHERE ta.track_id = t.id AND ta.role = 'main' AND NOT a.is_hidden + ORDER BY ta.position, a.id), + ARRAY(SELECT a.name::text FROM furumusic__track_artist ta + JOIN furumusic__artist a ON a.id = ta.artist_id + WHERE ta.track_id = t.id AND ta.role = 'featuring' AND NOT a.is_hidden + ORDER BY ta.position, a.id), + ARRAY(SELECT a.name::text FROM furumusic__release_artist ra + JOIN furumusic__artist a ON a.id = ra.artist_id + WHERE ra.release_id = r.id AND NOT a.is_hidden + ORDER BY ra.position, a.id) + FROM furumusic__track t + JOIN furumusic__release r ON r.id = t.release_id AND NOT r.is_hidden + JOIN furumusic__media_file m ON m.id = t.audio_file_id + LEFT JOIN furumusic__federation_content_id_cache c + ON c.media_file_id = m.id AND c.sha256_hash = m.sha256_hash + WHERE t.id = ANY($1) AND NOT t.is_hidden + ORDER BY t.id", + ) + .bind(ids) + .fetch_all(pool) + .await?; + Ok(rows + .into_iter() + .map(|row| { + let content_id: Option = row.get(2); + let content_id = content_id + .as_deref() + .and_then(music_dht::normalize_content_id); + let main: Vec = row.get(6); + let release_artists: Vec = row.get(8); + let duration: f64 = row.get(5); + LocalTrack { + track_id: row.get(0), + media_file_id: row.get(1), + candidate: Candidate { + origin: Origin::Local, + title: row.get(3), + // Tracks without credits belong to their release artists. + artists: if main.is_empty() { + release_artists + } else { + main + }, + featured_artists: row.get(7), + album: row.get(4), + duration_seconds: (duration > 0.0).then_some(duration), + content_id: content_id.clone(), + owners: 0, + }, + content_id, + } + }) + .collect()) +} + +#[derive(Deserialize)] +struct RefArtist { + #[serde(default)] + name: String, +} + +#[derive(Deserialize)] +struct RefRelease { + #[serde(default)] + title: Option, +} + +/// `furumusic__track_ref.metadata_json` as written by the federation search. +#[derive(Deserialize)] +struct RefMetadata { + #[serde(default)] + title: String, + #[serde(default)] + artists: Vec, + #[serde(default)] + featured_artists: Vec, + #[serde(default)] + release: Option, + #[serde(default)] + year: Option, + #[serde(default)] + duration_seconds: Option, + #[serde(default)] + track_number: Option, + #[serde(default)] + disc_number: Option, +} + +/// A federated source the web player can show and the network can serve: +/// not the web player's own metadata of a local track. +fn usable_source(owner: &str, item_id: &str) -> bool { + !owner.trim().is_empty() + && !item_id.trim().is_empty() + && owner != "WEB" + && !item_id.starts_with("web:") +} + +fn jsonb_array(path: &str) -> String { + format!("CASE WHEN jsonb_typeof({path}) = 'array' THEN {path} ELSE '[]'::jsonb END") +} + +/// Federated tracks this server already knows, by the artists' keys (stage 2): +/// search results in `track_ref` with their freshest source, and the import +/// owner's own likes and playlist entries from Device Sync. +async fn load_known_federated( + pool: &PgPool, + user_id: i64, + wanted: &HashSet, +) -> sqlx::Result> { + if wanted.is_empty() { + return Ok(Vec::new()); + } + let keys: Vec<&str> = wanted.iter().map(String::as_str).collect(); + let artists = format!( + "{} || {}", + jsonb_array("r.metadata_json->'artists'"), + jsonb_array("r.metadata_json->'featured_artists'") + ); + let rows = sqlx::query(&format!( + "SELECT r.content_id, r.metadata_json, src.owner_peer_id, src.item_id, src.owners + FROM furumusic__track_ref r + CROSS JOIN LATERAL ( + SELECT s.owner_peer_id, s.item_id, count(*) OVER () AS owners + FROM furumusic__federation_track_source s + WHERE s.track_ref_id = r.id AND s.owner_peer_id <> 'WEB' + AND s.item_id NOT LIKE 'web:%' + ORDER BY s.last_seen_ms DESC, s.owner_peer_id, s.item_id + LIMIT 1) src + WHERE r.id IN ( + SELECT r.id FROM furumusic__track_ref r + CROSS JOIN LATERAL jsonb_array_elements({artists}) artist + CROSS JOIN LATERAL (VALUES + (replace(artist->'key'->>'normalized_name', 'ё', 'е')), + (regexp_replace(normalize(artist->'key'->>'normalized_name', NFD), + {FOLD_SQL}, '', 'g'))) name(key) + WHERE name.key IN (SELECT unnest($1::text[])))" + )) + .bind(&keys) + .fetch_all(pool) + .await?; + let mut seen = HashSet::new(); + let mut tracks = Vec::new(); + for row in rows { + let content_id: String = row.get(0); + let Some(content_id) = music_dht::normalize_content_id(&content_id) else { + continue; + }; + let Ok(metadata) = serde_json::from_value::(row.get(1)) else { + continue; + }; + let owner: String = row.get(2); + let item_id: String = row.get(3); + let owners: i64 = row.get(4); + if metadata.title.trim().is_empty() || !usable_source(&owner, &item_id) { + continue; + } + let names = |artists: Vec| -> Vec { + artists + .into_iter() + .map(|artist| artist.name) + .filter(|name| !name.trim().is_empty()) + .collect() + }; + if seen.insert(content_id.clone()) { + tracks.push(( + SyncedFedTrack { + item_id, + owner, + title: metadata.title, + artist_names: names(metadata.artists), + featured_artist_names: names(metadata.featured_artists), + year: metadata.year, + duration_seconds: metadata + .duration_seconds + .filter(|seconds| seconds.is_finite() && *seconds > 0.0) + .map(|seconds| seconds.round() as i64), + content_id, + release_title: metadata.release.and_then(|release| release.title), + track_number: metadata.track_number, + disc_number: metadata.disc_number, + }, + u32::try_from(owners).unwrap_or(u32::MAX), + )); + } + } + let own: Vec = sqlx::query_scalar( + "SELECT fed_json FROM furumusic__fed_state_like + WHERE user_id = $1 AND fed_json IS NOT NULL + UNION ALL + SELECT fed_json FROM furumusic__fed_state_playlist_item + WHERE user_id = $1 AND fed_json IS NOT NULL", + ) + .bind(user_id) + .fetch_all(pool) + .await?; + for value in own { + let Ok(mut fed) = serde_json::from_value::(value) else { + continue; + }; + let Some(content_id) = music_dht::normalize_content_id(&fed.content_id) else { + continue; + }; + let by_wanted_artist = fed + .artist_names + .iter() + .chain(&fed.featured_artist_names) + .flat_map(|name| keys_of(name)) + .any(|key| wanted.contains(&key)); + if fed.title.trim().is_empty() + || !usable_source(&fed.owner, &fed.item_id) + || !by_wanted_artist + || !seen.insert(content_id.clone()) + { + continue; + } + fed.content_id = content_id; + tracks.push((fed, 1)); + } + Ok(tracks) +} diff --git a/src/library_import/store.rs b/src/library_import/store.rs index eac9b67..976dcbf 100644 --- a/src/library_import/store.rs +++ b/src/library_import/store.rs @@ -775,6 +775,152 @@ pub async fn resume_after_reauth( Ok(outcome) } +// --------------------------------------------------------------------------- +// Worker: resolution +// --------------------------------------------------------------------------- + +/// An entry waiting for the resolver. +#[derive(Debug, Clone)] +pub struct PendingEntry { + pub id: i64, + pub artist_key: Option, + pub metadata: Value, +} + +/// Pending entries of an import, grouped by their main artist. +pub async fn pending_entries(pool: &PgPool, import_id: i64) -> sqlx::Result> { + let rows = sqlx::query( + "SELECT i.id, i.artist_key, i.metadata + FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 AND i.resolution_status = 'pending' + ORDER BY i.artist_key NULLS LAST, i.id", + ) + .bind(import_id) + .fetch_all(pool) + .await?; + Ok(rows + .into_iter() + .map(|row| PendingEntry { + id: row.get(0), + artist_key: row.get(1), + metadata: row.get(2), + }) + .collect()) +} + +/// The resolver's decision for one entry. +#[derive(Debug, Clone, PartialEq)] +pub struct Resolution { + pub item_id: i64, + pub status: ResolutionStatus, + pub note: Option, + /// `local` or `federation` for a match. + pub origin: Option<&'static str>, + pub score: Option, + pub content_id: Option, + pub track_id: Option, + /// `SyncedFedTrack` of a federated match. + pub fed: Option, + pub candidates: Option, + pub publication: PublicationStatus, +} + +impl Resolution { + /// A decision without a match and without a note. + pub fn new(item_id: i64, status: ResolutionStatus) -> Self { + Self { + item_id, + status, + note: None, + origin: None, + score: None, + content_id: None, + track_id: None, + fed: None, + candidates: None, + publication: PublicationStatus::NotReady, + } + } + + /// An entry that could not be processed; Resync tries it again. + pub fn failed(item_id: i64, note: &str) -> Self { + Self { + note: Some(note.to_owned()), + ..Self::new(item_id, ResolutionStatus::Failed) + } + } +} + +/// Stores decisions for pending entries in one transaction and refreshes the +/// counters. Entries that are no longer pending keep their state. `false` +/// when the worker no longer owns the import. +pub async fn store_resolutions( + pool: &PgPool, + import_id: i64, + run_id: i64, + resolutions: &[Resolution], +) -> sqlx::Result { + let mut tx = pool.begin().await?; + let owned: Option = sqlx::query_scalar( + "SELECT id FROM furumusic__library_import + WHERE id = $1 AND lease_owner = $2 AND status = 'running' FOR SHARE", + ) + .bind(import_id) + .bind(run_id) + .fetch_optional(&mut *tx) + .await?; + if owned.is_none() { + return Ok(false); + } + for chunk in resolutions.chunks(INSERT_CHUNK) { + let ids: Vec = chunk.iter().map(|r| r.item_id).collect(); + let statuses: Vec<&str> = chunk.iter().map(|r| r.status.as_str()).collect(); + let notes: Vec> = chunk.iter().map(|r| r.note.as_deref()).collect(); + let origins: Vec> = chunk.iter().map(|r| r.origin).collect(); + let scores: Vec> = chunk.iter().map(|r| r.score).collect(); + let content_ids: Vec> = + chunk.iter().map(|r| r.content_id.as_deref()).collect(); + let track_ids: Vec> = chunk.iter().map(|r| r.track_id).collect(); + let fed: Vec> = chunk.iter().map(|r| r.fed.as_ref()).collect(); + let candidates: Vec> = chunk.iter().map(|r| r.candidates.as_ref()).collect(); + let publication: Vec<&str> = chunk.iter().map(|r| r.publication.as_str()).collect(); + sqlx::query( + "UPDATE furumusic__library_import_item i + SET resolution_status = r.status, resolution_note = r.note, + match_origin = r.origin, + match_method = CASE WHEN r.status = 'matched' THEN 'auto' END, + match_score = r.score, matched_content_id = r.content_id, + matched_track_id = r.track_id, matched_fed = r.fed, + candidates = r.candidates, publication_status = r.publication, + last_attempt_at = now(), attempt_count = i.attempt_count + 1 + FROM UNNEST($2::int8[], $3::text[], $4::text[], $5::text[], $6::float4[], + $7::text[], $8::int8[], $9::jsonb[], $10::jsonb[], $11::text[]) + AS r(id, status, note, origin, score, content_id, track_id, fed, + candidates, publication), + furumusic__library_import_playlist p + WHERE i.id = r.id AND p.id = i.import_playlist_id AND p.import_id = $1 + AND i.resolution_status = 'pending'", + ) + .bind(import_id) + .bind(&ids) + .bind(&statuses) + .bind(¬es) + .bind(&origins) + .bind(&scores) + .bind(&content_ids) + .bind(&track_ids) + .bind(&fed) + .bind(&candidates) + .bind(&publication) + .execute(&mut *tx) + .await?; + } + refresh_statistics(&mut tx, import_id).await?; + tx.commit().await?; + Ok(true) +} + // --------------------------------------------------------------------------- // Owner requests // --------------------------------------------------------------------------- diff --git a/src/library_import/tests.rs b/src/library_import/tests.rs index 0929ec3..aa6818a 100644 --- a/src/library_import/tests.rs +++ b/src/library_import/tests.rs @@ -19,6 +19,7 @@ use super::model::{ use super::providers::{ AccessToken, Connection, FetchError, FetchTarget, LibraryFetcher, TOKEN_TTL, TokenVault, }; +use super::resolver::FederationAccess; use super::store::{ self, CancelOutcome, Control, CreateImportError, DeleteOutcome, FinishOutcome, ItemFilter, NewImport, NewItem, NewPlaylist, ReauthOutcome, ReauthTarget, @@ -40,12 +41,17 @@ impl Fixture { let url = std::env::var("FURU_LIBRARY_IMPORT_TEST_DATABASE_URL") .expect("disposable database URL"); let admin = PgPool::connect(&url).await.unwrap(); + // Trigram operators of the resolver; the extension lives in `public`. + sqlx::query("CREATE EXTENSION IF NOT EXISTS pg_trgm SCHEMA public") + .execute(&admin) + .await + .unwrap(); let schema = format!("library_import_test_{}", uuid::Uuid::new_v4().simple()); sqlx::query(&format!("CREATE SCHEMA {schema}")) .execute(&admin) .await .unwrap(); - let search_path = format!("SET search_path TO {schema}"); + let search_path = format!("SET search_path TO {schema}, public"); let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(8) .after_connect(move |connection, _| { @@ -63,7 +69,40 @@ impl Fixture { CREATE TABLE furumusic__user(id BIGINT PRIMARY KEY); CREATE TABLE furumusic__playlist(id BIGSERIAL PRIMARY KEY, owner_id BIGINT NOT NULL, title TEXT NOT NULL); CREATE TABLE furumusic__job_run(id BIGINT PRIMARY KEY, status TEXT NOT NULL); - INSERT INTO furumusic__user VALUES (1), (2);", + INSERT INTO furumusic__user VALUES (1), (2); + -- The library and federation tables the resolver reads. + CREATE TABLE furumusic__artist(id BIGINT PRIMARY KEY, name TEXT NOT NULL, + name_sort TEXT NOT NULL, is_hidden BOOLEAN NOT NULL DEFAULT false); + CREATE TABLE furumusic__release(id BIGINT PRIMARY KEY, title TEXT NOT NULL, + year INTEGER, is_hidden BOOLEAN NOT NULL DEFAULT false); + CREATE TABLE furumusic__release_artist(release_id BIGINT NOT NULL, + artist_id BIGINT NOT NULL, position INTEGER NOT NULL DEFAULT 0); + CREATE TABLE furumusic__media_file(id BIGINT PRIMARY KEY, file_path TEXT NOT NULL, + sha256_hash TEXT NOT NULL); + CREATE TABLE furumusic__track(id BIGINT PRIMARY KEY, title TEXT NOT NULL, + title_sort TEXT NOT NULL, release_id BIGINT NOT NULL, + track_number INTEGER, disc_number INTEGER, + duration_seconds DOUBLE PRECISION NOT NULL, audio_file_id BIGINT NOT NULL, + is_hidden BOOLEAN NOT NULL DEFAULT false); + CREATE TABLE furumusic__track_artist(track_id BIGINT NOT NULL, + artist_id BIGINT NOT NULL, role TEXT NOT NULL, position INTEGER NOT NULL DEFAULT 0); + CREATE TABLE furumusic__federation_content_id_cache(media_file_id BIGINT PRIMARY KEY, + sha256_hash TEXT NOT NULL, content_id TEXT NOT NULL, updated_at TEXT NOT NULL); + CREATE TABLE furumusic__track_ref(id BIGSERIAL PRIMARY KEY, content_id TEXT UNIQUE, + local_track_id BIGINT, title TEXT, metadata_json JSONB NOT NULL DEFAULT '{}'); + CREATE TABLE furumusic__federation_track_source(track_ref_id BIGINT NOT NULL, + owner_peer_id TEXT NOT NULL, item_id TEXT NOT NULL, last_seen_ms BIGINT NOT NULL, + metadata_json JSONB NOT NULL DEFAULT '{}', PRIMARY KEY (owner_peer_id, item_id)); + CREATE TABLE furumusic__fed_state_like(user_id BIGINT NOT NULL, content_id TEXT NOT NULL, + liked BOOLEAN NOT NULL, hlc_ms BIGINT NOT NULL, op_id TEXT NOT NULL, + local_track_id BIGINT, fed_json JSONB, PRIMARY KEY (user_id, content_id)); + CREATE TABLE furumusic__fed_state_playlist_item(user_id BIGINT NOT NULL, + playlist_id TEXT NOT NULL, content_id TEXT NOT NULL, + present BOOLEAN NOT NULL DEFAULT true, position BIGINT NOT NULL DEFAULT 0, + hlc_ms BIGINT NOT NULL, op_id TEXT NOT NULL, local_track_id BIGINT, fed_json JSONB, + PRIMARY KEY (user_id, playlist_id, content_id)); + CREATE TABLE furumusic__track_content_alias(track_id BIGINT NOT NULL, content_id TEXT NOT NULL); + CREATE TABLE furumusic__user_liked_track(user_id BIGINT NOT NULL, track_id BIGINT NOT NULL);", ) .execute(&pool) .await @@ -184,6 +223,16 @@ fn mixed_playlist(key: &str) -> NewPlaylist { ) } +/// Fails the test on any use of the network side of the resolver. +struct NoNetwork; + +#[async_trait::async_trait] +impl FederationAccess for NoNetwork { + async fn is_running(&self) -> bool { + panic!("the resolver must not use the federation without consent"); + } +} + async fn run_worker(pool: &PgPool, run_id: i64) -> String { let mut log = JobLog::new(); job::run_worker(pool, Arc::new(AppConfig::default()), run_id, &mut log) @@ -810,6 +859,27 @@ async fn library_import_stores_every_entry_of_a_large_export() { ) .await; assert_eq!(artist_key, "artist 0"); + + // The resolver handles every entry; with 300 artists it scans the artist table. + sqlx::raw_sql( + "INSERT INTO furumusic__artist VALUES (7, 'Artist 7', 'artist 7', false); + INSERT INTO furumusic__release VALUES (7, 'Album 7', 2020, false); + INSERT INTO furumusic__media_file VALUES (7, 'artist/7.flac', 'sha-7'); + INSERT INTO furumusic__track VALUES (7, 'Song 7', 'song 7', 7, 1, 1, 200.0, 7, false); + INSERT INTO furumusic__track_artist VALUES (7, 7, 'main', 0);", + ) + .execute(pool) + .await + .unwrap(); + let log = run_worker(pool, 901).await; + assert!( + log.contains("resolved 4500 entries locally (2 matched, 0 ambiguous, 4498 unmatched"), + "{log}" + ); + let detail = store::get_import(pool, 1, id).await.unwrap().unwrap(); + assert_eq!(detail.summary.status, "done"); + assert_eq!(detail.summary.statistics["matched_local"], 2); + assert_eq!(detail.summary.statistics["no_content_id"], 2); db.drop().await; } @@ -1027,9 +1097,16 @@ async fn library_import_continues_the_same_api_import_after_signing_in_again() { let api = Arc::clone(&api); async move { let mut log = crate::scheduler::JobLog::new(); - job::run_worker_with(pool, Arc::new(AppConfig::default()), run_id, &mut log, api) - .await - .unwrap(); + job::run_worker_with( + pool, + Arc::new(AppConfig::default()), + run_id, + &mut log, + api, + Arc::new(NoNetwork), + ) + .await + .unwrap(); log.output() } }; @@ -1201,3 +1278,402 @@ async fn library_import_continues_the_same_api_import_after_signing_in_again() { ); db.drop().await; } + +fn b3(digit: char) -> String { + format!("b3:{}", digit.to_string().repeat(64)) +} + +fn timed( + position: u32, + title: &str, + artist: &str, + album: Option<&str>, + seconds: Option, +) -> ImportedTrack { + ImportedTrack { + album: album.map(Into::into), + duration_ms: seconds.map(|seconds| seconds * 1000), + ..track(position, title, artist, "") + } +} + +/// A small library: local tracks, tracks known from federated searches and +/// Device Sync state of two users. +async fn seed_library(pool: &PgPool) { + sqlx::raw_sql( + "INSERT INTO furumusic__artist VALUES + (1, 'Кино', 'кино', false), (2, 'Beyoncé', 'beyoncé', false), + (3, 'Queen', 'queen', false), (4, 'Tyler, The Creator', 'tyler, the creator', false), + (5, 'Tyler', 'tyler', false); + INSERT INTO furumusic__release VALUES + (1, 'Группа крови', 1988, false), (2, 'Lemonade', 2016, false), + (3, 'A Night at the Opera', 1975, false), (4, 'IGOR', 2019, false), + (5, 'Other', 2000, false); + INSERT INTO furumusic__release_artist VALUES (1, 1, 0), (2, 2, 0), (3, 3, 0), (4, 4, 0), (5, 5, 0); + INSERT INTO furumusic__media_file VALUES + (1, 'kino/blood.flac', 'sha-1'), (2, 'beyonce/formation.flac', 'sha-2'), + (3, 'queen/rhapsody.flac', 'sha-3'), (4, 'tyler/earfquake.flac', 'sha-4'), + (5, 'kino/cuckoo.flac', 'sha-5'), (6, 'tyler/other.flac', 'sha-6'); + INSERT INTO furumusic__track VALUES + (1, 'Группа крови', 'группа крови', 1, 1, 1, 285.0, 1, false), + (2, 'Formation', 'formation', 2, 1, 1, 206.0, 2, false), + (3, 'Bohemian Rhapsody', 'bohemian rhapsody', 3, 11, 1, 355.0, 3, false), + (4, 'EARFQUAKE', 'earfquake', 4, 1, 1, 190.0, 4, false), + (5, 'Кукушка', 'кукушка', 1, 2, 1, 400.0, 5, false), + (6, 'EARFQUAKE', 'earfquake', 5, 1, 1, 190.0, 6, false); + INSERT INTO furumusic__track_artist VALUES + (1, 1, 'main', 0), (2, 2, 'main', 0), (3, 3, 'main', 0), (4, 4, 'main', 0), + (5, 1, 'main', 0), (6, 5, 'main', 0);", + ) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO furumusic__federation_content_id_cache VALUES (2, 'sha-2', $1, '2026-01-01T00:00:00Z')", + ) + .bind(b3('a')) + .execute(pool) + .await + .unwrap(); + let aphex = + json!([{"key": {"normalized_name": "aphex twin"}, "name": "Aphex Twin", "local_id": null}]); + for (id, content_id, title, release) in [ + (1, b3('b'), "Windowlicker", "Windowlicker"), + (2, b3('c'), "Xtal", "Selected Ambient Works 85-92"), + ] { + sqlx::query( + "INSERT INTO furumusic__track_ref (id, content_id, title, metadata_json) VALUES ($1, $2, $3, $4)", + ) + .bind(id) + .bind(content_id) + .bind(title) + .bind(json!({"title": title, "artists": aphex, "featured_artists": [], + "release": {"title": release}, "duration_seconds": null})) + .execute(pool) + .await + .unwrap(); + } + // Two peers offer Windowlicker; Xtal is only the web player's own metadata. + sqlx::raw_sql( + "INSERT INTO furumusic__federation_track_source (track_ref_id, owner_peer_id, item_id, last_seen_ms) VALUES + (1, 'peer-a', 'item-1', 100), (1, 'peer-b', 'item-9', 200), (2, 'WEB', 'web:7', 300)", + ) + .execute(pool) + .await + .unwrap(); + for (user_id, content_id, title) in [(1, b3('d'), "Avril 14th"), (2, b3('e'), "Flim")] { + sqlx::query( + "INSERT INTO furumusic__fed_state_like VALUES ($1, $2, true, 1, 'op', NULL, $3)", + ) + .bind(user_id) + .bind(&content_id) + .bind( + json!({"item_id": "item-2", "owner": "peer-c", "title": title, + "artist_names": ["Aphex Twin"], "featured_artist_names": [], + "year": 2001, "duration_seconds": 125, "content_id": content_id, + "release_title": "Drukqs", "track_number": 1, "disc_number": 1}), + ) + .execute(pool) + .await + .unwrap(); + } +} + +type ItemRow = ( + String, + Option, + Option, + Option, + Option, + Option, + Option, + String, +); + +async fn resolved_items(pool: &PgPool, import_id: i64) -> Vec { + sqlx::query_as( + "SELECT i.resolution_status, i.resolution_note, i.match_origin, i.matched_content_id, + i.matched_track_id, i.matched_fed->>'owner', jsonb_array_length(i.candidates), + i.publication_status + FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 ORDER BY i.source_position", + ) + .bind(import_id) + .fetch_all(pool) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires FURU_LIBRARY_IMPORT_TEST_DATABASE_URL pointing to a disposable PostgreSQL database"] +async fn library_import_resolves_locally_without_the_network() { + let _serial = SERIAL.lock().await; + let fixture = Fixture::new().await; + let pool = &fixture.pool; + seed_library(pool).await; + let storage = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(storage.path().join("kino")).unwrap(); + std::fs::write(storage.path().join("kino/blood.flac"), b"kino-blood").unwrap(); + + let mut episode = track(9, "Episode", "Host", "Show"); + episode.kind = TrackKind::Episode; + let tracks = [ + timed(0, "Группа крови", "Кино", Some("Группа крови"), Some(285)), + timed(1, "Formation", "Beyonce", Some("Lemonade"), Some(206)), + timed( + 2, + "Bohemian Rhapsody - Remastered 2011", + "Queen", + Some("A Night At The Opera (2011 Remaster)"), + Some(355), + ), + timed( + 3, + "EARFQUAKE", + "Tyler, The Creator", + Some("IGOR"), + Some(190), + ), + timed(4, "Windowlicker", "Aphex Twin", Some("Windowlicker"), None), + timed( + 5, + "Xtal", + "Aphex Twin", + Some("Selected Ambient Works 85-92"), + None, + ), + timed(6, "Avril 14th", "Aphex Twin", Some("Drukqs"), Some(125)), + timed(7, "Flim", "Aphex Twin", Some("Come to Daddy"), Some(177)), + timed(8, "Formation", "Somebody Else", None, Some(206)), + episode, + ]; + let import_id = fixture + .create(1, "spotify", vec![playlist("local", "Mix", &tracks)]) + .await; + + // Local import with the federation disabled; any network use panics. + let config = AppConfig { + agent_storage_dir: storage.path().to_string_lossy().into_owned(), + federation_enabled: false, + ..AppConfig::default() + }; + let mut log = JobLog::new(); + job::run_worker_with( + pool, + Arc::new(config), + 501, + &mut log, + Arc::new(super::providers::ProviderFetchers), + Arc::new(NoNetwork), + ) + .await + .unwrap(); + let output = log.output(); + assert!( + output + .contains("resolved 9 entries locally (5 matched, 1 ambiguous, 3 unmatched, 0 failed)"), + "{output}" + ); + // The log carries ids and counters only. + for private in ["Кино", "Formation", "Aphex", "spotify:track"] { + assert!(!output.contains(private), "{output}"); + } + assert_eq!(fixture.status(import_id).await, "done"); + + let blood = format!("b3:{}", blake3::hash(b"kino-blood").to_hex()); + let s = |value: &str| Some(value.to_owned()); + let items = resolved_items(pool, import_id).await; + let expected: Vec = vec![ + // The content id of a local match is computed without the federation. + ( + "matched".into(), + None, + s("local"), + Some(blood.clone()), + Some(1), + None, + None, + "pending".into(), + ), + // Diacritics fold; the cached content id is used. + ( + "matched".into(), + None, + s("local"), + Some(b3('a')), + Some(2), + None, + None, + "pending".into(), + ), + // A remaster on one side only is left to the user. + ( + "ambiguous".into(), + None, + None, + None, + None, + None, + Some(1), + "not_ready".into(), + ), + // Known as a whole: the track of the artist "Tyler" is not a candidate. + // Its file is missing, so it cannot be published yet. + ( + "matched".into(), + None, + s("local"), + None, + Some(4), + None, + None, + "no_content_id".into(), + ), + // Known federated track: the album confirms it; the freshest source is used. + ( + "matched".into(), + None, + s("federation"), + Some(b3('b')), + None, + s("peer-b"), + None, + "pending".into(), + ), + // The web player's own metadata is not a federated source. + ( + "unmatched".into(), + s("not_found"), + None, + None, + None, + None, + None, + "not_ready".into(), + ), + // The import owner's federated like. + ( + "matched".into(), + None, + s("federation"), + Some(b3('d')), + None, + s("peer-c"), + None, + "pending".into(), + ), + // Another user's like is not used. + ( + "unmatched".into(), + s("not_found"), + None, + None, + None, + None, + None, + "not_ready".into(), + ), + // Found by title, but by another artist. + ( + "unmatched".into(), + s("not_found"), + None, + None, + None, + None, + None, + "not_ready".into(), + ), + ( + "unsupported".into(), + s("episode"), + None, + None, + None, + None, + None, + "not_ready".into(), + ), + ]; + assert_eq!(items, expected); + let cached: String = sqlx::query_scalar( + "SELECT content_id FROM furumusic__federation_content_id_cache WHERE media_file_id = 1 AND sha256_hash = 'sha-1'", + ) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(cached, blood); + let candidates: serde_json::Value = sqlx::query_scalar( + "SELECT i.candidates FROM furumusic__library_import_item i + JOIN furumusic__library_import_playlist p ON p.id = i.import_playlist_id + WHERE p.import_id = $1 AND i.source_position = 2", + ) + .bind(import_id) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(candidates[0]["track_id"], 3); + assert_eq!(candidates[0]["origin"], "local"); + assert_eq!(candidates[0]["level"], "weak"); + let statistics = store::get_import(pool, 1, import_id) + .await + .unwrap() + .unwrap() + .summary + .statistics; + assert_eq!(statistics["matched_local"], 3); + assert_eq!(statistics["matched_federation"], 2); + assert_eq!(statistics["ambiguous"], 1); + assert_eq!(statistics["unmatched"], 3); + assert_eq!(statistics["pending"], 0); + + // With consent but the federation disabled, the network is still not used. + let mut new = new_import( + 1, + "spotify", + vec![playlist( + "consent", + "Consent", + &[timed(0, "Кукушка", "Кино", Some("Группа крови"), Some(400))], + )], + ); + new.federated_search = true; + let consent_id = store::create_import(pool, &new).await.unwrap(); + let mut log = JobLog::new(); + job::run_worker_with( + pool, + Arc::new(AppConfig::default()), + 502, + &mut log, + Arc::new(super::providers::ProviderFetchers), + Arc::new(NoNetwork), + ) + .await + .unwrap(); + assert!( + log.output().contains("federation is disabled"), + "{}", + log.output() + ); + assert_eq!(fixture.status(consent_id).await, "done"); + // Without agent_storage_dir the match waits for its content id. + let items = resolved_items(pool, consent_id).await; + assert_eq!(items[0].0, "matched"); + assert_eq!(items[0].4, Some(5)); + assert_eq!(items[0].7, "no_content_id"); + + // A repeated pass leaves decided entries alone. + let before = resolved_items(pool, import_id).await; + sqlx::query( + "UPDATE furumusic__library_import SET status = 'queued', phase = NULL WHERE id = $1", + ) + .bind(import_id) + .execute(pool) + .await + .unwrap(); + run_worker(pool, 503).await; + assert_eq!(resolved_items(pool, import_id).await, before); + + fixture.drop().await; +}