Diff
Logged in as anonymous

Differences From Artifact [5aa2f82de1]:

To Artifact [483b69f7a3]:


1






2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
use std::borrow::Cow;







use anyhow::{
	Result,
	bail,
};
use chrono::{
	DateTime,
	FixedOffset,
	Local,
};
use sqlx::{
	Pool,
	Postgres,
	Row,
	postgres::PgPoolOptions,
	pool::PoolConnection,
};

#[derive(sqlx::FromRow, Debug)]
|
>
>
>
>
>
>











<







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 std::{
	borrow::Cow,
	sync::{
		Arc,
		Mutex,
	},
};

use anyhow::{
	Result,
	bail,
};
use chrono::{
	DateTime,
	FixedOffset,
	Local,
};
use sqlx::{

	Postgres,
	Row,
	postgres::PgPoolOptions,
	pool::PoolConnection,
};

#[derive(sqlx::FromRow, Debug)]
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
	pub source_id: Option<i32>,
	pub next_fetch: Option<DateTime<Local>>,
	pub owner: Option<i64>,
}

#[derive(Clone)]
pub struct Db {
	pool: sqlx::Pool<sqlx::Postgres>,
}

pub struct Conn{
	conn: PoolConnection<Postgres>,
}

impl Db {
	pub fn new (pguri: &str) -> Result<Db> {
		Ok(Db{
			pool: PgPoolOptions::new()
				.max_connections(5)
				.acquire_timeout(std::time::Duration::new(300, 0))
				.idle_timeout(std::time::Duration::new(60, 0))
				.connect_lazy(pguri)?,
		})
	}

	pub async fn begin(&mut self) -> Result<Conn> {

		Conn::new(&mut self.pool).await

	}
}

impl Conn {
	pub async fn new (pool: &mut Pool<Postgres>) -> Result<Conn> {
		let conn = pool.acquire().await?;
		Ok(Conn{
			conn,
		})
	}

