Annotation For src/core.rs
Logged in as anonymous

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

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