Annotation For src/core.rs
Logged in as anonymous

Lines of src/core.rs from check-in 61899b5618 that are changed by the sequence of edits moving toward check-in 1bd041d00f:

                         1: use crate::{
                         2: 	command,
                         3: 	sql::Db,
                         4: };
                         5: 
                         6: use std::{
                         7: 	borrow::Cow,
                         8: 	collections::{
                         9: 		BTreeMap,
                        10: 		HashSet,
                        11: 	},
                        12: 	num::TryFromIntError,
                        13: 	sync::{
                        14: 		Arc,
                        15: 		Mutex
                        16: 	},
                        17: };
                        18: 
                        19: use anyhow::{
                        20: 	bail,
                        21: 	Result,
                        22: };
                        23: use async_std::task;
                        24: use chrono::DateTime;
                        25: use frankenstein::{
                        26: 	client_reqwest::Bot,
                        27: 	methods::{
                        28: 		GetUpdatesParams,
                        29: 		SendMessageParams
                        30: 	},
                        31: 	types::{
                        32: 		AllowedUpdate,
                        33: 		MessageEntityType,
                        34: 		User,
                        35: 	},
                        36: 	updates::UpdateContent,
61899b5618 2025-04-26   37: 	AsyncTelegramApi,
61899b5618 2025-04-26   38: 	ParseMode,
                        39: };
                        40: use thiserror::Error;
                        41: 
                        42: #[derive(Error, Debug)]
                        43: pub enum RssError {
                        44: 	// #[error(transparent)]
                        45: 	// Tg(#[from] TgError),
                        46: 	#[error(transparent)]
                        47: 	Int(#[from] TryFromIntError),
                        48: }
                        49: 
                        50: #[derive(Clone)]
                        51: pub struct Core {
                        52: 	owner_chat: i64,
                        53: 	pub tg: Bot,
                        54: 	pub me: User,
                        55: 	pub db: Db,
                        56: 	sources: Arc<Mutex<HashSet<Arc<i32>>>>,
                        57: 	http_client: reqwest::Client,
                        58: }
                        59: 
                        60: impl Core {
                        61: 	pub async fn new(settings: config::Config) -> Result<Core> {
                        62: 		let owner_chat = settings.get_int("owner")?;
                        63: 		let api_key = settings.get_string("api_key")?;
                        64: 		let tg = Bot::new(&api_key);
                        65: 
                        66: 		let mut client = reqwest::Client::builder();
                        67: 		if let Ok(proxy) = settings.get_string("proxy") {
                        68: 			let proxy = reqwest::Proxy::all(proxy)?;
                        69: 			client = client.proxy(proxy);
                        70: 		}
                        71: 		let http_client = client.build()?;
                        72: 		let me = tg.get_me().await?;
                        73: 		let me = me.result;
                        74: 		let core = Core {
                        75: 			tg,
                        76: 			me,
                        77: 			owner_chat,
                        78: 			db: Db::new(&settings.get_string("pg")?)?,
                        79: 			sources: Arc::new(Mutex::new(HashSet::new())),
                        80: 			http_client,
                        81: 		};
                        82: 		let mut clone = core.clone();
                        83: 		task::spawn(async move {
                        84: 			loop {
                        85: 				let delay = match &clone.autofetch().await {
                        86: 					Err(err) => {
                        87: 						if let Err(err) = clone.send(format!("šŸ›‘ {err:?}"), None, None).await {
                        88: 							eprintln!("Autofetch error: {err:?}");
                        89: 						};
                        90: 						std::time::Duration::from_secs(60)
                        91: 					},
                        92: 					Ok(time) => *time,
                        93: 				};
                        94: 				task::sleep(delay).await;
                        95: 			}
                        96: 		});
                        97: 		Ok(core)
                        98: 	}
                        99: 
                       100: 	pub async fn stream(&mut self) -> Result<()> {
                       101: 		let mut offset: i64 = 0;
                       102: 		let mut params = GetUpdatesParams {
                       103: 			offset: None,
                       104: 			limit: Some(100),
                       105: 			timeout: Some(300),
                       106: 			allowed_updates: Some(vec![AllowedUpdate::Message]),
                       107: 		};
                       108: 		loop {
                       109: 			let updates = self.tg.get_updates(&params).await?.result;
                       110: 			if updates.is_empty() {
                       111: 				offset = 0;
                       112: 				params.offset = None;
                       113: 				continue;
                       114: 			}
                       115: 			for update in updates {
                       116: 				if i64::from(update.update_id) >= offset {
                       117: 					offset = i64::from(update.update_id) + 1;
                       118: 					params.offset = Some(offset);
                       119: 				}
                       120: 				if let UpdateContent::Message(msg) = update.content {
                       121: 					if let Some(text) = msg.text {
                       122: 						if let Some(entities) = msg.entities {
                       123: 							let chars: Vec<u16> = text.encode_utf16().collect();
                       124: 							for entity in entities {
                       125: 								if entity.type_field == MessageEntityType::BotCommand && entity.offset != 0 {
                       126: 									bail!("commands should be at message start");
                       127: 								};
                       128: 								let cmd = String::from_utf16_lossy(&chars[entity.offset as usize..entity.length as usize]);
                       129: 								let words: Vec<&str> = text.split_whitespace().collect();
61899b5618 2025-04-26  130: 								match cmd.as_ref() {
61899b5618 2025-04-26  131: 									"/check" | "/clean" | "/enable" | "/delete" | "/disable" => { command::command(self, msg.chat.id, words).await? },
61899b5618 2025-04-26  132: 									"/start" => { command::start(self, msg.chat.id).await?; },
61899b5618 2025-04-26  133: 									"/list" => { command::list(self, msg.chat.id).await?; },
61899b5618 2025-04-26  134: 									"/add" | "/update" => { command::update(self, msg.chat.id, words).await?; },
61899b5618 2025-04-26  135: 									any => {
61899b5618 2025-04-26  136: 										self.send(format!("\\#error\n```\nUnknown command: {any}\n```"),
61899b5618 2025-04-26  137: 											Some(msg.chat.id),
61899b5618 2025-04-26  138: 											Some(ParseMode::MarkdownV2)
61899b5618 2025-04-26  139: 										).await?;
61899b5618 2025-04-26  140: 									},
61899b5618 2025-04-26  141: 								};
                       142: 							};
                       143: 						};
                       144: 					};
                       145: 				};
                       146: 			}
                       147: 		}
                       148: 	}
                       149: 
                       150: 	pub async fn send <S>(&self, msg: S, target: Option<i64>, mode: Option<ParseMode>) -> Result<()>
                       151: 	where S: Into<String> {
                       152: 		let msg = msg.into();
                       153: 
                       154: 		let mode = mode.unwrap_or(ParseMode::Html);
                       155: 		let target = target.unwrap_or(self.owner_chat);
                       156: 		let send = SendMessageParams::builder()
                       157: 			.chat_id(target)
                       158: 			.text(msg)
                       159: 			.parse_mode(mode)
                       160: 			.build();
61899b5618 2025-04-26  161: 		self.tg.send_message(&send).await?;
                       162: 		Ok(())
                       163: 	}
                       164: 
                       165: 	pub async fn check (&mut self, id: &i32, owner: i64, real: bool) -> Result<String> {
                       166: 		let mut posted: i32 = 0;
                       167: 		let mut conn = self.db.begin().await?;
                       168: 
                       169: 		let id = {
                       170: 			let mut set = self.sources.lock().unwrap();
                       171: 			match set.get(id) {
                       172: 				Some(id) => id.clone(),
                       173: 				None => {
                       174: 					let id = Arc::new(*id);
                       175: 					set.insert(id.clone());
                       176: 					id.clone()
                       177: 				},
                       178: 			}
                       179: 		};
                       180: 		let count = Arc::strong_count(&id);
                       181: 		if count == 2 {
                       182: 			let source = conn.get_source(*id, owner).await?;
                       183: 			conn.set_scrape(*id).await?;
                       184: 			let destination = match real {
                       185: 				true => source.channel_id,
                       186: 				false => source.owner,
                       187: 			};
                       188: 			let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
                       189: 			let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
                       190: 
                       191: 			let response = self.http_client.get(&source.url).send().await?;
                       192: 			let status = response.status();
                       193: 			let content = response.bytes().await?;
                       194: 			match rss::Channel::read_from(&content[..]) {
                       195: 				Ok(feed) => {
                       196: 					for item in feed.items() {
                       197: 						if let Some(link) = item.link() {
                       198: 							let date = match item.pub_date() {
                       199: 								Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
                       200: 								None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]),
                       201: 							}?;
                       202: 							let url = link;
                       203: 							posts.insert(date, url.to_string());
                       204: 						}
                       205: 					};
                       206: 				},
                       207: 				Err(err) => match err {
                       208: 					rss::Error::InvalidStartTag => {
                       209: 						match atom_syndication::Feed::read_from(&content[..]) {
                       210: 							Ok(feed) => {
                       211: 								for item in feed.entries() {
                       212: 									let date = item.published().unwrap();
                       213: 									let url = item.links()[0].href();
                       214: 									posts.insert(*date, url.to_string());
                       215: 								};
                       216: 							},
                       217: 							Err(err) => {
                       218: 								bail!("Unsupported or mangled content:\n{:?}\n{err:#?}\n{status:#?}\n", &source.url)
                       219: 							},
                       220: 						}
                       221: 					},
                       222: 					rss::Error::Eof => (),
                       223: 					_ => bail!("Unsupported or mangled content:\n{:?}\n{err:#?}\n{status:#?}\n", &source.url)
                       224: 				}
                       225: 			};
                       226: 			for (date, url) in posts.iter() {
                       227: 				let post_url: Cow<str> = match source.url_re {
                       228: 					Some(ref x) => sedregex::ReplaceCommand::new(x)?.execute(url),
                       229: 					None => url.into(),
                       230: 				};
                       231: 				if let Some(exists) = conn.exists(&post_url, *id).await? {
                       232: 					if ! exists {
                       233: 						if this_fetch.is_none() || *date > this_fetch.unwrap() {
                       234: 							this_fetch = Some(*date);
                       235: 						};
                       236: 						self.send( match &source.iv_hash {
                       237: 							Some(hash) => format!("<a href=\"https://t.me/iv?url={post_url}&rhash={hash}\"> </a>{post_url}"),
                       238: 							None => format!("{post_url}"),
                       239: 						}, Some(destination), Some(ParseMode::Html)).await?;
                       240: 						conn.add_post(*id, date, &post_url).await?;
                       241: 					};
                       242: 				};
                       243: 				posted += 1;
                       244: 			};
                       245: 			posts.clear();
                       246: 		};
                       247: 		Ok(format!("Posted: {posted}"))
                       248: 	}
                       249: 
                       250: 	async fn autofetch(&mut self) -> Result<std::time::Duration> {
                       251: 		let mut delay = chrono::Duration::minutes(1);
                       252: 		let now = chrono::Local::now();
                       253: 		let mut conn = self.db.begin().await?;
                       254: 		for row in conn.get_queue().await? {
                       255: 			if let Some(next_fetch) = row.next_fetch {
                       256: 				if next_fetch < now {
                       257: 					if let (Some(owner), Some(source_id)) = (row.owner, row.source_id) {
                       258: 						let mut clone = Core {
                       259: 							owner_chat: owner,
                       260: 							..self.clone()
                       261: 						};
                       262: 						task::spawn(async move {
                       263: 							if let Err(err) = clone.check(&source_id, owner, true).await {
                       264: 								if let Err(err) = clone.send(&format!("šŸ›‘ {err:?}"), None, None).await {
                       265: 									eprintln!("Check error: {err:?}");
                       266: 									// clone.disable(&source_id, owner).await.unwrap();
                       267: 								};
                       268: 							};
                       269: 						});
                       270: 					}
                       271: 				} else if next_fetch - now < delay {
                       272: 					delay = next_fetch - now;
                       273: 				}
                       274: 			}
                       275: 		};
                       276: 		Ok(delay.to_std()?)
                       277: 	}
                       278: 
                       279: 	pub async fn list (&mut self, owner: i64) -> Result<String> {
                       280: 		let mut reply: Vec<Cow<str>> = vec![];
                       281: 		reply.push("Channels:".into());
                       282: 		let mut conn = self.db.begin().await?;
                       283: 		for row in conn.get_list(owner).await? {
                       284: 			reply.push(format!("\n\\#ļøāƒ£ {} \\*ļøāƒ£ `{}` {}\nšŸ”— `{}`", row.source_id, row.channel,
                       285: 				match row.enabled {
                       286: 					true  => "šŸ”„ enabled",
                       287: 					false => "ā›” disabled",
                       288: 				}, row.url).into());
                       289: 			if let Some(hash) = &row.iv_hash {
                       290: 				reply.push(format!("IV: `{hash}`").into());
                       291: 			}
                       292: 			if let Some(re) = &row.url_re {
                       293: 				reply.push(format!("RE: `{re}`").into());
                       294: 			}
                       295: 		};
                       296: 		Ok(reply.join("\n"))
                       297: 	}
                       298: }