	pub async fn add_post (&mut self, id: i32, date: &DateTime<FixedOffset>, post_url: &str) -> Result<()> {
		sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);")
			.bind(id)
			.bind(date)
			.bind(post_url)
			.execute(&mut *self.conn).await?;
		Ok(())
	}

	pub async fn clean (&mut self, source_id: i32, owner: i64) -> Result<Cow<'_, str>> {

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

	pub async fn delete (&mut self, source_id: i32, owner: i64) -> Result<Cow<'_, str>> {

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

	pub async fn disable (&mut self, source_id: i32, owner: i64) -> Result<&str> {

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

	pub async fn enable (&mut self, source_id: i32, owner: i64) -> Result<&str> {

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

	pub async fn exists (&mut self, post_url: &str, id: i32) -> Result<Option<bool>> {

		let row = sqlx::query("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;")
			.bind(post_url)
			.bind(id)
			.fetch_one(&mut *self.conn).await?;
		let exists: Option<bool> = row.try_get("exists")?;
		Ok(exists)
	}

	pub async fn get_queue (&mut self) -> Result<Vec<Queue>> {
		let block: Vec<Queue> = sqlx::query_as("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source where next_fetch < now() + interval '1 minute';")
			.fetch_all(&mut *self.conn).await?;
		Ok(block)
	}

	pub async fn get_list (&mut self, owner: i64) -> Result<Vec<List>> {

		let source: Vec<List> = sqlx::query_as("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id")
			.bind(owner)
			.fetch_all(&mut *self.conn).await?;
		Ok(source)
	}

	pub async fn get_source (&mut self, id: i32, owner: i64) -> Result<Source> {

		let source: Source = sqlx::query_as("select channel_id, url, iv_hash, owner, url_re from rsstg_source where source_id = $1 and owner = $2")
			.bind(id)
			.bind(owner)
			.fetch_one(&mut *self.conn).await?;
		Ok(source)
	}

	pub async fn set_scrape (&mut self, id: i32) -> Result<()> {

		sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
			.bind(id)
			.execute(&mut *self.conn).await?;
		Ok(())
	}

	pub async fn update (&mut self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: i64) -> Result<&str> {

		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")
						.bind(id)
				},
				None => {
					sqlx::query("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)")
				},
			}
				.bind(channel_id)
				.bind(url)
				.bind(iv_hash)
				.bind(owner)
				.bind(channel)
				.bind(url_re)
				.execute(&mut *self.conn).await
			{
			Ok(_) => Ok(match update {
				Some(_) => "Channel updated.",
				None => "Channel added.",







|









|



|



|
>
|
>




|
<





|

|






|
>


|






|
>


|






|
>


|







|
>


|







|
>


|











|
>

|




|
>


|




|
>

|




|
>












|







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
	pub source_id: Option<i32>,
	pub next_fetch: Option<DateTime<Local>>,
	pub owner: Option<i64>,
}

#[derive(Clone)]
pub struct Db {
	pool: Arc<Mutex<Arc<sqlx::Pool<sqlx::Postgres>>>>,
}

pub struct Conn{
	conn: PoolConnection<Postgres>,
}

impl Db {
	pub fn new (pguri: &str) -> Result<Db> {
		Ok(Db{
			pool: Arc::new(Mutex::new(Arc::new(PgPoolOptions::new()
				.max_connections(5)
				.acquire_timeout(std::time::Duration::new(300, 0))
				.idle_timeout(std::time::Duration::new(60, 0))
				.connect_lazy(pguri)?))),
		})
	}

	pub async fn begin(&self) -> Result<Conn> {
		let pool = self.pool.lock().unwrap().clone();
		let conn = Conn::new(pool.acquire().await?).await?;
		Ok(conn)
	}
}

impl Conn {
	pub async fn new (conn: PoolConnection<Postgres>) -> Result<Conn> {

		Ok(Conn{
			conn,
		})
	}

	pub async fn add_post (&mut self, source_id: i32, date: &DateTime<FixedOffset>, post_url: &str) -> Result<()> {
		sqlx::query("insert into rsstg_post (source_id, posted, url) values ($1, $2, $3);")
			.bind(source_id)
			.bind(date)
			.bind(post_url)
			.execute(&mut *self.conn).await?;
		Ok(())
	}

	pub async fn clean <I> (&mut self, source_id: i32, owner: I) -> Result<Cow<'_, str>>
	where I: Into<i64> {
		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(owner.into())
			.execute(&mut *self.conn).await?.rows_affected() {
			0 => { Ok("No data found found.".into()) },
			x => { Ok(format!("{x} posts purged.").into()) },
		}
	}

	pub async fn delete <I> (&mut self, source_id: i32, owner: I) -> Result<Cow<'_, str>>
	where I: Into<i64> {
		match sqlx::query("delete from rsstg_source where source_id = $1 and owner = $2;")
			.bind(source_id)
			.bind(owner.into())
			.execute(&mut *self.conn).await?.rows_affected() {
			0 => { Ok("No data found found.".into()) },
			x => { Ok(format!("{} sources removed.", x).into()) },
		}
	}

	pub async fn disable <I> (&mut self, source_id: i32, owner: I) -> Result<&str>
	where I: Into<i64> {
		match sqlx::query("update rsstg_source set enabled = false where source_id = $1 and owner = $2")
			.bind(source_id)
			.bind(owner.into())
			.execute(&mut *self.conn).await?.rows_affected() {
			1 => { Ok("Source disabled.") },
			0 => { Ok("Source not found.") },
			_ => { bail!("Database error.") },
		}
	}

	pub async fn enable <I> (&mut self, source_id: i32, owner: I) -> Result<&str>
	where I: Into<i64> {
		match sqlx::query("update rsstg_source set enabled = true where source_id = $1 and owner = $2")
			.bind(source_id)
			.bind(owner.into())
			.execute(&mut *self.conn).await?.rows_affected() {
			1 => { Ok("Source enabled.") },
			0 => { Ok("Source not found.") },
			_ => { bail!("Database error.") },
		}
	}

	pub async fn exists <I> (&mut self, post_url: &str, id: I) -> Result<Option<bool>>
	where I: Into<i64> {
		let row = sqlx::query("select exists(select true from rsstg_post where url = $1 and source_id = $2) as exists;")
			.bind(post_url)
			.bind(id.into())
			.fetch_one(&mut *self.conn).await?;
		let exists: Option<bool> = row.try_get("exists")?;
		Ok(exists)
	}

	pub async fn get_queue (&mut self) -> Result<Vec<Queue>> {
		let block: Vec<Queue> = sqlx::query_as("select source_id, next_fetch, owner from rsstg_order natural left join rsstg_source where next_fetch < now() + interval '1 minute';")
			.fetch_all(&mut *self.conn).await?;
		Ok(block)
	}

	pub async fn get_list <I> (&mut self, owner: I) -> Result<Vec<List>>
	where I: Into<i64> {
		let source: Vec<List> = sqlx::query_as("select source_id, channel, enabled, url, iv_hash, url_re from rsstg_source where owner = $1 order by source_id")
			.bind(owner.into())
			.fetch_all(&mut *self.conn).await?;
		Ok(source)
	}

	pub async fn get_source <I> (&mut self, id: i32, owner: I) -> Result<Source>
	where I: Into<i64> {
		let source: Source = sqlx::query_as("select channel_id, url, iv_hash, owner, url_re from rsstg_source where source_id = $1 and owner = $2")
			.bind(id)
			.bind(owner.into())
			.fetch_one(&mut *self.conn).await?;
		Ok(source)
	}

	pub async fn set_scrape <I> (&mut self, id: I) -> Result<()>
	where I: Into<i64> {
		sqlx::query("update rsstg_source set last_scrape = now() where source_id = $1;")
			.bind(id.into())
			.execute(&mut *self.conn).await?;
		Ok(())
	}

	pub async fn update <I> (&mut self, update: Option<i32>, channel: &str, channel_id: i64, url: &str, iv_hash: Option<&str>, url_re: Option<&str>, owner: I) -> Result<&str>
	where I: Into<i64> {
		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")
						.bind(id)
				},
				None => {
					sqlx::query("insert into rsstg_source (channel_id, url, iv_hash, owner, channel, url_re) values ($1, $2, $3, $4, $5, $6)")
				},
			}
				.bind(channel_id)
				.bind(url)
				.bind(iv_hash)
				.bind(owner.into())
				.bind(channel)
				.bind(url_re)
				.execute(&mut *self.conn).await
			{
			Ok(_) => Ok(match update {
				Some(_) => "Channel updated.",
				None => "Channel added.",