add: questions, requests

This commit is contained in:
trisua 2025-04-12 22:25:54 -04:00
parent 24f67221ca
commit 7960484bf9
52 changed files with 1698 additions and 100 deletions

View file

@ -41,12 +41,39 @@ impl DataManager {
last_seen: get!(x->12(i64)) as usize,
totp: get!(x->13(String)),
recovery_codes: serde_json::from_str(&get!(x->14(String)).to_string()).unwrap(),
post_count: get!(x->15(i32)) as usize,
request_count: get!(x->16(i32)) as usize,
}
}
auto_method!(get_user_by_id(usize as i64)@get_user_from_row -> "SELECT * FROM users WHERE id = $1" --name="user" --returns=User --cache-key-tmpl="atto.user:{}");
auto_method!(get_user_by_username(&str)@get_user_from_row -> "SELECT * FROM users WHERE username = $1" --name="user" --returns=User --cache-key-tmpl="atto.user:{}");
/// Get a user given just their ID. Returns the void user if the user doesn't exist.
///
/// # Arguments
/// * `id` - the ID of the user
pub async fn get_user_by_id_with_void(&self, id: usize) -> Result<User> {
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 users WHERE id = $1",
&[&(id as i64)],
|x| Ok(Self::get_user_from_row(x))
);
if res.is_err() {
return Ok(User::deleted());
// return Err(Error::UserNotFound);
}
Ok(res.unwrap())
}
/// Get a user given just their auth token.
///
/// # Arguments
@ -110,7 +137,7 @@ impl DataManager {
let res = execute!(
&conn,
"INSERT INTO users VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)",
"INSERT INTO users VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)",
params![
&(data.id as i64),
&(data.created as i64),
@ -126,7 +153,9 @@ impl DataManager {
&0_i32,
&(data.last_seen as i64),
&String::new(),
&"[]"
&"[]",
&0_i32,
&0_i32
]
);
@ -559,4 +588,10 @@ impl DataManager {
auto_method!(incr_user_following_count()@get_user_by_id -> "UPDATE users SET following_count = following_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_user --incr);
auto_method!(decr_user_following_count()@get_user_by_id -> "UPDATE users SET following_count = following_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_user --decr);
auto_method!(incr_user_post_count()@get_user_by_id -> "UPDATE users SET post_count = post_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_user --incr);
auto_method!(decr_user_post_count()@get_user_by_id -> "UPDATE users SET post_count = post_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_user --decr);
auto_method!(incr_user_request_count()@get_user_by_id -> "UPDATE users SET request_count = request_count + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_user --incr);
auto_method!(decr_user_request_count()@get_user_by_id -> "UPDATE users SET request_count = request_count - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_user --decr);
}

View file

@ -25,6 +25,8 @@ impl DataManager {
execute!(&conn, common::CREATE_TABLE_AUDIT_LOG).unwrap();
execute!(&conn, common::CREATE_TABLE_REPORTS).unwrap();
execute!(&conn, common::CREATE_TABLE_USER_WARNINGS).unwrap();
execute!(&conn, common::CREATE_TABLE_REQUESTS).unwrap();
execute!(&conn, common::CREATE_TABLE_QUESTIONS).unwrap();
Ok(())
}

View file

@ -10,3 +10,5 @@ pub const CREATE_TABLE_IPBANS: &str = include_str!("./sql/create_ipbans.sql");
pub const CREATE_TABLE_AUDIT_LOG: &str = include_str!("./sql/create_audit_log.sql");
pub const CREATE_TABLE_REPORTS: &str = include_str!("./sql/create_reports.sql");
pub const CREATE_TABLE_USER_WARNINGS: &str = include_str!("./sql/create_user_warnings.sql");
pub const CREATE_TABLE_REQUESTS: &str = include_str!("./sql/create_requests.sql");
pub const CREATE_TABLE_QUESTIONS: &str = include_str!("./sql/create_questions.sql");

View file

@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS questions (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
receiver BIGINT NOT NULL,
content TEXT NOT NULL,
is_global INT NOT NULL,
answer_count INT NOT NULL,
community BIGINT NOT NULL
)

View file

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS requests (
id BIGINT NOT NULL PRIMARY KEY,
created BIGINT NOT NULL,
owner BIGINT NOT NULL,
action_type TEXT NOT NULL,
linked_asset BIGINT NOT NULL
)

View file

@ -11,5 +11,9 @@ CREATE TABLE IF NOT EXISTS users (
notification_count INT NOT NULL,
follower_count INT NOT NULL,
following_count INT NOT NULL,
last_seen BIGINT NOT NULL
last_seen BIGINT NOT NULL,
totp TEXT NOT NULL,
recovery_codes TEXT NOT NULL,
post_count INT NOT NULL,
request_count INT NOT NULL
)

View file

@ -1,7 +1,7 @@
use super::*;
use crate::cache::Cache;
use crate::model::auth::Notification;
use crate::model::communities::Community;
use crate::model::requests::{ActionRequest, ActionType};
use crate::model::{
Error, Result,
auth::User,
@ -191,14 +191,12 @@ impl DataManager {
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/user/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
),
// create join request
self.create_request(ActionRequest::with_id(
data.owner,
community.owner,
ActionType::CommunityJoin,
community.id,
))
.await?;

View file

@ -7,8 +7,10 @@ mod ipbans;
mod memberships;
mod notifications;
mod posts;
mod questions;
mod reactions;
mod reports;
mod requests;
mod user_warnings;
mod userblocks;
mod userfollows;

View file

@ -51,7 +51,7 @@ impl DataManager {
/// Create a new notification in the database.
///
/// # Arguments
/// * `data` - a mock [`Reaction`] object to insert
/// * `data` - a mock [`Notification`] object to insert
pub async fn create_notification(&self, data: Notification) -> Result<()> {
let conn = match self.connect().await {
Ok(c) => c,
@ -85,7 +85,9 @@ impl DataManager {
pub async fn delete_notification(&self, id: usize, user: &User) -> Result<()> {
let notification = self.get_notification_by_id(id).await?;
if user.id != notification.owner && !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) {
if user.id != notification.owner
&& !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS)
{
return Err(Error::NotAllowed);
}
@ -121,7 +123,9 @@ impl DataManager {
let notifications = self.get_notifications_by_owner(user.id).await?;
for notification in notifications {
if user.id != notification.owner && !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) {
if user.id != notification.owner
&& !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS)
{
return Err(Error::NotAllowed);
}

View file

@ -3,6 +3,7 @@ use std::collections::HashMap;
use super::*;
use crate::cache::Cache;
use crate::model::auth::Notification;
use crate::model::communities::Question;
use crate::model::communities_permissions::CommunityPermission;
use crate::model::moderation::AuditLogEntry;
use crate::model::{
@ -100,12 +101,23 @@ impl DataManager {
}
}
/// Get the question of a given post.
pub async fn get_post_question(&self, post: &Post) -> Result<Option<(Question, User)>> {
if post.context.answering != 0 {
let question = self.get_question_by_id(post.context.answering).await?;
let user = self.get_user_by_id_with_void(question.owner).await?;
Ok(Some((question, user)))
} else {
Ok(None)
}
}
/// Complete a vector of just posts with their owner as well.
pub async fn fill_posts(
&self,
posts: Vec<Post>,
) -> Result<Vec<(Post, User, Option<(User, Post)>)>> {
let mut out: Vec<(Post, User, Option<(User, Post)>)> = Vec::new();
) -> Result<Vec<(Post, User, Option<(User, Post)>, Option<(Question, User)>)>> {
let mut out: Vec<(Post, User, Option<(User, Post)>, Option<(Question, User)>)> = Vec::new();
let mut users: HashMap<usize, User> = HashMap::new();
for post in posts {
@ -116,11 +128,17 @@ impl DataManager {
post.clone(),
user.clone(),
self.get_post_reposting(&post).await,
self.get_post_question(&post).await?,
));
} else {
let user = self.get_user_by_id(owner).await?;
users.insert(owner, user.clone());
out.push((post.clone(), user, self.get_post_reposting(&post).await));
out.push((
post.clone(),
user,
self.get_post_reposting(&post).await,
self.get_post_question(&post).await?,
));
}
}
@ -132,8 +150,22 @@ impl DataManager {
&self,
posts: Vec<Post>,
user_id: usize,
) -> Result<Vec<(Post, User, Community, Option<(User, Post)>)>> {
let mut out: Vec<(Post, User, Community, Option<(User, Post)>)> = Vec::new();
) -> Result<
Vec<(
Post,
User,
Community,
Option<(User, Post)>,
Option<(Question, User)>,
)>,
> {
let mut out: Vec<(
Post,
User,
Community,
Option<(User, Post)>,
Option<(Question, User)>,
)> = Vec::new();
let mut seen_before: HashMap<(usize, usize), (User, Community)> = HashMap::new();
let mut seen_user_follow_statuses: HashMap<(usize, usize), bool> = HashMap::new();
@ -148,6 +180,7 @@ impl DataManager {
user.clone(),
community.to_owned(),
self.get_post_reposting(&post).await,
self.get_post_question(&post).await?,
));
} else {
let user = self.get_user_by_id(owner).await?;
@ -186,6 +219,7 @@ impl DataManager {
user,
community,
self.get_post_reposting(&post).await,
self.get_post_question(&post).await?,
));
}
}
@ -303,6 +337,66 @@ impl DataManager {
Ok(res.unwrap())
}
/// Get all posts answering the given question (from most recent).
///
/// # Arguments
/// * `id` - the ID of the question the requested posts belong to
/// * `batch` - the limit of posts in each page
/// * `page` - the page number
pub async fn get_posts_by_question(
&self,
id: usize,
batch: usize,
page: usize,
) -> Result<Vec<Post>> {
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 posts WHERE context LIKE $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
params![
&format!("%\"answering\":{id}%"),
&(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())
}
/// Get a post given its owner and question ID.
///
/// # Arguments
/// * `owner` - the ID of the post owner
/// * `question` - the ID of the post question
pub async fn get_post_by_owner_question(&self, owner: usize, question: usize) -> Result<Post> {
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 posts WHERE context LIKE $1 AND owner = $2 LIMIT 1",
params![&format!("%\"answering\":{question}%"), &(owner as i64),],
|x| { Ok(Self::get_post_from_row(x)) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("post".to_string()));
}
Ok(res.unwrap())
}
/// Get posts from all communities, sorted by likes.
///
/// # Arguments
@ -508,6 +602,42 @@ impl DataManager {
// mirror nsfw state
data.context.is_nsfw = community.context.is_nsfw;
// remove request if we were answering a question
let owner = self.get_user_by_id(data.owner).await?;
if data.context.answering != 0 {
let question = self.get_question_by_id(data.context.answering).await?;
// check if we've already answered this
if self
.get_post_by_owner_question(owner.id, question.id)
.await
.is_ok()
{
return Err(Error::MiscError(
"You've already answered this question".to_string(),
));
}
if !question.is_global {
self.delete_request(question.owner, question.id, &owner)
.await?;
} else {
self.incr_question_answer_count(data.context.answering)
.await?;
}
// create notification for question owner
self.create_notification(Notification::new(
"Your question has received a new answer!".to_string(),
format!(
"[@{}](/api/v1/auth/user/find/{}) has answered your [question](/question/{}).",
owner.username, owner.id, question.id
),
question.owner,
))
.await?;
}
// check if we're reposting a post
let reposting = if let Some(ref repost) = data.context.repost {
if let Some(id) = repost.reposting {
@ -650,6 +780,9 @@ impl DataManager {
}
}
// increase user post count
self.incr_user_post_count(data.owner).await?;
// return
Ok(data.id)
}
@ -695,6 +828,22 @@ impl DataManager {
self.decr_post_comments(replying_to).await.unwrap();
}
// decr user post count
let owner = self.get_user_by_id(y.owner).await?;
if owner.post_count > 0 {
self.decr_user_post_count(y.owner).await?;
}
// decr question answer count
if y.context.answering != 0 {
let question = self.get_question_by_id(y.context.answering).await?;
if question.is_global {
self.incr_question_answer_count(y.context.answering).await?;
}
}
// return
Ok(())
}
@ -707,6 +856,7 @@ impl DataManager {
) -> Result<()> {
let y = self.get_post_by_id(id).await?;
x.repost = y.context.repost; // cannot change repost settings at all
x.answering = y.context.answering; // cannot change answering settings at all
let user_membership = self
.get_membership_by_owner_community(user.id, y.community)

View file

@ -0,0 +1,261 @@
use std::collections::HashMap;
use super::*;
use crate::cache::Cache;
use crate::model::{
Error, Result,
communities::Question,
requests::{ActionRequest, ActionType},
auth::User,
permissions::FinePermission,
};
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 [`Question`] from an SQL row.
pub(crate) fn get_question_from_row(
#[cfg(feature = "sqlite")] x: &Row<'_>,
#[cfg(feature = "postgres")] x: &Row,
) -> Question {
Question {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
receiver: get!(x->3(i64)) as usize,
content: get!(x->4(String)),
is_global: get!(x->5(i32)) as i8 == 1,
answer_count: get!(x->6(i32)) as usize,
community: get!(x->7(i64)) as usize,
}
}
auto_method!(get_question_by_id()@get_question_from_row -> "SELECT * FROM questions WHERE id = $1" --name="question" --returns=Question --cache-key-tmpl="atto.question:{}");
/// Fill the given vector of questions with their owner as well.
pub async fn fill_questions(&self, questions: Vec<Question>) -> Result<Vec<(Question, User)>> {
let mut out: Vec<(Question, User)> = Vec::new();
let mut seen_users: HashMap<usize, User> = HashMap::new();
for question in questions {
if let Some(ua) = seen_users.get(&question.owner) {
out.push((question, ua.to_owned()));
} else {
let user = self.get_user_by_id_with_void(question.owner).await?;
seen_users.insert(question.owner, user.clone());
out.push((question, user));
}
}
Ok(out)
}
/// Get all questions by `owner`.
pub async fn get_questions_by_owner(&self, owner: usize) -> Result<Vec<Question>> {
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 questions WHERE owner = $1 ORDER BY created DESC",
&[&(owner as i64)],
|x| { Self::get_question_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("question".to_string()));
}
Ok(res.unwrap())
}
/// Get all questions by `receiver`.
pub async fn get_questions_by_receiver(&self, receiver: usize) -> Result<Vec<Question>> {
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 questions WHERE receiver = $1 ORDER BY created DESC",
&[&(receiver as i64)],
|x| { Self::get_question_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("question".to_string()));
}
Ok(res.unwrap())
}
/// Get all global questions by `community`.
pub async fn get_questions_by_community(
&self,
community: usize,
batch: usize,
page: usize,
) -> Result<Vec<Question>> {
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 questions WHERE community = $1 AND is_global = 1 ORDER BY created DESC LIMIT $2 OFFSET $3",
&[
&(community as i64),
&(batch as i64),
&((page * batch) as i64)
],
|x| { Self::get_question_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("question".to_string()));
}
Ok(res.unwrap())
}
/// Create a new question in the database.
///
/// # Arguments
/// * `data` - a mock [`Question`] object to insert
pub async fn create_question(&self, mut data: Question) -> Result<usize> {
// check if we can post this
if data.is_global {
if data.community > 0 {
// posting to community
data.receiver = 0;
let community = self.get_community_by_id(data.community).await?;
if !community.context.enable_questions
| !self.check_can_post(&community, data.owner).await
{
return Err(Error::QuestionsDisabled);
}
} else {
let receiver = self.get_user_by_id(data.receiver).await?;
if !receiver.settings.enable_questions {
return Err(Error::QuestionsDisabled);
}
}
} else {
let receiver = self.get_user_by_id(data.receiver).await?;
if !receiver.settings.enable_questions {
return Err(Error::QuestionsDisabled);
}
}
// ...
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO questions VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&(data.receiver as i64),
&data.content,
&{ if data.is_global { 1 } else { 0 } },
&0_i32,
&(data.community as i64)
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// create request
if !data.is_global {
self.create_request(ActionRequest::with_id(
data.owner,
data.receiver,
ActionType::Answer,
data.id,
))
.await?;
}
// return
Ok(data.id)
}
pub async fn delete_question(&self, id: usize, user: &User) -> Result<()> {
let y = self.get_question_by_id(id).await?;
if user.id != y.owner
&& user.id != y.receiver
&& !user.permissions.check(FinePermission::MANAGE_QUESTIONS)
{
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 questions WHERE id = $1",
&[&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.2.remove(format!("atto.question:{}", id)).await;
// delete request (if it exists and question isn't global)
if !y.is_global
&& self
.get_request_by_id_linked_asset(y.owner, y.id)
.await
.is_ok()
{
// requests are also deleted when a post is created answering the given question
// (unless the question is global)
self.delete_request(y.owner, y.id, &user).await?;
}
// return
Ok(())
}
pub async fn delete_all_questions(&self, user: &User) -> Result<()> {
let y = self.get_questions_by_receiver(user.id).await?;
for x in y {
if user.id != x.receiver && !user.permissions.check(FinePermission::MANAGE_QUESTIONS) {
return Err(Error::NotAllowed);
}
self.delete_question(x.id, user).await?
}
Ok(())
}
auto_method!(incr_question_answer_count() -> "UPDATE questions SET answer_count = answer_count + 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --incr);
auto_method!(decr_question_answer_count() -> "UPDATE questions SET answer_count = answer_count - 1 WHERE id = $1" --cache-key-tmpl="atto.question:{}" --decr);
}

View file

@ -0,0 +1,169 @@
use super::*;
use crate::cache::Cache;
use crate::model::requests::ActionType;
use crate::model::{Error, Result, requests::ActionRequest, auth::User, permissions::FinePermission};
use crate::{execute, get, query_row, query_rows, params};
#[cfg(feature = "sqlite")]
use rusqlite::Row;
#[cfg(feature = "postgres")]
use tokio_postgres::Row;
impl DataManager {
/// Get an [`ActionRequest`] from an SQL row.
pub(crate) fn get_request_from_row(
#[cfg(feature = "sqlite")] x: &Row<'_>,
#[cfg(feature = "postgres")] x: &Row,
) -> ActionRequest {
ActionRequest {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
action_type: serde_json::from_str(&get!(x->3(String))).unwrap(),
linked_asset: get!(x->4(i64)) as usize,
}
}
pub async fn get_request_by_id_linked_asset(
&self,
id: usize,
linked_asset: usize,
) -> Result<ActionRequest> {
if let Some(cached) = self
.2
.get(format!("atto.request:{}:{}", id, linked_asset))
.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 requests WHERE id = $1 AND linked_asset = $2",
&[&(id as i64), &(linked_asset as i64)],
|x| { Ok(Self::get_request_from_row(x)) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("request".to_string()));
}
let x = res.unwrap();
self.2
.set(
format!("atto.request:{}:{}", id, linked_asset),
serde_json::to_string(&x).unwrap(),
)
.await;
Ok(x)
}
/// Get all action requests by `owner`.
pub async fn get_requests_by_owner(&self, owner: usize) -> Result<Vec<ActionRequest>> {
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 requests WHERE owner = $1 ORDER BY created DESC",
&[&(owner as i64)],
|x| { Self::get_request_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("request".to_string()));
}
Ok(res.unwrap())
}
/// Create a new request in the database.
///
/// # Arguments
/// * `data` - a mock [`ActionRequest`] object to insert
pub async fn create_request(&self, data: ActionRequest) -> Result<()> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO requests VALUES ($1, $2, $3, $4, $5)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&serde_json::to_string(&data.action_type).unwrap().as_str(),
&(data.linked_asset as i64),
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// incr request count
self.incr_user_request_count(data.owner).await.unwrap();
// return
Ok(())
}
pub async fn delete_request(&self, id: usize, linked_asset: usize, user: &User) -> Result<()> {
let y = self
.get_request_by_id_linked_asset(id, linked_asset)
.await?;
if user.id != y.owner && !user.permissions.check(FinePermission::MANAGE_REQUESTS) {
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 requests WHERE id = $1", &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.2.remove(format!("atto.request:{}", id)).await;
// decr request count
self.decr_user_request_count(y.owner).await.unwrap();
// return
Ok(())
}
pub async fn delete_all_requests(&self, user: &User) -> Result<()> {
let y = self.get_requests_by_owner(user.id).await?;
for x in y {
if user.id != x.owner && !user.permissions.check(FinePermission::MANAGE_REQUESTS) {
return Err(Error::NotAllowed);
}
self.delete_request(x.id, x.linked_asset, user).await?;
// delete question
if x.action_type == ActionType::Answer {
self.delete_question(x.linked_asset, user).await?;
}
}
Ok(())
}
}