Annotation For src/core.rs
Logged in as anonymous

Lines of src/core.rs from check-in 3dc9cddd4d that are changed by the sequence of edits moving toward check-in 79c91a5357:

                         1: use anyhow::{anyhow, bail, Context, Result};
                         2: use async_std::task;
                         3: use chrono::DateTime;
                         4: use sqlx::postgres::PgPoolOptions;
                         5: use std::{
                         6: 	borrow::Cow,
                         7: 	collections::{
                         8: 		BTreeMap,
                         9: 		HashSet,
                        10: 	},
                        11: 	sync::{Arc, Mutex},
                        12: };
                        13: 
                        14: #[derive(Clone)]
                        15: pub struct Core {
                        16: 	owner_chat: telegram_bot::UserId,
                        17: 	pub tg: telegram_bot::Api,
                        18: 	pub my: telegram_bot::User,
                        19: 	pool: sqlx::Pool<sqlx::Postgres>,
                        20: 	sources: Arc<Mutex<HashSet<Arc<i32>>>>,
                        21: 	http_client: reqwest::Client,
                        22: }
                        23: 
                        24: impl Core {
                        25: 	pub fn new(settings: config::Config) -> Result<Arc<Core>> {
                        26: 		let owner = settings.get_int("owner")?;
                        27: 		let api_key = settings.get_string("api_key")?;
                        28: 		let tg = telegram_bot::Api::new(api_key);
                        29: 		let tg_cloned = tg.clone();
                        30: 
                        31: 		let mut client = reqwest::Client::builder();
                        32: 		if let Ok(proxy) = settings.get_string("proxy") {
                        33: 			let proxy = reqwest::Proxy::all(proxy)?;
                        34: 			client = client.proxy(proxy);
                        35: 		}
                        36: 		let http_client = client.build()?;
                        37: 		let core = Arc::new(Core {
                        38: 			tg,
                        39: 			my: task::block_on(async {
                        40: 				tg_cloned.send(telegram_bot::GetMe).await
                        41: 			})?,
                        42: 			owner_chat: telegram_bot::UserId::new(owner),
                        43: 			pool: PgPoolOptions::new()
                        44: 				.max_connections(5)
                        45: 				.acquire_timeout(std::time::Duration::new(300, 0))
                        46: 				.idle_timeout(std::time::Duration::new(60, 0))
                        47: 				.connect_lazy(&settings.get_string("pg")?)?,
                        48: 			sources: Arc::new(Mutex::new(HashSet::new())),
                        49: 			http_client,
                        50: 		});
                        51: 		let clone = core.clone();
                        52: 		task::spawn(async move {
                        53: 			loop {
                        54: 				let delay = match &clone.autofetch().await {
                        55: 					Err(err) => {
                        56: 						if let Err(err) = clone.send(format!("šŸ›‘ {:?}", err), None, None).await {
                        57: 							eprintln!("Autofetch error: {}", err);
                        58: 						};
                        59: 						std::time::Duration::from_secs(60)
                        60: 					},
                        61: 					Ok(time) => *time,
                        62: 				};
                        63: 				task::sleep(delay).await;
                        64: 			}
                        65: 		});
                        66: 		Ok(core)
                        67: 	}
                        68: 
                        69: 	pub fn stream(&self) -> telegram_bot::UpdatesStream {
                        70: 		self.tg.stream()
                        71: 	}
                        72: 
                        73: 	pub async fn send<'a, S>(&self, msg: S, target: Option<telegram_bot::UserId>, mode: Option<telegram_bot::types::ParseMode>) -> Result<()>
                        74: 	where S: Into<Cow<'a, str>> {
                        75: 		let mode = mode.unwrap_or(telegram_bot::types::ParseMode::Html);
                        76: 		let target = target.unwrap_or(self.owner_chat);
3dc9cddd4d 2023-08-04   77: 		self.tg.send(telegram_bot::SendMessage::new(target, msg).parse_mode(mode)).await?;
                        78: 		Ok(())
                        79: 	}
                        80: 
                        81: 	pub async fn check<S>(&self, id: &i32, owner: S, real: bool) -> Result<Cow<'_, str>>
                        82: 	where S: Into<i64> {
                        83: 		let owner = owner.into();
                        84: 
                        85: 		let mut posted: i32 = 0;
                        86: 		let id = {
                        87: 			let mut set = self.sources.lock().unwrap();
                        88: 			match set.get(id) {
                        89: 				Some(id) => id.clone(),
                        90: 				None => {
                        91: 					let id = Arc::new(*id);
                        92: 					set.insert(id.clone());
                        93: 					id.clone()
                        94: 				},
                        95: 			}
                        96: 		};
                        97: 		let count = Arc::strong_count(&id);
                        98: 		if count == 2 {
                        99: 			let source = sqlx::query!("select source_id, channel_id, url, iv_hash, owner, url_re from rsstg_source where source_id = $1 and owner = $2",
                       100: 				*id, owner).fetch_one(&mut self.pool.acquire().await?).await?;
                       101: 			let destination = match real {
                       102: 				true => telegram_bot::UserId::new(source.channel_id),
                       103: 				false => telegram_bot::UserId::new(source.owner),
                       104: 			};
                       105: 			let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
                       106: 			let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
                       107: 
                       108: 			let response = self.http_client.get(&source.url).send().await?;
                       109: 			let status = response.status();
                       110: 			let content = response.bytes().await?;
                       111: 			match rss::Channel::read_from(&content[..]) {
                       112: 				Ok(feed) => {
                       113: 					for item in feed.items() {
                       114: 						if let Some(link) = item.link() {
                       115: 							let date = match item.pub_date() {
                       116: 								Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
                       117: 								None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]),
                       118: 							}?;
                       119: 							let url = link;
                       120: 							posts.insert(date, url.to_string());
                       121: 						}
                       122: 					};
                       123: 				},
                       124: 				Err(err) => match err {
                       125: 					rss::Error::InvalidStartTag => {
                       126: 						let feed = atom_syndication::Feed::read_from(&content[..])
                       127: 							.with_context(|| format!("Problem opening feed url:\n{}\n{}", &source.url, status))?;
                       128: 						for item in feed.entries() {
                       129: 							let date = item.published().unwrap();
                       130: 							let url = item.links()[0].href();
                       131: 							posts.insert(*date, url.to_string());
                       132: 						};
                       133: 					},
                       134: 					rss::Error::Eof => (),
                       135: 					_ => bail!("Unsupported or mangled content:\n{:?}\n{:#?}\n{:#?}\n", &source.url, err, status)
                       136: 				}
                       137: 			};
                       138: 			for (date, url) in posts.iter() {
                       139: 				let post_url: Cow<str> = match source.url_re {
                       140: 					Some(ref x) => sedregex::ReplaceCommand::new(x)?.execute(url),
                       141: 					None => url.into(),
                       142: 				};
                       143: 				if let Some(exists) = sqlx::query!("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;",
                       144: 					&post_url, *id).fetch_one(&mut self.pool.acquire().await?).await?.exists {
                       145: 					if ! exists {
                       146: 						if this_fetch.is_none() || *date > this_fetch.unwrap() {
                       147: 							this_fetch = Some(*date);
                       148: 						};
3dc9cddd4d 2023-08-04  149: 						self.tg.send( match &source.iv_hash {
                       150: 								Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", &post_url, hash)),
                       151: 								None => telegram_bot::SendMessage::new(destination, format!("{}", post_url)),
                       152: 							}.parse_mode(telegram_bot::types::ParseMode::Html)).await
                       153: 							.context("Can't post message:")?;
                       154: 						sqlx::query!("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);",
                       155: 							*id, date, &post_url).execute(&mut self.pool.acquire().await?).await?;
3dc9cddd4d 2023-08-04  156: 						task::sleep(std::time::Duration::new(4, 0)).await;
                       157: 					};
                       158: 				};
                       159: 				posted += 1;
                       160: 			};
                       161: 			posts.clear();
                       162: 		};
                       163: 		sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
                       164: 			*id).execute(&mut self.pool.acquire().await?).await?;
                       165: 		Ok(format!("Posted: {}", &posted).into())
                       166: 	}
                       167: 
                       168: 	pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
                       169: 	where S: Into<i64> {
                       170: 		let owner = owner.into();
                       171: 
                       172: 		match sqlx::query!("delete from rsstg_source where source_id = $1 and owner = $2;",
                       173: 			source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
                       174: 			0 => { Ok("No data found found.".into()) },
                       175: 			x => { Ok(format!("{} sources removed.", x).into()) },
                       176: 		}
                       177: 	}
                       178: 
                       179: 	pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
                       180: 	where S: Into<i64> {
                       181: 		let owner = owner.into();
                       182: 
                       183: 		match sqlx::query!("delete from rsstg_post p using rsstg_source s where p.source_id = $1 and owner = $2 and p.source_id = s.source_id;",
                       184: 			source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
                       185: 			0 => { Ok("No data found found.".into()) },
                       186: 			x => { Ok(format!("{} posts purged.", x).into()) },
                       187: 		}
                       188: 	}
                       189: 
                       190: 	pub async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
                       191: 	where S: Into<i64> {
                       192: 		let owner = owner.into();
                       193: 
                       194: 		match sqlx::query!("update rsstg_source set enabled = true where source_id = $1 and owner = $2",
                       195: 			source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
                       196: 			1 => { Ok("Source enabled.") },
                       197: 			0 => { Ok("Source not found.") },
                       198: 			_ => { Err(anyhow!("Database error.")) },
                       199: 		}
                       200: 	}
                       201: 
                       202: 	pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
                       203: 	where S: Into<i64> {
                       204: 		let owner = owner.into();
                       205: 
                       206: 		match sqlx::query!("update rsstg_source set enabled = false where source_id = $1 and owner = $2",
                       207: 			source_id, owner).execute(&mut self.pool.acquire().await?).await?.rows_affected() {
                       208: 			1 => { Ok("Source disabled.") },
                       209: 			0 => { Ok("Source not found.") },
                       210: 			_ => { Err(anyhow!("Database error.")) },
                       211: 		}
                       212: 	}
                       213: 
                       214: 	pub async fn update<S>(&self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: S) -> Result<&str>
                       215: 	where S: Into<i64> {
                       216: 		let owner = owner.into();
                       217: 
                       218: 		match match update {
                       219: 				Some(id) => {
                       220: 					sqlx::query!("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $5, channel = $6, url_re = $7 where source_id = $1",
                       221: 						id, channel_id, url, iv_hash, owner, channel, url_re).execute(&mut self.pool.acquire().await?).await
                       222: 				},
                       223: 				None => {
                       224: 					sqlx::query!("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)",
                       225: 						channel_id, url, iv_hash, owner, channel, url_re).execute(&mut self.pool.acquire().await?).await
                       226: 				},
                       227: 			} {
                       228: 			Ok(_) => Ok(match update {
                       229: 				Some(_) => "Channel updated.",
                       230: 				None => "Channel added.",
                       231: 			}),
                       232: 			Err(sqlx::Error::Database(err)) => {
                       233: 				match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
                       234: 					Some("_bt_check_unique", ) => {
                       235: 						Ok("Duplicate key.")
                       236: 					},
                       237: 					Some(_) => {
                       238: 						Ok("Database error.")
                       239: 					},
                       240: 					None => {
                       241: 						Ok("No database error extracted.")
                       242: 					},
                       243: 				}
                       244: 			},
                       245: 			Err(err) => {
                       246: 				bail!("Sorry, unknown error:\n{:#?}\n", err);
                       247: 			},
                       248: 		}
                       249: 	}
                       250: 
                       251: 	async fn autofetch(&self) -> Result<std::time::Duration> {
                       252: 		let mut delay = chrono::Duration::minutes(1);
                       253: 		let now = chrono::Local::now();
                       254: 		let mut queue = sqlx::query!(r#"select source_id, next_fetch as "next_fetch: DateTime<chrono::Local>", owner from rsstg_order natural left join rsstg_source where next_fetch < now() + interval '1 minute';"#)
                       255: 			.fetch_all(&mut self.pool.acquire().await?).await?;
                       256: 		for row in queue.iter() {
                       257: 			if let Some(next_fetch) = row.next_fetch {
                       258: 				if next_fetch < now {
                       259: 					if let (Some(owner), Some(source_id)) = (row.owner, row.source_id) {
                       260: 						let clone = Core {
                       261: 							owner_chat: telegram_bot::UserId::new(owner),
                       262: 							..self.clone()
                       263: 						};
                       264: 						task::spawn(async move {
                       265: 							if let Err(err) = clone.check(&source_id, owner, true).await {
                       266: 								if let Err(err) = clone.send(&format!("šŸ›‘ {:?}", err), None, None).await {
3dc9cddd4d 2023-08-04  267: 									eprintln!("Check error: {}", err);
3dc9cddd4d 2023-08-04  268: 									clone.disable(&source_id, owner).await.unwrap();
                       269: 								};
                       270: 							};
                       271: 						});
                       272: 					}
                       273: 				} else if next_fetch - now < delay {
                       274: 					delay = next_fetch - now;
                       275: 				}
                       276: 			}
                       277: 		};
                       278: 		queue.clear();
                       279: 		Ok(delay.to_std()?)
                       280: 	}
                       281: 
                       282: 	pub async fn list<S>(&self, owner: S) -> Result<String>
                       283: 	where S: Into<i64> {
                       284: 		let owner = owner.into();
                       285: 
                       286: 		let mut reply: Vec<Cow<str>> = vec![];
                       287: 		reply.push("Channels:".into());
                       288: 		let rows = sqlx::query!("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id",
3dc9cddd4d 2023-08-04  289: 			owner).fetch_all(&mut self.pool.acquire().await?).await?;
                       290: 		for row in rows.iter() {
3dc9cddd4d 2023-08-04  291: 			reply.push(format!("\n\\#ļøāƒ£ {} \\*ļøāƒ£ `{}` {}\nšŸ”— `{}`", row.source_id, row.channel,  
                       292: 				match row.enabled {
                       293: 					true  => "šŸ”„ enabled",
                       294: 					false => "ā›” disabled",
                       295: 				}, row.url).into());
                       296: 			if let Some(hash) = &row.iv_hash {
                       297: 				reply.push(format!("IV: `{}`", hash).into());
                       298: 			}
                       299: 			if let Some(re) = &row.url_re {
                       300: 				reply.push(format!("RE: `{}`", re).into());
                       301: 			}
                       302: 		};
                       303: 		Ok(reply.join("\n"))
                       304: 	}
                       305: }