Lines of
src/core.rs
from check-in b23050a4ea
that are changed by the sequence of edits moving toward
check-in 704bf85f8c:
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:
b23050a4ea 2026-01-06 58: /// Encodes special HTML entities to prevent them interfering with Telegram HTML
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: 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: #[derive(Clone)]
113: pub struct Core {
114: owner_chat: ChatPeerId,
115: // max_delay: u16,
116: pub tg: Client,
117: pub me: Bot,
118: pub db: Db,
119: running: Arc<Mutex<HashSet<i32>>>,
120: http_client: reqwest::Client,
121: }
122:
123: pub struct Post {
124: uri: String,
125: title: String,
126: authors: String,
127: summary: String,
128: }
129:
130: impl Core {
131: pub async fn new(settings: config::Config) -> Result<Core> {
132: let owner_chat = ChatPeerId::from(settings.get_int("owner").stack()?);
133: let api_key = settings.get_string("api_key").stack()?;
134: let tg = Client::new(&api_key).stack()?
135: .with_host(settings.get_string("api_gateway").stack()?);
136:
137: let mut client = reqwest::Client::builder();
138: if let Ok(proxy) = settings.get_string("proxy") {
139: let proxy = reqwest::Proxy::all(proxy).stack()?;
140: client = client.proxy(proxy);
141: }
142: let http_client = client.build().stack()?;
143: let me = tg.execute(GetBot).await.stack()?;
144: let core = Core {
145: tg,
146: me,
147: owner_chat,
148: db: Db::new(&settings.get_string("pg").stack()?)?,
149: running: Arc::new(Mutex::new(HashSet::new())),
150: http_client,
151: // max_delay: 60,
152: };
153: let clone = core.clone();
154: smol::spawn(Compat::new(async move {
155: loop {
156: let delay = match &clone.autofetch().await {
157: Err(err) => {
158: if let Err(err) = clone.send(format!("🛑 {err}"), None, None).await {
159: eprintln!("Autofetch error: {err:?}");
160: };
161: std::time::Duration::from_secs(60)
162: },
163: Ok(time) => *time,
164: };
165: Timer::after(delay).await;
166: }
167: })).detach();
168: Ok(core)
169: }
170:
171: pub async fn send <S>(&self, msg: S, target: Option<ChatPeerId>, mode: Option<ParseMode>) -> Result<Message>
172: where S: Into<String> {
173: let msg = msg.into();
174:
175: let mode = mode.unwrap_or(ParseMode::Html);
176: let target = target.unwrap_or(self.owner_chat);
177: self.tg.execute(
178: SendMessage::new(target, msg)
179: .with_parse_mode(mode)
180: ).await.stack()
181: }
182:
183: pub async fn check (&self, id: i32, real: bool, last_scrape: Option<DateTime<Local>>) -> Result<String> {
184: let mut posted: i32 = 0;
185: let mut conn = self.db.begin().await.stack()?;
186:
187: let _token = Token::new(&self.running, id).await.stack()?;
188: let source = conn.get_source(id, self.owner_chat).await.stack()?;
189: conn.set_scrape(id).await.stack()?;
190: let destination = ChatPeerId::from(match real {
191: true => source.channel_id,
192: false => source.owner,
193: });
194: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
195: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, Post> = BTreeMap::new();
196:
197: let mut builder = self.http_client.get(&source.url);
198: if let Some(last_scrape) = last_scrape {
199: builder = builder.header(LAST_MODIFIED, last_scrape.to_rfc2822());
200: };
201: let response = builder.send().await.stack()?;
202: {
203: let headers = response.headers();
204: let expires = headers.get(EXPIRES);
205: let cache = headers.get(CACHE_CONTROL);
206: if expires.is_some() || cache.is_some() {
207: println!("{} {} {:?} {:?} {:?}", Local::now().to_rfc2822(), &source.url, last_scrape, expires, cache);
208: }
209: }
210: let status = response.status();
211: let content = response.bytes().await.stack()?;
212: match rss::Channel::read_from(&content[..]) {
213: Ok(feed) => {
214: for item in feed.items() {
215: if let Some(link) = item.link() {
216: let date = match item.pub_date() {
217: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
218: None => DateTime::parse_from_rfc3339(match item.dublin_core_ext() {
b23050a4ea 2026-01-06 219: Some(dates) => &dates.dates()[0],
220: None => bail!("Feed item misses posting date."),
221: }),
222: }.stack()?;
223: let uri = link.to_string();
224: let title = item.title().unwrap_or("").to_string();
225: let authors = item.author().unwrap_or("").to_string();
226: let summary = item.content().unwrap_or("").to_string();
227: posts.insert(date, Post{
228: uri,
229: title,
230: authors,
231: summary,
232: });
233: }
234: };
235: },
236: Err(err) => match err {
237: rss::Error::InvalidStartTag => {
238: match atom_syndication::Feed::read_from(&content[..]) {
239: Ok(feed) => {
240: for item in feed.entries() {
241: let date = item.published().unwrap();
242: let uri = item.links()[0].href().to_string();
243: let title = item.title().to_string();
244: let authors = item.authors().iter().map(|x| format!("{} <{:?}>", x.name(), x.email())).collect::<Vec<String>>().join(", ");
245: let summary = if let Some(sum) = item.summary() { sum.value.clone() } else { String::new() };
246: posts.insert(*date, Post{
247: uri,
248: title,
249: authors,
250: summary,
251: });
252: };
253: },
254: Err(err) => {
255: bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
256: },
257: }
258: },
259: rss::Error::Eof => (),
260: _ => bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
261: }
262: };
263: for (date, post) in posts.iter() {
264: let post_url: Cow<str> = match source.url_re {
265: Some(ref x) => sedregex::ReplaceCommand::new(x).stack()?.execute(&post.uri),
266: None => post.uri.clone().into(),
267: };
268: if let Some(exists) = conn.exists(&post_url, id).await.stack()? {
269: if ! exists {
270: if this_fetch.is_none() || *date > this_fetch.unwrap() {
271: this_fetch = Some(*date);
272: };
273: self.send( match &source.iv_hash {
274: Some(hash) => format!("<a href=\"https://t.me/iv?url={post_url}&rhash={hash}\"> </a>{post_url}"),
275: None => format!("{post_url}"),
276: }, Some(destination), Some(ParseMode::Html)).await.stack()?;
277: conn.add_post(id, date, &post_url).await.stack()?;
278: };
279: };
280: posted += 1;
281: };
282: posts.clear();
283: Ok(format!("Posted: {posted}"))
284: }
285:
286: async fn autofetch(&self) -> Result<std::time::Duration> {
287: let mut delay = chrono::Duration::minutes(1);
288: let now = chrono::Local::now();
289: let queue = {
290: let mut conn = self.db.begin().await.stack()?;
291: conn.get_queue().await.stack()?
292: };
293: for row in queue {
294: if let Some(next_fetch) = row.next_fetch {
295: if next_fetch < now {
296: if let (Some(owner), Some(source_id), last_scrape) = (row.owner, row.source_id, row.last_scrape) {
297: let clone = Core {
298: owner_chat: ChatPeerId::from(owner),
299: ..self.clone()
300: };
301: let source = {
302: let mut conn = self.db.begin().await.stack()?;
303: match conn.get_one(owner, source_id).await {
304: Ok(Some(source)) => source.to_string(),
305: Ok(None) => "Source not found in database?".to_string(),
306: Err(err) => format!("Failed to fetch source data:\n{err}"),
307: }
308: };
309: smol::spawn(Compat::new(async move {
310: if let Err(err) = clone.check(source_id, true, Some(last_scrape)).await {
311: if let Err(err) = clone.send(&format!("🛑 {source}\n{}", encode(&err.to_string())), None, Some(ParseMode::MarkdownV2)).await {
312: eprintln!("Check error: {err}");
313: // clone.disable(&source_id, owner).await.unwrap();
314: };
315: };
316: })).detach();
317: }
318: } else if next_fetch - now < delay {
319: delay = next_fetch - now;
320: }
321: }
322: };
323: delay.to_std().stack()
324: }
325:
326: pub async fn list (&self, owner: UserPeerId) -> Result<String> {
327: let mut reply: Vec<String> = vec![];
328: reply.push("Channels:".into());
329: let mut conn = self.db.begin().await.stack()?;
330: for row in conn.get_list(owner).await.stack()? {
331: reply.push(row.to_string());
332: };
333: Ok(reply.join("\n\n"))
334: }
335: }
336:
337: impl UpdateHandler for Core {
338: async fn handle (&self, update: Update) {
339: if let UpdateType::Message(msg) = update.update_type {
340: if let Ok(cmd) = Command::try_from(msg) {
341: let msg = cmd.get_message();
342: let words = cmd.get_args();
343: let command = cmd.get_name();
344: let res = match command {
345: "/check" | "/clean" | "/enable" | "/delete" | "/disable" => command::command(self, command, msg, words).await,
346: "/start" => command::start(self, msg).await,
347: "/list" => command::list(self, msg).await,
348: "/add" | "/update" => command::update(self, command, msg, words).await,
349: any => Err(anyhow!("Unknown command: {any}")),
350: };
351: if let Err(err) = res {
352: if let Err(err2) = self.send(format!("\\#error\n```\n{err}\n```"),
353: Some(msg.chat.get_id()),
354: Some(ParseMode::MarkdownV2)
355: ).await{
356: dbg!(err2);
357: };
358: }
359: };
360: };
361: }
362: }