6ac5737a72 2020-11-18 1: use std::collections::BTreeMap;
6ac5737a72 2020-11-18 2:
61df933942 2020-11-18 3: use config;
61df933942 2020-11-18 4:
61df933942 2020-11-18 5: use tokio;
423cadd9c7 2020-11-27 6:
61df933942 2020-11-18 7: use rss;
423cadd9c7 2020-11-27 8:
61df933942 2020-11-18 9: use chrono::DateTime;
61df933942 2020-11-18 10:
61df933942 2020-11-18 11: use regex::Regex;
61df933942 2020-11-18 12:
61df933942 2020-11-18 13: use telegram_bot::*;
423cadd9c7 2020-11-27 14: use tokio::stream::StreamExt;
61df933942 2020-11-18 15:
61df933942 2020-11-18 16: use sqlx::postgres::PgPoolOptions;
61df933942 2020-11-18 17: use sqlx::Row;
423cadd9c7 2020-11-27 18: use sqlx::Done; // .rows_affected()
4acdad1942 2020-11-26 19:
4acdad1942 2020-11-26 20: #[macro_use]
4acdad1942 2020-11-26 21: extern crate lazy_static;
61df933942 2020-11-18 22:
4acdad1942 2020-11-26 23: use anyhow::{anyhow, Context, Result};
61df933942 2020-11-18 24:
0191d490fe 2020-11-18 25: #[derive(Clone)]
61df933942 2020-11-18 26: struct Core {
61df933942 2020-11-18 27: owner: i64,
0191d490fe 2020-11-18 28: api_key: String,
61df933942 2020-11-18 29: owner_chat: UserId,
61df933942 2020-11-18 30: tg: telegram_bot::Api,
61df933942 2020-11-18 31: my: User,
61df933942 2020-11-18 32: pool: sqlx::Pool<sqlx::Postgres>,
61df933942 2020-11-18 33: }
61df933942 2020-11-18 34:
61df933942 2020-11-18 35: impl Core {
61df933942 2020-11-18 36: async fn new(settings: config::Config) -> Result<Core> {
61df933942 2020-11-18 37: let owner = settings.get_int("owner")?;
0191d490fe 2020-11-18 38: let api_key = settings.get_str("api_key")?;
0191d490fe 2020-11-18 39: let tg = Api::new(&api_key);
0191d490fe 2020-11-18 40: let core = Core {
0191d490fe 2020-11-18 41: owner: owner,
0191d490fe 2020-11-18 42: api_key: api_key.clone(),
0191d490fe 2020-11-18 43: my: tg.send(telegram_bot::GetMe).await?,
0191d490fe 2020-11-18 44: tg: tg,
0191d490fe 2020-11-18 45: owner_chat: UserId::new(owner),
3d3fde1b28 2020-11-25 46: pool: PgPoolOptions::new()
3d3fde1b28 2020-11-25 47: .max_connections(5)
3d3fde1b28 2020-11-25 48: .connect_timeout(std::time::Duration::new(300, 0))
3d3fde1b28 2020-11-25 49: .idle_timeout(std::time::Duration::new(60, 0))
3d3fde1b28 2020-11-25 50: .connect_lazy(&settings.get_str("pg")?)?,
0191d490fe 2020-11-18 51: };
0191d490fe 2020-11-18 52: let clone = core.clone();
0191d490fe 2020-11-18 53: tokio::spawn(async move {
423cadd9c7 2020-11-27 54: if let Err(err) = &clone.autofetch().await {
39ee25f5c3 2020-11-29 55: if let Err(err) = clone.debug(&format!("{:?}", err)) {
423cadd9c7 2020-11-27 56: eprintln!("Autofetch error: {}", err);
423cadd9c7 2020-11-27 57: };
0191d490fe 2020-11-18 58: }
0191d490fe 2020-11-18 59: });
0191d490fe 2020-11-18 60: Ok(core)
61df933942 2020-11-18 61: }
61df933942 2020-11-18 62:
61df933942 2020-11-18 63: fn stream(&self) -> telegram_bot::UpdatesStream {
61df933942 2020-11-18 64: self.tg.stream()
61df933942 2020-11-18 65: }
61df933942 2020-11-18 66:
61df933942 2020-11-18 67: fn debug(&self, msg: &str) -> Result<()> {
61df933942 2020-11-18 68: self.tg.spawn(SendMessage::new(self.owner_chat, msg));
61df933942 2020-11-18 69: Ok(())
61df933942 2020-11-18 70: }
61df933942 2020-11-18 71:
ebe7c281a5 2020-11-27 72: async fn check<S>(&self, id: &i32, owner: S, real: bool) -> Result<()>
ebe7c281a5 2020-11-27 73: where S: Into<i64> {
ebe7c281a5 2020-11-27 74: let owner: i64 = owner.into();
423cadd9c7 2020-11-27 75: let mut conn = self.pool.acquire().await
423cadd9c7 2020-11-27 76: .with_context(|| format!("π Query queue fetch conn:\n{:?}", &self.pool))?;
ebe7c281a5 2020-11-27 77: let row = sqlx::query("select source_id, channel_id, url, iv_hash, owner from rsstg_source where source_id = $1 and owner = $2")
423cadd9c7 2020-11-27 78: .bind(id)
ebe7c281a5 2020-11-27 79: .bind(owner)
423cadd9c7 2020-11-27 80: .fetch_one(&mut conn).await
423cadd9c7 2020-11-27 81: .with_context(|| format!("π Query source:\n{:?}", &self.pool))?;
423cadd9c7 2020-11-27 82: drop(conn);
423cadd9c7 2020-11-27 83: let channel_id: i64 = row.try_get("channel_id")?;
423cadd9c7 2020-11-27 84: let destination = match real {
423cadd9c7 2020-11-27 85: true => UserId::new(channel_id),
423cadd9c7 2020-11-27 86: false => UserId::new(row.try_get("owner")?),
423cadd9c7 2020-11-27 87: };
423cadd9c7 2020-11-27 88: let url: &str = row.try_get("url")?;
423cadd9c7 2020-11-27 89: let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None;
423cadd9c7 2020-11-27 90: let iv_hash: Option<&str> = row.try_get("iv_hash")?;
423cadd9c7 2020-11-27 91: let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new();
423cadd9c7 2020-11-27 92: let feed = rss::Channel::from_url(url)
423cadd9c7 2020-11-27 93: .with_context(|| format!("π Problem opening feed url:\n{}", &url))?;
423cadd9c7 2020-11-27 94: for item in feed.items() {
423cadd9c7 2020-11-27 95: let date = match item.pub_date() {
423cadd9c7 2020-11-27 96: Some(feed_date) => DateTime::parse_from_rfc2822(feed_date),
423cadd9c7 2020-11-27 97: None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]),
423cadd9c7 2020-11-27 98: }?;
423cadd9c7 2020-11-27 99: let url = item.link().unwrap().to_string();
423cadd9c7 2020-11-27 100: posts.insert(date.clone(), url.clone());
423cadd9c7 2020-11-27 101: };
423cadd9c7 2020-11-27 102: for (date, url) in posts.iter() {
423cadd9c7 2020-11-27 103: let mut conn = self.pool.acquire().await
423cadd9c7 2020-11-27 104: .with_context(|| format!("π Check post fetch conn:\n{:?}", &self.pool))?;
423cadd9c7 2020-11-27 105: let row = sqlx::query("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;")
423cadd9c7 2020-11-27 106: .bind(&url)
423cadd9c7 2020-11-27 107: .bind(id)
423cadd9c7 2020-11-27 108: .fetch_one(&mut conn).await
423cadd9c7 2020-11-27 109: .with_context(|| format!("π Check post:\n{:?}", &conn))?;
423cadd9c7 2020-11-27 110: let exists: bool = row.try_get("exists")?;
423cadd9c7 2020-11-27 111: if ! exists {
423cadd9c7 2020-11-27 112: if this_fetch == None || *date > this_fetch.unwrap() {
423cadd9c7 2020-11-27 113: this_fetch = Some(*date);
423cadd9c7 2020-11-27 114: };
423cadd9c7 2020-11-27 115: self.tg.send( match iv_hash {
423cadd9c7 2020-11-27 116: Some(x) => SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", url, x)),
423cadd9c7 2020-11-27 117: None => SendMessage::new(destination, format!("{}", url)),
423cadd9c7 2020-11-27 118: }.parse_mode(types::ParseMode::Html)).await
423cadd9c7 2020-11-27 119: .context("π Can't post message:")?;
423cadd9c7 2020-11-27 120: sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);")
423cadd9c7 2020-11-27 121: .bind(id)
423cadd9c7 2020-11-27 122: .bind(date)
423cadd9c7 2020-11-27 123: .bind(url)
423cadd9c7 2020-11-27 124: .execute(&mut conn).await
423cadd9c7 2020-11-27 125: .with_context(|| format!("πRecord post:\n{:?}", &conn))?;
423cadd9c7 2020-11-27 126: drop(conn);
423cadd9c7 2020-11-27 127: tokio::time::delay_for(std::time::Duration::new(4, 0)).await;
423cadd9c7 2020-11-27 128: };
423cadd9c7 2020-11-27 129: };
423cadd9c7 2020-11-27 130: posts.clear();
423cadd9c7 2020-11-27 131: let mut conn = self.pool.acquire().await
423cadd9c7 2020-11-27 132: .with_context(|| format!("π Update scrape fetch conn:\n{:?}", &self.pool))?;
423cadd9c7 2020-11-27 133: sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
423cadd9c7 2020-11-27 134: .bind(id)
423cadd9c7 2020-11-27 135: .execute(&mut conn).await
423cadd9c7 2020-11-27 136: .with_context(|| format!("π Update scrape:\n{:?}", &conn))?;
423cadd9c7 2020-11-27 137: Ok(())
423cadd9c7 2020-11-27 138: }
423cadd9c7 2020-11-27 139:
ebe7c281a5 2020-11-27 140: async fn clean<S>(&self, source_id: &i32, id: S) -> Result<String>
ebe7c281a5 2020-11-27 141: where S: Into<i64> {
ebe7c281a5 2020-11-27 142: let id: i64 = id.into();
423cadd9c7 2020-11-27 143: let mut conn = self.pool.acquire().await
423cadd9c7 2020-11-27 144: .with_context(|| format!("π Clean fetch conn:\n{:?}", &self.pool))?;
ebe7c281a5 2020-11-27 145: 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;")
423cadd9c7 2020-11-27 146: .bind(source_id)
ebe7c281a5 2020-11-27 147: .bind(id)
423cadd9c7 2020-11-27 148: .execute(&mut conn).await
ebe7c281a5 2020-11-27 149: .with_context(|| format!("π Clean seen posts:\n{:?}", &self.pool))?
ebe7c281a5 2020-11-27 150: .rows_affected() {
ebe7c281a5 2020-11-27 151: 0 => { Ok("No data found found\\.".to_string()) },
ebe7c281a5 2020-11-27 152: x => { Ok(format!("{} posts purged\\.", x)) },
ebe7c281a5 2020-11-27 153: }
423cadd9c7 2020-11-27 154: }
423cadd9c7 2020-11-27 155:
ebe7c281a5 2020-11-27 156: async fn enable<S>(&self, source_id: &i32, id: S) -> Result<&str>
ebe7c281a5 2020-11-27 157: where S: Into<i64> {
ebe7c281a5 2020-11-27 158: let id: i64 = id.into();
4acdad1942 2020-11-26 159: let mut conn = self.pool.acquire().await
4acdad1942 2020-11-26 160: .with_context(|| format!("π Enable fetch conn:\n{:?}", &self.pool))?;
4acdad1942 2020-11-26 161: match sqlx::query("update rsstg_source set enabled = true where source_id = $1 and owner = $2")
4acdad1942 2020-11-26 162: .bind(source_id)
ebe7c281a5 2020-11-27 163: .bind(id)
4acdad1942 2020-11-26 164: .execute(&mut conn).await
39ee25f5c3 2020-11-29 165: .with_context(|| format!("π Enable source:\n{:?}", &self.pool))?
4acdad1942 2020-11-26 166: .rows_affected() {
4acdad1942 2020-11-26 167: 1 => { Ok("Source disabled\\.") },
4acdad1942 2020-11-26 168: 0 => { Ok("Source not found\\.") },
4acdad1942 2020-11-26 169: _ => { Err(anyhow!("Database error.")) },
4acdad1942 2020-11-26 170: }
4acdad1942 2020-11-26 171: }
4acdad1942 2020-11-26 172:
ebe7c281a5 2020-11-27 173: async fn disable<S>(&self, source_id: &i32, id: S) -> Result<&str>
ebe7c281a5 2020-11-27 174: where S: Into<i64> {
ebe7c281a5 2020-11-27 175: let id: i64 = id.into();
4acdad1942 2020-11-26 176: let mut conn = self.pool.acquire().await
4acdad1942 2020-11-26 177: .with_context(|| format!("π Disable fetch conn:\n{:?}", &self.pool))?;
4acdad1942 2020-11-26 178: match sqlx::query("update rsstg_source set enabled = false where source_id = $1 and owner = $2")
4acdad1942 2020-11-26 179: .bind(source_id)
ebe7c281a5 2020-11-27 180: .bind(id)
4acdad1942 2020-11-26 181: .execute(&mut conn).await
39ee25f5c3 2020-11-29 182: .with_context(|| format!("π Disable source:\n{:?}", &self.pool))?
4acdad1942 2020-11-26 183: .rows_affected() {
4acdad1942 2020-11-26 184: 1 => { Ok("Source disabled\\.") },
4acdad1942 2020-11-26 185: 0 => { Ok("Source not found\\.") },
4acdad1942 2020-11-26 186: _ => { Err(anyhow!("Database error.")) },
4acdad1942 2020-11-26 187: }
61df933942 2020-11-18 188: }
61df933942 2020-11-18 189:
61df933942 2020-11-18 190: async fn autofetch(&self) -> Result<()> {
61df933942 2020-11-18 191: let mut delay = chrono::Duration::minutes(5);
61df933942 2020-11-18 192: let mut now;
61df933942 2020-11-18 193: loop {
423cadd9c7 2020-11-27 194: let mut conn = self.pool.acquire().await
423cadd9c7 2020-11-27 195: .with_context(|| format!("π Autofetch fetch conn:\n{:?}", &self.pool))?;
423cadd9c7 2020-11-27 196: now = chrono::Local::now();
ebe7c281a5 2020-11-27 197: let mut queue = sqlx::query("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source natural left join rsstg_channel where next_fetch < now();")
423cadd9c7 2020-11-27 198: .fetch_all(&mut conn).await?;
423cadd9c7 2020-11-27 199: for row in queue.iter() {
423cadd9c7 2020-11-27 200: let source_id: i32 = row.try_get("source_id")?;
ebe7c281a5 2020-11-27 201: let owner: i64 = row.try_get("owner")?;
423cadd9c7 2020-11-27 202: let next_fetch: DateTime<chrono::Local> = row.try_get("next_fetch")?;
423cadd9c7 2020-11-27 203: if next_fetch < now {
423cadd9c7 2020-11-27 204: sqlx::query("update rsstg_source set last_scrape = now() + interval '1 hour' where source_id = $1;")
423cadd9c7 2020-11-27 205: .bind(source_id)
423cadd9c7 2020-11-27 206: .execute(&mut conn).await
423cadd9c7 2020-11-27 207: .with_context(|| format!("π Lock source:\n\n{:?}", &self.pool))?;
423cadd9c7 2020-11-27 208: let clone = self.clone();
423cadd9c7 2020-11-27 209: tokio::spawn(async move {
ebe7c281a5 2020-11-27 210: if let Err(err) = clone.check(&source_id, owner, true).await {
39ee25f5c3 2020-11-29 211: if let Err(err) = clone.debug(&format!("{:?}", err)) {
423cadd9c7 2020-11-27 212: eprintln!("Check error: {}", err);
423cadd9c7 2020-11-27 213: };
423cadd9c7 2020-11-27 214: };
423cadd9c7 2020-11-27 215: });
423cadd9c7 2020-11-27 216: } else {
423cadd9c7 2020-11-27 217: if next_fetch - now < delay {
423cadd9c7 2020-11-27 218: delay = next_fetch - now;
423cadd9c7 2020-11-27 219: }
423cadd9c7 2020-11-27 220: }
423cadd9c7 2020-11-27 221: };
423cadd9c7 2020-11-27 222: queue.clear();
61df933942 2020-11-18 223: tokio::time::delay_for(delay.to_std()?).await;
075be7e40e 2020-11-18 224: delay = chrono::Duration::minutes(5);
61df933942 2020-11-18 225: }
61df933942 2020-11-18 226: }
61df933942 2020-11-18 227:
ebe7c281a5 2020-11-27 228: async fn list(&self, id: telegram_bot::UserId) -> Result<Vec<String>> {
ebe7c281a5 2020-11-27 229: let id = i64::from(id);
ebe7c281a5 2020-11-27 230: let mut reply = vec![];
ebe7c281a5 2020-11-27 231: let mut conn = self.pool.acquire().await
ebe7c281a5 2020-11-27 232: .with_context(|| format!("π List fetch conn:\n{:?}", &self.pool))?;
ebe7c281a5 2020-11-27 233: reply.push("Channels:".to_string());
ebe7c281a5 2020-11-27 234: let rows = sqlx::query("select source_id, username, enabled, url, iv_hash from rsstg_source left join rsstg_channel using (channel_id) where owner = $1 order by source_id")
ebe7c281a5 2020-11-27 235: .bind(id)
ebe7c281a5 2020-11-27 236: .fetch_all(&mut conn).await?;
ebe7c281a5 2020-11-27 237: for row in rows.iter() {
ebe7c281a5 2020-11-27 238: let source_id: i32 = row.try_get("source_id")?;
ebe7c281a5 2020-11-27 239: let username: &str = row.try_get("username")?;
ebe7c281a5 2020-11-27 240: let enabled: bool = row.try_get("enabled")?;
ebe7c281a5 2020-11-27 241: let url: &str = row.try_get("url")?;
ebe7c281a5 2020-11-27 242: let iv_hash: Option<&str> = row.try_get("iv_hash")?;
ebe7c281a5 2020-11-27 243: reply.push(format!("\n\\#οΈβ£ {} \\*οΈβ£ `{}` {}\nπ `{}`", source_id, username,
ebe7c281a5 2020-11-27 244: match enabled {
ebe7c281a5 2020-11-27 245: true => "π enabled",
ebe7c281a5 2020-11-27 246: false => "β disabled",
ebe7c281a5 2020-11-27 247: }, url));
ebe7c281a5 2020-11-27 248: if let Some(hash) = iv_hash {
ebe7c281a5 2020-11-27 249: reply.push(format!("IV `{}`", hash));
ebe7c281a5 2020-11-27 250: }
ebe7c281a5 2020-11-27 251: };
ebe7c281a5 2020-11-27 252: Ok(reply)
ebe7c281a5 2020-11-27 253: }
61df933942 2020-11-18 254: }
61df933942 2020-11-18 255:
ec616a2a43 2020-11-19 256: #[tokio::main]
61df933942 2020-11-18 257: async fn main() -> Result<()> {
61df933942 2020-11-18 258: let mut settings = config::Config::default();
61df933942 2020-11-18 259: settings.merge(config::File::with_name("rsstg"))?;
61df933942 2020-11-18 260:
61df933942 2020-11-18 261: let core = Core::new(settings).await?;
61df933942 2020-11-18 262:
61df933942 2020-11-18 263: let mut stream = core.stream();
61df933942 2020-11-18 264:
61df933942 2020-11-18 265: while let Some(update) = stream.next().await {
423cadd9c7 2020-11-27 266: if let Err(err) = handle(update?, &core).await {
39ee25f5c3 2020-11-29 267: core.debug(&format!("{:?}", err))?;
4acdad1942 2020-11-26 268: };
4acdad1942 2020-11-26 269: }
4acdad1942 2020-11-26 270:
4acdad1942 2020-11-26 271: Ok(())
4acdad1942 2020-11-26 272: }
4acdad1942 2020-11-26 273:
4acdad1942 2020-11-26 274: async fn handle(update: telegram_bot::Update, core: &Core) -> Result<()> {
4acdad1942 2020-11-26 275: lazy_static! {
4acdad1942 2020-11-26 276: static ref RE_USERNAME: Regex = Regex::new(r"^@[a-zA-Z][a-zA-Z0-9_]+$").unwrap();
4acdad1942 2020-11-26 277: static ref RE_LINK: Regex = Regex::new(r"^https?://[a-zA-Z.0-9-]+/[-_a-zA-Z.0-9/?=]+$").unwrap();
4acdad1942 2020-11-26 278: static ref RE_IV_HASH: Regex = Regex::new(r"^[a-f0-9]{14}$").unwrap();
4acdad1942 2020-11-26 279: }
4acdad1942 2020-11-26 280:
4acdad1942 2020-11-26 281: match update.kind {
4acdad1942 2020-11-26 282: UpdateKind::Message(message) => {
4acdad1942 2020-11-26 283: let mut reply: Vec<String> = vec![];
4acdad1942 2020-11-26 284: match message.kind {
4acdad1942 2020-11-26 285: MessageKind::Text { ref data, .. } => {
4acdad1942 2020-11-26 286: let mut words = data.split_whitespace();
4acdad1942 2020-11-26 287: let cmd = words.next().unwrap();
4acdad1942 2020-11-26 288: match cmd {
4acdad1942 2020-11-26 289:
4acdad1942 2020-11-26 290: // start
4acdad1942 2020-11-26 291:
4acdad1942 2020-11-26 292: "/start" => {
4acdad1942 2020-11-26 293: reply.push("We are open\\. Probably\\. Visit [channel](https://t.me/rsstg_bot_help/3) for details\\.".to_string());
4acdad1942 2020-11-26 294: },
4acdad1942 2020-11-26 295:
4acdad1942 2020-11-26 296: // list
4acdad1942 2020-11-26 297:
4acdad1942 2020-11-26 298: "/list" => {
ebe7c281a5 2020-11-27 299: reply.append(&mut core.list(message.from.id).await?);
4acdad1942 2020-11-26 300: },
4acdad1942 2020-11-26 301:
4acdad1942 2020-11-26 302: // add
4acdad1942 2020-11-26 303:
4acdad1942 2020-11-26 304: "/add" | "/update" => {
4acdad1942 2020-11-26 305: let mut source_id: i32 = 0;
4acdad1942 2020-11-26 306: if cmd == "/update" {
4acdad1942 2020-11-26 307: source_id = words.next().unwrap().parse::<i32>()?;
4acdad1942 2020-11-26 308: }
4acdad1942 2020-11-26 309: let (channel, url, iv_hash) = (words.next().unwrap(), words.next().unwrap(), words.next());
4acdad1942 2020-11-26 310: let ok_link = RE_LINK.is_match(&url);
4acdad1942 2020-11-26 311: let ok_hash = match iv_hash {
4acdad1942 2020-11-26 312: Some(hash) => RE_IV_HASH.is_match(&hash),
4acdad1942 2020-11-26 313: None => true,
4acdad1942 2020-11-26 314: };
4acdad1942 2020-11-26 315: if ! ok_link {
4acdad1942 2020-11-26 316: reply.push("Link should be link to atom/rss feed, something like \"https://domain/path\"\\.".to_string());
4acdad1942 2020-11-26 317: core.debug(&format!("Url: {:?}", &url))?;
4acdad1942 2020-11-26 318: }
4acdad1942 2020-11-26 319: if ! ok_hash {
4acdad1942 2020-11-26 320: reply.push("IV hash should be 14 hex digits.".to_string());
4acdad1942 2020-11-26 321: core.debug(&format!("IV: {:?}", &iv_hash))?;
4acdad1942 2020-11-26 322: }
4acdad1942 2020-11-26 323: if ok_link && ok_hash {
4acdad1942 2020-11-26 324: let chan: Option<i64> = match sqlx::query("select channel_id from rsstg_channel where username = $1")
4acdad1942 2020-11-26 325: .bind(channel)
4acdad1942 2020-11-26 326: .fetch_one(&core.pool).await {
4acdad1942 2020-11-26 327: Ok(chan) => Some(chan.try_get("channel_id")?),
4acdad1942 2020-11-26 328: Err(sqlx::Error::RowNotFound) => {
4acdad1942 2020-11-26 329: let chan_id = i64::from(core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await?.id());
4acdad1942 2020-11-26 330: sqlx::query("insert into rsstg_channel (channel_id, username) values ($1, $2);")
4acdad1942 2020-11-26 331: .bind(chan_id)
4acdad1942 2020-11-26 332: .bind(channel)
4acdad1942 2020-11-26 333: .execute(&core.pool).await?;
4acdad1942 2020-11-26 334: Some(chan_id)
4acdad1942 2020-11-26 335: },
4acdad1942 2020-11-26 336: Err(err) => {
4acdad1942 2020-11-26 337: reply.push("Sorry, unknown error\\.".to_string());
4acdad1942 2020-11-26 338: core.debug(&format!("Sorry, unknown error:\n{:#?}\n", err))?;
4acdad1942 2020-11-26 339: None
4acdad1942 2020-11-26 340: },
4acdad1942 2020-11-26 341: };
4acdad1942 2020-11-26 342: if let Some(chan) = chan {
4acdad1942 2020-11-26 343: match if cmd == "/update" {
4acdad1942 2020-11-26 344: sqlx::query("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $4 where source_id = $1").bind(source_id)
4acdad1942 2020-11-26 345: } else {
4acdad1942 2020-11-26 346: sqlx::query("insert into rsstg_source (channel_id, url, iv_hash, owner) values ($1, $2, $3, $4)")
4acdad1942 2020-11-26 347: }
4acdad1942 2020-11-26 348: .bind(chan)
4acdad1942 2020-11-26 349: .bind(url)
4acdad1942 2020-11-26 350: .bind(iv_hash)
4acdad1942 2020-11-26 351: .bind(i64::from(message.from.id))
4acdad1942 2020-11-26 352: .execute(&core.pool).await {
4acdad1942 2020-11-26 353: Ok(_) => reply.push("Channel added\\.".to_string()),
4acdad1942 2020-11-26 354: Err(sqlx::Error::Database(err)) => {
4acdad1942 2020-11-26 355: match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
4acdad1942 2020-11-26 356: Some("_bt_check_unique", ) => {
4acdad1942 2020-11-26 357: reply.push("Duplicate key\\.".to_string());
4acdad1942 2020-11-26 358: },
4acdad1942 2020-11-26 359: Some(_) => {
4acdad1942 2020-11-26 360: reply.push("Database error\\.".to_string());
4acdad1942 2020-11-26 361: },
4acdad1942 2020-11-26 362: None => {
4acdad1942 2020-11-26 363: reply.push("No database error extracted\\.".to_string());
4acdad1942 2020-11-26 364: },
4acdad1942 2020-11-26 365: };
4acdad1942 2020-11-26 366: },
4acdad1942 2020-11-26 367: Err(err) => {
4acdad1942 2020-11-26 368: reply.push("Sorry, unknown error\\.".to_string());
4acdad1942 2020-11-26 369: core.debug(&format!("Sorry, unknown error:\n{:#?}\n", err))?;
4acdad1942 2020-11-26 370: },
4acdad1942 2020-11-26 371: };
4acdad1942 2020-11-26 372: };
4acdad1942 2020-11-26 373: };
4acdad1942 2020-11-26 374: },
4acdad1942 2020-11-26 375:
4acdad1942 2020-11-26 376: // addchan
4acdad1942 2020-11-26 377:
4acdad1942 2020-11-26 378: "/addchan" => {
4acdad1942 2020-11-26 379: let channel = words.next().unwrap();
4acdad1942 2020-11-26 380: if ! RE_USERNAME.is_match(&channel) {
4acdad1942 2020-11-26 381: reply.push("Usernames should be something like \"@\\[a\\-zA\\-Z]\\[a\\-zA\\-Z0\\-9\\_]+\", aren't they?".to_string());
4acdad1942 2020-11-26 382: } else {
4acdad1942 2020-11-26 383: let chan: Option<i64> = match sqlx::query("select channel_id from rsstg_channel where username = $1")
4acdad1942 2020-11-26 384: .bind(channel)
4acdad1942 2020-11-26 385: .fetch_one(&core.pool).await {
4acdad1942 2020-11-26 386: Ok(chan) => Some(chan.try_get("channel_id")?),
4acdad1942 2020-11-26 387: Err(sqlx::Error::RowNotFound) => None,
4acdad1942 2020-11-26 388: Err(err) => {
4acdad1942 2020-11-26 389: reply.push("Sorry, unknown error\\.".to_string());
4acdad1942 2020-11-26 390: core.debug(&format!("Sorry, unknown error:\n{:#?}", err))?;
4acdad1942 2020-11-26 391: None
4acdad1942 2020-11-26 392: },
4acdad1942 2020-11-26 393: };
4acdad1942 2020-11-26 394: match chan {
4acdad1942 2020-11-26 395: Some(chan) => {
4acdad1942 2020-11-26 396: let new_chan = core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatId::new(chan))).await?;
4acdad1942 2020-11-26 397: if i64::from(new_chan.id()) == chan {
4acdad1942 2020-11-26 398: reply.push("I already know that channel\\.".to_string());
4acdad1942 2020-11-26 399: } else {
4acdad1942 2020-11-26 400: reply.push("Hmm, channel has changed⦠I'll fix it later\\.".to_string());
4acdad1942 2020-11-26 401: };
4acdad1942 2020-11-26 402: },
4acdad1942 2020-11-26 403: None => {
4acdad1942 2020-11-26 404: match core.tg.send(telegram_bot::GetChatAdministrators::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await {
4acdad1942 2020-11-26 405: Ok(chan_adm) => {
4acdad1942 2020-11-26 406: let (mut me, mut user) = (false, false);
4acdad1942 2020-11-26 407: for admin in &chan_adm {
4acdad1942 2020-11-26 408: if admin.user.id == core.my.id {
4acdad1942 2020-11-26 409: me = true;
4acdad1942 2020-11-26 410: };
4acdad1942 2020-11-26 411: if admin.user.id == message.from.id {
4acdad1942 2020-11-26 412: user = true;
4acdad1942 2020-11-26 413: };
4acdad1942 2020-11-26 414: };
4acdad1942 2020-11-26 415: if ! me { reply.push("I need to be admin on that channel\\.".to_string()); };
4acdad1942 2020-11-26 416: if ! user { reply.push("You should be admin on that channel\\.".to_string()); };
4acdad1942 2020-11-26 417: if me && user {
4acdad1942 2020-11-26 418: let chan_id = core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await?;
4acdad1942 2020-11-26 419: sqlx::query("insert into rsstg_channel (channel_id, username) values ($1, $2);")
4acdad1942 2020-11-26 420: .bind(i64::from(chan_id.id()))
4acdad1942 2020-11-26 421: .bind(channel)
4acdad1942 2020-11-26 422: .execute(&core.pool).await?;
4acdad1942 2020-11-26 423: reply.push("Good, I know that channel now\\.\n".to_string());
4acdad1942 2020-11-26 424: };
4acdad1942 2020-11-26 425: },
4acdad1942 2020-11-26 426: Err(_) => {
4acdad1942 2020-11-26 427: reply.push("Sorry, I have no access to that chat\\.".to_string());
4acdad1942 2020-11-26 428: },
4acdad1942 2020-11-26 429: };
4acdad1942 2020-11-26 430: },
4acdad1942 2020-11-26 431: };
4acdad1942 2020-11-26 432: };
4acdad1942 2020-11-26 433: },
4acdad1942 2020-11-26 434:
4acdad1942 2020-11-26 435: // check
4acdad1942 2020-11-26 436:
4acdad1942 2020-11-26 437: "/check" => {
4acdad1942 2020-11-26 438: match &words.next().unwrap().parse::<i32>() {
4acdad1942 2020-11-26 439: Err(err) => {
4acdad1942 2020-11-26 440: reply.push(format!("I need a number\\.\n{}", &err));
4acdad1942 2020-11-26 441: },
4acdad1942 2020-11-26 442: Ok(number) => {
ebe7c281a5 2020-11-27 443: core.check(&number, message.from.id, false).await
ebe7c281a5 2020-11-27 444: .context("π Channel check failed.")?;
4acdad1942 2020-11-26 445: },
4acdad1942 2020-11-26 446: };
4acdad1942 2020-11-26 447: },
4acdad1942 2020-11-26 448:
4acdad1942 2020-11-26 449: // clean
4acdad1942 2020-11-26 450:
4acdad1942 2020-11-26 451: "/clean" => {
ebe7c281a5 2020-11-27 452: match &words.next().unwrap().parse::<i32>() {
ebe7c281a5 2020-11-27 453: Err(err) => {
ebe7c281a5 2020-11-27 454: reply.push(format!("I need a number\\.\n{}", &err));
ebe7c281a5 2020-11-27 455: },
ebe7c281a5 2020-11-27 456: Ok(number) => {
ebe7c281a5 2020-11-27 457: let result = core.clean(&number, message.from.id).await?;
ebe7c281a5 2020-11-27 458: reply.push(result.to_string());
ebe7c281a5 2020-11-27 459: },
ebe7c281a5 2020-11-27 460: };
4acdad1942 2020-11-26 461: },
4acdad1942 2020-11-26 462:
4acdad1942 2020-11-26 463: // enable
4acdad1942 2020-11-26 464:
4acdad1942 2020-11-26 465: "/enable" => {
4acdad1942 2020-11-26 466: match &words.next().unwrap().parse::<i32>() {
4acdad1942 2020-11-26 467: Err(err) => {
4acdad1942 2020-11-26 468: reply.push(format!("I need a number\\.\n{}", &err));
4acdad1942 2020-11-26 469: },
4acdad1942 2020-11-26 470: Ok(number) => {
4acdad1942 2020-11-26 471: let result = core.enable(&number, message.from.id).await?;
4acdad1942 2020-11-26 472: reply.push(result.to_string());
4acdad1942 2020-11-26 473: },
4acdad1942 2020-11-26 474: };
4acdad1942 2020-11-26 475: },
4acdad1942 2020-11-26 476:
4acdad1942 2020-11-26 477: // disable
4acdad1942 2020-11-26 478:
4acdad1942 2020-11-26 479: "/disable" => {
4acdad1942 2020-11-26 480: match &words.next().unwrap().parse::<i32>() {
4acdad1942 2020-11-26 481: Err(err) => {
4acdad1942 2020-11-26 482: reply.push(format!("I need a number\\.\n{}", &err));
4acdad1942 2020-11-26 483: },
4acdad1942 2020-11-26 484: Ok(number) => {
4acdad1942 2020-11-26 485: let result = core.disable(&number, message.from.id).await?;
4acdad1942 2020-11-26 486: reply.push(result.to_string());
4acdad1942 2020-11-26 487: },
4acdad1942 2020-11-26 488: };
4acdad1942 2020-11-26 489: },
4acdad1942 2020-11-26 490:
4acdad1942 2020-11-26 491: _ => {
4acdad1942 2020-11-26 492: },
4acdad1942 2020-11-26 493: };
4acdad1942 2020-11-26 494: },
4acdad1942 2020-11-26 495: _ => {
4acdad1942 2020-11-26 496: },
4acdad1942 2020-11-26 497: };
4acdad1942 2020-11-26 498:
4acdad1942 2020-11-26 499: if reply.len() > 0 {
423cadd9c7 2020-11-27 500: if let Err(err) = core.tg.send(message.text_reply(reply.join("\n")).parse_mode(types::ParseMode::MarkdownV2)).await {
423cadd9c7 2020-11-27 501: dbg!(reply.join("\n"));
423cadd9c7 2020-11-27 502: println!("{}", err);
423cadd9c7 2020-11-27 503: };
423cadd9c7 2020-11-27 504: };
4acdad1942 2020-11-26 505: },
4acdad1942 2020-11-26 506: _ => {},
4acdad1942 2020-11-26 507: };
61df933942 2020-11-18 508:
61df933942 2020-11-18 509: Ok(())
61df933942 2020-11-18 510: }