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        arcade: use crate::{
0340541002 2025-04-24        arcade: 	command,
0340541002 2025-04-24        arcade: 	sql::Db,
9c4f09193a 2026-01-09        arcade: 	tg_bot::Tg,
0340541002 2025-04-24        arcade: };
1c444d34ff 2024-08-28        arcade: 
9171c791eb 2021-11-13        arcade: use std::{
c1e27b74ed 2021-11-13        arcade: 	borrow::Cow,
9171c791eb 2021-11-13        arcade: 	collections::{
9171c791eb 2021-11-13        arcade: 		BTreeMap,
9171c791eb 2021-11-13        arcade: 		HashSet,
9171c791eb 2021-11-13        arcade: 	},
dc7c43b010 2026-01-01        arcade: 	sync::Arc,
44575a91d3 2025-07-09        arcade: };
44575a91d3 2025-07-09        arcade: 
dc7c43b010 2026-01-01        arcade: use async_compat::Compat;
acb0a4ac54 2025-09-28        arcade: use chrono::{
acb0a4ac54 2025-09-28        arcade: 	DateTime,
acb0a4ac54 2025-09-28        arcade: 	Local,
44575a91d3 2025-07-09        arcade: };
5a4aab7687 2025-06-29        arcade: use lazy_static::lazy_static;
5a4aab7687 2025-06-29        arcade: use regex::Regex;
9c4f09193a 2026-01-09        arcade: use reqwest::header::LAST_MODIFIED;
dc7c43b010 2026-01-01        arcade: use smol::{
dc7c43b010 2026-01-01        arcade: 	Timer,
dc7c43b010 2026-01-01        arcade: 	lock::Mutex,
acb0a4ac54 2025-09-28        arcade: };
5a4aab7687 2025-06-29        arcade: use tgbot::{
bb89b6fab8 2025-06-15        arcade: 	handler::UpdateHandler,
bb89b6fab8 2025-06-15        arcade: 	types::{
bb89b6fab8 2025-06-15        arcade: 		ChatPeerId,
bb89b6fab8 2025-06-15        arcade: 		Command,
bb89b6fab8 2025-06-15        arcade: 		ParseMode,
bb89b6fab8 2025-06-15        arcade: 		Update,
bb89b6fab8 2025-06-15        arcade: 		UpdateType,
bb89b6fab8 2025-06-15        arcade: 		UserPeerId,
1bd041d00f 2025-05-20        arcade: 	},
44575a91d3 2025-07-09        arcade: };
44575a91d3 2025-07-09        arcade: use stacked_errors::{
44575a91d3 2025-07-09        arcade: 	Result,
44575a91d3 2025-07-09        arcade: 	StackableErr,
44575a91d3 2025-07-09        arcade: 	anyhow,
44575a91d3 2025-07-09        arcade: 	bail,
5a4aab7687 2025-06-29        arcade: };
5a4aab7687 2025-06-29        arcade: 
5a4aab7687 2025-06-29        arcade: lazy_static!{
5a4aab7687 2025-06-29        arcade: 	pub static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap();
5a4aab7687 2025-06-29        arcade: }
5a4aab7687 2025-06-29        arcade: 
7393d62235 2026-01-07        arcade: /// Escape characters that are special in Telegram MarkdownV2 by prefixing them with a backslash.
7393d62235 2026-01-07        arcade: ///
7393d62235 2026-01-07        arcade: /// This ensures the returned string can be used as MarkdownV2-formatted Telegram message content
7393d62235 2026-01-07        arcade: /// without special characters being interpreted as MarkdownV2 markup.
5a4aab7687 2025-06-29        arcade: pub fn encode (text: &str) -> Cow<'_, str> {
5a4aab7687 2025-06-29        arcade: 	RE_SPECIAL.replace_all(text, "\\$1")
5a4aab7687 2025-06-29        arcade: }
5a4aab7687 2025-06-29        arcade: 
7393d62235 2026-01-07        arcade: // This one does nothing except making sure only one token exists for each id
7393d62235 2026-01-07        arcade: pub struct Token {
7393d62235 2026-01-07        arcade: 	running: Arc<Mutex<HashSet<i32>>>,
7393d62235 2026-01-07        arcade: 	my_id: i32,
7393d62235 2026-01-07        arcade: }
7393d62235 2026-01-07        arcade: 
7393d62235 2026-01-07        arcade: impl Token {
7393d62235 2026-01-07        arcade: 	/// Attempts to acquire a per-id token by inserting `my_id` into the shared `running` set.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// If the id was not already present, the function inserts it and returns `Some(Token)`.
7393d62235 2026-01-07        arcade: 	/// When the returned `Token` is dropped, the id will be removed from the `running` set,
7393d62235 2026-01-07        arcade: 	/// allowing subsequent acquisitions for the same id.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// # Parameters
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// - `running`: Shared set tracking active ids.
7393d62235 2026-01-07        arcade: 	/// - `my_id`: Identifier to acquire a token for.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// # Returns
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// `Ok(Token)` if the id was successfully acquired, `Error` if a token for the id is already active.
7393d62235 2026-01-07        arcade: 	async fn new (running: &Arc<Mutex<HashSet<i32>>>, my_id: i32) -> Result<Token> {
7393d62235 2026-01-07        arcade: 		let running = running.clone();
7393d62235 2026-01-07        arcade: 		let mut set = running.lock_arc().await;
7393d62235 2026-01-07        arcade: 		if set.contains(&my_id) {
7393d62235 2026-01-07        arcade: 			bail!("Token already taken");
7393d62235 2026-01-07        arcade: 		} else {
7393d62235 2026-01-07        arcade: 			set.insert(my_id);
7393d62235 2026-01-07        arcade: 			Ok(Token {
7393d62235 2026-01-07        arcade: 				running,
7393d62235 2026-01-07        arcade: 				my_id,
7393d62235 2026-01-07        arcade: 			})
7393d62235 2026-01-07        arcade: 		}
7393d62235 2026-01-07        arcade: 	}
7393d62235 2026-01-07        arcade: }
7393d62235 2026-01-07        arcade: 
7393d62235 2026-01-07        arcade: impl Drop for Token {
7393d62235 2026-01-07        arcade: 	/// Releases this token's claim on the shared running-set when the token is dropped.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// The token's identifier is removed from the shared `running` set so that future
7393d62235 2026-01-07        arcade: 	/// operations for the same id may proceed.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// TODO: is using block_on inside block_on safe? Currently tested and working fine.
7393d62235 2026-01-07        arcade: 	fn drop (&mut self) {
7393d62235 2026-01-07        arcade: 		smol::block_on(async {
7393d62235 2026-01-07        arcade: 			let mut set = self.running.lock_arc().await;
7393d62235 2026-01-07        arcade: 			set.remove(&self.my_id);
7393d62235 2026-01-07        arcade: 		})
7393d62235 2026-01-07        arcade: 	}
7393d62235 2026-01-07        arcade: }
7393d62235 2026-01-07        arcade: 
9171c791eb 2021-11-13        arcade: #[derive(Clone)]
9171c791eb 2021-11-13        arcade: pub struct Core {
9c4f09193a 2026-01-09        arcade: 	pub tg: Tg,
0340541002 2025-04-24        arcade: 	pub db: Db,
7393d62235 2026-01-07        arcade: 	running: Arc<Mutex<HashSet<i32>>>,
45e34762e4 2023-05-28        arcade: 	http_client: reqwest::Client,
45e34762e4 2023-05-28        arcade: }
45e34762e4 2023-05-28        arcade: 
dc7c43b010 2026-01-01        arcade: pub struct Post {
dc7c43b010 2026-01-01        arcade: 	uri: String,
9c4f09193a 2026-01-09        arcade: 	_title: String,
9c4f09193a 2026-01-09        arcade: 	_authors: String,
9c4f09193a 2026-01-09        arcade: 	_summary: String,
dc7c43b010 2026-01-01        arcade: }
dc7c43b010 2026-01-01        arcade: 
9171c791eb 2021-11-13        arcade: impl Core {
7393d62235 2026-01-07        arcade: 	/// Create a Core instance from configuration and start its background autofetch loop.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// The provided `settings` must include:
fabcca1eaf 2026-01-09        arcade: 	/// - `owner` (integer): default chat id to use as the owner/destination,
7393d62235 2026-01-07        arcade: 	/// - `api_key` (string): Telegram bot API key,
7393d62235 2026-01-07        arcade: 	/// - `api_gateway` (string): Telegram API gateway host,
7393d62235 2026-01-07        arcade: 	/// - `pg` (string): PostgreSQL connection string,
7393d62235 2026-01-07        arcade: 	/// - optional `proxy` (string): proxy URL for the HTTP client.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// On success returns an initialized `Core` with Telegram and HTTP clients, database connection,
7393d62235 2026-01-07        arcade: 	/// an empty running set for per-id tokens, and a spawned background task that periodically runs
7393d62235 2026-01-07        arcade: 	/// `autofetch`. If any required setting is missing or initialization fails, an error is returned.
0340541002 2025-04-24        arcade: 	pub async fn new(settings: config::Config) -> Result<Core> {
45e34762e4 2023-05-28        arcade: 		let mut client = reqwest::Client::builder();
9d8a6738fd 2023-07-30        arcade: 		if let Ok(proxy) = settings.get_string("proxy") {
44575a91d3 2025-07-09        arcade: 			let proxy = reqwest::Proxy::all(proxy).stack()?;
45e34762e4 2023-05-28        arcade: 			client = client.proxy(proxy);
45e34762e4 2023-05-28        arcade: 		}
9c4f09193a 2026-01-09        arcade: 
0340541002 2025-04-24        arcade: 		let core = Core {
9c4f09193a 2026-01-09        arcade: 			tg: Tg::new(&settings).await.stack()?,
44575a91d3 2025-07-09        arcade: 			db: Db::new(&settings.get_string("pg").stack()?)?,
7393d62235 2026-01-07        arcade: 			running: Arc::new(Mutex::new(HashSet::new())),
9c4f09193a 2026-01-09        arcade: 			http_client: client.build().stack()?,
0340541002 2025-04-24        arcade: 		};
9c4f09193a 2026-01-09        arcade: 
bb89b6fab8 2025-06-15        arcade: 		let clone = core.clone();
dc7c43b010 2026-01-01        arcade: 		smol::spawn(Compat::new(async move {
26339860ce 2022-02-13        arcade: 			loop {
26339860ce 2022-02-13        arcade: 				let delay = match &clone.autofetch().await {
26339860ce 2022-02-13        arcade: 					Err(err) => {
9c4f09193a 2026-01-09        arcade: 						if let Err(err) = clone.tg.send(format!("🛑 {err}"), None, None).await {
e624ef9d66 2025-04-20        arcade: 							eprintln!("Autofetch error: {err:?}");
26339860ce 2022-02-13        arcade: 						};
cb86e770f9 2022-03-15        arcade: 						std::time::Duration::from_secs(60)
26339860ce 2022-02-13        arcade: 					},
26339860ce 2022-02-13        arcade: 					Ok(time) => *time,
9171c791eb 2021-11-13        arcade: 				};
dc7c43b010 2026-01-01        arcade: 				Timer::after(delay).await;
9171c791eb 2021-11-13        arcade: 			}
dc7c43b010 2026-01-01        arcade: 		})).detach();
9171c791eb 2021-11-13        arcade: 		Ok(core)
9171c791eb 2021-11-13        arcade: 	}
9171c791eb 2021-11-13        arcade: 
7393d62235 2026-01-07        arcade: 	/// 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        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// 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        arcade: 	/// 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        arcade: 	/// 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        arcade: 	/// channel (when `real` is true) or the source owner (when `real` is false), and persists posted entries so they are
7393d62235 2026-01-07        arcade: 	/// not reposted later.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// Parameters:
7393d62235 2026-01-07        arcade: 	/// - `id`: Identifier of the source to check.
7393d62235 2026-01-07        arcade: 	/// - `real`: When `true`, send posts to the source's channel; when `false`, send to the source owner.
7393d62235 2026-01-07        arcade: 	/// - `last_scrape`: Optional timestamp used to set the `If-Modified-Since` header for the HTTP request.
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// # Returns
7393d62235 2026-01-07        arcade: 	///
7393d62235 2026-01-07        arcade: 	/// `Posted: N` where `N` is the number of posts processed and sent.
acb0a4ac54 2025-09-28        arcade: 	pub async fn check (&self, id: i32, real: bool, last_scrape: Option<DateTime<Local>>) -> Result<String> {
44575a91d3 2025-07-09        arcade: 		let mut posted: i32 = 0;
44575a91d3 2025-07-09        arcade: 		let mut conn = self.db.begin().await.stack()?;
44575a91d3 2025-07-09        arcade: 
7393d62235 2026-01-07        arcade: 		let _token = Token::new(&self.running, id).await.stack()?;
9c4f09193a 2026-01-09        arcade: 		let source = conn.get_source(id, self.tg.owner).await.stack()?;
7393d62235 2026-01-07        arcade: 		conn.set_scrape(id).await.stack()?;
7393d62235 2026-01-07        arcade: 		let destination = ChatPeerId::from(match real {
7393d62235 2026-01-07        arcade: 			true => source.channel_id,
7393d62235 2026-01-07        arcade: 			false => source.owner,
7393d62235 2026-01-07        arcade: 		});
7393d62235 2026-01-07        arcade: 		let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
7393d62235 2026-01-07        arcade: 		let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, Post> = BTreeMap::new();
7393d62235 2026-01-07        arcade: 
7393d62235 2026-01-07        arcade: 		let mut builder = self.http_client.get(&source.url);
7393d62235 2026-01-07        arcade: 		if let Some(last_scrape) = last_scrape {
7393d62235 2026-01-07        arcade: 			builder = builder.header(LAST_MODIFIED, last_scrape.to_rfc2822());
7393d62235 2026-01-07        arcade: 		};
7393d62235 2026-01-07        arcade: 		let response = builder.send().await.stack()?;
7393d62235 2026-01-07        arcade: 		#[cfg(debug_assertions)]
7393d62235 2026-01-07        arcade: 		{
9c4f09193a 2026-01-09        arcade: 			use reqwest::header::{
9c4f09193a 2026-01-09        arcade: 				CACHE_CONTROL,
9c4f09193a 2026-01-09        arcade: 				EXPIRES,
9c4f09193a 2026-01-09        arcade: 			};
7393d62235 2026-01-07        arcade: 			let headers = response.headers();
7393d62235 2026-01-07        arcade: 			let expires = headers.get(EXPIRES);
7393d62235 2026-01-07        arcade: 			let cache = headers.get(CACHE_CONTROL);
7393d62235 2026-01-07        arcade: 			if expires.is_some() || cache.is_some() {
7393d62235 2026-01-07        arcade: 				println!("{} {} {:?} {:?} {:?}", Local::now().to_rfc2822(), &source.url, last_scrape, expires, cache);
7393d62235 2026-01-07        arcade: 			}
7393d62235 2026-01-07        arcade: 		}
7393d62235 2026-01-07        arcade: 		let status = response.status();
7393d62235 2026-01-07        arcade: 		let content = response.bytes().await.stack()?;
7393d62235 2026-01-07        arcade: 		match rss::Channel::read_from(&content[..]) {
7393d62235 2026-01-07        arcade: 			Ok(feed) => {
7393d62235 2026-01-07        arcade: 				for item in feed.items() {
7393d62235 2026-01-07        arcade: 					if let Some(link) = item.link() {
7393d62235 2026-01-07        arcade: 						let date = match item.pub_date() {
7393d62235 2026-01-07        arcade: 							Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
7393d62235 2026-01-07        arcade: 							None => DateTime::parse_from_rfc3339(match item.dublin_core_ext() {
7393d62235 2026-01-07        arcade: 								Some(ext) => {
7393d62235 2026-01-07        arcade: 									let dates = ext.dates();
7393d62235 2026-01-07        arcade: 									if dates.is_empty() {
7393d62235 2026-01-07        arcade: 										bail!("Feed item has Dublin Core extension but no dates.")
7393d62235 2026-01-07        arcade: 									} else {
7393d62235 2026-01-07        arcade: 										&dates[0]
7393d62235 2026-01-07        arcade: 									}
7393d62235 2026-01-07        arcade: 								},
7393d62235 2026-01-07        arcade: 								None => bail!("Feed item misses posting date."),
7393d62235 2026-01-07        arcade: 							}),
7393d62235 2026-01-07        arcade: 						}.stack()?;
7393d62235 2026-01-07        arcade: 						posts.insert(date, Post{
9c4f09193a 2026-01-09        arcade: 							uri: link.to_string(),
9c4f09193a 2026-01-09        arcade: 							_title: item.title().unwrap_or("").to_string(),
9c4f09193a 2026-01-09        arcade: 							_authors: item.author().unwrap_or("").to_string(),
9c4f09193a 2026-01-09        arcade: 							_summary: item.content().unwrap_or("").to_string(),
7393d62235 2026-01-07        arcade: 						});
7393d62235 2026-01-07        arcade: 					}
7393d62235 2026-01-07        arcade: 				};
7393d62235 2026-01-07        arcade: 			},
7393d62235 2026-01-07        arcade: 			Err(err) => match err {
7393d62235 2026-01-07        arcade: 				rss::Error::InvalidStartTag => {
7393d62235 2026-01-07        arcade: 					match atom_syndication::Feed::read_from(&content[..]) {
7393d62235 2026-01-07        arcade: 						Ok(feed) => {
7393d62235 2026-01-07        arcade: 							for item in feed.entries() {
7393d62235 2026-01-07        arcade: 								let date = item.published()
7393d62235 2026-01-07        arcade: 									.stack_err("Feed item missing publishing date.")?;
7393d62235 2026-01-07        arcade: 								let uri = {
7393d62235 2026-01-07        arcade: 									let links = item.links();
7393d62235 2026-01-07        arcade: 									if links.is_empty() {
7393d62235 2026-01-07        arcade: 										bail!("Feed item missing post links.");
7393d62235 2026-01-07        arcade: 									} else {
7393d62235 2026-01-07        arcade: 										links[0].href().to_string()
7393d62235 2026-01-07        arcade: 									}
7393d62235 2026-01-07        arcade: 								};
9c4f09193a 2026-01-09        arcade: 								let _authors = item.authors().iter().map(|x| format!("{} <{:?}>", x.name(), x.email())).collect::<Vec<String>>().join(", ");
9c4f09193a 2026-01-09        arcade: 								let _summary = if let Some(sum) = item.summary() { sum.value.clone() } else { String::new() };
7393d62235 2026-01-07        arcade: 								posts.insert(*date, Post{
7393d62235 2026-01-07        arcade: 									uri,
9c4f09193a 2026-01-09        arcade: 									_title: item.title().to_string(),
9c4f09193a 2026-01-09        arcade: 									_authors,
9c4f09193a 2026-01-09        arcade: 									_summary,
7393d62235 2026-01-07        arcade: 								});
7393d62235 2026-01-07        arcade: 							};
7393d62235 2026-01-07        arcade: 						},
7393d62235 2026-01-07        arcade: 						Err(err) => {
7393d62235 2026-01-07        arcade: 							bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
7393d62235 2026-01-07        arcade: 						},
7393d62235 2026-01-07        arcade: 					}
7393d62235 2026-01-07        arcade: 				},
7393d62235 2026-01-07        arcade: 				rss::Error::Eof => (),
7393d62235 2026-01-07        arcade: 				_ => bail!("Unsupported or mangled content:\n{:?}\n{err}\n{status:#?}\n", &source.url)
7393d62235 2026-01-07        arcade: 			}
7393d62235 2026-01-07        arcade: 		};
7393d62235 2026-01-07        arcade: 		for (date, post) in posts.iter() {
7393d62235 2026-01-07        arcade: 			let post_url: Cow<str> = match source.url_re {
7393d62235 2026-01-07        arcade: 				Some(ref x) => sedregex::ReplaceCommand::new(x).stack()?.execute(&post.uri),
7393d62235 2026-01-07        arcade: 				None => post.uri.clone().into(),
7393d62235 2026-01-07        arcade: 			};
7393d62235 2026-01-07        arcade: 			if ! conn.exists(&post_url, id).await.stack()? {
7393d62235 2026-01-07        arcade: 				if this_fetch.is_none() || *date > this_fetch.unwrap() {
7393d62235 2026-01-07        arcade: 					this_fetch = Some(*date);
7393d62235 2026-01-07        arcade: 				};
9c4f09193a 2026-01-09        arcade: 				self.tg.send( match &source.iv_hash {
7393d62235 2026-01-07        arcade: 					Some(hash) => format!("<a href=\"https://t.me/iv?url={post_url}&rhash={hash}\"> </a>{post_url}"),
7393d62235 2026-01-07        arcade: 					None => format!("{post_url}"),
7393d62235 2026-01-07        arcade: 				}, Some(destination), Some(ParseMode::Html)).await.stack()?;
7393d62235 2026-01-07        arcade: 				conn.add_post(id, date, &post_url).await.stack()?;
fae13a0e55 2025-06-28        arcade: 				posted += 1;
fae13a0e55 2025-06-28        arcade: 			};
fae13a0e55 2025-06-28        arcade: 		};
7393d62235 2026-01-07        arcade: 		posts.clear();
0340541002 2025-04-24        arcade: 		Ok(format!("Posted: {posted}"))
0340541002 2025-04-24        arcade: 	}
0340541002 2025-04-24        arcade: 
fabcca1eaf 2026-01-09        arcade: 	/// Determine the delay until the next scheduled fetch and spawn background checks for any overdue sources.
fabcca1eaf 2026-01-09        arcade: 	///
fabcca1eaf 2026-01-09        arcade: 	/// This scans the database queue, spawns background tasks to run checks for sources whose `next_fetch`
fabcca1eaf 2026-01-09        arcade: 	/// is in the past (each task uses a Core clone with the appropriate owner), and computes the shortest
fabcca1eaf 2026-01-09        arcade: 	/// duration until the next `next_fetch`.
bb89b6fab8 2025-06-15        arcade: 	async fn autofetch(&self) -> Result<std::time::Duration> {
26339860ce 2022-02-13        arcade: 		let mut delay = chrono::Duration::minutes(1);
9910c2209c 2023-08-04        arcade: 		let now = chrono::Local::now();
bb89b6fab8 2025-06-15        arcade: 		let queue = {
44575a91d3 2025-07-09        arcade: 			let mut conn = self.db.begin().await.stack()?;
44575a91d3 2025-07-09        arcade: 			conn.get_queue().await.stack()?
bb89b6fab8 2025-06-15        arcade: 		};
bb89b6fab8 2025-06-15        arcade: 		for row in queue {
9910c2209c 2023-08-04        arcade: 			if let Some(next_fetch) = row.next_fetch {
9910c2209c 2023-08-04        arcade: 				if next_fetch < now {
acb0a4ac54 2025-09-28        arcade: 					if let (Some(owner), Some(source_id), last_scrape) = (row.owner, row.source_id, row.last_scrape) {
bb89b6fab8 2025-06-15        arcade: 						let clone = Core {
9c4f09193a 2026-01-09        arcade: 							tg: self.tg.with_owner(owner),
9910c2209c 2023-08-04        arcade: 							..self.clone()
9910c2209c 2023-08-04        arcade: 						};
b4af85e31b 2025-06-29        arcade: 						let source = {
44575a91d3 2025-07-09        arcade: 							let mut conn = self.db.begin().await.stack()?;
b4af85e31b 2025-06-29        arcade: 							match conn.get_one(owner, source_id).await {
b4af85e31b 2025-06-29        arcade: 								Ok(Some(source)) => source.to_string(),
7393d62235 2026-01-07        arcade: 								Ok(None) => "Source not found in database?".to_string(),
b4af85e31b 2025-06-29        arcade: 								Err(err) => format!("Failed to fetch source data:\n{err}"),
b4af85e31b 2025-06-29        arcade: 							}
b4af85e31b 2025-06-29        arcade: 						};
dc7c43b010 2026-01-01        arcade: 						smol::spawn(Compat::new(async move {
9c4f09193a 2026-01-09        arcade: 							if let Err(err) = clone.check(source_id, true, Some(last_scrape)).await
9c4f09193a 2026-01-09        arcade: 								&& let Err(err) = clone.tg.send(&format!("🛑 {source}\n{}", encode(&err.to_string())), None, Some(ParseMode::MarkdownV2)).await
9c4f09193a 2026-01-09        arcade: 							{
9c4f09193a 2026-01-09        arcade: 								eprintln!("Check error: {err}");
dc7c43b010 2026-01-01        arcade: 							};
dc7c43b010 2026-01-01        arcade: 						})).detach();
9910c2209c 2023-08-04        arcade: 					}
9910c2209c 2023-08-04        arcade: 				} else if next_fetch - now < delay {
9910c2209c 2023-08-04        arcade: 					delay = next_fetch - now;
9910c2209c 2023-08-04        arcade: 				}
9910c2209c 2023-08-04        arcade: 			}
9910c2209c 2023-08-04        arcade: 		};
44575a91d3 2025-07-09        arcade: 		delay.to_std().stack()
9910c2209c 2023-08-04        arcade: 	}
9910c2209c 2023-08-04        arcade: 
bb89b6fab8 2025-06-15        arcade: 	pub async fn list (&self, owner: UserPeerId) -> Result<String> {
b4af85e31b 2025-06-29        arcade: 		let mut reply: Vec<String> = vec![];
f988dfd28f 2022-02-13        arcade: 		reply.push("Channels:".into());
44575a91d3 2025-07-09        arcade: 		let mut conn = self.db.begin().await.stack()?;
44575a91d3 2025-07-09        arcade: 		for row in conn.get_list(owner).await.stack()? {
b4af85e31b 2025-06-29        arcade: 			reply.push(row.to_string());
9910c2209c 2023-08-04        arcade: 		};
b4af85e31b 2025-06-29        arcade: 		Ok(reply.join("\n\n"))
bb89b6fab8 2025-06-15        arcade: 	}
bb89b6fab8 2025-06-15        arcade: }
bb89b6fab8 2025-06-15        arcade: 
bb89b6fab8 2025-06-15        arcade: impl UpdateHandler for Core {
fabcca1eaf 2026-01-09        arcade: 	/// Dispatches an incoming Telegram update to a matching command handler and reports handler errors to the originating chat.
fabcca1eaf 2026-01-09        arcade: 	///
fabcca1eaf 2026-01-09        arcade: 	/// This method inspects the update; if it contains a message that can be parsed as a bot command,
fabcca1eaf 2026-01-09        arcade: 	/// it executes the corresponding command handler. If the handler returns an error, the error text
13265e7697 2026-01-10        arcade: 	/// is sent back to the message's chat using MarkdownV2 formatting. Unknown commands produce an error
fabcca1eaf 2026-01-09        arcade: 	/// which is also reported to the chat.
9c4f09193a 2026-01-09        arcade: 	async fn handle (&self, update: Update) {
9c4f09193a 2026-01-09        arcade: 		if let UpdateType::Message(msg) = update.update_type 
9c4f09193a 2026-01-09        arcade: 			&& let Ok(cmd) = Command::try_from(msg)
9c4f09193a 2026-01-09        arcade: 		{
9c4f09193a 2026-01-09        arcade: 			let msg = cmd.get_message();
9c4f09193a 2026-01-09        arcade: 			let words = cmd.get_args();
9c4f09193a 2026-01-09        arcade: 			let command = cmd.get_name();
9c4f09193a 2026-01-09        arcade: 			let res = match command {
9c4f09193a 2026-01-09        arcade: 				"/check" | "/clean" | "/enable" | "/delete" | "/disable" => command::command(self, command, msg, words).await,
9c4f09193a 2026-01-09        arcade: 				"/start" => command::start(self, msg).await,
9c4f09193a 2026-01-09        arcade: 				"/list" => command::list(self, msg).await,
9c4f09193a 2026-01-09        arcade: 				"/add" | "/update" => command::update(self, command, msg, words).await,
9c4f09193a 2026-01-09        arcade: 				any => Err(anyhow!("Unknown command: {any}")),
9c4f09193a 2026-01-09        arcade: 			};
9c4f09193a 2026-01-09        arcade: 			if let Err(err) = res 
9c4f09193a 2026-01-09        arcade: 				&& let Err(err2) = self.tg.send(format!("\\#error\n```\n{err}\n```"),
9c4f09193a 2026-01-09        arcade: 					Some(msg.chat.get_id()),
9c4f09193a 2026-01-09        arcade: 					Some(ParseMode::MarkdownV2)
9c4f09193a 2026-01-09        arcade: 				).await
9c4f09193a 2026-01-09        arcade: 			{
9c4f09193a 2026-01-09        arcade: 				dbg!(err2);
9c4f09193a 2026-01-09        arcade: 			}
fabcca1eaf 2026-01-09        arcade: 		} // TODO: debug log for skipped updates?;
e624ef9d66 2025-04-20        arcade: 	}
9171c791eb 2021-11-13        arcade: }