laravel-comments 0.3.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! The package's settings.

use std::fmt;
use std::str::FromStr;

use laravel::config::Section;

/// The package's settings, read from the environment. An application changes them in
/// `with_config`:
///
/// ```no_run
/// # use laravel::Application;
/// use laravel_comments::CommentsConfig;
///
/// # let _ =
/// Application::configure().with_config(|config, _| {
///     config.section_mut::<CommentsConfig>().reactions = vec!["like".into(), "heart".into()];
/// })
/// # ;
/// ```
#[derive(Debug, Clone, Section)]
pub struct CommentsConfig {
    /// The deepest level a reply may sit at: `0` for top-level comments, `1` for their replies,
    /// and so on. A reply to a comment at this level joins its parent's replies instead, as on
    /// Reddit. `0` turns replies off.
    #[env("COMMENTS_MAX_DEPTH", default = 8)]
    pub max_depth: i64,
    /// The most characters a comment's text may have.
    #[env("COMMENTS_MAX_LENGTH", default = 10_000)]
    pub max_length: usize,
    /// The reactions people may leave on a comment, such as `like` or `heart`.
    #[env("COMMENTS_REACTIONS", separator = ",", default = vec!["like".to_owned()])]
    pub reactions: Vec<String>,
    /// Which new comments are approved at once, unless the application sets a rule of its own
    /// with [`CommentsServiceProvider::moderate_with`](crate::CommentsServiceProvider::moderate_with).
    #[env("COMMENTS_AUTO_APPROVE", default = AutoApprove::Users)]
    pub auto_approve: AutoApprove,
    /// For how many minutes after posting an author may edit a comment, by the default policy.
    /// `0` for no limit.
    #[env("COMMENTS_EDIT_WINDOW", default = 0)]
    pub edit_window: i64,
    /// How many comments an author may post a minute, by [`throttle`](crate::throttle): users
    /// by their key, guests by their IP address. `0` for no limit.
    #[env("COMMENTS_RATE_LIMIT", default = 10)]
    pub rate_limit: u32,
    /// Whether to keep the text before each edit, for [`CommentModel::revisions`](crate::CommentModel::revisions).
    #[env("COMMENTS_REVISIONS", default = true)]
    pub revisions: bool,
    /// Whether and how the events broadcast, on the channel `comments.{type}.{id}` of the model
    /// the comment belongs to.
    #[env("COMMENTS_BROADCAST", default = BroadcastChannel::Off)]
    pub broadcast: BroadcastChannel,
}

/// How the events broadcast.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BroadcastChannel {
    /// They don't.
    Off,
    /// On a public channel, which anyone may subscribe to.
    Public,
    /// On a private channel, whose subscriptions the application authorizes.
    Private,
}

impl FromStr for BroadcastChannel {
    type Err = UnknownBroadcastChannel;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.to_ascii_lowercase().as_str() {
            "off" | "" => Ok(Self::Off),
            "public" => Ok(Self::Public),
            "private" => Ok(Self::Private),
            _ => Err(UnknownBroadcastChannel(value.to_owned())),
        }
    }
}

/// A `COMMENTS_BROADCAST` value other than `off`, `public`, or `private`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownBroadcastChannel(String);

impl fmt::Display for UnknownBroadcastChannel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`{}` isn't one of `off`, `public`, `private`", self.0)
    }
}

impl std::error::Error for UnknownBroadcastChannel {}

/// Which new comments are approved at once. The rest wait for a moderator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoApprove {
    /// Every comment.
    Everyone,
    /// Comments by users; guests' comments wait.
    Users,
    /// No comment.
    Nobody,
}

impl FromStr for AutoApprove {
    type Err = UnknownAutoApprove;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.to_ascii_lowercase().as_str() {
            "everyone" => Ok(Self::Everyone),
            "users" => Ok(Self::Users),
            "nobody" => Ok(Self::Nobody),
            _ => Err(UnknownAutoApprove(value.to_owned())),
        }
    }
}

/// A `COMMENTS_AUTO_APPROVE` value other than `everyone`, `users`, or `nobody`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownAutoApprove(String);

impl fmt::Display for UnknownAutoApprove {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`{}` isn't one of `everyone`, `users`, `nobody`", self.0)
    }
}

impl std::error::Error for UnknownAutoApprove {}