tetratto-core 17.0.0

The core behind Tetratto
Documentation
use oiseau::{cache::Cache, query_row};
use crate::{
    database::common::NAME_REGEX,
    model::{
        auth::User,
        journals::{Journal, JournalPrivacyPermission},
        permissions::FinePermission,
        Error, Result,
    },
};
use crate::{auto_method, DataManager};
use oiseau::{PostgresRow, execute, get, query_rows, params};

impl DataManager {
    /// Get a [`Journal`] from an SQL row.
    pub(crate) fn get_journal_from_row(x: &PostgresRow) -> Journal {
        Journal {
            id: get!(x->0(i64)) as usize,
            created: get!(x->1(i64)) as usize,
            owner: get!(x->2(i64)) as usize,
            title: get!(x->3(String)),
            privacy: serde_json::from_str(&get!(x->4(String))).unwrap(),
            dirs: serde_json::from_str(&get!(x->5(String))).unwrap(),
        }
    }

    auto_method!(get_journal_by_id(usize as i64)@get_journal_from_row -> "SELECT * FROM journals WHERE id = $1" --name="journal" --returns=Journal --cache-key-tmpl="atto.journal:{}");

    /// Get a journal by `owner` and `title`.
    pub async fn get_journal_by_owner_title(&self, owner: usize, title: &str) -> Result<Journal> {
        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 journals WHERE owner = $1 AND title = $2",
            params![&(owner as i64), &title],
            |x| { Ok(Self::get_journal_from_row(x)) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("journal".to_string()));
        }

        Ok(res.unwrap())
    }

    /// Get all journals by user.
    ///
    /// # Arguments
    /// * `id` - the ID of the user to fetch journals for
    pub async fn get_journals_by_user(&self, id: usize) -> Result<Vec<Journal>> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM journals WHERE owner = $1 ORDER BY title ASC",
            &[&(id as i64)],
            |x| { Self::get_journal_from_row(x) }
        );

        if res.is_err() {
            return Err(Error::GeneralNotFound("journal".to_string()));
        }

        Ok(res.unwrap())
    }

    const MAXIMUM_FREE_JOURNALS: usize = 5;

    /// Create a new journal in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`Journal`] object to insert
    pub async fn create_journal(&self, mut data: Journal) -> Result<Journal> {
        // check values
        if data.title.len() < 2 {
            return Err(Error::DataTooShort("title".to_string()));
        } else if data.title.len() > 32 {
            return Err(Error::DataTooLong("title".to_string()));
        }

        data.title = data.title.replace(" ", "_").to_lowercase();

        // check name
        let regex = regex::RegexBuilder::new(NAME_REGEX)
            .multi_line(true)
            .build()
            .unwrap();

        if regex.captures(&data.title).is_some() {
            return Err(Error::MiscError(
                "This title contains invalid characters".to_string(),
            ));
        }

        // make sure this title isn't already in use
        if self
            .get_journal_by_owner_title(data.owner, &data.title)
            .await
            .is_ok()
        {
            return Err(Error::TitleInUse);
        }

        // check number of journals
        let owner = self.get_user_by_id(data.owner).await?;

        if !owner.permissions.check(FinePermission::SUPPORTER) {
            let journals = self.get_journals_by_user(data.owner).await?;

            if journals.len() >= Self::MAXIMUM_FREE_JOURNALS {
                return Err(Error::MiscError(
                    "You already have the maximum number of journals you can have".to_string(),
                ));
            }
        }

        // ...
        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 journals VALUES ($1, $2, $3, $4, $5, $6)",
            params![
                &(data.id as i64),
                &(data.created as i64),
                &(data.owner as i64),
                &data.title,
                &serde_json::to_string(&data.privacy).unwrap(),
                &serde_json::to_string(&data.dirs).unwrap(),
            ]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        Ok(data)
    }

    pub async fn delete_journal(&self, id: usize, user: &User) -> Result<()> {
        let journal = self.get_journal_by_id(id).await?;

        // check user permission
        if user.id != journal.owner && !user.permissions.check(FinePermission::MANAGE_JOURNALS) {
            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 journals WHERE id = $1", &[&(id as i64)]);

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // delete notes
        let res = execute!(
            &conn,
            "DELETE FROM notes WHERE journal = $1",
            &[&(id as i64)]
        );

        if let Err(e) = res {
            return Err(Error::DatabaseError(e.to_string()));
        }

        // ...
        self.0.1.remove(format!("atto.journal:{}", id)).await;
        Ok(())
    }

    auto_method!(update_journal_title(&str)@get_journal_by_id:FinePermission::MANAGE_JOURNALS; -> "UPDATE journals SET title = $1 WHERE id = $2" --cache-key-tmpl="atto.journal:{}");
    auto_method!(update_journal_privacy(JournalPrivacyPermission)@get_journal_by_id:FinePermission::MANAGE_JOURNALS; -> "UPDATE journals SET privacy = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
    auto_method!(update_journal_dirs(Vec<(usize, usize, String)>)@get_journal_by_id:FinePermission::MANAGE_JOURNALS; -> "UPDATE journals SET dirs = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.journal:{}");
}