Diff
Logged in as anonymous

Differences From Artifact [ee7367a2d2]:

To Artifact [aa11d5be5f]:


16
17
18
19
20
21
22
23

24
25
26
27
28
29
30
16
17
18
19
20
21
22

23
24
25
26
27
28
29
30







-
+







use sqlx::postgres::PgPoolOptions;
use sqlx::Row;
use sqlx::Done; // .rows_affected()

#[macro_use]
extern crate lazy_static;

use anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, bail, Context, Result};

#[derive(Clone)]
struct Core {
	owner: i64,
	api_key: String,
	owner_chat: UserId,
	tg: telegram_bot::Api,
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
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







-
+




















-
+




-
+











-
+










-
+




-
+









-
+





-
+






-
+



-
+



+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+

-
+

-
+


-
+

-
+






-
+

-
+

-
+


-
+

-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







-
+

-
+

-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







-
+

-
+









-
+



-
+
















-
-
+
+
+


-
+

-
-
+
+



-
+







				.connect_timeout(std::time::Duration::new(300, 0))
				.idle_timeout(std::time::Duration::new(60, 0))
				.connect_lazy(&settings.get_str("pg")?)?,
		};
		let clone = core.clone();
		tokio::spawn(async move {
			if let Err(err) = &clone.autofetch().await {
				if let Err(err) = clone.debug(&format!("{:?}", err)) {
				if let Err(err) = clone.debug(&format!("πŸ›‘ {:?}", err)) {
					eprintln!("Autofetch 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<S>(&self, id: &i32, owner: S, real: bool) -> Result<()>
	where S: Into<i64> {
		let owner: i64 = owner.into();
		let mut conn = self.pool.acquire().await
			.with_context(|| format!("πŸ›‘ Query queue fetch conn:\n{:?}", &self.pool))?;
			.with_context(|| format!("Query queue fetch conn:\n{:?}", &self.pool))?;
		let row = sqlx::query("select source_id, channel_id, url, iv_hash, owner from rsstg_source where source_id = $1 and owner = $2")
			.bind(id)
			.bind(owner)
			.fetch_one(&mut conn).await
			.with_context(|| format!("πŸ›‘ Query source:\n{:?}", &self.pool))?;
			.with_context(|| format!("Query source:\n{:?}", &self.pool))?;
		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();
		let feed = rss::Channel::from_url(url)
			.with_context(|| format!("πŸ›‘ Problem opening feed url:\n{}", &url))?;
			.with_context(|| format!("Problem opening feed url:\n{}", &url))?;
		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() {
			let mut conn = self.pool.acquire().await
				.with_context(|| format!("πŸ›‘ Check post fetch conn:\n{:?}", &self.pool))?;
				.with_context(|| format!("Check post fetch conn:\n{:?}", &self.pool))?;
			let row = 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
				.with_context(|| format!("πŸ›‘ Check post:\n{:?}", &conn))?;
				.with_context(|| format!("Check post:\n{:?}", &conn))?;
			let exists: bool = row.try_get("exists")?;
			if ! exists {
				if this_fetch == None || *date > this_fetch.unwrap() {
					this_fetch = Some(*date);
				};
				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
					.context("πŸ›‘ Can't post message:")?;
					.context("Can't post message:")?;
				sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);")
					.bind(id)
					.bind(date)
					.bind(url)
					.execute(&mut conn).await
					.with_context(|| format!("πŸ›‘Record post:\n{:?}", &conn))?;
					.with_context(|| format!("Record post:\n{:?}", &conn))?;
				drop(conn);
				tokio::time::delay_for(std::time::Duration::new(4, 0)).await;
			};
		};
		posts.clear();
		let mut conn = self.pool.acquire().await
			.with_context(|| format!("πŸ›‘ Update scrape fetch conn:\n{:?}", &self.pool))?;
			.with_context(|| format!("Update scrape fetch conn:\n{:?}", &self.pool))?;
		sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
			.bind(id)
			.execute(&mut conn).await
			.with_context(|| format!("πŸ›‘ Update scrape:\n{:?}", &conn))?;
			.with_context(|| format!("Update scrape:\n{:?}", &conn))?;
		Ok(())
	}

	async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<String>
	where S: Into<i64> {
		let owner: i64 = owner.into();
		let mut conn = self.pool.acquire().await
			.with_context(|| format!("Delete fetch conn:\n{:?}", &self.pool))?;
		match sqlx::query("delete from rsstg_source where source_id = $1 and owner = $2;")
			.bind(source_id)
			.bind(owner)
			.execute(&mut conn).await
			.with_context(|| format!("Delete source rule:\n{:?}", &self.pool))?
			.rows_affected() {
			0 => { Ok("No data found found\\.".to_string()) },
			x => { Ok(format!("{} sources removed\\.", x)) },
		}
	}

	async fn clean<S>(&self, source_id: &i32, id: S) -> Result<String>
	async fn clean<S>(&self, source_id: &i32, owner: S) -> Result<String>
	where S: Into<i64> {
		let id: i64 = id.into();
		let owner: i64 = owner.into();
		let mut conn = self.pool.acquire().await
			.with_context(|| format!("πŸ›‘ Clean fetch conn:\n{:?}", &self.pool))?;
			.with_context(|| format!("Clean fetch conn:\n{:?}", &self.pool))?;
		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;")
			.bind(source_id)
			.bind(id)
			.bind(owner)
			.execute(&mut conn).await
			.with_context(|| format!("πŸ›‘ Clean seen posts:\n{:?}", &self.pool))?
			.with_context(|| format!("Clean seen posts:\n{:?}", &self.pool))?
			.rows_affected() {
			0 => { Ok("No data found found\\.".to_string()) },
			x => { Ok(format!("{} posts purged\\.", x)) },
		}
	}

	async fn enable<S>(&self, source_id: &i32, id: S) -> Result<&str>
	async fn enable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
	where S: Into<i64> {
		let id: i64 = id.into();
		let owner: i64 = owner.into();
		let mut conn = self.pool.acquire().await
			.with_context(|| format!("πŸ›‘ Enable fetch conn:\n{:?}", &self.pool))?;
			.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(id)
			.bind(owner)
			.execute(&mut conn).await
			.with_context(|| format!("πŸ›‘ Enable source:\n{:?}", &self.pool))?
			.with_context(|| format!("Enable source:\n{:?}", &self.pool))?
			.rows_affected() {
			1 => { Ok("Source disabled\\.") },
			0 => { Ok("Source not found\\.") },
			_ => { Err(anyhow!("Database error.")) },
		}
	}

	async fn disable<S>(&self, source_id: &i32, owner: S) -> Result<&str>
	where S: Into<i64> {
		let owner: i64 = owner.into();
		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(owner)
			.execute(&mut conn).await
			.with_context(|| format!("Disable source:\n{:?}", &self.pool))?
			.rows_affected() {
			1 => { Ok("Source disabled\\.") },
			0 => { Ok("Source not found\\.") },
			_ => { Err(anyhow!("Database error.")) },
		}
	}

	async fn disable<S>(&self, source_id: &i32, id: S) -> Result<&str>
	async fn update<S>(&self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, owner: S) -> Result<String>
	where S: Into<i64> {
		let id: i64 = id.into();
		let owner: i64 = owner.into();
		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(id)
			.execute(&mut conn).await
			.with_context(|| format!("Update fetch conn:\n{:?}", &self.pool))?;

		match match update {
				Some(id) => {
					sqlx::query("update rsstg_source set channel_id = $2, url = $3, iv_hash = $4, owner = $5, channel = $6 where source_id = $1").bind(id)
				},
				None => {
					sqlx::query("insert into rsstg_source (channel_id, url, iv_hash, owner, channel) values ($1, $2, $3, $4, $5)")
				},
			}
			.bind(channel_id)
			.bind(url)
			.bind(iv_hash)
			.bind(owner)
			.bind(channel)
			.execute(&mut conn).await {
			.with_context(|| format!("πŸ›‘ Disable source:\n{:?}", &self.pool))?
			.rows_affected() {
			1 => { Ok("Source disabled\\.") },
			0 => { Ok("Source not found\\.") },
			_ => { Err(anyhow!("Database error.")) },
		}
			Ok(_) => return Ok(String::from("Channel added\\.")),
			Err(sqlx::Error::Database(err)) => {
				match err.downcast::<sqlx::postgres::PgDatabaseError>().routine() {
					Some("_bt_check_unique", ) => {
						return Ok("Duplicate key\\.".to_string())
					},
					Some(_) => {
						return Ok("Database error\\.".to_string())
					},
					None => {
						return Ok("No database error extracted\\.".to_string())
					},
				};
			},
			Err(err) => {
				bail!("Sorry, unknown error:\n{:#?}\n", err);
			},
		};
	}

	async fn autofetch(&self) -> Result<()> {
		let mut delay = chrono::Duration::minutes(5);
		let mut now;
		loop {
			let mut conn = self.pool.acquire().await
				.with_context(|| format!("πŸ›‘ Autofetch fetch conn:\n{:?}", &self.pool))?;
				.with_context(|| format!("Autofetch fetch conn:\n{:?}", &self.pool))?;
			now = chrono::Local::now();
			let mut queue = sqlx::query("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source natural left join rsstg_channel where next_fetch < now();")
			let mut queue = sqlx::query("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source where next_fetch < now();")
				.fetch_all(&mut conn).await?;
			for row in queue.iter() {
				let source_id: i32 = row.try_get("source_id")?;
				let owner: i64 = row.try_get("owner")?;
				let next_fetch: DateTime<chrono::Local> = row.try_get("next_fetch")?;
				if next_fetch < now {
					sqlx::query("update rsstg_source set last_scrape = now() + interval '1 hour' where source_id = $1;")
						.bind(source_id)
						.execute(&mut conn).await
						.with_context(|| format!("πŸ›‘ Lock source:\n\n{:?}", &self.pool))?;
						.with_context(|| format!(" Lock source:\n\n{:?}", &self.pool))?;
					let clone = self.clone();
					tokio::spawn(async move {
						if let Err(err) = clone.check(&source_id, owner, true).await {
							if let Err(err) = clone.debug(&format!("{:?}", err)) {
							if let Err(err) = clone.debug(&format!("πŸ›‘ {:?}", err)) {
								eprintln!("Check 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);
		}
	}

	async fn list(&self, id: telegram_bot::UserId) -> Result<Vec<String>> {
		let id = i64::from(id);
	async fn list<S>(&self, owner: S) -> Result<Vec<String>>
	where S: Into<i64> {
		let owner = owner.into();
		let mut reply = vec![];
		let mut conn = self.pool.acquire().await
			.with_context(|| format!("πŸ›‘ List fetch conn:\n{:?}", &self.pool))?;
			.with_context(|| format!("List fetch conn:\n{:?}", &self.pool))?;
		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(id)
		let rows = sqlx::query("select source_id, channel, enabled, url, iv_hash from rsstg_source where owner = $1 order by source_id")
			.bind(owner)
			.fetch_all(&mut conn).await?;
		for row in rows.iter() {
			let source_id: i32 = row.try_get("source_id")?;
			let username: &str = row.try_get("username")?;
			let username: &str = row.try_get("channel")?;
			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",
260
261
262
263
264
265
266
267

268
269
270
271
272
273
274
317
318
319
320
321
322
323

324
325
326
327
328
329
330
331







-
+








	let core = Core::new(settings).await?;

	let mut stream = core.stream();

	while let Some(update) = stream.next().await {
		if let Err(err) = handle(update?, &core).await {
			core.debug(&format!("{:?}", err))?;
			core.debug(&format!("πŸ›‘ {:?}", err))?;
		};
	}

	Ok(())
}

async fn handle(update: telegram_bot::Update, core: &Core) -> Result<()> {
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
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







-
+
+

-
+
+
+
+

-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-

-
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
-
+
-
-
-
+
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-











-
+







						"/list" => {
							reply.append(&mut core.list(message.from.id).await?);
						},

// add

						"/add" | "/update" => {
							let mut source_id: i32 = 0;
							let mut source_id: Option<i32> = None;
							let at_least = "Requires at least 3 parameters.";
							if cmd == "/update" {
								source_id = words.next().unwrap().parse::<i32>()?;
								let first_word = words.next()
									.context(at_least)?;
								source_id = Some(first_word.parse::<i32>()
									.with_context(|| format!("I need a number, but got {}.", first_word))?);
							}
							let (channel, url, iv_hash) = (words.next().unwrap(), words.next().unwrap(), words.next());
							let ok_link = RE_LINK.is_match(&url);
							let (channel, url, iv_hash) = (
								words.next().context(at_least)?,
								words.next().context(at_least)?,
								words.next());
							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());
								bail!("Wrong username {:?}.", &channel);
							}
							if ! 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))?;
								bail!("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());
							if let Some(hash) = iv_hash {
								if ! RE_IV_HASH.is_match(&hash) {
									reply.push("IV hash should be 14 hex digits.".to_string());
												},
												None => {
									bail!("IV: {:?}", &iv_hash);
													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?;
							let channel_id = i64::from(core.tg.send(telegram_bot::GetChat::new(telegram_bot::types::ChatRef::ChannelUsername(channel.to_string()))).await?.id());
										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 {
							let chan_adm = 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()); };
								.context("Sorry, I have no access to that chat\\.")?;
							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   { bail!("I need to be admin on that channel\\."); };
							if ! user { bail!("You should be admin on that channel\\."); };
												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());
							reply.push(core.update(source_id, channel, channel_id, url, iv_hash, message.from.id).await?);
												};
											},
											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) => {
									core.check(&number, message.from.id, false).await
										.context("πŸ›‘ Channel check failed.")?;
										.context("Channel check failed.")?;
								},
							};
						},

// clean

						"/clean" => {
469
470
471
472
473
474
475














476
477
478
479
480
481
482
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+







								},
								Ok(number) => {
									let result = core.enable(&number, message.from.id).await?;
									reply.push(result.to_string());
								},
							};
						},

// delete

						"/delete" => {
							match &words.next().unwrap().parse::<i32>() {
								Err(err) => {
									reply.push(format!("I need a number\\.\n{}", &err));
								},
								Ok(number) => {
									let result = core.delete(&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));