tetratto-core 18.0.2

The core behind Tetratto
Documentation
use oiseau::cache::Cache;
use crate::model::{Error, Result, auth::User, auth::UserBlock, permissions::FinePermission};
use crate::{auto_method, DataManager};

use oiseau::{PostgresRow, execute, get, query_row, query_rows, params};

impl DataManager {
    /// Get a [`UserBlock`] from an SQL row.
    pub(crate) fn get_userblock_from_row(x: &PostgresRow) -> UserBlock {
        UserBlock {
            id: get!(x->0(i64)) as usize,
            created: get!(x->1(i64)) as usize,
            initiator: get!(x->2(i64)) as usize,
            receiver: get!(x->3(i64)) as usize,
        }
    }

    auto_method!(get_userblock_by_id()@get_userblock_from_row -> "SELECT * FROM userblocks WHERE id = $1" --name="user block" --returns=UserBlock --cache-key-tmpl="atto.userblock:{}");

    /// Fill a vector of user blocks with their receivers.
    pub async fn fill_userblocks_receivers(&self, list: Vec<UserBlock>) -> Result<Vec<User>> {
        let mut out = Vec::new();

        for block in list {
            out.push(match self.get_user_by_id(block.receiver).await {
                Ok(ua) => ua,
                Err(_) => {
                    self.delete_userblock_sudo(block.id).await?;
                    continue;
                }
            });
        }

        Ok(out)
    }

    /// Get a user block by `initiator` and `receiver` (in that order).
    pub async fn get_userblock_by_initiator_receiver(
        &self,
        initiator: usize,
        receiver: usize,
    ) -> Result<UserBlock> {
        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 userblocks WHERE initiator = $1 AND receiver = $2",
            &[&(initiator as i64), &(receiver as i64)],
            |x| { Ok(Self::get_userblock_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get a user block by `receiver` and `initiator` (in that order).
    pub async fn get_userblock_by_receiver_initiator(
        &self,
        receiver: usize,
        initiator: usize,
    ) -> Result<UserBlock> {
        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 userblocks WHERE receiver = $1 AND initiator = $2",
            &[&(receiver as i64), &(initiator as i64)],
            |x| { Ok(Self::get_userblock_from_row(x)) }
        );

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

        Ok(res.unwrap())
    }

    /// Get the receiver of all user blocks for the given `initiator`.
    pub async fn get_userblocks_receivers(
        &self,
        initiator: usize,
        associated: &Vec<usize>,
        do_associated: bool,
    ) -> Vec<usize> {
        let mut associated_str = String::new();

        if do_associated {
            for id in associated {
                associated_str.push_str(&(" OR initiator = ".to_string() + &id.to_string()));
            }
        }

        // ...
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let res = query_rows!(
            &conn,
            &format!("SELECT * FROM userblocks WHERE initiator = $1{associated_str}"),
            &[&(initiator as i64)],
            |x| { Self::get_userblock_from_row(x) }
        );

        if res.is_err() {
            return Vec::new();
        }

        // get receivers
        let mut out: Vec<usize> = Vec::new();

        for b in res.unwrap() {
            out.push(b.receiver);
        }

        // return
        out
    }

    /// Get all user blocks created by the given `initiator`.
    pub async fn get_userblocks_by_initiator(&self, initiator: usize) -> Vec<UserBlock> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM userblocks WHERE initiator = $1",
            &[&(initiator as i64)],
            |x| { Self::get_userblock_from_row(x) }
        );

        if res.is_err() {
            return Vec::new();
        }

        // return
        res.unwrap()
    }

    /// Get the owner of all user blocks for the given `receiver`.
    pub async fn get_userblocks_initiator_by_receivers(&self, receiver: usize) -> Vec<usize> {
        let conn = match self.0.connect().await {
            Ok(c) => c,
            Err(_) => return Vec::new(),
        };

        let res = query_rows!(
            &conn,
            "SELECT * FROM userblocks WHERE receiver = $1",
            &[&(receiver as i64)],
            |x| { Self::get_userblock_from_row(x) }
        );

        if res.is_err() {
            return Vec::new();
        }

        // get owner
        let mut out: Vec<usize> = Vec::new();

        for b in res.unwrap() {
            out.push(b.initiator);
        }

        // return
        out
    }

    /// Create a new user block in the database.
    ///
    /// # Arguments
    /// * `data` - a mock [`UserBlock`] object to insert
    pub async fn create_userblock(&self, data: UserBlock) -> Result<()> {
        let initiator = self.get_user_by_id(data.initiator).await?;
        let receiver = self.get_user_by_id(data.receiver).await?;

        // ...
        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 userblocks VALUES ($1, $2, $3, $4)",
            params![
                &(data.id as i64),
                &(data.created as i64),
                &(data.initiator as i64),
                &(data.receiver as i64)
            ]
        );

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

        // remove initiator from receiver's communities
        for community in self.get_communities_by_owner(data.receiver).await? {
            if let Ok(membership) = self
                .get_membership_by_owner_community_no_void(data.initiator, community.id)
                .await
            {
                self.delete_membership_force(membership.id).await?;
            }
        }

        // unfollow/remove follower
        if let Ok(f) = self
            .get_userfollow_by_initiator_receiver(data.initiator, data.receiver)
            .await
        {
            self.delete_userfollow(f.id, &initiator, false).await?;
        }

        if let Ok(f) = self
            .get_userfollow_by_receiver_initiator(data.initiator, data.receiver)
            .await
        {
            self.delete_userfollow(f.id, &receiver, false).await?;
        }

        // return
        Ok(())
    }

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

        if user.id != block.initiator {
            // only the initiator (or moderators) can delete user 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 userblocks WHERE id = $1",
            &[&(id as i64)]
        );

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

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

        // return
        Ok(())
    }

    pub async fn delete_userblock_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 userblocks WHERE id = $1",
            &[&(id as i64)]
        );

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

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

        // return
        Ok(())
    }
}