init
This commit is contained in:
@@ -1,9 +1,82 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { storeToRefs } from 'pinia'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useConversationStore } from '@/stores/conversation'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const conversationStore = useConversationStore()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const authStore = useAuthStore()
|
||||||
|
const { conversations } = storeToRefs(conversationStore)
|
||||||
|
const showCreateDialog = ref(false)
|
||||||
|
const selectedUserIds = ref<string[]>([])
|
||||||
|
const submitting = ref(false)
|
||||||
|
const users = computed(() => userStore.users.filter(user => user.id !== authStore.currentUser?.id))
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await Promise.all([userStore.fetchUsers(), conversationStore.fetchConversations()])
|
||||||
|
})
|
||||||
|
|
||||||
|
const createConversation = async () => {
|
||||||
|
if (!selectedUserIds.value.length) return
|
||||||
|
submitting.value = true
|
||||||
|
try {
|
||||||
|
const conversation = await conversationStore.createConversation(selectedUserIds.value)
|
||||||
|
showCreateDialog.value = false
|
||||||
|
selectedUserIds.value = []
|
||||||
|
await router.push(`/conversation/${conversation.id}`)
|
||||||
|
} finally { submitting.value = false }
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<v-navigation-drawer permanent width="280" color="grey-lighten-5">
|
||||||
Hello
|
<div class="d-flex align-center px-4 py-4">
|
||||||
|
<span class="text-h6 font-weight-medium">Messages</span>
|
||||||
|
<v-spacer />
|
||||||
|
<v-btn icon="mdi-square-edit-outline" size="small" variant="text" aria-label="Nouvelle discussion" @click="showCreateDialog = true" />
|
||||||
</div>
|
</div>
|
||||||
|
<v-divider />
|
||||||
|
<v-list density="comfortable" nav>
|
||||||
|
<v-list-item
|
||||||
|
v-for="conversation in conversations"
|
||||||
|
:key="conversation.id"
|
||||||
|
:to="`/conversation/${conversation.id}`"
|
||||||
|
:title="conversation.title"
|
||||||
|
:subtitle="conversation.last_message ?? 'Aucun message'"
|
||||||
|
:class="{ 'font-weight-bold': conversation.unread_count > 0 }"
|
||||||
|
rounded="lg"
|
||||||
|
>
|
||||||
|
<template #prepend><v-avatar color="primary" size="34"><v-icon icon="mdi-account-multiple-outline" /></v-avatar></template>
|
||||||
|
<template #append><v-chip v-if="conversation.unread_count > 0" color="primary" size="small">{{ conversation.unread_count }}</v-chip></template>
|
||||||
|
</v-list-item>
|
||||||
|
<v-list-item v-if="!conversationStore.loading && !conversations.length" class="text-medium-emphasis" title="Aucune discussion" subtitle="Commencez une conversation" />
|
||||||
|
</v-list>
|
||||||
|
</v-navigation-drawer>
|
||||||
|
|
||||||
|
<v-main class="conversation-main">
|
||||||
|
<router-view />
|
||||||
|
<div v-if="!$route.params.channelId" class="empty-state">
|
||||||
|
<v-icon icon="mdi-message-text-outline" size="64" color="grey" />
|
||||||
|
<div class="text-h6 mt-4">Vos discussions</div>
|
||||||
|
<div class="text-body-2 text-medium-emphasis">Sélectionnez une discussion ou commencez-en une nouvelle.</div>
|
||||||
|
<v-btn class="mt-4" color="primary" prepend-icon="mdi-plus" @click="showCreateDialog = true">Nouvelle discussion</v-btn>
|
||||||
|
</div>
|
||||||
|
</v-main>
|
||||||
|
|
||||||
|
<v-dialog v-model="showCreateDialog" width="420">
|
||||||
|
<v-card>
|
||||||
|
<v-card-title>Nouvelle discussion</v-card-title>
|
||||||
|
<v-card-text><v-select v-model="selectedUserIds" :items="users" item-title="username" item-value="id" label="Participants" multiple chips closable-chips /></v-card-text>
|
||||||
|
<v-card-actions><v-spacer /><v-btn @click="showCreateDialog = false">Annuler</v-btn><v-btn color="primary" :loading="submitting" :disabled="!selectedUserIds.length" @click="createConversation">Créer</v-btn></v-card-actions>
|
||||||
|
</v-card>
|
||||||
|
</v-dialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.conversation-main { height: 100%; position: relative; }
|
||||||
|
.empty-state { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; }
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -10,9 +10,11 @@ import {onReloadAll} from '@/plugins/events.ts'
|
|||||||
import EmojiPicker from '@/components/EmojiPicker.vue'
|
import EmojiPicker from '@/components/EmojiPicker.vue'
|
||||||
import {useEmojiStore, type Emoji} from '@/stores/emoji.ts'
|
import {useEmojiStore, type Emoji} from '@/stores/emoji.ts'
|
||||||
import {useAuthStore} from '@/stores/auth.ts'
|
import {useAuthStore} from '@/stores/auth.ts'
|
||||||
|
import {useConversationStore} from '@/stores/conversation'
|
||||||
|
import {useRoute, useRouter} from 'vue-router'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
serverId: string
|
serverId?: string
|
||||||
channelId: string
|
channelId: string
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
@@ -22,6 +24,9 @@ const serverStore = useServerStore();
|
|||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
const emojiStore = useEmojiStore();
|
const emojiStore = useEmojiStore();
|
||||||
const authStore = useAuthStore();
|
const authStore = useAuthStore();
|
||||||
|
const conversationStore = useConversationStore()
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
const {renderMarkdown} = useMarkdown()
|
const {renderMarkdown} = useMarkdown()
|
||||||
|
|
||||||
const messageContainer = ref<HTMLElement | null>(null);
|
const messageContainer = ref<HTMLElement | null>(null);
|
||||||
@@ -35,6 +40,16 @@ const paginationLockScrollTop = ref(0);
|
|||||||
const lastScrollTop = ref(0);
|
const lastScrollTop = ref(0);
|
||||||
const markedMessageByChannel = new Map<string, string>();
|
const markedMessageByChannel = new Map<string, string>();
|
||||||
const reactionPending = ref(new Set<string>());
|
const reactionPending = ref(new Set<string>());
|
||||||
|
const isConversation = computed(() => route.name === 'home-conversation')
|
||||||
|
const addParticipantDialog = ref(false)
|
||||||
|
const selectedParticipantIds = ref<string[]>([])
|
||||||
|
const addingParticipants = ref(false)
|
||||||
|
const currentConversation = computed(() => conversationStore.conversations.find(item => item.id === channelId.value))
|
||||||
|
const availableParticipants = computed(() => userStore.users.filter(user =>
|
||||||
|
user.id !== authStore.currentUser?.id &&
|
||||||
|
!currentConversation.value?.participants.some(participant => participant.id === user.id) &&
|
||||||
|
!selectedParticipantIds.value.includes(user.id),
|
||||||
|
))
|
||||||
|
|
||||||
const markCurrentChannelRead = async (targetChannelId: string) => {
|
const markCurrentChannelRead = async (targetChannelId: string) => {
|
||||||
if (messageStore.activeChannelId !== targetChannelId || !newestId.value) return;
|
if (messageStore.activeChannelId !== targetChannelId || !newestId.value) return;
|
||||||
@@ -47,12 +62,24 @@ const markCurrentChannelRead = async (targetChannelId: string) => {
|
|||||||
if (messageStore.activeChannelId !== targetChannelId) return;
|
if (messageStore.activeChannelId !== targetChannelId) return;
|
||||||
|
|
||||||
markedMessageByChannel.set(targetChannelId, messageId);
|
markedMessageByChannel.set(targetChannelId, messageId);
|
||||||
serverStore.applyChannelReadState(props.serverId, targetChannelId, readState.unread_count);
|
if (isConversation.value) conversationStore.applyReadState(targetChannelId, readState.unread_count)
|
||||||
|
else if (props.serverId) serverStore.applyChannelReadState(props.serverId, targetChannelId, readState.unread_count);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erreur lors de la mise à jour de la lecture:', error);
|
console.error('Erreur lors de la mise à jour de la lecture:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const forkConversation = async () => {
|
||||||
|
if (!selectedParticipantIds.value.length) return
|
||||||
|
addingParticipants.value = true
|
||||||
|
try {
|
||||||
|
const conversation = await conversationStore.forkConversation(channelId.value, selectedParticipantIds.value)
|
||||||
|
addParticipantDialog.value = false
|
||||||
|
selectedParticipantIds.value = []
|
||||||
|
await router.push(`/conversation/${conversation.id}`)
|
||||||
|
} finally { addingParticipants.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
const showRecentMessagesButton = computed(() =>
|
const showRecentMessagesButton = computed(() =>
|
||||||
!loading.value && (hasMoreAfter.value || !isAtBottom.value),
|
!loading.value && (hasMoreAfter.value || !isAtBottom.value),
|
||||||
);
|
);
|
||||||
@@ -247,7 +274,7 @@ watch(isAtBottom, async (atBottom) => {
|
|||||||
|
|
||||||
watch(channelId, async (newChannelId) => {
|
watch(channelId, async (newChannelId) => {
|
||||||
if (newChannelId) {
|
if (newChannelId) {
|
||||||
await emojiStore.fetchEmojis(props.serverId);
|
if (props.serverId) await emojiStore.fetchEmojis(props.serverId);
|
||||||
await messageStore.fetchMessages(newChannelId);
|
await messageStore.fetchMessages(newChannelId);
|
||||||
await scrollToBottom();
|
await scrollToBottom();
|
||||||
await markCurrentChannelRead(newChannelId);
|
await markCurrentChannelRead(newChannelId);
|
||||||
@@ -261,6 +288,12 @@ watch(() => props.serverId, (newServerId) => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<v-container class="pa-0 fill-height d-flex flex-column channel-layout" fluid>
|
<v-container class="pa-0 fill-height d-flex flex-column channel-layout" fluid>
|
||||||
|
<v-sheet v-if="isConversation" class="px-4 py-2 d-flex align-center" border>
|
||||||
|
<v-icon class="mr-3" icon="mdi-account-multiple-outline" />
|
||||||
|
<span class="font-weight-medium">{{ currentConversation?.title ?? 'Discussion' }}</span>
|
||||||
|
<v-spacer />
|
||||||
|
<v-btn prepend-icon="mdi-account-plus" variant="text" @click="addParticipantDialog = true">Ajouter</v-btn>
|
||||||
|
</v-sheet>
|
||||||
<div
|
<div
|
||||||
ref="messageContainer"
|
ref="messageContainer"
|
||||||
class="flex-grow-1 overflow-y-auto w-100 message-container"
|
class="flex-grow-1 overflow-y-auto w-100 message-container"
|
||||||
@@ -372,6 +405,16 @@ watch(() => props.serverId, (newServerId) => {
|
|||||||
</v-textarea>
|
</v-textarea>
|
||||||
</v-sheet>
|
</v-sheet>
|
||||||
</v-container>
|
</v-container>
|
||||||
|
|
||||||
|
<v-dialog v-model="addParticipantDialog" width="420">
|
||||||
|
<v-card>
|
||||||
|
<v-card-title>Nouvelle discussion de groupe</v-card-title>
|
||||||
|
<v-card-text>
|
||||||
|
<v-select v-model="selectedParticipantIds" :items="availableParticipants" item-title="username" item-value="id" label="Ajouter des participants" multiple chips closable-chips />
|
||||||
|
</v-card-text>
|
||||||
|
<v-card-actions><v-spacer /><v-btn @click="addParticipantDialog = false">Annuler</v-btn><v-btn color="primary" :loading="addingParticipants" :disabled="!selectedParticipantIds.length" @click="forkConversation">Créer</v-btn></v-card-actions>
|
||||||
|
</v-card>
|
||||||
|
</v-dialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -230,6 +230,7 @@ function onChannelContextMenu(event: MouseEvent, channel: any) {
|
|||||||
</v-list-item>
|
</v-list-item>
|
||||||
</template>
|
</template>
|
||||||
</v-list>
|
</v-list>
|
||||||
|
|
||||||
</v-navigation-drawer>
|
</v-navigation-drawer>
|
||||||
|
|
||||||
<CreateChannelDialog
|
<CreateChannelDialog
|
||||||
|
|||||||
@@ -45,6 +45,14 @@ const router = createRouter({
|
|||||||
path: '',
|
path: '',
|
||||||
name: 'home',
|
name: 'home',
|
||||||
component: () => import('@/pages/index.vue'),
|
component: () => import('@/pages/index.vue'),
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: 'conversation/:channelId(default|[0-9a-fA-F-]{36})',
|
||||||
|
name: 'home-conversation',
|
||||||
|
component: () => import('@/pages/server/channel/index.vue'),
|
||||||
|
props: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'server/:serverId(default|[0-9a-fA-F-]{36})',
|
path: 'server/:serverId(default|[0-9a-fA-F-]{36})',
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { useApi } from '@/composables/useApi'
|
||||||
|
|
||||||
|
export interface ConversationParticipant { id: string; username: string }
|
||||||
|
export interface Conversation {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
participants: ConversationParticipant[]
|
||||||
|
last_message: string | null
|
||||||
|
unread_count: number
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useConversationStore = defineStore('conversation', {
|
||||||
|
state: () => ({ conversations: [] as Conversation[], loading: false }),
|
||||||
|
actions: {
|
||||||
|
async fetchConversations() {
|
||||||
|
this.loading = true
|
||||||
|
try {
|
||||||
|
const response = await useApi().get('/conversations')
|
||||||
|
if (!response.ok) throw new Error(`Conversation loading failed (${response.status})`)
|
||||||
|
this.conversations = await response.json()
|
||||||
|
} finally { this.loading = false }
|
||||||
|
},
|
||||||
|
async createConversation(userIds: string[]) {
|
||||||
|
const response = await useApi().post('/conversations', { user_ids: userIds })
|
||||||
|
if (!response.ok) throw new Error(`Conversation creation failed (${response.status})`)
|
||||||
|
const conversation = await response.json() as Conversation
|
||||||
|
const index = this.conversations.findIndex(item => item.id === conversation.id)
|
||||||
|
if (index >= 0) this.conversations[index] = conversation
|
||||||
|
else this.conversations.unshift(conversation)
|
||||||
|
return conversation
|
||||||
|
},
|
||||||
|
async forkConversation(id: string, userIds: string[]) {
|
||||||
|
const response = await useApi().post(`/conversations/${id}/fork`, { user_ids: userIds })
|
||||||
|
if (!response.ok) throw new Error(`Conversation fork failed (${response.status})`)
|
||||||
|
const conversation = await response.json() as Conversation
|
||||||
|
this.conversations.unshift(conversation)
|
||||||
|
return conversation
|
||||||
|
},
|
||||||
|
applyReadState(id: string, unreadCount: number) {
|
||||||
|
const conversation = this.conversations.find(item => item.id === id)
|
||||||
|
if (conversation) conversation.unread_count = unreadCount
|
||||||
|
},
|
||||||
|
reset() { this.conversations = []; this.loading = false }
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
pub struct ConversationParticipantResponse {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
pub struct ConversationResponse {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub title: String,
|
||||||
|
pub participants: Vec<ConversationParticipantResponse>,
|
||||||
|
pub last_message: Option<String>,
|
||||||
|
pub unread_count: u64,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub updated_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
pub struct CreateConversationRequest {
|
||||||
|
pub user_ids: Vec<Uuid>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, ToSchema)]
|
||||||
|
pub struct ForkConversationRequest {
|
||||||
|
pub user_ids: Vec<Uuid>,
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ pub mod attachment;
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod category;
|
pub mod category;
|
||||||
pub mod channel;
|
pub mod channel;
|
||||||
|
pub mod conversation;
|
||||||
pub mod core;
|
pub mod core;
|
||||||
pub mod emoji;
|
pub mod emoji;
|
||||||
pub mod message;
|
pub mod message;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use crate::domain::dto::channel::{
|
|||||||
};
|
};
|
||||||
use crate::http::context::{CurrentUser, Superuser};
|
use crate::http::context::{CurrentUser, Superuser};
|
||||||
use crate::http::error::HTTPError;
|
use crate::http::error::HTTPError;
|
||||||
|
use crate::models::{channel, channel_user};
|
||||||
use crate::routes::channel::mapper;
|
use crate::routes::channel::mapper;
|
||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
Json,
|
||||||
@@ -13,6 +14,15 @@ use axum::{
|
|||||||
http::StatusCode,
|
http::StatusCode,
|
||||||
};
|
};
|
||||||
use uuid::Uuid;
|
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
|
/// Liste tous les channels
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
@@ -54,12 +64,7 @@ pub async fn get_read_state(
|
|||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Path(channel_id): Path<Uuid>,
|
Path(channel_id): Path<Uuid>,
|
||||||
) -> Result<Json<ReadStateResponse>, HTTPError> {
|
) -> Result<Json<ReadStateResponse>, HTTPError> {
|
||||||
state
|
require_channel_member(&state, channel_id, user.id).await?;
|
||||||
.repositories
|
|
||||||
.channel
|
|
||||||
.get_by_id(channel_id)
|
|
||||||
.await?
|
|
||||||
.ok_or(HTTPError::NotFound)?;
|
|
||||||
let read_state = state
|
let read_state = state
|
||||||
.repositories
|
.repositories
|
||||||
.read_state
|
.read_state
|
||||||
@@ -99,12 +104,7 @@ pub async fn set_read_state(
|
|||||||
Path(channel_id): Path<Uuid>,
|
Path(channel_id): Path<Uuid>,
|
||||||
Json(payload): Json<SetReadStateRequest>,
|
Json(payload): Json<SetReadStateRequest>,
|
||||||
) -> Result<Json<ReadStateResponse>, HTTPError> {
|
) -> Result<Json<ReadStateResponse>, HTTPError> {
|
||||||
state
|
require_channel_member(&state, channel_id, user.id).await?;
|
||||||
.repositories
|
|
||||||
.channel
|
|
||||||
.get_by_id(channel_id)
|
|
||||||
.await?
|
|
||||||
.ok_or(HTTPError::NotFound)?;
|
|
||||||
|
|
||||||
if let Some(message_id) = payload.last_read_message_id {
|
if let Some(message_id) = payload.last_read_message_id {
|
||||||
let message = state
|
let message = state
|
||||||
|
|||||||
@@ -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?))
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod handlers;
|
||||||
|
pub mod routes;
|
||||||
@@ -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))
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ use crate::domain::dto::message::{
|
|||||||
use crate::domain::dto::reaction::{CreateReactionRequest, DeleteReactionQuery, ReactionResponse};
|
use crate::domain::dto::reaction::{CreateReactionRequest, DeleteReactionQuery, ReactionResponse};
|
||||||
use crate::http::context::CurrentUser;
|
use crate::http::context::CurrentUser;
|
||||||
use crate::http::error::HTTPError;
|
use crate::http::error::HTTPError;
|
||||||
|
use crate::models::{channel, channel_user};
|
||||||
use crate::routes::message::mapper;
|
use crate::routes::message::mapper;
|
||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
Json,
|
||||||
@@ -13,6 +14,20 @@ use axum::{
|
|||||||
http::StatusCode,
|
http::StatusCode,
|
||||||
};
|
};
|
||||||
use uuid::Uuid;
|
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
|
/// Liste une fenêtre paginée de messages
|
||||||
#[utoipa::path(
|
#[utoipa::path(
|
||||||
@@ -29,6 +44,7 @@ use uuid::Uuid;
|
|||||||
tag = "Messages"
|
tag = "Messages"
|
||||||
)]
|
)]
|
||||||
pub async fn get_all(
|
pub async fn get_all(
|
||||||
|
user: CurrentUser,
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Query(filters): Query<MessageQueryParams>,
|
Query(filters): Query<MessageQueryParams>,
|
||||||
) -> Result<Json<MessagePageResponse>, HTTPError> {
|
) -> Result<Json<MessagePageResponse>, HTTPError> {
|
||||||
@@ -39,6 +55,11 @@ pub async fn get_all(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let params = mapper::query_params_to_message_filter(filters);
|
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 page = state.repositories.message.filter(params).await?;
|
||||||
let message_ids: Vec<_> = page.messages.iter().map(|message| message.id).collect();
|
let message_ids: Vec<_> = page.messages.iter().map(|message| message.id).collect();
|
||||||
let mut reactions = state
|
let mut reactions = state
|
||||||
@@ -80,6 +101,7 @@ pub async fn get_all(
|
|||||||
tag = "Messages"
|
tag = "Messages"
|
||||||
)]
|
)]
|
||||||
pub async fn get_by_id(
|
pub async fn get_by_id(
|
||||||
|
user: CurrentUser,
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Path(id): Path<Uuid>,
|
Path(id): Path<Uuid>,
|
||||||
) -> Result<Json<MessageResponse>, HTTPError> {
|
) -> Result<Json<MessageResponse>, HTTPError> {
|
||||||
@@ -89,6 +111,9 @@ pub async fn get_by_id(
|
|||||||
.get_by_id(id)
|
.get_by_id(id)
|
||||||
.await?
|
.await?
|
||||||
.ok_or(HTTPError::NotFound)?;
|
.ok_or(HTTPError::NotFound)?;
|
||||||
|
if !can_access(&state, message.channel_id, user.id).await? {
|
||||||
|
return Err(HTTPError::Forbidden);
|
||||||
|
}
|
||||||
|
|
||||||
let reactions = state
|
let reactions = state
|
||||||
.services
|
.services
|
||||||
@@ -130,6 +155,9 @@ pub async fn create(
|
|||||||
.get_by_id(payload.channel_id)
|
.get_by_id(payload.channel_id)
|
||||||
.await?
|
.await?
|
||||||
.ok_or(HTTPError::BadRequest("Channel not found".to_string()))?;
|
.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
|
// Optionnel: vérifier reply_to_id
|
||||||
if let Some(reply_id) = payload.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>,
|
Path(message_id): Path<Uuid>,
|
||||||
Json(payload): Json<CreateReactionRequest>,
|
Json(payload): Json<CreateReactionRequest>,
|
||||||
) -> Result<(StatusCode, Json<ReactionResponse>), HTTPError> {
|
) -> 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
|
let (reaction, created) = state
|
||||||
.services
|
.services
|
||||||
.message_reaction
|
.message_reaction
|
||||||
@@ -270,6 +300,8 @@ pub async fn remove_reaction(
|
|||||||
Path((message_id, emoji_id)): Path<(Uuid, Uuid)>,
|
Path((message_id, emoji_id)): Path<(Uuid, Uuid)>,
|
||||||
Query(query): Query<DeleteReactionQuery>,
|
Query(query): Query<DeleteReactionQuery>,
|
||||||
) -> Result<StatusCode, HTTPError> {
|
) -> 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
|
state
|
||||||
.services
|
.services
|
||||||
.message_reaction
|
.message_reaction
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ pub mod attachment;
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod category;
|
pub mod category;
|
||||||
pub mod channel;
|
pub mod channel;
|
||||||
|
pub mod conversation;
|
||||||
pub mod core;
|
pub mod core;
|
||||||
pub mod emoji;
|
pub mod emoji;
|
||||||
pub mod gateway;
|
pub mod gateway;
|
||||||
@@ -23,6 +24,7 @@ pub fn router() -> OxRouter {
|
|||||||
.merge(server::routes::router())
|
.merge(server::routes::router())
|
||||||
.merge(category::routes::router())
|
.merge(category::routes::router())
|
||||||
.merge(channel::routes::router())
|
.merge(channel::routes::router())
|
||||||
|
.merge(conversation::routes::router())
|
||||||
.merge(role::routes::router())
|
.merge(role::routes::router())
|
||||||
.merge(message::routes::router())
|
.merge(message::routes::router())
|
||||||
.merge(user::routes::router())
|
.merge(user::routes::router())
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ use utoipa::{Modify, OpenApi};
|
|||||||
channel::handlers::create,
|
channel::handlers::create,
|
||||||
channel::handlers::update,
|
channel::handlers::update,
|
||||||
channel::handlers::delete,
|
channel::handlers::delete,
|
||||||
|
conversation::handlers::list,
|
||||||
|
conversation::handlers::create,
|
||||||
|
conversation::handlers::fork,
|
||||||
role::handlers::get_all,
|
role::handlers::get_all,
|
||||||
role::handlers::get_by_id,
|
role::handlers::get_by_id,
|
||||||
role::handlers::create,
|
role::handlers::create,
|
||||||
@@ -69,6 +72,10 @@ use utoipa::{Modify, OpenApi};
|
|||||||
crate::domain::dto::channel::UpdateChannelRequest,
|
crate::domain::dto::channel::UpdateChannelRequest,
|
||||||
crate::domain::dto::channel::ReadStateResponse,
|
crate::domain::dto::channel::ReadStateResponse,
|
||||||
crate::domain::dto::channel::SetReadStateRequest,
|
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::RoleResponse,
|
||||||
crate::domain::dto::role::CreateRoleRequest,
|
crate::domain::dto::role::CreateRoleRequest,
|
||||||
crate::domain::dto::role::UpdateRoleRequest,
|
crate::domain::dto::role::UpdateRoleRequest,
|
||||||
|
|||||||
Reference in New Issue
Block a user