1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
use anyhow::{anyhow, bail, Context, Result};
use async_std::task;
use chrono::DateTime;
use sqlx::postgres::PgPoolOptions;
use std::{
borrow::Cow,
collections::{
BTreeMap,
HashSet,
},
sync::{Arc, Mutex},
};
#[derive(Clone)]
pub struct Core {
owner_chat: telegram_bot::UserId,
pub tg: telegram_bot::Api,
pub my: telegram_bot::User,
pool: sqlx::Pool<sqlx::Postgres>,
|
>
>
>
>
>
>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
use anyhow::{anyhow, bail, Context, Result};
use async_std::task;
use chrono::DateTime;
use lazy_static::lazy_static;
use regex::Regex;
use sqlx::postgres::PgPoolOptions;
use std::{
borrow::Cow,
collections::{
BTreeMap,
HashSet,
},
sync::{Arc, Mutex},
};
lazy_static! {
static ref RE_DELAY: Regex = Regex::new(r"^Too Many Requests: retry after ([0-9]+)(,.*)?$").unwrap();
}
#[derive(Clone)]
pub struct Core {
owner_chat: telegram_bot::UserId,
pub tg: telegram_bot::Api,
pub my: telegram_bot::User,
pool: sqlx::Pool<sqlx::Postgres>,
|
︙ | | | ︙ | |
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
self.tg.stream()
}
pub async fn send<'a, S>(&self, msg: S, target: Option<telegram_bot::UserId>, mode: Option<telegram_bot::types::ParseMode>) -> Result<()>
where S: Into<Cow<'a, str>> {
let mode = mode.unwrap_or(telegram_bot::types::ParseMode::Html);
let target = target.unwrap_or(self.owner_chat);
self.tg.send(telegram_bot::SendMessage::new(target, msg).parse_mode(mode)).await?;
Ok(())
}
pub async fn check<S>(&self, id: &i32, owner: S, real: bool) -> Result<Cow<'_, str>>
where S: Into<i64> {
let owner = owner.into();
let mut posted: i32 = 0;
let id = {
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
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
|
self.tg.stream()
}
pub async fn send<'a, S>(&self, msg: S, target: Option<telegram_bot::UserId>, mode: Option<telegram_bot::types::ParseMode>) -> Result<()>
where S: Into<Cow<'a, str>> {
let mode = mode.unwrap_or(telegram_bot::types::ParseMode::Html);
let target = target.unwrap_or(self.owner_chat);
self.request(telegram_bot::SendMessage::new(target, msg).parse_mode(mode)).await?;
Ok(())
}
pub async fn request<Req: telegram_bot::Request> (&self, req: Req) -> Result<<Req::Response as telegram_bot::ResponseType>::Type> {
loop {
let res = self.tg.send(&req).await;
match res {
Ok(_) => return Ok(res?),
Err(err) => {
dbg!(&err);
if let Some(caps) = RE_DELAY.captures(err.to_string().as_ref()) {
if let Some(delay) = caps.get(1) {
let delay = delay.as_str().parse::<u64>()?;
println!("Throttled, waiting {} senconds.", delay);
task::sleep(std::time::Duration::from_secs(delay)).await;
} else {
bail!("Can't read throttling message.");
}
} else {
return Err(err.into());
}
},
};
}
}
pub async fn check<S>(&self, id: &i32, owner: S, real: bool) -> Result<Cow<'_, str>>
where S: Into<i64> {
let owner = owner.into();
let mut posted: i32 = 0;
let id = {
|
︙ | | | ︙ | |
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
|
};
if let Some(exists) = sqlx::query!("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;",
&post_url, *id).fetch_one(&mut self.pool.acquire().await?).await?.exists {
if ! exists {
if this_fetch.is_none() || *date > this_fetch.unwrap() {
this_fetch = Some(*date);
};
self.tg.send( match &source.iv_hash {
Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", &post_url, hash)),
None => telegram_bot::SendMessage::new(destination, format!("{}", post_url)),
}.parse_mode(telegram_bot::types::ParseMode::Html)).await
.context("Can't post message:")?;
sqlx::query!("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);",
*id, date, &post_url).execute(&mut self.pool.acquire().await?).await?;
task::sleep(std::time::Duration::new(4, 0)).await;
};
};
posted += 1;
};
posts.clear();
};
sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
|
|
<
|
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
|
};
if let Some(exists) = sqlx::query!("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;",
&post_url, *id).fetch_one(&mut self.pool.acquire().await?).await?.exists {
if ! exists {
if this_fetch.is_none() || *date > this_fetch.unwrap() {
this_fetch = Some(*date);
};
self.request( match &source.iv_hash {
Some(hash) => telegram_bot::SendMessage::new(destination, format!("<a href=\"https://t.me/iv?url={}&rhash={}\"> </a>{0}", &post_url, hash)),
None => telegram_bot::SendMessage::new(destination, format!("{}", post_url)),
}.parse_mode(telegram_bot::types::ParseMode::Html)).await
.context("Can't post message:")?;
sqlx::query!("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);",
*id, date, &post_url).execute(&mut self.pool.acquire().await?).await?;
};
};
posted += 1;
};
posts.clear();
};
sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
|
︙ | | | ︙ | |
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
|
let clone = Core {
owner_chat: telegram_bot::UserId::new(owner),
..self.clone()
};
task::spawn(async move {
if let Err(err) = clone.check(&source_id, owner, true).await {
if let Err(err) = clone.send(&format!("š {:?}", err), None, None).await {
eprintln!("Check error: {}", err);
clone.disable(&source_id, owner).await.unwrap();
};
};
});
}
} else if next_fetch - now < delay {
delay = next_fetch - now;
}
}
};
queue.clear();
Ok(delay.to_std()?)
}
pub async fn list<S>(&self, owner: S) -> Result<String>
where S: Into<i64> {
let owner = owner.into();
let mut reply: Vec<Cow<str>> = vec![];
reply.push("Channels:".into());
let rows = sqlx::query!("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id",
owner).fetch_all(&mut self.pool.acquire().await?).await?;
for row in rows.iter() {
reply.push(format!("\n\\#ļøā£ {} \\*ļøā£ `{}` {}\nš `{}`", row.source_id, row.channel,
match row.enabled {
true => "š enabled",
false => "ā disabled",
}, row.url).into());
if let Some(hash) = &row.iv_hash {
reply.push(format!("IV: `{}`", hash).into());
}
|
|
|
|
|
|
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
|
let clone = Core {
owner_chat: telegram_bot::UserId::new(owner),
..self.clone()
};
task::spawn(async move {
if let Err(err) = clone.check(&source_id, owner, true).await {
if let Err(err) = clone.send(&format!("š {:?}", err), None, None).await {
dbg!("Check error: {}", err);
// clone.disable(&source_id, owner).await.unwrap();
};
};
});
}
} else if next_fetch - now < delay {
delay = next_fetch - now;
}
}
};
queue.clear();
Ok(delay.to_std()?)
}
pub async fn list<S>(&self, owner: S) -> Result<String>
where S: Into<i64> {
let owner = owner.into();
let mut reply: Vec<Cow<str>> = vec![];
reply.push("Channels:".into());
let rows = sqlx::query!("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id",
owner).fetch_all(&mut *self.pool.acquire().await?).await?;
for row in rows.iter() {
reply.push(format!("\n\\#ļøā£ {} \\*ļøā£ `{}` {}\nš `{}`", row.source_id, row.channel,
match row.enabled {
true => "š enabled",
false => "ā disabled",
}, row.url).into());
if let Some(hash) = &row.iv_hash {
reply.push(format!("IV: `{}`", hash).into());
}
|
︙ | | | ︙ | |