0340541002 2025-04-24 1: use crate::{
0340541002 2025-04-24 2: command,
0340541002 2025-04-24 3: sql::Db,
0340541002 2025-04-24 4: };
1c444d34ff 2024-08-28 5:
9171c791eb 2021-11-13 6: use std::{
c1e27b74ed 2021-11-13 7: borrow::Cow,
9171c791eb 2021-11-13 8: collections::{
9171c791eb 2021-11-13 9: BTreeMap,
9171c791eb 2021-11-13 10: HashSet,
9171c791eb 2021-11-13 11: },
dc7c43b010 2026-01-01 12: sync::Arc,
44575a91d3 2025-07-09 13: };
44575a91d3 2025-07-09 14:
dc7c43b010 2026-01-01 15: use async_compat::Compat;
acb0a4ac54 2025-09-28 16: use chrono::{
acb0a4ac54 2025-09-28 17: DateTime,
acb0a4ac54 2025-09-28 18: Local,
44575a91d3 2025-07-09 19: };
5a4aab7687 2025-06-29 20: use lazy_static::lazy_static;
5a4aab7687 2025-06-29 21: use regex::Regex;
dae6672b4d 2026-09-13 22: use reqwest::header::LAST_MODIFIED;
dc7c43b010 2026-01-01 23: use smol::{
dc7c43b010 2026-01-01 24: Timer,
dc7c43b010 2026-01-01 25: lock::Mutex,
acb0a4ac54 2025-09-28 26: };
bb89b6fab8 2025-06-15 27: use tgbot::{
bb89b6fab8 2025-06-15 28: api::Client,
bb89b6fab8 2025-06-15 29: handler::UpdateHandler,
bb89b6fab8 2025-06-15 30: types::{
bb89b6fab8 2025-06-15 31: Bot,
bb89b6fab8 2025-06-15 32: ChatPeerId,
bb89b6fab8 2025-06-15 33: Command,
bb89b6fab8 2025-06-15 34: GetBot,
dae6672b4d 2026-09-13 35: InputText,
bb89b6fab8 2025-06-15 36: Message,
bb89b6fab8 2025-06-15 37: ParseMode,
bb89b6fab8 2025-06-15 38: SendMessage,
bb89b6fab8 2025-06-15 39: Update,
bb89b6fab8 2025-06-15 40: UpdateType,
bb89b6fab8 2025-06-15 41: UserPeerId,
1bd041d00f 2025-05-20 42: },
1bd041d00f 2025-05-20 43: };
44575a91d3 2025-07-09 44: use stacked_errors::{
44575a91d3 2025-07-09 45: Result,
44575a91d3 2025-07-09 46: StackableErr,
44575a91d3 2025-07-09 47: anyhow,
44575a91d3 2025-07-09 48: bail,
44575a91d3 2025-07-09 49: };
5a4aab7687 2025-06-29 50:
5a4aab7687 2025-06-29 51: lazy_static!{
5a4aab7687 2025-06-29 52: pub static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap();
5a4aab7687 2025-06-29 53: }
5a4aab7687 2025-06-29 54:
7393d62235 2026-01-07 55: /// Escape characters that are special in Telegram MarkdownV2 by prefixing them with a backslash.
7393d62235 2026-01-07 56: ///
7393d62235 2026-01-07 57: /// This ensures the returned string can be used as MarkdownV2-formatted Telegram message content
7393d62235 2026-01-07 58: /// without special characters being interpreted as MarkdownV2 markup.
5a4aab7687 2025-06-29 59: pub fn encode (text: &str) -> Cow<'_, str> {
5a4aab7687 2025-06-29 60: RE_SPECIAL.replace_all(text, "\\$1")
7393d62235 2026-01-07 61: }
7393d62235 2026-01-07 62:
7393d62235 2026-01-07 63: // This one does nothing except making sure only one token exists for each id
7393d62235 2026-01-07 64: pub struct Token {
7393d62235 2026-01-07 65: running: Arc<Mutex<HashSet<i32>>>,
7393d62235 2026-01-07 66: my_id: i32,
7393d62235 2026-01-07 67: }
7393d62235 2026-01-07 68:
7393d62235 2026-01-07 69: impl Token {
7393d62235 2026-01-07 70: /// Attempts to acquire a per-id token by inserting `my_id` into the shared `running` set.
7393d62235 2026-01-07 71: ///
7393d62235 2026-01-07 72: /// If the id was not already present, the function inserts it and returns `Some(Token)`.
7393d62235 2026-01-07 73: /// When the returned `Token` is dropped, the id will be removed from the `running` set,
7393d62235 2026-01-07 74: /// allowing subsequent acquisitions for the same id.
7393d62235 2026-01-07 75: ///
7393d62235 2026-01-07 76: /// # Parameters
7393d62235 2026-01-07 77: ///
7393d62235 2026-01-07 78: /// - `running`: Shared set tracking active ids.
7393d62235 2026-01-07 79: /// - `my_id`: Identifier to acquire a token for.
7393d62235 2026-01-07 80: ///
7393d62235 2026-01-07 81: /// # Returns
7393d62235 2026-01-07 82: ///
7393d62235 2026-01-07 83: /// `Ok(Token)` if the id was successfully acquired, `Error` if a token for the id is already active.
7393d62235 2026-01-07 84: async fn new (running: &Arc<Mutex<HashSet<i32>>>, my_id: i32) -> Result<Token> {
7393d62235 2026-01-07 85: let running = running.clone();
7393d62235 2026-01-07 86: let mut set = running.lock_arc().await;
7393d62235 2026-01-07 87: if set.contains(&my_id) {
7393d62235 2026-01-07 88: bail!("Token already taken");
7393d62235 2026-01-07 89: } else {
7393d62235 2026-01-07 90: set.insert(my_id);
7393d62235 2026-01-07 91: Ok(Token {
7393d62235 2026-01-07 92: running,
7393d62235 2026-01-07 93: my_id,
7393d62235 2026-01-07 94: })
7393d62235 2026-01-07 95: }
7393d62235 2026-01-07 96: }
7393d62235 2026-01-07 97: }
7393d62235 2026-01-07 98:
7393d62235 2026-01-07 99: impl Drop for Token {
7393d62235 2026-01-07 100: /// Releases this token's claim on the shared running-set when the token is dropped.
7393d62235 2026-01-07 101: ///
7393d62235 2026-01-07 102: /// The token's identifier is removed from the shared `running` set so that future
7393d62235 2026-01-07 103: /// operations for the same id may proceed.
7393d62235 2026-01-07 104: ///
7393d62235 2026-01-07 105: /// TODO: is using block_on inside block_on safe? Currently tested and working fine.
7393d62235 2026-01-07 106: fn drop (&mut self) {
7393d62235 2026-01-07 107: smol::block_on(async {
7393d62235 2026-01-07 108: let mut set = self.running.lock_arc().await;
7393d62235 2026-01-07 109: set.remove(&self.my_id);
7393d62235 2026-01-07 110: })
7393d62235 2026-01-07 111: }
5a4aab7687 2025-06-29 112: }
9171c791eb 2021-11-13 113:
9171c791eb 2021-11-13 114: #[derive(Clone)]
9171c791eb 2021-11-13 115: pub struct Core {
bb89b6fab8 2025-06-15 116: owner_chat: ChatPeerId,
bb89b6fab8 2025-06-15 117: // max_delay: u16,
bb89b6fab8 2025-06-15 118: pub tg: Client,
bb89b6fab8 2025-06-15 119: pub me: Bot,
0340541002 2025-04-24 120: pub db: Db,
7393d62235 2026-01-07 121: running: Arc<Mutex<HashSet<i32>>>,
45e34762e4 2023-05-28 122: http_client: reqwest::Client,
45e34762e4 2023-05-28 123: }
45e34762e4 2023-05-28 124:
01565c7f7e 2026-04-23 125: // XXX Right now that part is unfinished and I guess I need to finish menu first
01565c7f7e 2026-04-23 126: #[allow(unused)]
dc7c43b010 2026-01-01 127: pub struct Post {
dc7c43b010 2026-01-01 128: uri: String,
dc7c43b010 2026-01-01 129: title: String,
dc7c43b010 2026-01-01 130: authors: String,
dc7c43b010 2026-01-01 131: summary: String,
dc7c43b010 2026-01-01 132: }
dc7c43b010 2026-01-01 133:
9171c791eb 2021-11-13 134: impl Core {
7393d62235 2026-01-07 135: /// Create a Core instance from configuration and start its background autofetch loop.
7393d62235 2026-01-07 136: ///
7393d62235 2026-01-07 137: /// The provided `settings` must include:
7393d62235 2026-01-07 138: /// - `owner` (integer): chat id to use as the default destination,
7393d62235 2026-01-07 139: /// - `api_key` (string): Telegram bot API key,
7393d62235 2026-01-07 140: /// - `api_gateway` (string): Telegram API gateway host,
7393d62235 2026-01-07 141: /// - `pg` (string): PostgreSQL connection string,
7393d62235 2026-01-07 142: /// - optional `proxy` (string): proxy URL for the HTTP client.
7393d62235 2026-01-07 143: ///
7393d62235 2026-01-07 144: /// On success returns an initialized `Core` with Telegram and HTTP clients, database connection,
7393d62235 2026-01-07 145: /// an empty running set for per-id tokens, and a spawned background task that periodically runs
7393d62235 2026-01-07 146: /// `autofetch`. If any required setting is missing or initialization fails, an error is returned.
0340541002 2025-04-24 147: pub async fn new(settings: config::Config) -> Result<Core> {
44575a91d3 2025-07-09 148: let owner_chat = ChatPeerId::from(settings.get_int("owner").stack()?);
44575a91d3 2025-07-09 149: let api_key = settings.get_string("api_key").stack()?;
42b29b744b 2026-01-01 150: let tg = Client::new(&api_key).stack()?
42b29b744b 2026-01-01 151: .with_host(settings.get_string("api_gateway").stack()?);
45e34762e4 2023-05-28 152:
45e34762e4 2023-05-28 153: let mut client = reqwest::Client::builder();
9d8a6738fd 2023-07-30 154: if let Ok(proxy) = settings.get_string("proxy") {
44575a91d3 2025-07-09 155: let proxy = reqwest::Proxy::all(proxy).stack()?;
45e34762e4 2023-05-28 156: client = client.proxy(proxy);
45e34762e4 2023-05-28 157: }
44575a91d3 2025-07-09 158: let http_client = client.build().stack()?;
44575a91d3 2025-07-09 159: let me = tg.execute(GetBot).await.stack()?;
0340541002 2025-04-24 160: let core = Core {
f988dfd28f 2022-02-13 161: tg,
e624ef9d66 2025-04-20 162: me,
e624ef9d66 2025-04-20 163: owner_chat,
44575a91d3 2025-07-09 164: db: Db::new(&settings.get_string("pg").stack()?)?,
7393d62235 2026-01-07 165: running: Arc::new(Mutex::new(HashSet::new())),
45e34762e4 2023-05-28 166: http_client,
bb89b6fab8 2025-06-15 167: // max_delay: 60,
0340541002 2025-04-24 168: };
bb89b6fab8 2025-06-15 169: let clone = core.clone();
dc7c43b010 2026-01-01 170: smol::spawn(Compat::new(async move {
26339860ce 2022-02-13 171: loop {
26339860ce 2022-02-13 172: let delay = match &clone.autofetch().await {
26339860ce 2022-02-13 173: Err(err) => {
07b34bcad6 2025-08-05 174: if let Err(err) = clone.send(format!("🛑 {err}"), None, None).await {
e624ef9d66 2025-04-20 175: eprintln!("Autofetch error: {err:?}");
26339860ce 2022-02-13 176: };
cb86e770f9 2022-03-15 177: std::time::Duration::from_secs(60)
26339860ce 2022-02-13 178: },
26339860ce 2022-02-13 179: Ok(time) => *time,
9171c791eb 2021-11-13 180: };
dc7c43b010 2026-01-01 181: Timer::after(delay).await;
9171c791eb 2021-11-13 182: }
dc7c43b010 2026-01-01 183: })).detach();
9171c791eb 2021-11-13 184: Ok(core)
9171c791eb 2021-11-13 185: }
9171c791eb 2021-11-13 186:
bb89b6fab8 2025-06-15 187: pub async fn send <S>(&self, msg: S, target: Option<ChatPeerId>, mode: Option<ParseMode>) -> Result<Message>
e624ef9d66 2025-04-20 188: where S: Into<String> {
e624ef9d66 2025-04-20 189: let msg = msg.into();
e624ef9d66 2025-04-20 190:
e624ef9d66 2025-04-20 191: let mode = mode.unwrap_or(ParseMode::Html);
e624ef9d66 2025-04-20 192: let target = target.unwrap_or(self.owner_chat);
44575a91d3 2025-07-09 193: self.tg.execute(
dae6672b4d 2026-09-13 194: SendMessage::new(target, InputText::from(msg)
dae6672b4d 2026-09-13 195: .with_format(mode))
44575a91d3 2025-07-09 196: ).await.stack()
44575a91d3 2025-07-09 197: }
44575a91d3 2025-07-09 198:
7393d62235 2026-01-07 199: /// Fetches the feed for a source, sends any newly discovered posts to the appropriate chat, and records them in the database.
7393d62235 2026-01-07 200: ///
7393d62235 2026-01-07 201: /// This acquires a per-source guard to prevent concurrent checks for the same `id`. If a check is already running for
7393d62235 2026-01-07 202: /// the given `id`, the function returns an error. If `last_scrape` is provided, it is sent as the `If-Modified-Since`
7393d62235 2026-01-07 203: /// header to the feed request. The function parses RSS or Atom feeds, sends unseen post URLs to either the source's
7393d62235 2026-01-07 204: /// channel (when `real` is true) or the source owner (when `real` is false), and persists posted entries so they are
7393d62235 2026-01-07 205: /// not reposted later.
7393d62235 2026-01-07 206: ///
7393d62235 2026-01-07 207: /// Parameters:
7393d62235 2026-01-07 208: /// - `id`: Identifier of the source to check.
7393d62235 2026-01-07 209: /// - `real`: When `true`, send posts to the source's channel; when `false`, send to the source owner.
7393d62235 2026-01-07 210: /// - `last_scrape`: Optional timestamp used to set the `If-Modified-Since` header for the HTTP request.
7393d62235 2026-01-07 211: ///
7393d62235 2026-01-07 212: /// # Returns
7393d62235 2026-01-07 213: ///
7393d62235 2026-01-07 214: /// `Posted: N` where `N` is the number of posts processed and sent.
acb0a4ac54 2025-09-28 215: pub async fn check (&self, id: i32, real: bool, last_scrape: Option<DateTime<Local>>) -> Result<String> {
44575a91d3 2025-07-09 216: let mut posted: i32 = 0;
44575a91d3 2025-07-09 217: let mut conn = self.db.begin().await.stack()?;
44575a91d3 2025-07-09 218:
7393d62235 2026-01-07 219: let _token = Token::new(&self.running, id).await.stack()?;
7393d62235 2026-01-07 220: let source = conn.get_source(id, self.owner_chat).await.stack()?;
7393d62235 2026-01-07 221: conn.set_scrape(id).await.stack()?;
7393d62235 2026-01-07 222: let destination = ChatPeerId::from(match real {
7393d62235 2026-01-07 223: true => source.channel_id,
7393d62235 2026-01-07 224: false => source.owner,
7393d62235 2026-01-07 225: });
7393d62235 2026-01-07 226: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
7393d62235 2026-01-07 227: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, Post> = BTreeMap::new();
7393d62235 2026-01-07 228:
7393d62235 2026-01-07 229: let mut builder = self.http_client.get(&source.url);
7393d62235 2026-01-07 230: if let Some(last_scrape) = last_scrape {
7393d62235 2026-01-07 231: builder = builder.header(LAST_MODIFIED, last_scrape.to_rfc2822());
7393d62235 2026-01-07 232: };
7393d62235 2026-01-07 233: let response = builder.send().await.stack()?;
2f0b8bb368 2026-09-14 234:
2f0b8bb368 2026-09-14 235: // Print debug output for each response processed to track how expires
2f0b8bb368 2026-09-14 236: // are handled
2f0b8bb368 2026-09-14 237: #[cfg(debug_assertions)] {
2f0b8bb368 2026-09-14 238: use reqwest::header::{
2f0b8bb368 2026-09-14 239: EXPIRES,
2f0b8bb368 2026-09-14 240: CACHE_CONTROL,
2f0b8bb368 2026-09-14 241: };
2f0b8bb368 2026-09-14 242:
7393d62235 2026-01-07 243: let headers = response.headers();
7393d62235 2026-01-07 244: let expires = headers.get(EXPIRES);
7393d62235 2026-01-07 245: let cache = headers.get(CACHE_CONTROL);
7393d62235 2026-01-07 246: if expires.is_some() || cache.is_some() {
2bac369e41 2026-07-19 247: println!("{} {} {:?} {:?} {:?}", Local::now().to_rfc2822(), source.url, last_scrape, expires, cache);
2f0b8bb368 2026-09-14 248: } }
2f0b8bb368 2026-09-14 249:
7393d62235 2026-01-07 250: let status = response.status();
7393d62235 2026-01-07 251: let content = response.bytes().await.stack()?;
7393d62235 2026-01-07 252: match rss::Channel::read_from(&content[..]) {
7393d62235 2026-01-07 253: Ok(feed) => {
7393d62235 2026-01-07 254: for item in feed.items() {
7393d62235 2026-01-07 255: if let Some(link) = item.link() {
7393d62235 2026-01-07 256: let date = match item.pub_date() {
7393d62235 2026-01-07 257: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
7393d62235 2026-01-07 258: None => DateTime::parse_from_rfc3339(match item.dublin_core_ext() {
7393d62235 2026-01-07 259: Some(ext) => {
7393d62235 2026-01-07 260: let dates = ext.dates();
7393d62235 2026-01-07 261: if dates.is_empty() {
7393d62235 2026-01-07 262: bail!("Feed item has Dublin Core extension but no dates.")
7393d62235 2026-01-07 263: } else {
7393d62235 2026-01-07 264: &dates[0]
7393d62235 2026-01-07 265: }
7393d62235 2026-01-07 266: },
7393d62235 2026-01-07 267: None => bail!("Feed item misses posting date."),
7393d62235 2026-01-07 268: }),
7393d62235 2026-01-07 269: }.stack()?;
7393d62235 2026-01-07 270: let uri = link.to_string();
7393d62235 2026-01-07 271: let title = item.title().unwrap_or("").to_string();
7393d62235 2026-01-07 272: let authors = item.author().unwrap_or("").to_string();
7393d62235 2026-01-07 273: let summary = item.content().unwrap_or("").to_string();
7393d62235 2026-01-07 274: posts.insert(date, Post{
7393d62235 2026-01-07 275: uri,
7393d62235 2026-01-07 276: title,
7393d62235 2026-01-07 277: authors,
7393d62235 2026-01-07 278: summary,
7393d62235 2026-01-07 279: });
7393d62235 2026-01-07 280: }
7393d62235 2026-01-07 281: };
7393d62235 2026-01-07 282: },
7393d62235 2026-01-07 283: Err(err) => match err {
7393d62235 2026-01-07 284: rss::Error::InvalidStartTag => {
7393d62235 2026-01-07 285: match atom_syndication::Feed::read_from(&content[..]) {
7393d62235 2026-01-07 286: Ok(feed) => {
7393d62235 2026-01-07 287: for item in feed.entries() {
7393d62235 2026-01-07 288: let date = item.published()
7393d62235 2026-01-07 289: .stack_err("Feed item missing publishing date.")?;
7393d62235 2026-01-07 290: let uri = {
7393d62235 2026-01-07 291: let links = item.links();
7393d62235 2026-01-07 292: if links.is_empty() {
7393d62235 2026-01-07 293: bail!("Feed item missing post links.");
7393d62235 2026-01-07 294: } else {
7393d62235 2026-01-07 295: links[0].href().to_string()
7393d62235 2026-01-07 296: }
7393d62235 2026-01-07 297: };
7393d62235 2026-01-07 298: let title = item.title().to_string();
7393d62235 2026-01-07 299: let authors = item.authors().iter().map(|x| format!("{} <{:?}>", x.name(), x.email())).collect::<Vec<String>>().join(", ");
7393d62235 2026-01-07 300: let summary = if let Some(sum) = item.summary() { sum.value.clone() } else { String::new() };
7393d62235 2026-01-07 301: posts.insert(*date, Post{
7393d62235 2026-01-07 302: uri,
7393d62235 2026-01-07 303: title,
7393d62235 2026-01-07 304: authors,
7393d62235 2026-01-07 305: summary,
7393d62235 2026-01-07 306: });
7393d62235 2026-01-07 307: };
7393d62235 2026-01-07 308: },
7393d62235 2026-01-07 309: Err(err) => {
7393d62235 2026-01-07 310: bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
7393d62235 2026-01-07 311: },
7393d62235 2026-01-07 312: }
7393d62235 2026-01-07 313: },
7393d62235 2026-01-07 314: rss::Error::Eof => (),
7393d62235 2026-01-07 315: _ => bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
7393d62235 2026-01-07 316: }
7393d62235 2026-01-07 317: };
7393d62235 2026-01-07 318: for (date, post) in posts.iter() {
7393d62235 2026-01-07 319: let post_url: Cow<str> = match source.url_re {
7393d62235 2026-01-07 320: Some(ref x) => sedregex::ReplaceCommand::new(x).stack()?.execute(&post.uri),
7393d62235 2026-01-07 321: None => post.uri.clone().into(),
7393d62235 2026-01-07 322: };
7393d62235 2026-01-07 323: if ! conn.exists(&post_url, id).await.stack()? {
7393d62235 2026-01-07 324: if this_fetch.is_none() || *date > this_fetch.unwrap() {
7393d62235 2026-01-07 325: this_fetch = Some(*date);
7393d62235 2026-01-07 326: };
7393d62235 2026-01-07 327: self.send( match &source.iv_hash {
7393d62235 2026-01-07 328: Some(hash) => format!("<a href=\"https://t.me/iv?url={post_url}&rhash={hash}\"> </a>{post_url}"),
7393d62235 2026-01-07 329: None => format!("{post_url}"),
7393d62235 2026-01-07 330: }, Some(destination), Some(ParseMode::Html)).await.stack()?;
7393d62235 2026-01-07 331: conn.add_post(id, date, &post_url).await.stack()?;
44575a91d3 2025-07-09 332: posted += 1;
44575a91d3 2025-07-09 333: };
44575a91d3 2025-07-09 334: };
7393d62235 2026-01-07 335: posts.clear();
0340541002 2025-04-24 336: Ok(format!("Posted: {posted}"))
26339860ce 2022-02-13 337: }
26339860ce 2022-02-13 338:
bb89b6fab8 2025-06-15 339: async fn autofetch(&self) -> Result<std::time::Duration> {
26339860ce 2022-02-13 340: let mut delay = chrono::Duration::minutes(1);
9910c2209c 2023-08-04 341: let now = chrono::Local::now();
bb89b6fab8 2025-06-15 342: let queue = {
44575a91d3 2025-07-09 343: let mut conn = self.db.begin().await.stack()?;
44575a91d3 2025-07-09 344: conn.get_queue().await.stack()?
bb89b6fab8 2025-06-15 345: };
bb89b6fab8 2025-06-15 346: for row in queue {
9910c2209c 2023-08-04 347: if let Some(next_fetch) = row.next_fetch {
9910c2209c 2023-08-04 348: if next_fetch < now {
acb0a4ac54 2025-09-28 349: if let (Some(owner), Some(source_id), last_scrape) = (row.owner, row.source_id, row.last_scrape) {
bb89b6fab8 2025-06-15 350: let clone = Core {
bb89b6fab8 2025-06-15 351: owner_chat: ChatPeerId::from(owner),
9910c2209c 2023-08-04 352: ..self.clone()
9910c2209c 2023-08-04 353: };
b4af85e31b 2025-06-29 354: let source = {
44575a91d3 2025-07-09 355: let mut conn = self.db.begin().await.stack()?;
b4af85e31b 2025-06-29 356: match conn.get_one(owner, source_id).await {
b4af85e31b 2025-06-29 357: Ok(Some(source)) => source.to_string(),
7393d62235 2026-01-07 358: Ok(None) => "Source not found in database?".to_string(),
b4af85e31b 2025-06-29 359: Err(err) => format!("Failed to fetch source data:\n{err}"),
b4af85e31b 2025-06-29 360: }
b4af85e31b 2025-06-29 361: };
dc7c43b010 2026-01-01 362: smol::spawn(Compat::new(async move {
acb0a4ac54 2025-09-28 363: if let Err(err) = clone.check(source_id, true, Some(last_scrape)).await {
7393d62235 2026-01-07 364: if let Err(err) = clone.send(&format!("🛑 {source}\n{}", encode(&err.to_string())), None, Some(ParseMode::MarkdownV2)).await {
ec71df21e1 2025-11-07 365: eprintln!("Check error: {err}");
79c91a5357 2024-08-02 366: // clone.disable(&source_id, owner).await.unwrap();
9910c2209c 2023-08-04 367: };
9910c2209c 2023-08-04 368: };
dc7c43b010 2026-01-01 369: })).detach();
9910c2209c 2023-08-04 370: }
9910c2209c 2023-08-04 371: } else if next_fetch - now < delay {
9910c2209c 2023-08-04 372: delay = next_fetch - now;
9910c2209c 2023-08-04 373: }
9910c2209c 2023-08-04 374: }
9910c2209c 2023-08-04 375: };
44575a91d3 2025-07-09 376: delay.to_std().stack()
9910c2209c 2023-08-04 377: }
9910c2209c 2023-08-04 378:
bb89b6fab8 2025-06-15 379: pub async fn list (&self, owner: UserPeerId) -> Result<String> {
b4af85e31b 2025-06-29 380: let mut reply: Vec<String> = vec![];
9910c2209c 2023-08-04 381: reply.push("Channels:".into());
44575a91d3 2025-07-09 382: let mut conn = self.db.begin().await.stack()?;
44575a91d3 2025-07-09 383: for row in conn.get_list(owner).await.stack()? {
b4af85e31b 2025-06-29 384: reply.push(row.to_string());
e624ef9d66 2025-04-20 385: };
b4af85e31b 2025-06-29 386: Ok(reply.join("\n\n"))
bb89b6fab8 2025-06-15 387: }
bb89b6fab8 2025-06-15 388: }
bb89b6fab8 2025-06-15 389:
bb89b6fab8 2025-06-15 390: impl UpdateHandler for Core {
bb89b6fab8 2025-06-15 391: async fn handle (&self, update: Update) {
bb89b6fab8 2025-06-15 392: if let UpdateType::Message(msg) = update.update_type {
bc5f7c980c 2026-03-24 393: if let Ok(cmd) = Command::try_from(*msg) {
bb89b6fab8 2025-06-15 394: let msg = cmd.get_message();
bb89b6fab8 2025-06-15 395: let words = cmd.get_args();
fae13a0e55 2025-06-28 396: let command = cmd.get_name();
fae13a0e55 2025-06-28 397: let res = match command {
fae13a0e55 2025-06-28 398: "/check" | "/clean" | "/enable" | "/delete" | "/disable" => command::command(self, command, msg, words).await,
bb89b6fab8 2025-06-15 399: "/start" => command::start(self, msg).await,
bb89b6fab8 2025-06-15 400: "/list" => command::list(self, msg).await,
fae13a0e55 2025-06-28 401: "/add" | "/update" => command::update(self, command, msg, words).await,
bb89b6fab8 2025-06-15 402: any => Err(anyhow!("Unknown command: {any}")),
bb89b6fab8 2025-06-15 403: };
bb89b6fab8 2025-06-15 404: if let Err(err) = res {
07b34bcad6 2025-08-05 405: if let Err(err2) = self.send(format!("\\#error\n```\n{err}\n```"),
bb89b6fab8 2025-06-15 406: Some(msg.chat.get_id()),
bb89b6fab8 2025-06-15 407: Some(ParseMode::MarkdownV2)
dae6672b4d 2026-09-13 408: ).await {
dae6672b4d 2026-09-13 409: let _ = dbg!(err2);
bb89b6fab8 2025-06-15 410: };
bb89b6fab8 2025-06-15 411: }
bb89b6fab8 2025-06-15 412: };
bb89b6fab8 2025-06-15 413: };
e624ef9d66 2025-04-20 414: }
9171c791eb 2021-11-13 415: }