Diff
Logged in as anonymous

Differences From Artifact [acda50f390]:

To Artifact [90bda79dca]:


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
26
27


28
29
30
31
32
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
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
26
27
28
29
30


31
32
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




-
-
-
+
+
+
+
+
+
+
+


















-
-
+
+






-
-
-
+
+
+







-
+

-
+











-
+

-
+








-
+













-
+



-
-
+
+
+
+
+
+


+






-
+

-
+



















-
+

-
+







use anyhow::{anyhow, bail, Context, Result};
use async_std::task;
use chrono::DateTime;
use sqlx::postgres::PgPoolOptions;
use telegram_bot::{
	_base::Error as TgrError,
	Error as TgError,
use teloxide::{
	Bot,
	payloads::SendMessage,
	requests::Requester,
	types::{
		Me,
		UserId,
	},
};
use thiserror::Error;

use std::{
	borrow::Cow,
	collections::{
		BTreeMap,
		HashSet,
	},
	num::TryFromIntError,
	sync::{
		Arc,
		Mutex
	},
};

#[derive(Error, Debug)]
pub enum RssError {
	#[error(transparent)]
	Tg(#[from] TgError),
	// #[error(transparent)]
	// Tg(#[from] TgError),
	#[error(transparent)]
	Int(#[from] TryFromIntError),
}

#[derive(Clone)]
pub struct Core {
	owner_chat: telegram_bot::UserId,
	pub tg: telegram_bot::Api,
	pub my: telegram_bot::User,
	owner_chat: UserId,
	pub tg: Bot,
	pub my: Me,
	pool: sqlx::Pool<sqlx::Postgres>,
	sources: Arc<Mutex<HashSet<Arc<i32>>>>,
	http_client: reqwest::Client,
}

impl Core {
	pub fn new(settings: config::Config) -> Result<Arc<Core>> {
		let owner = settings.get_int("owner")?;
		let owner: u64 = settings.get_int("owner")?.try_into()?;
		let api_key = settings.get_string("api_key")?;
		let tg = telegram_bot::Api::new(api_key);
		let tg = Bot::new(api_key);
		let tg_cloned = tg.clone();

		let mut client = reqwest::Client::builder();
		if let Ok(proxy) = settings.get_string("proxy") {
			let proxy = reqwest::Proxy::all(proxy)?;
			client = client.proxy(proxy);
		}
		let http_client = client.build()?;
		let core = Arc::new(Core {
			tg,
			my: task::block_on(async {
				tg_cloned.send(telegram_bot::GetMe).await
				tg_cloned.get_me().await
			})?,
			owner_chat: telegram_bot::UserId::new(owner),
			owner_chat: UserId(owner),
			pool: PgPoolOptions::new()
				.max_connections(5)
				.acquire_timeout(std::time::Duration::new(300, 0))
				.idle_timeout(std::time::Duration::new(60, 0))
				.connect_lazy(&settings.get_string("pg")?)?,
			sources: Arc::new(Mutex::new(HashSet::new())),
			http_client,
		});
		let clone = core.clone();
		/* let clone = core.clone();
		task::spawn(async move {
			loop {
				let delay = match &clone.autofetch().await {
					Err(err) => {
						if let Err(err) = clone.send(format!("🛑 {:?}", err), None, None).await {
							eprintln!("Autofetch error: {}", err);
						};
						std::time::Duration::from_secs(60)
					},
					Ok(time) => *time,
				};
				task::sleep(delay).await;
			}
		});
		}); */
		Ok(core)
	}

	pub fn stream(&self) -> telegram_bot::UpdatesStream {
		self.tg.stream()
	pub fn stream(&self) -> Result<()> {
		let mut last_update: Option<i32> = None;
		loop {
			let updates = self.tg.get_updates(last_update, None, 300, Some(vec!["message"]));
		}
		Ok(())
	}

	/*
	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, RssError> {
	/* pub async fn request<Req: telegram_bot::Request> (&self, req: Req) -> Result<<Req::Response as telegram_bot::ResponseType>::Type, RssError> {
		loop {
			let res = self.tg.send(&req).await;
			match res {
				Ok(_) => return Ok(res?),
				Err(err) => {
					match &err {
						TgError::Raw(TgrError::TelegramError { description: _, parameters: Some(params) }) => {
							if let Some(delay) = params.retry_after {
								println!("Throttled, waiting {} senconds.", delay);
								task::sleep(std::time::Duration::from_secs(delay.try_into()?)).await;
							} else {
								return Err(err.into());
							}
						},
						_ => return Err(err.into()),
					}
				},
			};
		}
	}
	} */

	pub async fn check<S>(&self, id: &i32, owner: S, real: bool) -> Result<Cow<'_, str>>
	/* 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 mut conn = self.pool.acquire().await?;

		let id = {
			let mut set = self.sources.lock().unwrap();
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
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







-
+

-
+








-
+

-
+








-
+

-
+









-
+

-
+









-
+

-
+







				posted += 1;
			};
			posts.clear();
		};
		sqlx::query!("update rsstg_source set last_scrape = now() where source_id = $1;",
			*id).execute(&mut *conn).await?;
		Ok(format!("Posted: {}", &posted).into())
	}
	} */

	pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
	/* pub async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
	where S: Into<i64> {
		let owner = owner.into();

		match sqlx::query!("delete from rsstg_source where source_id = $1 and owner = $2;",
			source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
			0 => { Ok("No data found found.".into()) },
			x => { Ok(format!("{} sources removed.", x).into()) },
		}
	}
	} */

	pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
	/* pub async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<Cow<'_, str>>
	where S: Into<i64> {
		let owner = owner.into();

		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;",
			source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
			0 => { Ok("No data found found.".into()) },
			x => { Ok(format!("{} posts purged.", x).into()) },
		}
	}
	} */

	pub async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
	/* pub async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
	where S: Into<i64> {
		let owner = owner.into();

		match sqlx::query!("update rsstg_source set enabled = true where source_id = $1 and owner = $2",
			source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
			1 => { Ok("Source enabled.") },
			0 => { Ok("Source not found.") },
			_ => { Err(anyhow!("Database error.")) },
		}
	}
	} */

	pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
	/* pub async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
	where S: Into<i64> {
		let owner = owner.into();

		match sqlx::query!("update rsstg_source set enabled = false where source_id = $1 and owner = $2",
			source_id, owner).execute(&mut *self.pool.acquire().await?).await?.rows_affected() {
			1 => { Ok("Source disabled.") },
			0 => { Ok("Source not found.") },
			_ => { Err(anyhow!("Database error.")) },
		}
	}
	} */

	pub async fn update<S>(&self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: S) -> Result<&str>
	/* pub async fn update<S>(&self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: S) -> Result<&str>
	where S: Into<i64> {
		let owner = owner.into();
		let mut conn = self.pool.acquire().await?;

		match match update {
				Some(id) => {
					sqlx::query!("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $5, channel = $6, url_re = $7 where source_id = $1",
343
344
345
346
347
348
349
350

351
353
354
355
356
357
358
359

360
361







-
+

				reply.push(format!("IV: `{}`", hash).into());
			}
			if let Some(re) = &row.url_re {
				reply.push(format!("RE: `{}`", re).into());
			}
		};
		Ok(reply.join("\n"))
	}
	} */
}