Lines of
src/core.rs
from check-in 1c444d34ff
that are changed by the sequence of edits moving toward
check-in 285ce2bc31:
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:
1c444d34ff 2024-08-28 125: let mut posted: i32 = 0;
126: let id = {
127: let mut set = self.sources.lock().unwrap();
128: match set.get(id) {
129: Some(id) => id.clone(),
130: None => {
131: let id = Arc::new(*id);
132: set.insert(id.clone());
133: id.clone()
134: },
135: }
136: };
137: let count = Arc::strong_count(&id);
138: if count == 2 {
139: 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",
1c444d34ff 2024-08-28 140: *id, owner).fetch_one(&mut self.pool.acquire().await?).await?;
141: let destination = match real {
142: true => telegram_bot::UserId::new(source.channel_id),
143: false => telegram_bot::UserId::new(source.owner),
144: };
145: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
146: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
147:
148: let response = self.http_client.get(&source.url).send().await?;
149: let status = response.status();
150: let content = response.bytes().await?;
151: match rss::Channel::read_from(&content[..]) {
152: Ok(feed) => {
153: for item in feed.items() {
154: if let Some(link) = item.link() {
155: let date = match item.pub_date() {
156: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
157: None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]),
158: }?;
159: let url = link;
160: posts.insert(date, url.to_string());
161: }
162: };
163: },
164: Err(err) => match err {
165: rss::Error::InvalidStartTag => {
166: let feed = atom_syndication::Feed::read_from(&content[..])
167: .with_context(|| format!("Problem opening feed url:\n{}\n{}", &source.url, status))?;
168: for item in feed.entries() {
169: let date = item.published().unwrap();
170: let url = item.links()[0].href();
171: posts.insert(*date, url.to_string());
172: };
173: },
174: rss::Error::Eof => (),
175: _ => bail!("Unsupported or mangled content:\n{:?}\n{:#?}\n{:#?}\n", &source.url, err, status)
176: }
177: };
178: for (date, url) in posts.iter() {
179: let post_url: Cow<str> = match source.url_re {
180: Some(ref x) => sedregex::ReplaceCommand::new(x)?.execute(url),
181: None => url.into(),
182: };
183: if let Some(exists) = sqlx::query!("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;",
1c444d34ff 2024-08-28 184: &post_url, *id).fetch_one(&mut self.pool.acquire().await?).await?.exists {
185: if ! exists {
186: if this_fetch.is_none() || *date > this_fetch.unwrap() {
187: this_fetch = Some(*date);
188: };
189: self.request( match &source.iv_hash {
190: Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", &post_url, hash)),
191: None => telegram_bot::SendMessage::new(destination, format!("{}", post_url)),
192: }.parse_mode(telegram_bot::types::ParseMode::Html)).await
193: .context("Can't post message:")?;
194: sqlx::query!("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);",
1c444d34ff 2024-08-28 195: *id, date, &post_url).execute(&mut self.pool.acquire().await?).await?;
196: };
197: };
198: posted += 1;
199: };
200: posts.clear();
201: };
202: sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
1c444d34ff 2024-08-28 203: *id).execute(&mut self.pool.acquire().await?).await?;
204: Ok(format!("Posted: {}", &posted).into())
205: }
206:
207: pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
208: where S: Into<i64> {
209: let owner = owner.into();
210:
211: match sqlx::query!("delete from rsstg_source where source_id = $1 and owner = $2;",
1c444d34ff 2024-08-28 212: source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
213: 0 => { Ok("No data found found.".into()) },
214: x => { Ok(format!("{} sources removed.", x).into()) },
215: }
216: }
217:
218: pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
219: where S: Into<i64> {
220: let owner = owner.into();
221:
222: 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;",
1c444d34ff 2024-08-28 223: source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
224: 0 => { Ok("No data found found.".into()) },
225: x => { Ok(format!("{} posts purged.", x).into()) },
226: }
227: }
228:
229: pub async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
230: where S: Into<i64> {
231: let owner = owner.into();
232:
233: match sqlx::query!("update rsstg_source set enabled = true where source_id = $1 and owner = $2",
1c444d34ff 2024-08-28 234: source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
235: 1 => { Ok("Source enabled.") },
236: 0 => { Ok("Source not found.") },
237: _ => { Err(anyhow!("Database error.")) },
238: }
239: }
240:
241: pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
242: where S: Into<i64> {
243: let owner = owner.into();
244:
245: match sqlx::query!("update rsstg_source set enabled = false where source_id = $1 and owner = $2",
1c444d34ff 2024-08-28 246: source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
247: 1 => { Ok("Source disabled.") },
248: 0 => { Ok("Source not found.") },
249: _ => { Err(anyhow!("Database error.")) },
250: }
251: }
252:
253: 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>
254: where S: Into<i64> {
255: let owner = owner.into();
256:
257: match match update {
258: Some(id) => {
259: 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",
1c444d34ff 2024-08-28 260: id, channel_id, url, iv_hash, owner, channel, url_re).execute(&mut self.pool.acquire().await?).await
261: },
262: None => {
263: sqlx::query!("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)",
1c444d34ff 2024-08-28 264: channel_id, url, iv_hash, owner, channel, url_re).execute(&mut self.pool.acquire().await?).await
265: },
266: } {
267: Ok(_) => Ok(match update {
268: Some(_) => "Channel updated.",
269: None => "Channel added.",
270: }),
271: Err(sqlx::Error::Database(err)) => {
272: match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
273: Some("_bt_check_unique", ) => {
274: Ok("Duplicate key.")
275: },
276: Some(_) => {
277: Ok("Database error.")
278: },
279: None => {
280: Ok("No database error extracted.")
281: },
282: }
283: },
284: Err(err) => {
285: bail!("Sorry, unknown error:\n{:#?}\n", err);
286: },
287: }
288: }
289:
290: async fn autofetch(&self) -> Result<std::time::Duration> {
291: let mut delay = chrono::Duration::minutes(1);
292: let now = chrono::Local::now();
293: 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';"#)
1c444d34ff 2024-08-28 294: .fetch_all(&mut self.pool.acquire().await?).await?;
295: for row in queue.iter() {
296: if let Some(next_fetch) = row.next_fetch {
297: if next_fetch < now {
298: if let (Some(owner), Some(source_id)) = (row.owner, row.source_id) {
299: let clone = Core {
300: owner_chat: telegram_bot::UserId::new(owner),
301: ..self.clone()
302: };
303: task::spawn(async move {
304: if let Err(err) = clone.check(&source_id, owner, true).await {
305: if let Err(err) = clone.send(&format!("š {:?}", err), None, None).await {
306: dbg!("Check error: {}", err);
307: // clone.disable(&source_id, owner).await.unwrap();
308: };
309: };
310: });
311: }
312: } else if next_fetch - now < delay {
313: delay = next_fetch - now;
314: }
315: }
316: };
317: queue.clear();
318: Ok(delay.to_std()?)
319: }
320:
321: pub async fn list<S>(&self, owner: S) -> Result<String>
322: where S: Into<i64> {
323: let owner = owner.into();
324:
325: let mut reply: Vec<Cow<str>> = vec![];
326: reply.push("Channels:".into());
327: let rows = sqlx::query!("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id",
328: owner).fetch_all(&mut *self.pool.acquire().await?).await?;
329: for row in rows.iter() {
330: reply.push(format!("\n\\#ļøā£ {} \\*ļøā£ `{}` {}\nš `{}`", row.source_id, row.channel,
331: match row.enabled {
332: true => "š enabled",
333: false => "ā disabled",
334: }, row.url).into());
335: if let Some(hash) = &row.iv_hash {
336: reply.push(format!("IV: `{}`", hash).into());
337: }
338: if let Some(re) = &row.url_re {
339: reply.push(format!("RE: `{}`", re).into());
340: }
341: };
342: Ok(reply.join("\n"))
343: }
344: }