Annotation For src/core.rs
Logged in as anonymous

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

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