Overview
Comment: | 0.1.6: switch to connection acquiring, expand error messages |
---|---|
Downloads: | Tarball | ZIP archive | SQL archive |
Timelines: | family | ancestors | descendants | both | trunk |
Files: | files | file ages | folders |
SHA3-256: |
3d3fde1b28faf7cedb93c7905ad150ad |
User & Date: | arcade on 2020-11-25 16:57:46.192 |
Other Links: | manifest | tags |
Context
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 | |
2020-11-24
| ||
09:41 | add start message check-in: 8db3dfecf8 user: arcade tags: trunk | |
Changes
Modified Cargo.toml
from [32385ff949]
to [1227a57894].
1 2 | [package] name = "rsstg" | | | 1 2 3 4 5 6 7 8 9 10 | [package] name = "rsstg" version = "0.1.6" authors = ["arcade"] edition = "2018" [dependencies] config = "*" futures = "*" |
︙ | ︙ |
Modified src/main.rs
from [69a051652f]
to [75f4088805].
︙ | ︙ | |||
33 34 35 36 37 38 39 | let tg = Api::new(&api_key); let core = Core { owner: owner, api_key: api_key.clone(), my: tg.send(telegram_bot::GetMe).await?, tg: tg, owner_chat: UserId::new(owner), | | > > > > > | > > > > > | | | > > > | > | | | | | | | | | | > > > | | | | | | | | | | > > > > > | | | | > > > | | | | | | | | | | > > > | | | | | | | | | | | | < < < | > | | | < < | > | > > > | < | | | < > | | | < | | | > | | < < > > > > > > > > | | | < | | > > > > > > > > | | | < | | | > | > > > > > > > | | | < | | | > | > > < > > > > > | | | | | | | | | | | | | | | | | | | | | | | | | | > > > < > > > > > > > > | | | | > | | | | | | | | | | | | | | | > > | 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 | let tg = Api::new(&api_key); let core = Core { owner: owner, api_key: api_key.clone(), my: tg.send(telegram_bot::GetMe).await?, tg: tg, owner_chat: UserId::new(owner), pool: PgPoolOptions::new() .max_connections(5) .connect_timeout(std::time::Duration::new(300, 0)) .idle_timeout(std::time::Duration::new(60, 0)) .connect_lazy(&settings.get_str("pg")?)?, //.connect(&settings.get_str("pg")?).await?, }; let clone = core.clone(); tokio::spawn(async move { if let Err(err) = clone.autofetch().await { eprintln!("connection error: {}", err); } }); Ok(core) } fn stream(&self) -> telegram_bot::UpdatesStream { self.tg.stream() } fn debug(&self, msg: &str) -> Result<()> { self.tg.spawn(SendMessage::new(self.owner_chat, msg)); Ok(()) } async fn check(&self, id: &i32, real: bool) -> Result<()> { match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Query queue fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { match sqlx::query("select source_id, channel_id, url, iv_hash, owner from rsstg_source where source_id = $1") .bind(id) .fetch_one(&mut conn).await { Err(err) => { self.debug(&format!("π Query queue:\n{}\n{:?}", &err, &conn))?; }, Ok(row) => { drop(conn); let channel_id: i64 = row.try_get("channel_id")?; let destination = match real { true => UserId::new(channel_id), false => UserId::new(row.try_get("owner")?), }; let url: &str = row.try_get("url")?; let mut this_fetch: Option<DateTime<chrono::FixedOffset>> = None; let iv_hash: Option<&str> = row.try_get("iv_hash")?; let mut posts: BTreeMap<DateTime<chrono::FixedOffset>, String> = BTreeMap::new(); match rss::Channel::from_url(url) { Err(err) => { self.debug(&format!("π Problem opening feed url:\n{}\n{}", &url, &err))?; }, Ok(feed) => { for item in feed.items() { let date = match item.pub_date() { Some(feed_date) => DateTime::parse_from_rfc2822(feed_date), None => DateTime::parse_from_rfc3339(&item.dublin_core_ext().unwrap().dates()[0]), }?; let url = item.link().unwrap().to_string(); posts.insert(date.clone(), url.clone()); }; for (date, url) in posts.iter() { match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Check post fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { match sqlx::query("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;") .bind(&url) .bind(id) .fetch_one(&mut conn).await { Err(err) => { self.debug(&format!("π Check post:\n{}\n{:?}", &err, &conn))?; }, Ok(row) => { let exists: bool = row.try_get("exists")?; if ! exists { if this_fetch == None || *date > this_fetch.unwrap() { this_fetch = Some(*date); } match self.tg.send( match iv_hash { Some(x) => SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", url, x)), None => SendMessage::new(destination, format!("{}", url)), }.parse_mode(types::ParseMode::Html)).await { Err(err) => { self.debug(&format!("π Can't post message:\n{}", &err))?; }, Ok(_) => { match sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);") .bind(id) .bind(date) .bind(url) .execute(&mut conn).await { Ok(_) => {}, Err(err) => { self.debug(&format!("πRrecord post:\n{}\n{:?}", &err, &conn))?; }, }; }, }; drop(conn); tokio::time::delay_for(std::time::Duration::new(4, 0)).await; } }, }; } }; }; posts.clear(); }, }; match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Update scrape fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { match sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;") .bind(id) .execute(&mut conn).await { Err(err) => { self.debug(&format!("π Update scrape:\n{}\n{:?}", &err, &conn))?; }, Ok(_) => {}, }; }, }; }, }; }, }; Ok(()) } async fn clean(&self, source_id: i32) -> Result<()> { match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Clean fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { match sqlx::query("delete from rsstg_post where source_id = $1;") .bind(source_id) .execute(&mut conn).await { Err(err) => { self.debug(&format!("π Clean seen posts:\n{}\n{:?}", &err, &self.pool))?; }, Ok(_) => {}, }; }, }; Ok(()) } async fn enable(&self, source_id: &i32) -> Result<()> { match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Enable fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { match sqlx::query("update rsstg_source set enabled = true where source_id = $1") .bind(source_id) .execute(&mut conn).await { Err(err) => { self.debug(&format!("π Enable source:\n{}\n{:?}", &err, &self.pool))?; }, Ok(_) => {}, } }, }; Ok(()) } async fn disable(&self, source_id: &i32) -> Result<()> { match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Disable fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { match sqlx::query("update rsstg_source set enabled = false where source_id = $1") .bind(source_id) .execute(&mut conn).await { Err(err) => { self.debug(&format!("π Disable source:\n{}\n{:?}", &err, &self.pool))?; }, Ok(_) => {}, } }, }; Ok(()) } async fn autofetch(&self) -> Result<()> { let mut delay = chrono::Duration::minutes(5); let mut now; loop { match self.pool.acquire().await { Err(err) => { self.debug(&format!("π Autofetch fetch conn:\n{}\n{:?}", &err, &self.pool))?; }, Ok(mut conn) => { now = chrono::Local::now(); let mut queue = sqlx::query("select source_id, next_fetch from rsstg_order natural left join rsstg_source natural left join rsstg_channel where next_fetch < now();") .fetch_all(&mut conn).await?; for row in queue.iter() { let source_id: i32 = row.try_get("source_id")?; let next_fetch: DateTime<chrono::Local> = row.try_get("next_fetch")?; if next_fetch < now { match sqlx::query("update rsstg_source set last_scrape = now() + interval '1 hour' where source_id = $1;") .bind(source_id) .execute(&mut conn).await { Ok(_) => {}, Err(err) => { self.debug(&err.to_string())?; }, }; let clone = self.clone(); tokio::spawn(async move { if let Err(err) = clone.check(&source_id.clone(), true).await { eprintln!("connection error: {}", err); } }); } else { if next_fetch - now < delay { delay = next_fetch - now; } } }; queue.clear(); }, }; tokio::time::delay_for(delay.to_std()?).await; delay = chrono::Duration::minutes(5); } } } #[tokio::main] async fn main() -> Result<()> { let mut settings = config::Config::default(); settings.merge(config::File::with_name("rsstg"))?; let re_username = Regex::new(r"^@[a-zA-Z][a-zA-Z0-9_]+$")?; let re_link = Regex::new(r"^https?://[a-zA-Z.0-9-]+/[-_a-zA-Z.0-9/?=]+$")?; let re_iv_hash = Regex::new(r"^[a-f0-9]{14}$")?; let core = Core::new(settings).await?; let mut stream = core.stream(); while let Some(update) = stream.next().await { match update { Err(err) => { core.debug(&err.to_string())?; }, Ok(update) => { 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" { |
︙ | ︙ | |||
301 302 303 304 305 306 307 | Ok(chan) => Some(chan.try_get("channel_id")?), Err(sqlx::Error::RowNotFound) => { reply.push("Sorry, I don't know about that channel. Please, add a channel with /addchan.".to_string()); None }, Err(err) => { reply.push("Sorry, unknown error\\.".to_string()); | | | 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | Ok(chan) => Some(chan.try_get("channel_id")?), Err(sqlx::Error::RowNotFound) => { reply.push("Sorry, I don't know about that channel. Please, add a channel with /addchan.".to_string()); None }, 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 { |
︙ | ︙ | |||
332 333 334 335 336 337 338 | None => { reply.push("No database error extracted\\.".to_string()); }, }; }, Err(err) => { reply.push("Sorry, unknown error\\.".to_string()); | | | | 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 | 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{:#?}\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 { |
︙ | ︙ | |||
401 402 403 404 405 406 407 | }; }; }, // check "/check" => { | | > > > > > > > > > > > > > > | > > > > > | | | | | > > | > > > > > | | | | | > > | 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 | }; }; }, // 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) => { match core.enable(&number).await { Ok(_) => { reply.push("Channel enabled\\.".to_string()); } Err(err) => { core.debug(&err.to_string())?; }, }; }, }; }, // disable "/disable" => { match &words.next().unwrap().parse::<i32>() { Err(err) => { reply.push(format!("I need a number\\.\n{}", &err)); }, Ok(number) => { match core.disable(&number).await { Ok(_) => { reply.push("Channel disabled\\.".to_string()); } Err(err) => { core.debug(&err.to_string())?; }, }; }, }; }, _ => { }, }; |
︙ | ︙ | |||
462 463 464 465 466 467 468 | } } }, _ => {}, }; }, | < < < | 556 557 558 559 560 561 562 563 564 565 566 567 | } } }, _ => {}, }; }, }; } Ok(()) } |