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