use sea_orm::{ConnectionTrait, DatabaseConnection, DbBackend, QueryResult, Statement};
#[derive(Debug, Clone)]
pub struct SearchHit {
pub id: String,
pub channel_id: String,
pub title: String,
pub description: String,
pub thumbnail_url: String,
pub published_at: Option<chrono::DateTime<chrono::FixedOffset>>,
pub source: String,
pub score: f32,
pub match_tier: i32,
pub matched_by: String,
pub matched_field: Option<String>,
pub snippet: String,
pub start_ms: Option<i32>,
}
#[derive(Debug, Clone)]
pub struct SearchQuery {
pub text: String,
pub page: u32,
pub page_size: u32,
pub search_in: Option<Vec<String>>,
pub substring: bool,
pub channel_id: Option<String>,
pub text_config: String,
pub include_fuzzy: bool,
pub sort_by: SearchSort,
pub desc: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SearchSort {
#[default]
Relevance,
PublishedAt,
Title,
}
impl SearchSort {
pub fn as_str(&self) -> &'static str {
match self {
SearchSort::Relevance => "relevance",
SearchSort::PublishedAt => "published_at",
SearchSort::Title => "title",
}
}
pub fn all() -> [&'static str; 3] {
["relevance", "published_at", "title"]
}
pub fn parse(raw: &str) -> Result<Self, InvalidQuery> {
match raw.trim().to_lowercase().as_str() {
"relevance" | "relevance_score" | "best" => Ok(SearchSort::Relevance),
"published_at" | "published" | "date" | "newest" => Ok(SearchSort::PublishedAt),
"title" | "alphabetical" => Ok(SearchSort::Title),
other => Err(InvalidQuery(format!(
"unknown sort key {other:?}. Expected one of: {}",
SearchSort::all().join(", ")
))),
}
}
}
impl std::str::FromStr for SearchSort {
type Err = InvalidQuery;
fn from_str(s: &str) -> Result<Self, Self::Err> {
SearchSort::parse(s)
}
}
pub const SEARCH_FIELDS: [&str; 3] = ["title", "description", "tags"];
pub const DEFAULT_TEXT_CONFIG: &str = "english";
#[derive(Debug)]
pub struct InvalidQuery(pub String);
impl std::fmt::Display for InvalidQuery {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for InvalidQuery {}
pub const MAX_QUERY_CHARS: usize = 100;
pub const MIN_QUERY_CHARS: usize = 3;
pub fn validate_query(raw: &str) -> Result<String, InvalidQuery> {
let q = raw.trim();
if q.is_empty() {
return Err(InvalidQuery("q cannot be empty".into()));
}
if q.chars().count() < MIN_QUERY_CHARS {
return Err(InvalidQuery(format!(
"q must be at least {MIN_QUERY_CHARS} characters"
)));
}
if q.chars().count() > MAX_QUERY_CHARS {
return Err(InvalidQuery(format!(
"q must be {MAX_QUERY_CHARS} characters or less"
)));
}
let q: String = q
.chars()
.filter(|c| c.is_alphanumeric() || c.is_whitespace() || "-:'\"()".contains(*c))
.collect();
let q = q.trim().to_string();
if q.is_empty() {
return Err(InvalidQuery("q contains no searchable characters".into()));
}
Ok(q)
}
pub fn parse_search_fields(raw: Option<&str>) -> anyhow::Result<Vec<String>> {
let Some(raw) = raw else {
return Ok(SEARCH_FIELDS.iter().map(|f| f.to_string()).collect());
};
let mut fields: Vec<String> = Vec::new();
for part in raw.split(',') {
let part = part.trim().to_lowercase();
if part.is_empty() {
continue;
}
let canonical = match part.as_str() {
"title" | "titles" => "title",
"description" | "desc" | "descriptions" => "description",
"tags" | "tag" => "tags",
other => anyhow::bail!(
"unknown search field {other:?}. Expected a comma-separated list of: {}",
SEARCH_FIELDS.join(", ")
),
};
if !fields.iter().any(|f| f == canonical) {
fields.push(canonical.to_string());
}
}
if fields.is_empty() {
anyhow::bail!(
"--in named no fields. Expected a comma-separated list of: {}",
SEARCH_FIELDS.join(", ")
);
}
Ok(fields)
}
const CALL: &str = "SELECT * FROM public.search_content(\
$1, $2::int, $3::int, $4::text[], $5, $6::regconfig, $7, $8, $9, $10)";
const COUNT: &str = "SELECT public.search_content_count(\
$1, $4::text[], $5, $6::regconfig, $7, $8)";
fn values(q: &SearchQuery, page: u32, page_size: u32) -> Vec<sea_orm::Value> {
vec![
q.text.clone().into(),
page.max(1).into(),
page_size.max(1).into(),
search_fields_value(q.search_in.as_deref()),
q.channel_id.clone().into(),
q.text_config.clone().into(),
q.include_fuzzy.into(),
q.substring.into(),
q.sort_by.as_str().into(),
q.desc.into(),
]
}
fn count_values(q: &SearchQuery) -> Vec<sea_orm::Value> {
let mut values = values(q, 1, 1);
values.truncate(8);
values
}
pub async fn count(db: &DatabaseConnection, q: &SearchQuery) -> anyhow::Result<u64> {
let statement = Statement::from_sql_and_values(DbBackend::Postgres, COUNT, count_values(q));
let row = db
.query_one_raw(statement)
.await
.map_err(|e| anyhow::anyhow!("search count failed: {e}"))?;
Ok(row
.map(|row| row.try_get::<i64>("", "search_content_count"))
.transpose()?
.unwrap_or(0)
.max(0) as u64)
}
pub async fn search(db: &DatabaseConnection, q: &SearchQuery) -> anyhow::Result<Vec<SearchHit>> {
let statement =
Statement::from_sql_and_values(DbBackend::Postgres, CALL, values(q, q.page, q.page_size));
let rows = db
.query_all_raw(statement)
.await
.map_err(|e| anyhow::anyhow!("search failed: {e}"))?;
rows.iter().map(to_hit).collect()
}
fn search_fields_value(fields: Option<&[String]>) -> sea_orm::Value {
match fields {
Some(fields) => sea_orm::Value::Array(
sea_orm::sea_query::ArrayType::String,
Some(Box::new(
fields
.iter()
.map(|f| sea_orm::Value::String(Some(f.clone())))
.collect(),
)),
),
None => sea_orm::Value::String(None),
}
}
fn to_hit(row: &QueryResult) -> anyhow::Result<SearchHit> {
let published_at: Option<chrono::DateTime<chrono::FixedOffset>> =
row.try_get("", "published_at")?;
Ok(SearchHit {
id: row.try_get("", "id")?,
channel_id: row.try_get("", "channel_id")?,
title: row.try_get("", "title")?,
description: row.try_get("", "description")?,
thumbnail_url: row.try_get("", "thumbnail_url")?,
published_at,
source: row.try_get("", "source")?,
score: row.try_get("", "score")?,
match_tier: row.try_get("", "match_tier")?,
matched_by: row.try_get("", "matched_by")?,
matched_field: row.try_get("", "matched_field")?,
snippet: row.try_get("", "snippet")?,
start_ms: row.try_get("", "start_ms")?,
})
}
impl SearchHit {
pub fn reference(&self) -> String {
match self.source.as_str() {
"playlist" => format!("https://www.youtube.com/playlist?list={}", self.id),
"transcript" => match self.start_ms {
Some(ms) => format!(
"https://www.youtube.com/watch?v={}&t={}s",
self.id,
ms / 1000
),
None => format!("https://www.youtube.com/watch?v={}", self.id),
},
_ => format!("https://www.youtube.com/watch?v={}", self.id),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hit(source: &str) -> SearchHit {
SearchHit {
id: "abc".into(),
channel_id: "UC_x".into(),
title: "t".into(),
description: String::new(),
thumbnail_url: String::new(),
published_at: None,
source: source.into(),
score: 0.5,
match_tier: 1,
matched_by: "fts".into(),
matched_field: Some("title".into()),
snippet: String::new(),
start_ms: None,
}
}
#[test]
fn video_hits_reference_a_watch_url() {
assert_eq!(
hit("video").reference(),
"https://www.youtube.com/watch?v=abc"
);
}
#[test]
fn playlist_hits_reference_a_playlist_url() {
assert_eq!(
hit("playlist").reference(),
"https://www.youtube.com/playlist?list=abc"
);
}
#[test]
fn a_transcript_hit_links_straight_to_the_moment() {
let mut transcript = hit("transcript");
transcript.start_ms = Some(7_320);
assert_eq!(
transcript.reference(),
"https://www.youtube.com/watch?v=abc&t=7s"
);
}
#[test]
fn a_transcript_hit_without_a_position_is_still_linkable() {
assert_eq!(
hit("transcript").reference(),
"https://www.youtube.com/watch?v=abc"
);
}
#[test]
fn the_seek_parameter_is_seconds_not_milliseconds() {
let mut transcript = hit("transcript");
transcript.start_ms = Some(94_160);
assert!(transcript.reference().ends_with("&t=94s"));
}
#[test]
fn no_list_means_every_field() {
assert_eq!(parse_search_fields(None).unwrap(), SEARCH_FIELDS.to_vec());
}
#[test]
fn a_list_is_split_and_trimmed() {
assert_eq!(
parse_search_fields(Some(" title , description ")).unwrap(),
vec!["title", "description"]
);
}
#[test]
fn aliases_resolve_to_the_canonical_name() {
assert_eq!(
parse_search_fields(Some("titles,desc,tag")).unwrap(),
vec!["title", "description", "tags"]
);
}
#[test]
fn transcripts_are_refused_as_a_field() {
let err = parse_search_fields(Some("title,transcript")).unwrap_err();
let message = err.to_string();
assert!(message.contains("transcript"), "{message}");
assert!(message.contains("title, description, tags"), "{message}");
}
#[test]
fn a_repeated_field_is_collapsed() {
assert_eq!(
parse_search_fields(Some("title,title,tags")).unwrap(),
vec!["title", "tags"]
);
}
#[test]
fn an_unknown_field_is_refused_rather_than_ignored() {
let err = parse_search_fields(Some("title,descriptionsss")).unwrap_err();
let message = err.to_string();
assert!(message.contains("descriptionsss"), "{message}");
assert!(message.contains("title, description, tags"), "{message}");
}
#[test]
fn an_empty_list_is_refused() {
assert!(parse_search_fields(Some(" , ")).is_err());
assert!(parse_search_fields(Some("")).is_err());
}
#[test]
fn an_unqualified_search_binds_null_rather_than_the_full_list() {
assert!(matches!(
search_fields_value(None),
sea_orm::Value::String(None)
));
}
#[test]
fn relevance_is_the_default_sort() {
assert_eq!(SearchSort::default(), SearchSort::Relevance);
}
#[test]
fn the_three_sort_keys_parse_in_any_case() {
for (raw, expected) in [
("relevance", SearchSort::Relevance),
("Relevance", SearchSort::Relevance),
("published_at", SearchSort::PublishedAt),
("PUBLISHED_AT", SearchSort::PublishedAt),
(" title ", SearchSort::Title),
] {
assert_eq!(SearchSort::parse(raw).unwrap(), expected, "{raw}");
}
}
#[test]
fn the_aliases_are_the_spellings_people_type() {
assert_eq!(
SearchSort::parse("newest").unwrap(),
SearchSort::PublishedAt
);
assert_eq!(
SearchSort::parse("alphabetical").unwrap(),
SearchSort::Title
);
}
#[test]
fn score_is_not_a_sort_key() {
let err = SearchSort::parse("score").unwrap_err().to_string();
assert!(err.contains("score"), "{err}");
assert!(err.contains("relevance, published_at, title"), "{err}");
}
#[test]
fn an_unknown_sort_key_is_refused_rather_than_ignored() {
assert!(SearchSort::parse("relevances").is_err());
}
}