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