Shorten workspace directory names to app, bot and core

This commit is contained in:
2026-12-03 04:26:31 +08:00
parent 3ae1097e1b
commit ef251ae339
28 changed files with 4 additions and 4 deletions
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "telefind-bot"
version.workspace = true
edition.workspace = true
[dependencies]
telefind-core = { path = "../core" }
+62
View File
@@ -0,0 +1,62 @@
use telefind_core::{Kind, Media, Query};
pub(crate) enum Input<'a> {
Ignore,
Help,
Search(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 search(text, 1);
}
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) => search(query, 1),
("/page", args) => {
let Some((number, text)) = args.split_once(char::is_whitespace) else {
return Input::Help;
};
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)
}
+61
View File
@@ -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<ResultLink>,
},
}
/// 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<S: SearchIndex>(index: &S, bot: &str, text: &str) -> Result<Reply, S::Error> {
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::<Vec<_>>()
.join(" ")
.chars()
.take(60)
.collect();
ResultLink {
label: format!("{kind} · {compact}"),
url: doc.url(),
}
}
+134
View File
@@ -0,0 +1,134 @@
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);
}
}
#[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
);
}
#[test]
fn scoped_media_search_keeps_quoted_phrase_and_original_link() {
let mut index = MemoryIndex::default();
for (message, body) in [
(1, "Rust search"),
(2, "Rust search SALE"),
(3, "search Rust"),
] {
index
.upsert(Document {
id: DocumentId::Post { chat: 3, message },
username: PublicName::new("my_feed").unwrap(),
title: String::new(),
body: body.into(),
media: Some(telefind_core::Media::Video),
})
.unwrap();
}
let Reply::Results { total, links } = handle(
&index,
"me",
r#"/page@me 1 type:video from:@My_Feed exclude:sale "rust search""#,
)
.unwrap() else {
panic!("expected a search result")
};
assert_eq!(total, 1);
assert_eq!(links[0].url, "https://t.me/my_feed/1");
}