Lines of
src/core.rs
from check-in 285ce2bc31
that are changed by the sequence of edits moving toward
check-in 2c36f015d8:
1: use anyhow::{anyhow, bail, Context, Result};
2: use async_std::task;
3: use chrono::DateTime;
4: use sqlx::postgres::PgPoolOptions;
5: use telegram_bot::{
6: _base::Error as TgrError,
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 {
26: #[error(transparent)]
27: Tg(#[from] TgError),
28: #[error(transparent)]
29: Int(#[from] TryFromIntError),
30: }
31:
32: #[derive(Clone)]
33: pub struct Core {
34: owner_chat: telegram_bot::UserId,
35: pub tg: telegram_bot::Api,
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>> {
44: let owner = settings.get_int("owner")?;
45: let api_key = settings.get_string("api_key")?;
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 {
58: tg_cloned.send(telegram_bot::GetMe).await
59: })?,
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: });
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: }
83: });
84: Ok(core)
85: }
86:
87: pub fn stream(&self) -> telegram_bot::UpdatesStream {
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(())
97: }
98:
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: }
119: }
120:
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 => {
285ce2bc31 2024-09-17 167: let feed = atom_syndication::Feed::read_from(&content[..])
285ce2bc31 2024-09-17 168: .with_context(|| format!("Problem opening feed url:\n{}\n{}", &source.url, status))?;
285ce2bc31 2024-09-17 169: for item in feed.entries() {
285ce2bc31 2024-09-17 170: let date = item.published().unwrap();
285ce2bc31 2024-09-17 171: let url = item.links()[0].href();
285ce2bc31 2024-09-17 172: posts.insert(*date, url.to_string());
285ce2bc31 2024-09-17 173: };
174: },
175: rss::Error::Eof => (),
176: _ => bail!("Unsupported or mangled content:\n{:?}\n{:#?}\n{:#?}\n", &source.url, err, status)
177: }
178: };
179: for (date, url) in posts.iter() {
180: let post_url: Cow<str> = match source.url_re {
181: Some(ref x) => sedregex::ReplaceCommand::new(x)?.execute(url),
182: None => url.into(),
183: };
184: if let Some(exists) = sqlx::query!("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;",
185: &post_url, *id).fetch_one(&mut *conn).await?.exists {
186: if ! exists {
187: if this_fetch.is_none() || *date > this_fetch.unwrap() {
188: this_fetch = Some(*date);
189: };
190: self.request( match &source.iv_hash {
191: Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", &post_url, hash)),
192: None => telegram_bot::SendMessage::new(destination, format!("{}", post_url)),
193: }.parse_mode(telegram_bot::types::ParseMode::Html)).await
194: .context("Can't post message:")?;
195: sqlx::query!("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);",
196: *id, date, &post_url).execute(&mut *conn).await?;
197: };
198: };
199: posted += 1;
200: };
201: posts.clear();
202: };
203: sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
204: *id).execute(&mut *conn).await?;
205: Ok(format!("Posted: {}", &posted).into())
206: }
207:
208: pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
209: where S: Into<i64> {
210: let owner = owner.into();
211:
212: match sqlx::query!("delete from rsstg_source where source_id = $1 and owner = $2;",
213: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
214: 0 => { Ok("No data found found.".into()) },
215: x => { Ok(format!("{} sources removed.", x).into()) },
216: }
217: }
218:
219: pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
220: where S: Into<i64> {
221: let owner = owner.into();
222:
223: 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;",
224: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
225: 0 => { Ok("No data found found.".into()) },
226: x => { Ok(format!("{} posts purged.", x).into()) },
227: }
228: }
229:
230: pub async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
231: where S: Into<i64> {
232: let owner = owner.into();
233:
234: match sqlx::query!("update rsstg_source set enabled = true where source_id = $1 and owner = $2",
235: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
236: 1 => { Ok("Source enabled.") },
237: 0 => { Ok("Source not found.") },
238: _ => { Err(anyhow!("Database error.")) },
239: }
240: }
241:
242: pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
243: where S: Into<i64> {
244: let owner = owner.into();
245:
246: match sqlx::query!("update rsstg_source set enabled = false where source_id = $1 and owner = $2",
247: source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
248: 1 => { Ok("Source disabled.") },
249: 0 => { Ok("Source not found.") },
250: _ => { Err(anyhow!("Database error.")) },
251: }
252: }
253:
254: 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>
255: where S: Into<i64> {
256: let owner = owner.into();
257: let mut conn = self.pool.acquire().await?;
258:
259: match match update {
260: Some(id) => {
261: 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",
262: id, channel_id, url, iv_hash, owner, channel, url_re).execute(&mut *conn).await
263: },
264: None => {
265: sqlx::query!("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)",
266: channel_id, url, iv_hash, owner, channel, url_re).execute(&mut *conn).await
267: },
268: } {
269: Ok(_) => Ok(match update {
270: Some(_) => "Channel updated.",
271: None => "Channel added.",
272: }),
273: Err(sqlx::Error::Database(err)) => {
274: match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
275: Some("_bt_check_unique", ) => {
276: Ok("Duplicate key.")
277: },
278: Some(_) => {
279: Ok("Database error.")
280: },
281: None => {
282: Ok("No database error extracted.")
283: },
284: }
285: },
286: Err(err) => {
287: bail!("Sorry, unknown error:\n{:#?}\n", err);
288: },
289: }
290: }
291:
292: async fn autofetch(&self) -> Result<std::time::Duration> {
293: let mut delay = chrono::Duration::minutes(1);
294: let now = chrono::Local::now();
295: 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';"#)
296: .fetch_all(&mut *self.pool.acquire().await?).await?;
297: for row in queue.iter() {
298: if let Some(next_fetch) = row.next_fetch {
299: if next_fetch < now {
300: if let (Some(owner), Some(source_id)) = (row.owner, row.source_id) {
301: let clone = Core {
302: owner_chat: telegram_bot::UserId::new(owner),
303: ..self.clone()
304: };
305: task::spawn(async move {
306: if let Err(err) = clone.check(&source_id, owner, true).await {
307: if let Err(err) = clone.send(&format!("š {:?}", err), None, None).await {
308: dbg!("Check error: {}", err);
309: // clone.disable(&source_id, owner).await.unwrap();
310: };
311: };
312: });
313: }
314: } else if next_fetch - now < delay {
315: delay = next_fetch - now;
316: }
317: }
318: };
319: queue.clear();
320: Ok(delay.to_std()?)
321: }
322:
323: pub async fn list<S>(&self, owner: S) -> Result<String>
324: where S: Into<i64> {
325: let owner = owner.into();
326:
327: let mut reply: Vec<Cow<str>> = vec![];
328: reply.push("Channels:".into());
329: let rows = sqlx::query!("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id",
330: owner).fetch_all(&mut *self.pool.acquire().await?).await?;
331: for row in rows.iter() {
332: reply.push(format!("\n\\#ļøā£ {} \\*ļøā£ `{}` {}\nš `{}`", row.source_id, row.channel,
333: match row.enabled {
334: true => "š enabled",
335: false => "ā disabled",
336: }, row.url).into());
337: if let Some(hash) = &row.iv_hash {
338: reply.push(format!("IV: `{}`", hash).into());
339: }
340: if let Some(re) = &row.url_re {
341: reply.push(format!("RE: `{}`", re).into());
342: }
343: };
344: Ok(reply.join("\n"))
345: }
346: }