add: block list stacks

This commit is contained in:
trisua 2025-06-15 11:52:44 -04:00
parent 9bb5f38f76
commit b71ae1f5a4
28 changed files with 700 additions and 219 deletions

View file

@ -35,6 +35,7 @@ impl DataManager {
execute!(&conn, common::CREATE_TABLE_POLLS).unwrap();
execute!(&conn, common::CREATE_TABLE_POLLVOTES).unwrap();
execute!(&conn, common::CREATE_TABLE_APPS).unwrap();
execute!(&conn, common::CREATE_TABLE_STACKBLOCKS).unwrap();
self.0
.1
@ -363,7 +364,10 @@ macro_rules! auto_method {
} else {
self.create_audit_log_entry($crate::model::moderation::AuditLogEntry::new(
user.id,
format!("invoked `{}` with x value `{x:?}`", stringify!($name)),
format!(
"invoked `{}` with x value `{id}` and y value `{x:?}`",
stringify!($name)
),
))
.await?
}

View file

@ -22,3 +22,4 @@ pub const CREATE_TABLE_DRAFTS: &str = include_str!("./sql/create_drafts.sql");
pub const CREATE_TABLE_POLLS: &str = include_str!("./sql/create_polls.sql");
pub const CREATE_TABLE_POLLVOTES: &str = include_str!("./sql/create_pollvotes.sql");
pub const CREATE_TABLE_APPS: &str = include_str!("./sql/create_apps.sql");
pub const CREATE_TABLE_STACKBLOCKS: &str = include_str!("./sql/create_stackblocks.sql");

View file

@ -0,0 +1,6 @@
CREATE TABLE IF NOT EXISTS stackblocks (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
initiator BIGINT NOT NULL,
stack BIGINT NOT NULL
)

View file

@ -18,6 +18,7 @@ mod questions;
mod reactions;
mod reports;
mod requests;
mod stackblocks;
mod stacks;
mod uploads;
mod user_warnings;

View file

@ -1507,6 +1507,10 @@ impl DataManager {
.get_userblock_by_initiator_receiver(rt.owner, data.owner)
.await
.is_ok()
| self
.get_user_stack_blocked_users(rt.owner)
.await
.contains(&data.owner)
{
return Err(Error::NotAllowed);
}
@ -1552,6 +1556,10 @@ impl DataManager {
.get_userblock_by_initiator_receiver(rt.owner, data.owner)
.await
.is_ok()
| self
.get_user_stack_blocked_users(rt.owner)
.await
.contains(&data.owner)
{
return Err(Error::NotAllowed);
}
@ -1571,6 +1579,10 @@ impl DataManager {
.get_userblock_by_initiator_receiver(user.id, data.owner)
.await
.is_ok()
| self
.get_user_stack_blocked_users(user.id)
.await
.contains(&data.owner)
{
return Err(Error::NotAllowed);
}

View file

@ -145,10 +145,14 @@ impl DataManager {
if data.asset_type == AssetType::Post {
let post = self.get_post_by_id(data.asset).await?;
if self
if (self
.get_userblock_by_initiator_receiver(post.owner, user.id)
.await
.is_ok()
| self
.get_user_stack_blocked_users(post.owner)
.await
.contains(&user.id))
&& !user.permissions.check(FinePermission::MANAGE_POSTS)
{
return Err(Error::NotAllowed);
@ -156,10 +160,14 @@ impl DataManager {
} else if data.asset_type == AssetType::Question {
let question = self.get_question_by_id(data.asset).await?;
if self
if (self
.get_userblock_by_initiator_receiver(question.owner, user.id)
.await
.is_ok()
| self
.get_user_stack_blocked_users(question.owner)
.await
.contains(&user.id))
&& !user.permissions.check(FinePermission::MANAGE_POSTS)
{
return Err(Error::NotAllowed);

View file

@ -0,0 +1,224 @@
use oiseau::cache::Cache;
use crate::model::stacks::StackPrivacy;
use crate::model::{Error, Result, auth::User, stacks::StackBlock, permissions::FinePermission};
use crate::{auto_method, DataManager};
#[cfg(feature = "sqlite")]
use oiseau::SqliteRow;
#[cfg(feature = "postgres")]
use oiseau::PostgresRow;
use oiseau::{execute, get, params, query_row, query_rows};
impl DataManager {
/// Get a [`StackBlock`] from an SQL row.
pub(crate) fn get_stackblock_from_row(
#[cfg(feature = "sqlite")] x: &SqliteRow<'_>,
#[cfg(feature = "postgres")] x: &PostgresRow,
) -> StackBlock {
StackBlock {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
initiator: get!(x->2(i64)) as usize,
stack: get!(x->3(i64)) as usize,
}
}
auto_method!(get_stackblock_by_id()@get_stackblock_from_row -> "SELECT * FROM stackblocks WHERE id = $1" --name="stack block" --returns=StackBlock --cache-key-tmpl="atto.stackblock:{}");
pub async fn get_user_stack_blocked_users(&self, user_id: usize) -> Vec<usize> {
let mut stack_block_users = Vec::new();
for block in self.get_stackblocks_by_initiator(user_id).await {
for user in match self.fill_stackblocks_receivers(block.stack).await {
Ok(ul) => ul,
Err(_) => continue,
} {
stack_block_users.push(user);
}
}
stack_block_users
}
/// Fill a vector of stack blocks with their receivers (by pulling the stack).
pub async fn fill_stackblocks_receivers(&self, stack: usize) -> Result<Vec<usize>> {
let stack = self.get_stack_by_id(stack).await?;
let mut out = Vec::new();
for block in stack.users {
out.push(block);
}
Ok(out)
}
/// Get all stack blocks created by the given `initiator`.
pub async fn get_stackblocks_by_initiator(&self, initiator: usize) -> Vec<StackBlock> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(_) => return Vec::new(),
};
let res = query_rows!(
&conn,
"SELECT * FROM stackblocks WHERE initiator = $1",
&[&(initiator as i64)],
|x| { Self::get_stackblock_from_row(x) }
);
if res.is_err() {
return Vec::new();
}
// make sure all stacks still exist
let list = res.unwrap();
for block in &list {
if self.get_stack_by_id(block.stack).await.is_err() {
if self.delete_stackblock_sudo(block.id).await.is_err() {
continue;
}
}
}
// return
list
}
/// Get a stack block by `initiator` and `stack` (in that order).
pub async fn get_stackblock_by_initiator_stack(
&self,
initiator: usize,
stack: usize,
) -> Result<StackBlock> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_row!(
&conn,
"SELECT * FROM stackblocks WHERE initiator = $1 AND stack = $2",
&[&(initiator as i64), &(stack as i64)],
|x| { Ok(Self::get_stackblock_from_row(x)) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("stack block".to_string()));
}
Ok(res.unwrap())
}
/// Create a new stack block in the database.
///
/// # Arguments
/// * `data` - a mock [`StackBlock`] object to insert
pub async fn create_stackblock(&self, data: StackBlock) -> Result<()> {
let initiator = self.get_user_by_id(data.initiator).await?;
let stack = self.get_stack_by_id(data.stack).await?;
if initiator.id != stack.owner
&& stack.privacy == StackPrivacy::Private
&& !initiator.permissions.check(FinePermission::MANAGE_STACKS)
{
return Err(Error::NotAllowed);
}
// ...
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO stackblocks VALUES ($1, $2, $3, $4)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.initiator as i64),
&(data.stack as i64)
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// unfollow/remove follower
for user in stack.users {
if let Ok(f) = self
.get_userfollow_by_initiator_receiver(data.initiator, user)
.await
{
self.delete_userfollow_sudo(f.id, data.initiator).await?;
}
if let Ok(f) = self
.get_userfollow_by_receiver_initiator(data.initiator, user)
.await
{
self.delete_userfollow_sudo(f.id, data.initiator).await?;
}
}
// return
Ok(())
}
pub async fn delete_stackblock(&self, id: usize, user: User) -> Result<()> {
let block = self.get_stackblock_by_id(id).await?;
if user.id != block.initiator {
// only the initiator (or moderators) can delete stack blocks!
if !user.permissions.check(FinePermission::MANAGE_FOLLOWS) {
return Err(Error::NotAllowed);
}
}
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"DELETE FROM stackblocks WHERE id = $1",
&[&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.stackblock:{}", id)).await;
// return
Ok(())
}
pub async fn delete_stackblock_sudo(&self, id: usize) -> Result<()> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"DELETE FROM stackblocks WHERE id = $1",
&[&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.stackblock:{}", id)).await;
// return
Ok(())
}
}

View file

@ -91,9 +91,39 @@ impl DataManager {
}
}
}
StackMode::BlockList => {
return Err(Error::MiscError(
"You should use `get_stack_users` for this type".to_string(),
));
}
})
}
pub async fn get_stack_users(&self, id: usize, batch: usize, page: usize) -> Result<Vec<User>> {
let stack = self.get_stack_by_id(id).await?;
if stack.mode != StackMode::BlockList {
return Err(Error::MiscError(
"You should use `get_stack_posts` for this type".to_string(),
));
}
// build list
let mut out = Vec::new();
let mut i = 0;
for user in stack.users.iter().skip(batch * page) {
if i == batch {
break;
}
out.push(self.get_user_by_id(user.to_owned()).await?);
i += 1;
}
Ok(out)
}
/// Get all stacks by user.
///
/// # Arguments

View file

@ -346,4 +346,41 @@ impl DataManager {
// return
Ok(())
}
pub async fn delete_userfollow_sudo(&self, id: usize, user_id: usize) -> Result<()> {
let follow = self.get_userfollow_by_id(id).await?;
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"DELETE FROM userfollows WHERE id = $1",
&[&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.userfollow:{}", id)).await;
// decr counts
if follow.initiator != user_id {
self.decr_user_following_count(follow.initiator)
.await
.unwrap();
}
if follow.receiver != user_id {
self.decr_user_follower_count(follow.receiver)
.await
.unwrap();
}
// return
Ok(())
}
}

View file

@ -76,6 +76,8 @@ pub enum AppScope {
UserCreateCommunities,
/// Create stacks on behalf of the user.
UserCreateStacks,
/// Create circles on behalf of the user.
UserCreateCircles,
/// Delete posts owned by the user.
UserDeletePosts,
/// Delete messages owned by the user.
@ -106,6 +108,8 @@ pub enum AppScope {
UserManageRequests,
/// Manage the user's uploads.
UserManageUploads,
/// Manage the user's circles (add/remove users or delete).
UserManageCircles,
/// Edit posts created by the user.
UserEditPosts,
/// Edit drafts created by the user.
@ -142,68 +146,6 @@ pub enum AppScope {
CommunityManageChannels,
}
impl AppScope {
/// Parse the given input string as a list of scopes.
pub fn parse(input: &str) -> Vec<AppScope> {
let mut out: Vec<AppScope> = Vec::new();
for scope in input.split(" ") {
out.push(match scope {
"user-read-profiles" => Self::UserReadProfiles,
"user-read-profile" => Self::UserReadProfile,
"user-read-settings" => Self::UserReadSettings,
"user-read-sessions" => Self::UserReadSessions,
"user-read-posts" => Self::UserReadPosts,
"user-read-messages" => Self::UserReadMessages,
"user-read-drafts" => Self::UserReadDrafts,
"user-read-communities" => Self::UserReadCommunities,
"user-read-sockets" => Self::UserReadSockets,
"user-read-notifications" => Self::UserReadNotifications,
"user-read-requests" => Self::UserReadRequests,
"user-read-questions" => Self::UserReadQuestions,
"user-create-posts" => Self::UserCreatePosts,
"user-create-messages" => Self::UserCreateMessages,
"user-create-questions" => Self::UserCreateQuestions,
"user-create-ip-blocks" => Self::UserCreateIpBlock,
"user-create-drafts" => Self::UserCreateDrafts,
"user-create-communities" => Self::UserCreateCommunities,
"user-delete-posts" => Self::UserDeletePosts,
"user-delete-messages" => Self::UserDeleteMessages,
"user-delete-questions" => Self::UserDeleteQuestions,
"user-delete-drafts" => Self::UserDeleteDrafts,
"user-manage-profile" => Self::UserManageProfile,
"user-manage-stacks" => Self::UserManageStacks,
"user-manage-relationships" => Self::UserManageRelationships,
"user-manage-memberships" => Self::UserManageMemberships,
"user-manage-following" => Self::UserManageFollowing,
"user-manage-followers" => Self::UserManageFollowers,
"user-manage-blocks" => Self::UserManageBlocks,
"user-manage-notifications" => Self::UserManageNotifications,
"user-manage-requests" => Self::UserManageRequests,
"user-manage-uploads" => Self::UserManageUploads,
"user-edit-posts" => Self::UserEditPosts,
"user-edit-drafts" => Self::UserEditDrafts,
"user-vote" => Self::UserVote,
"user-react" => Self::UserReact,
"user-join-communities" => Self::UserJoinCommunities,
"mod-purge-posts" => Self::ModPurgePosts,
"mod-delete-posts" => Self::ModDeletePosts,
"mod-manage-warnings" => Self::ModManageWarnings,
"user-read-emojis" => Self::UserReadEmojis,
"community-create-emojis" => Self::CommunityCreateEmojis,
"community-manage-emojis" => Self::CommunityManageEmojis,
"community-delete" => Self::CommunityDelete,
"community-manage" => Self::CommunityManage,
"community-transfer-ownership" => Self::CommunityTransferOwnership,
"community-read-memberships" => Self::CommunityReadMemberships,
"community-create-channels" => Self::CommunityCreateChannels,
"community-manage-channels" => Self::CommunityManageChannels,
_ => continue,
})
}
out
}
}
impl AuthGrant {
/// Check a verifier against the stored challenge (using the given [`PkceChallengeMethod`]).
pub fn check_verifier(&self, verifier: &str) -> Result<()> {

View file

@ -23,6 +23,11 @@ pub enum StackMode {
/// `users` vec contains ID of users to EXCLUDE from the timeline;
/// every other user is included
Exclude,
/// `users` vec contains ID of users to show in a user listing on the stack's
/// page (instead of a timeline).
///
/// Other users can block the entire list (creating a `StackBlock`, not a `UserBlock`).
BlockList,
}
impl Default for StackMode {
@ -70,3 +75,23 @@ impl UserStack {
}
}
}
#[derive(Serialize, Deserialize)]
pub struct StackBlock {
pub id: usize,
pub created: usize,
pub initiator: usize,
pub stack: usize,
}
impl StackBlock {
/// Create a new [`StackBlock`].
pub fn new(initiator: usize, stack: usize) -> Self {
Self {
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
created: unix_epoch_timestamp(),
initiator,
stack,
}
}
}