Annotation For src/core.rs
Logged in as anonymous

Origin for each line in src/core.rs from check-in 13265e7697:

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