Lines of
src/core.rs
from check-in 2c36f015d8
that are changed by the sequence of edits moving toward
check-in a2880e5100:
1: use anyhow::{anyhow, bail, Context, Result};
2: use async_std::task;
3: use chrono::DateTime;
4: use sqlx::postgres::PgPoolOptions;
2c36f015d8 2024-11-23 5: use telegram_bot::{
2c36f015d8 2024-11-23 6: _base::Error as TgrError,
2c36f015d8 2024-11-23 7: Error as TgError,
8: };
9: use thiserror::Error;
10:
11: use std::{
12: borrow::Cow,
13: collections::{
14: BTreeMap,
15: HashSet,
16: },
17: num::TryFromIntError,
18: sync::{
19: Arc,
20: Mutex
21: },
22: };
23:
24: #[derive(Error, Debug)]
25: pub enum RssError {
2c36f015d8 2024-11-23 26: #[error(transparent)]
2c36f015d8 2024-11-23 27: Tg(#[from] TgError),
28: #[error(transparent)]
29: Int(#[from] TryFromIntError),
30: }
31:
32: #[derive(Clone)]
33: pub struct Core {
2c36f015d8 2024-11-23 34: owner_chat: telegram_bot::UserId,
2c36f015d8 2024-11-23 35: pub tg: telegram_bot::Api,
2c36f015d8 2024-11-23 36: pub my: telegram_bot::User,
37: pool: sqlx::Pool<sqlx::Postgres>,
38: sources: Arc<Mutex<HashSet<Arc<i32>>>>,
39: http_client: reqwest::Client,
40: }
41:
42: impl Core {
43: pub fn new(settings: config::Config) -> Result<Arc<Core>> {
2c36f015d8 2024-11-23 44: let owner = settings.get_int("owner")?;
45: let api_key = settings.get_string("api_key")?;
2c36f015d8 2024-11-23 46: let tg = telegram_bot::Api::new(api_key);
47: let tg_cloned = tg.clone();
48:
49: let mut client = reqwest::Client::builder();
50: if let Ok(proxy) = settings.get_string("proxy") {
51: let proxy = reqwest::Proxy::all(proxy)?;
52: client = client.proxy(proxy);
53: }
54: let http_client = client.build()?;
55: let core = Arc::new(Core {
56: tg,
57: my: task::block_on(async {
2c36f015d8 2024-11-23 58: tg_cloned.send(telegram_bot::GetMe).await
59: })?,
2c36f015d8 2024-11-23 60: owner_chat: telegram_bot::UserId::new(owner),
61: pool: PgPoolOptions::new()
62: .max_connections(5)
63: .acquire_timeout(std::time::Duration::new(300, 0))
64: .idle_timeout(std::time::Duration::new(60, 0))
65: .connect_lazy(&settings.get_string("pg")?)?,
66: sources: Arc::new(Mutex::new(HashSet::new())),
67: http_client,
68: });
2c36f015d8 2024-11-23 69: let clone = core.clone();
70: task::spawn(async move {
71: loop {
72: let delay = match &clone.autofetch().await {
73: Err(err) => {
74: if let Err(err) = clone.send(format!("š {:?}", err), None, None).await {
75: eprintln!("Autofetch error: {}", err);
76: };
77: std::time::Duration::from_secs(60)
78: },
79: Ok(time) => *time,
80: };
81: task::sleep(delay).await;
82: }
2c36f015d8 2024-11-23 83: });
84: Ok(core)
85: }
86:
2c36f015d8 2024-11-23 87: pub fn stream(&self) -> telegram_bot::UpdatesStream {
2c36f015d8 2024-11-23 88: self.tg.stream()
89: }
90:
91: pub async fn send<'a, S>(&self, msg: S, target: Option<telegram_bot::UserId>, mode: Option<telegram_bot::types::ParseMode>) -> Result<()>
92: where S: Into<Cow<'a, str>> {
93: let mode = mode.unwrap_or(telegram_bot::types::ParseMode::Html);
94: let target = target.unwrap_or(self.owner_chat);
95: self.request(telegram_bot::SendMessage::new(target, msg).parse_mode(mode)).await?;
96: Ok(())
2c36f015d8 2024-11-23 97: }
98:
2c36f015d8 2024-11-23 99: pub async fn request<Req: telegram_bot::Request> (&self, req: Req) -> Result<<Req::Response as telegram_bot::ResponseType>::Type, RssError> {
100: loop {
101: let res = self.tg.send(&req).await;
102: match res {
103: Ok(_) => return Ok(res?),
104: Err(err) => {
105: match &err {
106: TgError::Raw(TgrError::TelegramError { description: _, parameters: Some(params) }) => {
107: if let Some(delay) = params.retry_after {
108: println!("Throttled, waiting {} senconds.", delay);
109: task::sleep(std::time::Duration::from_secs(delay.try_into()?)).await;
110: } else {
111: return Err(err.into());
112: }
113: },
114: _ => return Err(err.into()),
115: }
116: },
117: };
118: }
2c36f015d8 2024-11-23 119: }
120:
2c36f015d8 2024-11-23 121: pub async fn check<S>(&self, id: &i32, owner: S, real: bool) -> Result<Cow<'_, str>>
122: where S: Into<i64> {
123: let owner = owner.into();
124: let mut posted: i32 = 0;
125: let mut conn = self.pool.acquire().await?;
126:
127: let id = {
128: let mut set = self.sources.lock().unwrap();
129: match set.get(id) {
130: Some(id) => id.clone(),
131: None => {
132: let id = Arc::new(*id);
133: set.insert(id.clone());
134: id.clone()
135: },
136: }
137: };
138: let count = Arc::strong_count(&id);
139: if count == 2 {
140: let source = sqlx::query!("select source_id, channel_id, url, iv_hash, owner, url_re from rsstg_source where source_id = $1 and owner = $2",
141: *id, owner).fetch_one(&mut *conn).await?;
142: let destination = match real {
143: true => telegram_bot::UserId::new(source.channel_id),
144: false => telegram_bot::UserId::new(source.owner),
145: };
146: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
147: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
148:
149: let response = self.http_client.get(&source.url).send().await?;
150: let status = response.status();
151: let content = response.bytes().await?;
152: match rss::Channel::read_from(&content[..]) {
153: Ok(feed) => {
154: for item in feed.items() {
155: if let Some(link) = item.link() {
156: let date = match item.pub_date() {
157: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
158: None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]),
159: }?;
160: let url = link;
161: posts.insert(date, url.to_string());
162: }
163: };
164: },
165: Err(err) => match err {
166: rss::Error::InvalidStartTag => {
167: match atom_syndication::Feed::read_from(&content[..]) {
168: Ok(feed) => {
169: for item in feed.entries() {
170: let date = item.published().unwrap();
171: let url = item.links()[0].href();
172: posts.insert(*date, url.to_string());
173: };
174: },
175: Err(err) => {
176: bail!("Unsupported or mangled content:\n{:?}\n{:#?}\n{:#?}\n", &source.url, err, status)
177: },
178: }
179: },
180: rss::Error::Eof => (),
181: _ => bail!("Unsupported or mangled content:\n{:?}\n{:#?}\n{:#?}\n", &source.url, err, status)
182: }
183: };
184: for (date, url) in posts.iter() {
185: let post_url: Cow<str> = match source.url_re {
186: Some(ref x) => sedregex::ReplaceCommand::new(x)?.execute(url),
187: None => url.into(),
188: };
189: if let Some(exists) = sqlx::query!("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;",
190: &post_url, *id).fetch_one(&mut *conn).await?.exists {
191: if ! exists {
192: if this_fetch.is_none() || *date > this_fetch.unwrap() {
193: this_fetch = Some(*date);
194: };
195: self.request( match &source.iv_hash {
196: Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", &post_url, hash)),
197: None => telegram_bot::SendMessage::new(destination, format!("{}", post_url)),
198: }.parse_mode(telegram_bot::types::ParseMode::Html)).await
199: .context("Can't post message:")?;
200: sqlx::query!("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);",
201: *id, date, &post_url).execute(&mut *conn).await?;
202: };
203: };
204: posted += 1;
205: };
206: posts.clear();
207: };
208: sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
209: *id).execute(&mut *conn).await?;
210: Ok(format!("Posted: {}", &posted).into())
2c36f015d8 2024-11-23 211: }
212:
2c36f015d8 2024-11-23 213: pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
214: where S: Into<i64> {
215: let owner = owner.into();
216:
217: match sqlx::query!("delete from rsstg_source where source_id = $1 and owner = $2;",
218: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
219: 0 => { Ok("No data found found.".into()) },
220: x => { Ok(format!("{} sources removed.", x).into()) },
221: }
2c36f015d8 2024-11-23 222: }
223:
2c36f015d8 2024-11-23 224: pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
225: where S: Into<i64> {
226: let owner = owner.into();
227:
228: match sqlx::query!("delete from rsstg_post p using rsstg_source s where p.source_id = $1 and owner = $2 and p.source_id = s.source_id;",
229: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
230: 0 => { Ok("No data found found.".into()) },
231: x => { Ok(format!("{} posts purged.", x).into()) },
232: }
2c36f015d8 2024-11-23 233: }
234:
2c36f015d8 2024-11-23 235: pub async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
236: where S: Into<i64> {
237: let owner = owner.into();
238:
239: match sqlx::query!("update rsstg_source set enabled = true where source_id = $1 and owner = $2",
240: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
241: 1 => { Ok("Source enabled.") },
242: 0 => { Ok("Source not found.") },
243: _ => { Err(anyhow!("Database error.")) },
244: }
2c36f015d8 2024-11-23 245: }
246:
2c36f015d8 2024-11-23 247: pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
248: where S: Into<i64> {
249: let owner = owner.into();
250:
251: match sqlx::query!("update rsstg_source set enabled = false where source_id = $1 and owner = $2",
252: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
253: 1 => { Ok("Source disabled.") },
254: 0 => { Ok("Source not found.") },
255: _ => { Err(anyhow!("Database error.")) },
256: }
2c36f015d8 2024-11-23 257: }
258:
2c36f015d8 2024-11-23 259: pub async fn update<S>(&self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: S) -> Result<&str>
260: where S: Into<i64> {
261: let owner = owner.into();
262: let mut conn = self.pool.acquire().await?;
263:
264: match match update {
265: Some(id) => {
266: sqlx::query!("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $5, channel = $6, url_re = $7 where source_id = $1",
267: id, channel_id, url, iv_hash, owner, channel, url_re).execute(&mut *conn).await
268: },
269: None => {
270: sqlx::query!("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)",
271: channel_id, url, iv_hash, owner, channel, url_re).execute(&mut *conn).await
272: },
273: } {
274: Ok(_) => Ok(match update {
275: Some(_) => "Channel updated.",
276: None => "Channel added.",
277: }),
278: Err(sqlx::Error::Database(err)) => {
279: match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
280: Some("_bt_check_unique", ) => {
281: Ok("Duplicate key.")
282: },
283: Some(_) => {
284: Ok("Database error.")
285: },
286: None => {
287: Ok("No database error extracted.")
288: },
289: }
290: },
291: Err(err) => {
292: bail!("Sorry, unknown error:\n{:#?}\n", err);
293: },
294: }
295: }
296:
297: async fn autofetch(&self) -> Result<std::time::Duration> {
298: let mut delay = chrono::Duration::minutes(1);
299: let now = chrono::Local::now();
300: let mut queue = sqlx::query!(r#"select source_id, next_fetch as "next_fetch: DateTime<chrono::Local>", owner from rsstg_order natural left join rsstg_source where next_fetch < now() + interval '1 minute';"#)
301: .fetch_all(&mut *self.pool.acquire().await?).await?;
302: for row in queue.iter() {
303: if let Some(next_fetch) = row.next_fetch {
304: if next_fetch < now {
305: if let (Some(owner), Some(source_id)) = (row.owner, row.source_id) {
306: let clone = Core {
307: owner_chat: telegram_bot::UserId::new(owner),
308: ..self.clone()
309: };
310: task::spawn(async move {
311: if let Err(err) = clone.check(&source_id, owner, true).await {
312: if let Err(err) = clone.send(&format!("š {:?}", err), None, None).await {
313: dbg!("Check error: {}", err);
314: // clone.disable(&source_id, owner).await.unwrap();
315: };
316: };
317: });
318: }
319: } else if next_fetch - now < delay {
320: delay = next_fetch - now;
321: }
322: }
323: };
324: queue.clear();
325: Ok(delay.to_std()?)
326: }
327:
328: pub async fn list<S>(&self, owner: S) -> Result<String>
329: where S: Into<i64> {
330: let owner = owner.into();
331:
332: let mut reply: Vec<Cow<str>> = vec![];
333: reply.push("Channels:".into());
334: let rows = sqlx::query!("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id",
335: owner).fetch_all(&mut *self.pool.acquire().await?).await?;
336: for row in rows.iter() {
337: reply.push(format!("\n\\#ļøā£ {} \\*ļøā£ `{}` {}\nš `{}`", row.source_id, row.channel,
338: match row.enabled {
339: true => "š enabled",
340: false => "ā disabled",
341: }, row.url).into());
342: if let Some(hash) = &row.iv_hash {
343: reply.push(format!("IV: `{}`", hash).into());
344: }
345: if let Some(re) = &row.url_re {
346: reply.push(format!("RE: `{}`", re).into());
347: }
348: };
349: Ok(reply.join("\n"))
2c36f015d8 2024-11-23 350: }
351: }