feat: init
This commit is contained in:
@@ -0,0 +1,715 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{ArticleAction, ArticleEvent};
|
||||
use crate::models::channels::{Article, ArticleComment, ArticleReaction};
|
||||
use crate::models::common::{ArticleStatus, Visibility};
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateArticleParams {
|
||||
pub title: String,
|
||||
pub summary: Option<String>,
|
||||
pub body: String,
|
||||
pub cover_image_url: Option<String>,
|
||||
pub tags: Option<Vec<String>>,
|
||||
pub visibility: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateArticleParams {
|
||||
pub title: Option<String>,
|
||||
pub summary: Option<String>,
|
||||
pub body: Option<String>,
|
||||
pub cover_image_url: Option<String>,
|
||||
pub tags: Option<Vec<String>>,
|
||||
pub visibility: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct ArticleListFilters {
|
||||
pub status: Option<String>,
|
||||
pub tag: Option<String>,
|
||||
pub author_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateArticleCommentParams {
|
||||
pub body: String,
|
||||
pub parent_comment_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
async fn article_realtime(&self, channel_id: Uuid, article_id: Uuid, action: ArticleAction) {
|
||||
let request_id = Uuid::nil();
|
||||
let event = ArticleEvent {
|
||||
channel_id,
|
||||
article_id,
|
||||
action,
|
||||
};
|
||||
self.publish(&format!("im.article.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Article {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn article_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
filters: ArticleListFilters,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<Article>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
let status = filters
|
||||
.status
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<ArticleStatus>().ok())
|
||||
.filter(|s| *s != ArticleStatus::Unknown);
|
||||
|
||||
sqlx::query_as::<_, Article>(
|
||||
"SELECT id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at \
|
||||
FROM article WHERE channel_id = $1 AND deleted_at IS NULL \
|
||||
AND ($2::text IS NULL OR status::text = $2) \
|
||||
AND ($3::uuid IS NULL OR author_id = $3) \
|
||||
AND ($4::text IS NULL OR $4 = ANY(tags)) \
|
||||
ORDER BY created_at DESC LIMIT $5 OFFSET $6",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(status.map(|s| s.to_string()))
|
||||
.bind(filters.author_id)
|
||||
.bind(filters.tag.as_deref())
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn article_get(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
) -> Result<Article, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let article = self.resolve_article(article_id, channel_id).await?;
|
||||
|
||||
// Increment view count (best-effort, not in a txn)
|
||||
let _ = sqlx::query("UPDATE article SET views_count = views_count + 1 WHERE id = $1")
|
||||
.bind(article_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await;
|
||||
|
||||
Ok(article)
|
||||
}
|
||||
|
||||
pub async fn article_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: CreateArticleParams,
|
||||
) -> Result<Article, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
|
||||
let title = required_text(params.title, "title")?;
|
||||
if title.len() > MAX_ARTICLE_TITLE {
|
||||
return Err(AppError::BadRequest("article title too long".into()));
|
||||
}
|
||||
let body = required_text(params.body, "body")?;
|
||||
|
||||
let visibility = parse_enum(
|
||||
params.visibility,
|
||||
Visibility::Public,
|
||||
Visibility::Unknown,
|
||||
"visibility",
|
||||
)?;
|
||||
|
||||
let slug = self.generate_article_slug(channel_id, &title).await?;
|
||||
let now = chrono::Utc::now();
|
||||
let tags = params.tags.unwrap_or_default();
|
||||
|
||||
let article = sqlx::query_as::<_, Article>(
|
||||
"INSERT INTO article \
|
||||
(id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, cross_posted, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'draft', $9, $10, false, $11, $11) \
|
||||
RETURNING id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(&title)
|
||||
.bind(&slug)
|
||||
.bind(params.summary.as_deref())
|
||||
.bind(&body)
|
||||
.bind(params.cover_image_url.as_deref())
|
||||
.bind(visibility)
|
||||
.bind(&tags)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.article_realtime(channel_id, article.id, ArticleAction::Created)
|
||||
.await;
|
||||
Ok(article)
|
||||
}
|
||||
|
||||
pub async fn article_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
params: UpdateArticleParams,
|
||||
) -> Result<Article, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
let article = self.resolve_article(article_id, channel_id).await?;
|
||||
|
||||
if article.author_id != user_uid {
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let new_title = match params.title {
|
||||
Some(t) => {
|
||||
let t = required_text(t, "title")?;
|
||||
if t.len() > MAX_ARTICLE_TITLE {
|
||||
return Err(AppError::BadRequest("article title too long".into()));
|
||||
}
|
||||
t
|
||||
}
|
||||
None => article.title,
|
||||
};
|
||||
let new_body = params.body.unwrap_or(article.body);
|
||||
let new_summary = params.summary.or(article.summary);
|
||||
let new_cover = params.cover_image_url.or(article.cover_image_url);
|
||||
let new_tags = params.tags.unwrap_or(article.tags);
|
||||
let visibility = parse_enum(
|
||||
params.visibility,
|
||||
article.visibility,
|
||||
Visibility::Unknown,
|
||||
"visibility",
|
||||
)?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let updated = sqlx::query_as::<_, Article>(
|
||||
"UPDATE article SET title = $1, summary = $2, body = $3, cover_image_url = $4, \
|
||||
tags = $5, visibility = $6, updated_at = $7 \
|
||||
WHERE id = $8 AND deleted_at IS NULL \
|
||||
RETURNING id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(&new_title)
|
||||
.bind(&new_summary)
|
||||
.bind(&new_body)
|
||||
.bind(&new_cover)
|
||||
.bind(&new_tags)
|
||||
.bind(visibility)
|
||||
.bind(now)
|
||||
.bind(article_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Updated)
|
||||
.await;
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
pub async fn article_publish(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
) -> Result<Article, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
let article = self.resolve_article(article_id, channel_id).await?;
|
||||
|
||||
if article.author_id != user_uid {
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
if article.status != ArticleStatus::Draft && article.status != ArticleStatus::Scheduled {
|
||||
return Err(AppError::BadRequest(
|
||||
"only draft or scheduled articles can be published".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let published = sqlx::query_as::<_, Article>(
|
||||
"UPDATE article SET status = 'published', published_at = $1, published_by = $2, \
|
||||
updated_at = $1 \
|
||||
WHERE id = $3 AND deleted_at IS NULL \
|
||||
RETURNING id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(user_uid)
|
||||
.bind(article_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
// Trigger cross-posts to followers
|
||||
if let Err(e) = self
|
||||
.cross_post_article(article_id, channel_id, user_uid)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(article_id = %article_id, error = %e, "cross-post failed");
|
||||
}
|
||||
|
||||
tracing::info!(article_id = %article_id, "Article published");
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Published)
|
||||
.await;
|
||||
Ok(published)
|
||||
}
|
||||
|
||||
pub async fn article_unpublish(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
) -> Result<Article, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
let article = self.resolve_article(article_id, channel_id).await?;
|
||||
|
||||
if article.author_id != user_uid {
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let unpublished = sqlx::query_as::<_, Article>(
|
||||
"UPDATE article SET status = 'unpublished', unpublished_at = $1, updated_at = $1 \
|
||||
WHERE id = $2 AND status = 'published' AND deleted_at IS NULL \
|
||||
RETURNING id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(article_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Unpublished)
|
||||
.await;
|
||||
Ok(unpublished)
|
||||
}
|
||||
|
||||
pub async fn article_schedule(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
scheduled_at: chrono::DateTime<chrono::Utc>,
|
||||
) -> Result<Article, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
let article = self.resolve_article(article_id, channel_id).await?;
|
||||
|
||||
if article.author_id != user_uid {
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
if article.status != ArticleStatus::Draft {
|
||||
return Err(AppError::BadRequest(
|
||||
"only draft articles can be scheduled".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let scheduled = sqlx::query_as::<_, Article>(
|
||||
"UPDATE article SET status = 'scheduled', scheduled_at = $1, updated_at = $2 \
|
||||
WHERE id = $3 AND deleted_at IS NULL \
|
||||
RETURNING id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(scheduled_at)
|
||||
.bind(now)
|
||||
.bind(article_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Updated)
|
||||
.await;
|
||||
Ok(scheduled)
|
||||
}
|
||||
|
||||
pub async fn article_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
let article = self.resolve_article(article_id, channel_id).await?;
|
||||
|
||||
if article.author_id != user_uid {
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let result = sqlx::query(
|
||||
"UPDATE article SET deleted_at = $1, updated_at = $1 WHERE id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(article_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "article not found")?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Deleted)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn article_comment_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<ArticleComment>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, ArticleComment>(
|
||||
"SELECT id, article_id, channel_id, author_id, parent_comment_id, body, \
|
||||
edited_at, deleted_at, created_at, updated_at \
|
||||
FROM article_comment WHERE article_id = $1 AND deleted_at IS NULL \
|
||||
ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(article_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn article_comment_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
params: CreateArticleCommentParams,
|
||||
) -> Result<ArticleComment, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let body = required_text(params.body, "body")?;
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let comment = sqlx::query_as::<_, ArticleComment>(
|
||||
"INSERT INTO article_comment \
|
||||
(id, article_id, channel_id, author_id, parent_comment_id, body, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $7) \
|
||||
RETURNING id, article_id, channel_id, author_id, parent_comment_id, body, \
|
||||
edited_at, deleted_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(article_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(params.parent_comment_id)
|
||||
.bind(&body)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query("UPDATE article SET comments_count = comments_count + 1 WHERE id = $1")
|
||||
.bind(article_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Updated)
|
||||
.await;
|
||||
Ok(comment)
|
||||
}
|
||||
|
||||
pub async fn article_comment_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
comment_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
|
||||
let comment = sqlx::query_as::<_, ArticleComment>(
|
||||
"SELECT id, article_id, channel_id, author_id, parent_comment_id, body, \
|
||||
edited_at, deleted_at, created_at, updated_at \
|
||||
FROM article_comment WHERE id = $1 AND article_id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(comment_id)
|
||||
.bind(article_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("comment not found".into()))?;
|
||||
|
||||
if comment.author_id != user_uid {
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query("UPDATE article_comment SET deleted_at = $1, updated_at = $1 WHERE id = $2")
|
||||
.bind(now)
|
||||
.bind(comment_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE article SET comments_count = GREATEST(comments_count - 1, 0) WHERE id = $1",
|
||||
)
|
||||
.bind(article_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Updated)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn article_reaction_add(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
content: &str,
|
||||
) -> Result<ArticleReaction, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let content = required_text(content.to_string(), "content")?;
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let reaction = sqlx::query_as::<_, ArticleReaction>(
|
||||
"INSERT INTO article_reaction (id, article_id, channel_id, user_id, content, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) \
|
||||
ON CONFLICT (article_id, user_id, content) DO NOTHING \
|
||||
RETURNING id, article_id, channel_id, user_id, content, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(article_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(&content)
|
||||
.bind(now)
|
||||
.fetch_optional(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if reaction.is_some() {
|
||||
sqlx::query("UPDATE article SET reactions_count = reactions_count + 1 WHERE id = $1")
|
||||
.bind(article_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
let reaction = reaction.ok_or(AppError::Conflict("reaction already exists".into()))?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Updated)
|
||||
.await;
|
||||
Ok(reaction)
|
||||
}
|
||||
|
||||
pub async fn article_reaction_remove(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
content: &str,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let _now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let result = sqlx::query(
|
||||
"DELETE FROM article_reaction WHERE article_id = $1 AND user_id = $2 AND content = $3",
|
||||
)
|
||||
.bind(article_id)
|
||||
.bind(user_uid)
|
||||
.bind(content)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "reaction not found")?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE article SET reactions_count = GREATEST(reactions_count - 1, 0) WHERE id = $1",
|
||||
)
|
||||
.bind(article_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
self.article_realtime(channel_id, article_id, ArticleAction::Updated)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_article(
|
||||
&self,
|
||||
article_id: Uuid,
|
||||
channel_id: Uuid,
|
||||
) -> Result<Article, AppError> {
|
||||
sqlx::query_as::<_, Article>(
|
||||
"SELECT id, channel_id, author_id, title, slug, summary, body, cover_image_url, \
|
||||
status, visibility, tags, published_at, published_by, scheduled_at, unpublished_at, \
|
||||
views_count, comments_count, reactions_count, cross_posted, cross_posted_from, \
|
||||
metadata, created_at, updated_at, deleted_at \
|
||||
FROM article WHERE id = $1 AND channel_id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(article_id)
|
||||
.bind(channel_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("article not found".into()))
|
||||
}
|
||||
|
||||
async fn generate_article_slug(
|
||||
&self,
|
||||
channel_id: Uuid,
|
||||
title: &str,
|
||||
) -> Result<String, AppError> {
|
||||
let base = slugify(title);
|
||||
let mut slug = base.clone();
|
||||
let mut counter = 1u32;
|
||||
|
||||
loop {
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM article WHERE channel_id = $1 AND slug = $2)",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(&slug)
|
||||
.fetch_one(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if !exists {
|
||||
return Ok(slug);
|
||||
}
|
||||
slug = format!("{base}-{counter}");
|
||||
counter += 1;
|
||||
if counter > 100 {
|
||||
return Err(AppError::InternalServerError(
|
||||
"failed to generate unique slug".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{CategoryAction, CategoryEvent};
|
||||
use crate::models::channels::ChannelCategory;
|
||||
use crate::models::common::Role;
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateCategoryParams {
|
||||
pub name: String,
|
||||
pub position: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateCategoryParams {
|
||||
pub name: Option<String>,
|
||||
pub position: Option<i32>,
|
||||
pub collapsed: Option<bool>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
async fn category_realtime(
|
||||
&self,
|
||||
workspace_name: &str,
|
||||
category_id: Uuid,
|
||||
action: CategoryAction,
|
||||
) {
|
||||
let request_id = Uuid::nil();
|
||||
let event = CategoryEvent {
|
||||
workspace_name: workspace_name.to_string(),
|
||||
category_id,
|
||||
action,
|
||||
};
|
||||
self.publish(&format!("im.category.{workspace_name}"), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Category {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn category_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
) -> Result<Vec<ChannelCategory>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
|
||||
sqlx::query_as::<_, ChannelCategory>(
|
||||
"SELECT id, workspace_id, name, position, collapsed, created_by, created_at, updated_at \
|
||||
FROM channel_category WHERE workspace_id = $1 ORDER BY position ASC, name ASC",
|
||||
)
|
||||
.bind(ws.id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn category_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
params: CreateCategoryParams,
|
||||
) -> Result<ChannelCategory, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Member)
|
||||
.await?;
|
||||
|
||||
let name = required_text(params.name, "name")?;
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let category = sqlx::query_as::<_, ChannelCategory>(
|
||||
"INSERT INTO channel_category (id, workspace_id, name, position, collapsed, created_by, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, false, $5, $6, $6) \
|
||||
RETURNING id, workspace_id, name, position, collapsed, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(ws.id)
|
||||
.bind(&name)
|
||||
.bind(params.position.unwrap_or(0))
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.category_realtime(wk_name, category.id, CategoryAction::Created)
|
||||
.await;
|
||||
Ok(category)
|
||||
}
|
||||
|
||||
pub async fn category_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
category_id: Uuid,
|
||||
params: UpdateCategoryParams,
|
||||
) -> Result<ChannelCategory, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Member)
|
||||
.await?;
|
||||
|
||||
let cat = self.resolve_category(category_id, ws.id).await?;
|
||||
let new_name = params.name.unwrap_or(cat.name);
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let category = sqlx::query_as::<_, ChannelCategory>(
|
||||
"UPDATE channel_category SET name = $1, position = COALESCE($2, position), \
|
||||
collapsed = COALESCE($3, collapsed), updated_at = $4 \
|
||||
WHERE id = $5 \
|
||||
RETURNING id, workspace_id, name, position, collapsed, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(&new_name)
|
||||
.bind(params.position)
|
||||
.bind(params.collapsed)
|
||||
.bind(now)
|
||||
.bind(category_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.category_realtime(wk_name, category_id, CategoryAction::Updated)
|
||||
.await;
|
||||
Ok(category)
|
||||
}
|
||||
|
||||
pub async fn category_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
category_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
|
||||
.await?;
|
||||
|
||||
let result =
|
||||
sqlx::query("DELETE FROM channel_category WHERE id = $1 AND workspace_id = $2")
|
||||
.bind(category_id)
|
||||
.bind(ws.id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "category not found")?;
|
||||
self.category_realtime(wk_name, category_id, CategoryAction::Deleted)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_category(
|
||||
&self,
|
||||
category_id: Uuid,
|
||||
workspace_id: Uuid,
|
||||
) -> Result<ChannelCategory, AppError> {
|
||||
sqlx::query_as::<_, ChannelCategory>(
|
||||
"SELECT id, workspace_id, name, position, collapsed, created_by, created_at, updated_at \
|
||||
FROM channel_category WHERE id = $1 AND workspace_id = $2",
|
||||
)
|
||||
.bind(category_id)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("category not found".into()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::channels::Channel;
|
||||
use crate::models::common::{ChannelKind, ChannelType, Role, Visibility};
|
||||
use crate::models::workspaces::Workspace;
|
||||
use crate::service::ImService;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
use crate::immediate::{ChannelAction, ChannelEvent};
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateChannelParams {
|
||||
pub name: String,
|
||||
pub topic: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub channel_type: Option<String>,
|
||||
pub channel_kind: Option<String>,
|
||||
pub visibility: Option<String>,
|
||||
pub category_id: Option<Uuid>,
|
||||
pub parent_channel_id: Option<Uuid>,
|
||||
pub nsfw: Option<bool>,
|
||||
pub rate_limit_per_user: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateChannelParams {
|
||||
pub name: Option<String>,
|
||||
pub topic: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub visibility: Option<String>,
|
||||
pub category_id: Option<Uuid>,
|
||||
pub position: Option<i32>,
|
||||
pub nsfw: Option<bool>,
|
||||
pub rate_limit_per_user: Option<i32>,
|
||||
pub archived: Option<bool>,
|
||||
pub read_only: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct ChannelListFilters {
|
||||
pub channel_type: Option<String>,
|
||||
pub channel_kind: Option<String>,
|
||||
pub category_id: Option<Uuid>,
|
||||
pub archived: Option<bool>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn channel_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
filters: ChannelListFilters,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<Channel>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
let kind = filters
|
||||
.channel_kind
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<ChannelKind>().ok())
|
||||
.filter(|k| *k != ChannelKind::Unknown);
|
||||
let ch_type = filters
|
||||
.channel_type
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<ChannelType>().ok())
|
||||
.filter(|t| *t != ChannelType::Unknown);
|
||||
|
||||
sqlx::query_as::<_, Channel>(
|
||||
"SELECT id, workspace_id, repo_id, category_id, created_by, name, topic, description, \
|
||||
channel_type, channel_kind, visibility, position, nsfw, archived, read_only, \
|
||||
bitrate, user_limit, rtc_region, \
|
||||
default_auto_archive_duration, default_reaction_emoji, default_sort_order, \
|
||||
default_forum_layout, require_tag, available_tags, default_thread_rate_limit, \
|
||||
rate_limit_per_user, parent_channel_id, \
|
||||
last_message_id, last_message_at, archived_at, created_at, updated_at, deleted_at \
|
||||
FROM channel \
|
||||
WHERE workspace_id = $1 AND deleted_at IS NULL \
|
||||
AND ($2::text IS NULL OR channel_kind::text = $2) \
|
||||
AND ($3::text IS NULL OR channel_type::text = $3) \
|
||||
AND ($4::uuid IS NULL OR category_id = $4) \
|
||||
AND ($5::bool IS NULL OR archived = $5) \
|
||||
ORDER BY position ASC NULLS LAST, name ASC \
|
||||
LIMIT $6 OFFSET $7",
|
||||
)
|
||||
.bind(ws.id)
|
||||
.bind(kind.map(|k| k.to_string()))
|
||||
.bind(ch_type.map(|t| t.to_string()))
|
||||
.bind(filters.category_id)
|
||||
.bind(filters.archived)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn channel_get(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
) -> Result<Channel, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
Ok(channel)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self, ctx, params), fields(name = %params.name))]
|
||||
pub async fn channel_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
params: CreateChannelParams,
|
||||
request_id: Uuid,
|
||||
) -> Result<Channel, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let name = required_text(params.name, "name")?;
|
||||
if name.len() > MAX_CHANNEL_NAME {
|
||||
return Err(AppError::BadRequest("channel name too long".into()));
|
||||
}
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_role_at_least(user_uid, &ws, Role::Member)
|
||||
.await?;
|
||||
|
||||
if let Some(topic) = ¶ms.topic
|
||||
&& topic.len() > MAX_CHANNEL_TOPIC
|
||||
{
|
||||
return Err(AppError::BadRequest("channel topic too long".into()));
|
||||
}
|
||||
|
||||
let ch_kind = parse_enum(
|
||||
params.channel_kind,
|
||||
ChannelKind::Text,
|
||||
ChannelKind::Unknown,
|
||||
"channel_kind",
|
||||
)?;
|
||||
let ch_type = parse_enum(
|
||||
params.channel_type,
|
||||
ChannelType::Public,
|
||||
ChannelType::Unknown,
|
||||
"channel_type",
|
||||
)?;
|
||||
let visibility = parse_enum(
|
||||
params.visibility,
|
||||
Visibility::Public,
|
||||
Visibility::Unknown,
|
||||
"visibility",
|
||||
)?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let channel_id = Uuid::now_v7();
|
||||
|
||||
let channel = sqlx::query_as::<_, Channel>(
|
||||
"INSERT INTO channel \
|
||||
(id, workspace_id, repo_id, category_id, created_by, name, topic, description, \
|
||||
channel_type, channel_kind, visibility, position, nsfw, archived, read_only, \
|
||||
rate_limit_per_user, parent_channel_id, created_at, updated_at) \
|
||||
VALUES ($1, $2, NULL, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, false, false, \
|
||||
$13, $14, $15, $15) \
|
||||
RETURNING id, workspace_id, repo_id, category_id, created_by, name, topic, description, \
|
||||
channel_type, channel_kind, visibility, position, nsfw, archived, read_only, \
|
||||
bitrate, user_limit, rtc_region, \
|
||||
default_auto_archive_duration, default_reaction_emoji, default_sort_order, \
|
||||
default_forum_layout, require_tag, available_tags, default_thread_rate_limit, \
|
||||
rate_limit_per_user, parent_channel_id, \
|
||||
last_message_id, last_message_at, archived_at, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(ws.id)
|
||||
.bind(params.category_id)
|
||||
.bind(user_uid)
|
||||
.bind(&name)
|
||||
.bind(params.topic.as_deref())
|
||||
.bind(params.description.as_deref())
|
||||
.bind(ch_type)
|
||||
.bind(ch_kind)
|
||||
.bind(visibility)
|
||||
.bind(0_i32) // position
|
||||
.bind(params.nsfw.unwrap_or(false))
|
||||
.bind(params.rate_limit_per_user)
|
||||
.bind(params.parent_channel_id)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
// Auto-add creator as channel member with owner role
|
||||
sqlx::query(
|
||||
"INSERT INTO channel_member \
|
||||
(id, channel_id, user_id, role, status, muted, pinned, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, 'owner', 'active', false, false, $4, $4)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
tracing::info!(channel_id = %channel_id, name = %name, "Channel created");
|
||||
|
||||
let event = ChannelEvent {
|
||||
channel_id: channel.id,
|
||||
action: ChannelAction::Created,
|
||||
workspace_name: Some(ws.name.clone()),
|
||||
};
|
||||
self.publish(&format!("im.channel.{}", ws.name), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Channel {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(channel)
|
||||
}
|
||||
|
||||
pub async fn channel_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: UpdateChannelParams,
|
||||
request_id: Uuid,
|
||||
) -> Result<Channel, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
|
||||
if let Some(name) = ¶ms.name
|
||||
&& name.len() > MAX_CHANNEL_NAME
|
||||
{
|
||||
return Err(AppError::BadRequest("channel name too long".into()));
|
||||
}
|
||||
|
||||
let visibility = match params.visibility {
|
||||
Some(ref v) => parse_enum(
|
||||
Some(v.clone()),
|
||||
channel.visibility,
|
||||
Visibility::Unknown,
|
||||
"visibility",
|
||||
)?,
|
||||
None => channel.visibility,
|
||||
};
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let new_name = merge_optional_text(params.name, Some(channel.name.clone()))
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or(channel.name);
|
||||
let new_topic = merge_optional_text(params.topic, channel.topic.clone());
|
||||
let new_desc = merge_optional_text(params.description, channel.description.clone());
|
||||
|
||||
let updated = sqlx::query_as::<_, Channel>(
|
||||
"UPDATE channel SET \
|
||||
name = $1, topic = $2, description = $3, visibility = $4, \
|
||||
category_id = COALESCE($5, category_id), position = COALESCE($6, position), \
|
||||
nsfw = COALESCE($7, nsfw), archived = COALESCE($8, archived), \
|
||||
read_only = COALESCE($9, read_only), \
|
||||
rate_limit_per_user = COALESCE($10, rate_limit_per_user), \
|
||||
updated_at = $11 \
|
||||
WHERE id = $12 AND deleted_at IS NULL \
|
||||
RETURNING id, workspace_id, repo_id, category_id, created_by, name, topic, description, \
|
||||
channel_type, channel_kind, visibility, position, nsfw, archived, read_only, \
|
||||
bitrate, user_limit, rtc_region, \
|
||||
default_auto_archive_duration, default_reaction_emoji, default_sort_order, \
|
||||
default_forum_layout, require_tag, available_tags, default_thread_rate_limit, \
|
||||
rate_limit_per_user, parent_channel_id, \
|
||||
last_message_id, last_message_at, archived_at, created_at, updated_at, deleted_at",
|
||||
)
|
||||
.bind(&new_name)
|
||||
.bind(&new_topic)
|
||||
.bind(&new_desc)
|
||||
.bind(visibility)
|
||||
.bind(params.category_id)
|
||||
.bind(params.position)
|
||||
.bind(params.nsfw)
|
||||
.bind(params.archived)
|
||||
.bind(params.read_only)
|
||||
.bind(params.rate_limit_per_user)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let event = ChannelEvent {
|
||||
channel_id,
|
||||
action: ChannelAction::Updated,
|
||||
workspace_name: None,
|
||||
};
|
||||
self.publish(&format!("im.channel.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Channel {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
pub async fn channel_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
request_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let result = sqlx::query(
|
||||
"UPDATE channel SET deleted_at = $1, updated_at = $1 \
|
||||
WHERE id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "channel not found")?;
|
||||
|
||||
let event = ChannelEvent {
|
||||
channel_id,
|
||||
action: ChannelAction::Deleted,
|
||||
workspace_name: None,
|
||||
};
|
||||
self.publish(&format!("im.channel.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Channel {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_workspace(&self, wk_name: &str) -> Result<Workspace, AppError> {
|
||||
Workspace::find_by_name(self.ctx.db.reader(), wk_name)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("workspace not found".into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_channel(&self, channel_id: Uuid) -> Result<Channel, AppError> {
|
||||
sqlx::query_as::<_, Channel>(
|
||||
"SELECT id, workspace_id, repo_id, category_id, created_by, name, topic, description, \
|
||||
channel_type, channel_kind, visibility, position, nsfw, archived, read_only, \
|
||||
bitrate, user_limit, rtc_region, \
|
||||
default_auto_archive_duration, default_reaction_emoji, default_sort_order, \
|
||||
default_forum_layout, require_tag, available_tags, default_thread_rate_limit, \
|
||||
rate_limit_per_user, parent_channel_id, \
|
||||
last_message_id, last_message_at, archived_at, created_at, updated_at, deleted_at \
|
||||
FROM channel WHERE id = $1 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("channel not found".into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_workspace_readable(
|
||||
&self,
|
||||
user_uid: Uuid,
|
||||
ws: &Workspace,
|
||||
) -> Result<(), AppError> {
|
||||
if Workspace::is_readable(self.ctx.db.reader(), ws, user_uid)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(AppError::Unauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_workspace_role_at_least(
|
||||
&self,
|
||||
user_uid: Uuid,
|
||||
ws: &Workspace,
|
||||
min_role: Role,
|
||||
) -> Result<Role, AppError> {
|
||||
let role = Workspace::user_role(self.ctx.db.reader(), ws.id, user_uid, ws.owner_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.unwrap_or(Role::Unknown);
|
||||
if role_level(role) < role_level(min_role) {
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
Ok(role)
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_channel_readable(
|
||||
&self,
|
||||
user_uid: Uuid,
|
||||
channel: &Channel,
|
||||
) -> Result<(), AppError> {
|
||||
if channel.created_by == user_uid {
|
||||
return Ok(());
|
||||
}
|
||||
let is_member = self.is_channel_member(channel.id, user_uid).await?;
|
||||
if is_member {
|
||||
return Ok(());
|
||||
}
|
||||
if channel.visibility == Visibility::Public {
|
||||
let ws = Workspace::find_by_id(self.ctx.db.reader(), channel.workspace_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("workspace not found".into()))?;
|
||||
if Workspace::is_readable(self.ctx.db.reader(), &ws, user_uid)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(AppError::Unauthorized)
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_channel_member(
|
||||
&self,
|
||||
user_uid: Uuid,
|
||||
channel: &Channel,
|
||||
) -> Result<(), AppError> {
|
||||
if channel.created_by == user_uid {
|
||||
return Ok(());
|
||||
}
|
||||
let is_member = self.is_channel_member(channel.id, user_uid).await?;
|
||||
if is_member {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(AppError::Forbidden("not a channel member".into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_channel_editable(
|
||||
&self,
|
||||
user_uid: Uuid,
|
||||
channel: &Channel,
|
||||
) -> Result<(), AppError> {
|
||||
if channel.created_by == user_uid {
|
||||
return Ok(());
|
||||
}
|
||||
let role = self.channel_member_role(channel.id, user_uid).await?;
|
||||
if role_level(role) >= role_level(Role::Member) {
|
||||
return Ok(());
|
||||
}
|
||||
self.ensure_workspace_role_at_least(
|
||||
user_uid,
|
||||
&Workspace::find_by_id(self.ctx.db.reader(), channel.workspace_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("workspace not found".into()))?,
|
||||
Role::Admin,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_channel_admin(
|
||||
&self,
|
||||
user_uid: Uuid,
|
||||
channel: &Channel,
|
||||
) -> Result<(), AppError> {
|
||||
let role = self.channel_member_role(channel.id, user_uid).await?;
|
||||
if role_level(role) >= role_level(Role::Admin) {
|
||||
return Ok(());
|
||||
}
|
||||
self.ensure_workspace_role_at_least(
|
||||
user_uid,
|
||||
&Workspace::find_by_id(self.ctx.db.reader(), channel.workspace_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("workspace not found".into()))?,
|
||||
Role::Admin,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn is_channel_member(
|
||||
&self,
|
||||
channel_id: Uuid,
|
||||
user_uid: Uuid,
|
||||
) -> Result<bool, AppError> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM channel_member \
|
||||
WHERE channel_id = $1 AND user_id = $2 AND status = 'active')",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.fetch_one(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub(crate) async fn channel_member_role(
|
||||
&self,
|
||||
channel_id: Uuid,
|
||||
user_uid: Uuid,
|
||||
) -> Result<Role, AppError> {
|
||||
let role: Option<String> = sqlx::query_scalar(
|
||||
"SELECT role::text FROM channel_member \
|
||||
WHERE channel_id = $1 AND user_id = $2 AND status = 'active'",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
Ok(role
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<Role>().ok())
|
||||
.unwrap_or(Role::Unknown))
|
||||
}
|
||||
|
||||
pub(crate) async fn update_channel_stats(
|
||||
&self,
|
||||
channel_id: Uuid,
|
||||
now: chrono::DateTime<chrono::Utc>,
|
||||
txn: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), AppError> {
|
||||
sqlx::query(
|
||||
"UPDATE channel_stats SET \
|
||||
members_count = (SELECT COUNT(*) FROM channel_member WHERE channel_id = $1 AND status = 'active'), \
|
||||
messages_count = (SELECT COUNT(*) FROM message WHERE channel_id = $1 AND deleted_at IS NULL), \
|
||||
threads_count = (SELECT COUNT(*) FROM message_thread WHERE channel_id = $1), \
|
||||
reactions_count = (SELECT COUNT(*) FROM message_reaction WHERE channel_id = $1), \
|
||||
mentions_count = (SELECT COUNT(*) FROM message_mention WHERE channel_id = $1), \
|
||||
files_count = (SELECT COUNT(*) FROM message_attachment WHERE channel_id = $1), \
|
||||
last_activity_at = $2, updated_at = $2 \
|
||||
WHERE channel_id = $1",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(now)
|
||||
.execute(&mut **txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn trace_request(stage: &'static str, request_id: Uuid, subject: &str) {
|
||||
tracing::info!(
|
||||
target: "im.delivery",
|
||||
stage,
|
||||
request_id = %request_id,
|
||||
subject,
|
||||
"im delivery trace"
|
||||
);
|
||||
}
|
||||
|
||||
pub fn trace_message(
|
||||
stage: &'static str,
|
||||
request_id: Uuid,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
seq: Option<i64>,
|
||||
) {
|
||||
tracing::info!(
|
||||
target: "im.delivery",
|
||||
stage,
|
||||
request_id = %request_id,
|
||||
channel_id = %channel_id,
|
||||
message_id = %message_id,
|
||||
seq,
|
||||
"im message delivery trace"
|
||||
);
|
||||
}
|
||||
|
||||
pub fn trace_error(
|
||||
stage: &'static str,
|
||||
request_id: Uuid,
|
||||
subject: &str,
|
||||
error: &dyn std::fmt::Display,
|
||||
) {
|
||||
tracing::warn!(
|
||||
target: "im.delivery",
|
||||
stage,
|
||||
request_id = %request_id,
|
||||
subject,
|
||||
error = %error,
|
||||
"im delivery trace failed"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{DraftAction, DraftEvent};
|
||||
use crate::models::channels::MessageDraft;
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct SaveDraftParams {
|
||||
pub content: String,
|
||||
pub thread_id: Option<Uuid>,
|
||||
pub reply_to_message_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
async fn draft_realtime(
|
||||
&self,
|
||||
channel_id: Uuid,
|
||||
user_id: Uuid,
|
||||
thread_id: Option<Uuid>,
|
||||
action: DraftAction,
|
||||
) {
|
||||
let request_id = Uuid::nil();
|
||||
let event = DraftEvent {
|
||||
channel_id,
|
||||
user_id,
|
||||
thread_id,
|
||||
action,
|
||||
};
|
||||
self.publish(&format!("im.draft.{user_id}"), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Draft {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn draft_save(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: SaveDraftParams,
|
||||
) -> Result<MessageDraft, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
if params.content.len() > MAX_MESSAGE_BODY {
|
||||
return Err(AppError::BadRequest("draft content too long".into()));
|
||||
}
|
||||
|
||||
// NOTE: COALESCE(thread_id, nil_uuid) in ON CONFLICT requires a matching
|
||||
// UNIQUE index with the identical COALESCE expression.
|
||||
let now = chrono::Utc::now();
|
||||
let draft = sqlx::query_as::<_, MessageDraft>(
|
||||
"INSERT INTO message_draft \
|
||||
(id, user_id, channel_id, thread_id, reply_to_message_id, content, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $7) \
|
||||
ON CONFLICT (user_id, channel_id, COALESCE(thread_id, '00000000-0000-0000-0000-000000000000'::uuid)) \
|
||||
DO UPDATE SET content = $6, reply_to_message_id = $5, updated_at = $7 \
|
||||
RETURNING id, user_id, channel_id, thread_id, reply_to_message_id, content, \
|
||||
attachments, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_uid)
|
||||
.bind(channel_id)
|
||||
.bind(params.thread_id)
|
||||
.bind(params.reply_to_message_id)
|
||||
.bind(¶ms.content)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.draft_realtime(channel_id, user_uid, draft.thread_id, DraftAction::Saved)
|
||||
.await;
|
||||
Ok(draft)
|
||||
}
|
||||
|
||||
pub async fn draft_get(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
thread_id: Option<Uuid>,
|
||||
) -> Result<Option<MessageDraft>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, MessageDraft>(
|
||||
"SELECT id, user_id, channel_id, thread_id, reply_to_message_id, content, \
|
||||
attachments, created_at, updated_at \
|
||||
FROM message_draft \
|
||||
WHERE user_id = $1 AND channel_id = $2 \
|
||||
AND (thread_id = $3 OR (thread_id IS NULL AND $3 IS NULL))",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(channel_id)
|
||||
.bind(thread_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn draft_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
thread_id: Option<Uuid>,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
|
||||
let result = sqlx::query(
|
||||
"DELETE FROM message_draft \
|
||||
WHERE user_id = $1 AND channel_id = $2 \
|
||||
AND (thread_id = $3 OR (thread_id IS NULL AND $3 IS NULL))",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(channel_id)
|
||||
.bind(thread_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "draft not found")?;
|
||||
self.draft_realtime(channel_id, user_uid, thread_id, DraftAction::Deleted)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn draft_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<MessageDraft>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let _ = self.resolve_workspace(wk_name).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, MessageDraft>(
|
||||
"SELECT id, user_id, channel_id, thread_id, reply_to_message_id, content, \
|
||||
attachments, created_at, updated_at \
|
||||
FROM message_draft WHERE user_id = $1 \
|
||||
ORDER BY updated_at DESC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::immediate::{
|
||||
ArticleEvent, CategoryEvent, ChannelEvent, DraftEvent, FollowEvent, MemberEvent, MessageEvent,
|
||||
PollEvent, PresenceEvent, ReactionEvent, ThreadEvent, TypingEvent,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ImEvent {
|
||||
Typing {
|
||||
request_id: Uuid,
|
||||
data: TypingEvent,
|
||||
},
|
||||
Presence {
|
||||
request_id: Uuid,
|
||||
data: PresenceEvent,
|
||||
},
|
||||
Message {
|
||||
request_id: Uuid,
|
||||
data: MessageEvent,
|
||||
},
|
||||
Channel {
|
||||
request_id: Uuid,
|
||||
data: ChannelEvent,
|
||||
},
|
||||
Thread {
|
||||
request_id: Uuid,
|
||||
data: ThreadEvent,
|
||||
},
|
||||
Member {
|
||||
request_id: Uuid,
|
||||
data: MemberEvent,
|
||||
},
|
||||
Reaction {
|
||||
request_id: Uuid,
|
||||
data: ReactionEvent,
|
||||
},
|
||||
Poll {
|
||||
request_id: Uuid,
|
||||
data: PollEvent,
|
||||
},
|
||||
Article {
|
||||
request_id: Uuid,
|
||||
data: ArticleEvent,
|
||||
},
|
||||
Category {
|
||||
request_id: Uuid,
|
||||
data: CategoryEvent,
|
||||
},
|
||||
Draft {
|
||||
request_id: Uuid,
|
||||
data: DraftEvent,
|
||||
},
|
||||
Follow {
|
||||
request_id: Uuid,
|
||||
data: FollowEvent,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ImEventBus {
|
||||
tx: broadcast::Sender<ImEvent>,
|
||||
lagged: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
impl ImEventBus {
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
let (tx, _) = broadcast::channel(capacity);
|
||||
Self {
|
||||
tx,
|
||||
lagged: Arc::new(AtomicU64::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn publish(&self, event: ImEvent) -> bool {
|
||||
self.tx.send(event).is_ok()
|
||||
}
|
||||
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<ImEvent> {
|
||||
self.tx.subscribe()
|
||||
}
|
||||
|
||||
pub fn record_lagged(&self, count: u64) {
|
||||
self.lagged.fetch_add(count, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn lagged_total(&self) -> u64 {
|
||||
self.lagged.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ImEventBus {
|
||||
fn default() -> Self {
|
||||
Self::new(1024)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{FollowAction, FollowEvent};
|
||||
use crate::models::channels::{ArticleCrossPost, ChannelFollow};
|
||||
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct FollowChannelParams {
|
||||
pub target_workspace_id: Uuid,
|
||||
pub target_channel_id: Option<Uuid>,
|
||||
pub webhook_url: Option<String>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
async fn follow_realtime(&self, channel_id: Uuid, follow_id: Uuid, action: FollowAction) {
|
||||
let request_id = Uuid::nil();
|
||||
let event = FollowEvent {
|
||||
channel_id,
|
||||
follow_id,
|
||||
action,
|
||||
};
|
||||
self.publish(&format!("im.follow.{channel_id}"), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Follow {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn follow_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
) -> Result<Vec<ChannelFollow>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, ChannelFollow>(
|
||||
"SELECT id, source_channel_id, target_workspace_id, target_channel_id, \
|
||||
webhook_url, webhook_secret_ciphertext, enabled, followed_by, \
|
||||
unfollowed_at, last_delivery_at, last_delivery_status, created_at, updated_at \
|
||||
FROM channel_follow WHERE source_channel_id = $1 AND unfollowed_at IS NULL \
|
||||
ORDER BY created_at DESC",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn follow_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: FollowChannelParams,
|
||||
) -> Result<ChannelFollow, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let follow = sqlx::query_as::<_, ChannelFollow>(
|
||||
"INSERT INTO channel_follow \
|
||||
(id, source_channel_id, target_workspace_id, target_channel_id, \
|
||||
webhook_url, enabled, followed_by, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, true, $6, $7, $7) \
|
||||
ON CONFLICT (source_channel_id, target_workspace_id, target_channel_id) \
|
||||
DO UPDATE SET enabled = true, unfollowed_at = NULL, updated_at = $7 \
|
||||
RETURNING id, source_channel_id, target_workspace_id, target_channel_id, \
|
||||
webhook_url, webhook_secret_ciphertext, enabled, followed_by, \
|
||||
unfollowed_at, last_delivery_at, last_delivery_status, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(channel_id)
|
||||
.bind(params.target_workspace_id)
|
||||
.bind(params.target_channel_id)
|
||||
.bind(params.webhook_url.as_deref())
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.follow_realtime(channel_id, follow.id, FollowAction::Created)
|
||||
.await;
|
||||
Ok(follow)
|
||||
}
|
||||
|
||||
pub async fn follow_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
follow_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let result = sqlx::query(
|
||||
"UPDATE channel_follow SET unfollowed_at = $1, enabled = false, updated_at = $1 \
|
||||
WHERE id = $2 AND source_channel_id = $3 AND unfollowed_at IS NULL",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(follow_id)
|
||||
.bind(channel_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "follow not found")?;
|
||||
self.follow_realtime(channel_id, follow_id, FollowAction::Deleted)
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn cross_post_article(
|
||||
&self,
|
||||
article_id: Uuid,
|
||||
channel_id: Uuid,
|
||||
_actor_id: Uuid,
|
||||
) -> Result<u64, AppError> {
|
||||
let followers = sqlx::query_as::<_, ChannelFollow>(
|
||||
"SELECT id, source_channel_id, target_workspace_id, target_channel_id, \
|
||||
webhook_url, webhook_secret_ciphertext, enabled, followed_by, \
|
||||
unfollowed_at, last_delivery_at, last_delivery_status, created_at, updated_at \
|
||||
FROM channel_follow WHERE source_channel_id = $1 AND enabled AND unfollowed_at IS NULL",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut count = 0u64;
|
||||
|
||||
for follow in &followers {
|
||||
sqlx::query(
|
||||
"INSERT INTO article_cross_post \
|
||||
(id, article_id, follow_id, target_workspace_id, target_channel_id, \
|
||||
status, attempts, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, 'pending', 0, $6) \
|
||||
ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(article_id)
|
||||
.bind(follow.id)
|
||||
.bind(follow.target_workspace_id)
|
||||
.bind(follow.target_channel_id)
|
||||
.bind(now)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
count += 1;
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
sqlx::query("UPDATE article SET cross_posted = true WHERE id = $1")
|
||||
.bind(article_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
article_id = %article_id,
|
||||
followers = count,
|
||||
"Cross-post jobs created"
|
||||
);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub async fn cross_post_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
article_id: Uuid,
|
||||
) -> Result<Vec<ArticleCrossPost>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, ArticleCrossPost>(
|
||||
"SELECT id, article_id, follow_id, target_workspace_id, target_channel_id, \
|
||||
status, attempts, last_error, sent_at, delivered_at, failed_at, created_at \
|
||||
FROM article_cross_post WHERE article_id = $1 ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(article_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn cross_post_retry(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
cross_post_id: Uuid,
|
||||
) -> Result<ArticleCrossPost, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
let post = sqlx::query_as::<_, ArticleCrossPost>(
|
||||
"UPDATE article_cross_post SET status = 'pending', attempts = 0, \
|
||||
last_error = NULL, failed_at = NULL \
|
||||
WHERE id = $1 AND status = 'failed' \
|
||||
RETURNING id, article_id, follow_id, target_workspace_id, target_channel_id, \
|
||||
status, attempts, last_error, sent_at, delivered_at, failed_at, created_at",
|
||||
)
|
||||
.bind(cross_post_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
self.follow_realtime(channel_id, post.follow_id, FollowAction::Retried)
|
||||
.await;
|
||||
Ok(post)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{MemberAction, MemberEvent};
|
||||
use crate::models::channels::ChannelMember;
|
||||
use crate::models::common::Role;
|
||||
use crate::models::workspaces::Workspace;
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct InviteMemberParams {
|
||||
pub user_id: Uuid,
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateMemberParams {
|
||||
pub role: Option<String>,
|
||||
pub muted: Option<bool>,
|
||||
pub pinned: Option<bool>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn member_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<ChannelMember>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, ChannelMember>(
|
||||
"SELECT id, channel_id, user_id, role, status, muted, pinned, \
|
||||
last_read_message_id, last_read_at, joined_at, left_at, created_at, updated_at \
|
||||
FROM channel_member WHERE channel_id = $1 AND status = 'active' \
|
||||
ORDER BY joined_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn member_invite(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: InviteMemberParams,
|
||||
) -> Result<ChannelMember, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
|
||||
let ws = Workspace::find_by_id(self.ctx.db.reader(), channel.workspace_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("workspace not found".into()))?;
|
||||
let ws_role =
|
||||
Workspace::user_role(self.ctx.db.reader(), ws.id, params.user_id, ws.owner_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
if ws_role == Some(Role::Unknown) || ws_role.is_none() {
|
||||
return Err(AppError::BadRequest(
|
||||
"invited user is not a workspace member".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let is_already = self.is_channel_member(channel_id, params.user_id).await?;
|
||||
if is_already {
|
||||
return Err(AppError::Conflict("user is already a member".into()));
|
||||
}
|
||||
|
||||
let role = parse_enum(params.role, Role::Member, Role::Unknown, "role")?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let member = sqlx::query_as::<_, ChannelMember>(
|
||||
"INSERT INTO channel_member \
|
||||
(id, channel_id, user_id, role, status, muted, pinned, joined_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, 'active', false, false, $5, $5, $5) \
|
||||
RETURNING id, channel_id, user_id, role, status, muted, pinned, \
|
||||
last_read_message_id, last_read_at, joined_at, left_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(channel_id)
|
||||
.bind(params.user_id)
|
||||
.bind(role)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
self.update_channel_stats(channel_id, now, &mut txn).await?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
tracing::info!(channel_id = %channel_id, user_id = %params.user_id, "Member invited");
|
||||
let request_id = Uuid::nil();
|
||||
let event = MemberEvent {
|
||||
channel_id,
|
||||
user_id: member.user_id,
|
||||
action: MemberAction::Joined,
|
||||
};
|
||||
self.publish(&format!("im.member.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Member {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub async fn member_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
member_user_id: Uuid,
|
||||
params: UpdateMemberParams,
|
||||
) -> Result<ChannelMember, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
let role = match params.role {
|
||||
Some(ref v) => parse_enum(Some(v.clone()), Role::Member, Role::Unknown, "role")?,
|
||||
None => {
|
||||
// Fetch current role
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"SELECT role::text FROM channel_member \
|
||||
WHERE channel_id = $1 AND user_id = $2 AND status = 'active'",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(member_user_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.map(|s| s.parse::<Role>().unwrap_or(Role::Member))
|
||||
.unwrap_or(Role::Member)
|
||||
}
|
||||
};
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let member = sqlx::query_as::<_, ChannelMember>(
|
||||
"UPDATE channel_member SET role = $1, muted = COALESCE($2, muted), \
|
||||
pinned = COALESCE($3, pinned), updated_at = $4 \
|
||||
WHERE channel_id = $5 AND user_id = $6 AND status = 'active' \
|
||||
RETURNING id, channel_id, user_id, role, status, muted, pinned, \
|
||||
last_read_message_id, last_read_at, joined_at, left_at, created_at, updated_at",
|
||||
)
|
||||
.bind(role)
|
||||
.bind(params.muted)
|
||||
.bind(params.pinned)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.bind(member_user_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = MemberEvent {
|
||||
channel_id,
|
||||
user_id: member.user_id,
|
||||
action: MemberAction::Updated,
|
||||
};
|
||||
self.publish(&format!("im.member.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Member {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub async fn member_kick(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
member_user_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
if member_user_id == channel.created_by {
|
||||
return Err(AppError::Forbidden("cannot kick channel owner".into()));
|
||||
}
|
||||
|
||||
let ws = Workspace::find_by_id(self.ctx.db.reader(), channel.workspace_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("workspace not found".into()))?;
|
||||
if member_user_id == ws.owner_id {
|
||||
return Err(AppError::Forbidden("cannot kick workspace owner".into()));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE channel_member SET status = 'inactive', left_at = $1, updated_at = $1 \
|
||||
WHERE channel_id = $2 AND user_id = $3 AND status = 'active'",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.bind(member_user_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "member not found")?;
|
||||
|
||||
self.update_channel_stats(channel_id, now, &mut txn).await?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
|
||||
tracing::info!(channel_id = %channel_id, user_id = %member_user_id, "Member kicked");
|
||||
let request_id = Uuid::nil();
|
||||
let event = MemberEvent {
|
||||
channel_id,
|
||||
user_id: member_user_id,
|
||||
action: MemberAction::Kicked,
|
||||
};
|
||||
self.publish(&format!("im.member.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Member {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn member_leave(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
|
||||
if channel.created_by == user_uid {
|
||||
return Err(AppError::Forbidden("channel owner cannot leave".into()));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE channel_member SET status = 'inactive', left_at = $1, updated_at = $1 \
|
||||
WHERE channel_id = $2 AND user_id = $3 AND status = 'active'",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "not a member")?;
|
||||
|
||||
self.update_channel_stats(channel_id, now, &mut txn).await?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = MemberEvent {
|
||||
channel_id,
|
||||
user_id: user_uid,
|
||||
action: MemberAction::Left,
|
||||
};
|
||||
self.publish(&format!("im.member.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Member {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn member_join(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
) -> Result<ChannelMember, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let is_already = self.is_channel_member(channel_id, user_uid).await?;
|
||||
if is_already {
|
||||
return Err(AppError::Conflict("already a member".into()));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let member = sqlx::query_as::<_, ChannelMember>(
|
||||
"INSERT INTO channel_member \
|
||||
(id, channel_id, user_id, role, status, muted, pinned, joined_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, 'member', 'active', false, false, $4, $4, $4) \
|
||||
RETURNING id, channel_id, user_id, role, status, muted, pinned, \
|
||||
last_read_message_id, last_read_at, joined_at, left_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
self.update_channel_stats(channel_id, now, &mut txn).await?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = MemberEvent {
|
||||
channel_id,
|
||||
user_id: member.user_id,
|
||||
action: MemberAction::Joined,
|
||||
};
|
||||
self.publish(&format!("im.member.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Member {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub async fn member_update_read(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> Result<ChannelMember, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, ChannelMember>(
|
||||
"UPDATE channel_member SET last_read_message_id = $1, last_read_at = $2, updated_at = $2 \
|
||||
WHERE channel_id = $3 AND user_id = $4 AND status = 'active' \
|
||||
RETURNING id, channel_id, user_id, role, status, muted, pinned, \
|
||||
last_read_message_id, last_read_at, joined_at, left_at, created_at, updated_at",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,889 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{MessageAction, MessageEvent};
|
||||
use crate::models::channels::{Message, MessageBookmark, MessageEditHistory, SavedMessage};
|
||||
use crate::models::common::{JsonValue, MessageType};
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::delivery_trace::trace_message;
|
||||
use crate::service::im::events::ImEvent;
|
||||
use ::redis::Cmd;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
const MESSAGE_SEQ_SCRIPT: &str = "local cur = redis.call('GET', KEYS[1]); if (not cur) or (tonumber(cur) < tonumber(ARGV[1])) then redis.call('SET', KEYS[1], ARGV[1]); end; return redis.call('INCR', KEYS[1]);";
|
||||
static MESSAGE_SEQ_SHA: OnceLock<String> = OnceLock::new();
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct SendMessageParams {
|
||||
pub body: String,
|
||||
pub message_type: Option<String>,
|
||||
pub thread_id: Option<Uuid>,
|
||||
pub reply_to_message_id: Option<Uuid>,
|
||||
pub pinned: Option<bool>,
|
||||
pub attachments: Option<Vec<CreateAttachmentParams>>,
|
||||
pub embeds: Option<Vec<CreateEmbedParams>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct EditMessageParams {
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateAttachmentParams {
|
||||
pub filename: String,
|
||||
pub url: String,
|
||||
pub proxy_url: Option<String>,
|
||||
pub size_bytes: i64,
|
||||
pub mime_type: String,
|
||||
pub width: Option<i32>,
|
||||
pub height: Option<i32>,
|
||||
pub duration_ms: Option<i64>,
|
||||
pub thumbnail_url: Option<String>,
|
||||
pub blurhash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateEmbedParams {
|
||||
pub embed_type: Option<String>,
|
||||
pub title: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub url: Option<String>,
|
||||
pub author_name: Option<String>,
|
||||
pub author_url: Option<String>,
|
||||
pub author_icon_url: Option<String>,
|
||||
pub thumbnail_url: Option<String>,
|
||||
pub image_url: Option<String>,
|
||||
pub color: Option<i32>,
|
||||
pub fields: Option<JsonValue>,
|
||||
pub footer_text: Option<String>,
|
||||
pub footer_icon_url: Option<String>,
|
||||
pub provider_name: Option<String>,
|
||||
pub timestamp: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct MessageListFilters {
|
||||
pub thread_id: Option<Uuid>,
|
||||
pub author_id: Option<Uuid>,
|
||||
pub pinned: Option<bool>,
|
||||
pub before: Option<Uuid>,
|
||||
pub after: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn message_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
filters: MessageListFilters,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<Message>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, Message>(
|
||||
"SELECT id, channel_id, author_id, thread_id, reply_to_message_id, seq, \
|
||||
message_type, body, metadata, pinned, system, edited_at, deleted_at, \
|
||||
created_at, updated_at \
|
||||
FROM message \
|
||||
WHERE channel_id = $1 AND deleted_at IS NULL \
|
||||
AND ($2::uuid IS NULL OR thread_id = $2) \
|
||||
AND ($3::uuid IS NULL OR author_id = $3) \
|
||||
AND ($4::bool IS NULL OR pinned = $4) \
|
||||
AND ($5::uuid IS NULL OR seq < (SELECT seq FROM message WHERE id = $5)) \
|
||||
AND ($6::uuid IS NULL OR seq > (SELECT seq FROM message WHERE id = $6)) \
|
||||
ORDER BY seq DESC LIMIT $7 OFFSET $8",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(filters.thread_id)
|
||||
.bind(filters.author_id)
|
||||
.bind(filters.pinned)
|
||||
.bind(filters.before)
|
||||
.bind(filters.after)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self, ctx, params))]
|
||||
pub async fn message_send(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: SendMessageParams,
|
||||
request_id: Uuid,
|
||||
) -> Result<Message, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_member(user_uid, &channel).await?;
|
||||
|
||||
if channel.read_only {
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let body = required_text(params.body, "body")?;
|
||||
if body.len() > MAX_MESSAGE_BODY {
|
||||
return Err(AppError::BadRequest("message body too long".into()));
|
||||
}
|
||||
|
||||
let msg_type = parse_enum(
|
||||
params.message_type,
|
||||
MessageType::Text,
|
||||
MessageType::Unknown,
|
||||
"message_type",
|
||||
)?;
|
||||
let thread_id = params.thread_id;
|
||||
if let Some(thread_id) = thread_id {
|
||||
self.resolve_thread(thread_id, channel_id).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let message_id = Uuid::now_v7();
|
||||
let seq = self.next_message_seq(channel_id).await?;
|
||||
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let message = sqlx::query_as::<_, Message>(
|
||||
"INSERT INTO message \
|
||||
(id, channel_id, author_id, thread_id, reply_to_message_id, seq, \
|
||||
message_type, body, metadata, pinned, system, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NULL, $9, false, $10, $10) \
|
||||
RETURNING id, channel_id, author_id, thread_id, reply_to_message_id, seq, \
|
||||
message_type, body, metadata, pinned, system, edited_at, deleted_at, \
|
||||
created_at, updated_at",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(thread_id)
|
||||
.bind(params.reply_to_message_id)
|
||||
.bind(seq)
|
||||
.bind(msg_type)
|
||||
.bind(&body)
|
||||
.bind(params.pinned.unwrap_or(false))
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
// Insert attachments
|
||||
if let Some(attachments) = params.attachments {
|
||||
for att in &attachments {
|
||||
let att_filename = required_text(att.filename.clone(), "filename")?;
|
||||
let att_url = required_text(att.url.clone(), "url")?;
|
||||
let att_mime = required_text(att.mime_type.clone(), "mime_type")?;
|
||||
sqlx::query(
|
||||
"INSERT INTO message_attachment \
|
||||
(id, message_id, channel_id, filename, url, proxy_url, \
|
||||
size_bytes, mime_type, width, height, duration_ms, \
|
||||
thumbnail_url, blurhash, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(&att_filename)
|
||||
.bind(&att_url)
|
||||
.bind(att.proxy_url.as_deref())
|
||||
.bind(att.size_bytes)
|
||||
.bind(&att_mime)
|
||||
.bind(att.width)
|
||||
.bind(att.height)
|
||||
.bind(att.duration_ms)
|
||||
.bind(att.thumbnail_url.as_deref())
|
||||
.bind(att.blurhash.as_deref())
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Insert embeds
|
||||
if let Some(embeds) = params.embeds {
|
||||
for emb in &embeds {
|
||||
sqlx::query(
|
||||
"INSERT INTO message_embed \
|
||||
(id, message_id, embed_type, title, description, url, \
|
||||
author_name, author_url, author_icon_url, thumbnail_url, \
|
||||
image_url, color, fields, footer_text, footer_icon_url, \
|
||||
provider_name, \"timestamp\", created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, \
|
||||
$11, $12, $13, $14, $15, $16, $17, $18)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(message_id)
|
||||
.bind(emb.embed_type.as_deref().unwrap_or("rich"))
|
||||
.bind(emb.title.as_deref())
|
||||
.bind(emb.description.as_deref())
|
||||
.bind(emb.url.as_deref())
|
||||
.bind(emb.author_name.as_deref())
|
||||
.bind(emb.author_url.as_deref())
|
||||
.bind(emb.author_icon_url.as_deref())
|
||||
.bind(emb.thumbnail_url.as_deref())
|
||||
.bind(emb.image_url.as_deref())
|
||||
.bind(emb.color)
|
||||
.bind(emb.fields.clone())
|
||||
.bind(emb.footer_text.as_deref())
|
||||
.bind(emb.footer_icon_url.as_deref())
|
||||
.bind(emb.provider_name.as_deref())
|
||||
.bind(emb.timestamp)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(thread_id) = thread_id {
|
||||
sqlx::query(
|
||||
"UPDATE message_thread SET replies_count = replies_count + 1, \
|
||||
participants_count = (SELECT COUNT(DISTINCT author_id)::int FROM message WHERE thread_id = $3 AND deleted_at IS NULL), \
|
||||
last_reply_message_id = $1, last_reply_at = $2, updated_at = $2 \
|
||||
WHERE id = $3 AND channel_id = $4",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(now)
|
||||
.bind(thread_id)
|
||||
.bind(channel_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
// Update channel last_message
|
||||
sqlx::query(
|
||||
"UPDATE channel SET last_message_id = $1, last_message_at = $2, updated_at = $2 \
|
||||
WHERE id = $3",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(now)
|
||||
.bind(channel_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
self.update_channel_stats(channel_id, now, &mut txn).await?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
tracing::info!(message_id = %message_id, channel_id = %channel_id, "Message sent");
|
||||
trace_message(
|
||||
"committed",
|
||||
request_id,
|
||||
channel_id,
|
||||
message.id,
|
||||
Some(message.seq),
|
||||
);
|
||||
|
||||
let event = MessageEvent {
|
||||
channel_id,
|
||||
thread_id: message.thread_id,
|
||||
message_id: message.id,
|
||||
author_id: message.author_id,
|
||||
action: MessageAction::Created,
|
||||
body: Some(message.body.clone()),
|
||||
seq: Some(message.seq),
|
||||
};
|
||||
self.publish(&format!("im.message.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Message {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
pub async fn message_edit(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
params: EditMessageParams,
|
||||
request_id: Uuid,
|
||||
) -> Result<Message, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let body = required_text(params.body, "body")?;
|
||||
if body.len() > MAX_MESSAGE_BODY {
|
||||
return Err(AppError::BadRequest("message body too long".into()));
|
||||
}
|
||||
|
||||
let existing = self.resolve_message(message_id, channel_id).await?;
|
||||
if existing.author_id != user_uid {
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
// Save edit history
|
||||
sqlx::query(
|
||||
"INSERT INTO message_edit_history (id, message_id, channel_id, previous_body, edited_by, edited_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(&existing.body)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let updated = sqlx::query_as::<_, Message>(
|
||||
"UPDATE message SET body = $1, edited_at = $2, updated_at = $2 \
|
||||
WHERE id = $3 AND channel_id = $4 AND deleted_at IS NULL \
|
||||
RETURNING id, channel_id, author_id, thread_id, reply_to_message_id, seq, \
|
||||
message_type, body, metadata, pinned, system, edited_at, deleted_at, \
|
||||
created_at, updated_at",
|
||||
)
|
||||
.bind(&body)
|
||||
.bind(now)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
|
||||
let event = MessageEvent {
|
||||
channel_id,
|
||||
thread_id: updated.thread_id,
|
||||
message_id: updated.id,
|
||||
author_id: updated.author_id,
|
||||
action: MessageAction::Edited,
|
||||
body: Some(updated.body.clone()),
|
||||
seq: Some(updated.seq),
|
||||
};
|
||||
self.publish(&format!("im.message.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Message {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
pub async fn message_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
request_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
|
||||
let existing = self.resolve_message(message_id, channel_id).await?;
|
||||
if existing.author_id != user_uid {
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE message SET deleted_at = $1, updated_at = $1 \
|
||||
WHERE id = $2 AND channel_id = $3 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "message not found")?;
|
||||
|
||||
self.update_channel_stats(channel_id, now, &mut txn).await?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
|
||||
let event = MessageEvent {
|
||||
channel_id,
|
||||
thread_id: None,
|
||||
message_id,
|
||||
author_id: existing.author_id,
|
||||
action: MessageAction::Deleted,
|
||||
body: None,
|
||||
seq: Some(existing.seq),
|
||||
};
|
||||
self.publish(&format!("im.message.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Message {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn message_pin(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
request_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
let message = self.resolve_message(message_id, channel_id).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query("UPDATE message SET pinned = true, updated_at = $1 WHERE id = $2 AND deleted_at IS NULL")
|
||||
.bind(now)
|
||||
.bind(message_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO message_pin (id, message_id, channel_id, pinned_by, pinned_at) \
|
||||
VALUES ($1, $2, $3, $4, $5) \
|
||||
ON CONFLICT (message_id) DO NOTHING",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
|
||||
let event = MessageEvent {
|
||||
channel_id,
|
||||
thread_id: None,
|
||||
message_id,
|
||||
author_id: ctx.user,
|
||||
action: MessageAction::Pinned,
|
||||
body: None,
|
||||
seq: Some(message.seq),
|
||||
};
|
||||
self.publish(&format!("im.message.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Message {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn message_unpin(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
request_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
let message = self.resolve_message(message_id, channel_id).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query("UPDATE message SET pinned = false, updated_at = $1 WHERE id = $2 AND deleted_at IS NULL")
|
||||
.bind(now)
|
||||
.bind(message_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query("DELETE FROM message_pin WHERE message_id = $1")
|
||||
.bind(message_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
|
||||
let event = MessageEvent {
|
||||
channel_id,
|
||||
thread_id: None,
|
||||
message_id,
|
||||
author_id: ctx.user,
|
||||
action: MessageAction::Unpinned,
|
||||
body: None,
|
||||
seq: Some(message.seq),
|
||||
};
|
||||
self.publish(&format!("im.message.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Message {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn message_list_pinned(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
) -> Result<Vec<Message>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, Message>(
|
||||
"SELECT m.id, m.channel_id, m.author_id, m.thread_id, m.reply_to_message_id, m.seq, \
|
||||
m.message_type, m.body, m.metadata, m.pinned, m.system, m.edited_at, m.deleted_at, \
|
||||
m.created_at, m.updated_at \
|
||||
FROM message m \
|
||||
JOIN message_pin mp ON mp.message_id = m.id \
|
||||
WHERE m.channel_id = $1 AND m.deleted_at IS NULL AND m.pinned \
|
||||
ORDER BY mp.pinned_at DESC",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn message_edit_history(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> Result<Vec<MessageEditHistory>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, MessageEditHistory>(
|
||||
"SELECT id, message_id, channel_id, previous_body, edited_by, edited_at \
|
||||
FROM message_edit_history \
|
||||
WHERE message_id = $1 AND channel_id = $2 \
|
||||
ORDER BY edited_at ASC",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn message_bookmark(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
note: Option<String>,
|
||||
) -> Result<MessageBookmark, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
self.resolve_message(message_id, channel_id).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, MessageBookmark>(
|
||||
"INSERT INTO message_bookmark (id, message_id, channel_id, user_id, note, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $6) \
|
||||
ON CONFLICT (message_id, user_id) DO UPDATE SET note = COALESCE($5, message_bookmark.note), updated_at = $6 \
|
||||
RETURNING id, message_id, channel_id, user_id, note, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(note.as_deref())
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn message_unbookmark(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let result = sqlx::query(
|
||||
"DELETE FROM message_bookmark WHERE message_id = $1 AND user_id = $2 AND channel_id = $3",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(user_uid)
|
||||
.bind(channel_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "bookmark not found")
|
||||
}
|
||||
|
||||
pub async fn message_list_bookmarks(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<MessageBookmark>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, MessageBookmark>(
|
||||
"SELECT mb.id, mb.message_id, mb.channel_id, mb.user_id, mb.note, mb.created_at, mb.updated_at \
|
||||
FROM message_bookmark mb \
|
||||
JOIN channel c ON c.id = mb.channel_id \
|
||||
WHERE mb.user_id = $1 AND c.workspace_id = $2 \
|
||||
ORDER BY mb.created_at DESC LIMIT $3 OFFSET $4",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(ws.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn message_save(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
note: Option<String>,
|
||||
) -> Result<SavedMessage, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
self.resolve_message(message_id, channel_id).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, SavedMessage>(
|
||||
"INSERT INTO saved_message (id, user_id, message_id, channel_id, note, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) \
|
||||
ON CONFLICT (user_id, message_id) DO NOTHING \
|
||||
RETURNING id, user_id, message_id, channel_id, note, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_uid)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(note.as_deref())
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn message_unsave(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
message_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
|
||||
let result =
|
||||
sqlx::query("DELETE FROM saved_message WHERE user_id = $1 AND message_id = $2")
|
||||
.bind(user_uid)
|
||||
.bind(message_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "saved message not found")
|
||||
}
|
||||
|
||||
pub async fn message_list_saved(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<SavedMessage>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, SavedMessage>(
|
||||
"SELECT sm.id, sm.user_id, sm.message_id, sm.channel_id, sm.note, sm.created_at \
|
||||
FROM saved_message sm \
|
||||
JOIN channel c ON c.id = sm.channel_id \
|
||||
WHERE sm.user_id = $1 AND c.workspace_id = $2 \
|
||||
ORDER BY sm.created_at DESC LIMIT $3 OFFSET $4",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(ws.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
async fn next_message_seq(&self, channel_id: Uuid) -> Result<i64, AppError> {
|
||||
let key = format!("im:seq:{channel_id}");
|
||||
let mut conn = self.ctx.redis.get_connection()?;
|
||||
let exists: bool = Cmd::new()
|
||||
.arg("EXISTS")
|
||||
.arg(&key)
|
||||
.query(&mut *conn.inner_mut())
|
||||
.map_err(AppError::Redis)?;
|
||||
let db_max = if exists {
|
||||
0
|
||||
} else {
|
||||
sqlx::query_scalar(
|
||||
"SELECT COALESCE(MAX(seq), 0)::bigint FROM message WHERE channel_id = $1",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.fetch_one(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
};
|
||||
let sha = self.message_seq_sha()?;
|
||||
let result: Result<i64, redis::RedisError> = Cmd::new()
|
||||
.arg("EVALSHA")
|
||||
.arg(&sha)
|
||||
.arg(1)
|
||||
.arg(&key)
|
||||
.arg(db_max)
|
||||
.query(&mut *conn.inner_mut());
|
||||
match result {
|
||||
Ok(seq) => Ok(seq),
|
||||
Err(e) if e.to_string().contains("NOSCRIPT") => Cmd::new()
|
||||
.arg("EVAL")
|
||||
.arg(MESSAGE_SEQ_SCRIPT)
|
||||
.arg(1)
|
||||
.arg(&key)
|
||||
.arg(db_max)
|
||||
.query(&mut *conn.inner_mut())
|
||||
.map_err(AppError::Redis),
|
||||
Err(e) => Err(AppError::Redis(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn message_seq_sha(&self) -> Result<String, AppError> {
|
||||
if let Some(sha) = MESSAGE_SEQ_SHA.get() {
|
||||
return Ok(sha.clone());
|
||||
}
|
||||
let mut conn = self.ctx.redis.get_connection()?;
|
||||
let sha: String = Cmd::new()
|
||||
.arg("SCRIPT")
|
||||
.arg("LOAD")
|
||||
.arg(MESSAGE_SEQ_SCRIPT)
|
||||
.query(&mut *conn.inner_mut())
|
||||
.map_err(AppError::Redis)?;
|
||||
let _ = MESSAGE_SEQ_SHA.set(sha.clone());
|
||||
Ok(sha)
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_message(
|
||||
&self,
|
||||
message_id: Uuid,
|
||||
channel_id: Uuid,
|
||||
) -> Result<Message, AppError> {
|
||||
sqlx::query_as::<_, Message>(
|
||||
"SELECT id, channel_id, author_id, thread_id, reply_to_message_id, seq, \
|
||||
message_type, body, metadata, pinned, system, edited_at, deleted_at, \
|
||||
created_at, updated_at \
|
||||
FROM message WHERE id = $1 AND channel_id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("message not found".into()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::service::ServiceContext;
|
||||
use delivery_trace::{trace_error, trace_request};
|
||||
use events::ImEvent;
|
||||
|
||||
pub mod articles;
|
||||
pub mod categories;
|
||||
pub mod channels;
|
||||
pub mod delivery_trace;
|
||||
pub mod drafts;
|
||||
pub mod events;
|
||||
pub mod follows;
|
||||
pub mod members;
|
||||
pub mod messages;
|
||||
pub mod polls;
|
||||
pub mod presence;
|
||||
pub mod reactions;
|
||||
pub mod session;
|
||||
pub mod threads;
|
||||
pub mod util;
|
||||
|
||||
pub use messages::{EditMessageParams, SendMessageParams};
|
||||
pub use presence::UpdatePresenceParams;
|
||||
pub use session::ImSession;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ImService {
|
||||
pub ctx: Arc<ServiceContext>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
fn emit_event(&self, event: ImEvent) {
|
||||
let _ = self.ctx.im_events.publish(event);
|
||||
}
|
||||
|
||||
async fn publish<T: Serialize>(&self, subject: &str, request_id: Uuid, event: &T) {
|
||||
match self
|
||||
.ctx
|
||||
.nats
|
||||
.publish_with_headers(
|
||||
subject,
|
||||
&serde_json::to_vec(event).unwrap_or_default(),
|
||||
vec![("X-Request-Id".into(), request_id.to_string())],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => trace_request("nats_published", request_id, subject),
|
||||
Err(e) => {
|
||||
trace_error("nats_failed", request_id, subject, &e);
|
||||
tracing::warn!(subject, error = %e, "nats publish failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{PollAction, PollEvent};
|
||||
use crate::models::channels::{MessagePoll, MessagePollOption, MessagePollVote};
|
||||
use crate::models::common::PollLayout;
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreatePollParams {
|
||||
pub question: String,
|
||||
pub description: Option<String>,
|
||||
pub options: Vec<CreatePollOptionParams>,
|
||||
pub layout: Option<String>,
|
||||
pub allow_multiselect: Option<bool>,
|
||||
pub duration_hours: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreatePollOptionParams {
|
||||
pub text: String,
|
||||
pub emoji_id: Option<String>,
|
||||
pub emoji_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct VoteParams {
|
||||
pub option_ids: Vec<Uuid>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn poll_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
params: CreatePollParams,
|
||||
) -> Result<MessagePoll, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
self.resolve_message(message_id, channel_id).await?;
|
||||
|
||||
let question = required_text(params.question, "question")?;
|
||||
if params.options.is_empty() || params.options.len() > MAX_POLL_OPTIONS {
|
||||
return Err(AppError::BadRequest(format!(
|
||||
"poll must have between 1 and {MAX_POLL_OPTIONS} options"
|
||||
)));
|
||||
}
|
||||
|
||||
let layout = parse_enum(
|
||||
params.layout,
|
||||
PollLayout::Default,
|
||||
PollLayout::Unknown,
|
||||
"layout",
|
||||
)?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let poll_id = Uuid::now_v7();
|
||||
let ends_at = params
|
||||
.duration_hours
|
||||
.map(|h| now + chrono::Duration::hours(h as i64));
|
||||
|
||||
let validated_options: Vec<(String, Option<String>, Option<String>)> = params
|
||||
.options
|
||||
.iter()
|
||||
.map(|opt| {
|
||||
let text = required_text(opt.text.clone(), "option text")?;
|
||||
if text.len() > MAX_POLL_OPTION_TEXT {
|
||||
return Err(AppError::BadRequest("poll option text too long".into()));
|
||||
}
|
||||
Ok((text, opt.emoji_id.clone(), opt.emoji_name.clone()))
|
||||
})
|
||||
.collect::<Result<Vec<_>, AppError>>()?;
|
||||
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let poll = sqlx::query_as::<_, MessagePoll>(
|
||||
"INSERT INTO message_poll \
|
||||
(id, message_id, channel_id, question, description, layout, \
|
||||
allow_multiselect, duration_hours, ends_at, total_votes, metadata, \
|
||||
created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 0, NULL, $10, $10) \
|
||||
RETURNING id, message_id, channel_id, question, description, layout, \
|
||||
allow_multiselect, duration_hours, ends_at, total_votes, metadata, \
|
||||
created_at, updated_at",
|
||||
)
|
||||
.bind(poll_id)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(&question)
|
||||
.bind(params.description.as_deref())
|
||||
.bind(layout)
|
||||
.bind(params.allow_multiselect.unwrap_or(false))
|
||||
.bind(params.duration_hours)
|
||||
.bind(ends_at)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
for (i, (text, emoji_id, emoji_name)) in validated_options.iter().enumerate() {
|
||||
sqlx::query(
|
||||
"INSERT INTO message_poll_option \
|
||||
(id, poll_id, position, text, emoji_id, emoji_name, vote_count, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 0, $7)",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(poll_id)
|
||||
.bind(i as i32)
|
||||
.bind(text)
|
||||
.bind(emoji_id.as_deref())
|
||||
.bind(emoji_name.as_deref())
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
tracing::info!(poll_id = %poll_id, "Poll created");
|
||||
let request_id = Uuid::nil();
|
||||
let event = PollEvent {
|
||||
channel_id,
|
||||
poll_id,
|
||||
action: PollAction::Created,
|
||||
};
|
||||
self.publish(&format!("im.poll.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Poll {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(poll)
|
||||
}
|
||||
|
||||
pub async fn poll_get(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
poll_id: Uuid,
|
||||
) -> Result<(MessagePoll, Vec<MessagePollOption>), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let poll = sqlx::query_as::<_, MessagePoll>(
|
||||
"SELECT id, message_id, channel_id, question, description, layout, \
|
||||
allow_multiselect, duration_hours, ends_at, total_votes, metadata, \
|
||||
created_at, updated_at \
|
||||
FROM message_poll WHERE id = $1 AND channel_id = $2",
|
||||
)
|
||||
.bind(poll_id)
|
||||
.bind(channel_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("poll not found".into()))?;
|
||||
|
||||
let options = sqlx::query_as::<_, MessagePollOption>(
|
||||
"SELECT id, poll_id, position, text, emoji_id, emoji_name, vote_count, created_at \
|
||||
FROM message_poll_option WHERE poll_id = $1 ORDER BY position ASC",
|
||||
)
|
||||
.bind(poll_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
Ok((poll, options))
|
||||
}
|
||||
|
||||
pub async fn poll_vote(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
poll_id: Uuid,
|
||||
params: VoteParams,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let poll = sqlx::query_as::<_, MessagePoll>(
|
||||
"SELECT id, message_id, channel_id, question, description, layout, \
|
||||
allow_multiselect, duration_hours, ends_at, total_votes, metadata, \
|
||||
created_at, updated_at \
|
||||
FROM message_poll WHERE id = $1 AND channel_id = $2",
|
||||
)
|
||||
.bind(poll_id)
|
||||
.bind(channel_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("poll not found".into()))?;
|
||||
|
||||
if let Some(ends) = poll.ends_at
|
||||
&& chrono::Utc::now() > ends
|
||||
{
|
||||
return Err(AppError::BadRequest("poll has ended".into()));
|
||||
}
|
||||
|
||||
if !poll.allow_multiselect && params.option_ids.len() > 1 {
|
||||
return Err(AppError::BadRequest("multiselect not allowed".into()));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let mut txn = self
|
||||
.ctx
|
||||
.db
|
||||
.writer()
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|_| AppError::TxnError)?;
|
||||
sqlx::query("SET LOCAL app.current_user_id = $1")
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
// Collect old option_ids before deleting
|
||||
let old_option_ids: Vec<Uuid> = sqlx::query_scalar(
|
||||
"DELETE FROM message_poll_vote WHERE poll_id = $1 AND user_id = $2 RETURNING option_id",
|
||||
)
|
||||
.bind(poll_id)
|
||||
.bind(user_uid)
|
||||
.fetch_all(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let removed = old_option_ids.len() as i32;
|
||||
|
||||
// Decrement old vote counts
|
||||
for opt_id in &old_option_ids {
|
||||
sqlx::query(
|
||||
"UPDATE message_poll_option SET vote_count = GREATEST(vote_count - 1, 0) WHERE id = $1",
|
||||
)
|
||||
.bind(opt_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
// Insert new votes
|
||||
let mut new_count = 0i32;
|
||||
for option_id in ¶ms.option_ids {
|
||||
sqlx::query(
|
||||
"INSERT INTO message_poll_vote (id, poll_id, option_id, user_id, voted_at) \
|
||||
VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(poll_id)
|
||||
.bind(option_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE message_poll_option SET vote_count = vote_count + 1 \
|
||||
WHERE id = $1 AND poll_id = $2",
|
||||
)
|
||||
.bind(option_id)
|
||||
.bind(poll_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
new_count += 1;
|
||||
}
|
||||
|
||||
let delta = new_count - removed;
|
||||
sqlx::query(
|
||||
"UPDATE message_poll SET total_votes = total_votes + $1, updated_at = $2 WHERE id = $3",
|
||||
)
|
||||
.bind(delta)
|
||||
.bind(now)
|
||||
.bind(poll_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = PollEvent {
|
||||
channel_id,
|
||||
poll_id,
|
||||
action: PollAction::Voted,
|
||||
};
|
||||
self.publish(&format!("im.poll.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Poll {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn poll_results(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
poll_id: Uuid,
|
||||
) -> Result<Vec<MessagePollVote>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, MessagePollVote>(
|
||||
"SELECT id, poll_id, option_id, user_id, voted_at \
|
||||
FROM message_poll_vote WHERE poll_id = $1 ORDER BY voted_at ASC",
|
||||
)
|
||||
.bind(poll_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn poll_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
poll_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
|
||||
let result = sqlx::query("DELETE FROM message_poll WHERE id = $1 AND channel_id = $2")
|
||||
.bind(poll_id)
|
||||
.bind(channel_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "poll not found")?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = PollEvent {
|
||||
channel_id,
|
||||
poll_id,
|
||||
action: PollAction::Deleted,
|
||||
};
|
||||
self.publish(&format!("im.poll.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Poll {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{PresenceEvent, TypingEvent};
|
||||
use crate::models::common::PresenceStatus;
|
||||
use crate::models::users::UserPresence;
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdatePresenceParams {
|
||||
pub status: String,
|
||||
pub custom_status_text: Option<String>,
|
||||
pub custom_status_emoji: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct TypingParams {
|
||||
pub channel_id: Uuid,
|
||||
pub thread_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn presence_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
params: UpdatePresenceParams,
|
||||
) -> Result<UserPresence, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let _ = self.resolve_workspace(wk_name).await?;
|
||||
|
||||
let status = parse_enum(
|
||||
Some(params.status),
|
||||
PresenceStatus::Online,
|
||||
PresenceStatus::Unknown,
|
||||
"status",
|
||||
)?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let presence = sqlx::query_as::<_, UserPresence>(
|
||||
"INSERT INTO user_presence (id, user_id, status, custom_status_text, custom_status_emoji, \
|
||||
last_active_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $6, $6) \
|
||||
ON CONFLICT (user_id) DO UPDATE SET \
|
||||
status = $3, custom_status_text = $4, custom_status_emoji = $5, \
|
||||
last_active_at = $6, updated_at = $6 \
|
||||
RETURNING id, user_id, status, custom_status_text, custom_status_emoji, \
|
||||
device_type, ip_address, last_active_at, last_seen_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_uid)
|
||||
.bind(status)
|
||||
.bind(params.custom_status_text.as_deref())
|
||||
.bind(params.custom_status_emoji.as_deref())
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
// Cache in Redis for fast lookup
|
||||
let key = format!("{PRESENCE_PREFIX}{user_uid}");
|
||||
if let Ok(mut conn) = self.ctx.redis.get_connection() {
|
||||
let _ = redis::cmd("SETEX")
|
||||
.arg(&key)
|
||||
.arg(PRESENCE_TTL_SECS as u64)
|
||||
.arg(status.to_string())
|
||||
.query::<()>(&mut *conn.inner_mut());
|
||||
}
|
||||
|
||||
let request_id = Uuid::nil();
|
||||
let event = PresenceEvent {
|
||||
user_id: user_uid,
|
||||
status: presence.status.to_string(),
|
||||
custom_status_text: presence.custom_status_text.clone(),
|
||||
custom_status_emoji: presence.custom_status_emoji.clone(),
|
||||
};
|
||||
self.publish(&format!("im.presence.{}", user_uid), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Presence {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(presence)
|
||||
}
|
||||
|
||||
pub async fn presence_get(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
user_id: Uuid,
|
||||
) -> Result<Option<UserPresence>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
|
||||
// Try DB first (has full record)
|
||||
if let Some(p) = sqlx::query_as::<_, UserPresence>(
|
||||
"SELECT id, user_id, status, custom_status_text, custom_status_emoji, \
|
||||
device_type, ip_address, last_active_at, last_seen_at, created_at, updated_at \
|
||||
FROM user_presence WHERE user_id = $1",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
{
|
||||
return Ok(Some(p));
|
||||
}
|
||||
|
||||
// Fallback: check Redis for a cached status
|
||||
let key = format!("{PRESENCE_PREFIX}{user_id}");
|
||||
if let Ok(mut conn) = self.ctx.redis.get_connection() {
|
||||
let cached: Option<String> = redis::cmd("GET")
|
||||
.arg(&key)
|
||||
.query(&mut *conn.inner_mut())
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
if let Some(status_str) = cached
|
||||
&& let Ok(status) = status_str.parse::<PresenceStatus>()
|
||||
{
|
||||
let now = chrono::Utc::now();
|
||||
return Ok(Some(UserPresence {
|
||||
id: Uuid::nil(),
|
||||
user_id,
|
||||
status,
|
||||
custom_status_text: None,
|
||||
custom_status_emoji: None,
|
||||
device_type: None,
|
||||
ip_address: None,
|
||||
last_active_at: now,
|
||||
last_seen_at: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub async fn presence_heartbeat(&self, ctx: &ImSession, wk_name: &str) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
|
||||
let key = format!("{PRESENCE_PREFIX}{user_uid}");
|
||||
if let Ok(mut conn) = self.ctx.redis.get_connection()
|
||||
&& let Err(e) = redis::cmd("SETEX")
|
||||
.arg(&key)
|
||||
.arg(PRESENCE_TTL_SECS as u64)
|
||||
.arg("online")
|
||||
.query::<()>(&mut *conn.inner_mut())
|
||||
{
|
||||
tracing::warn!(error = %e, "redis presence heartbeat failed");
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
if let Err(e) = sqlx::query(
|
||||
"UPDATE user_presence SET last_active_at = $1, updated_at = $1 WHERE user_id = $2",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(user_uid)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "db presence heartbeat failed");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn typing_start(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
params: TypingParams,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
|
||||
let channel = self.resolve_channel(params.channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let key = typing_key(params.channel_id, params.thread_id, user_uid);
|
||||
let mut conn = self.ctx.redis.get_connection()?;
|
||||
redis::cmd("SETEX")
|
||||
.arg(&key)
|
||||
.arg(TYPING_TTL_SECS as u64)
|
||||
.arg("1")
|
||||
.query::<()>(&mut *conn.inner_mut())?;
|
||||
|
||||
let request_id = Uuid::nil();
|
||||
let event = TypingEvent {
|
||||
channel_id: params.channel_id,
|
||||
thread_id: params.thread_id,
|
||||
user_id: user_uid,
|
||||
};
|
||||
self.publish(
|
||||
&format!("im.typing.{}", params.channel_id),
|
||||
request_id,
|
||||
&event,
|
||||
)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Typing {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn typing_stop(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
params: TypingParams,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
self.ensure_workspace_readable(user_uid, &ws).await?;
|
||||
|
||||
let key = typing_key(params.channel_id, params.thread_id, user_uid);
|
||||
let mut conn = self.ctx.redis.get_connection()?;
|
||||
redis::cmd("DEL")
|
||||
.arg(&key)
|
||||
.query::<()>(&mut *conn.inner_mut())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn typing_key(channel_id: Uuid, thread_id: Option<Uuid>, user_id: Uuid) -> String {
|
||||
match thread_id {
|
||||
Some(tid) => format!("{TYPING_PREFIX}{channel_id}:{tid}:{user_id}"),
|
||||
None => format!("{TYPING_PREFIX}{channel_id}:{user_id}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{ReactionAction, ReactionEvent};
|
||||
use crate::models::channels::{MessageMention, MessageReaction};
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct AddReactionParams {
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct AddMentionParams {
|
||||
pub mentioned_user_id: Uuid,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn reaction_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> Result<Vec<MessageReaction>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query_as::<_, MessageReaction>(
|
||||
"SELECT id, message_id, channel_id, user_id, content, created_at \
|
||||
FROM message_reaction WHERE message_id = $1 AND channel_id = $2 \
|
||||
ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn reaction_add(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
params: AddReactionParams,
|
||||
) -> Result<MessageReaction, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
self.resolve_message(message_id, channel_id).await?;
|
||||
|
||||
let content = required_text(params.content, "content")?;
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let reaction = sqlx::query_as::<_, MessageReaction>(
|
||||
"INSERT INTO message_reaction (id, message_id, channel_id, user_id, content, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) \
|
||||
ON CONFLICT (message_id, user_id, content) DO NOTHING \
|
||||
RETURNING id, message_id, channel_id, user_id, content, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(&content)
|
||||
.bind(now)
|
||||
.fetch_optional(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if reaction.is_none() {
|
||||
return Err(AppError::Conflict("reaction already exists".into()));
|
||||
}
|
||||
|
||||
let reaction = reaction.unwrap();
|
||||
let request_id = Uuid::nil();
|
||||
let event = ReactionEvent {
|
||||
channel_id,
|
||||
message_id,
|
||||
user_id: reaction.user_id,
|
||||
action: ReactionAction::Added,
|
||||
content: Some(reaction.content.clone()),
|
||||
};
|
||||
self.publish(&format!("im.reaction.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Reaction {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(reaction)
|
||||
}
|
||||
|
||||
pub async fn reaction_remove(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
content: &str,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
|
||||
let result = sqlx::query(
|
||||
"DELETE FROM message_reaction \
|
||||
WHERE message_id = $1 AND channel_id = $2 AND user_id = $3 AND content = $4",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.bind(user_uid)
|
||||
.bind(content)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "reaction not found")?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = ReactionEvent {
|
||||
channel_id,
|
||||
message_id,
|
||||
user_id: user_uid,
|
||||
action: ReactionAction::Removed,
|
||||
content: Some(content.to_string()),
|
||||
};
|
||||
self.publish(&format!("im.reaction.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Reaction {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reaction_remove_all(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
sqlx::query("DELETE FROM message_reaction WHERE message_id = $1 AND channel_id = $2")
|
||||
.bind(message_id)
|
||||
.bind(channel_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let request_id = Uuid::nil();
|
||||
let event = ReactionEvent {
|
||||
channel_id,
|
||||
message_id,
|
||||
user_id: user_uid,
|
||||
action: ReactionAction::Removed,
|
||||
content: None,
|
||||
};
|
||||
self.publish(&format!("im.reaction.{}", channel_id), request_id, &event)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Reaction {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn mention_list_for_user(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
unread_only: bool,
|
||||
) -> Result<Vec<MessageMention>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let _ = self.resolve_workspace(wk_name).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
if unread_only {
|
||||
sqlx::query_as::<_, MessageMention>(
|
||||
"SELECT id, message_id, channel_id, mentioned_user_id, mentioned_by, read_at, created_at \
|
||||
FROM message_mention \
|
||||
WHERE mentioned_user_id = $1 AND read_at IS NULL \
|
||||
ORDER BY created_at DESC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
} else {
|
||||
sqlx::query_as::<_, MessageMention>(
|
||||
"SELECT id, message_id, channel_id, mentioned_user_id, mentioned_by, read_at, created_at \
|
||||
FROM message_mention \
|
||||
WHERE mentioned_user_id = $1 \
|
||||
ORDER BY created_at DESC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(user_uid)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mention_mark_read(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
mention_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE message_mention SET read_at = $1 \
|
||||
WHERE id = $2 AND mentioned_user_id = $3 AND read_at IS NULL",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(mention_id)
|
||||
.bind(user_uid)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "mention not found or already read")
|
||||
}
|
||||
|
||||
pub async fn mention_mark_all_read(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
wk_name: &str,
|
||||
) -> Result<u64, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let _ = self.resolve_workspace(wk_name).await?;
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let result = sqlx::query(
|
||||
"UPDATE message_mention SET read_at = $1 \
|
||||
WHERE mentioned_user_id = $2 AND read_at IS NULL",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(user_uid)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
Ok(result.rows_affected())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImSession {
|
||||
pub user: Uuid,
|
||||
}
|
||||
|
||||
impl ImSession {
|
||||
pub fn new(user: Uuid) -> Self {
|
||||
Self { user }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::immediate::{ThreadAction, ThreadEvent};
|
||||
use crate::models::channels::MessageThread;
|
||||
use crate::service::ImService;
|
||||
use crate::service::im::events::ImEvent;
|
||||
|
||||
use super::session::ImSession;
|
||||
use super::util::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateThreadParams {
|
||||
pub title: Option<String>,
|
||||
pub root_message_id: Uuid,
|
||||
pub tags: Option<Vec<String>>,
|
||||
pub auto_archive_duration: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateThreadParams {
|
||||
pub title: Option<String>,
|
||||
pub tags: Option<Vec<String>>,
|
||||
pub pinned: Option<bool>,
|
||||
pub locked: Option<bool>,
|
||||
pub rate_limit_per_user: Option<i32>,
|
||||
pub resolved: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct ThreadListFilters {
|
||||
pub pinned: Option<bool>,
|
||||
pub locked: Option<bool>,
|
||||
pub resolved: Option<bool>,
|
||||
}
|
||||
|
||||
impl ImService {
|
||||
pub async fn thread_list(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
filters: ThreadListFilters,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<MessageThread>, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, MessageThread>(
|
||||
"SELECT id, channel_id, root_message_id, created_by, replies_count, \
|
||||
participants_count, last_reply_message_id, last_reply_at, resolved, \
|
||||
resolved_by, resolved_at, title, tags, pinned, locked, \
|
||||
rate_limit_per_user, auto_archive_at, created_at, updated_at \
|
||||
FROM message_thread WHERE channel_id = $1 \
|
||||
AND ($2::bool IS NULL OR pinned = $2) \
|
||||
AND ($3::bool IS NULL OR locked = $3) \
|
||||
AND ($4::bool IS NULL OR resolved = $4) \
|
||||
ORDER BY last_reply_at DESC NULLS LAST, created_at DESC \
|
||||
LIMIT $5 OFFSET $6",
|
||||
)
|
||||
.bind(channel_id)
|
||||
.bind(filters.pinned)
|
||||
.bind(filters.locked)
|
||||
.bind(filters.resolved)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn thread_get(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
thread_id: Uuid,
|
||||
) -> Result<MessageThread, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
self.resolve_thread(thread_id, channel_id).await
|
||||
}
|
||||
|
||||
pub async fn thread_create(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
params: CreateThreadParams,
|
||||
) -> Result<MessageThread, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
self.resolve_message(params.root_message_id, channel_id)
|
||||
.await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let thread_id = Uuid::now_v7();
|
||||
let tags = params.tags.unwrap_or_default();
|
||||
let auto_archive_at = params
|
||||
.auto_archive_duration
|
||||
.map(|d| now + chrono::Duration::minutes(d as i64));
|
||||
|
||||
let thread = sqlx::query_as::<_, MessageThread>(
|
||||
"INSERT INTO message_thread \
|
||||
(id, channel_id, root_message_id, created_by, replies_count, \
|
||||
participants_count, last_reply_message_id, last_reply_at, resolved, \
|
||||
title, tags, pinned, locked, auto_archive_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, 0, 0, NULL, NULL, false, $5, $6, false, false, $7, $8, $8) \
|
||||
RETURNING id, channel_id, root_message_id, created_by, replies_count, \
|
||||
participants_count, last_reply_message_id, last_reply_at, resolved, \
|
||||
resolved_by, resolved_at, title, tags, pinned, locked, \
|
||||
rate_limit_per_user, auto_archive_at, created_at, updated_at",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(channel_id)
|
||||
.bind(params.root_message_id)
|
||||
.bind(user_uid)
|
||||
.bind(params.title.as_deref())
|
||||
.bind(&tags)
|
||||
.bind(auto_archive_at)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
tracing::info!(thread_id = %thread_id, channel_id = %channel_id, "Thread created");
|
||||
let request_id = Uuid::nil();
|
||||
let event = ThreadEvent {
|
||||
channel_id,
|
||||
thread_id,
|
||||
action: ThreadAction::Created,
|
||||
};
|
||||
self.publish(
|
||||
&format!("im.thread.{}.{}", channel_id, thread_id),
|
||||
request_id,
|
||||
&event,
|
||||
)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Thread {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
pub async fn thread_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
thread_id: Uuid,
|
||||
params: UpdateThreadParams,
|
||||
) -> Result<MessageThread, AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
let thread = self.resolve_thread(thread_id, channel_id).await?;
|
||||
|
||||
let is_owner = thread.created_by == user_uid;
|
||||
if !is_owner {
|
||||
self.ensure_channel_editable(user_uid, &channel).await?;
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
let resolved_by = if params.resolved == Some(true) && !thread.resolved {
|
||||
Some(user_uid)
|
||||
} else {
|
||||
thread.resolved_by
|
||||
};
|
||||
let resolved_at = if params.resolved == Some(true) && !thread.resolved {
|
||||
Some(now)
|
||||
} else if params.resolved == Some(false) {
|
||||
None
|
||||
} else {
|
||||
thread.resolved_at
|
||||
};
|
||||
|
||||
let updated = sqlx::query_as::<_, MessageThread>(
|
||||
"UPDATE message_thread SET \
|
||||
title = COALESCE($1, title), \
|
||||
tags = COALESCE($2, tags), \
|
||||
pinned = COALESCE($3, pinned), \
|
||||
locked = COALESCE($4, locked), \
|
||||
rate_limit_per_user = COALESCE($5, rate_limit_per_user), \
|
||||
resolved = COALESCE($6, resolved), \
|
||||
resolved_by = $7, resolved_at = $8, \
|
||||
updated_at = $9 \
|
||||
WHERE id = $10 \
|
||||
RETURNING id, channel_id, root_message_id, created_by, replies_count, \
|
||||
participants_count, last_reply_message_id, last_reply_at, resolved, \
|
||||
resolved_by, resolved_at, title, tags, pinned, locked, \
|
||||
rate_limit_per_user, auto_archive_at, created_at, updated_at",
|
||||
)
|
||||
.bind(params.title.as_deref())
|
||||
.bind(params.tags.as_deref())
|
||||
.bind(params.pinned)
|
||||
.bind(params.locked)
|
||||
.bind(params.rate_limit_per_user)
|
||||
.bind(params.resolved)
|
||||
.bind(resolved_by)
|
||||
.bind(resolved_at)
|
||||
.bind(now)
|
||||
.bind(thread_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = ThreadEvent {
|
||||
channel_id,
|
||||
thread_id,
|
||||
action: ThreadAction::Updated,
|
||||
};
|
||||
self.publish(
|
||||
&format!("im.thread.{}.{}", channel_id, thread_id),
|
||||
request_id,
|
||||
&event,
|
||||
)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Thread {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
pub async fn thread_delete(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
thread_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_admin(user_uid, &channel).await?;
|
||||
|
||||
let result = sqlx::query("DELETE FROM message_thread WHERE id = $1 AND channel_id = $2")
|
||||
.bind(thread_id)
|
||||
.bind(channel_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
ensure_affected(result.rows_affected(), "thread not found")?;
|
||||
let request_id = Uuid::nil();
|
||||
let event = ThreadEvent {
|
||||
channel_id,
|
||||
thread_id,
|
||||
action: ThreadAction::Deleted,
|
||||
};
|
||||
self.publish(
|
||||
&format!("im.thread.{}.{}", channel_id, thread_id),
|
||||
request_id,
|
||||
&event,
|
||||
)
|
||||
.await;
|
||||
self.emit_event(ImEvent::Thread {
|
||||
request_id,
|
||||
data: event,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn thread_read_state_update(
|
||||
&self,
|
||||
ctx: &ImSession,
|
||||
_wk_name: &str,
|
||||
channel_id: Uuid,
|
||||
thread_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user;
|
||||
let channel = self.resolve_channel(channel_id).await?;
|
||||
self.ensure_channel_readable(user_uid, &channel).await?;
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query(
|
||||
"INSERT INTO thread_read_state (id, user_id, thread_id, channel_id, last_read_message_id, last_read_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $6) \
|
||||
ON CONFLICT (user_id, thread_id) DO UPDATE SET \
|
||||
last_read_message_id = $5, last_read_at = $6, updated_at = $6",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(user_uid)
|
||||
.bind(thread_id)
|
||||
.bind(channel_id)
|
||||
.bind(message_id)
|
||||
.bind(now)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_thread(
|
||||
&self,
|
||||
thread_id: Uuid,
|
||||
channel_id: Uuid,
|
||||
) -> Result<MessageThread, AppError> {
|
||||
sqlx::query_as::<_, MessageThread>(
|
||||
"SELECT id, channel_id, root_message_id, created_by, replies_count, \
|
||||
participants_count, last_reply_message_id, last_reply_at, resolved, \
|
||||
resolved_by, resolved_at, title, tags, pinned, locked, \
|
||||
rate_limit_per_user, auto_archive_at, created_at, updated_at \
|
||||
FROM message_thread WHERE id = $1 AND channel_id = $2",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(channel_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("thread not found".into()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
pub use crate::service::util::{
|
||||
clamp_limit_offset, ensure_affected, merge_optional_text, parse_enum, required_text, role_level,
|
||||
};
|
||||
|
||||
/// Maximum length for a channel name.
|
||||
pub const MAX_CHANNEL_NAME: usize = 100;
|
||||
|
||||
/// Maximum length for a channel topic.
|
||||
pub const MAX_CHANNEL_TOPIC: usize = 1024;
|
||||
|
||||
/// Maximum length for a message body.
|
||||
pub const MAX_MESSAGE_BODY: usize = 4096;
|
||||
|
||||
/// Maximum length for an article title.
|
||||
pub const MAX_ARTICLE_TITLE: usize = 256;
|
||||
|
||||
/// Maximum number of poll options.
|
||||
pub const MAX_POLL_OPTIONS: usize = 10;
|
||||
|
||||
/// Maximum length for a poll option text.
|
||||
pub const MAX_POLL_OPTION_TEXT: usize = 100;
|
||||
|
||||
/// Redis key prefix for typing indicators.
|
||||
pub const TYPING_PREFIX: &str = "im:typing:";
|
||||
|
||||
/// Redis key prefix for user presence.
|
||||
pub const PRESENCE_PREFIX: &str = "im:presence:";
|
||||
|
||||
/// Redis TTL for typing indicators (seconds).
|
||||
pub const TYPING_TTL_SECS: usize = 8;
|
||||
|
||||
/// Redis TTL for presence heartbeats (seconds).
|
||||
pub const PRESENCE_TTL_SECS: usize = 120;
|
||||
|
||||
/// Maximum length for generated slugs.
|
||||
pub const MAX_SLUG_LEN: usize = 128;
|
||||
|
||||
/// Generate a slug from a title string.
|
||||
pub fn slugify(title: &str) -> String {
|
||||
let slug: String = title
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.filter_map(|c| {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
Some(c)
|
||||
} else if c.is_whitespace() || !c.is_ascii() {
|
||||
Some('-')
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<String>()
|
||||
.split('-')
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-");
|
||||
|
||||
let mut result = slug;
|
||||
result.truncate(MAX_SLUG_LEN);
|
||||
if result.ends_with('-') {
|
||||
result.pop();
|
||||
}
|
||||
result
|
||||
}
|
||||
Reference in New Issue
Block a user