tetratto-core 15.0.2

The core behind Tetratto
Documentation
use serde::{Serialize, Deserialize};
use tetratto_shared::{snow::Snowflake, unix_epoch_timestamp};
use crate::model::auth::User;

/// A letter is the most basic structure of the mail system. Letters are sent
/// and received by users.
#[derive(Serialize, Deserialize)]
pub struct Letter {
    pub id: usize,
    pub created: usize,
    pub owner: usize,
    pub receivers: Vec<usize>,
    pub subject: String,
    pub content: String,
    /// The ID of every use who has read the letter. Can be checked in the UI
    /// with `user.id in letter.read_by`.
    ///
    /// This field can be updated by anyone in the letter's `receivers` field.
    /// Other fields in the letter can only be updated by the letter's `owner`.
    pub read_by: Vec<usize>,
    /// The ID of the letter this letter is replying to.
    pub replying_to: usize,
    pub likes: isize,
    pub dislikes: isize,
}

impl Letter {
    /// Create a new [`Letter`].
    pub fn new(
        owner: usize,
        receivers: Vec<usize>,
        subject: String,
        content: String,
        replying_to: usize,
    ) -> Self {
        Self {
            id: Snowflake::new().to_string().parse::<usize>().unwrap(),
            created: unix_epoch_timestamp(),
            owner,
            receivers,
            subject,
            content,
            read_by: Vec::new(),
            replying_to,
            likes: 0,
            dislikes: 0,
        }
    }

    /// Check if the given user can read the letter.
    pub fn can_read(&self, user: &User) -> bool {
        (user.id == self.owner) | self.receivers.contains(&user.id)
    }
}