63 lines
2.1 KiB
Rust
63 lines
2.1 KiB
Rust
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)
|
|
}
|