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); + } +}