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