add: request-to-join communities

add: private joined communities setting
add: "void" community
add: ability to delete communities
This commit is contained in:
trisua 2025-04-01 15:03:56 -04:00
parent 3a8af17154
commit d0c1fbcf9a
20 changed files with 669 additions and 122 deletions

View file

@ -1,6 +1,6 @@
use super::*;
use crate::cache::Cache;
use crate::model::communities::{CommunityContext, CommunityMembership};
use crate::model::communities::{CommunityContext, CommunityJoinAccess, CommunityMembership};
use crate::model::communities_permissions::CommunityPermission;
use crate::model::{
Error, Result,
@ -10,6 +10,8 @@ use crate::model::{
permissions::FinePermission,
};
use crate::{auto_method, execute, get, query_row};
use pathbufd::PathBufD;
use std::fs::{exists, remove_file};
#[cfg(feature = "sqlite")]
use rusqlite::Row;
@ -31,16 +33,91 @@ impl DataManager {
owner: get!(x->4(isize)) as usize,
read_access: serde_json::from_str(&get!(x->5(String))).unwrap(),
write_access: serde_json::from_str(&get!(x->6(String))).unwrap(),
join_access: serde_json::from_str(&get!(x->7(String))).unwrap(),
// likes
likes: get!(x->7(isize)) as isize,
dislikes: get!(x->8(isize)) as isize,
likes: get!(x->8(isize)) as isize,
dislikes: get!(x->9(isize)) as isize,
// counts
member_count: get!(x->9(isize)) as usize,
member_count: get!(x->10(isize)) as usize,
}
}
auto_method!(get_community_by_id()@get_community_from_row -> "SELECT * FROM communities WHERE id = $1" --name="community" --returns=Community --cache-key-tmpl="atto.community:{}");
auto_method!(get_community_by_title(&str)@get_community_from_row -> "SELECT * FROM communities WHERE title = $1" --name="community" --returns=Community --cache-key-tmpl="atto.community:{}");
pub async fn get_community_by_id(&self, id: usize) -> Result<Community> {
if id == 0 {
return Ok(Community::void());
}
if let Some(cached) = self.2.get(format!("atto.community:{}", id)).await {
return Ok(serde_json::from_str(&cached).unwrap());
}
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_row!(
&conn,
"SELECT * FROM communities WHERE id = $1",
&[&(id as isize)],
|x| { Ok(Self::get_community_from_row(x)) }
);
if res.is_err() {
return Ok(Community::void());
// return Err(Error::GeneralNotFound("community".to_string()));
}
let x = res.unwrap();
self.2
.set(
format!("atto.community:{}", id),
serde_json::to_string(&x).unwrap(),
)
.await;
Ok(x)
}
pub async fn get_community_by_title(&self, id: &str) -> Result<Community> {
if id == "void" {
return Ok(Community::void());
}
if let Some(cached) = self.2.get(format!("atto.community:{}", id)).await {
return Ok(serde_json::from_str(&cached).unwrap());
}
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_row!(
&conn,
"SELECT * FROM communities WHERE title = $1",
&[id],
|x| { Ok(Self::get_community_from_row(x)) }
);
if res.is_err() {
return Ok(Community::void());
// return Err(Error::GeneralNotFound("community".to_string()));
}
let x = res.unwrap();
self.2
.set(
format!("atto.community:{}", id),
serde_json::to_string(&x).unwrap(),
)
.await;
Ok(x)
}
auto_method!(get_community_by_id_no_void()@get_community_from_row -> "SELECT * FROM communities WHERE id = $1" --name="community" --returns=Community --cache-key-tmpl="atto.community:{}");
auto_method!(get_community_by_title_no_void(&str)@get_community_from_row -> "SELECT * FROM communities WHERE title = $1" --name="community" --returns=Community --cache-key-tmpl="atto.community:{}");
/// Create a new community in the database.
///
@ -60,9 +137,30 @@ impl DataManager {
));
}
if self.0.banned_usernames.contains(&data.title) {
return Err(Error::MiscError("This title cannot be used".to_string()));
}
// check number of communities
let memberships = self.get_memberships_by_owner(data.owner).await?;
let mut admin_count = 0; // you can not make anymore communities if you are already admin of at least 5
for membership in memberships {
if membership.role.check(CommunityPermission::ADMINISTRATOR) {
admin_count += 1;
}
}
if admin_count >= 5 {
return Err(Error::MiscError(
"You are already owner/co-owner of too many communities to create another"
.to_string(),
));
}
// make sure community doesn't already exist with title
if self
.get_community_by_title(&data.title.to_lowercase())
.get_community_by_title_no_void(&data.title.to_lowercase())
.await
.is_ok()
{
@ -77,7 +175,7 @@ impl DataManager {
let res = execute!(
&conn,
"INSERT INTO communities VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
"INSERT INTO communities VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
&[
&data.id.to_string().as_str(),
&data.created.to_string().as_str(),
@ -86,6 +184,7 @@ impl DataManager {
&data.owner.to_string().as_str(),
&serde_json::to_string(&data.read_access).unwrap().as_str(),
&serde_json::to_string(&data.write_access).unwrap().as_str(),
&serde_json::to_string(&data.join_access).unwrap().as_str(),
&0.to_string().as_str(),
&0.to_string().as_str(),
&0.to_string().as_str()
@ -118,17 +217,79 @@ impl DataManager {
.await;
}
auto_method!(delete_community()@get_community_by_id:MANAGE_COMMUNITIES -> "DELETE communities pages WHERE id = $1" --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_title(String)@get_community_by_id:MANAGE_COMMUNITIES -> "UPDATE communities SET title = $1 WHERE id = $2" --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_context(CommunityContext)@get_community_by_id:MANAGE_COMMUNITIES -> "UPDATE communities SET context = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_read_access(CommunityReadAccess)@get_community_by_id:MANAGE_COMMUNITIES -> "UPDATE communities SET read_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_write_access(CommunityWriteAccess)@get_community_by_id:MANAGE_COMMUNITIES -> "UPDATE communities SET write_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
pub async fn delete_community(&self, id: usize, user: User) -> Result<()> {
let y = self.get_community_by_id(id).await?;
auto_method!(incr_community_likes()@get_community_by_id -> "UPDATE communities SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
auto_method!(incr_community_dislikes()@get_community_by_id -> "UPDATE communities SET dislikes = dislikes + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
auto_method!(decr_community_likes()@get_community_by_id -> "UPDATE communities SET likes = likes - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr);
auto_method!(decr_community_dislikes()@get_community_by_id -> "UPDATE communities SET dislikes = dislikes - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr);
if user.id != y.owner {
if !user.permissions.check(FinePermission::MANAGE_COMMUNITIES) {
return Err(Error::NotAllowed);
}
}
auto_method!(incr_community_member_count()@get_community_by_id -> "UPDATE communities SET member_count = member_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
auto_method!(decr_community_member_count()@get_community_by_id -> "UPDATE communities SET member_count = member_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr);
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"DELETE FROM communities WHERE id = $1",
&[&id.to_string()]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.cache_clear_community(&y).await;
// remove memberships
let res = execute!(
&conn,
"DELETE FROM memberships WHERE community = $1",
&[&id.to_string()]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// remove images
let avatar = PathBufD::current().extend(&[
self.0.dirs.media.as_str(),
"community_avatars",
&format!("{}.avif", &y.id),
]);
let banner = PathBufD::current().extend(&[
self.0.dirs.media.as_str(),
"community_banners",
&format!("{}.avif", &y.id),
]);
if exists(&avatar).unwrap() {
remove_file(avatar).unwrap();
}
if exists(&banner).unwrap() {
remove_file(banner).unwrap();
}
// ...
Ok(())
}
auto_method!(update_community_title(String)@get_community_by_id_no_void:MANAGE_COMMUNITIES -> "UPDATE communities SET title = $1 WHERE id = $2" --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_context(CommunityContext)@get_community_by_id_no_void:MANAGE_COMMUNITIES -> "UPDATE communities SET context = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_read_access(CommunityReadAccess)@get_community_by_id_no_void:MANAGE_COMMUNITIES -> "UPDATE communities SET read_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_write_access(CommunityWriteAccess)@get_community_by_id_no_void:MANAGE_COMMUNITIES -> "UPDATE communities SET write_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
auto_method!(update_community_join_access(CommunityJoinAccess)@get_community_by_id_no_void:MANAGE_COMMUNITIES -> "UPDATE communities SET join_access = $1 WHERE id = $2" --serde --cache-key-tmpl=cache_clear_community);
auto_method!(incr_community_likes()@get_community_by_id_no_void -> "UPDATE communities SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
auto_method!(incr_community_dislikes()@get_community_by_id_no_void -> "UPDATE communities SET dislikes = dislikes + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
auto_method!(decr_community_likes()@get_community_by_id_no_void -> "UPDATE communities SET likes = likes - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr);
auto_method!(decr_community_dislikes()@get_community_by_id_no_void -> "UPDATE communities SET dislikes = dislikes - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr);
auto_method!(incr_community_member_count()@get_community_by_id_no_void -> "UPDATE communities SET member_count = member_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --incr);
auto_method!(decr_community_member_count()@get_community_by_id_no_void -> "UPDATE communities SET member_count = member_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_community --decr);
}

View file

@ -6,6 +6,7 @@ CREATE TABLE IF NOT EXISTS communities (
owner INTEGER NOT NULL,
read_access TEXT NOT NULL,
write_access TEXT NOT NULL,
join_access TEXT NOT NULL,
-- likes
likes INTEGER NOT NULL,
dislikes INTEGER NOT NULL,

View file

@ -1,9 +1,13 @@
use super::*;
use crate::cache::Cache;
use crate::model::auth::Notification;
use crate::model::communities::Community;
use crate::model::{
Error, Result, auth::User, communities::CommunityMembership,
communities_permissions::CommunityPermission, permissions::FinePermission,
Error, Result,
auth::User,
communities::{CommunityJoinAccess, CommunityMembership},
communities_permissions::CommunityPermission,
permissions::FinePermission,
};
use crate::{auto_method, execute, get, query_row, query_rows};
@ -73,7 +77,8 @@ impl DataManager {
let res = query_rows!(
&conn,
"SELECT * FROM memberships WHERE owner = $1 AND role IS NOT 33",
// 33 = banned, 65 = pending membership
"SELECT * FROM memberships WHERE owner = $1 AND role IS NOT 33 AND role IS NOT 65 ORDER BY created DESC",
&[&(owner as isize)],
|x| { Self::get_membership_from_row(x) }
);
@ -89,7 +94,8 @@ impl DataManager {
///
/// # Arguments
/// * `data` - a mock [`CommunityMembership`] object to insert
pub async fn create_membership(&self, data: CommunityMembership) -> Result<()> {
#[async_recursion::async_recursion]
pub async fn create_membership(&self, data: CommunityMembership) -> Result<String> {
// make sure membership doesn't already exist
if self
.get_membership_by_owner_community(data.owner, data.community)
@ -99,6 +105,34 @@ impl DataManager {
return Err(Error::MiscError("Already joined community".to_string()));
}
// check permission
let community = self.get_community_by_id(data.community).await?;
match community.join_access {
CommunityJoinAccess::Nobody => return Err(Error::NotAllowed),
CommunityJoinAccess::Request => {
if !data.role.check(CommunityPermission::REQUESTED) {
let mut data = data.clone();
data.role = CommunityPermission::DEFAULT | CommunityPermission::REQUESTED;
// send notification to the owner
self.create_notification(Notification::new(
"You've received a community join request!".to_string(),
format!(
"[Somebody](/api/v1/auth/profile/find/{}) is asking to join your [community](/community/{}).\n\n[Click here to review their request](/community/{}/manage?uid={}#/members).",
data.owner, data.community, data.community, data.owner
),
community.owner,
))
.await?;
// ...
return self.create_membership(data).await;
}
}
_ => (),
}
// ...
let conn = match self.connect().await {
Ok(c) => c,
@ -121,11 +155,18 @@ impl DataManager {
return Err(Error::DatabaseError(e.to_string()));
}
self.incr_community_member_count(data.community)
.await
.unwrap();
if !data.role.check(CommunityPermission::REQUESTED) {
// users who are just a requesting to join do not count towards the member count
self.incr_community_member_count(data.community)
.await
.unwrap();
}
Ok(())
Ok(if data.role.check(CommunityPermission::REQUESTED) {
"Join request sent".to_string()
} else {
"Community joined".to_string()
})
}
/// Delete a membership given its `id`
@ -134,7 +175,10 @@ impl DataManager {
if user.id != y.owner {
// pull other user's membership status
if let Ok(z) = self.get_membership_by_id(user.id).await {
if let Ok(z) = self
.get_membership_by_owner_community(user.id, y.community)
.await
{
// somebody with MANAGE_ROLES _and_ a higher role number can remove us
if (!z.role.check(CommunityPermission::MANAGE_ROLES) | (z.role < y.role))
&& !z.role.check(CommunityPermission::ADMINISTRATOR)

View file

@ -36,7 +36,7 @@ impl DataManager {
let res = query_rows!(
&conn,
"SELECT * FROM notifications WHERE owner = $1",
"SELECT * FROM notifications WHERE owner = $1 ORDER BY created DESC",
&[&(owner as isize)],
|x| { Self::get_notification_from_row(x) }
);

View file

@ -96,7 +96,7 @@ impl DataManager {
} {
return Err(e);
} else if data.is_like {
let community = self.get_community_by_id(data.asset).await.unwrap();
let community = self.get_community_by_id_no_void(data.asset).await.unwrap();
if community.owner != user.id {
if let Err(e) = self