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