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