Lines of
src/core.rs
from check-in 10c25017bb
that are changed by the sequence of edits moving toward
check-in fb629f170b:
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:
64: pub fn send<S>(&self, msg: S, target: Option<telegram_bot::UserId>, parse_mode: Option<telegram_bot::types::ParseMode>) -> Result<()>
65: where S: Into<String> {
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,
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;
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")?;
10c25017bb 2021-11-13 105: /*let url: Cow<'a, str> = match row.try_get("url") {
10c25017bb 2021-11-13 106: Ok(x) => String::from(x).to_owned().into(),
10c25017bb 2021-11-13 107: Err(err) => bail!("Test"),
10c25017bb 2021-11-13 108: };*/
109: let iv_hash: Option<&str> = row.try_get("iv_hash")?;
10c25017bb 2021-11-13 110: //let url_re: Option<sedregex::ReplaceCommand> = match row.try_get("url_re")? {
111: let url_re = match row.try_get("url_re")? {
112: Some(x) => Some(sedregex::ReplaceCommand::new(x)?),
113: None => None,
114: };
115: let destination = match real {
116: true => telegram_bot::UserId::new(channel_id),
117: false => telegram_bot::UserId::new(row.try_get("owner")?),
118: };
119: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
120: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
121: let content = reqwest::get(url).await?.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{}", &url))?;
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", &url, err)
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))?;
155: let row = sqlx::query("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;")
156: .bind(url)
157: .bind(*id)
158: .fetch_one(&mut conn).await
159: .with_context(|| format!("Check post:\n{:?}", &conn))?;
160: let exists: bool = row.try_get("exists")?;
161: if ! exists {
162: if this_fetch == None || *date > this_fetch.unwrap() {
163: this_fetch = Some(*date);
164: };
165: self.tg.send( match iv_hash {
166: Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", match url_re {
10c25017bb 2021-11-13 167: Some(x) => {
10c25017bb 2021-11-13 168: bail!("Regex hit, result:\n{:#?}", x.execute(url));
10c25017bb 2021-11-13 169: url
10c25017bb 2021-11-13 170: },
10c25017bb 2021-11-13 171: None => url,
172: }, hash)),
173: None => telegram_bot::SendMessage::new(destination, format!("{}", url)),
174: }.parse_mode(telegram_bot::types::ParseMode::Html)).await
175: .context("Can't post message:")?;
176: sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);")
177: .bind(*id)
178: .bind(date)
179: .bind(url)
180: .execute(&mut conn).await
181: .with_context(|| format!("Record post:\n{:?}", &conn))?;
182: drop(conn);
183: tokio::time::sleep(std::time::Duration::new(4, 0)).await;
184: };
185: posted += 1;
186: };
187: posts.clear();
188: };
189: let mut conn = self.pool.acquire().await
190: .with_context(|| format!("Update scrape fetch conn:\n{:?}", &self.pool))?;
191: sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
192: .bind(*id)
193: .execute(&mut conn).await
194: .with_context(|| format!("Update scrape:\n{:?}", &conn))?;
195: Ok(format!("Posted: {}", &posted))
196: }
197:
198: pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<String>
199: where S: Into<i64> {
200: let owner: i64 = owner.into();
201: let mut conn = self.pool.acquire().await
202: .with_context(|| format!("Delete fetch conn:\n{:?}", &self.pool))?;
203: match sqlx::query("delete from rsstg_source where source_id = $1 and owner = $2;")
204: .bind(source_id)
205: .bind(owner)
206: .execute(&mut conn).await
207: .with_context(|| format!("Delete source rule:\n{:?}", &self.pool))?
208: .rows_affected() {
209: 0 => { Ok("No data found found.".to_string()) },
210: x => { Ok(format!("{} sources removed.", x)) },
211: }
212: }
213:
214: pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<String>
215: where S: Into<i64> {
216: let owner: i64 = owner.into();
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() {
225: 0 => { Ok("No data found found.".to_string()) },
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: i64 = owner.into();
233: let mut conn = self.pool.acquire().await
234: .with_context(|| format!("Enable fetch conn:\n{:?}", &self.pool))?;
235: match sqlx::query("update rsstg_source set enabled = true where source_id = $1 and owner = $2")
236: .bind(source_id)
237: .bind(owner)
238: .execute(&mut conn).await
239: .with_context(|| format!("Enable source:\n{:?}", &self.pool))?
240: .rows_affected() {
241: 1 => { Ok("Source enabled.") },
242: 0 => { Ok("Source not found.") },
243: _ => { Err(anyhow!("Database error.")) },
244: }
245: }
246:
247: pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
248: where S: Into<i64> {
249: let owner: i64 = owner.into();
250: let mut conn = self.pool.acquire().await
251: .with_context(|| format!("Disable fetch conn:\n{:?}", &self.pool))?;
252: match sqlx::query("update rsstg_source set enabled = false where source_id = $1 and owner = $2")
253: .bind(source_id)
254: .bind(owner)
255: .execute(&mut conn).await
256: .with_context(|| format!("Disable source:\n{:?}", &self.pool))?
257: .rows_affected() {
258: 1 => { Ok("Source disabled.") },
259: 0 => { Ok("Source not found.") },
260: _ => { Err(anyhow!("Database error.")) },
261: }
262: }
263:
264: 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>
265: where S: Into<i64> {
266: let owner: i64 = owner.into();
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 {
10c25017bb 2021-11-13 322: //let clone = self.clone();
10c25017bb 2021-11-13 323: //clone.owner_chat(UserId::new(owner));
324: let clone = Core {
325: owner_chat: telegram_bot::UserId::new(owner),
326: ..self.clone()
327: };
328: tokio::spawn(async move {
329: if let Err(err) = clone.check(&source_id, owner, true).await {
330: if let Err(err) = clone.send(&format!("š {:?}", err), None, None) {
331: eprintln!("Check error: {}", err);
332: };
333: };
334: });
335: } else {
336: if next_fetch - now < delay {
337: delay = next_fetch - now;
338: }
339: }
340: };
341: queue.clear();
342: tokio::time::sleep(delay.to_std()?).await;
343: delay = chrono::Duration::minutes(1);
344: }
345: }
346:
347: pub async fn list<S>(&self, owner: S) -> Result<String>
348: where S: Into<i64> {
349: let owner = owner.into();
350: let mut reply = vec![];
351: let mut conn = self.pool.acquire().await
352: .with_context(|| format!("List fetch conn:\n{:?}", &self.pool))?;
353: reply.push("Channels:".to_string());
354: let rows = sqlx::query("select source_id, channel, enabled, url, iv_hash from rsstg_source where owner = $1 order by source_id")
355: .bind(owner)
356: .fetch_all(&mut conn).await?;
357: for row in rows.iter() {
358: let source_id: i32 = row.try_get("source_id")?;
359: let username: &str = row.try_get("channel")?;
360: let enabled: bool = row.try_get("enabled")?;
361: let url: &str = row.try_get("url")?;
362: let iv_hash: Option<&str> = row.try_get("iv_hash")?;
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: };
372: Ok(reply.join("\n"))
373: }
374: }