This commit is contained in:
2026-08-22 20:34:43 +02:00
parent 120b6cf4d5
commit da151c13ed
14 changed files with 366 additions and 21 deletions
+12 -12
View File
@@ -6,6 +6,7 @@ use crate::domain::dto::channel::{
};
use crate::http::context::{CurrentUser, Superuser};
use crate::http::error::HTTPError;
use crate::models::{channel, channel_user};
use crate::routes::channel::mapper;
use axum::{
Json,
@@ -13,6 +14,15 @@ use axum::{
http::StatusCode,
};
use uuid::Uuid;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
async fn require_channel_member(state: &AppState, channel_id: Uuid, user_id: Uuid) -> Result<(), HTTPError> {
let channel = state.repositories.channel.get_by_id(channel_id).await?.ok_or(HTTPError::NotFound)?;
if channel.channel_type == channel::ChannelType::DM
&& channel_user::Entity::find().filter(channel_user::Column::ChannelId.eq(channel_id)).filter(channel_user::Column::UserId.eq(user_id)).one(&state.db).await?.is_none()
{ return Err(HTTPError::Forbidden); }
Ok(())
}
/// Liste tous les channels
#[utoipa::path(
@@ -54,12 +64,7 @@ pub async fn get_read_state(
State(state): State<AppState>,
Path(channel_id): Path<Uuid>,
) -> Result<Json<ReadStateResponse>, HTTPError> {
state
.repositories
.channel
.get_by_id(channel_id)
.await?
.ok_or(HTTPError::NotFound)?;
require_channel_member(&state, channel_id, user.id).await?;
let read_state = state
.repositories
.read_state
@@ -99,12 +104,7 @@ pub async fn set_read_state(
Path(channel_id): Path<Uuid>,
Json(payload): Json<SetReadStateRequest>,
) -> Result<Json<ReadStateResponse>, HTTPError> {
state
.repositories
.channel
.get_by_id(channel_id)
.await?
.ok_or(HTTPError::NotFound)?;
require_channel_member(&state, channel_id, user.id).await?;
if let Some(message_id) = payload.last_read_message_id {
let message = state
+88
View File
@@ -0,0 +1,88 @@
use crate::core::state::AppState;
use crate::domain::dto::conversation::{
ConversationParticipantResponse, ConversationResponse, CreateConversationRequest,
ForkConversationRequest,
};
use crate::http::context::CurrentUser;
use crate::http::error::HTTPError;
use crate::models::{channel, channel_user, message, user};
use axum::{Json, extract::{Path, State}};
use chrono::Utc;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, QueryOrder, Set, TransactionTrait};
use std::collections::HashSet;
use uuid::Uuid;
async fn member_ids(state: &AppState, channel_id: Uuid) -> Result<Vec<Uuid>, HTTPError> {
Ok(channel_user::Entity::find()
.filter(channel_user::Column::ChannelId.eq(channel_id))
.all(&state.db).await?.into_iter().map(|m| m.user_id).collect())
}
async fn response(state: &AppState, current_user_id: Uuid, channel: channel::Model) -> Result<ConversationResponse, HTTPError> {
let ids = member_ids(state, channel.id).await?;
let users = user::Entity::find().filter(user::Column::Id.is_in(ids.clone())).all(&state.db).await?;
let mut participants: Vec<_> = users.into_iter().map(|u| ConversationParticipantResponse { id: u.id, username: u.username }).collect();
participants.sort_by(|a, b| a.username.to_lowercase().cmp(&b.username.to_lowercase()));
let title = participants.iter().filter(|p| p.id != current_user_id).map(|p| p.username.clone()).collect::<Vec<_>>().join(", ");
let last_message = message::Entity::find().filter(message::Column::ChannelId.eq(channel.id)).order_by_desc(message::Column::Id).one(&state.db).await?.map(|m| m.content);
let unread_count = state.repositories.read_state.unread_counts(&[channel.id], current_user_id).await?.get(&channel.id).copied().unwrap_or(0);
Ok(ConversationResponse { id: channel.id, title: if title.is_empty() { "Discussion".into() } else { title }, participants, last_message, unread_count, created_at: channel.created_at, updated_at: channel.updated_at })
}
async fn create_channel(state: &AppState, ids: &[Uuid]) -> Result<channel::Model, HTTPError> {
let txn = state.db.begin().await?;
let channel = channel::ActiveModel { server_id: Set(None), category_id: Set(None), channel_type: Set(channel::ChannelType::DM), name: Set(None), ..Default::default() }.insert(&txn).await?;
for user_id in ids {
channel_user::ActiveModel { channel_id: Set(channel.id), user_id: Set(*user_id), role: Set("member".into()), joined_at: Set(Utc::now()), ..Default::default() }.insert(&txn).await?;
}
txn.commit().await?;
state.event_bus.emit("channel_created", channel.clone());
Ok(channel)
}
async fn validate_ids(state: &AppState, ids: &[Uuid]) -> Result<(), HTTPError> {
if ids.is_empty() { return Err(HTTPError::BadRequest("At least one participant is required".into())); }
let found = user::Entity::find().filter(user::Column::Id.is_in(ids.to_vec())).all(&state.db).await?;
if found.len() != ids.iter().collect::<HashSet<_>>().len() { return Err(HTTPError::BadRequest("Unknown participant".into())); }
Ok(())
}
#[utoipa::path(get, path = "/conversations", responses((status = 200, body = [ConversationResponse])), tag = "Conversations", security(("bearerAuth" = [])))]
pub async fn list(user: CurrentUser, State(state): State<AppState>) -> Result<Json<Vec<ConversationResponse>>, HTTPError> {
let memberships = channel_user::Entity::find().filter(channel_user::Column::UserId.eq(user.id)).all(&state.db).await?;
let ids: Vec<_> = memberships.into_iter().map(|m| m.channel_id).collect();
if ids.is_empty() { return Ok(Json(Vec::new())); }
let channels = channel::Entity::find().filter(channel::Column::Id.is_in(ids)).filter(channel::Column::ChannelType.eq(channel::ChannelType::DM)).order_by_desc(channel::Column::UpdatedAt).all(&state.db).await?;
let mut result = Vec::with_capacity(channels.len());
for channel in channels { result.push(response(&state, user.id, channel).await?); }
Ok(Json(result))
}
#[utoipa::path(post, path = "/conversations", request_body = CreateConversationRequest, responses((status = 200, body = ConversationResponse)), tag = "Conversations", security(("bearerAuth" = [])))]
pub async fn create(user: CurrentUser, State(state): State<AppState>, Json(payload): Json<CreateConversationRequest>) -> Result<Json<ConversationResponse>, HTTPError> {
let mut ids = payload.user_ids;
ids.push(user.id);
ids.sort_unstable(); ids.dedup();
validate_ids(&state, &ids).await?;
let channels = channel_user::Entity::find().filter(channel_user::Column::UserId.eq(user.id)).all(&state.db).await?;
for membership in channels {
if let Some(channel) = channel::Entity::find_by_id(membership.channel_id).filter(channel::Column::ChannelType.eq(channel::ChannelType::DM)).one(&state.db).await? {
let existing: HashSet<_> = member_ids(&state, channel.id).await?.into_iter().collect();
if existing == ids.iter().copied().collect() { return Ok(Json(response(&state, user.id, channel).await?)); }
}
}
let channel = create_channel(&state, &ids).await?;
Ok(Json(response(&state, user.id, channel).await?))
}
#[utoipa::path(post, path = "/conversations/{id}/fork", request_body = ForkConversationRequest, params(("id" = Uuid, Path)), responses((status = 200, body = ConversationResponse)), tag = "Conversations", security(("bearerAuth" = [])))]
pub async fn fork(user: CurrentUser, State(state): State<AppState>, Path(id): Path<Uuid>, Json(payload): Json<ForkConversationRequest>) -> Result<Json<ConversationResponse>, HTTPError> {
let source = channel::Entity::find_by_id(id).one(&state.db).await?.ok_or(HTTPError::NotFound)?;
if source.channel_type != channel::ChannelType::DM || !member_ids(&state, id).await?.contains(&user.id) { return Err(HTTPError::Forbidden); }
let mut ids = member_ids(&state, id).await?;
ids.extend(payload.user_ids);
ids.sort_unstable(); ids.dedup();
validate_ids(&state, &ids).await?;
let channel = create_channel(&state, &ids).await?;
Ok(Json(response(&state, user.id, channel).await?))
}
+2
View File
@@ -0,0 +1,2 @@
pub mod handlers;
pub mod routes;
+9
View File
@@ -0,0 +1,9 @@
use super::handlers;
use crate::core::state::AppState;
use axum::{routing::{get, post}, Router};
pub fn router() -> Router<AppState> {
Router::new()
.route("/conversations", get(handlers::list).post(handlers::create))
.route("/conversations/{id}/fork", post(handlers::fork))
}
+32
View File
@@ -6,6 +6,7 @@ use crate::domain::dto::message::{
use crate::domain::dto::reaction::{CreateReactionRequest, DeleteReactionQuery, ReactionResponse};
use crate::http::context::CurrentUser;
use crate::http::error::HTTPError;
use crate::models::{channel, channel_user};
use crate::routes::message::mapper;
use axum::{
Json,
@@ -13,6 +14,20 @@ use axum::{
http::StatusCode,
};
use uuid::Uuid;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
pub(crate) async fn can_access(state: &AppState, channel_id: Uuid, user_id: Uuid) -> Result<bool, HTTPError> {
let Some(channel) = channel::Entity::find_by_id(channel_id).one(&state.db).await? else {
return Ok(false);
};
if channel.channel_type != channel::ChannelType::DM {
return Ok(true);
}
Ok(channel_user::Entity::find()
.filter(channel_user::Column::ChannelId.eq(channel_id))
.filter(channel_user::Column::UserId.eq(user_id))
.one(&state.db).await?.is_some())
}
/// Liste une fenêtre paginée de messages
#[utoipa::path(
@@ -29,6 +44,7 @@ use uuid::Uuid;
tag = "Messages"
)]
pub async fn get_all(
user: CurrentUser,
State(state): State<AppState>,
Query(filters): Query<MessageQueryParams>,
) -> Result<Json<MessagePageResponse>, HTTPError> {
@@ -39,6 +55,11 @@ pub async fn get_all(
}
let params = mapper::query_params_to_message_filter(filters);
if let Some(channel_id) = params.channel_id {
if !can_access(&state, channel_id, user.id).await? {
return Err(HTTPError::Forbidden);
}
}
let page = state.repositories.message.filter(params).await?;
let message_ids: Vec<_> = page.messages.iter().map(|message| message.id).collect();
let mut reactions = state
@@ -80,6 +101,7 @@ pub async fn get_all(
tag = "Messages"
)]
pub async fn get_by_id(
user: CurrentUser,
State(state): State<AppState>,
Path(id): Path<Uuid>,
) -> Result<Json<MessageResponse>, HTTPError> {
@@ -89,6 +111,9 @@ pub async fn get_by_id(
.get_by_id(id)
.await?
.ok_or(HTTPError::NotFound)?;
if !can_access(&state, message.channel_id, user.id).await? {
return Err(HTTPError::Forbidden);
}
let reactions = state
.services
@@ -130,6 +155,9 @@ pub async fn create(
.get_by_id(payload.channel_id)
.await?
.ok_or(HTTPError::BadRequest("Channel not found".to_string()))?;
if !can_access(&state, channel.id, user.id).await? {
return Err(HTTPError::Forbidden);
}
// Optionnel: vérifier reply_to_id
if let Some(reply_id) = payload.reply_to_id {
@@ -233,6 +261,8 @@ pub async fn add_reaction(
Path(message_id): Path<Uuid>,
Json(payload): Json<CreateReactionRequest>,
) -> Result<(StatusCode, Json<ReactionResponse>), HTTPError> {
let message = state.repositories.message.get_by_id(message_id).await?.ok_or(HTTPError::NotFound)?;
if !can_access(&state, message.channel_id, user.id).await? { return Err(HTTPError::Forbidden); }
let (reaction, created) = state
.services
.message_reaction
@@ -270,6 +300,8 @@ pub async fn remove_reaction(
Path((message_id, emoji_id)): Path<(Uuid, Uuid)>,
Query(query): Query<DeleteReactionQuery>,
) -> Result<StatusCode, HTTPError> {
let message = state.repositories.message.get_by_id(message_id).await?.ok_or(HTTPError::NotFound)?;
if !can_access(&state, message.channel_id, user.id).await? { return Err(HTTPError::Forbidden); }
state
.services
.message_reaction
+2
View File
@@ -8,6 +8,7 @@ pub mod attachment;
pub mod auth;
pub mod category;
pub mod channel;
pub mod conversation;
pub mod core;
pub mod emoji;
pub mod gateway;
@@ -23,6 +24,7 @@ pub fn router() -> OxRouter {
.merge(server::routes::router())
.merge(category::routes::router())
.merge(channel::routes::router())
.merge(conversation::routes::router())
.merge(role::routes::router())
.merge(message::routes::router())
.merge(user::routes::router())
+7
View File
@@ -31,6 +31,9 @@ use utoipa::{Modify, OpenApi};
channel::handlers::create,
channel::handlers::update,
channel::handlers::delete,
conversation::handlers::list,
conversation::handlers::create,
conversation::handlers::fork,
role::handlers::get_all,
role::handlers::get_by_id,
role::handlers::create,
@@ -69,6 +72,10 @@ use utoipa::{Modify, OpenApi};
crate::domain::dto::channel::UpdateChannelRequest,
crate::domain::dto::channel::ReadStateResponse,
crate::domain::dto::channel::SetReadStateRequest,
crate::domain::dto::conversation::ConversationParticipantResponse,
crate::domain::dto::conversation::ConversationResponse,
crate::domain::dto::conversation::CreateConversationRequest,
crate::domain::dto::conversation::ForkConversationRequest,
crate::domain::dto::role::RoleResponse,
crate::domain::dto::role::CreateRoleRequest,
crate::domain::dto::role::UpdateRoleRequest,