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