Lines of
src/core.rs
from check-in dae6672b4d
that are changed by the sequence of edits moving toward
check-in 2f0b8bb368:
1: use crate::{
2: command,
3: sql::Db,
4: };
5:
6: use std::{
7: borrow::Cow,
8: collections::{
9: BTreeMap,
10: HashSet,
11: },
12: sync::Arc,
13: };
14:
15: use async_compat::Compat;
16: use chrono::{
17: DateTime,
18: Local,
19: };
20: use lazy_static::lazy_static;
21: use regex::Regex;
22: use reqwest::header::LAST_MODIFIED;
23: use smol::{
24: Timer,
25: lock::Mutex,
26: };
27: use tgbot::{
28: api::Client,
29: handler::UpdateHandler,
30: types::{
31: Bot,
32: ChatPeerId,
33: Command,
34: GetBot,
35: InputText,
36: Message,
37: ParseMode,
38: SendMessage,
39: Update,
40: UpdateType,
41: UserPeerId,
42: },
43: };
44: use stacked_errors::{
45: Result,
46: StackableErr,
47: anyhow,
48: bail,
49: };
50:
51: lazy_static!{
52: pub static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap();
53: }
54:
55: /// Escape characters that are special in Telegram MarkdownV2 by prefixing them with a backslash.
56: ///
57: /// This ensures the returned string can be used as MarkdownV2-formatted Telegram message content
58: /// without special characters being interpreted as MarkdownV2 markup.
59: pub fn encode (text: &str) -> Cow<'_, str> {
60: RE_SPECIAL.replace_all(text, "\\$1")
61: }
62:
63: // This one does nothing except making sure only one token exists for each id
64: pub struct Token {
65: running: Arc<Mutex<HashSet<i32>>>,
66: my_id: i32,
67: }
68:
69: impl Token {
70: /// Attempts to acquire a per-id token by inserting `my_id` into the shared `running` set.
71: ///
72: /// If the id was not already present, the function inserts it and returns `Some(Token)`.
73: /// When the returned `Token` is dropped, the id will be removed from the `running` set,
74: /// allowing subsequent acquisitions for the same id.
75: ///
76: /// # Parameters
77: ///
78: /// - `running`: Shared set tracking active ids.
79: /// - `my_id`: Identifier to acquire a token for.
80: ///
81: /// # Returns
82: ///
83: /// `Ok(Token)` if the id was successfully acquired, `Error` if a token for the id is already active.
84: async fn new (running: &Arc<Mutex<HashSet<i32>>>, my_id: i32) -> Result<Token> {
85: let running = running.clone();
86: let mut set = running.lock_arc().await;
87: if set.contains(&my_id) {
88: bail!("Token already taken");
89: } else {
90: set.insert(my_id);
91: Ok(Token {
92: running,
93: my_id,
94: })
95: }
96: }
97: }
98:
99: impl Drop for Token {
100: /// Releases this token's claim on the shared running-set when the token is dropped.
101: ///
102: /// The token's identifier is removed from the shared `running` set so that future
103: /// operations for the same id may proceed.
104: ///
105: /// TODO: is using block_on inside block_on safe? Currently tested and working fine.
106: fn drop (&mut self) {
107: smol::block_on(async {
108: let mut set = self.running.lock_arc().await;
109: set.remove(&self.my_id);
110: })
111: }
112: }
113:
114: #[derive(Clone)]
115: pub struct Core {
116: owner_chat: ChatPeerId,
117: // max_delay: u16,
118: pub tg: Client,
119: pub me: Bot,
120: pub db: Db,
121: running: Arc<Mutex<HashSet<i32>>>,
122: http_client: reqwest::Client,
123: }
124:
125: // XXX Right now that part is unfinished and I guess I need to finish menu first
126: #[allow(unused)]
127: pub struct Post {
128: uri: String,
129: title: String,
130: authors: String,
131: summary: String,
132: }
133:
134: impl Core {
135: /// Create a Core instance from configuration and start its background autofetch loop.
136: ///
137: /// The provided `settings` must include:
138: /// - `owner` (integer): chat id to use as the default destination,
139: /// - `api_key` (string): Telegram bot API key,
140: /// - `api_gateway` (string): Telegram API gateway host,
141: /// - `pg` (string): PostgreSQL connection string,
142: /// - optional `proxy` (string): proxy URL for the HTTP client.
143: ///
144: /// On success returns an initialized `Core` with Telegram and HTTP clients, database connection,
145: /// an empty running set for per-id tokens, and a spawned background task that periodically runs
146: /// `autofetch`. If any required setting is missing or initialization fails, an error is returned.
147: pub async fn new(settings: config::Config) -> Result<Core> {
148: let owner_chat = ChatPeerId::from(settings.get_int("owner").stack()?);
149: let api_key = settings.get_string("api_key").stack()?;
150: let tg = Client::new(&api_key).stack()?
151: .with_host(settings.get_string("api_gateway").stack()?);
152:
153: let mut client = reqwest::Client::builder();
154: if let Ok(proxy) = settings.get_string("proxy") {
155: let proxy = reqwest::Proxy::all(proxy).stack()?;
156: client = client.proxy(proxy);
157: }
158: let http_client = client.build().stack()?;
159: let me = tg.execute(GetBot).await.stack()?;
160: let core = Core {
161: tg,
162: me,
163: owner_chat,
164: db: Db::new(&settings.get_string("pg").stack()?)?,
165: running: Arc::new(Mutex::new(HashSet::new())),
166: http_client,
167: // max_delay: 60,
168: };
169: let clone = core.clone();
170: smol::spawn(Compat::new(async move {
171: loop {
172: let delay = match &clone.autofetch().await {
173: Err(err) => {
174: if let Err(err) = clone.send(format!("🛑 {err}"), None, None).await {
175: eprintln!("Autofetch error: {err:?}");
176: };
177: std::time::Duration::from_secs(60)
178: },
179: Ok(time) => *time,
180: };
181: Timer::after(delay).await;
182: }
183: })).detach();
184: Ok(core)
185: }
186:
187: pub async fn send <S>(&self, msg: S, target: Option<ChatPeerId>, mode: Option<ParseMode>) -> Result<Message>
188: where S: Into<String> {
189: let msg = msg.into();
190:
191: let mode = mode.unwrap_or(ParseMode::Html);
192: let target = target.unwrap_or(self.owner_chat);
193: self.tg.execute(
194: SendMessage::new(target, InputText::from(msg)
195: .with_format(mode))
196: ).await.stack()
197: }
198:
199: /// Fetches the feed for a source, sends any newly discovered posts to the appropriate chat, and records them in the database.
200: ///
201: /// This acquires a per-source guard to prevent concurrent checks for the same `id`. If a check is already running for
202: /// the given `id`, the function returns an error. If `last_scrape` is provided, it is sent as the `If-Modified-Since`
203: /// header to the feed request. The function parses RSS or Atom feeds, sends unseen post URLs to either the source's
204: /// channel (when `real` is true) or the source owner (when `real` is false), and persists posted entries so they are
205: /// not reposted later.
206: ///
207: /// Parameters:
208: /// - `id`: Identifier of the source to check.
209: /// - `real`: When `true`, send posts to the source's channel; when `false`, send to the source owner.
210: /// - `last_scrape`: Optional timestamp used to set the `If-Modified-Since` header for the HTTP request.
211: ///
212: /// # Returns
213: ///
214: /// `Posted: N` where `N` is the number of posts processed and sent.
215: pub async fn check (&self, id: i32, real: bool, last_scrape: Option<DateTime<Local>>) -> Result<String> {
216: let mut posted: i32 = 0;
217: let mut conn = self.db.begin().await.stack()?;
218:
219: let _token = Token::new(&self.running, id).await.stack()?;
220: let source = conn.get_source(id, self.owner_chat).await.stack()?;
221: conn.set_scrape(id).await.stack()?;
222: let destination = ChatPeerId::from(match real {
223: true => source.channel_id,
224: false => source.owner,
225: });
226: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
227: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, Post> = BTreeMap::new();
228:
229: let mut builder = self.http_client.get(&source.url);
230: if let Some(last_scrape) = last_scrape {
231: builder = builder.header(LAST_MODIFIED, last_scrape.to_rfc2822());
232: };
233: let response = builder.send().await.stack()?;
dae6672b4d 2026-09-13 234: #[cfg(debug_assertions)]
dae6672b4d 2026-09-13 235: {
236: let headers = response.headers();
237: let expires = headers.get(EXPIRES);
238: let cache = headers.get(CACHE_CONTROL);
239: if expires.is_some() || cache.is_some() {
240: println!("{} {} {:?} {:?} {:?}", Local::now().to_rfc2822(), source.url, last_scrape, expires, cache);
dae6672b4d 2026-09-13 241: }
dae6672b4d 2026-09-13 242: }
243: let status = response.status();
244: let content = response.bytes().await.stack()?;
245: match rss::Channel::read_from(&content[..]) {
246: Ok(feed) => {
247: for item in feed.items() {
248: if let Some(link) = item.link() {
249: let date = match item.pub_date() {
250: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
251: None => DateTime::parse_from_rfc3339(match item.dublin_core_ext() {
252: Some(ext) => {
253: let dates = ext.dates();
254: if dates.is_empty() {
255: bail!("Feed item has Dublin Core extension but no dates.")
256: } else {
257: &dates[0]
258: }
259: },
260: None => bail!("Feed item misses posting date."),
261: }),
262: }.stack()?;
263: let uri = link.to_string();
264: let title = item.title().unwrap_or("").to_string();
265: let authors = item.author().unwrap_or("").to_string();
266: let summary = item.content().unwrap_or("").to_string();
267: posts.insert(date, Post{
268: uri,
269: title,
270: authors,
271: summary,
272: });
273: }
274: };
275: },
276: Err(err) => match err {
277: rss::Error::InvalidStartTag => {
278: match atom_syndication::Feed::read_from(&content[..]) {
279: Ok(feed) => {
280: for item in feed.entries() {
281: let date = item.published()
282: .stack_err("Feed item missing publishing date.")?;
283: let uri = {
284: let links = item.links();
285: if links.is_empty() {
286: bail!("Feed item missing post links.");
287: } else {
288: links[0].href().to_string()
289: }
290: };
291: let title = item.title().to_string();
292: let authors = item.authors().iter().map(|x| format!("{} <{:?}>", x.name(), x.email())).collect::<Vec<String>>().join(", ");
293: let summary = if let Some(sum) = item.summary() { sum.value.clone() } else { String::new() };
294: posts.insert(*date, Post{
295: uri,
296: title,
297: authors,
298: summary,
299: });
300: };
301: },
302: Err(err) => {
303: bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
304: },
305: }
306: },
307: rss::Error::Eof => (),
308: _ => bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
309: }
310: };
311: for (date, post) in posts.iter() {
312: let post_url: Cow<str> = match source.url_re {
313: Some(ref x) => sedregex::ReplaceCommand::new(x).stack()?.execute(&post.uri),
314: None => post.uri.clone().into(),
315: };
316: if ! conn.exists(&post_url, id).await.stack()? {
317: if this_fetch.is_none() || *date > this_fetch.unwrap() {
318: this_fetch = Some(*date);
319: };
320: self.send( match &source.iv_hash {
321: Some(hash) => format!("<a href=\"https://t.me/iv?url={post_url}&rhash={hash}\"> </a>{post_url}"),
322: None => format!("{post_url}"),
323: }, Some(destination), Some(ParseMode::Html)).await.stack()?;
324: conn.add_post(id, date, &post_url).await.stack()?;
325: posted += 1;
326: };
327: };
328: posts.clear();
329: Ok(format!("Posted: {posted}"))
330: }
331:
332: async fn autofetch(&self) -> Result<std::time::Duration> {
333: let mut delay = chrono::Duration::minutes(1);
334: let now = chrono::Local::now();
335: let queue = {
336: let mut conn = self.db.begin().await.stack()?;
337: conn.get_queue().await.stack()?
338: };
339: for row in queue {
340: if let Some(next_fetch) = row.next_fetch {
341: if next_fetch < now {
342: if let (Some(owner), Some(source_id), last_scrape) = (row.owner, row.source_id, row.last_scrape) {
343: let clone = Core {
344: owner_chat: ChatPeerId::from(owner),
345: ..self.clone()
346: };
347: let source = {
348: let mut conn = self.db.begin().await.stack()?;
349: match conn.get_one(owner, source_id).await {
350: Ok(Some(source)) => source.to_string(),
351: Ok(None) => "Source not found in database?".to_string(),
352: Err(err) => format!("Failed to fetch source data:\n{err}"),
353: }
354: };
355: smol::spawn(Compat::new(async move {
356: if let Err(err) = clone.check(source_id, true, Some(last_scrape)).await {
357: if let Err(err) = clone.send(&format!("🛑 {source}\n{}", encode(&err.to_string())), None, Some(ParseMode::MarkdownV2)).await {
358: eprintln!("Check error: {err}");
359: // clone.disable(&source_id, owner).await.unwrap();
360: };
361: };
362: })).detach();
363: }
364: } else if next_fetch - now < delay {
365: delay = next_fetch - now;
366: }
367: }
368: };
369: delay.to_std().stack()
370: }
371:
372: pub async fn list (&self, owner: UserPeerId) -> Result<String> {
373: let mut reply: Vec<String> = vec![];
374: reply.push("Channels:".into());
375: let mut conn = self.db.begin().await.stack()?;
376: for row in conn.get_list(owner).await.stack()? {
377: reply.push(row.to_string());
378: };
379: Ok(reply.join("\n\n"))
380: }
381: }
382:
383: impl UpdateHandler for Core {
384: async fn handle (&self, update: Update) {
385: if let UpdateType::Message(msg) = update.update_type {
386: if let Ok(cmd) = Command::try_from(*msg) {
387: let msg = cmd.get_message();
388: let words = cmd.get_args();
389: let command = cmd.get_name();
390: let res = match command {
391: "/check" | "/clean" | "/enable" | "/delete" | "/disable" => command::command(self, command, msg, words).await,
392: "/start" => command::start(self, msg).await,
393: "/list" => command::list(self, msg).await,
394: "/add" | "/update" => command::update(self, command, msg, words).await,
395: any => Err(anyhow!("Unknown command: {any}")),
396: };
397: if let Err(err) = res {
398: if let Err(err2) = self.send(format!("\\#error\n```\n{err}\n```"),
399: Some(msg.chat.get_id()),
400: Some(ParseMode::MarkdownV2)
401: ).await {
402: let _ = dbg!(err2);
403: };
404: }
405: };
406: };
407: }
408: }