From a1fbdd33eb7b5a4d1d2f9d4e8edcdb85a2fa17ee Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 2 Dec 2026 18:44:32 +0800 Subject: [PATCH 1/4] Implement fielded Telegram search with a pluggable index store --- .gitignore | 1 + Cargo.lock | 25 +++++ Cargo.toml | 7 ++ crates/telefind-core/Cargo.toml | 7 ++ crates/telefind-core/src/document.rs | 71 +++++++++++++ crates/telefind-core/src/index/memory.rs | 63 +++++++++++ crates/telefind-core/src/index/mod.rs | 68 ++++++++++++ crates/telefind-core/src/index/store.rs | 34 ++++++ crates/telefind-core/src/lib.rs | 8 ++ crates/telefind-core/src/search/analysis.rs | 58 ++++++++++ crates/telefind-core/src/search/mod.rs | 32 ++++++ crates/telefind-core/src/search/rank.rs | 18 ++++ crates/telefind-core/src/search/retrieve.rs | 105 ++++++++++++++++++ crates/telefind-core/tests/retrieval.rs | 112 ++++++++++++++++++++ 14 files changed, 609 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/telefind-core/Cargo.toml create mode 100644 crates/telefind-core/src/document.rs create mode 100644 crates/telefind-core/src/index/memory.rs create mode 100644 crates/telefind-core/src/index/mod.rs create mode 100644 crates/telefind-core/src/index/store.rs create mode 100644 crates/telefind-core/src/lib.rs create mode 100644 crates/telefind-core/src/search/analysis.rs create mode 100644 crates/telefind-core/src/search/mod.rs create mode 100644 crates/telefind-core/src/search/rank.rs create mode 100644 crates/telefind-core/src/search/retrieve.rs create mode 100644 crates/telefind-core/tests/retrieval.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..8a4f599 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,25 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "telefind-core" +version = "0.1.0" +dependencies = [ + "unicode-normalization", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c58aeb2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,7 @@ +[workspace] +members = ["crates/telefind-core"] +resolver = "2" + +[workspace.package] +version = "0.1.0" +edition = "2021" diff --git a/crates/telefind-core/Cargo.toml b/crates/telefind-core/Cargo.toml new file mode 100644 index 0000000..149aeee --- /dev/null +++ b/crates/telefind-core/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "telefind-core" +version.workspace = true +edition.workspace = true + +[dependencies] +unicode-normalization = "0.1" diff --git a/crates/telefind-core/src/document.rs b/crates/telefind-core/src/document.rs new file mode 100644 index 0000000..7df306b --- /dev/null +++ b/crates/telefind-core/src/document.rs @@ -0,0 +1,71 @@ +/// Stable Telegram identity. A post number is scoped to its source. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub enum DocumentId { + Channel(i64), + Group(i64), + Bot(i64), + Post { chat: i64, message: u32 }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Kind { + Channel, + Group, + Bot, + Post, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Media { + Photo, + Video, + Audio, + File, +} + +/// A public username, validated for safe interpolation into a t.me path. +/// Existence and public accessibility are checked by the caller at ingestion. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct PublicName(String); + +impl PublicName { + pub fn new(value: &str) -> Option { + let name = value.strip_prefix('@').unwrap_or(value); + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return None; + } + Some(Self(name.to_ascii_lowercase())) + } + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Clone, Debug)] +pub struct Document { + pub id: DocumentId, + pub username: PublicName, + /// For posts, use the post title or attachment filename, not the channel name. + pub title: String, + /// Directory description, post text or media caption. + pub body: String, + pub media: Option, +} + +impl Document { + pub fn kind(&self) -> Kind { + match self.id { + DocumentId::Channel(_) => Kind::Channel, + DocumentId::Group(_) => Kind::Group, + DocumentId::Bot(_) => Kind::Bot, + DocumentId::Post { .. } => Kind::Post, + } + } + pub fn url(&self) -> String { + let base = format!("https://t.me/{}", self.username.as_str()); + match self.id { + DocumentId::Post { message, .. } => format!("{base}/{message}"), + _ => base, + } + } +} diff --git a/crates/telefind-core/src/index/memory.rs b/crates/telefind-core/src/index/memory.rs new file mode 100644 index 0000000..0f2e007 --- /dev/null +++ b/crates/telefind-core/src/index/memory.rs @@ -0,0 +1,63 @@ +use super::{IndexReader, IndexStore, IndexedDocument, Postings}; +use crate::DocumentId; +use std::{borrow::Cow, collections::HashMap, convert::Infallible}; + +#[derive(Default)] +pub struct MemoryStore { + docs: HashMap, + postings: HashMap, + lengths: [usize; 2], +} + +impl IndexStore for MemoryStore { + type Error = Infallible; + type Reader<'a> = &'a Self; + fn snapshot(&self) -> Result<&Self, Infallible> { + Ok(self) + } + fn replace(&mut self, entry: IndexedDocument) -> Result<(), Infallible> { + let id = entry.document.id; + self.delete(id)?; + for (term, counts) in &entry.frequencies { + self.postings + .entry(term.clone()) + .or_default() + .insert(id, *counts); + } + for (sum, count) in self.lengths.iter_mut().zip(entry.lengths) { + *sum += count; + } + self.docs.insert(id, entry); + Ok(()) + } + fn delete(&mut self, id: DocumentId) -> Result { + let Some(entry) = self.docs.remove(&id) else { + return Ok(false); + }; + for (sum, count) in self.lengths.iter_mut().zip(entry.lengths) { + *sum -= count; + } + for term in entry.frequencies.keys() { + if let Some(list) = self.postings.get_mut(term) { + list.remove(&id); + if list.is_empty() { + self.postings.remove(term); + } + } + } + Ok(true) + } +} + +impl IndexReader for &MemoryStore { + type Error = Infallible; + fn statistics(&self) -> Result<(usize, [usize; 2]), Infallible> { + Ok((self.docs.len(), self.lengths)) + } + fn postings(&self, term: &str) -> Result>, Infallible> { + Ok(self.postings.get(term).map(Cow::Borrowed)) + } + fn document(&self, id: DocumentId) -> Result, Infallible> { + Ok(Cow::Borrowed(&self.docs[&id])) + } +} diff --git a/crates/telefind-core/src/index/mod.rs b/crates/telefind-core/src/index/mod.rs new file mode 100644 index 0000000..d1e60fc --- /dev/null +++ b/crates/telefind-core/src/index/mod.rs @@ -0,0 +1,68 @@ +mod memory; +mod store; +use crate::search::{analysis, retrieve::retrieve}; +use crate::Kind; +use std::collections::BTreeMap; +pub use store::{IndexReader, IndexStore, IndexedDocument, Postings}; + +use crate::{Document, DocumentId, Query, SearchPage}; +pub use memory::MemoryStore; +pub type MemoryIndex = Engine; + +/// Port for a database-backed searchable index. Writes replace by stable ID. +/// Implementations must make document, token and statistics changes atomic. +/// Search requires all query terms, applies filters before paging and returns +/// a deterministic order for an unchanged snapshot. Errors reach the caller. +pub trait SearchIndex { + type Error; + fn upsert(&mut self, document: Document) -> Result<(), Self::Error>; + fn remove(&mut self, id: DocumentId) -> Result; + fn search(&self, query: &Query<'_>) -> Result; +} + +#[derive(Default)] +pub struct Engine { + store: S, +} + +impl Engine { + pub fn new(store: S) -> Self { + Self { store } + } +} + +impl SearchIndex for Engine { + type Error = S::Error; + fn upsert(&mut self, doc: Document) -> Result<(), Self::Error> { + let title = analysis::normalize(&doc.title); + let body = analysis::normalize(&doc.body); + let mut short = analysis::index_tokens(&title); + if doc.kind() != Kind::Post { + short.push(doc.username.as_str().to_owned()); + } + let mut counts: BTreeMap = BTreeMap::new(); + let mut lengths = [0; 2]; + for (field, tokens) in [short, analysis::index_tokens(&body)] + .into_iter() + .enumerate() + { + lengths[field] = tokens.len(); + for term in tokens { + counts.entry(term).or_default()[field] += 1; + } + } + self.store.replace(IndexedDocument { + document: doc, + title, + body, + lengths, + frequencies: counts, + }) + } + fn remove(&mut self, id: DocumentId) -> Result { + self.store.delete(id) + } + fn search(&self, query: &Query) -> Result { + retrieve(&self.store.snapshot()?, query) + } +} diff --git a/crates/telefind-core/src/index/store.rs b/crates/telefind-core/src/index/store.rs new file mode 100644 index 0000000..13bc8fd --- /dev/null +++ b/crates/telefind-core/src/index/store.rs @@ -0,0 +1,34 @@ +//! Persistence boundary. A read view must represent a single committed revision. +use crate::{Document, DocumentId}; +use std::{borrow::Cow, collections::BTreeMap}; + +pub type Postings = BTreeMap; + +#[derive(Clone, Debug)] +pub struct IndexedDocument { + pub document: Document, + pub title: String, + pub body: String, + pub lengths: [usize; 2], + pub frequencies: BTreeMap, +} + +pub trait IndexReader { + type Error; + /// Document count and total token counts in the short and body fields. + fn statistics(&self) -> Result<(usize, [usize; 2]), Self::Error>; + fn postings(&self, term: &str) -> Result>, Self::Error>; + /// IDs come from this snapshot's posting lists and must resolve. + fn document(&self, id: DocumentId) -> Result, Self::Error>; +} + +pub trait IndexStore { + type Error; + type Reader<'a>: IndexReader + where + Self: 'a; + fn snapshot(&self) -> Result, Self::Error>; + /// Atomically replace the old document, its postings and field statistics. + fn replace(&mut self, entry: IndexedDocument) -> Result<(), Self::Error>; + fn delete(&mut self, id: DocumentId) -> Result; +} diff --git a/crates/telefind-core/src/lib.rs b/crates/telefind-core/src/lib.rs new file mode 100644 index 0000000..fe1faaa --- /dev/null +++ b/crates/telefind-core/src/lib.rs @@ -0,0 +1,8 @@ +//! Lexical retrieval over already-collected, public Telegram records. +mod document; +pub mod index; +pub mod search; + +pub use document::{Document, DocumentId, Kind, Media, PublicName}; +pub use index::{MemoryIndex, SearchIndex}; +pub use search::{Query, SearchPage}; diff --git a/crates/telefind-core/src/search/analysis.rs b/crates/telefind-core/src/search/analysis.rs new file mode 100644 index 0000000..4b6a2a2 --- /dev/null +++ b/crates/telefind-core/src/search/analysis.rs @@ -0,0 +1,58 @@ +use std::collections::BTreeSet; +use unicode_normalization::UnicodeNormalization; + +pub(crate) fn normalize(text: &str) -> String { + text.nfkc() + .flat_map(char::to_lowercase) + .collect::() + .split_whitespace() + .collect::>() + .join(" ") +} + +fn han(c: char) -> bool { + matches!(c as u32, 0x3400..=0x4dbf | 0x4e00..=0x9fff | 0xf900..=0xfaff | 0x20000..=0x323af) +} + +// Keep individual Han characters in the index for one-character queries; +// for longer Han runs query only the more selective overlapping bigrams. +fn tokens(text: &str, indexing: bool) -> Vec { + let mut output = Vec::new(); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if han(c) { + let mut previous = c; + let mut single = true; + if indexing { + output.push(c.to_string()); + } + while let Some(next) = chars.next_if(|&n| han(n)) { + output.push(format!("{previous}{next}")); + if indexing { + output.push(next.to_string()); + } + single = false; + previous = next; + } + if single && !indexing { + output.push(c.to_string()); + } + } else if c.is_alphanumeric() || c == '_' { + let mut word = String::from(c); + while let Some(next) = chars.next_if(|&n| !han(n) && (n.is_alphanumeric() || n == '_')) + { + word.push(next); + } + output.push(word); + } + } + output +} + +pub(crate) fn index_tokens(text: &str) -> Vec { + tokens(text, true) +} + +pub(crate) fn query_terms(text: &str) -> BTreeSet { + tokens(text, false).into_iter().collect() +} diff --git a/crates/telefind-core/src/search/mod.rs b/crates/telefind-core/src/search/mod.rs new file mode 100644 index 0000000..8005174 --- /dev/null +++ b/crates/telefind-core/src/search/mod.rs @@ -0,0 +1,32 @@ +pub(crate) mod analysis; +pub(crate) mod rank; +pub(crate) mod retrieve; + +use crate::{Document, Kind, Media}; + +#[derive(Clone, Debug)] +pub struct Query<'a> { + pub text: &'a str, + pub kind: Option, + pub media: Option, + pub offset: usize, + pub limit: usize, +} + +impl<'a> Query<'a> { + pub fn new(text: &'a str) -> Self { + Self { + text, + kind: None, + media: None, + offset: 0, + limit: 10, + } + } +} + +#[derive(Debug)] +pub struct SearchPage { + pub total: usize, + pub hits: Vec, +} diff --git a/crates/telefind-core/src/search/rank.rs b/crates/telefind-core/src/search/rank.rs new file mode 100644 index 0000000..ec86d69 --- /dev/null +++ b/crates/telefind-core/src/search/rank.rs @@ -0,0 +1,18 @@ +// BM25F: normalize field frequencies before saturation. Title/username share +// the short field. Corpus-wide document frequency is counted once per term. +pub(crate) fn term_score( + counts: [usize; 2], + lengths: [usize; 2], + averages: [f64; 2], + n: usize, + df: usize, +) -> f64 { + let weights = [3.0, 1.0]; + let mut frequency = 0.0; + for field in 0..2 { + let norm = 0.25 + 0.75 * lengths[field] as f64 / averages[field].max(1.0); + frequency += weights[field] * counts[field] as f64 / norm; + } + let idf = (1.0 + ((n - df) as f64 + 0.5) / (df as f64 + 0.5)).ln(); + idf * (2.2 * frequency) / (1.2 + frequency) +} diff --git a/crates/telefind-core/src/search/retrieve.rs b/crates/telefind-core/src/search/retrieve.rs new file mode 100644 index 0000000..eb337ed --- /dev/null +++ b/crates/telefind-core/src/search/retrieve.rs @@ -0,0 +1,105 @@ +use super::{analysis, rank}; +use crate::{index::IndexReader, DocumentId, Kind, Query, SearchPage}; +use std::{ + cmp::{Ordering, Reverse}, + collections::BinaryHeap, +}; + +#[derive(Debug)] +struct Hit { + exact: bool, + score: f64, + id: DocumentId, +} + +impl Ord for Hit { + fn cmp(&self, other: &Self) -> Ordering { + self.exact + .cmp(&other.exact) + .then_with(|| self.score.total_cmp(&other.score)) + .then_with(|| other.id.cmp(&self.id)) + } +} +impl PartialOrd for Hit { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl PartialEq for Hit { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} +impl Eq for Hit {} + +pub(crate) fn retrieve(reader: &R, query: &Query) -> Result { + let empty = || SearchPage { + total: 0, + hits: Vec::new(), + }; + let text = analysis::normalize(query.text); + let mut lists = Vec::new(); + for term in analysis::query_terms(&text) { + let Some(postings) = reader.postings(&term)? else { + return Ok(empty()); + }; + lists.push(postings); + } + lists.sort_unstable_by_key(|list| list.len()); + let Some(first) = lists.first() else { + return Ok(empty()); + }; + let (n, lengths) = reader.statistics()?; + let avg = lengths.map(|length| length as f64 / n.max(1) as f64); + let mut best = BinaryHeap::new(); + let mut total = 0; + let window = query.offset.saturating_add(query.limit); + for id in first.keys() { + if !lists[1..].iter().all(|list| list.contains_key(id)) { + continue; + } + let entry = reader.document(*id)?; + if query.kind.is_some_and(|kind| kind != entry.document.kind()) + || query + .media + .is_some_and(|media| Some(media) != entry.document.media) + { + continue; + } + total += 1; + if query.limit == 0 || query.offset >= first.len() { + continue; + } + let mut score: f64 = lists + .iter() + .map(|list| rank::term_score(list[id], entry.lengths, avg, n, list.len())) + .sum(); + if entry.title.contains(&text) { + score += 2.0; + } else if entry.body.contains(&text) { + score += 0.5; + } + let exact = entry.document.kind() != Kind::Post + && (entry.title == text + || entry.document.username.as_str() == text.trim_start_matches('@')); + let hit = Hit { + exact, + score, + id: *id, + }; + if best.len() < window { + best.push(Reverse(hit)); + } else if let Some(mut worst) = best.peek_mut() { + if hit > worst.0 { + *worst = Reverse(hit); + } + } + } + let hits = best + .into_sorted_vec() + .into_iter() + .skip(query.offset) + .map(|Reverse(hit)| reader.document(hit.id).map(|entry| entry.document.clone())) + .collect::, _>>()?; + Ok(SearchPage { total, hits }) +} diff --git a/crates/telefind-core/tests/retrieval.rs b/crates/telefind-core/tests/retrieval.rs new file mode 100644 index 0000000..23f6118 --- /dev/null +++ b/crates/telefind-core/tests/retrieval.rs @@ -0,0 +1,112 @@ +use telefind_core::{ + Document, DocumentId, Kind, Media, MemoryIndex, PublicName, Query, SearchIndex, +}; + +fn post(chat: i64, message: u32, title: &str, body: &str) -> Document { + Document { + id: DocumentId::Post { chat, message }, + username: PublicName::new(&format!("chat{chat}")).unwrap(), + title: title.into(), + body: body.into(), + media: None, + } +} +fn ids(index: &MemoryIndex, q: &Query) -> Vec { + index + .search(q) + .unwrap() + .hits + .into_iter() + .map(|doc| doc.id) + .collect() +} + +#[test] +fn mixed_script_and_single_character_queries() { + let mut index = MemoryIndex::default(); + let doc = post(1, 2, "深圳二手", "RTX 5090"); + index.upsert(doc.clone()).unwrap(); + for keyword in ["深圳 RTX 5090", "深", "5090 二手", "二手 二手"] { + assert_eq!(ids(&index, &Query::new(keyword)), vec![doc.id]); + } + for keyword in ["深圳 5080", "", "!!"] { + assert!(ids(&index, &Query::new(keyword)).is_empty()); + } +} + +#[test] +fn edits_and_deletes_remove_stale_postings_and_keep_other_chats() { + let mut index = MemoryIndex::default(); + let first = post(1, 7, "旧标题", ""); + let second = post(2, 7, "旧标题", ""); + for doc in [&first, &second, &first] { + index.upsert(doc.clone()).unwrap(); + } + assert_eq!(index.search(&Query::new("旧标题")).unwrap().total, 2); + index.upsert(post(1, 7, "新标题", "")).unwrap(); + assert_eq!(ids(&index, &Query::new("旧标题")), vec![second.id]); + assert_eq!(ids(&index, &Query::new("新标题")), vec![first.id]); + assert!(index.remove(first.id).unwrap()); + assert!(!index.remove(first.id).unwrap()); + assert!(ids(&index, &Query::new("新标题")).is_empty()); +} + +#[test] +fn directory_identity_and_exact_title_rank_first() { + let mut index = MemoryIndex::default(); + let mut channel = post(1, 1, "摄影", ""); + channel.id = DocumentId::Channel(1); + channel.username = PublicName::new("@Photo_News").unwrap(); + index.upsert(post(2, 3, "摄影", "photo_news")).unwrap(); + index.upsert(channel.clone()).unwrap(); + for term in ["摄影", "@PHOTO_NEWS"] { + assert_eq!(ids(&index, &Query::new(term))[0], channel.id); + } + assert_eq!(channel.url(), "https://t.me/photo_news"); + assert!(PublicName::new("a/b?c").is_none()); +} + +#[test] +fn title_and_contiguous_phrase_outrank_scattered_words() { + let mut index = MemoryIndex::default(); + let exact = post(1, 1, "rust search", ""); + let separated = post(1, 2, "search rust", ""); + let body = post(1, 3, "", "rust and search"); + for doc in [&body, &separated, &exact] { + index.upsert(doc.clone()).unwrap(); + } + assert_eq!( + ids(&index, &Query::new("rust search")), + vec![exact.id, separated.id, body.id] + ); +} + +#[test] +fn filtering_precedes_paging_and_ties_are_stable() { + let mut index = MemoryIndex::default(); + for id in (1..=5).rev() { + let mut doc = post(1, id, "sample", ""); + if id % 2 == 1 { + doc.media = Some(Media::Video); + } + index.upsert(doc).unwrap(); + } + let mut query = Query { + kind: Some(Kind::Post), + media: Some(Media::Video), + offset: 1, + limit: 1, + ..Query::new("sample") + }; + let page = index.search(&query).unwrap(); + assert_eq!(page.total, 3); + assert_eq!(page.hits[0].url(), "https://t.me/chat1/3"); + query.offset = usize::MAX; + assert!(ids(&index, &query).is_empty()); + query.offset = 0; + query.limit = 0; + assert_eq!(index.search(&query).unwrap().total, 3); + assert!(ids(&index, &query).is_empty()); + query.kind = Some(Kind::Bot); + assert_eq!(index.search(&query).unwrap().total, 0); +} -- 2.52.0 From dc9baa4deced2eba35436e06584591fe49e4f7fb Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 2 Dec 2026 18:45:02 +0800 Subject: [PATCH 2/4] Handle Telegram keyword searches and stateless result pages --- Cargo.lock | 7 +++ Cargo.toml | 2 +- crates/telefind-bot/Cargo.toml | 7 +++ crates/telefind-bot/src/command.rs | 43 ++++++++++++++++ crates/telefind-bot/src/lib.rs | 61 +++++++++++++++++++++++ crates/telefind-bot/tests/commands.rs | 70 +++++++++++++++++++++++++++ 6 files changed, 189 insertions(+), 1 deletion(-) create mode 100644 crates/telefind-bot/Cargo.toml create mode 100644 crates/telefind-bot/src/command.rs create mode 100644 crates/telefind-bot/src/lib.rs create mode 100644 crates/telefind-bot/tests/commands.rs diff --git a/Cargo.lock b/Cargo.lock index 8a4f599..235a10e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,13 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "telefind-bot" +version = "0.1.0" +dependencies = [ + "telefind-core", +] + [[package]] name = "telefind-core" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c58aeb2..2077cf1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/telefind-core"] +members = ["crates/telefind-core", "crates/telefind-bot"] resolver = "2" [workspace.package] diff --git a/crates/telefind-bot/Cargo.toml b/crates/telefind-bot/Cargo.toml new file mode 100644 index 0000000..f5fe7b0 --- /dev/null +++ b/crates/telefind-bot/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "telefind-bot" +version.workspace = true +edition.workspace = true + +[dependencies] +telefind-core = { path = "../telefind-core" } diff --git a/crates/telefind-bot/src/command.rs b/crates/telefind-bot/src/command.rs new file mode 100644 index 0000000..b25b97a --- /dev/null +++ b/crates/telefind-bot/src/command.rs @@ -0,0 +1,43 @@ +pub(crate) enum Input<'a> { + Ignore, + Help, + Search(telefind_core::Query<'a>), +} + +pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> { + let text = text.trim(); + if text.is_empty() { + return Input::Ignore; + } + if !text.starts_with('/') { + return Input::Search(telefind_core::Query::new(text)); + } + let (command, args) = text.split_once(char::is_whitespace).unwrap_or((text, "")); + let (command, target) = command + .split_once('@') + .map_or((command, None), |(cmd, target)| (cmd, Some(target))); + if target.is_some_and(|name| !name.eq_ignore_ascii_case(bot.trim_start_matches('@'))) { + return Input::Ignore; + } + match (command, args.trim()) { + ("/search", "") | ("/help" | "/start", _) => Input::Help, + ("/search", query) => Input::Search(telefind_core::Query::new(query)), + ("/page", args) => { + let Some((number, text)) = args.split_once(char::is_whitespace) else { + return Input::Help; + }; + let mut query = telefind_core::Query::new(text.trim()); + let Some(offset) = number + .parse::() + .ok() + .and_then(|n| n.checked_sub(1)) + .and_then(|n| n.checked_mul(query.limit)) + else { + return Input::Help; + }; + query.offset = offset; + Input::Search(query) + } + _ => Input::Ignore, + } +} diff --git a/crates/telefind-bot/src/lib.rs b/crates/telefind-bot/src/lib.rs new file mode 100644 index 0000000..0533f55 --- /dev/null +++ b/crates/telefind-bot/src/lib.rs @@ -0,0 +1,61 @@ +//! Transport-independent Telegram search interaction. The host supplies +//! incoming text and sends the returned plain-text labels and URL buttons. +mod command; +use telefind_core::{Document, Kind, SearchIndex}; + +#[derive(Debug, PartialEq)] +pub struct ResultLink { + pub label: String, + pub url: String, +} + +#[derive(Debug, PartialEq)] +pub enum Reply { + Ignored, + Help, + Results { + total: usize, + links: Vec, + }, +} + +/// Accept a keyword message or /search. The bot username is needed for +/// commands addressed to a particular bot in a group. Use /page N keywords +/// to fetch a later page without storing per-user sessions. +pub fn handle(index: &S, bot: &str, text: &str) -> Result { + let request = match command::parse(bot, text) { + command::Input::Ignore => return Ok(Reply::Ignored), + command::Input::Help => return Ok(Reply::Help), + command::Input::Search(query) => query, + }; + let page = index.search(&request)?; + Ok(Reply::Results { + total: page.total, + links: page.hits.iter().map(link).collect(), + }) +} + +fn link(doc: &Document) -> ResultLink { + let kind = match doc.kind() { + Kind::Channel => "频道", + Kind::Group => "群组", + Kind::Bot => "Bot", + Kind::Post => "帖子", + }; + let name = [&doc.title[..], &doc.body[..], doc.username.as_str()] + .into_iter() + .map(str::trim) + .find(|s| !s.is_empty()) + .unwrap_or_default(); + let compact: String = name + .split_whitespace() + .collect::>() + .join(" ") + .chars() + .take(60) + .collect(); + ResultLink { + label: format!("{kind} · {compact}"), + url: doc.url(), + } +} diff --git a/crates/telefind-bot/tests/commands.rs b/crates/telefind-bot/tests/commands.rs new file mode 100644 index 0000000..d926380 --- /dev/null +++ b/crates/telefind-bot/tests/commands.rs @@ -0,0 +1,70 @@ +use telefind_bot::{handle, Reply}; +use telefind_core::{Document, DocumentId, MemoryIndex, PublicName, SearchIndex}; + +#[test] +fn plain_and_addressed_search_return_public_post_link() { + let mut index = MemoryIndex::default(); + index + .upsert(Document { + id: DocumentId::Post { + chat: 9, + message: 4, + }, + username: PublicName::new("techfeed").unwrap(), + title: "".into(), + body: "Rust 教程".into(), + media: None, + }) + .unwrap(); + for text in ["rust", "/search@MyBot RUST", "/search 教程"] { + let Reply::Results { total, links } = handle(&index, "mybot", text).unwrap() else { + panic!("expected results") + }; + assert_eq!(total, 1); + assert_eq!(links[0].url, "https://t.me/techfeed/4"); + assert_eq!(links[0].label, "帖子 · Rust 教程"); + } +} + +#[test] +fn missing_queries_and_foreign_commands_are_distinct() { + let index = MemoryIndex::default(); + for text in ["/start", "/search@me ", "/help"] { + assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help); + } + for text in [" ", "/search@another x", "/status"] { + assert_eq!(handle(&index, "me", text).unwrap(), Reply::Ignored); + } + assert_eq!( + handle(&index, "me", "中文").unwrap(), + Reply::Results { + total: 0, + links: vec![] + } + ); +} + +#[test] +fn paging_is_stateless_and_rejects_invalid_numbers() { + let mut index = MemoryIndex::default(); + for message in 1..=11 { + index + .upsert(Document { + id: DocumentId::Post { chat: 1, message }, + username: PublicName::new("books").unwrap(), + title: "book".into(), + body: String::new(), + media: None, + }) + .unwrap(); + } + let Reply::Results { total, links } = handle(&index, "me", "/page@me 2 book").unwrap() else { + panic!("expected page") + }; + assert_eq!(total, 11); + assert_eq!(links.len(), 1); + assert_eq!(links[0].url, "https://t.me/books/11"); + for text in ["/page 0 book", "/page x book", "/page 2"] { + assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help); + } +} -- 2.52.0 From 61d9e6877ac86ef26505e2e5351bd51c64ba195a Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 2 Dec 2026 19:09:46 +0800 Subject: [PATCH 3/4] Support segmented Chinese queries, phrase matching and type filters --- Cargo.lock | 445 ++++++++++++++++++++ crates/telefind-bot/src/command.rs | 47 ++- crates/telefind-bot/tests/commands.rs | 34 ++ crates/telefind-core/Cargo.toml | 1 + crates/telefind-core/src/search/analysis.rs | 23 +- crates/telefind-core/src/search/retrieve.rs | 13 + crates/telefind-core/tests/retrieval.rs | 73 ++++ 7 files changed, 620 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 235a10e..9a6da1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,416 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" + +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cedarwood" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d910bedd62c24733263d0bed247460853c9d22e8956bd4cd964302095e04e90" +dependencies = [ + "smallvec", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "dary_heap" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "include-flate" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f677e494e19ac4aa62375916f64b496f6b2655964c7313231c959858608cd9eb" +dependencies = [ + "include-flate-codegen", + "include-flate-compress", +] + +[[package]] +name = "include-flate-codegen" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d3749676b6129ea4cf1e75adfb280a2148f03113806cb68cd7775fdfc65edf" +dependencies = [ + "include-flate-compress", + "proc-macro-error3", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "include-flate-compress" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "476a7e4feb3325e85ca85565893517e283a1e59d3c9b695c162791dead7f004d" +dependencies = [ + "libflate", + "zstd", +] + +[[package]] +name = "jieba-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "348294e44ee7e3c42685da656490f8febc7359632544019621588902216da95c" +dependencies = [ + "phf_codegen", +] + +[[package]] +name = "jieba-rs" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "766bd7012aa5ba49411ebdf4e93bddd59b182d2918e085d58dec5bb9b54b7105" +dependencies = [ + "cedarwood", + "include-flate", + "jieba-macros", + "phf", + "regex", + "rustc-hash", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libflate" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561a8da1a50e1428d3c51321dafeca849df992a5bb67720c386131234caba82e" +dependencies = [ + "adler32", + "crc32fast", + "dary_heap", + "libflate_lz77", + "no_std_io2", +] + +[[package]] +name = "libflate_lz77" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7a10e427698aef6eef269482776debfef63384d30f13aad39a1a95e0e098fd" +dependencies = [ + "hashbrown", + "no_std_io2", + "rle-decode-fast", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro-error-attr3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233" +dependencies = [ + "proc-macro-error-attr3", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rle-decode-fast" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "telefind-bot" version = "0.1.0" @@ -13,6 +423,7 @@ dependencies = [ name = "telefind-core" version = "0.1.0" dependencies = [ + "jieba-rs", "unicode-normalization", ] @@ -22,6 +433,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + [[package]] name = "unicode-normalization" version = "0.1.26" @@ -30,3 +447,31 @@ checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] + +[[package]] +name = "zstd" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/crates/telefind-bot/src/command.rs b/crates/telefind-bot/src/command.rs index b25b97a..c394f37 100644 --- a/crates/telefind-bot/src/command.rs +++ b/crates/telefind-bot/src/command.rs @@ -1,7 +1,8 @@ +use telefind_core::{Kind, Media, Query}; pub(crate) enum Input<'a> { Ignore, Help, - Search(telefind_core::Query<'a>), + Search(Query<'a>), } pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> { @@ -10,7 +11,7 @@ pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> { return Input::Ignore; } if !text.starts_with('/') { - return Input::Search(telefind_core::Query::new(text)); + return search(text, 1); } let (command, args) = text.split_once(char::is_whitespace).unwrap_or((text, "")); let (command, target) = command @@ -21,23 +22,41 @@ pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> { } match (command, args.trim()) { ("/search", "") | ("/help" | "/start", _) => Input::Help, - ("/search", query) => Input::Search(telefind_core::Query::new(query)), + ("/search", query) => search(query, 1), ("/page", args) => { let Some((number, text)) = args.split_once(char::is_whitespace) else { return Input::Help; }; - let mut query = telefind_core::Query::new(text.trim()); - let Some(offset) = number - .parse::() - .ok() - .and_then(|n| n.checked_sub(1)) - .and_then(|n| n.checked_mul(query.limit)) - else { - return Input::Help; - }; - query.offset = offset; - Input::Search(query) + number + .parse() + .map_or(Input::Help, |page| search(text.trim(), page)) } _ => Input::Ignore, } } + +fn search(text: &str, page: usize) -> Input<'_> { + let mut q = Query::new(text); + if let Some(filter) = text.strip_prefix("type:") { + let Some((kind, rest)) = filter.split_once(char::is_whitespace) else { + return Input::Help; + }; + q.text = rest.trim(); + match kind { + "channel" => q.kind = Some(Kind::Channel), + "group" => q.kind = Some(Kind::Group), + "bot" => q.kind = Some(Kind::Bot), + "post" => q.kind = Some(Kind::Post), + "photo" => q.media = Some(Media::Photo), + "video" => q.media = Some(Media::Video), + "audio" => q.media = Some(Media::Audio), + "file" => q.media = Some(Media::File), + _ => return Input::Help, + } + } + let Some(offset) = page.checked_sub(1).and_then(|p| p.checked_mul(q.limit)) else { + return Input::Help; + }; + q.offset = offset; + Input::Search(q) +} diff --git a/crates/telefind-bot/tests/commands.rs b/crates/telefind-bot/tests/commands.rs index d926380..573e48c 100644 --- a/crates/telefind-bot/tests/commands.rs +++ b/crates/telefind-bot/tests/commands.rs @@ -68,3 +68,37 @@ fn paging_is_stateless_and_rejects_invalid_numbers() { assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help); } } + +#[test] +fn type_filter_is_available_in_search_and_page_commands() { + let mut index = MemoryIndex::default(); + for (id, media) in [(1, None), (2, Some(telefind_core::Media::Video))] { + index + .upsert(Document { + id: DocumentId::Post { + chat: 1, + message: id, + }, + username: PublicName::new("demo_feed").unwrap(), + title: "教程".into(), + body: String::new(), + media, + }) + .unwrap(); + } + for query in [ + "type:video 教程", + "/search type:video 教程", + "/page 1 type:video 教程", + ] { + let Reply::Results { links, total } = handle(&index, "me", query).unwrap() else { + panic!("expected results") + }; + assert_eq!(total, 1); + assert_eq!(links[0].url, "https://t.me/demo_feed/2"); + } + assert_eq!( + handle(&index, "me", "/search type:unknown 教程").unwrap(), + Reply::Help + ); +} diff --git a/crates/telefind-core/Cargo.toml b/crates/telefind-core/Cargo.toml index 149aeee..58b77d6 100644 --- a/crates/telefind-core/Cargo.toml +++ b/crates/telefind-core/Cargo.toml @@ -4,4 +4,5 @@ version.workspace = true edition.workspace = true [dependencies] +jieba-rs = "0.8" unicode-normalization = "0.1" diff --git a/crates/telefind-core/src/search/analysis.rs b/crates/telefind-core/src/search/analysis.rs index 4b6a2a2..ea662a1 100644 --- a/crates/telefind-core/src/search/analysis.rs +++ b/crates/telefind-core/src/search/analysis.rs @@ -1,4 +1,5 @@ -use std::collections::BTreeSet; +use jieba_rs::Jieba; +use std::{collections::BTreeSet, sync::OnceLock}; use unicode_normalization::UnicodeNormalization; pub(crate) fn normalize(text: &str) -> String { @@ -54,5 +55,23 @@ pub(crate) fn index_tokens(text: &str) -> Vec { } pub(crate) fn query_terms(text: &str) -> BTreeSet { - tokens(text, false).into_iter().collect() + static LEXICON: OnceLock = OnceLock::new(); + let mut terms = BTreeSet::new(); + let mut rest = text; + while let Some(first) = rest.chars().next() { + let is_han = han(first); + let end = rest.find(|c: char| han(c) != is_han).unwrap_or(rest.len()); + let (run, tail) = rest.split_at(end); + if is_han { + // Segment only the query. The existing character/bigram postings can + // match each dictionary word even in names absent from the dictionary. + for word in LEXICON.get_or_init(Jieba::new).cut(run, false) { + terms.extend(tokens(word, false)); + } + } else { + terms.extend(tokens(run, false)); + } + rest = tail; + } + terms } diff --git a/crates/telefind-core/src/search/retrieve.rs b/crates/telefind-core/src/search/retrieve.rs index eb337ed..9c20d22 100644 --- a/crates/telefind-core/src/search/retrieve.rs +++ b/crates/telefind-core/src/search/retrieve.rs @@ -38,6 +38,13 @@ pub(crate) fn retrieve(reader: &R, query: &Query) -> Result = text.split('"').skip(1).collect(); + let phrases: Vec<_> = parts + .chunks_exact(2) + .map(|pair| pair[0].trim()) + .filter(|phrase| !phrase.is_empty()) + .collect(); let mut lists = Vec::new(); for term in analysis::query_terms(&text) { let Some(postings) = reader.postings(&term)? else { @@ -66,6 +73,12 @@ pub(crate) fn retrieve(reader: &R, query: &Query) -> Result= first.len() { continue; diff --git a/crates/telefind-core/tests/retrieval.rs b/crates/telefind-core/tests/retrieval.rs index 23f6118..a7d6f98 100644 --- a/crates/telefind-core/tests/retrieval.rs +++ b/crates/telefind-core/tests/retrieval.rs @@ -110,3 +110,76 @@ fn filtering_precedes_paging_and_ties_are_stable() { query.kind = Some(Kind::Bot); assert_eq!(index.search(&query).unwrap().total, 0); } + +#[test] +fn quoted_phrase_requires_adjacency_in_a_single_field() { + let mut index = MemoryIndex::default(); + for doc in [ + post(1, 1, "Rust Search", "入门"), + post(1, 2, "Rust", "Search 入门"), + post(1, 3, "Search Rust", "入门"), + ] { + index.upsert(doc).unwrap(); + } + assert_eq!( + ids(&index, &Query::new("\"rust search\" 入门")), + vec![DocumentId::Post { + chat: 1, + message: 1 + }] + ); +} + +#[test] +fn unspaced_chinese_query_matches_words_across_fields_and_keeps_model_required() { + let mut index = MemoryIndex::default(); + index + .upsert(post(1, 1, "上海", "二手 相机 RTX 5090")) + .unwrap(); + index + .upsert(post(1, 2, "上海", "二手 相机 RTX 5080")) + .unwrap(); + assert_eq!( + ids(&index, &Query::new("上海二手相机 5090")), + vec![DocumentId::Post { + chat: 1, + message: 1 + }] + ); +} + +#[test] +#[ignore = "synthetic capacity measurement; run explicitly in release mode"] +fn measure_ranked_queries_over_25000_posts() { + use std::time::Instant; + let mut index = MemoryIndex::default(); + let start = Instant::now(); + for id in 1..=25_000 { + let title = format!("频道sku{} 相机 {}", id % 100, id % 50); + index.upsert(post(1, id, &title, "摄影教程与设备")).unwrap(); + } + let ingest = start.elapsed(); + let queries = ["相机", "sku3 3", "设备", "摄影教程 17"]; + for text in queries { + let query = Query::new(text); + let page = index.search(&query).unwrap(); + let expected = match text { + "sku3 3" => 250, + "摄影教程 17" => 500, + _ => 25_000, + }; + assert_eq!(page.total, expected); + let mut times = Vec::new(); + for _ in 0..30 { + let start = Instant::now(); + let result = index.search(&query).unwrap(); + assert_eq!(result.hits.len(), 10); + times.push(start.elapsed()); + } + times.sort_unstable(); + println!( + "records=25000 ingest={ingest:?} query={text:?} matches={expected} p50={:?} p95={:?}", + times[14], times[28] + ); + } +} -- 2.52.0 From 5f69f4bfd1739d28e26f69639a4b2706feb288a2 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Wed, 2 Dec 2026 19:10:26 +0800 Subject: [PATCH 4/4] Run Telegram polling, document ingestion and search replies from a Rust executable --- Cargo.lock | 720 ++++++++++++++++++++- Cargo.toml | 2 +- README.md | 41 ++ crates/telefind-app/Cargo.toml | 16 + crates/telefind-app/src/input.rs | 108 ++++ crates/telefind-app/src/lib.rs | 3 + crates/telefind-app/src/main.rs | 58 ++ crates/telefind-app/src/telegram/client.rs | 99 +++ crates/telefind-app/src/telegram/mod.rs | 83 +++ crates/telefind-app/src/telegram/tests.rs | 158 +++++ crates/telefind-app/src/telegram/update.rs | 150 +++++ crates/telefind-app/tests/cli.rs | 56 ++ 12 files changed, 1491 insertions(+), 3 deletions(-) create mode 100644 README.md create mode 100644 crates/telefind-app/Cargo.toml create mode 100644 crates/telefind-app/src/input.rs create mode 100644 crates/telefind-app/src/lib.rs create mode 100644 crates/telefind-app/src/main.rs create mode 100644 crates/telefind-app/src/telegram/client.rs create mode 100644 crates/telefind-app/src/telegram/mod.rs create mode 100644 crates/telefind-app/src/telegram/tests.rs create mode 100644 crates/telefind-app/src/telegram/update.rs create mode 100644 crates/telefind-app/tests/cli.rs diff --git a/Cargo.lock b/Cargo.lock index 9a6da1a..f499d3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "adler32" version = "1.2.0" @@ -23,6 +29,18 @@ version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + [[package]] name = "cc" version = "1.12.0" @@ -50,6 +68,35 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "crc32fast" version = "1.5.6" @@ -65,6 +112,32 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe" +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -83,12 +156,43 @@ version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -111,6 +215,132 @@ dependencies = [ "foldhash", ] +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "http" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "include-flate" version = "0.3.5" @@ -144,6 +374,22 @@ dependencies = [ "zstd", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + [[package]] name = "jieba-macros" version = "0.8.1" @@ -173,7 +419,7 @@ version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" dependencies = [ - "getrandom", + "getrandom 0.4.3", "libc", ] @@ -202,17 +448,45 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff7a10e427698aef6eef269482776debfef63384d30f13aad39a1a95e0e098fd" dependencies = [ - "hashbrown", + "hashbrown 0.16.1", "no_std_io2", "rle-decode-fast", ] +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "no_std_io2" version = "0.9.4" @@ -222,6 +496,24 @@ dependencies = [ "memchr", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + [[package]] name = "phf" version = "0.13.1" @@ -267,6 +559,21 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro-error-attr3" version = "3.1.1" @@ -342,6 +649,20 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys", +] + [[package]] name = "rle-decode-fast" version = "1.0.3" @@ -354,6 +675,41 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "serde" version = "1.0.229" @@ -361,6 +717,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -383,12 +740,31 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "siphasher" version = "1.0.4" @@ -401,6 +777,18 @@ version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "3.0.10" @@ -412,6 +800,28 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "telefind-app" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "telefind-bot", + "telefind-core", + "ureq", +] + [[package]] name = "telefind-bot" version = "0.1.0" @@ -427,6 +837,46 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinyvec" version = "1.13.3" @@ -448,6 +898,272 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + [[package]] name = "zstd" version = "0.14.5" diff --git a/Cargo.toml b/Cargo.toml index 2077cf1..f89b0a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/telefind-core", "crates/telefind-bot"] +members = ["crates/telefind-core", "crates/telefind-bot", "crates/telefind-app"] resolver = "2" [workspace.package] diff --git a/README.md b/README.md new file mode 100644 index 0000000..00ba7f3 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# telefind-rs + +Rust keyword search for public Telegram channels, groups, bots and posts. The executable runs with an in-memory index. It accepts records from the caller and new channel updates delivered to the bot. + +## Try a query locally + +From the workspace root: + +```sh +cargo run -p telefind-app -- query - '/search type:video 上海相机' <<'JSONL' +{"op":"upsert","kind":"post","id":-100501,"message_id":42,"username":"example_feed","title":"相机入门.mp4","body":"上海 摄影","media":"video"} +JSONL +``` + +This prints the reply as JSON, including a button with the URL `https://t.me/example_feed/42`. The example uses a fictional record. + +## Telegram bot + +Supply the bot token through the environment variable `TELEGRAM_BOT_TOKEN` and run: + +```sh +cargo run -p telefind-app -- bot events.jsonl +``` + +The input file is optional. The process identifies its username via `getMe`, then long-polls for incoming messages and sends search results with URL buttons. Type keywords in private chat or use `/search@YourBot keywords` in a group. In a public channel where the bot receives posts, incoming posts and edits update the in-memory index. For channels without a public username, protected posts and unsupported content, the bot skips indexing the message. Telegram does not send ordinary post-deletion notifications via this update stream. An upstream source can supply deletion events. If a reply reached Telegram but its HTTP acknowledgement was lost, retrying an update can send the reply twice. + +Use a leading `type:channel`, `type:group`, `type:bot`, `type:post`, `type:photo`, `type:video`, `type:audio` or `type:file` to filter. Double quotes require a contiguous phrase in one field. Use `/page 2 type:video 摄影` to repeat a query on another page. + +## Document input and storage + +Pass an ordered UTF-8 JSONL stream in a file, or pass `-` to read standard input until EOF. The executable replays it before processing queries. A directory record uses its Telegram numeric ID. A post uses its chat ID and positive message ID. An upsert replaces the previous version with the same identity. Run a delete with the same key, for example: + +```json +{"op":"delete","kind":"post","id":-100501,"message_id":42} +``` + +The process keeps no database or history archive. Restarting loads whichever input the caller supplies. For a persistent or concurrent host, implement `telefind_core::index::IndexStore` and its snapshot reader, then use `Engine::new(store)`. Pass the resulting engine to `telefind_app::telegram::run` with a `telefind_app::telegram::Client` to reuse the same polling and reply logic. The JSONL reader `telefind_app::input::load` also accepts any implementation of `SearchIndex`. + +## Verification + +`cargo test --workspace --locked` exercises the index, the executable with piped input, and Telegram Bot API requests against a loopback HTTP fixture. These tests use synthetic records. diff --git a/crates/telefind-app/Cargo.toml b/crates/telefind-app/Cargo.toml new file mode 100644 index 0000000..225fc1e --- /dev/null +++ b/crates/telefind-app/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "telefind-app" +version.workspace = true +edition.workspace = true +default-run = "telefind" + +[[bin]] +name = "telefind" +path = "src/main.rs" + +[dependencies] +telefind-core = { path = "../telefind-core" } +telefind-bot = { path = "../telefind-bot" } +ureq = { version = "3", features = ["json"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/crates/telefind-app/src/input.rs b/crates/telefind-app/src/input.rs new file mode 100644 index 0000000..4851c46 --- /dev/null +++ b/crates/telefind-app/src/input.rs @@ -0,0 +1,108 @@ +//! Line-delimited public document changes supplied by the caller. +use serde::Deserialize; +use std::{error::Error, io::BufRead}; +use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex}; + +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +enum Kind { + Channel, + Group, + Bot, + Post, +} + +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +enum Attachment { + Photo, + Video, + Audio, + File, +} +impl From for Media { + fn from(media: Attachment) -> Self { + match media { + Attachment::Photo => Media::Photo, + Attachment::Video => Media::Video, + Attachment::Audio => Media::Audio, + Attachment::File => Media::File, + } + } +} + +#[derive(Deserialize)] +struct Key { + kind: Kind, + id: i64, + message_id: Option, +} +impl Key { + fn resolve(&self) -> Result { + match (&self.kind, self.message_id) { + (Kind::Channel, None) => Ok(DocumentId::Channel(self.id)), + (Kind::Group, None) => Ok(DocumentId::Group(self.id)), + (Kind::Bot, None) => Ok(DocumentId::Bot(self.id)), + (Kind::Post, Some(n)) if n > 0 => Ok(DocumentId::Post { + chat: self.id, + message: n, + }), + _ => Err("message_id must be positive for a post and absent for a directory record"), + } + } +} + +#[derive(Deserialize)] +#[serde(tag = "op", rename_all = "lowercase")] +enum Change { + Upsert { + #[serde(flatten)] + key: Key, + username: String, + #[serde(default)] + title: String, + #[serde(default)] + body: String, + media: Option, + }, + Delete { + #[serde(flatten)] + key: Key, + }, +} + +pub fn load(reader: R, index: &mut S) -> Result<(), Box> +where + S::Error: Error + 'static, +{ + for (number, line) in reader.lines().enumerate() { + let line = line?; + if line.trim().is_empty() { + continue; + } + let context = |err: &str| format!("input line {}: {}", number + 1, err); + let change: Change = serde_json::from_str(&line).map_err(|e| context(&e.to_string()))?; + match change { + Change::Delete { key } => { + index.remove(key.resolve().map_err(context)?)?; + } + Change::Upsert { + key, + username, + title, + body, + media, + } => { + index.upsert(Document { + id: key.resolve().map_err(context)?, + username: PublicName::new(&username) + .ok_or_else(|| context("invalid public username"))?, + title, + body, + media: media.map(Into::into), + })?; + } + } + } + Ok(()) +} diff --git a/crates/telefind-app/src/lib.rs b/crates/telefind-app/src/lib.rs new file mode 100644 index 0000000..aa0eb96 --- /dev/null +++ b/crates/telefind-app/src/lib.rs @@ -0,0 +1,3 @@ +//! Integration entry points for hosts supplying their own search index. +pub mod input; +pub mod telegram; diff --git a/crates/telefind-app/src/main.rs b/crates/telefind-app/src/main.rs new file mode 100644 index 0000000..3d10ae3 --- /dev/null +++ b/crates/telefind-app/src/main.rs @@ -0,0 +1,58 @@ +use std::{ + env, + error::Error, + fs::File, + io::{self, BufReader}, + process::ExitCode, +}; +use telefind_app::{input, telegram}; +use telefind_core::MemoryIndex; + +const USAGE: &str = concat!( + "telefind bot [events.jsonl|-]\n", + "telefind query \n", + "Bot mode reads TELEGRAM_BOT_TOKEN. An optional JSONL input is consumed before polling." +); + +fn load(path: &str, index: &mut MemoryIndex) -> Result<(), Box> { + if path == "-" { + input::load(io::stdin().lock(), index) + } else { + input::load(BufReader::new(File::open(path)?), index) + } +} +fn run() -> Result<(), Box> { + let args: Vec<_> = env::args().skip(1).collect(); + let mut index = MemoryIndex::default(); + match args.first().map(String::as_str) { + Some("bot") if args.len() <= 2 => { + let token = + env::var("TELEGRAM_BOT_TOKEN").map_err(|_| "TELEGRAM_BOT_TOKEN is required")?; + let client = telegram::Client::new(&token)?; + if let Some(path) = args.get(1) { + load(path, &mut index)?; + } + telegram::run(&client, &mut index) + } + Some("query") if args.len() >= 3 => { + load(&args[1], &mut index)?; + let reply = telefind_bot::handle(&index, "telefind", &args[2..].join(" "))?; + println!("{}", serde_json::to_string(&telegram::render(reply))?); + Ok(()) + } + Some("--help" | "-h") => { + println!("{USAGE}"); + Ok(()) + } + _ => Err(USAGE.into()), + } +} +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(err) => { + eprintln!("{err}"); + ExitCode::FAILURE + } + } +} diff --git a/crates/telefind-app/src/telegram/client.rs b/crates/telefind-app/src/telegram/client.rs new file mode 100644 index 0000000..7cc8c27 --- /dev/null +++ b/crates/telefind-app/src/telegram/client.rs @@ -0,0 +1,99 @@ +use serde::{de::DeserializeOwned, Deserialize}; +use serde_json::Value; +use std::{fmt, time::Duration}; +use ureq::Agent; + +#[derive(Debug)] +pub struct Failure { + pub code: u16, + pub retry_after: Option, +} +impl Failure { + pub fn transient(&self) -> bool { + self.code == 0 || self.code == 429 || self.code >= 500 + } +} +impl fmt::Display for Failure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.code { + 0 => f.write_str("Telegram connection failed"), + 200..=299 => f.write_str("invalid Telegram API response"), + code => write!(f, "Telegram API failure (code {code})"), + } + } +} +impl std::error::Error for Failure {} + +#[derive(Deserialize)] +struct Response { + ok: bool, + result: Option, + error_code: Option, + parameters: Option, +} +#[derive(Deserialize)] +struct Parameters { + retry_after: Option, +} + +pub struct Client { + agent: Agent, + endpoint: String, +} +impl Client { + pub fn new(token: &str) -> Result { + let Some((id, secret)) = token.split_once(':') else { + return Err("invalid TELEGRAM_BOT_TOKEN"); + }; + if id.is_empty() + || secret.is_empty() + || !id.bytes().all(|b| b.is_ascii_digit()) + || !secret + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') + { + return Err("invalid TELEGRAM_BOT_TOKEN"); + } + Ok(Self::at(format!("https://api.telegram.org/bot{token}"))) + } + pub(super) fn at(endpoint: String) -> Self { + let config = Agent::config_builder() + .timeout_global(Some(Duration::from_secs(50))) + .max_redirects(0) + .http_status_as_error(false) + .build(); + Self { + agent: config.into(), + endpoint, + } + } + pub fn call(&self, method: &str, payload: &Value) -> Result { + // Transport errors may include the request URL, which contains the token. + let mut response = self + .agent + .post(format!("{}/{method}", self.endpoint)) + .send_json(payload) + .map_err(|_| Failure { + code: 0, + retry_after: None, + })?; + let status = response.status().as_u16(); + let envelope: Response = response.body_mut().read_json().map_err(|_| Failure { + code: status, + retry_after: None, + })?; + if envelope.ok { + return envelope.result.ok_or(Failure { + code: status, + retry_after: None, + }); + } + Err(Failure { + code: envelope.error_code.unwrap_or(status), + retry_after: envelope + .parameters + .and_then(|p| p.retry_after) + .map(Duration::from_secs), + }) + } +} diff --git a/crates/telefind-app/src/telegram/mod.rs b/crates/telefind-app/src/telegram/mod.rs new file mode 100644 index 0000000..c4d48a2 --- /dev/null +++ b/crates/telefind-app/src/telegram/mod.rs @@ -0,0 +1,83 @@ +mod client; +mod update; +use self::{ + client::Failure, + update::{dispatch, Update}, +}; +pub use client::Client; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::{error::Error, thread, time::Duration}; +use telefind_core::SearchIndex; +pub use update::render; + +fn with_retry( + mut operation: impl FnMut() -> Result>, +) -> Result> { + let mut delay = Duration::from_secs(1); + loop { + match operation() { + Err(err) => { + let Some(failure) = err.downcast_ref::().filter(|e| e.transient()) else { + return Err(err); + }; + let wait = failure + .retry_after + .unwrap_or(delay) + .max(Duration::from_secs(1)); + eprintln!("{failure}; retrying in {}s", wait.as_secs()); + thread::sleep(wait); + delay = (delay * 2).min(Duration::from_secs(60)); + } + Ok(value) => return Ok(value), + } + } +} + +#[derive(Deserialize)] +struct BotInfo { + username: String, +} +pub fn run(client: &Client, index: &mut S) -> Result<(), Box> +where + S::Error: Error + 'static, +{ + let bot: BotInfo = with_retry(|| Ok(client.call("getMe", &json!({}))?))?; + let mut offset = None; + loop { + with_retry(|| poll(client, index, &bot.username, &mut offset))?; + } +} + +fn poll( + client: &Client, + index: &mut S, + bot: &str, + offset: &mut Option, +) -> Result<(), Box> +where + S::Error: Error + 'static, +{ + let mut request = json!({"timeout":25,"limit":32,"allowed_updates":["message","channel_post","edited_channel_post"]}); + if let Some(next) = offset { + request["offset"] = json!(next); + } + let batch: Vec = client.call("getUpdates", &request)?; + for update in batch { + if let Some(payload) = dispatch(index, bot, &update)? { + match client.call::("sendMessage", &payload) { + Ok(_) => (), + // Deleted chats and blocked bots must not stall the rest of the batch. + Err(err) if matches!(err.code, 400 | 403) => { + eprintln!("sendMessage for update {}: {err}", update.update_id) + } + Err(err) => return Err(err.into()), + } + } + *offset = Some(update.update_id + 1); + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/telefind-app/src/telegram/tests.rs b/crates/telefind-app/src/telegram/tests.rs new file mode 100644 index 0000000..739ddaa --- /dev/null +++ b/crates/telefind-app/src/telegram/tests.rs @@ -0,0 +1,158 @@ +use super::*; +use std::{ + io::{BufRead, BufReader, Read, Write}, + net::TcpListener, +}; +use telefind_core::MemoryIndex; + +fn respond(server: &TcpListener, reply: impl FnOnce(&str, Value) -> (u16, String)) { + let (mut socket, _) = server.accept().unwrap(); + let mut reader = BufReader::new(&socket); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let mut size = 0; + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert!(!line.is_empty(), "unexpected end of headers"); + if line == "\r\n" { + break; + } + if let Some((_, n)) = line + .to_lowercase() + .strip_prefix("content-length") + .and_then(|s| s.split_once(':')) + { + size = n.trim().parse().unwrap(); + } + } + let mut bytes = vec![0; size]; + reader.read_exact(&mut bytes).unwrap(); + let req: Value = serde_json::from_slice(&bytes).unwrap(); + let (status, body) = reply(&first, req); + write!( + socket, + "HTTP/1.1 {status} Response\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ) + .unwrap(); +} + +#[test] +fn actual_http_client_handles_live_edit_and_returns_keyboard_and_offset() { + // Loopback only. Exercise real HTTP serialization in both directions. + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = server.local_addr().unwrap(); + let peer = thread::spawn(move || { + let channel = json!({"id":-123,"type":"channel","username":"photofeed","title":"摄影频道"}); + let user = json!({"id":9,"type":"private"}); + let batch = json!([ + {"update_id":1,"channel_post":{"message_id":11,"chat":channel,"text":"旧教程"}}, + {"update_id":2,"edited_channel_post":{"message_id":11,"chat":channel,"caption":"摄影 新教程","video":{"file_name":"入门.mp4"}}}, + {"update_id":3,"message":{"message_id":1,"chat":user,"text":"/search type:video 新教程"}}, + {"update_id":4,"message":{"message_id":2,"chat":user,"text":"旧教程"}} + ]); + for step in 0..4 { + respond(&server, |first, req| { + let result = match step { + 0 => { + assert!(first.contains("/getUpdates ")); + assert!(req.get("offset").is_none()); + batch.clone() + } + 1 => { + assert!(first.contains("/sendMessage ")); + assert_eq!(req["chat_id"], 9); + assert_eq!( + req["reply_markup"]["inline_keyboard"][0][0]["url"], + "https://t.me/photofeed/11" + ); + json!({}) + } + 2 => { + assert_eq!(req["text"], "没有找到匹配结果。"); + json!({}) + } + _ => { + assert_eq!(req["offset"], 5); + json!([]) + } + }; + let body = json!({"ok":true,"result":result}).to_string(); + (200, body) + }); + } + }); + let client = Client::at(format!("http://{address}/botTest")); + let mut offset = None; + let mut index = MemoryIndex::default(); + poll(&client, &mut index, "searchbot", &mut offset).unwrap(); + poll(&client, &mut index, "searchbot", &mut offset).unwrap(); + peer.join().unwrap(); +} + +#[test] +fn nonpublic_and_protected_updates_do_not_add_searchable_posts() { + let mut index = MemoryIndex::default(); + for (name, protected) in [(Value::Null, false), (json!("demo_channel"), true)] { + let update = serde_json::from_value(json!({"update_id":1,"channel_post":{ + "message_id":2,"chat":{"id":9,"type":"channel","username":name}, + "text":"private phrase","has_protected_content":protected + }})) + .unwrap(); + assert!(dispatch(&mut index, "mybot", &update).unwrap().is_none()); + } + assert_eq!( + index + .search(&telefind_core::Query::new("private")) + .unwrap() + .total, + 0 + ); +} + +#[test] +fn flood_wait_keeps_failed_update_pending_and_preserves_prior_progress() { + let server = TcpListener::bind("127.0.0.1:0").unwrap(); + let client = Client::at(format!("http://{}/botTest", server.local_addr().unwrap())); + let peer = thread::spawn(move || { + let query = json!({"update_id":22,"message":{"message_id":1,"chat":{"id":9,"type":"private"},"text":"example"}}); + respond(&server, |_, _| { + ( + 200, + json!({"ok":true,"result":[{"update_id":21},query]}).to_string(), + ) + }); + respond(&server, |_, _| { + ( + 429, + json!({"ok":false,"error_code":429,"parameters":{"retry_after":7}}).to_string(), + ) + }); + respond(&server, |_, request| { + assert_eq!(request["offset"], 22); + (200, json!({"ok":true,"result":[query]}).to_string()) + }); + respond(&server, |_, _| { + (403, json!({"ok":false,"error_code":403}).to_string()) + }); + respond(&server, |_, _| { + (401, json!({"ok":false,"error_code":401}).to_string()) + }); + }); + let mut offset = None; + let mut index = MemoryIndex::default(); + let err = poll(&client, &mut index, "searchbot", &mut offset).unwrap_err(); + let flood = err.downcast_ref::().unwrap(); + assert!(flood.transient()); + assert_eq!(flood.retry_after, Some(Duration::from_secs(7))); + assert_eq!(offset, Some(22)); + poll(&client, &mut index, "searchbot", &mut offset).unwrap(); + assert_eq!(offset, Some(23)); + assert!(run(&client, &mut index) + .unwrap_err() + .to_string() + .contains("401")); + peer.join().unwrap(); +} diff --git a/crates/telefind-app/src/telegram/update.rs b/crates/telefind-app/src/telegram/update.rs new file mode 100644 index 0000000..6471382 --- /dev/null +++ b/crates/telefind-app/src/telegram/update.rs @@ -0,0 +1,150 @@ +use serde::Deserialize; +use serde_json::{json, Value}; +use telefind_bot::{handle, Reply}; +use telefind_core::{Document, DocumentId, Media, PublicName, SearchIndex}; + +#[derive(Deserialize)] +pub struct Update { + pub update_id: i64, + message: Option, + channel_post: Option, + edited_channel_post: Option, +} + +#[derive(Deserialize)] +struct Chat { + id: i64, + #[serde(rename = "type")] + kind: String, + username: Option, + title: Option, +} +#[derive(Deserialize)] +struct File { + file_name: Option, +} +#[derive(Deserialize)] +struct Message { + chat: Chat, + message_id: u32, + text: Option, + caption: Option, + video: Option, + audio: Option, + document: Option, + photo: Option>, + #[serde(default)] + has_protected_content: bool, + message_thread_id: Option, +} + +impl Message { + fn attachment(&self) -> (Option, String) { + for (media, file) in [ + (Media::Video, &self.video), + (Media::Audio, &self.audio), + (Media::File, &self.document), + ] { + if let Some(file) = file { + return (Some(media), file.file_name.clone().unwrap_or_default()); + } + } + ( + self.photo + .as_ref() + .filter(|p| !p.is_empty()) + .map(|_| Media::Photo), + String::new(), + ) + } + fn index_post(&self, index: &mut S) -> Result<(), S::Error> { + if self.chat.kind != "channel" || self.message_id == 0 { + return Ok(()); + } + let id = DocumentId::Post { + chat: self.chat.id, + message: self.message_id, + }; + let Some(username) = self.chat.username.as_deref().and_then(PublicName::new) else { + index.remove(id)?; + return Ok(()); + }; + let (media, title) = self.attachment(); + let body = self + .text + .as_ref() + .or(self.caption.as_ref()) + .cloned() + .unwrap_or_default(); + if self.has_protected_content || (body.is_empty() && title.is_empty() && media.is_none()) { + index.remove(id)?; + return Ok(()); + } + index.upsert(Document { + id: DocumentId::Channel(self.chat.id), + username: username.clone(), + title: self.chat.title.clone().unwrap_or_default(), + body: String::new(), + media: None, + })?; + index.upsert(Document { + id, + username, + title, + body, + media, + }) + } +} + +pub fn render(reply: Reply) -> Option { + match reply { + Reply::Ignored => None, + Reply::Help => Some( + json!({"text":"发送关键词或 /search 关键词。可用 type:channel、group、bot、post、video、photo、audio、file 筛选;用 /page 页码 关键词 翻页。"}), + ), + Reply::Results { total, links } if links.is_empty() => Some( + json!({"text":if total == 0 {"没有找到匹配结果。".into()} else {format!("本页没有结果,共 {total} 条。")}}), + ), + Reply::Results { total, links } => { + let rows: Vec<_> = links + .into_iter() + .map(|link| json!([{"text":link.label,"url":link.url}])) + .collect(); + Some( + json!({"text":format!("共 {total} 条结果"),"reply_markup":{"inline_keyboard":rows}}), + ) + } + } +} + +pub fn dispatch( + index: &mut S, + bot: &str, + update: &Update, +) -> Result, S::Error> { + if let Some(post) = update + .channel_post + .as_ref() + .or(update.edited_channel_post.as_ref()) + { + post.index_post(index)?; + return Ok(None); + } + let Some(message) = update.message.as_ref() else { + return Ok(None); + }; + let Some(text) = message.text.as_deref() else { + return Ok(None); + }; + if message.chat.kind != "private" && !text.trim_start().starts_with('/') { + return Ok(None); + } + Ok(render(handle(index, bot, text)?).map(|mut payload| { + payload["chat_id"] = json!(message.chat.id); + if let Some(thread) = message.message_thread_id { + payload["message_thread_id"] = json!(thread); + } + payload + })) +} diff --git a/crates/telefind-app/tests/cli.rs b/crates/telefind-app/tests/cli.rs new file mode 100644 index 0000000..f159fdb --- /dev/null +++ b/crates/telefind-app/tests/cli.rs @@ -0,0 +1,56 @@ +use serde_json::{json, Value}; +use std::{ + io::Write, + process::{Command, Stdio}, +}; + +#[test] +fn executable_replays_external_changes_and_returns_a_public_link() { + let mut child = Command::new(env!("CARGO_BIN_EXE_telefind")) + .args(["query", "-", "相机"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + { + let mut input = child.stdin.take().unwrap(); + for row in [ + json!({"op":"upsert","kind":"channel","id":9,"username":"photocn","title":"相机"}), + json!({"op":"upsert","kind":"post","id":9,"message_id":4,"username":"photocn","body":"相机"}), + json!({"op":"delete","kind":"channel","id":9}), + ] { + writeln!(input, "{row}").unwrap(); + } + } + let response = child.wait_with_output().unwrap(); + assert!(response.status.success()); + let result: Value = serde_json::from_slice(&response.stdout).unwrap(); + assert_eq!(result["text"], "共 1 条结果"); + assert_eq!( + result["reply_markup"]["inline_keyboard"][0][0]["url"], + "https://t.me/photocn/4" + ); +} + +#[test] +fn invalid_record_reports_its_line_and_fails_before_search() { + let mut child = Command::new(env!("CARGO_BIN_EXE_telefind")) + .args(["query", "-", "demo"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(b"\n{\"op\":\"delete\",\"kind\":\"post\",\"id\":5}\n") + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8(output.stderr) + .unwrap() + .contains("input line 2")); +} -- 2.52.0