Lines of
src/command.rs
from check-in 3fd8c40aa8
that are changed by the sequence of edits moving toward
check-in be0b8602d1:
1: use crate::{
2: core::Core,
3: tg_bot::{
4: Callback,
5: MyMessage,
6: get_kb,
7: },
8: };
9:
10: use lazy_static::lazy_static;
11: use regex::Regex;
12: use sedregex::ReplaceCommand;
13: use stacked_errors::{
14: Result,
15: StackableErr,
16: bail,
17: };
18: use tgbot::types::{
19: CallbackQuery,
20: ChatMember,
21: ChatUsername,
22: GetChat,
23: GetChatAdministrators,
24: Message,
25: };
26: use url::Url;
27:
28: lazy_static! {
29: static ref RE_USERNAME: Regex = Regex::new(r"^@([a-zA-Z][a-zA-Z0-9_]+)$").unwrap();
30: static ref RE_IV_HASH: Regex = Regex::new(r"^[a-f0-9]{14}$").unwrap();
31: }
32:
33: /// Sends an informational message to the message's chat linking to the bot help channel.
34: pub async fn start (core: &Core, msg: &Message) -> Result<()> {
35: core.tg.send(MyMessage::html_to(
36: "We are open. Probably. Visit <a href=\"https://t.me/rsstg_bot_help/3\">channel</a>) for details.",
37: msg.chat.get_id()
38: )).await.stack()?;
39: Ok(())
40: }
41:
42: /// Send the sender's subscription list to the chat.
43: ///
44: /// Retrieves the message sender's user ID, obtains their subscription list from `core`,
45: /// and sends the resulting reply into the message chat using MarkdownV2.
46: pub async fn list (core: &Core, msg: &Message) -> Result<()> {
47: let sender = msg.sender.get_user_id()
48: .stack_err("Ignoring unreal users.")?;
49: let reply = core.list(sender).await.stack()?;
50: core.tg.send(MyMessage::html_to(reply, msg.chat.get_id())).await.stack()?;
51: Ok(())
52: }
53:
54: pub async fn test (core: &Core, msg: &Message) -> Result<()> {
55: let sender: i64 = msg.sender.get_user_id()
56: .stack_err("Ignoring unreal users.")?.into();
57: let feeds = core.get_feeds(sender).await.stack()?;
3fd8c40aa8 2026-03-30 58: let kb = get_kb(&Callback::menu(), feeds).await.stack()?;
59: core.tg.send(MyMessage::html_to_kb("Main menu:", msg.chat.get_id(), kb)).await.stack()?;
60: Ok(())
61: }
62:
63: /// Handle channel-management commands that operate on a single numeric source ID.
64: ///
65: /// This validates that exactly one numeric argument is provided, performs the requested
66: /// operation (check, clean, enable, delete, disable) against the database or core,
67: /// and sends the resulting reply to the chat.
68: ///
69: /// # Parameters
70: ///
71: /// - `core`: application core containing database and Telegram clients.
72: /// - `command`: command string (e.g. "/check", "/clean", "/enable", "/delete", "/disable").
73: /// - `msg`: incoming Telegram message that triggered the command; used to determine sender and chat.
74: /// - `words`: command arguments; expected to contain exactly one element that parses as a 32-bit integer.
75: pub async fn command (core: &Core, command: &str, msg: &Message, words: &[String]) -> Result<()> {
76: let mut conn = core.db.begin().await.stack()?;
77: let sender = msg.sender.get_user_id()
78: .stack_err("Ignoring unreal users.")?;
79: let reply = if words.len() == 1 {
80: match words[0].parse::<i32>() {
81: Err(err) => format!("I need a number.\n{}", &err).into(),
82: Ok(number) => match command {
83: "/check" => core.check(number, false, None).await
84: .context("Channel check failed.")?.into(),
85: "/clean" => conn.clean(number, sender).await.stack()?,
86: "/enable" => conn.enable(number, sender).await.stack()?.into(),
87: "/delete" => {
88: let res = conn.delete(number, sender).await.stack()?;
89: core.rm_feed(sender.into(), &number).await.stack()?;
90: res
91: }
92: "/disable" => conn.disable(number, sender).await.stack()?.into(),
93: _ => bail!("Command {command} {words:?} not handled."),
94: },
95: }
96: } else {
97: "This command needs exactly one number.".into()
98: };
99: core.tg.send(MyMessage::html_to(reply, msg.chat.get_id())).await.stack()?;
100: Ok(())
101: }
102:
103: /// Validate command arguments, check permissions and update or add a channel feed configuration in the database.
104: ///
105: /// This function parses and validates parameters supplied by a user command (either "/update <id> ..." or "/add ..."),
106: /// verifies the channel username and feed URL, optionally validates an IV hash and a replacement regexp,
107: /// ensures both the bot and the command sender are administrators of the target channel, and performs the database update.
108: ///
109: /// # Parameters
110: ///
111: /// - `command` — the invoked command, expected to be either `"/update"` (followed by a numeric source id) or `"/add"`.
112: /// - `msg` — the incoming Telegram message; used to derive the command sender and target chat id for the reply.
113: /// - `words` — the command arguments: for `"/add"` expected `channel url [iv_hash|'-'] [url_re|'-']`; for `"/update"`
114: /// the first element must be a numeric `source_id` followed by the same parameters.
115: pub async fn update (core: &Core, command: &str, msg: &Message, words: &[String]) -> Result<()> {
116: let sender = msg.sender.get_user_id()
117: .stack_err("Ignoring unreal users.")?;
118: let mut source_id: Option<i32> = None;
119: let at_least = "Requires at least 3 parameters.";
120: let mut i_words = words.iter();
121: match command {
122: "/update" => {
123: let next_word = i_words.next().context(at_least)?;
124: source_id = Some(next_word.parse::<i32>()
125: .context(format!("I need a number, but got {next_word}."))?);
126: },
127: "/add" => {},
128: _ => bail!("Passing {command} is not possible here."),
129: };
130: let (channel, url, iv_hash, url_re) = (
131: i_words.next().context(at_least)?,
132: i_words.next().context(at_least)?,
133: i_words.next(),
134: i_words.next());
135: if ! RE_USERNAME.is_match(channel) {
136: bail!("Usernames should be something like \"@\\[a\\-zA\\-Z]\\[a\\-zA\\-Z0\\-9\\_]+\", aren't they?\nNot {channel:?}");
137: };
138: {
139: let parsed_url = Url::parse(url)
140: .stack_err("Expecting a valid link to ATOM/RSS feed.")?;
141: match parsed_url.scheme() {
142: "http" | "https" => {},
143: scheme => {
144: bail!("Unsupported URL scheme: {scheme}");
145: },
146: };
147: }
148: let iv_hash = match iv_hash {
149: Some(hash) => {
150: match hash.as_ref() {
151: "-" => None,
152: thing => {
153: if ! RE_IV_HASH.is_match(thing) {
154: bail!("IV hash should be 14 hex digits.\nNot {thing:?}");
155: };
156: Some(thing)
157: },
158: }
159: },
160: None => None,
161: };
162: let url_re = match url_re {
163: Some(re) => {
164: match re.as_ref() {
165: "-" => None,
166: thing => {
167: let _url_rex = ReplaceCommand::new(thing).context("Regexp parsing error:")?;
168: Some(thing)
169: }
170: }
171: },
172: None => None,
173: };
174: let chat_id = ChatUsername::from(channel.as_ref());
175: let channel_id = core.tg.client.execute(GetChat::new(chat_id.clone())).await.stack_err("getting GetChat")?.id;
176: let chan_adm = core.tg.client.execute(GetChatAdministrators::new(chat_id)).await
177: .context("Sorry, I have no access to that chat.")?;
178: let (mut me, mut user) = (false, false);
179: for admin in chan_adm {
180: let member_id = match admin {
181: ChatMember::Creator(member) => member.user.id,
182: ChatMember::Administrator(member) => member.user.id,
183: ChatMember::Left(_)
184: | ChatMember::Kicked(_)
185: | ChatMember::Member{..}
186: | ChatMember::Restricted(_) => continue,
187: };
188: if member_id == core.tg.me.id {
189: me = true;
190: }
191: if member_id == sender {
192: user = true;
193: }
194: };
195: if ! me { bail!("I need to be admin on that channel."); };
196: if ! user { bail!("You should be admin on that channel."); };
197: let mut conn = core.db.begin().await.stack()?;
198: let update = conn.update(source_id, channel, channel_id, url, iv_hash, url_re, sender).await.stack()?;
199: core.tg.send(MyMessage::html_to(update, msg.chat.get_id())).await.stack()?;
200: if command == "/add" {
201: if let Some(new_record) = conn.get_one_name(sender, channel).await.stack()? {
202: core.add_feed(sender.into(), new_record.source_id, new_record.channel).await.stack()?;
203: } else {
204: bail!("Failed to read data on freshly inserted source.");
205: }
206: };
207: Ok(())
208: }