Overview
Comment: | 0.1.7: I'm getting better at error handling + owner checks to enable/disable |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | trunk |
Files: | files | file ages | folders |
SHA3-256: |
4acdad19422d8b461458c3affdf624d2 |
User & Date: | arcade on 2020-11-26 21:02:56.696 |
Other Links: | manifest | tags |
Context
2020-11-27
| ||
07:18 | 0.1.8: rewrite error handling check-in: 423cadd9c7 user: arcade tags: trunk | |
2020-11-26
| ||
21:02 | 0.1.7: I'm getting better at error handling + owner checks to enable/disable check-in: 4acdad1942 user: arcade tags: trunk | |
2020-11-25
| ||
16:57 | 0.1.6: switch to connection acquiring, expand error messages check-in: 3d3fde1b28 user: arcade tags: trunk | |
Changes
Modified Cargo.toml
from [1227a57894]
to [baf3cf09dc].
1 2 | [package] name = "rsstg" | | > < > > > > < < < < | < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [package] name = "rsstg" version = "0.1.7" authors = ["arcade"] edition = "2018" [dependencies] chrono = "*" config = "*" futures = "*" futures-util = "*" regex = "*" rss = { version = "*", features = [ "from_url" ] } sqlx = { version = "*", features = [ "postgres", "tls", "runtime-async-std-native-tls", "chrono" ] } telegram-bot = "*" tokio = { version = "0.2", features = ["macros" ] } lazy_static = "*" anyhow = "*" [profile.release] lto = true codegen-units = 1 |
Modified src/main.rs
from [75f4088805]
to [360195a8e3].
︙ | ︙ | |||
9 10 11 12 13 14 15 16 | use regex::Regex; use tokio::stream::StreamExt; use telegram_bot::*; use sqlx::postgres::PgPoolOptions; use sqlx::Row; | > > > > > > | | 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | use regex::Regex; use tokio::stream::StreamExt; use telegram_bot::*; use sqlx::postgres::PgPoolOptions; use sqlx::Row; use sqlx::Done; #[macro_use] extern crate lazy_static; use anyhow::{anyhow, Context, Result}; //type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[derive(Clone)] struct Core { owner: i64, api_key: String, owner_chat: UserId, tg: telegram_bot::Api, |
︙ | ︙ | |||
185 186 187 188 189 190 191 | Ok(_) => {}, }; }, }; Ok(()) } | | | < | < < | | > | < | > | | > | < < < | | < | < < | | > | < | > | | > | < < < | 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | Ok(_) => {}, }; }, }; Ok(()) } async fn enable(&self, source_id: &i32, id: telegram_bot::UserId) -> Result<&str> { let mut conn = self.pool.acquire().await .with_context(|| format!("π Enable fetch conn:\n{:?}", &self.pool))?; match sqlx::query("update rsstg_source set enabled = true where source_id = $1 and owner = $2") .bind(source_id) .bind(i64::from(id)) .execute(&mut conn).await .with_context(|| format!("π Enable source:\n\n{:?}", &self.pool))? .rows_affected() { 1 => { Ok("Source disabled\\.") }, 0 => { Ok("Source not found\\.") }, _ => { Err(anyhow!("Database error.")) }, } } async fn disable(&self, source_id: &i32, id: telegram_bot::UserId) -> Result<&str> { let mut conn = self.pool.acquire().await .with_context(|| format!("π Disable fetch conn:\n{:?}", &self.pool))?; match sqlx::query("update rsstg_source set enabled = false where source_id = $1 and owner = $2") .bind(source_id) .bind(i64::from(id)) .execute(&mut conn).await .with_context(|| format!("π Disable source:\n\n{:?}", &self.pool))? .rows_affected() { 1 => { Ok("Source disabled\\.") }, 0 => { Ok("Source not found\\.") }, _ => { Err(anyhow!("Database error.")) }, } } async fn autofetch(&self) -> Result<()> { let mut delay = chrono::Duration::minutes(5); let mut now; loop { match self.pool.acquire().await { |
︙ | ︙ | |||
274 275 276 277 278 279 280 | } #[tokio::main] async fn main() -> Result<()> { let mut settings = config::Config::default(); settings.merge(config::File::with_name("rsstg"))?; | < < < < | > > | > | > > > > > > > > > > | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | > > | > > | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | < < < < | < < | | | | | | | | | | | < < < < | | | | < < | | | | | | | > | | | | | | | | | | | | < < < < | 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | } #[tokio::main] async fn main() -> Result<()> { let mut settings = config::Config::default(); settings.merge(config::File::with_name("rsstg"))?; let core = Core::new(settings).await?; let mut stream = core.stream(); while let Some(update) = stream.next().await { match handle(update?, &core).await { Ok(_) => {}, Err(err) => { core.debug(&err.to_string())?; } }; } Ok(()) } async fn handle(update: telegram_bot::Update, core: &Core) -> Result<()> { lazy_static! { static ref RE_USERNAME: Regex = Regex::new(r"^@[a-zA-Z][a-zA-Z0-9_]+$").unwrap(); static ref RE_LINK: Regex = Regex::new(r"^https?://[a-zA-Z.0-9-]+/[-_a-zA-Z.0-9/?=]+$").unwrap(); static ref RE_IV_HASH: Regex = Regex::new(r"^[a-f0-9]{14}$").unwrap(); } match update.kind { UpdateKind::Message(message) => { let mut reply: Vec<String> = vec![]; match message.kind { MessageKind::Text { ref data, .. } => { let mut words = data.split_whitespace(); let cmd = words.next().unwrap(); match cmd { // start "/start" => { reply.push("We are open\\. Probably\\. Visit [channel](https://t.me/rsstg_bot_help/3) for details\\.".to_string()); }, // list "/list" => { match core.pool.acquire().await { Err(err) => { core.debug(&format!("π Disable fetch conn:\n{}\n{:?}", &err, &core.pool))?; }, Ok(mut conn) => { reply.push("Channels:".to_string()); 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") .bind(i64::from(message.from.id)) .fetch_all(&mut conn).await?; for row in rows.iter() { //while let Some(row) = rows.try_next().await? { let source_id: i32 = row.try_get("source_id")?; let username: &str = row.try_get("username")?; let enabled: bool = row.try_get("enabled")?; let url: &str = row.try_get("url")?; let iv_hash: Option<&str> = row.try_get("iv_hash")?; reply.push(format!("\n\\#οΈβ£ {} \\*οΈβ£ `{}` {}\nπ `{}`", source_id, username, match enabled { true => "π enabled", false => "β disabled", }, url)); if let Some(hash) = iv_hash { reply.push(format!("IV `{}`", hash)); } } }, }; }, // add "/add" | "/update" => { let mut source_id: i32 = 0; if cmd == "/update" { source_id = words.next().unwrap().parse::<i32>()?; } let (channel, url, iv_hash) = (words.next().unwrap(), words.next().unwrap(), words.next()); let ok_link = RE_LINK.is_match(&url); let ok_hash = match iv_hash { Some(hash) => RE_IV_HASH.is_match(&hash), None => true, }; if ! ok_link { reply.push("Link should be link to atom/rss feed, something like \"https://domain/path\"\\.".to_string()); core.debug(&format!("Url: {:?}", &url))?; } if ! ok_hash { reply.push("IV hash should be 14 hex digits.".to_string()); core.debug(&format!("IV: {:?}", &iv_hash))?; } if ok_link && ok_hash { let chan: Option<i64> = match sqlx::query("select channel_id from rsstg_channel where username = $1") .bind(channel) .fetch_one(&core.pool).await { Ok(chan) => Some(chan.try_get("channel_id")?), Err(sqlx::Error::RowNotFound) => { let chan_id = i64::from(core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await?.id()); sqlx::query("insert into rsstg_channel (channel_id, username) values ($1, $2);") .bind(chan_id) .bind(channel) .execute(&core.pool).await?; Some(chan_id) }, Err(err) => { reply.push("Sorry, unknown error\\.".to_string()); core.debug(&format!("Sorry, unknown error:\n{:#?}\n", err))?; None }, }; if let Some(chan) = chan { match if cmd == "/update" { sqlx::query("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $4 where source_id = $1").bind(source_id) } else { sqlx::query("insert into rsstg_source (channel_id, url, iv_hash, owner) values ($1, $2, $3, $4)") } .bind(chan) .bind(url) .bind(iv_hash) .bind(i64::from(message.from.id)) .execute(&core.pool).await { Ok(_) => reply.push("Channel added\\.".to_string()), Err(sqlx::Error::Database(err)) => { match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() { Some("_bt_check_unique", ) => { reply.push("Duplicate key\\.".to_string()); }, Some(_) => { reply.push("Database error\\.".to_string()); }, None => { reply.push("No database error extracted\\.".to_string()); }, }; }, Err(err) => { reply.push("Sorry, unknown error\\.".to_string()); core.debug(&format!("Sorry, unknown error:\n{:#?}\n", err))?; }, }; }; }; }, // addchan "/addchan" => { let channel = words.next().unwrap(); if ! RE_USERNAME.is_match(&channel) { reply.push("Usernames should be something like \"@\\[a\\-zA\\-Z]\\[a\\-zA\\-Z0\\-9\\_]+\", aren't they?".to_string()); } else { let chan: Option<i64> = match sqlx::query("select channel_id from rsstg_channel where username = $1") .bind(channel) .fetch_one(&core.pool).await { Ok(chan) => Some(chan.try_get("channel_id")?), Err(sqlx::Error::RowNotFound) => None, Err(err) => { reply.push("Sorry, unknown error\\.".to_string()); core.debug(&format!("Sorry, unknown error:\n{:#?}", err))?; None }, }; match chan { Some(chan) => { let new_chan = core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatId::new(chan))).await?; if i64::from(new_chan.id()) == chan { reply.push("I already know that channel\\.".to_string()); } else { reply.push("Hmm, channel has changedβ¦ I'll fix it later\\.".to_string()); }; }, None => { match core.tg.send(telegram_bot::GetChatAdministrators::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await { Ok(chan_adm) => { let (mut me, mut user) = (false, false); for admin in &chan_adm { if admin.user.id == core.my.id { me = true; }; if admin.user.id == message.from.id { user = true; }; }; if ! me { reply.push("I need to be admin on that channel\\.".to_string()); }; if ! user { reply.push("You should be admin on that channel\\.".to_string()); }; if me && user { let chan_id = core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await?; sqlx::query("insert into rsstg_channel (channel_id, username) values ($1, $2);") .bind(i64::from(chan_id.id())) .bind(channel) .execute(&core.pool).await?; reply.push("Good, I know that channel now\\.\n".to_string()); }; }, Err(_) => { reply.push("Sorry, I have no access to that chat\\.".to_string()); }, }; }, }; }; }, // check "/check" => { match &words.next().unwrap().parse::<i32>() { Err(err) => { reply.push(format!("I need a number\\.\n{}", &err)); }, Ok(number) => { match &core.check(number, false).await { Ok(_) => { reply.push("Channel enabled\\.".to_string()); } Err(err) => { core.debug(&format!("π Channel check failed:\n{}", &err))?; }, }; }, }; }, // clean "/clean" => { if core.owner != i64::from(message.from.id) { reply.push("Reserved for testing\\.".to_string()); } else { let source_id = words.next().unwrap().parse::<i32>().unwrap_or(0); &core.clean(source_id).await?; } }, // enable "/enable" => { match &words.next().unwrap().parse::<i32>() { Err(err) => { reply.push(format!("I need a number\\.\n{}", &err)); }, Ok(number) => { let result = core.enable(&number, message.from.id).await?; reply.push(result.to_string()); }, }; }, // disable "/disable" => { match &words.next().unwrap().parse::<i32>() { Err(err) => { reply.push(format!("I need a number\\.\n{}", &err)); }, Ok(number) => { let result = core.disable(&number, message.from.id).await?; reply.push(result.to_string()); }, }; }, _ => { }, }; }, _ => { }, }; if reply.len() > 0 { match core.tg.send(message.text_reply(reply.join("\n")).parse_mode(types::ParseMode::MarkdownV2)).await { Ok(_) => {}, Err(err) => { dbg!(reply.join("\n")); println!("{}", err); }, } } }, _ => {}, }; Ok(()) } |