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