add: user stacks
This commit is contained in:
parent
8c3024cb40
commit
75d72460ae
28 changed files with 1028 additions and 9 deletions
|
@ -312,6 +312,7 @@ fn default_banned_usernames() -> Vec<String> {
|
|||
"post".to_string(),
|
||||
"void".to_string(),
|
||||
"anonymous".to_string(),
|
||||
"stack".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
|
|
|
@ -127,6 +127,16 @@ impl DataManager {
|
|||
return Err(Error::MiscError("This username cannot be used".to_string()));
|
||||
}
|
||||
|
||||
if data.username.contains(" ") {
|
||||
return Err(Error::MiscError("Name cannot contain spaces".to_string()));
|
||||
} else if data.username.contains("%") {
|
||||
return Err(Error::MiscError("Name cannot contain \"%\"".to_string()));
|
||||
} else if data.username.contains("?") {
|
||||
return Err(Error::MiscError("Name cannot contain \"?\"".to_string()));
|
||||
} else if data.username.contains("&") {
|
||||
return Err(Error::MiscError("Name cannot contain \"&\"".to_string()));
|
||||
}
|
||||
|
||||
// make sure username isn't taken
|
||||
if self.get_user_by_username(&data.username).await.is_ok() {
|
||||
return Err(Error::UsernameInUse);
|
||||
|
|
|
@ -32,6 +32,7 @@ impl DataManager {
|
|||
execute!(&conn, common::CREATE_TABLE_MESSAGES).unwrap();
|
||||
execute!(&conn, common::CREATE_TABLE_UPLOADS).unwrap();
|
||||
execute!(&conn, common::CREATE_TABLE_EMOJIS).unwrap();
|
||||
execute!(&conn, common::CREATE_TABLE_STACKS).unwrap();
|
||||
|
||||
self.2
|
||||
.set("atto.active_connections:users".to_string(), "0".to_string())
|
||||
|
|
|
@ -17,3 +17,4 @@ pub const CREATE_TABLE_CHANNELS: &str = include_str!("./sql/create_channels.sql"
|
|||
pub const CREATE_TABLE_MESSAGES: &str = include_str!("./sql/create_messages.sql");
|
||||
pub const CREATE_TABLE_UPLOADS: &str = include_str!("./sql/create_uploads.sql");
|
||||
pub const CREATE_TABLE_EMOJIS: &str = include_str!("./sql/create_emojis.sql");
|
||||
pub const CREATE_TABLE_STACKS: &str = include_str!("./sql/create_stacks.sql");
|
||||
|
|
8
crates/core/src/database/drivers/sql/create_stacks.sql
Normal file
8
crates/core/src/database/drivers/sql/create_stacks.sql
Normal file
|
@ -0,0 +1,8 @@
|
|||
CREATE TABLE IF NOT EXISTS stacks (
|
||||
id BIGINT NOT NULL PRIMARY KEY,
|
||||
created BIGINT NOT NULL,
|
||||
owner BIGINT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
users TEXT NOT NULL,
|
||||
privacy TEXT NOT NULL
|
||||
)
|
|
@ -14,6 +14,7 @@ mod questions;
|
|||
mod reactions;
|
||||
mod reports;
|
||||
mod requests;
|
||||
mod stacks;
|
||||
mod uploads;
|
||||
mod user_warnings;
|
||||
mod userblocks;
|
||||
|
|
|
@ -732,6 +732,55 @@ impl DataManager {
|
|||
Ok(res.unwrap())
|
||||
}
|
||||
|
||||
/// Get posts from all users in the given stack.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `id` - the ID of the stack
|
||||
/// * `batch` - the limit of posts in each page
|
||||
/// * `page` - the page number
|
||||
pub async fn get_posts_from_stack(
|
||||
&self,
|
||||
id: usize,
|
||||
batch: usize,
|
||||
page: usize,
|
||||
) -> Result<Vec<Post>> {
|
||||
let users = self.get_stack_by_id(id).await?.users;
|
||||
let mut users = users.iter();
|
||||
|
||||
let first = match users.next() {
|
||||
Some(f) => f,
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
|
||||
let mut query_string: String = String::new();
|
||||
|
||||
for user in users {
|
||||
query_string.push_str(&format!(" OR owner = {}", user));
|
||||
}
|
||||
|
||||
// ...
|
||||
let conn = match self.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
let res = query_rows!(
|
||||
&conn,
|
||||
&format!(
|
||||
"SELECT * FROM posts WHERE (owner = {} {query_string}) AND replying_to = 0 ORDER BY created DESC LIMIT $1 OFFSET $2",
|
||||
first
|
||||
),
|
||||
&[&(batch as i64), &((page * batch) as i64)],
|
||||
|x| { Self::get_post_from_row(x) }
|
||||
);
|
||||
|
||||
if res.is_err() {
|
||||
return Err(Error::GeneralNotFound("post".to_string()));
|
||||
}
|
||||
|
||||
Ok(res.unwrap())
|
||||
}
|
||||
|
||||
/// Check if the given `uid` can post in the given `community`.
|
||||
pub async fn check_can_post(&self, community: &Community, uid: usize) -> bool {
|
||||
match community.write_access {
|
||||
|
|
133
crates/core/src/database/stacks.rs
Normal file
133
crates/core/src/database/stacks.rs
Normal file
|
@ -0,0 +1,133 @@
|
|||
use super::*;
|
||||
use crate::cache::Cache;
|
||||
use crate::model::{
|
||||
Error, Result,
|
||||
auth::User,
|
||||
permissions::FinePermission,
|
||||
stacks::{StackPrivacy, UserStack},
|
||||
};
|
||||
use crate::{auto_method, execute, get, query_row, query_rows, params};
|
||||
|
||||
#[cfg(feature = "sqlite")]
|
||||
use rusqlite::Row;
|
||||
|
||||
#[cfg(feature = "postgres")]
|
||||
use tokio_postgres::Row;
|
||||
|
||||
impl DataManager {
|
||||
/// Get a [`UserStack`] from an SQL row.
|
||||
pub(crate) fn get_stack_from_row(
|
||||
#[cfg(feature = "sqlite")] x: &Row<'_>,
|
||||
#[cfg(feature = "postgres")] x: &Row,
|
||||
) -> UserStack {
|
||||
UserStack {
|
||||
id: get!(x->0(i64)) as usize,
|
||||
created: get!(x->1(i64)) as usize,
|
||||
owner: get!(x->2(i64)) as usize,
|
||||
name: get!(x->3(String)),
|
||||
users: serde_json::from_str(&get!(x->4(String))).unwrap(),
|
||||
privacy: serde_json::from_str(&get!(x->5(String))).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
auto_method!(get_stack_by_id(usize as i64)@get_stack_from_row -> "SELECT * FROM stacks WHERE id = $1" --name="stack" --returns=UserStack --cache-key-tmpl="atto.stack:{}");
|
||||
|
||||
/// Get all stacks by user.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `id` - the ID of the user to fetch stacks for
|
||||
pub async fn get_stacks_by_owner(&self, id: usize) -> Result<Vec<UserStack>> {
|
||||
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 stacks WHERE owner = $1 ORDER BY name ASC",
|
||||
&[&(id as i64)],
|
||||
|x| { Self::get_stack_from_row(x) }
|
||||
);
|
||||
|
||||
if res.is_err() {
|
||||
return Err(Error::GeneralNotFound("stack".to_string()));
|
||||
}
|
||||
|
||||
Ok(res.unwrap())
|
||||
}
|
||||
|
||||
/// Create a new stack in the database.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `data` - a mock [`UserStack`] object to insert
|
||||
pub async fn create_stack(&self, data: UserStack) -> Result<UserStack> {
|
||||
// check number of stacks
|
||||
let owner = self.get_user_by_id(data.owner).await?;
|
||||
|
||||
if !owner.permissions.check(FinePermission::SUPPORTER) {
|
||||
let stacks = self.get_stacks_by_owner(data.owner).await?;
|
||||
let maximum_count = 5;
|
||||
|
||||
if stacks.len() >= maximum_count {
|
||||
return Err(Error::MiscError(
|
||||
"You already have the maximum number of stacks you can have".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
let conn = match self.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
let res = execute!(
|
||||
&conn,
|
||||
"INSERT INTO stacks VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
params![
|
||||
&(data.id as i64),
|
||||
&(data.created as i64),
|
||||
&(data.owner as i64),
|
||||
&data.name,
|
||||
&serde_json::to_string(&data.users).unwrap(),
|
||||
&serde_json::to_string(&data.privacy).unwrap(),
|
||||
]
|
||||
);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub async fn delete_stack(&self, id: usize, user: &User) -> Result<()> {
|
||||
let stack = self.get_stack_by_id(id).await?;
|
||||
|
||||
// check user permission
|
||||
if user.id != stack.owner {
|
||||
if !user.permissions.check(FinePermission::MANAGE_STACKS) {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
}
|
||||
|
||||
// ...
|
||||
let conn = match self.connect().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
|
||||
};
|
||||
|
||||
let res = execute!(&conn, "DELETE FROM stacks WHERE id = $1", &[&(id as i64)]);
|
||||
|
||||
if let Err(e) = res {
|
||||
return Err(Error::DatabaseError(e.to_string()));
|
||||
}
|
||||
|
||||
self.2.remove(format!("atto.stack:{}", id)).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
auto_method!(update_stack_name(&str)@get_stack_by_id:MANAGE_STACKS -> "UPDATE stacks SET name = $1 WHERE id = $2" --cache-key-tmpl="atto.stack:{}");
|
||||
auto_method!(update_stack_privacy(StackPrivacy)@get_stack_by_id:MANAGE_STACKS -> "UPDATE stacks SET privacy = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.stack:{}");
|
||||
auto_method!(update_stack_users(Vec<usize>)@get_stack_by_id:MANAGE_STACKS -> "UPDATE stacks SET users = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.stack:{}");
|
||||
}
|
|
@ -6,6 +6,7 @@ pub mod oauth;
|
|||
pub mod permissions;
|
||||
pub mod reactions;
|
||||
pub mod requests;
|
||||
pub mod stacks;
|
||||
pub mod uploads;
|
||||
|
||||
#[cfg(feature = "redis")]
|
||||
|
|
|
@ -34,6 +34,7 @@ bitflags! {
|
|||
const MANAGE_MESSAGES = 1 << 23;
|
||||
const MANAGE_UPLOADS = 1 << 24;
|
||||
const MANAGE_EMOJIS = 1 << 25;
|
||||
const MANAGE_STACKS = 1 << 26;
|
||||
|
||||
const _ = !0;
|
||||
}
|
||||
|
|
40
crates/core/src/model/stacks.rs
Normal file
40
crates/core/src/model/stacks.rs
Normal file
|
@ -0,0 +1,40 @@
|
|||
use serde::{Serialize, Deserialize};
|
||||
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum StackPrivacy {
|
||||
/// Can be viewed by anyone.
|
||||
Public,
|
||||
/// Can only be viewed by the stack's owner (and users with `MANAGE_STACKS`).
|
||||
Private,
|
||||
}
|
||||
|
||||
impl Default for StackPrivacy {
|
||||
fn default() -> Self {
|
||||
Self::Private
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct UserStack {
|
||||
pub id: usize,
|
||||
pub created: usize,
|
||||
pub owner: usize,
|
||||
pub name: String,
|
||||
pub users: Vec<usize>,
|
||||
pub privacy: StackPrivacy,
|
||||
}
|
||||
|
||||
impl UserStack {
|
||||
/// Create a new [`UserStack`].
|
||||
pub fn new(name: String, owner: usize, users: Vec<usize>) -> Self {
|
||||
Self {
|
||||
id: Snowflake::new().to_string().parse::<usize>().unwrap(),
|
||||
created: unix_epoch_timestamp() as usize,
|
||||
owner,
|
||||
name,
|
||||
users,
|
||||
privacy: StackPrivacy::default(),
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue