* 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:
Geometrically
2021-03-04 20:35:23 -07:00
committed by GitHub
parent e46ff3de8b
commit 0ccb6cb873
25 changed files with 2298 additions and 782 deletions

View File

@@ -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),
);
}

View File

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

View File

@@ -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
View 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(""))
}
}

View File

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

View File

@@ -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))
}

View File

@@ -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(),

View File

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