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;
#[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>>;
#[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)))))
}
}
#[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, '_' | '.' | '-' | '@' | '/')
}
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
}
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)
}
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(())
}
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(());
}
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(())
}