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