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