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