Skip to main content

tetratto_core2/database/
drafts.rs

1use oiseau::cache::Cache;
2use crate::model::id::Id;
3use crate::model::moderation::AuditLogEntry;
4use crate::model::{Error, Result, auth::User, posts::PostDraft, permissions::FinePermission};
5use crate::{auto_method, DataManager};
6
7use oiseau::PostgresRow;
8
9use oiseau::{execute, get, query_rows, params};
10
11impl DataManager {
12    /// Get a [`PostDraft`] from an SQL row.
13    pub(crate) fn get_draft_from_row(x: &PostgresRow) -> PostDraft {
14        PostDraft {
15            id: Id::deserialize(&get!(x->0(String))),
16            created: get!(x->1(i64)) as u128,
17            content: get!(x->2(String)),
18            owner: Id::deserialize(&get!(x->3(String))),
19        }
20    }
21
22    auto_method!(get_draft_by_id()@get_draft_from_row -> "SELECT * FROM drafts WHERE id = $1" --name="draft" --returns=PostDraft --cache-key-tmpl="atto.draft:{}");
23
24    /// Get all drafts from the given user (from most recent, paginated).
25    ///
26    /// # Arguments
27    /// * `id` - the ID of the user the requested drafts belong to
28    /// * `batch` - the limit of posts in each page
29    /// * `page` - the page number
30    pub async fn get_drafts_by_user(
31        &self,
32        id: &Id,
33        batch: usize,
34        page: usize,
35    ) -> Result<Vec<PostDraft>> {
36        let conn = match self.0.connect().await {
37            Ok(c) => c,
38            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
39        };
40
41        // ...
42        let res = query_rows!(
43            &conn,
44            "SELECT * FROM drafts WHERE owner = $1 ORDER BY created DESC LIMIT $2 OFFSET $3",
45            &[&id.printable(), &(batch as i64), &((page * batch) as i64)],
46            |x| { Self::get_draft_from_row(x) }
47        );
48
49        if res.is_err() {
50            return Err(Error::GeneralNotFound("draft".to_string()));
51        }
52
53        Ok(res.unwrap())
54    }
55
56    /// Get all drafts from the given user (from most recent).
57    ///
58    /// # Arguments
59    /// * `id` - the ID of the user the requested drafts belong to
60    pub async fn get_drafts_by_user_all(&self, id: &Id) -> Result<Vec<PostDraft>> {
61        let conn = match self.0.connect().await {
62            Ok(c) => c,
63            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
64        };
65
66        // ...
67        let res = query_rows!(
68            &conn,
69            "SELECT * FROM drafts WHERE owner = $1 ORDER BY created DESC",
70            &[&id.printable()],
71            |x| { Self::get_draft_from_row(x) }
72        );
73
74        if res.is_err() {
75            return Err(Error::GeneralNotFound("draft".to_string()));
76        }
77
78        Ok(res.unwrap())
79    }
80
81    const MAXIMUM_FREE_DRAFTS: usize = 10;
82
83    /// Create a new post draft in the database.
84    ///
85    /// # Arguments
86    /// * `data` - a mock [`PostDraft`] object to insert
87    pub async fn create_draft(&self, data: PostDraft) -> Result<Id> {
88        // check values
89        if data.content.len() < 2 {
90            return Err(Error::DataTooShort("content".to_string()));
91        } else if data.content.len() > 4096 {
92            return Err(Error::DataTooLong("content".to_string()));
93        }
94
95        // check number of stacks
96        let owner = self.get_user_by_id(&data.owner).await?;
97
98        if !owner.permissions.check(FinePermission::Supporter) {
99            let drafts = self.get_drafts_by_user_all(&data.owner).await?;
100
101            if drafts.len() >= Self::MAXIMUM_FREE_DRAFTS {
102                return Err(Error::MiscError(
103                    "You already have the maximum number of drafts you can have".to_string(),
104                ));
105            }
106        }
107
108        // ...
109        let conn = match self.0.connect().await {
110            Ok(c) => c,
111            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
112        };
113
114        let res = execute!(
115            &conn,
116            "INSERT INTO drafts VALUES ($1, $2, $3, $4)",
117            params![
118                &data.id.printable(),
119                &(data.created as i64),
120                &data.content,
121                &data.owner.printable(),
122            ]
123        );
124
125        if let Err(e) = res {
126            return Err(Error::DatabaseError(e.to_string()));
127        }
128
129        Ok(data.id)
130    }
131
132    pub async fn delete_draft(&self, id: &crate::model::id::Id, user: User) -> Result<()> {
133        let y = self.get_draft_by_id(id).await?;
134
135        if user.id != y.owner {
136            if !user.permissions.check(FinePermission::ManagePosts) {
137                return Err(Error::NotAllowed);
138            } else {
139                self.create_audit_log_entry(AuditLogEntry::new(
140                    user.id,
141                    format!("invoked `delete_draft` with x value `{id}`"),
142                ))
143                .await?
144            }
145        }
146        let conn = match self.0.connect().await {
147            Ok(c) => c,
148            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
149        };
150
151        let res = execute!(
152            &conn,
153            "DELETE FROM drafts WHERE id = $1",
154            &[&id.printable()]
155        );
156
157        if let Err(e) = res {
158            return Err(Error::DatabaseError(e.to_string()));
159        }
160
161        self.0.1.remove(format!("atto.draft:{}", id)).await;
162
163        Ok(())
164    }
165
166    pub async fn update_draft_content(
167        &self,
168        id: &crate::model::id::Id,
169        user: User,
170        x: String,
171    ) -> Result<()> {
172        let y = self.get_draft_by_id(id).await?;
173
174        if user.id != y.owner {
175            if !user.permissions.check(FinePermission::ManagePosts) {
176                return Err(Error::NotAllowed);
177            } else {
178                self.create_audit_log_entry(AuditLogEntry::new(
179                    user.id,
180                    format!("invoked `update_draft_content` with x value `{id}`"),
181                ))
182                .await?
183            }
184        }
185
186        // ...
187        let conn = match self.0.connect().await {
188            Ok(c) => c,
189            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
190        };
191
192        let res = execute!(
193            &conn,
194            "UPDATE drafts SET content = $1 WHERE id = $2",
195            params![&x, &id.printable()]
196        );
197
198        if let Err(e) = res {
199            return Err(Error::DatabaseError(e.to_string()));
200        }
201
202        Ok(())
203    }
204}