Overhaul notifs + threads fixes (#573)

* Overhaul notifs + threads fixes

* fix lang
This commit is contained in:
Geometrically
2023-04-15 19:48:21 -07:00
committed by GitHub
parent 969eb67217
commit 95ae981698
12 changed files with 719 additions and 619 deletions

View File

@@ -1,31 +1,19 @@
use super::ids::*;
use crate::database::models::DatabaseError;
use crate::models::notifications::NotificationBody;
use chrono::{DateTime, Utc};
use serde::Deserialize;
pub struct NotificationBuilder {
pub notification_type: Option<String>,
pub title: String,
pub text: String,
pub link: String,
pub actions: Vec<NotificationActionBuilder>,
}
pub struct NotificationActionBuilder {
pub title: String,
pub action_route: (String, String),
pub body: NotificationBody,
}
pub struct Notification {
pub id: NotificationId,
pub user_id: UserId,
pub notification_type: Option<String>,
pub title: String,
pub text: String,
pub link: String,
pub body: NotificationBody,
pub read: bool,
pub created: DateTime<Utc>,
pub actions: Vec<NotificationAction>,
}
#[derive(Deserialize)]
@@ -54,28 +42,12 @@ impl NotificationBuilder {
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_method: action.action_route.0.clone(),
action_route: action.action_route.1.clone(),
})
}
Notification {
id,
user_id: user,
notification_type: self.notification_type.clone(),
title: self.title.clone(),
text: self.text.clone(),
link: self.link.clone(),
body: self.body.clone(),
read: false,
created: Utc::now(),
actions,
}
.insert(&mut *transaction)
.await?;
@@ -89,30 +61,23 @@ impl Notification {
pub async fn insert(
&self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
) -> Result<(), sqlx::error::Error> {
) -> Result<(), DatabaseError> {
sqlx::query!(
"
INSERT INTO notifications (
id, user_id, title, text, link, type
id, user_id, body
)
VALUES (
$1, $2, $3, $4, $5, $6
$1, $2, $3
)
",
self.id as NotificationId,
self.user_id as UserId,
&self.title,
&self.text,
&self.link,
self.notification_type
serde_json::value::to_value(self.body.clone())?
)
.execute(&mut *transaction)
.await?;
for action in &self.actions {
action.insert(&mut *transaction).await?;
}
Ok(())
}
@@ -141,7 +106,7 @@ impl Notification {
notification_ids.iter().map(|x| x.0).collect();
sqlx::query!(
"
SELECT n.id, n.user_id, n.title, n.text, n.link, n.created, n.read, n.type notification_type,
SELECT n.id, n.user_id, n.title, n.text, n.link, n.created, n.read, n.type notification_type, n.body,
JSONB_AGG(DISTINCT jsonb_build_object('id', na.id, 'notification_id', na.notification_id, 'title', na.title, 'action_route_method', na.action_route_method, 'action_route', na.action_route)) filter (where na.id is not null) actions
FROM notifications n
LEFT OUTER JOIN notifications_actions na on n.id = na.notification_id
@@ -159,17 +124,25 @@ impl Notification {
Notification {
id,
user_id: UserId(row.user_id),
notification_type: row.notification_type,
title: row.title,
text: row.text,
link: row.link,
read: row.read,
created: row.created,
actions: serde_json::from_value(
row.actions.unwrap_or_default(),
)
.ok()
.unwrap_or_default(),
body: row.body.clone().and_then(|x| serde_json::from_value(x).ok()).unwrap_or_else(|| {
if let Some(title) = row.title {
NotificationBody::LegacyMarkdown {
notification_type: row.notification_type,
title,
text: row.text.unwrap_or_default(),
link: row.link.unwrap_or_default(),
actions: serde_json::from_value(
row.actions.unwrap_or_default(),
)
.ok()
.unwrap_or_default(),
}
} else {
NotificationBody::Unknown
}
}),
}
}))
})
@@ -188,7 +161,7 @@ impl Notification {
sqlx::query!(
"
SELECT n.id, n.user_id, n.title, n.text, n.link, n.created, n.read, n.type notification_type,
SELECT n.id, n.user_id, n.title, n.text, n.link, n.created, n.read, n.type notification_type, n.body,
JSONB_AGG(DISTINCT jsonb_build_object('id', na.id, 'notification_id', na.notification_id, 'title', na.title, 'action_route_method', na.action_route_method, 'action_route', na.action_route)) filter (where na.id is not null) actions
FROM notifications n
LEFT OUTER JOIN notifications_actions na on n.id = na.notification_id
@@ -205,17 +178,25 @@ impl Notification {
Notification {
id,
user_id: UserId(row.user_id),
notification_type: row.notification_type,
title: row.title,
text: row.text,
link: row.link,
read: row.read,
created: row.created,
actions: serde_json::from_value(
row.actions.unwrap_or_default(),
)
.ok()
.unwrap_or_default(),
body: row.body.clone().and_then(|x| serde_json::from_value(x).ok()).unwrap_or_else(|| {
if let Some(title) = row.title {
NotificationBody::LegacyMarkdown {
notification_type: row.notification_type,
title,
text: row.text.unwrap_or_default(),
link: row.link.unwrap_or_default(),
actions: serde_json::from_value(
row.actions.unwrap_or_default(),
)
.ok()
.unwrap_or_default(),
}
} else {
NotificationBody::Unknown
}
}),
}
}))
})
@@ -260,29 +241,3 @@ impl Notification {
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, action_route_method
)
VALUES (
$1, $2, $3, $4
)
",
self.notification_id as NotificationId,
&self.title,
&self.action_route,
&self.action_route_method
)
.execute(&mut *transaction)
.await?;
Ok(())
}
}

