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