Annotation For src/core.rs
Logged in as anonymous

Lines of src/core.rs from check-in d8c1d259a2 that are changed by the sequence of edits moving toward check-in d3dbaf11e1:

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