Skip to main content

laravel_comments/
lib.rs

1//! Comments for [Laravel Rust](https://crates.io/crates/laravel-rust) models: threaded replies
2//! on [`laravel-nestedset`](https://crates.io/crates/laravel-nestedset), moderation, reactions,
3//! and events, read without N+1 queries.
4//!
5//! Register the provider in `src/app.rs`, run `laravel migrate`, and declare the comment model
6//! with [`comment_model!`]:
7//!
8//! ```no_run
9//! use laravel::Application;
10//!
11//! # let _ =
12//! Application::configure().with_providers(|providers| {
13//!     providers.add(laravel_comments::CommentsServiceProvider::new());
14//! })
15//! # ;
16//! ```
17//!
18//! See the README for a walkthrough.
19
20pub mod abilities;
21mod author;
22mod config;
23mod error;
24pub mod events;
25#[cfg(feature = "markdown")]
26pub mod markdown;
27mod mentions;
28mod model;
29mod moderation;
30mod ops;
31mod reactions;
32mod revisions;
33mod schema;
34mod status;
35mod thread;
36mod throttle;
37
38use std::future::Future;
39
40use laravel::config::{Config, Env};
41use laravel::container::Registrar;
42use laravel::foundation::ServiceProvider;
43
44pub use crate::author::{Author, Commenter};
45pub use crate::config::{AutoApprove, BroadcastChannel, CommentsConfig, UnknownAutoApprove, UnknownBroadcastChannel};
46pub use crate::error::CommentError;
47pub use crate::mentions::{CommentMention, mentions};
48pub use crate::model::{CommentColumns, CommentModel, CommentRow};
49pub use crate::moderation::NewComment;
50pub use crate::reactions::{CommentReaction, reaction_counts, reactions_of};
51pub use crate::revisions::CommentRevision;
52pub use crate::schema::CommentsBlueprint;
53pub use crate::status::{Status, Visibility};
54pub use crate::thread::{Location, Sort, ThreadNode, ThreadPage, Threads};
55pub use crate::throttle::throttle;
56
57use crate::mentions::MentionRule;
58use crate::moderation::ModerationRule;
59
60#[doc(hidden)]
61pub mod __private {
62    pub use {laravel, laravel_nestedset};
63}
64
65/// Adds the package's settings, its migrations, and the application's moderation and mention
66/// rules.
67#[derive(Clone, Default)]
68pub struct CommentsServiceProvider {
69    rule: Option<ModerationRule>,
70    mentions: MentionRule,
71}
72
73impl CommentsServiceProvider {
74    /// A provider that gives new comments the status `COMMENTS_AUTO_APPROVE` says.
75    #[must_use]
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    /// Gives each new comment the status `rule` returns, instead of `COMMENTS_AUTO_APPROVE`: a
81    /// place for trusted authors, banned words, or a spam check.
82    ///
83    /// ```no_run
84    /// use laravel_comments::{CommentsServiceProvider, NewComment, Status};
85    ///
86    /// let provider = CommentsServiceProvider::new().moderate_with(async |comment: NewComment| {
87    ///     if comment.body.contains("casino") {
88    ///         return Ok(Status::Spam);
89    ///     }
90    ///     Ok(if comment.author_id.is_some() { Status::Approved } else { Status::Pending })
91    /// });
92    /// ```
93    #[must_use]
94    pub fn moderate_with<F, Fut>(mut self, rule: F) -> Self
95    where
96        F: Fn(NewComment) -> Fut + Send + Sync + 'static,
97        Fut: Future<Output = laravel::Result<Status>> + Send + 'static,
98    {
99        self.rule = Some(ModerationRule::new(rule));
100        self
101    }
102
103    /// Turns `@name` mentions on: `rule` gets the names a comment mentions, lowercased, and
104    /// returns the keys of the users they name. Each mentioned user gets one
105    /// [`UserMentioned`](crate::events::UserMentioned) once the comment is visible.
106    ///
107    /// ```no_run
108    /// # use laravel::model::model;
109    /// # #[model] pub struct User { pub id: i64, pub username: String }
110    /// use laravel_comments::CommentsServiceProvider;
111    ///
112    /// let provider = CommentsServiceProvider::new().mentions_with(async |names: Vec<String>| {
113    ///     User::query().filter(User::username.is_in(names)).pluck(User::id).await
114    /// });
115    /// ```
116    #[must_use]
117    pub fn mentions_with<F, Fut>(mut self, rule: F) -> Self
118    where
119        F: Fn(Vec<String>) -> Fut + Send + Sync + 'static,
120        Fut: Future<Output = laravel::Result<Vec<i64>>> + Send + 'static,
121    {
122        self.mentions = MentionRule::new(rule);
123        self
124    }
125}
126
127laravel::db::migrations!(fn migrations = "database/migrations");
128
129impl ServiceProvider for CommentsServiceProvider {
130    fn config(&self, config: &mut Config, env: &Env) {
131        config.discover(env!("CARGO_CRATE_NAME"), env);
132    }
133
134    fn register(&self, app: &mut Registrar) {
135        app.migrations().add(migrations());
136        app.instance(self.rule.clone().unwrap_or(ModerationRule(None)));
137        app.instance(self.mentions.clone());
138    }
139}