Annotation For src/core.rs
Logged in as anonymous

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

0340541002 2025-04-24        arcade: use crate::{
9adc69d514 2026-03-25        arcade: 	Arc,
0340541002 2025-04-24        arcade: 	command,
9adc69d514 2026-03-25        arcade: 	Mutex,
0340541002 2025-04-24        arcade: 	sql::Db,
9adc69d514 2026-03-25        arcade: 	tg_bot::{
3fd8c40aa8 2026-03-30        arcade: 		Callback,
9adc69d514 2026-03-25        arcade: 		MyMessage,
9adc69d514 2026-03-25        arcade: 		Tg,
9adc69d514 2026-03-25        arcade: 	},
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: 	},
9adc69d514 2026-03-25        arcade: 	time::Duration,
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;
9adc69d514 2026-03-25        arcade: use smol::Timer;
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,
44575a91d3 2025-07-09        arcade: };
9adc69d514 2026-03-25        arcade: use tgbot::{
9adc69d514 2026-03-25        arcade: 	handler::UpdateHandler,
9adc69d514 2026-03-25        arcade: 	types::{
3fd8c40aa8 2026-03-30        arcade: 		CallbackQuery,
9adc69d514 2026-03-25        arcade: 		ChatPeerId,
9adc69d514 2026-03-25        arcade: 		Command,
9adc69d514 2026-03-25        arcade: 		Update,
9adc69d514 2026-03-25        arcade: 		UpdateType,
9adc69d514 2026-03-25        arcade: 		UserPeerId,
9adc69d514 2026-03-25        arcade: 	},
9adc69d514 2026-03-25        arcade: };
9adc69d514 2026-03-25        arcade: use ttl_cache::TtlCache;
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: // 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: 	}
5a4aab7687 2025-06-29        arcade: }
7393d62235 2026-01-07        arcade: 
be0b8602d1 2026-04-18        arcade: pub type FeedList = BTreeMap<i32, String>;
9adc69d514 2026-03-25        arcade: type UserCache = TtlCache<i64, Arc<Mutex<FeedList>>>;
9adc69d514 2026-03-25        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,
9adc69d514 2026-03-25        arcade: 	pub feeds: Arc<Mutex<UserCache>>,
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()?)?,
9adc69d514 2026-03-25        arcade: 			feeds: Arc::new(Mutex::new(TtlCache::new(10000))),
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) => {
9adc69d514 2026-03-25        arcade: 						if let Err(err) = clone.tg.send(MyMessage::html(format!("🛑 {err}"))).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: 				};
9adc69d514 2026-03-25        arcade: 				self.tg.send(MyMessage::html_to(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}"),
9adc69d514 2026-03-25        arcade: 				}, destination)).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> {
9910c2209c 2023-08-04        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
3fd8c40aa8 2026-03-30        arcade: 								&& let Err(err) = clone.tg.send(MyMessage::html(format!("🛑 {source}\n<pre>{}</pre>", &err.to_string()))).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()
b4af85e31b 2025-06-29        arcade: 	}
b4af85e31b 2025-06-29        arcade: 
9adc69d514 2026-03-25        arcade: 	/// Displays full list of managed channels for specified user
b4af85e31b 2025-06-29        arcade: 	pub async fn list (&self, owner: UserPeerId) -> Result<String> {
b4af85e31b 2025-06-29        arcade: 		let mut reply: Vec<String> = vec![];
b4af85e31b 2025-06-29        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());
b4af85e31b 2025-06-29        arcade: 		};
b4af85e31b 2025-06-29        arcade: 		Ok(reply.join("\n\n"))
9adc69d514 2026-03-25        arcade: 	}
9adc69d514 2026-03-25        arcade: 
9adc69d514 2026-03-25        arcade: 	/// Returns current cached list of feed for requested user, or loads data from database
3fd8c40aa8 2026-03-30        arcade: 	pub async fn get_feeds (&self, owner: i64) -> Result<Arc<Mutex<FeedList>>> {
9adc69d514 2026-03-25        arcade: 		let mut feeds = self.feeds.lock_arc().await;
9adc69d514 2026-03-25        arcade: 		Ok(match feeds.get(&owner) {
9adc69d514 2026-03-25        arcade: 			None => {
374eadef45 2026-03-28        arcade: 				let mut conn = self.db.begin().await.stack()?;
9adc69d514 2026-03-25        arcade: 				let feed_list = conn.get_feeds(owner).await.stack()?;
be0b8602d1 2026-04-18        arcade: 				let mut map = BTreeMap::new();
9adc69d514 2026-03-25        arcade: 				for feed in feed_list {
9adc69d514 2026-03-25        arcade: 					map.insert(feed.source_id, feed.channel);
9adc69d514 2026-03-25        arcade: 				};
9adc69d514 2026-03-25        arcade: 				let res = Arc::new(Mutex::new(map));
9adc69d514 2026-03-25        arcade: 				feeds.insert(owner, res.clone(), Duration::from_secs(60 * 60 * 3));
9adc69d514 2026-03-25        arcade: 				res
9adc69d514 2026-03-25        arcade: 			},
9adc69d514 2026-03-25        arcade: 			Some(res) => res.clone(),
9adc69d514 2026-03-25        arcade: 		})
9adc69d514 2026-03-25        arcade: 	}
9adc69d514 2026-03-25        arcade: 
9adc69d514 2026-03-25        arcade: 	/// Adds feed to cached list
9adc69d514 2026-03-25        arcade: 	pub async fn add_feed (&self, owner: i64, source_id: i32, channel: String) -> Result<()> {
9adc69d514 2026-03-25        arcade: 		let mut inserted = true;
9adc69d514 2026-03-25        arcade: 		{
9adc69d514 2026-03-25        arcade: 			let mut feeds = self.feeds.lock_arc().await;
9adc69d514 2026-03-25        arcade: 			if let Some(feed) = feeds.get_mut(&owner) {
9adc69d514 2026-03-25        arcade: 				let mut feed = feed.lock_arc().await;
9adc69d514 2026-03-25        arcade: 				feed.insert(source_id, channel);
9adc69d514 2026-03-25        arcade: 			} else {
9adc69d514 2026-03-25        arcade: 				inserted = false;
9adc69d514 2026-03-25        arcade: 			}
9adc69d514 2026-03-25        arcade: 		}
374eadef45 2026-03-28        arcade: 		// in case insert failed - we miss the entry we needed to expand, reload everything from
374eadef45 2026-03-28        arcade: 		// database
9adc69d514 2026-03-25        arcade: 		if !inserted {
9adc69d514 2026-03-25        arcade: 			self.get_feeds(owner).await.stack()?;
9adc69d514 2026-03-25        arcade: 		}
9adc69d514 2026-03-25        arcade: 		Ok(())
9adc69d514 2026-03-25        arcade: 	}
9adc69d514 2026-03-25        arcade: 
9adc69d514 2026-03-25        arcade: 	/// Removes feed from cached list
9adc69d514 2026-03-25        arcade: 	pub async fn rm_feed (&self, owner: i64, source_id: &i32) -> Result<()> {
9adc69d514 2026-03-25        arcade: 		let mut dropped = false;
9adc69d514 2026-03-25        arcade: 		{
9adc69d514 2026-03-25        arcade: 			let mut feeds = self.feeds.lock_arc().await;
9adc69d514 2026-03-25        arcade: 			if let Some(feed) = feeds.get_mut(&owner) {
9adc69d514 2026-03-25        arcade: 				let mut feed = feed.lock_arc().await;
9adc69d514 2026-03-25        arcade: 				feed.remove(source_id);
9adc69d514 2026-03-25        arcade: 				dropped = true;
9adc69d514 2026-03-25        arcade: 			}
9adc69d514 2026-03-25        arcade: 		}
374eadef45 2026-03-28        arcade: 		// in case we failed to found feed we need to remove - just reload everything from database
9adc69d514 2026-03-25        arcade: 		if !dropped {
9adc69d514 2026-03-25        arcade: 			self.get_feeds(owner).await.stack()?;
9adc69d514 2026-03-25        arcade: 		}
374eadef45 2026-03-28        arcade: 		Ok(())
374eadef45 2026-03-28        arcade: 	}
3fd8c40aa8 2026-03-30        arcade: 
3fd8c40aa8 2026-03-30        arcade: 	pub async fn cb (&self, query: &CallbackQuery, cb: &str) -> Result<()> {
3fd8c40aa8 2026-03-30        arcade: 		let cb: Callback = toml::from_str(cb).stack()?;
3fd8c40aa8 2026-03-30        arcade: 		todo!();
3fd8c40aa8 2026-03-30        arcade: 		Ok(())
3fd8c40aa8 2026-03-30        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.
3fd8c40aa8 2026-03-30        arcade: 	async fn handle (&self, update: Update) -> () {
3fd8c40aa8 2026-03-30        arcade: 		match update.update_type {
3fd8c40aa8 2026-03-30        arcade: 			UpdateType::Message(msg) => {
3fd8c40aa8 2026-03-30        arcade: 				if let Ok(cmd) = Command::try_from(*msg) {
3fd8c40aa8 2026-03-30        arcade: 					let msg = cmd.get_message();
3fd8c40aa8 2026-03-30        arcade: 					let words = cmd.get_args();
3fd8c40aa8 2026-03-30        arcade: 					let command = cmd.get_name();
3fd8c40aa8 2026-03-30        arcade: 					let res = match command {
3fd8c40aa8 2026-03-30        arcade: 						"/check" | "/clean" | "/enable" | "/delete" | "/disable" => command::command(self, command, msg, words).await,
3fd8c40aa8 2026-03-30        arcade: 						"/start" => command::start(self, msg).await,
3fd8c40aa8 2026-03-30        arcade: 						"/list" => command::list(self, msg).await,
3fd8c40aa8 2026-03-30        arcade: 						"/test" => command::test(self, msg).await,
3fd8c40aa8 2026-03-30        arcade: 						"/add" | "/update" => command::update(self, command, msg, words).await,
3fd8c40aa8 2026-03-30        arcade: 						any => Err(anyhow!("Unknown command: {any}")),
3fd8c40aa8 2026-03-30        arcade: 					};
3fd8c40aa8 2026-03-30        arcade: 					if let Err(err) = res 
3fd8c40aa8 2026-03-30        arcade: 						&& let Err(err2) = self.tg.send(MyMessage::html_to(
3fd8c40aa8 2026-03-30        arcade: 							format!("#error<pre>{err}</pre>"),
3fd8c40aa8 2026-03-30        arcade: 							msg.chat.get_id(),
3fd8c40aa8 2026-03-30        arcade: 						)).await
3fd8c40aa8 2026-03-30        arcade: 					{
3fd8c40aa8 2026-03-30        arcade: 						dbg!(err2);
3fd8c40aa8 2026-03-30        arcade: 					}
3fd8c40aa8 2026-03-30        arcade: 				} else {
3fd8c40aa8 2026-03-30        arcade: 					// not a command
3fd8c40aa8 2026-03-30        arcade: 				}
3fd8c40aa8 2026-03-30        arcade: 			},
3fd8c40aa8 2026-03-30        arcade: 			UpdateType::CallbackQuery(query) => {
3fd8c40aa8 2026-03-30        arcade: 				if let Some(ref cb) = query.data
3fd8c40aa8 2026-03-30        arcade: 					&& let Err(err) = self.cb(&query, cb).await
be0b8602d1 2026-04-18        arcade: 					&& let Err(err) = self.tg.answer_cb(query.id, err.to_string()).await
3fd8c40aa8 2026-03-30        arcade: 				{
be0b8602d1 2026-04-18        arcade: 					println!("{err:?}");
3fd8c40aa8 2026-03-30        arcade: 				}
3fd8c40aa8 2026-03-30        arcade: 			},
3fd8c40aa8 2026-03-30        arcade: 			_ => {
3fd8c40aa8 2026-03-30        arcade: 				println!("Unhandled UpdateKind:\n{update:?}")
3fd8c40aa8 2026-03-30        arcade: 			},
3fd8c40aa8 2026-03-30        arcade: 		}
e624ef9d66 2025-04-20        arcade: 	}
9171c791eb 2021-11-13        arcade: }