Follows (#172)
* Follows initial * Fix #171, Fix #170, Fix #169, Fix #164 * More work on follows * Fix compile error * Upgrade meili version, add follows to search
This commit is contained in:
parent
e46ff3de8b
commit
0ccb6cb873
127
Cargo.lock
generated
127
Cargo.lock
generated
@ -1072,6 +1072,37 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curl"
|
||||
version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e268162af1a5fe89917ae25ba3b0a77c8da752bdc58e7dbb4f15b91fbd33756e"
|
||||
dependencies = [
|
||||
"curl-sys",
|
||||
"libc",
|
||||
"openssl-probe",
|
||||
"openssl-sys",
|
||||
"schannel",
|
||||
"socket2",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curl-sys"
|
||||
version = "0.4.40+curl-7.75.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ffafc1c35958318bd7fdd0582995ce4c72f4f461a8e70499ccee83a619fd562"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"libnghttp2-sys",
|
||||
"libz-sys",
|
||||
"openssl-sys",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.10.2"
|
||||
@ -1298,6 +1329,18 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flume"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "531a685ab99b8f60a271b44d5dd1a76e55124a8c9fa0407b7a8e9cd172d5b588"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
"pin-project 1.0.4",
|
||||
"spinning_top",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@ -1856,6 +1899,30 @@ version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47be2f14c678be2fdcab04ab1171db51b2762ce6f0a8ee87c8dd4a04ed216135"
|
||||
|
||||
[[package]]
|
||||
name = "isahc"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af3d0a62435883f745c825ec06a03a38d24bf5fa65c43e2c083b6a60ce0058ae"
|
||||
dependencies = [
|
||||
"crossbeam-utils 0.8.1",
|
||||
"curl",
|
||||
"curl-sys",
|
||||
"encoding_rs",
|
||||
"flume",
|
||||
"futures-lite",
|
||||
"http",
|
||||
"log",
|
||||
"mime",
|
||||
"once_cell",
|
||||
"slab",
|
||||
"sluice",
|
||||
"tracing",
|
||||
"tracing-futures",
|
||||
"url",
|
||||
"waker-fn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "0.4.7"
|
||||
@ -1957,6 +2024,28 @@ version = "0.2.82"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89203f3fba0a3795506acaad8ebce3c80c0af93f994d5a1d7a0b1eeb23271929"
|
||||
|
||||
[[package]]
|
||||
name = "libnghttp2-sys"
|
||||
version = "0.1.6+1.43.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0af55541a8827e138d59ec9e5877fb6095ece63fb6f4da45e7491b4fbd262855"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libz-sys"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "602113192b08db8f38796c4e85c39e960c145965140e918018bcde1952429655"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linked-hash-map"
|
||||
version = "0.5.4"
|
||||
@ -2034,12 +2123,12 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
|
||||
|
||||
[[package]]
|
||||
name = "meilisearch-sdk"
|
||||
version = "0.4.0"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb2081610089deb10290747b8782049f9cb64a70a4d305a28970db8b780d1448"
|
||||
checksum = "f8972f69aef330566ece2a76e61ebb9383565b03c45aeb95dbd66ad672186497"
|
||||
dependencies = [
|
||||
"isahc",
|
||||
"log",
|
||||
"reqwest 0.10.10",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
@ -3179,6 +3268,17 @@ version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"
|
||||
|
||||
[[package]]
|
||||
name = "sluice"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fa0333a60ff2e3474a6775cc611840c2a55610c831dd366503474c02f1a28f5"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.6.1"
|
||||
@ -3202,6 +3302,15 @@ version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
|
||||
|
||||
[[package]]
|
||||
name = "spinning_top"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e529d73e80d64b5f2631f9035113347c578a1c9c7774b83a2b880788459ab36"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sqlformat"
|
||||
version = "0.1.5"
|
||||
@ -3701,9 +3810,21 @@ dependencies = [
|
||||
"cfg-if 1.0.0",
|
||||
"log",
|
||||
"pin-project-lite 0.2.4",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8a9bd1db7706f2373a190b0d067146caa39350c486f3d455b0e33b431f94c07"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.17"
|
||||
|
||||
@ -19,7 +19,7 @@ actix-multipart = "0.3.0"
|
||||
actix-cors = "0.4.1"
|
||||
actix-ratelimit = "0.3.0"
|
||||
|
||||
meilisearch-sdk = "0.4.0"
|
||||
meilisearch-sdk = "0.6.0"
|
||||
reqwest = { version = "0.10.8", features = ["json"] }
|
||||
|
||||
serde_json = "1.0"
|
||||
|
||||
17
migrations/20210224174945_notifications.sql
Normal file
17
migrations/20210224174945_notifications.sql
Normal file
@ -0,0 +1,17 @@
|
||||
-- Add migration script here
|
||||
CREATE TABLE notifications (
|
||||
id bigint PRIMARY KEY,
|
||||
user_id bigint REFERENCES users NOT NULL,
|
||||
title varchar(255) NOT NULL,
|
||||
text varchar(2048) NOT NULL,
|
||||
link varchar(2048) NOT NULL,
|
||||
created timestamptz DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
read boolean DEFAULT FALSE NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE notifications_actions (
|
||||
id serial PRIMARY KEY,
|
||||
notification_id bigint REFERENCES notifications NOT NULL,
|
||||
title varchar(255) NOT NULL,
|
||||
action_route varchar(2048) NOT NULL
|
||||
);
|
||||
9
migrations/20210301041252_follows.sql
Normal file
9
migrations/20210301041252_follows.sql
Normal file
@ -0,0 +1,9 @@
|
||||
CREATE TABLE mod_follows(
|
||||
follower_id bigint REFERENCES users NOT NULL,
|
||||
mod_id bigint REFERENCES mods NOT NULL,
|
||||
created timestamptz DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
PRIMARY KEY (follower_id, mod_id)
|
||||
);
|
||||
|
||||
ALTER TABLE mods
|
||||
ADD COLUMN follows integer NOT NULL default 0;
|
||||
1872
sqlx-data.json
1872
sqlx-data.json
File diff suppressed because it is too large
Load Diff
@ -94,6 +94,14 @@ generate_ids!(
|
||||
ReportId
|
||||
);
|
||||
|
||||
generate_ids!(
|
||||
pub generate_notification_id,
|
||||
NotificationId,
|
||||
8,
|
||||
"SELECT EXISTS(SELECT 1 FROM notifications WHERE id=$1)",
|
||||
NotificationId
|
||||
);
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Type)]
|
||||
#[sqlx(transparent)]
|
||||
pub struct UserId(pub i64);
|
||||
@ -152,6 +160,13 @@ pub struct FileId(pub i64);
|
||||
#[sqlx(transparent)]
|
||||
pub struct StateId(pub i64);
|
||||
|
||||
#[derive(Copy, Clone, Debug, Type)]
|
||||
#[sqlx(transparent)]
|
||||
pub struct NotificationId(pub i64);
|
||||
#[derive(Copy, Clone, Debug, Type)]
|
||||
#[sqlx(transparent)]
|
||||
pub struct NotificationActionId(pub i32);
|
||||
|
||||
use crate::models::ids;
|
||||
|
||||
impl From<ids::ModId> for ModId {
|
||||
@ -204,3 +219,13 @@ impl From<ReportId> for ids::ReportId {
|
||||
ids::ReportId(id.0 as u64)
|
||||
}
|
||||
}
|
||||
impl From<ids::NotificationId> for NotificationId {
|
||||
fn from(id: ids::NotificationId) -> Self {
|
||||
NotificationId(id.0 as i64)
|
||||
}
|
||||
}
|
||||
impl From<NotificationId> for ids::NotificationId {
|
||||
fn from(id: NotificationId) -> Self {
|
||||
ids::NotificationId(id.0 as u64)
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ use thiserror::Error;
|
||||
pub mod categories;
|
||||
pub mod ids;
|
||||
pub mod mod_item;
|
||||
pub mod notification_item;
|
||||
pub mod report_item;
|
||||
pub mod team_item;
|
||||
pub mod user_item;
|
||||
|
||||
@ -71,6 +71,7 @@ impl ModBuilder {
|
||||
updated: chrono::Utc::now(),
|
||||
status: self.status,
|
||||
downloads: 0,
|
||||
follows: 0,
|
||||
icon_url: self.icon_url,
|
||||
issues_url: self.issues_url,
|
||||
source_url: self.source_url,
|
||||
@ -122,6 +123,7 @@ pub struct Mod {
|
||||
pub updated: chrono::DateTime<chrono::Utc>,
|
||||
pub status: StatusId,
|
||||
pub downloads: i32,
|
||||
pub follows: i32,
|
||||
pub icon_url: Option<String>,
|
||||
pub issues_url: Option<String>,
|
||||
pub source_url: Option<String>,
|
||||
@ -153,7 +155,7 @@ impl Mod {
|
||||
$6, $7, $8, $9,
|
||||
$10, $11, $12, $13,
|
||||
$14, $15, $16, $17,
|
||||
$18
|
||||
LOWER($18)
|
||||
)
|
||||
",
|
||||
self.id as ModId,
|
||||
@ -187,7 +189,7 @@ impl Mod {
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT title, description, downloads,
|
||||
SELECT title, description, downloads, follows,
|
||||
icon_url, body, body_url, published,
|
||||
updated, status,
|
||||
issues_url, source_url, wiki_url, discord_url, license_url,
|
||||
@ -222,6 +224,7 @@ impl Mod {
|
||||
license: LicenseId(row.license),
|
||||
slug: row.slug,
|
||||
body: row.body,
|
||||
follows: row.follows,
|
||||
}))
|
||||
} else {
|
||||
Ok(None)
|
||||
@ -237,7 +240,7 @@ impl Mod {
|
||||
let mod_ids_parsed: Vec<i64> = mod_ids.into_iter().map(|x| x.0).collect();
|
||||
let mods = sqlx::query!(
|
||||
"
|
||||
SELECT id, title, description, downloads,
|
||||
SELECT id, title, description, downloads, follows,
|
||||
icon_url, body, body_url, published,
|
||||
updated, status,
|
||||
issues_url, source_url, wiki_url, discord_url, license_url,
|
||||
@ -270,6 +273,7 @@ impl Mod {
|
||||
license: LicenseId(m.license),
|
||||
slug: m.slug,
|
||||
body: m.body,
|
||||
follows: m.follows,
|
||||
}))
|
||||
})
|
||||
.try_collect::<Vec<Mod>>()
|
||||
@ -300,6 +304,26 @@ impl Mod {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM mod_follows
|
||||
WHERE mod_id = $1
|
||||
",
|
||||
id as ModId
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM mod_follows
|
||||
WHERE mod_id = $1
|
||||
",
|
||||
id as ModId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM reports
|
||||
@ -390,7 +414,7 @@ impl Mod {
|
||||
let id = sqlx::query!(
|
||||
"
|
||||
SELECT id FROM mods
|
||||
WHERE slug = $1
|
||||
WHERE LOWER(slug) = LOWER($1)
|
||||
",
|
||||
slug
|
||||
)
|
||||
@ -413,7 +437,7 @@ impl Mod {
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT m.id id, m.title title, m.description description, m.downloads downloads,
|
||||
SELECT m.id id, m.title title, m.description description, m.downloads downloads, m.follows follows,
|
||||
m.icon_url icon_url, m.body body, m.body_url body_url, m.published published,
|
||||
m.updated updated, m.status status,
|
||||
m.issues_url issues_url, m.source_url source_url, m.wiki_url wiki_url, m.discord_url discord_url, m.license_url license_url,
|
||||
@ -459,6 +483,7 @@ impl Mod {
|
||||
license: LicenseId(m.license),
|
||||
slug: m.slug.clone(),
|
||||
body: m.body.clone(),
|
||||
follows: m.follows,
|
||||
},
|
||||
categories: m
|
||||
.categories
|
||||
@ -496,7 +521,7 @@ impl Mod {
|
||||
let mod_ids_parsed: Vec<i64> = mod_ids.into_iter().map(|x| x.0).collect();
|
||||
sqlx::query!(
|
||||
"
|
||||
SELECT m.id id, m.title title, m.description description, m.downloads downloads,
|
||||
SELECT m.id id, m.title title, m.description description, m.downloads downloads, m.follows follows,
|
||||
m.icon_url icon_url, m.body body, m.body_url body_url, m.published published,
|
||||
m.updated updated, m.status status,
|
||||
m.issues_url issues_url, m.source_url source_url, m.wiki_url wiki_url, m.discord_url discord_url, m.license_url license_url,
|
||||
@ -540,6 +565,7 @@ impl Mod {
|
||||
license: LicenseId(m.license),
|
||||
slug: m.slug.clone(),
|
||||
body: m.body.clone(),
|
||||
follows: m.follows
|
||||
},
|
||||
categories: m.categories.unwrap_or_default().split(',').map(|x| x.to_string()).collect(),
|
||||
versions: m.versions.unwrap_or_default().split(',').map(|x| VersionId(x.parse().unwrap_or_default())).collect(),
|
||||
|
||||
327
src/database/models/notification_item.rs
Normal file
327
src/database/models/notification_item.rs
Normal file
@ -0,0 +1,327 @@
|
||||
use super::ids::*;
|
||||
use crate::database::models::DatabaseError;
|
||||
|
||||
pub struct NotificationBuilder {
|
||||
pub title: String,
|
||||
pub text: String,
|
||||
pub link: String,
|
||||
pub actions: Vec<NotificationActionBuilder>,
|
||||
}
|
||||
|
||||
pub struct NotificationActionBuilder {
|
||||
pub title: String,
|
||||
pub action_route: String,
|
||||
}
|
||||
|
||||
pub struct Notification {
|
||||
pub id: NotificationId,
|
||||
pub user_id: UserId,
|
||||
pub title: String,
|
||||
pub text: String,
|
||||
pub link: String,
|
||||
pub read: bool,
|
||||
pub created: chrono::DateTime<chrono::Utc>,
|
||||
pub actions: Vec<NotificationAction>,
|
||||
}
|
||||
|
||||
pub struct NotificationAction {
|
||||
pub id: NotificationActionId,
|
||||
pub notification_id: NotificationId,
|
||||
pub title: String,
|
||||
pub action_route: String,
|
||||
}
|
||||
|
||||
impl NotificationBuilder {
|
||||
pub async fn insert(
|
||||
&self,
|
||||
user: UserId,
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), DatabaseError> {
|
||||
self.insert_many(vec![user], transaction).await
|
||||
}
|
||||
|
||||
pub async fn insert_many(
|
||||
&self,
|
||||
users: Vec<UserId>,
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), DatabaseError> {
|
||||
for user in users {
|
||||
let id = generate_notification_id(&mut *transaction).await?;
|
||||
|
||||
let mut actions = Vec::new();
|
||||
|
||||
for action in &self.actions {
|
||||
actions.push(NotificationAction {
|
||||
id: NotificationActionId(0),
|
||||
notification_id: id,
|
||||
title: action.title.clone(),
|
||||
action_route: action.action_route.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
Notification {
|
||||
id,
|
||||
user_id: user,
|
||||
title: self.title.clone(),
|
||||
text: self.text.clone(),
|
||||
link: self.link.clone(),
|
||||
read: false,
|
||||
created: chrono::Utc::now(),
|
||||
actions,
|
||||
}
|
||||
.insert(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Notification {
|
||||
pub async fn insert(
|
||||
&self,
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), sqlx::error::Error> {
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO notifications (
|
||||
id, user_id, title, text, link
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5
|
||||
)
|
||||
",
|
||||
self.id as NotificationId,
|
||||
self.user_id as UserId,
|
||||
&self.title,
|
||||
&self.text,
|
||||
&self.link
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
for action in &self.actions {
|
||||
action.insert(&mut *transaction).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get<'a, 'b, E>(
|
||||
id: NotificationId,
|
||||
executor: E,
|
||||
) -> Result<Option<Self>, sqlx::error::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres>,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT n.user_id, n.title, n.text, n.link, n.created, n.read,
|
||||
STRING_AGG(DISTINCT na.id || ', ' || na.title || ', ' || na.action_route, ' ,') actions
|
||||
FROM notifications n
|
||||
LEFT OUTER JOIN notifications_actions na on n.id = na.notification_id
|
||||
WHERE n.id = $1
|
||||
GROUP BY n.id, n.user_id;
|
||||
",
|
||||
id as NotificationId,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await?;
|
||||
|
||||
if let Some(row) = result {
|
||||
let mut actions: Vec<NotificationAction> = Vec::new();
|
||||
|
||||
row.actions.unwrap_or_default().split(" ,").for_each(|x| {
|
||||
let action: Vec<&str> = x.split(", ").collect();
|
||||
|
||||
if action.len() >= 3 {
|
||||
actions.push(NotificationAction {
|
||||
id: NotificationActionId(action[0].parse().unwrap_or(0)),
|
||||
notification_id: id,
|
||||
title: action[1].to_string(),
|
||||
action_route: action[2].to_string(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Some(Notification {
|
||||
id,
|
||||
user_id: UserId(row.user_id),
|
||||
title: row.title,
|
||||
text: row.text,
|
||||
link: row.link,
|
||||
read: row.read,
|
||||
created: row.created,
|
||||
actions,
|
||||
}))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_many<'a, E>(
|
||||
notification_ids: Vec<NotificationId>,
|
||||
exec: E,
|
||||
) -> Result<Vec<Notification>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
|
||||
{
|
||||
use futures::stream::TryStreamExt;
|
||||
|
||||
let notification_ids_parsed: Vec<i64> = notification_ids.into_iter().map(|x| x.0).collect();
|
||||
sqlx::query!(
|
||||
"
|
||||
SELECT n.id, n.user_id, n.title, n.text, n.link, n.created, n.read,
|
||||
STRING_AGG(DISTINCT na.id || ', ' || na.title || ', ' || na.action_route, ' ,') actions
|
||||
FROM notifications n
|
||||
LEFT OUTER JOIN notifications_actions na on n.id = na.notification_id
|
||||
WHERE n.id IN (SELECT * FROM UNNEST($1::bigint[]))
|
||||
GROUP BY n.id, n.user_id;
|
||||
",
|
||||
¬ification_ids_parsed
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async {
|
||||
Ok(e.right().map(|row| {
|
||||
let id = NotificationId(row.id);
|
||||
let mut actions: Vec<NotificationAction> = Vec::new();
|
||||
|
||||
row.actions.unwrap_or_default().split(" ,").for_each(|x| {
|
||||
let action: Vec<&str> = x.split(", ").collect();
|
||||
|
||||
if action.len() >= 3 {
|
||||
actions.push(NotificationAction {
|
||||
id: NotificationActionId(action[0].parse().unwrap_or(0)),
|
||||
notification_id: id,
|
||||
title: action[1].to_string(),
|
||||
action_route: action[2].to_string(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Notification {
|
||||
id,
|
||||
user_id: UserId(row.user_id),
|
||||
title: row.title,
|
||||
text: row.text,
|
||||
link: row.link,
|
||||
read: row.read,
|
||||
created: row.created,
|
||||
actions,
|
||||
}
|
||||
}))
|
||||
})
|
||||
.try_collect::<Vec<Notification>>()
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_many_user<'a, E>(
|
||||
user_id: UserId,
|
||||
exec: E,
|
||||
) -> Result<Vec<Notification>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
|
||||
{
|
||||
use futures::stream::TryStreamExt;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
SELECT n.id, n.user_id, n.title, n.text, n.link, n.created, n.read,
|
||||
STRING_AGG(DISTINCT na.id || ', ' || na.title || ', ' || na.action_route, ' ,') actions
|
||||
FROM notifications n
|
||||
LEFT OUTER JOIN notifications_actions na on n.id = na.notification_id
|
||||
WHERE n.user_id = $1
|
||||
GROUP BY n.id, n.user_id;
|
||||
",
|
||||
user_id as UserId
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async {
|
||||
Ok(e.right().map(|row| {
|
||||
let id = NotificationId(row.id);
|
||||
let mut actions: Vec<NotificationAction> = Vec::new();
|
||||
|
||||
row.actions.unwrap_or_default().split(" ,").for_each(|x| {
|
||||
let action: Vec<&str> = x.split(", ").collect();
|
||||
|
||||
if action.len() >= 3 {
|
||||
actions.push(NotificationAction {
|
||||
id: NotificationActionId(action[0].parse().unwrap_or(0)),
|
||||
notification_id: id,
|
||||
title: action[1].to_string(),
|
||||
action_route: action[2].to_string(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Notification {
|
||||
id,
|
||||
user_id: UserId(row.user_id),
|
||||
title: row.title,
|
||||
text: row.text,
|
||||
link: row.link,
|
||||
read: row.read,
|
||||
created: row.created,
|
||||
actions,
|
||||
}
|
||||
}))
|
||||
})
|
||||
.try_collect::<Vec<Notification>>()
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn remove<'a, 'b, E>(
|
||||
id: NotificationId,
|
||||
exec: E,
|
||||
) -> Result<Option<()>, sqlx::error::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
|
||||
{
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM notifications_actions
|
||||
WHERE notification_id = $1
|
||||
",
|
||||
id as NotificationId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM notifications
|
||||
WHERE id = $1
|
||||
",
|
||||
id as NotificationId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
Ok(Some(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl NotificationAction {
|
||||
pub async fn insert(
|
||||
&self,
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), sqlx::error::Error> {
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO notifications_actions (
|
||||
notification_id, title, action_route
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3
|
||||
)
|
||||
",
|
||||
self.notification_id as NotificationId,
|
||||
&self.title,
|
||||
&self.action_route,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@ -24,7 +24,7 @@ impl User {
|
||||
avatar_url, bio, created
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5,
|
||||
$1, $2, LOWER($3), $4, $5,
|
||||
$6, $7, $8
|
||||
)
|
||||
",
|
||||
@ -126,7 +126,7 @@ impl User {
|
||||
u.avatar_url, u.bio,
|
||||
u.created, u.role
|
||||
FROM users u
|
||||
WHERE u.username = $1
|
||||
WHERE LOWER(u.username) = LOWER($1)
|
||||
",
|
||||
username
|
||||
)
|
||||
@ -239,6 +239,29 @@ impl User {
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
use futures::TryStreamExt;
|
||||
let notifications: Vec<i64> = sqlx::query!(
|
||||
"
|
||||
SELECT n.id FROM notifications n
|
||||
WHERE n.user_id = $1
|
||||
",
|
||||
id as UserId,
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|m| m.id as i64)) })
|
||||
.try_collect::<Vec<i64>>()
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM notifications
|
||||
WHERE user_id = $1
|
||||
",
|
||||
id as UserId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM reports
|
||||
@ -249,6 +272,26 @@ impl User {
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM mod_follows
|
||||
WHERE follower_id = $1
|
||||
",
|
||||
id as UserId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM notifications_actions
|
||||
WHERE notification_id IN (SELECT * FROM UNNEST($1::bigint[]))
|
||||
",
|
||||
¬ifications
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM team_members
|
||||
@ -298,6 +341,38 @@ impl User {
|
||||
let _result = super::mod_item::Mod::remove_full(mod_id, exec).await?;
|
||||
}
|
||||
|
||||
let notifications: Vec<i64> = sqlx::query!(
|
||||
"
|
||||
SELECT n.id FROM notifications n
|
||||
WHERE n.user_id = $1
|
||||
",
|
||||
id as UserId,
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|m| m.id as i64)) })
|
||||
.try_collect::<Vec<i64>>()
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM notifications
|
||||
WHERE user_id = $1
|
||||
",
|
||||
id as UserId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM notifications_actions
|
||||
WHERE notification_id IN (SELECT * FROM UNNEST($1::bigint[]))
|
||||
",
|
||||
¬ifications
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
let deleted_user: UserId = crate::models::users::DELETED_USER.into();
|
||||
|
||||
sqlx::query!(
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
use thiserror::Error;
|
||||
|
||||
pub use super::mods::{ModId, VersionId};
|
||||
pub use super::notifications::NotificationId;
|
||||
pub use super::reports::ReportId;
|
||||
pub use super::teams::TeamId;
|
||||
pub use super::users::UserId;
|
||||
@ -109,6 +110,7 @@ base62_id_impl!(UserId, UserId);
|
||||
base62_id_impl!(VersionId, VersionId);
|
||||
base62_id_impl!(TeamId, TeamId);
|
||||
base62_id_impl!(ReportId, ReportId);
|
||||
base62_id_impl!(NotificationId, NotificationId);
|
||||
|
||||
pub mod base62_impl {
|
||||
use serde::de::{self, Deserializer, Visitor};
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
pub mod error;
|
||||
pub mod ids;
|
||||
pub mod mods;
|
||||
pub mod notifications;
|
||||
pub mod reports;
|
||||
pub mod teams;
|
||||
pub mod users;
|
||||
|
||||
@ -49,6 +49,9 @@ pub struct Mod {
|
||||
|
||||
/// The total number of downloads the mod has had.
|
||||
pub downloads: u32,
|
||||
/// The total number of followers this mod has accumulated
|
||||
pub followers: u32,
|
||||
|
||||
/// A list of the categories that the mod is in.
|
||||
pub categories: Vec<String>,
|
||||
/// A list of ids for versions of the mod.
|
||||
|
||||
27
src/models/notifications.rs
Normal file
27
src/models/notifications.rs
Normal file
@ -0,0 +1,27 @@
|
||||
use super::ids::Base62Id;
|
||||
use super::users::UserId;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(from = "Base62Id")]
|
||||
#[serde(into = "Base62Id")]
|
||||
pub struct NotificationId(pub u64);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Notification {
|
||||
pub id: NotificationId,
|
||||
pub user_id: UserId,
|
||||
pub title: String,
|
||||
pub text: String,
|
||||
pub link: String,
|
||||
pub read: bool,
|
||||
pub created: DateTime<Utc>,
|
||||
pub actions: Vec<NotificationAction>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct NotificationAction {
|
||||
pub title: String,
|
||||
pub action_route: String,
|
||||
}
|
||||
@ -6,6 +6,7 @@ mod mod_creation;
|
||||
mod moderation;
|
||||
mod mods;
|
||||
mod not_found;
|
||||
mod notifications;
|
||||
mod reports;
|
||||
mod tags;
|
||||
mod teams;
|
||||
@ -65,8 +66,7 @@ pub fn users_config(cfg: &mut web::ServiceConfig) {
|
||||
.service(users::mods_list)
|
||||
.service(users::user_delete)
|
||||
.service(users::user_edit)
|
||||
.service(users::user_icon_edit)
|
||||
.service(users::teams),
|
||||
.service(users::user_icon_edit),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -299,6 +299,7 @@ async fn mod_create_inner(
|
||||
|
||||
check_length(3..=256, "mod name", &create_data.mod_name)?;
|
||||
check_length(3..=2048, "mod description", &create_data.mod_description)?;
|
||||
check_length(3..=64, "mod slug", &create_data.mod_slug)?;
|
||||
check_length(..65536, "mod body", &create_data.mod_body)?;
|
||||
|
||||
if create_data.categories.len() > 3 {
|
||||
@ -321,6 +322,12 @@ async fn mod_create_inner(
|
||||
if let Some(url) = &create_data.source_url {
|
||||
check_length(..=2048, "url", url)?;
|
||||
}
|
||||
if let Some(url) = &create_data.discord_url {
|
||||
check_length(..=2048, "url", url)?;
|
||||
}
|
||||
if let Some(url) = &create_data.license_url {
|
||||
check_length(..=2048, "url", url)?;
|
||||
}
|
||||
|
||||
create_data
|
||||
.initial_versions
|
||||
@ -565,6 +572,7 @@ async fn mod_create_inner(
|
||||
client_side: mod_create_data.client_side,
|
||||
server_side: mod_create_data.server_side,
|
||||
downloads: 0,
|
||||
followers: 0,
|
||||
categories: mod_create_data.categories,
|
||||
versions: mod_builder
|
||||
.initial_versions
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
use super::ApiError;
|
||||
use crate::auth::get_user_from_headers;
|
||||
use crate::database;
|
||||
use crate::file_hosting::FileHost;
|
||||
use crate::models;
|
||||
use crate::models::mods::{DonationLink, License, ModId, ModStatus, SearchRequest, SideType};
|
||||
use crate::models::teams::Permissions;
|
||||
use crate::routes::ApiError;
|
||||
use crate::search::indexing::queue::CreationQueue;
|
||||
use crate::search::{search_for_mod, SearchConfig, SearchError};
|
||||
use actix_web::web::Data;
|
||||
@ -214,6 +214,7 @@ pub fn convert_mod(data: database::models::mod_item::QueryMod) -> models::mods::
|
||||
client_side: data.client_side,
|
||||
server_side: data.server_side,
|
||||
downloads: m.downloads as u32,
|
||||
followers: m.follows as u32,
|
||||
categories: data.categories,
|
||||
versions: data.versions.into_iter().map(|v| v.into()).collect(),
|
||||
icon_url: m.icon_url,
|
||||
@ -333,6 +334,12 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if title.len() > 256 || title.len() < 3 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's title must be within 3-256 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -355,6 +362,12 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if description.len() > 2048 || description.len() < 3 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's description must be within 3-256 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -479,6 +492,14 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(issues) = issues_url {
|
||||
if issues.len() > 2048 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's issues url must be less than 2048 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -501,6 +522,14 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(source) = source_url {
|
||||
if source.len() > 2048 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's source url must be less than 2048 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -523,6 +552,14 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(wiki) = wiki_url {
|
||||
if wiki.len() > 2048 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's wiki url must be less than 2048 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -545,6 +582,14 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(license) = license_url {
|
||||
if license.len() > 2048 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's license url must be less than 2048 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -567,6 +612,14 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(discord) = discord_url {
|
||||
if discord.len() > 2048 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's discord url must be less than 2048 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -589,6 +642,12 @@ pub async fn mod_edit(
|
||||
}
|
||||
|
||||
if let Some(slug) = slug {
|
||||
if slug.len() > 64 || slug.len() < 3 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's slug must be within 3-64 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let slug_modid_option: Option<ModId> =
|
||||
serde_json::from_str(&*format!("\"{}\"", slug)).ok();
|
||||
if let Some(slug_modid) = slug_modid_option {
|
||||
@ -614,7 +673,7 @@ pub async fn mod_edit(
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
SET slug = $1
|
||||
SET slug = LOWER($1)
|
||||
WHERE (id = $2)
|
||||
",
|
||||
slug.as_deref(),
|
||||
@ -760,6 +819,12 @@ pub async fn mod_edit(
|
||||
));
|
||||
}
|
||||
|
||||
if body.len() > 65536 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The mod's body must be less than 65536 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
@ -921,6 +986,89 @@ pub async fn mod_delete(
|
||||
}
|
||||
}
|
||||
|
||||
#[get("{id}/follow")]
|
||||
pub async fn mod_follow(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(models::ids::ModId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
let id = info.into_inner().0;
|
||||
|
||||
let _result = database::models::Mod::get(id.into(), &**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?
|
||||
.ok_or_else(|| ApiError::InvalidInputError("Invalid Mod ID specified!".to_string()))?;
|
||||
|
||||
let user_id: database::models::ids::UserId = user.id.into();
|
||||
let mod_id: database::models::ids::ModId = id.into();
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
SET follows = follows + 1
|
||||
WHERE id = $1
|
||||
",
|
||||
mod_id as database::models::ids::ModId,
|
||||
)
|
||||
.execute(&**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO mod_follows (follower_id, mod_id)
|
||||
VALUES ($1, $2)
|
||||
",
|
||||
user_id as database::models::ids::UserId,
|
||||
mod_id as database::models::ids::ModId
|
||||
)
|
||||
.execute(&**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
}
|
||||
|
||||
#[delete("{id}/follow")]
|
||||
pub async fn mod_unfollow(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(models::ids::ModId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
let id = info.into_inner().0;
|
||||
|
||||
let user_id: database::models::ids::UserId = user.id.into();
|
||||
let mod_id: database::models::ids::ModId = id.into();
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
SET follows = follows - 1
|
||||
WHERE id = $1
|
||||
",
|
||||
mod_id as database::models::ids::ModId,
|
||||
)
|
||||
.execute(&**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM mod_follows
|
||||
WHERE follower_id = $1 AND mod_id = $2
|
||||
",
|
||||
user_id as database::models::ids::UserId,
|
||||
mod_id as database::models::ids::ModId
|
||||
)
|
||||
.execute(&**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
}
|
||||
|
||||
pub async fn delete_from_index(
|
||||
id: crate::models::mods::ModId,
|
||||
config: web::Data<SearchConfig>,
|
||||
|
||||
122
src/routes/notifications.rs
Normal file
122
src/routes/notifications.rs
Normal file
@ -0,0 +1,122 @@
|
||||
use crate::auth::get_user_from_headers;
|
||||
use crate::database;
|
||||
use crate::models::ids::NotificationId;
|
||||
use crate::models::notifications::{Notification, NotificationAction};
|
||||
use crate::routes::ApiError;
|
||||
use actix_web::{delete, get, web, HttpRequest, HttpResponse};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct NotificationIds {
|
||||
pub ids: String,
|
||||
}
|
||||
|
||||
#[get("notifications")]
|
||||
pub async fn notifications_get(
|
||||
req: HttpRequest,
|
||||
web::Query(ids): web::Query<NotificationIds>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
let notification_ids = serde_json::from_str::<Vec<NotificationId>>(&*ids.ids)?
|
||||
.into_iter()
|
||||
.map(|x| x.into())
|
||||
.collect();
|
||||
|
||||
let notifications_data =
|
||||
database::models::notification_item::Notification::get_many(notification_ids, &**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
let mut notifications: Vec<Notification> = Vec::new();
|
||||
|
||||
for notification in notifications_data {
|
||||
if notification.user_id == user.id.into() || user.role.is_mod() {
|
||||
notifications.push(convert_notification(notification));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(HttpResponse::Ok().json(notifications))
|
||||
}
|
||||
|
||||
#[get("{id}")]
|
||||
pub async fn notification_get(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(NotificationId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
let id = info.into_inner().0;
|
||||
|
||||
let notification_data =
|
||||
database::models::notification_item::Notification::get(id.into(), &**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
if let Some(data) = notification_data {
|
||||
if user.id == data.user_id.into() || user.role.is_mod() {
|
||||
Ok(HttpResponse::Ok().json(convert_notification(data)))
|
||||
} else {
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
} else {
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn convert_notification(
|
||||
notif: database::models::notification_item::Notification,
|
||||
) -> Notification {
|
||||
Notification {
|
||||
id: notif.id.into(),
|
||||
user_id: notif.user_id.into(),
|
||||
title: notif.title,
|
||||
text: notif.text,
|
||||
link: notif.link,
|
||||
read: notif.read,
|
||||
created: notif.created,
|
||||
actions: notif
|
||||
.actions
|
||||
.into_iter()
|
||||
.map(|x| NotificationAction {
|
||||
title: x.title,
|
||||
action_route: x.action_route,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[delete("{id}")]
|
||||
pub async fn notification_delete(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(NotificationId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
let id = info.into_inner().0;
|
||||
|
||||
let notification_data =
|
||||
database::models::notification_item::Notification::get(id.into(), &**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
if let Some(data) = notification_data {
|
||||
if data.user_id == user.id.into() || user.role.is_mod() {
|
||||
database::models::notification_item::Notification::remove(id.into(), &**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
} else {
|
||||
Err(ApiError::CustomAuthenticationError(
|
||||
"You are not authorized to delete this notification!".to_string(),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,7 @@
|
||||
use crate::auth::get_user_from_headers;
|
||||
use crate::database::models::notification_item::{NotificationActionBuilder, NotificationBuilder};
|
||||
use crate::database::models::TeamMember;
|
||||
use crate::models::ids::ModId;
|
||||
use crate::models::teams::{Permissions, TeamId};
|
||||
use crate::models::users::UserId;
|
||||
use crate::routes::ApiError;
|
||||
@ -196,6 +198,39 @@ pub async fn add_team_member(
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT m.title, m.id FROM mods m
|
||||
WHERE m.team_id = $1
|
||||
",
|
||||
team_id as crate::database::models::ids::TeamId
|
||||
)
|
||||
.fetch_one(&**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
let team: TeamId = team_id.into();
|
||||
NotificationBuilder {
|
||||
title: "You have been invited to join a team!".to_string(),
|
||||
text: format!(
|
||||
"Team invite from {} to join the team for mod {}",
|
||||
current_user.username, result.title
|
||||
),
|
||||
link: format!("mod/{}", ModId(result.id as u64)),
|
||||
actions: vec![
|
||||
NotificationActionBuilder {
|
||||
title: "Accept".to_string(),
|
||||
action_route: format!("team/{}/join", team),
|
||||
},
|
||||
NotificationActionBuilder {
|
||||
title: "Deny".to_string(),
|
||||
action_route: format!("team/{}/members/{}", team, new_member.user_id),
|
||||
},
|
||||
],
|
||||
}
|
||||
.insert(new_member.user_id.into(), &mut transaction)
|
||||
.await?;
|
||||
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
use crate::auth::get_user_from_headers;
|
||||
use crate::database::models::{TeamMember, User};
|
||||
use crate::database::models::User;
|
||||
use crate::file_hosting::FileHost;
|
||||
use crate::models::ids::NotificationId;
|
||||
use crate::models::notifications::Notification;
|
||||
use crate::models::users::{Role, UserId};
|
||||
use crate::routes::notifications::convert_notification;
|
||||
use crate::routes::ApiError;
|
||||
use actix_web::{delete, get, patch, web, HttpRequest, HttpResponse};
|
||||
use futures::StreamExt;
|
||||
@ -148,48 +151,6 @@ pub async fn mods_list(
|
||||
}
|
||||
}
|
||||
|
||||
#[get("{user_id}/teams")]
|
||||
pub async fn teams(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(UserId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let id: crate::database::models::UserId = info.into_inner().0.into();
|
||||
|
||||
let current_user = get_user_from_headers(req.headers(), &**pool).await.ok();
|
||||
|
||||
let results;
|
||||
let mut same_user = false;
|
||||
|
||||
if let Some(user) = current_user {
|
||||
if user.id.0 == id.0 as u64 {
|
||||
results = TeamMember::get_from_user_private(id, &**pool).await?;
|
||||
same_user = true;
|
||||
} else {
|
||||
results = TeamMember::get_from_user_public(id, &**pool).await?;
|
||||
}
|
||||
} else {
|
||||
results = TeamMember::get_from_user_public(id, &**pool).await?;
|
||||
}
|
||||
|
||||
let team_members: Vec<crate::models::teams::TeamMember> = results
|
||||
.into_iter()
|
||||
.map(|data| crate::models::teams::TeamMember {
|
||||
team_id: data.team_id.into(),
|
||||
user_id: data.user_id.into(),
|
||||
role: data.role,
|
||||
permissions: if same_user {
|
||||
Some(data.permissions)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
accepted: data.accepted,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(HttpResponse::Ok().json(team_members))
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct EditUser {
|
||||
pub username: Option<String>,
|
||||
@ -463,3 +424,63 @@ pub async fn user_delete(
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
}
|
||||
|
||||
#[get("{id}/follows")]
|
||||
pub async fn user_follows(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(UserId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
let id = info.into_inner().0;
|
||||
|
||||
if !user.role.is_mod() && user.id != id {
|
||||
return Err(ApiError::CustomAuthenticationError(
|
||||
"You do not have permission to see the mods this user follows!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
use futures::TryStreamExt;
|
||||
|
||||
let user_id: crate::database::models::UserId = id.into();
|
||||
let notifications: Vec<NotificationId> = sqlx::query!(
|
||||
"
|
||||
SELECT n.id FROM notifications n
|
||||
WHERE n.user_id = $1
|
||||
",
|
||||
user_id as crate::database::models::ids::UserId,
|
||||
)
|
||||
.fetch_many(&**pool)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|m| NotificationId(m.id as u64))) })
|
||||
.try_collect::<Vec<NotificationId>>()
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(notifications))
|
||||
}
|
||||
|
||||
#[get("{id}/notifications")]
|
||||
pub async fn user_notifications(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(UserId,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
let id = info.into_inner().0;
|
||||
|
||||
if !user.role.is_mod() && user.id != id {
|
||||
return Err(ApiError::CustomAuthenticationError(
|
||||
"You do not have permission to see the mods this user follows!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let notifications: Vec<Notification> =
|
||||
crate::database::models::notification_item::Notification::get_many_user(id.into(), &**pool)
|
||||
.await
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?
|
||||
.into_iter()
|
||||
.map(convert_notification)
|
||||
.collect();
|
||||
|
||||
Ok(HttpResponse::Ok().json(notifications))
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
use crate::auth::get_user_from_headers;
|
||||
use crate::database::models;
|
||||
use crate::database::models::notification_item::NotificationBuilder;
|
||||
use crate::database::models::version_item::{VersionBuilder, VersionFileBuilder};
|
||||
use crate::file_hosting::FileHost;
|
||||
use crate::models::mods::{
|
||||
@ -272,6 +273,49 @@ async fn version_create_inner(
|
||||
let builder = version_builder
|
||||
.ok_or_else(|| CreateError::InvalidInput("`data` field is required".to_string()))?;
|
||||
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT m.title FROM mods m
|
||||
WHERE id = $1
|
||||
",
|
||||
builder.mod_id as crate::database::models::ids::ModId
|
||||
)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
use futures::stream::TryStreamExt;
|
||||
|
||||
let users = sqlx::query!(
|
||||
"
|
||||
SELECT follower_id FROM mod_follows
|
||||
WHERE mod_id = $1
|
||||
",
|
||||
builder.mod_id as crate::database::models::ids::ModId
|
||||
)
|
||||
.fetch_many(&mut *transaction)
|
||||
.try_filter_map(|e| async {
|
||||
Ok(e.right()
|
||||
.map(|m| crate::database::models::ids::UserId(m.follower_id)))
|
||||
})
|
||||
.try_collect::<Vec<crate::database::models::ids::UserId>>()
|
||||
.await?;
|
||||
|
||||
let mod_id: ModId = builder.mod_id.into();
|
||||
let version_id: VersionId = builder.version_id.into();
|
||||
|
||||
NotificationBuilder {
|
||||
title: "A mod you followed has been updated!".to_string(),
|
||||
text: format!(
|
||||
"Mod {} has been updated to version {}",
|
||||
result.title,
|
||||
version_data.version_number.clone()
|
||||
),
|
||||
link: format!("mod/{}/version/{}", mod_id, version_id),
|
||||
actions: vec![],
|
||||
}
|
||||
.insert_many(users, &mut *transaction)
|
||||
.await?;
|
||||
|
||||
let response = Version {
|
||||
id: builder.version_id.into(),
|
||||
mod_id: builder.mod_id.into(),
|
||||
|
||||
@ -257,6 +257,12 @@ pub async fn version_edit(
|
||||
.map_err(|e| ApiError::DatabaseError(e.into()))?;
|
||||
|
||||
if let Some(name) = &new_version.name {
|
||||
if name.len() > 256 || name.len() < 3 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The version name must be within 3-256 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE versions
|
||||
@ -272,6 +278,12 @@ pub async fn version_edit(
|
||||
}
|
||||
|
||||
if let Some(number) = &new_version.version_number {
|
||||
if number.len() > 64 || number.is_empty() {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The version number must be within 1-64 characters!".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE versions
|
||||
@ -432,8 +444,8 @@ pub async fn version_edit(
|
||||
if let Some(primary_file) = &new_version.primary_file {
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT id FROM files
|
||||
INNER JOIN hashes ON hash = $1 AND algorithm = $2
|
||||
SELECT f.id FROM files f
|
||||
INNER JOIN hashes h ON h.hash = $1 AND h.algorithm = $2
|
||||
",
|
||||
primary_file.1.as_bytes(),
|
||||
primary_file.0
|
||||
@ -474,6 +486,13 @@ pub async fn version_edit(
|
||||
}
|
||||
|
||||
if let Some(body) = &new_version.changelog {
|
||||
if body.len() > 65536 {
|
||||
return Err(ApiError::InvalidInputError(
|
||||
"The version changelog must be less than 65536 characters long!"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE versions
|
||||
@ -648,13 +667,13 @@ pub async fn download_version(
|
||||
if !download_exists {
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO downloads (
|
||||
version_id, identifier
|
||||
)
|
||||
VALUES (
|
||||
$1, $2
|
||||
)
|
||||
",
|
||||
INSERT INTO downloads (
|
||||
version_id, identifier
|
||||
)
|
||||
VALUES (
|
||||
$1, $2
|
||||
)
|
||||
",
|
||||
id.version_id,
|
||||
hash
|
||||
)
|
||||
@ -664,10 +683,10 @@ pub async fn download_version(
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE versions
|
||||
SET downloads = downloads + 1
|
||||
WHERE id = $1
|
||||
",
|
||||
UPDATE versions
|
||||
SET downloads = downloads + 1
|
||||
WHERE id = $1
|
||||
",
|
||||
id.version_id,
|
||||
)
|
||||
.execute(&**pool)
|
||||
@ -676,10 +695,10 @@ pub async fn download_version(
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE mods
|
||||
SET downloads = downloads + 1
|
||||
WHERE id = $1
|
||||
",
|
||||
UPDATE mods
|
||||
SET downloads = downloads + 1
|
||||
WHERE id = $1
|
||||
",
|
||||
id.mod_id,
|
||||
)
|
||||
.execute(&**pool)
|
||||
|
||||
@ -15,7 +15,7 @@ pub async fn index_local(pool: PgPool) -> Result<Vec<UploadSearchMod>, IndexingE
|
||||
|
||||
let mut mods = sqlx::query!(
|
||||
"
|
||||
SELECT m.id, m.title, m.description, m.downloads, m.icon_url, m.body_url, m.published, m.updated, m.team_id, m.status, m.slug, m.license, m.client_side, m.server_side FROM mods m
|
||||
SELECT m.id, m.title, m.description, m.downloads, m.follows, m.icon_url, m.body_url, m.published, m.updated, m.team_id, m.status, m.slug, m.license, m.client_side, m.server_side FROM mods m
|
||||
"
|
||||
).fetch(&pool);
|
||||
|
||||
@ -55,7 +55,7 @@ pub async fn index_local(pool: PgPool) -> Result<Vec<UploadSearchMod>, IndexingE
|
||||
|
||||
let loaders = sqlx::query!(
|
||||
"
|
||||
SELECT loaders.loader FROM versions
|
||||
SELECT DISTINCT loaders.loader FROM versions
|
||||
INNER JOIN loaders_versions lv ON lv.version_id = versions.id
|
||||
INNER JOIN loaders ON loaders.id = lv.loader_id
|
||||
WHERE versions.mod_id = $1
|
||||
@ -151,6 +151,7 @@ pub async fn index_local(pool: PgPool) -> Result<Vec<UploadSearchMod>, IndexingE
|
||||
description: mod_data.description,
|
||||
categories,
|
||||
versions,
|
||||
follows: mod_data.follows,
|
||||
downloads: mod_data.downloads,
|
||||
page_url: format!("https://modrinth.com/mod/{}", mod_id),
|
||||
icon_url,
|
||||
@ -179,7 +180,7 @@ pub async fn query_one(
|
||||
) -> Result<UploadSearchMod, IndexingError> {
|
||||
let mod_data = sqlx::query!(
|
||||
"
|
||||
SELECT m.id, m.title, m.description, m.downloads, m.icon_url, m.body_url, m.published, m.updated, m.team_id, m.slug, m.license, m.client_side, m.server_side
|
||||
SELECT m.id, m.title, m.description, m.downloads, m.follows, m.icon_url, m.body_url, m.published, m.updated, m.team_id, m.slug, m.license, m.client_side, m.server_side
|
||||
FROM mods m
|
||||
WHERE id = $1
|
||||
",
|
||||
@ -203,7 +204,7 @@ pub async fn query_one(
|
||||
|
||||
let loaders = sqlx::query!(
|
||||
"
|
||||
SELECT loaders.loader FROM versions
|
||||
SELECT DISTINCT loaders.loader FROM versions
|
||||
INNER JOIN loaders_versions lv ON lv.version_id = versions.id
|
||||
INNER JOIN loaders ON loaders.id = lv.loader_id
|
||||
WHERE versions.mod_id = $1
|
||||
@ -299,6 +300,7 @@ pub async fn query_one(
|
||||
description: mod_data.description,
|
||||
categories,
|
||||
versions,
|
||||
follows: mod_data.follows,
|
||||
downloads: mod_data.downloads,
|
||||
page_url: format!("https://modrinth.com/mod/{}", mod_id),
|
||||
icon_url,
|
||||
|
||||
@ -8,7 +8,7 @@ use meilisearch_sdk::client::Client;
|
||||
use meilisearch_sdk::indexes::Index;
|
||||
use meilisearch_sdk::settings::Settings;
|
||||
use sqlx::postgres::PgPool;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::collections::VecDeque;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
@ -100,6 +100,14 @@ pub async fn reconfigure_indices(config: &SearchConfig) -> Result<(), IndexingEr
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Follows Index
|
||||
update_index(&client, "follows_mods", {
|
||||
let mut follows_rules = default_rules();
|
||||
follows_rules.push_front("desc(follows)".to_string());
|
||||
follows_rules.into()
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Updated Index
|
||||
update_index(&client, "updated_mods", {
|
||||
let mut updated_rules = default_rules();
|
||||
@ -242,6 +250,7 @@ fn default_settings() -> Settings {
|
||||
"categories".to_string(),
|
||||
"versions".to_string(),
|
||||
"downloads".to_string(),
|
||||
"follows".to_string(),
|
||||
"page_url".to_string(),
|
||||
"icon_url".to_string(),
|
||||
"author_url".to_string(),
|
||||
@ -262,8 +271,6 @@ fn default_settings() -> Settings {
|
||||
Settings::new()
|
||||
.with_displayed_attributes(displayed_attributes)
|
||||
.with_searchable_attributes(searchable_attributes)
|
||||
.with_stop_words(vec![])
|
||||
.with_synonyms(HashMap::new())
|
||||
.with_attributes_for_faceting(vec![
|
||||
String::from("categories"),
|
||||
String::from("host"),
|
||||
|
||||
@ -68,6 +68,7 @@ pub struct UploadSearchMod {
|
||||
pub description: String,
|
||||
pub categories: Vec<Cow<'static, str>>,
|
||||
pub versions: Vec<String>,
|
||||
pub follows: i32,
|
||||
pub downloads: i32,
|
||||
pub page_url: String,
|
||||
pub icon_url: String,
|
||||
@ -160,6 +161,7 @@ pub async fn search_for_mod(
|
||||
let index = match index {
|
||||
"relevance" => "relevance_mods",
|
||||
"downloads" => "downloads_mods",
|
||||
"follows" => "follows_mods",
|
||||
"updated" => "updated_mods",
|
||||
"newest" => "newest_mods",
|
||||
i => return Err(SearchError::InvalidIndex(i.to_string())),
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user