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