View File

@@ -7,6 +7,8 @@ use serde::Deserialize;
pub struct ThreadBuilder {
pub type_: ThreadType,
pub members: Vec<UserId>,
pub project_id: Option<ProjectId>,
pub report_id: Option<ReportId>,
}
#[derive(Clone)]
@@ -15,13 +17,15 @@ pub struct Thread {
pub type_: ThreadType,
pub messages: Vec<ThreadMessage>,
pub members: Vec<UserId>,
pub show_in_mod_inbox: bool,
pub project_id: Option<ProjectId>,
pub report_id: Option<ReportId>,
}
pub struct ThreadMessageBuilder {
pub author_id: Option<UserId>,
pub body: MessageBody,
pub thread_id: ThreadId,
pub show_in_mod_inbox: bool,
}
#[derive(Deserialize, Clone)]
@@ -31,7 +35,6 @@ pub struct ThreadMessage {
pub author_id: Option<UserId>,
pub body: MessageBody,
pub created: DateTime<Utc>,
pub show_in_mod_inbox: bool,
}
impl ThreadMessageBuilder {
@@ -45,17 +48,16 @@ impl ThreadMessageBuilder {
sqlx::query!(
"
INSERT INTO threads_messages (
id, author_id, body, thread_id, show_in_mod_inbox
id, author_id, body, thread_id
)
VALUES (
$1, $2, $3, $4, $5
$1, $2, $3, $4
)
",
thread_message_id as ThreadMessageId,
self.author_id.map(|x| x.0),
serde_json::value::to_value(self.body.clone())?,
self.thread_id as ThreadId,
self.show_in_mod_inbox,
)
.execute(&mut *transaction)
.await?;
@@ -133,9 +135,9 @@ impl Thread {
thread_ids.iter().map(|x| x.0).collect();
let threads = sqlx::query!(
"
SELECT t.id, t.thread_type,
SELECT t.id, t.thread_type, t.show_in_mod_inbox, t.project_id, t.report_id,
ARRAY_AGG(DISTINCT tm.user_id) filter (where tm.user_id is not null) members,
JSONB_AGG(DISTINCT jsonb_build_object('id', tmsg.id, 'author_id', tmsg.author_id, 'thread_id', tmsg.thread_id, 'body', tmsg.body, 'created', tmsg.created, 'show_in_mod_inbox', tmsg.show_in_mod_inbox)) filter (where tmsg.id is not null) messages
JSONB_AGG(DISTINCT jsonb_build_object('id', tmsg.id, 'author_id', tmsg.author_id, 'thread_id', tmsg.thread_id, 'body', tmsg.body, 'created', tmsg.created)) filter (where tmsg.id is not null) messages
FROM threads t
LEFT OUTER JOIN threads_messages tmsg ON tmsg.thread_id = t.id
LEFT OUTER JOIN threads_members tm ON tm.thread_id = t.id
@@ -159,6 +161,9 @@ impl Thread {
messages
},
members: x.members.unwrap_or_default().into_iter().map(UserId).collect(),
show_in_mod_inbox: x.show_in_mod_inbox,
project_id: x.project_id.map(ProjectId),
report_id: x.report_id.map(ReportId),
}))
})
.try_collect::<Vec<Thread>>()
@@ -229,7 +234,7 @@ impl ThreadMessage {
message_ids.iter().map(|x| x.0).collect();
let messages = sqlx::query!(
"
SELECT tm.id, tm.author_id, tm.thread_id, tm.body, tm.created, tm.show_in_mod_inbox
SELECT tm.id, tm.author_id, tm.thread_id, tm.body, tm.created
FROM threads_messages tm
WHERE tm.id = ANY($1)
",
@@ -244,7 +249,6 @@ impl ThreadMessage {
body: serde_json::from_value(x.body)
.unwrap_or(MessageBody::Deleted),
created: x.created,
show_in_mod_inbox: x.show_in_mod_inbox,
}))
})
.try_collect::<Vec<ThreadMessage>>()
@@ -259,10 +263,13 @@ impl ThreadMessage {
) -> Result<Option<()>, sqlx::error::Error> {
sqlx::query!(
"
DELETE FROM threads_messages
UPDATE threads_messages
SET body = $2
WHERE id = $1
",
id as ThreadMessageId,
serde_json::to_value(MessageBody::Deleted)
.unwrap_or(serde_json::json!({}))
)
.execute(&mut *transaction)
.await?;

View File

@@ -1,5 +1,11 @@
use super::ids::Base62Id;
use super::users::UserId;
use crate::database::models::notification_item::Notification as DBNotification;
use crate::database::models::notification_item::NotificationAction as DBNotificationAction;
use crate::models::ids::{
ProjectId, ReportId, TeamId, ThreadId, ThreadMessageId, VersionId,
};
use crate::models::projects::ProjectStatus;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
@@ -13,35 +19,176 @@ pub struct Notification {
pub id: NotificationId,
pub user_id: UserId,
#[serde(rename = "type")]
pub read: bool,
pub created: DateTime<Utc>,
pub body: NotificationBody,
// DEPRECATED: use body field instead
pub type_: Option<String>,
pub title: String,
pub text: String,
pub link: String,
pub read: bool,
pub created: DateTime<Utc>,
pub actions: Vec<NotificationAction>,
}
use crate::database::models::notification_item::Notification as DBNotification;
use crate::database::models::notification_item::NotificationAction as DBNotificationAction;
#[derive(Serialize, Deserialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NotificationBody {
ProjectUpdate {
project_id: ProjectId,
version_id: VersionId,
},
TeamInvite {
project_id: ProjectId,
team_id: TeamId,
invited_by: UserId,
role: String,
},
StatusChange {
project_id: ProjectId,
old_status: ProjectStatus,
new_status: ProjectStatus,
},
ModeratorMessage {
thread_id: ThreadId,
message_id: ThreadMessageId,
project_id: Option<ProjectId>,
report_id: Option<ReportId>,
},
LegacyMarkdown {
notification_type: Option<String>,
title: String,
text: String,
link: String,
actions: Vec<NotificationAction>,
},
Unknown,
}
impl From<DBNotification> for Notification {
fn from(notif: DBNotification) -> Self {
let (type_, title, text, link, actions) = {
match &notif.body {
NotificationBody::ProjectUpdate {
project_id,
version_id,
} => (
Some("project_update".to_string()),
"A project you follow has been updated!".to_string(),
format!(
"The project {} has released a new version: {}",
project_id, version_id
),
format!("/project/{}/version/{}", project_id, version_id),
vec![],
),
NotificationBody::TeamInvite {
project_id,
role,
team_id,
..
} => (
Some("team_invite".to_string()),
"You have been invited to join a team!".to_string(),
format!(
"An invite has been sent for you to be {} of a team",
role
),
format!("/project/{}", project_id),
vec![
NotificationAction {
title: "Accept".to_string(),
action_route: (
"POST".to_string(),
format!("team/{team_id}/join"),
),
},
NotificationAction {
title: "Deny".to_string(),
action_route: (
"DELETE".to_string(),
format!(
"team/{team_id}/members/{}",
UserId::from(notif.user_id)
),
),
},
],
),
NotificationBody::StatusChange {
old_status,
new_status,
project_id,
} => (
Some("status_change".to_string()),
"Project status has changed".to_string(),
format!(
"Status has changed from {} to {}",
old_status.as_friendly_str(),
new_status.as_friendly_str()
),
format!("/project/{}", project_id),
vec![],
),
NotificationBody::ModeratorMessage {
project_id,
report_id,
..
} => (
Some("moderator_message".to_string()),
"A moderator has sent you a message!".to_string(),
"Click on the link to read more.".to_string(),
if let Some(project_id) = project_id {
format!("/project/{}", project_id)
} else if let Some(report_id) = report_id {
format!("/project/{}", report_id)
} else {
"#".to_string()
},
vec![],
),
NotificationBody::LegacyMarkdown {
notification_type,
title,
text,
link,
actions,
} => (
notification_type.clone(),
title.clone(),
text.clone(),
link.clone(),
actions.clone().into_iter().map(Into::into).collect(),
),
NotificationBody::Unknown => (
None,
"".to_string(),
"".to_string(),
"#".to_string(),
vec![],
),
}
};
Self {
id: notif.id.into(),
user_id: notif.user_id.into(),
type_: notif.notification_type,
title: notif.title,
text: notif.text,
link: notif.link,
body: notif.body,
read: notif.read,
created: notif.created,
actions: notif.actions.into_iter().map(Into::into).collect(),
// DEPRECATED
type_,
title,
text,
link,
actions,
}
}
}
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct NotificationAction {
pub title: String,
/// The route to call when this notification action is called. Formatted HTTP Method, route

View File

@@ -1,4 +1,5 @@
use super::ids::Base62Id;
use crate::models::ids::{ProjectId, ReportId};
use crate::models::projects::ProjectStatus;
use crate::models::users::{User, UserId};
use chrono::{DateTime, Utc};
@@ -21,6 +22,9 @@ pub struct Thread {
pub type_: ThreadType,
pub messages: Vec<ThreadMessage>,
pub members: Vec<User>,
pub project_id: Option<ProjectId>,
pub report_id: Option<ReportId>,
}
#[derive(Serialize, Deserialize)]
@@ -45,6 +49,7 @@ pub enum MessageBody {
old_status: ProjectStatus,
},
ThreadClosure,
ThreadReopen,
Deleted,
}

