add: communities list page

TODO(ui): implement community creation, community viewing, community posting
TODO(ui): implement profile following, followers, and posts feed
This commit is contained in:
trisua 2025-03-27 18:10:47 -04:00
parent 5cfca49793
commit d6fbfc3cd6
28 changed files with 497 additions and 313 deletions

View file

@ -1,12 +1,12 @@
use super::*;
use crate::cache::Cache;
use crate::model::journal::JournalMembership;
use crate::model::journal_permissions::JournalPermission;
use crate::model::communities::{CommunityContext, CommunityMembership};
use crate::model::communities_permissions::CommunityPermission;
use crate::model::{
Error, Result,
auth::User,
journal::Journal,
journal::{JournalReadAccess, JournalWriteAccess},
communities::Community,
communities::{CommunityReadAccess, CommunityWriteAccess},
permissions::FinePermission,
};
use crate::{auto_method, execute, get, query_row};
@ -18,32 +18,32 @@ use rusqlite::Row;
use tokio_postgres::Row;
impl DataManager {
/// Get a [`Journal`] from an SQL row.
pub(crate) fn get_page_from_row(
/// Get a [`Community`] from an SQL row.
pub(crate) fn get_community_from_row(
#[cfg(feature = "sqlite")] x: &Row<'_>,
#[cfg(feature = "postgres")] x: &Row,
) -> Journal {
Journal {
) -> Community {
Community {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
title: get!(x->2(String)),
prompt: get!(x->3(String)),
context: serde_json::from_str(&get!(x->3(String))).unwrap(),
owner: get!(x->4(i64)) as usize,
read_access: serde_json::from_str(&get!(x->5(String)).to_string()).unwrap(),
write_access: serde_json::from_str(&get!(x->6(String)).to_string()).unwrap(),
read_access: serde_json::from_str(&get!(x->5(String))).unwrap(),
write_access: serde_json::from_str(&get!(x->6(String))).unwrap(),
// likes
likes: get!(x->6(i64)) as isize,
dislikes: get!(x->7(i64)) as isize,
}
}
auto_method!(get_page_by_id()@get_page_from_row -> "SELECT * FROM journals WHERE id = $1" --name="journal" --returns=Journal --cache-key-tmpl="atto.journal:{}");
auto_method!(get_page_by_id()@get_community_from_row -> "SELECT * FROM journals WHERE id = $1" --name="journal" --returns=Community --cache-key-tmpl="atto.journal:{}");
/// Create a new journal page in the database.
///
/// # Arguments
/// * `data` - a mock [`Journal`] object to insert
pub async fn create_page(&self, data: Journal) -> Result<()> {
pub async fn create_community(&self, data: Community) -> Result<()> {
// check values
if data.title.len() < 2 {
return Err(Error::DataTooShort("title".to_string()));
@ -51,12 +51,6 @@ impl DataManager {
return Err(Error::DataTooLong("title".to_string()));
}
if data.prompt.len() < 2 {
return Err(Error::DataTooShort("prompt".to_string()));
} else if data.prompt.len() > 2048 {
return Err(Error::DataTooLong("prompt".to_string()));
}
// ...
let conn = match self.connect().await {
Ok(c) => c,
@ -70,7 +64,7 @@ impl DataManager {
&data.id.to_string().as_str(),
&data.created.to_string().as_str(),
&data.title.as_str(),
&data.prompt.as_str(),
&serde_json::to_string(&data.context).unwrap().as_str(),
&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(),
@ -82,10 +76,10 @@ impl DataManager {
}
// add journal page owner as admin
self.create_membership(JournalMembership::new(
self.create_membership(CommunityMembership::new(
data.owner,
data.id,
JournalPermission::ADMINISTRATOR,
CommunityPermission::ADMINISTRATOR,
))
.await
.unwrap();
@ -94,11 +88,11 @@ impl DataManager {
Ok(())
}
auto_method!(delete_page()@get_page_by_id:MANAGE_JOURNAL_PAGES -> "DELETE journals pages WHERE id = $1" --cache-key-tmpl="atto.journal:{}");
auto_method!(update_page_title(String)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET title = $1 WHERE id = $2" --cache-key-tmpl="atto.journal:{}");
auto_method!(update_page_prompt(String)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET prompt = $1 WHERE id = $2" --cache-key-tmpl="atto.journal:{}");
auto_method!(update_page_read_access(JournalReadAccess)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET read_access = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
auto_method!(update_page_write_access(JournalWriteAccess)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET write_access = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
auto_method!(delete_community()@get_page_by_id:MANAGE_JOURNAL_PAGES -> "DELETE journals pages WHERE id = $1" --cache-key-tmpl="atto.journal:{}");
auto_method!(update_community_title(String)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET title = $1 WHERE id = $2" --cache-key-tmpl="atto.journal:{}");
auto_method!(update_community_context(CommunityContext)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET prompt = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
auto_method!(update_community_read_access(CommunityReadAccess)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET read_access = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
auto_method!(update_community_write_access(CommunityWriteAccess)@get_page_by_id:MANAGE_JOURNAL_PAGES -> "UPDATE journals SET write_access = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
auto_method!(incr_page_likes() -> "UPDATE journals SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl="atto.journal:{}" --incr);
auto_method!(incr_page_dislikes() -> "UPDATE journals SET likes = dislikes + 1 WHERE id = $1" --cache-key-tmpl="atto.journal:{}" --incr);

View file

@ -2,6 +2,6 @@ CREATE TABLE IF NOT EXISTS memberships (
id INTEGER NOT NULL PRIMARY KEY,
created INTEGER NOT NULL,
owner INTEGER NOT NULL,
journal INTEGER NOT NULL,
community INTEGER NOT NULL,
role INTEGER NOT NULL
)

View file

@ -3,7 +3,7 @@ CREATE TABLE IF NOT EXISTS posts (
created INTEGER NOT NULL,
content TEXT NOT NULL,
owner INTEGER NOT NULL,
journal INTEGER NOT NULL,
community INTEGER NOT NULL,
context TEXT NOT NULL,
replying_to INTEGER, -- the ID of the post this is a comment on... NULL means it isn't a reply
-- likes

View file

@ -1,10 +1,10 @@
use super::*;
use crate::cache::Cache;
use crate::model::{
Error, Result, auth::User, journal::JournalMembership, journal_permissions::JournalPermission,
permissions::FinePermission,
Error, Result, auth::User, communities::CommunityMembership,
communities_permissions::CommunityPermission, permissions::FinePermission,
};
use crate::{auto_method, execute, get, query_row};
use crate::{auto_method, execute, get, query_row, query_rows};
#[cfg(feature = "sqlite")]
use rusqlite::Row;
@ -17,24 +17,24 @@ impl DataManager {
pub(crate) fn get_membership_from_row(
#[cfg(feature = "sqlite")] x: &Row<'_>,
#[cfg(feature = "postgres")] x: &Row,
) -> JournalMembership {
JournalMembership {
) -> CommunityMembership {
CommunityMembership {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
journal: get!(x->3(i64)) as usize,
role: JournalPermission::from_bits(get!(x->4(u32))).unwrap(),
community: get!(x->3(i64)) as usize,
role: CommunityPermission::from_bits(get!(x->4(u32))).unwrap(),
}
}
auto_method!(get_membership_by_id()@get_membership_from_row -> "SELECT * FROM memberships WHERE id = $1" --name="journal membership" --returns=JournalMembership --cache-key-tmpl="atto.membership:{}");
auto_method!(get_membership_by_id()@get_membership_from_row -> "SELECT * FROM memberships WHERE id = $1" --name="journal membership" --returns=CommunityMembership --cache-key-tmpl="atto.membership:{}");
/// Get a journal membership by `owner` and `journal`.
pub async fn get_membership_by_owner_journal(
/// Get a community membership by `owner` and `community`.
pub async fn get_membership_by_owner_community(
&self,
owner: usize,
journal: usize,
) -> Result<JournalMembership> {
community: usize,
) -> Result<CommunityMembership> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
@ -42,23 +42,44 @@ impl DataManager {
let res = query_row!(
&conn,
"SELECT * FROM memberships WHERE owner = $1 AND journal = $2",
&[&(owner as i64), &(journal as i64)],
"SELECT * FROM memberships WHERE owner = $1 AND community = $2",
&[&(owner as i64), &(community as i64)],
|x| { Ok(Self::get_membership_from_row(x)) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("journal membership".to_string()));
return Err(Error::GeneralNotFound("community membership".to_string()));
}
Ok(res.unwrap())
}
/// Create a new journal membership in the database.
/// Get all community memberships by `owner`.
pub async fn get_memberships_by_owner(&self, owner: usize) -> Result<Vec<CommunityMembership>> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM memberships WHERE owner = $1",
&[&(owner as i64)],
|x| { Self::get_membership_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("community membership".to_string()));
}
Ok(res.unwrap())
}
/// Create a new community membership in the database.
///
/// # Arguments
/// * `data` - a mock [`JournalMembership`] object to insert
pub async fn create_membership(&self, data: JournalMembership) -> Result<()> {
/// * `data` - a mock [`CommunityMembership`] object to insert
pub async fn create_membership(&self, data: CommunityMembership) -> Result<()> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
@ -71,7 +92,7 @@ impl DataManager {
&data.id.to_string().as_str(),
&data.created.to_string().as_str(),
&data.owner.to_string().as_str(),
&data.journal.to_string().as_str(),
&data.community.to_string().as_str(),
&(data.role.bits()).to_string().as_str(),
]
);
@ -91,8 +112,8 @@ impl DataManager {
// pull other user's membership status
if let Ok(z) = self.get_membership_by_id(user.id).await {
// somebody with MANAGE_ROLES _and_ a higher role number can remove us
if (!z.role.check(JournalPermission::MANAGE_ROLES) | (z.role < y.role))
&& !z.role.check(JournalPermission::ADMINISTRATOR)
if (!z.role.check(CommunityPermission::MANAGE_ROLES) | (z.role < y.role))
&& !z.role.check(CommunityPermission::ADMINISTRATOR)
{
return Err(Error::NotAllowed);
}
@ -125,7 +146,7 @@ impl DataManager {
pub async fn update_membership_role(
&self,
id: usize,
new_role: JournalPermission,
new_role: CommunityPermission,
) -> Result<()> {
let conn = match self.connect().await {
Ok(c) => c,

View file

@ -1,8 +1,8 @@
mod auth;
mod common;
mod communities;
mod drivers;
mod ipbans;
mod journals;
mod memberships;
mod notifications;
mod posts;

View file

@ -26,7 +26,7 @@ impl DataManager {
auto_method!(get_notification_by_id()@get_notification_from_row -> "SELECT * FROM notifications WHERE id = $1" --name="notification" --returns=Notification --cache-key-tmpl="atto.notification:{}");
/// Get a reaction by `owner` and `asset`.
/// Get all notifications by `owner`.
pub async fn get_notifications_by_owner(&self, owner: usize) -> Result<Vec<Notification>> {
let conn = match self.connect().await {
Ok(c) => c,
@ -107,9 +107,9 @@ impl DataManager {
self.2.remove(format!("atto.notification:{}", id)).await;
// decr notification count
// self.decr_user_notifications(notification.owner)
// .await
// .unwrap();
self.decr_user_notifications(notification.owner)
.await
.unwrap();
// return
Ok(())

View file

@ -1,8 +1,10 @@
use super::*;
use crate::cache::Cache;
use crate::model::journal::JournalPostContext;
use crate::model::communities::PostContext;
use crate::model::{
Error, Result, auth::User, journal::JournalPost, journal::JournalWriteAccess,
Error, Result,
auth::User,
communities::{CommunityWriteAccess, Post},
permissions::FinePermission,
};
use crate::{auto_method, execute, get, query_row, query_rows};
@ -14,17 +16,17 @@ use rusqlite::Row;
use tokio_postgres::Row;
impl DataManager {
/// Get a [`JournalEntry`] from an SQL row.
/// Get a [`Post`] from an SQL row.
pub(crate) fn get_post_from_row(
#[cfg(feature = "sqlite")] x: &Row<'_>,
#[cfg(feature = "postgres")] x: &Row,
) -> JournalPost {
JournalPost {
) -> Post {
Post {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
content: get!(x->2(String)),
owner: get!(x->3(i64)) as usize,
journal: get!(x->4(i64)) as usize,
community: get!(x->4(i64)) as usize,
context: serde_json::from_str(&get!(x->5(String))).unwrap(),
replying_to: if let Some(id) = get!(x->6(Option<i64>)) {
Some(id as usize)
@ -39,7 +41,7 @@ impl DataManager {
}
}
auto_method!(get_post_by_id()@get_post_from_row -> "SELECT * FROM posts WHERE id = $1" --name="post" --returns=JournalPost --cache-key-tmpl="atto.post:{}");
auto_method!(get_post_by_id()@get_post_from_row -> "SELECT * FROM posts WHERE id = $1" --name="post" --returns=Post --cache-key-tmpl="atto.post:{}");
/// Get all posts which are comments on the given post by ID.
///
@ -47,12 +49,7 @@ impl DataManager {
/// * `id` - the ID of the post the requested posts are commenting on
/// * `batch` - the limit of posts in each page
/// * `page` - the page number
pub async fn get_post_comments(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<JournalPost> {
pub async fn get_post_comments(&self, id: usize, batch: usize, page: usize) -> Result<Post> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
@ -83,7 +80,7 @@ impl DataManager {
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<JournalPost>> {
) -> Result<Vec<Post>> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
@ -107,7 +104,7 @@ impl DataManager {
///
/// # Arguments
/// * `data` - a mock [`JournalEntry`] object to insert
pub async fn create_post(&self, data: JournalPost) -> Result<()> {
pub async fn create_post(&self, data: Post) -> Result<()> {
// check values
if data.content.len() < 2 {
return Err(Error::DataTooShort("content".to_string()));
@ -116,20 +113,20 @@ impl DataManager {
}
// check permission in page
let page = match self.get_page_by_id(data.journal).await {
let page = match self.get_page_by_id(data.community).await {
Ok(p) => p,
Err(e) => return Err(e),
};
match page.write_access {
JournalWriteAccess::Owner => {
CommunityWriteAccess::Owner => {
if data.owner != page.owner {
return Err(Error::NotAllowed);
}
}
JournalWriteAccess::Joined => {
CommunityWriteAccess::Joined => {
if let Err(_) = self
.get_membership_by_owner_journal(data.owner, page.id)
.get_membership_by_owner_community(data.owner, page.id)
.await
{
return Err(Error::NotAllowed);
@ -152,7 +149,7 @@ impl DataManager {
&Some(data.created.to_string()),
&Some(data.content),
&Some(data.owner.to_string()),
&Some(data.journal.to_string()),
&Some(data.community.to_string()),
&Some(serde_json::to_string(&data.context).unwrap()),
&if let Some(id) = data.replying_to {
Some(id.to_string())
@ -180,7 +177,7 @@ impl DataManager {
auto_method!(delete_post()@get_post_by_id:MANAGE_JOURNAL_ENTRIES -> "DELETE FROM posts WHERE id = $1" --cache-key-tmpl="atto.post:{}");
auto_method!(update_post_content(String)@get_post_by_id:MANAGE_JOURNAL_ENTRIES -> "UPDATE posts SET content = $1 WHERE id = $2" --cache-key-tmpl="atto.post:{}");
auto_method!(update_post_context(JournalPostContext)@get_post_by_id:MANAGE_JOURNAL_ENTRIES -> "UPDATE posts SET context = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.post:{}");
auto_method!(update_post_context(PostContext)@get_post_by_id:MANAGE_JOURNAL_ENTRIES -> "UPDATE posts SET context = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.post:{}");
auto_method!(incr_post_likes() -> "UPDATE posts SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl="atto.post:{}" --incr);
auto_method!(incr_post_dislikes() -> "UPDATE posts SET likes = dislikes + 1 WHERE id = $1" --cache-key-tmpl="atto.post:{}" --incr);

View file

@ -38,7 +38,7 @@ impl DataManager {
let res = query_row!(
&conn,
"SELECT * FROM userblocks WHERE initator = $1 AND receiver = $2",
"SELECT * FROM userblocks WHERE initiator = $1 AND receiver = $2",
&[&(initiator as i64), &(receiver as i64)],
|x| { Ok(Self::get_userblock_from_row(x)) }
);

View file

@ -38,7 +38,7 @@ impl DataManager {
let res = query_row!(
&conn,
"SELECT * FROM userfollows WHERE initator = $1 AND receiver = $2",
"SELECT * FROM userfollows WHERE initiator = $1 AND receiver = $2",
&[&(initiator as i64), &(receiver as i64)],
|x| { Ok(Self::get_userfollow_from_row(x)) }
);