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