View File

@@ -759,6 +759,8 @@ async fn project_create_inner(
let thread_id = ThreadBuilder {
type_: ThreadType::Project,
members: vec![],
project_id: Some(project_id.into()),
report_id: None,
}
.insert(&mut *transaction)
.await?;

View File

@@ -4,6 +4,7 @@ use crate::database::models::thread_item::ThreadMessageBuilder;
use crate::file_hosting::FileHost;
use crate::models;
use crate::models::ids::base62_impl::parse_base62;
use crate::models::notifications::NotificationBody;
use crate::models::projects::{
DonationLink, Project, ProjectId, ProjectStatus, SearchRequest, SideType,
};
@@ -615,23 +616,11 @@ pub async fn project_edit(
.await?;
NotificationBuilder {
notification_type: Some("status_update".to_string()),
title: format!(
"**{}**'s status has changed!",
project_item.inner.title
),
text: format!(
"The project {}'s status has changed from {} to {}",
project_item.inner.title,
project_item.inner.status.as_friendly_str(),
status.as_friendly_str()
),
link: format!(
"/{}/{}",
project_item.project_type,
ProjectId::from(id)
),
actions: vec![],
body: NotificationBody::StatusChange {
project_id: project_item.inner.id.into(),
old_status: project_item.inner.status,
new_status: *status,
},
}
.insert_many(notified_members, &mut transaction)
.await?;
@@ -645,7 +634,6 @@ pub async fn project_edit(
old_status: project_item.inner.status,
},
thread_id: thread,
show_in_mod_inbox: false,
}
.insert(&mut transaction)
.await?;

View File

@@ -71,6 +71,8 @@ pub async fn report_create(
let thread_id = ThreadBuilder {
type_: ThreadType::Report,
members: vec![],
project_id: None,
report_id: Some(id),
}
.insert(&mut transaction)
.await?;
@@ -314,7 +316,7 @@ pub async fn report_edit(
}
if let Some(edit_closed) = edit_report.closed {
if report.closed && !edit_closed && !user.role.is_mod() {
if !user.role.is_mod() {
return Err(ApiError::InvalidInput(
"You cannot reopen a report!".to_string(),
));
@@ -323,9 +325,12 @@ pub async fn report_edit(
if let Some(thread) = report.thread_id {
ThreadMessageBuilder {
author_id: Some(user.id.into()),
body: MessageBody::ThreadClosure,
body: if !edit_closed && report.closed {
MessageBody::ThreadReopen
} else {
MessageBody::ThreadClosure
},
thread_id: thread,
show_in_mod_inbox: false,
}
.insert(&mut transaction)
.await?;

View File

@@ -1,8 +1,7 @@
use crate::database::models::notification_item::{
NotificationActionBuilder, NotificationBuilder,
};
use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::TeamMember;
use crate::models::ids::ProjectId;
use crate::models::notifications::NotificationBody;
use crate::models::teams::{Permissions, TeamId};
use crate::models::users::UserId;
use crate::routes::ApiError;
@@ -333,9 +332,8 @@ pub async fn add_team_member(
let result = sqlx::query!(
"
SELECT m.title title, m.id id, pt.name project_type
SELECT m.id
FROM mods m
INNER JOIN project_types pt ON pt.id = m.project_type
WHERE m.team_id = $1
",
team_id as crate::database::models::ids::TeamId
@@ -343,32 +341,13 @@ pub async fn add_team_member(
.fetch_one(&**pool)
.await?;
let team: TeamId = team_id.into();
NotificationBuilder {
notification_type: Some("team_invite".to_string()),
title: "You have been invited to join a team!".to_string(),
text: format!(
"Team invite from {} to join the team for project {}",
current_user.username, result.title
),
link: format!(
"/{}/{}",
result.project_type,
ProjectId(result.id as u64)
),
actions: vec![
NotificationActionBuilder {
title: "Accept".to_string(),
action_route: ("POST".to_string(), format!("team/{team}/join")),
},
NotificationActionBuilder {
title: "Deny".to_string(),
action_route: (
"DELETE".to_string(),
format!("team/{team}/members/{}", new_member.user_id),
),
},
],
body: NotificationBody::TeamInvite {
project_id: ProjectId(result.id as u64),
team_id: team_id.into(),
invited_by: current_user.id,
role: new_member.role.clone(),
},
}
.insert(new_member.user_id.into(), &mut transaction)
.await?;

View File

@@ -1,7 +1,9 @@
use crate::database;
use crate::database::models::notification_item::NotificationBuilder;
use crate::database::models::thread_item::ThreadMessageBuilder;
use crate::models::ids::ThreadMessageId;
use crate::models::projects::ProjectStatus;
use crate::models::ids::{ReportId, ThreadMessageId};
use crate::models::notifications::NotificationBody;
use crate::models::projects::{ProjectId, ProjectStatus};
use crate::models::threads::{
MessageBody, Thread, ThreadId, ThreadMessage, ThreadType,
};
@@ -11,6 +13,7 @@ use crate::util::auth::{
check_is_moderator_from_headers, get_user_from_headers,
};
use actix_web::{delete, get, post, web, HttpRequest, HttpResponse};
use futures::TryStreamExt;
use serde::Deserialize;
use sqlx::PgPool;
@@ -19,7 +22,8 @@ pub fn config(cfg: &mut web::ServiceConfig) {
web::scope("thread")
.service(moderation_inbox)
.service(thread_get)
.service(thread_send_message),
.service(thread_send_message)
.service(thread_read),
);
cfg.service(web::scope("message").service(message_delete));
cfg.service(threads_get);
@@ -86,8 +90,6 @@ pub async fn filter_authorized_threads(
}
if !check_threads.is_empty() {
use futures::TryStreamExt;
let project_thread_ids = check_threads
.iter()
.filter(|x| x.type_ == ThreadType::Project)
@@ -248,6 +250,8 @@ fn convert_thread(
.into_iter()
.filter(|x| !x.role.is_mod() || user.role.is_mod())
.collect(),
project_id: data.project_id.map(ProjectId::from),
report_id: data.report_id.map(ReportId::from),
}
}
@@ -384,30 +388,93 @@ pub async fn thread_send_message(
return Ok(HttpResponse::NotFound().body(""));
}
let mod_notif = if thread.type_ == ThreadType::Project {
let status = sqlx::query!(
"SELECT m.status FROM mods m WHERE thread_id = $1",
let report = if let Some(report) = thread.report_id {
database::models::report_item::Report::get(report, &**pool).await?
} else {
None
};
if report.as_ref().map(|x| x.closed).unwrap_or(false)
&& !user.role.is_mod()
{
return Err(ApiError::InvalidInput(
"You may not reply to a closed report".to_string(),
));
}
let (mod_notif, (user_notif, team_id)) = if thread.type_
== ThreadType::Project
{
let record = sqlx::query!(
"SELECT m.status, m.team_id FROM mods m WHERE thread_id = $1",
thread.id as database::models::ids::ThreadId,
)
.fetch_one(&**pool)
.await?;
let status = ProjectStatus::from_str(&status.status);
let status = ProjectStatus::from_str(&record.status);
status == ProjectStatus::Processing && !user.role.is_mod()
(
status == ProjectStatus::Processing && !user.role.is_mod(),
(
status != ProjectStatus::Processing && user.role.is_mod(),
Some(record.team_id),
),
)
} else {
false
(false, (thread.type_ == ThreadType::Report, None))
};
let mut transaction = pool.begin().await?;
ThreadMessageBuilder {
sqlx::query!(
"
UPDATE threads
SET show_in_mod_inbox = $1
WHERE id = $2
",
mod_notif,
thread.id.0,
)
.execute(&mut *transaction)
.await?;
let id = ThreadMessageBuilder {
author_id: Some(user.id.into()),
body: new_message.body.clone(),
thread_id: thread.id,
show_in_mod_inbox: mod_notif,
}
.insert(&mut transaction)
.await?;
if user_notif {
let users_to_notify = if let Some(team_id) = team_id {
let members = database::models::TeamMember::get_from_team_full(
database::models::TeamId(team_id),
&**pool,
)
.await?;
members.into_iter().map(|x| x.user.id).collect()
} else if let Some(report) = report {
vec![report.reporter]
} else {
vec![]
};
if !users_to_notify.is_empty() {
NotificationBuilder {
body: NotificationBody::ModeratorMessage {
thread_id: thread.id.into(),
message_id: id.into(),
project_id: thread.project_id.map(ProjectId::from),
report_id: thread.report_id.map(ReportId::from),
},
}
.insert_many(users_to_notify, &mut transaction)
.await?;
}
}
transaction.commit().await?;
Ok(HttpResponse::NoContent().body(""))
@@ -421,36 +488,33 @@ pub async fn moderation_inbox(
req: HttpRequest,
pool: web::Data<PgPool>,
) -> Result<HttpResponse, ApiError> {
check_is_moderator_from_headers(req.headers(), &**pool).await?;
let user = check_is_moderator_from_headers(req.headers(), &**pool).await?;
let messages = sqlx::query!(
let ids = sqlx::query!(
"
SELECT tm.id, tm.thread_id, tm.author_id, tm.body, tm.created, m.id project_id FROM threads_messages tm
INNER JOIN mods m ON m.thread_id = tm.thread_id
WHERE tm.show_in_mod_inbox = TRUE
SELECT id
FROM threads
WHERE show_in_mod_inbox = TRUE
"
)
.fetch_all(&**pool)
.await?
.into_iter()
.map(|x| serde_json::json! ({
"message": ThreadMessage {
id: ThreadMessageId(x.id as u64),
author_id: x.author_id.map(|x| crate::models::users::UserId(x as u64)),
body: serde_json::from_value(x.body).unwrap_or(MessageBody::Deleted),
created: x.created
},
"project_id": crate::models::projects::ProjectId(x.project_id as u64),
}))
.collect::<Vec<_>>();
.fetch_many(&**pool)
.try_filter_map(|e| async {
Ok(e.right().map(|m| database::models::ThreadId(m.id)))
})
.try_collect::<Vec<database::models::ThreadId>>()
.await?;
Ok(HttpResponse::Ok().json(messages))
let threads_data =
database::models::Thread::get_many(&ids, &**pool).await?;
let threads = filter_authorized_threads(threads_data, &user, &pool).await?;
Ok(HttpResponse::Ok().json(threads))
}
#[post("{id}/read")]
pub async fn read_message(
pub async fn thread_read(
req: HttpRequest,
info: web::Path<(ThreadMessageId,)>,
info: web::Path<(ThreadId,)>,
pool: web::Data<PgPool>,
) -> Result<HttpResponse, ApiError> {
check_is_moderator_from_headers(req.headers(), &**pool).await?;
@@ -460,7 +524,7 @@ pub async fn read_message(
sqlx::query!(
"
UPDATE threads_messages
UPDATE threads
SET show_in_mod_inbox = FALSE
WHERE id = $1
",

View File

@@ -5,6 +5,7 @@ use crate::database::models::version_item::{
DependencyBuilder, VersionBuilder, VersionFileBuilder,
};
use crate::file_hosting::FileHost;
use crate::models::notifications::NotificationBody;
use crate::models::pack::PackFileHash;
use crate::models::projects::{
Dependency, DependencyType, FileType, GameVersion, Loader, ProjectId,
@@ -377,18 +378,6 @@ async fn version_create_inner(
));
}
let result = sqlx::query!(
"
SELECT m.title title, pt.name project_type
FROM mods m
INNER JOIN project_types pt ON pt.id = m.project_type
WHERE m.id = $1
",
builder.project_id as crate::database::models::ids::ProjectId
)
.fetch_one(&mut *transaction)
.await?;
use futures::stream::TryStreamExt;
let users = sqlx::query!(
@@ -409,18 +398,10 @@ async fn version_create_inner(
let version_id: VersionId = builder.version_id.into();
NotificationBuilder {
notification_type: Some("project_update".to_string()),
title: format!("**{}** has been updated!", result.title),
text: format!(
"The project {} has released a new version: {}",
result.title,
version_data.version_number.clone()
),
link: format!(
"/{}/{}/version/{}",
result.project_type, project_id, version_id
),
actions: vec![],
body: NotificationBody::ProjectUpdate {
project_id,
version_id,
},
}
.insert_many(users, &mut *transaction)
.await?;