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