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