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