Lines of
src/core.rs
from check-in 42b29b744b
that are changed by the sequence of edits moving toward
check-in dc7c43b010:
1: use crate::{
2: command,
3: sql::Db,
4: };
5:
6: use std::{
7: borrow::Cow,
8: collections::{
9: BTreeMap,
10: HashSet,
11: },
12: };
13:
42b29b744b 2026-01-01 14: use async_std::{
42b29b744b 2026-01-01 15: task,
42b29b744b 2026-01-01 16: sync::{
42b29b744b 2026-01-01 17: Arc,
42b29b744b 2026-01-01 18: Mutex
42b29b744b 2026-01-01 19: },
42b29b744b 2026-01-01 20: };
21: use chrono::{
22: DateTime,
23: Local,
24: };
25: use lazy_static::lazy_static;
26: use regex::Regex;
27: use reqwest::header::{
28: CACHE_CONTROL,
29: EXPIRES,
30: LAST_MODIFIED
31: };
32: use tgbot::{
33: api::Client,
34: handler::UpdateHandler,
35: types::{
36: Bot,
37: ChatPeerId,
38: Command,
39: GetBot,
40: Message,
41: ParseMode,
42: SendMessage,
43: Update,
44: UpdateType,
45: UserPeerId,
46: },
47: };
48: use stacked_errors::{
49: Result,
50: StackableErr,
51: anyhow,
52: bail,
53: };
54:
55: lazy_static!{
56: pub static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap();
57: }
58:
59: /// Encodes special HTML entities to prevent them interfering with Telegram HTML
60: pub fn encode (text: &str) -> Cow<'_, str> {
61: RE_SPECIAL.replace_all(text, "\\$1")
62: }
63:
64: #[derive(Clone)]
65: pub struct Core {
66: owner_chat: ChatPeerId,
67: // max_delay: u16,
68: pub tg: Client,
69: pub me: Bot,
70: pub db: Db,
71: sources: Arc<Mutex<HashSet<Arc<i32>>>>,
72: http_client: reqwest::Client,
73: }
74:
75: impl Core {
76: pub async fn new(settings: config::Config) -> Result<Core> {
77: let owner_chat = ChatPeerId::from(settings.get_int("owner").stack()?);
78: let api_key = settings.get_string("api_key").stack()?;
79: let tg = Client::new(&api_key).stack()?
80: .with_host(settings.get_string("api_gateway").stack()?);
81:
82: let mut client = reqwest::Client::builder();
83: if let Ok(proxy) = settings.get_string("proxy") {
84: let proxy = reqwest::Proxy::all(proxy).stack()?;
85: client = client.proxy(proxy);
86: }
87: let http_client = client.build().stack()?;
88: let me = tg.execute(GetBot).await.stack()?;
89: let core = Core {
90: tg,
91: me,
92: owner_chat,
93: db: Db::new(&settings.get_string("pg").stack()?)?,
94: sources: Arc::new(Mutex::new(HashSet::new())),
95: http_client,
96: // max_delay: 60,
97: };
98: let clone = core.clone();
42b29b744b 2026-01-01 99: task::spawn(async move {
100: loop {
101: let delay = match &clone.autofetch().await {
102: Err(err) => {
103: if let Err(err) = clone.send(format!("š {err}"), None, None).await {
104: eprintln!("Autofetch error: {err:?}");
105: };
106: std::time::Duration::from_secs(60)
107: },
108: Ok(time) => *time,
109: };
42b29b744b 2026-01-01 110: task::sleep(delay).await;
111: }
42b29b744b 2026-01-01 112: });
113: Ok(core)
114: }
115:
116: pub async fn send <S>(&self, msg: S, target: Option<ChatPeerId>, mode: Option<ParseMode>) -> Result<Message>
117: where S: Into<String> {
118: let msg = msg.into();
119:
120: let mode = mode.unwrap_or(ParseMode::Html);
121: let target = target.unwrap_or(self.owner_chat);
122: self.tg.execute(
123: SendMessage::new(target, msg)
124: .with_parse_mode(mode)
125: ).await.stack()
126: }
127:
128: pub async fn check (&self, id: i32, real: bool, last_scrape: Option<DateTime<Local>>) -> Result<String> {
129: let mut posted: i32 = 0;
130: let mut conn = self.db.begin().await.stack()?;
131:
132: let id = {
133: let mut set = self.sources.lock_arc().await;
134: match set.get(&id) {
135: Some(id) => id.clone(),
136: None => {
137: let id = Arc::new(id);
138: set.insert(id.clone());
139: id.clone()
140: },
141: }
142: };
143: let count = Arc::strong_count(&id);
144: if count == 2 {
145: let source = conn.get_source(*id, self.owner_chat).await.stack()?;
146: conn.set_scrape(*id).await.stack()?;
147: let destination = ChatPeerId::from(match real {
148: true => source.channel_id,
149: false => source.owner,
150: });
151: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
42b29b744b 2026-01-01 152: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
153:
154: let mut builder = self.http_client.get(&source.url);
155: if let Some(last_scrape) = last_scrape {
156: builder = builder.header(LAST_MODIFIED, last_scrape.to_rfc2822());
157: };
158: let response = builder.send().await.stack()?;
159: {
160: let headers = response.headers();
161: let expires = headers.get(EXPIRES);
162: let cache = headers.get(CACHE_CONTROL);
163: if expires.is_some() || cache.is_some() {
164: println!("{} {} {:?} {:?} {:?}", Local::now().to_rfc2822(), &source.url, last_scrape, expires, cache);
165: }
166: }
167: let status = response.status();
168: let content = response.bytes().await.stack()?;
169: match rss::Channel::read_from(&content[..]) {
170: Ok(feed) => {
171: for item in feed.items() {
172: if let Some(link) = item.link() {
173: let date = match item.pub_date() {
174: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
175: None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]),
176: }.stack()?;
42b29b744b 2026-01-01 177: let url = link;
42b29b744b 2026-01-01 178: posts.insert(date, url.to_string());
179: }
180: };
181: },
182: Err(err) => match err {
183: rss::Error::InvalidStartTag => {
184: match atom_syndication::Feed::read_from(&content[..]) {
185: Ok(feed) => {
186: for item in feed.entries() {
187: let date = item.published().unwrap();
42b29b744b 2026-01-01 188: let url = item.links()[0].href();
42b29b744b 2026-01-01 189: posts.insert(*date, url.to_string());
190: };
191: },
192: Err(err) => {
193: bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
194: },
195: }
196: },
197: rss::Error::Eof => (),
198: _ => bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
199: }
200: };
42b29b744b 2026-01-01 201: for (date, url) in posts.iter() {
202: let post_url: Cow<str> = match source.url_re {
42b29b744b 2026-01-01 203: Some(ref x) => sedregex::ReplaceCommand::new(x).stack()?.execute(url),
42b29b744b 2026-01-01 204: None => url.into(),
205: };
206: if let Some(exists) = conn.exists(&post_url, *id).await.stack()? {
207: if ! exists {
208: if this_fetch.is_none() || *date > this_fetch.unwrap() {
209: this_fetch = Some(*date);
210: };
211: self.send( match &source.iv_hash {
212: Some(hash) => format!("<a href=\"https://t.me/iv?url={post_url}&rhash={hash}\"> </a>{post_url}"),
213: None => format!("{post_url}"),
214: }, Some(destination), Some(ParseMode::Html)).await.stack()?;
215: conn.add_post(*id, date, &post_url).await.stack()?;
216: };
217: };
218: posted += 1;
219: };
220: posts.clear();
221: };
222: Ok(format!("Posted: {posted}"))
223: }
224:
225: async fn autofetch(&self) -> Result<std::time::Duration> {
226: let mut delay = chrono::Duration::minutes(1);
227: let now = chrono::Local::now();
228: let queue = {
229: let mut conn = self.db.begin().await.stack()?;
230: conn.get_queue().await.stack()?
231: };
232: for row in queue {
233: if let Some(next_fetch) = row.next_fetch {
234: if next_fetch < now {
235: if let (Some(owner), Some(source_id), last_scrape) = (row.owner, row.source_id, row.last_scrape) {
236: let clone = Core {
237: owner_chat: ChatPeerId::from(owner),
238: ..self.clone()
239: };
240: let source = {
241: let mut conn = self.db.begin().await.stack()?;
242: match conn.get_one(owner, source_id).await {
243: Ok(Some(source)) => source.to_string(),
244: Ok(None) => "Source not found in database.stack()?".to_string(),
245: Err(err) => format!("Failed to fetch source data:\n{err}"),
246: }
247: };
42b29b744b 2026-01-01 248: task::spawn(async move {
249: if let Err(err) = clone.check(source_id, true, Some(last_scrape)).await {
250: if let Err(err) = clone.send(&format!("{source}\n\nš {}", encode(&err.to_string())), None, Some(ParseMode::MarkdownV2)).await {
251: eprintln!("Check error: {err}");
252: // clone.disable(&source_id, owner).await.unwrap();
253: };
254: };
42b29b744b 2026-01-01 255: });
256: }
257: } else if next_fetch - now < delay {
258: delay = next_fetch - now;
259: }
260: }
261: };
262: delay.to_std().stack()
263: }
264:
265: pub async fn list (&self, owner: UserPeerId) -> Result<String> {
266: let mut reply: Vec<String> = vec![];
267: reply.push("Channels:".into());
268: let mut conn = self.db.begin().await.stack()?;
269: for row in conn.get_list(owner).await.stack()? {
270: reply.push(row.to_string());
271: };
272: Ok(reply.join("\n\n"))
273: }
274: }
275:
276: impl UpdateHandler for Core {
277: async fn handle (&self, update: Update) {
278: if let UpdateType::Message(msg) = update.update_type {
279: if let Ok(cmd) = Command::try_from(msg) {
280: let msg = cmd.get_message();
281: let words = cmd.get_args();
282: let command = cmd.get_name();
283: let res = match command {
284: "/check" | "/clean" | "/enable" | "/delete" | "/disable" => command::command(self, command, msg, words).await,
285: "/start" => command::start(self, msg).await,
286: "/list" => command::list(self, msg).await,
287: "/add" | "/update" => command::update(self, command, msg, words).await,
288: any => Err(anyhow!("Unknown command: {any}")),
289: };
290: if let Err(err) = res {
291: if let Err(err2) = self.send(format!("\\#error\n```\n{err}\n```"),
292: Some(msg.chat.get_id()),
293: Some(ParseMode::MarkdownV2)
294: ).await{
295: dbg!(err2);
296: };
297: }
298: };
299: };
300: }
301: }