Diff
Logged in as anonymous

Differences From Artifact [aa11d5be5f]:

To Artifact [db21699f9f]:


1


2
3
4
5
6
7
8

1
2
3
4
5
6
7
8
9
-
+
+







use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};
use std::sync::{Arc, Mutex};

use config;

use tokio;

use rss;

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







+


















+







struct Core {
	owner: i64,
	api_key: String,
	owner_chat: UserId,
	tg: telegram_bot::Api,
	my: User,
	pool: sqlx::Pool<sqlx::Postgres>,
	sources: Arc<Mutex<HashSet<Arc<i32>>>>,
}

impl Core {
	async fn new(settings: config::Config) -> Result<Core> {
		let owner = settings.get_int("owner")?;
		let api_key = settings.get_str("api_key")?;
		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")?)?,
			sources: Arc::new(Mutex::new(HashSet::new())),
		};
		let clone = core.clone();
		tokio::spawn(async move {
			if let Err(err) = &clone.autofetch().await {
				if let Err(err) = clone.debug(&format!("🛑 {:?}", err)) {
					eprintln!("Autofetch error: {}", err);
				};
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
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







-
+


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



-
+







	}

	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<()>
	async fn check<S>(&self, id: i32, owner: S, real: bool) -> Result<()>
	where S: Into<i64> {
		let owner: i64 = owner.into();
		let id = {
			let mut set = self.sources.lock().unwrap();
			match set.get(&id) {
				Some(id) => id.clone(),
				None => {
					let id = Arc::new(id);
					set.insert(id.clone());
					id.clone()
				},
			}
		};
		let count = Arc::strong_count(&id);
		if count == 2 {
		let mut conn = self.pool.acquire().await
			.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))?;
		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))?;
		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))?;
			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))?;
			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:")?;
				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))?;
				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!("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))?;
			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))?;
			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))?;
				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))?;
				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:")?;
					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))?;
					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))?;
		sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
			.bind(id)
			.bind(*id)
			.execute(&mut conn).await
			.with_context(|| format!("Update scrape:\n{:?}", &conn))?;
		Ok(())
	}

	async fn delete<S>(&self, source_id: &i32, owner: S) -> Result<String>
	where S: Into<i64> {
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
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







-
+






-
-
-
+
-
-
+
+
+
+
+

-
+







	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))?;
			now = chrono::Local::now();
			let mut queue = sqlx::query("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source 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() + interval '5 minutes';")
				.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
					//let clone = self.clone();
						.with_context(|| format!(" Lock source:\n\n{:?}", &self.pool))?;
					let clone = self.clone();
					//clone.owner_chat(UserId::new(owner));
					let clone = Core {
						owner_chat: UserId::new(owner),
						..self.clone()
					};
					tokio::spawn(async move {
						if let Err(err) = clone.check(&source_id, owner, true).await {
						if let Err(err) = clone.check(source_id, owner, true).await {
							if let Err(err) = clone.debug(&format!("🛑 {:?}", err)) {
								eprintln!("Check error: {}", err);
							};
						};
					});
				} else {
					if next_fetch - now < delay {
406
407
408
409
410
411
412
413

414
415
416
417
418
419
420
424
425
426
427
428
429
430

431
432
433
434
435
436
437
438







-
+








						"/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
									core.check(*number, message.from.id, false).await
										.context("Channel check failed.")?;
								},
							};
						},

// clean