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