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