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