laravel-comments 0.2.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! `@name` mentions: parsed from the text, resolved to users by the application's rule, kept in
//! `comment_mentions`, and announced once with [`UserMentioned`].

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use laravel::db::{self, col, values};
use laravel::model::model;
use laravel::time::Timestamp;

use crate::events::UserMentioned;
use crate::model::CommentModel;

/// A user mentioned in a comment, from the `comment_mentions` table.
#[model(table = "comment_mentions")]
pub struct CommentMention {
    pub id: i64,
    pub comment_id: i64,
    pub user_id: i64,
    pub notified_at: Option<Timestamp>,
}

type ResolveFuture = Pin<Box<dyn Future<Output = laravel::Result<Vec<i64>>> + Send>>;

/// The application's rule that finds the users with some names, registered with
/// [`CommentsServiceProvider::mentions_with`](crate::CommentsServiceProvider::mentions_with).
#[derive(Clone, Default)]
pub(crate) struct MentionRule(pub(crate) Option<Arc<dyn Fn(Vec<String>) -> ResolveFuture + Send + Sync>>);

impl MentionRule {
    pub(crate) fn new<F, Fut>(rule: F) -> Self
    where
        F: Fn(Vec<String>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = laravel::Result<Vec<i64>>> + Send + 'static,
    {
        Self(Some(Arc::new(move |names| Box::pin(rule(names)))))
    }
}

/// The names mentioned in `body`, lowercased, each once, in order: `@` followed by letters,
/// digits, `_`, `.`, or `-`, up to 64 of them. An `@` inside a word, as in an email address,
/// and anything in `` `code` `` or a fenced code block don't count, and a trailing `.` or `-`
/// ends the sentence rather than the name.
///
/// ```
/// assert_eq!(
///     laravel_comments::mentions("Thanks @Ann and @bob.smith. Mail me at me@example.com, `@not_me`"),
///     ["ann", "bob.smith"]
/// );
/// ```
#[must_use]
pub fn mentions(body: &str) -> Vec<String> {
    let text = without_code(body);
    let chars: Vec<char> = text.chars().collect();
    let mut names: Vec<String> = Vec::new();
    let mut index = 0;
    while index < chars.len() {
        if chars[index] != '@' || index > 0 && continues_word(chars[index - 1]) {
            index += 1;
            continue;
        }
        let start = index + 1;
        let mut end = start;
        while end < chars.len() && is_name_char(chars[end]) {
            end += 1;
        }
        let name: String = chars[start..end].iter().collect();
        let name = name.trim_end_matches(['.', '-']).to_lowercase();
        let starts_well = name
            .chars()
            .next()
            .is_some_and(|first| first.is_alphanumeric() || first == '_');
        if starts_well && name.chars().count() <= 64 && !names.contains(&name) {
            names.push(name);
        }
        index = end.max(start);
    }
    names
}

fn is_name_char(c: char) -> bool {
    c.is_alphanumeric() || matches!(c, '_' | '.' | '-')
}

fn continues_word(c: char) -> bool {
    c.is_alphanumeric() || matches!(c, '_' | '.' | '-' | '@' | '/')
}

/// `body` with code spans and fenced code blocks blanked out.
fn without_code(body: &str) -> String {
    let mut text = String::with_capacity(body.len());
    let mut rest = body;
    while let Some(start) = rest.find('`') {
        text.push_str(&rest[..start]);
        let ticks = rest[start..].chars().take_while(|c| *c == '`').count();
        let fence = &rest[start..start + ticks];
        let after = &rest[start + ticks..];
        if let Some(close) = after.find(fence) {
            text.push(' ');
            rest = &after[close + ticks..];
        } else {
            text.push_str(fence);
            rest = after;
        }
    }
    text.push_str(rest);
    text
}

/// The keys of the users `body` mentions, except `author_id`, by the application's rule. Empty
/// without a rule.
pub(crate) async fn resolve(body: &str, author_id: Option<i64>) -> laravel::Result<Vec<i64>> {
    let rule = laravel::resolve::<MentionRule>().await?;
    let Some(rule) = &rule.0 else {
        return Ok(Vec::new());
    };
    let names = mentions(body);
    if names.is_empty() {
        return Ok(Vec::new());
    }
    let mut users = rule(names).await?;
    users.sort_unstable();
    users.dedup();
    users.retain(|user| Some(*user) != author_id);
    Ok(users)
}

/// Makes the comment's mentions exactly `users`: adds the new ones, drops the rest.
pub(crate) async fn record(comment_id: i64, users: &[i64]) -> laravel::Result<()> {
    CommentMention::query()
        .filter(CommentMention::comment_id.eq(comment_id) & CommentMention::user_id.is_not_in(users.to_vec()))
        .delete()
        .await?;
    if users.is_empty() {
        return Ok(());
    }
    let rows: Vec<_> = users
        .iter()
        .map(|user| values! { comment_id: comment_id, user_id: *user })
        .collect();
    db::table("comment_mentions").insert_or_ignore(rows).await?;
    Ok(())
}

/// Dispatches [`UserMentioned`] for each mention of `comment` not announced yet, when the
/// comment is visible.
pub(crate) async fn announce<C: CommentModel>(comment: &C) -> laravel::Result<()> {
    if comment.visibility() != crate::Visibility::Visible {
        return Ok(());
    }
    let row = comment.row();
    let fresh = CommentMention::query()
        .filter(CommentMention::comment_id.eq(row.id) & CommentMention::notified_at.is_null())
        .pluck(CommentMention::user_id)
        .await?;
    if fresh.is_empty() {
        return Ok(());
    }
    // Only the mentions this call marks are announced, so two calls never announce one twice.
    let mut announced = Vec::new();
    for user_id in fresh {
        let marked = db::table("comment_mentions")
            .filter(col("comment_id").eq(row.id) & col("user_id").eq(user_id) & col("notified_at").is_null())
            .update(values! { notified_at: laravel::now().timestamp() })
            .await?;
        if marked > 0 {
            announced.push(user_id);
        }
    }
    for user_id in announced {
        UserMentioned {
            comment_id: row.id,
            commentable_type: row.commentable_type.name().to_owned(),
            commentable_id: row.commentable_id,
            user_id,
            author_id: row.author_id,
        }
        .dispatch()
        .await?;
    }
    Ok(())
}