diff --git a/app/Http/Controllers/ChatController.php b/app/Http/Controllers/ChatController.php index 35bc736..813ff52 100644 --- a/app/Http/Controllers/ChatController.php +++ b/app/Http/Controllers/ChatController.php @@ -69,59 +69,90 @@ public function getMessages($chatId) } public function storeMessage(Request $request, $chatId) -{ - $request->validate([ - 'message' => 'required|string', - ]); + { + $request->validate([ + 'message' => 'required|string', + ]); - $chat = Chat::with('members')->find($chatId); + $chat = Chat::with('members')->find($chatId); - if (!$chat || !$chat->members->contains(auth()->id())) { - return response()->json(['error' => 'Chat not found or unauthorized.'], 404); - } + if (!$chat || !$chat->members->contains(auth()->id())) { + return response()->json(['error' => 'Chat not found or unauthorized.'], 404); + } - if ($chat->members->count() > 2) { - $blockedByAnyone = $chat->members->filter(function ($member) { - return $member->id !== auth()->id(); - })->contains(function ($member) { - $friendship = Friendship::where(function ($query) use ($member) { + if ($chat->members->count() > 2) { + $blockedByAnyone = $chat->members->filter(function ($member) { + return $member->id !== auth()->id(); + })->contains(function ($member) { + $friendship = Friendship::where(function ($query) use ($member) { + $query->where('user_id', auth()->id()) + ->where('friend_id', $member->id); + })->orWhere(function ($query) use ($member) { + $query->where('user_id', $member->id) + ->where('friend_id', auth()->id()); + })->first(); + + return $friendship && $friendship->isBlocked(); + }); + + if ($blockedByAnyone) { + return response()->json(['error' => 'You are blocked by one of the members of this group.']); + } + } else { + $otherMember = $chat->members->firstWhere('id', '!=', auth()->id()); + + $friendship = Friendship::where(function ($query) use ($otherMember) { $query->where('user_id', auth()->id()) - ->where('friend_id', $member->id); - })->orWhere(function ($query) use ($member) { - $query->where('user_id', $member->id) - ->where('friend_id', auth()->id()); + ->where('friend_id', $otherMember->id); + })->orWhere(function ($query) use ($otherMember) { + $query->where('user_id', $otherMember->id) + ->where('friend_id', auth()->id()); })->first(); - return $friendship && $friendship->isBlocked(); - }); - - if ($blockedByAnyone) { - return response()->json(['error' => 'You are blocked by one of the members of this group.']); + if ($friendship && $friendship->isBlocked()) { + return response()->json(['error' => 'You are blocked by this user or you blocked this user.']); + } } - } else { - $otherMember = $chat->members->firstWhere('id', '!=', auth()->id()); - $friendship = Friendship::where(function ($query) use ($otherMember) { - $query->where('user_id', auth()->id()) - ->where('friend_id', $otherMember->id); - })->orWhere(function ($query) use ($otherMember) { - $query->where('user_id', $otherMember->id) - ->where('friend_id', auth()->id()); - })->first(); - - if ($friendship && $friendship->isBlocked()) { - return response()->json(['error' => 'You are blocked by this user or you blocked this user.']); - } + $message = new Message(); + $message->user_id = auth()->id(); + $message->chat_id = $chatId; + $message->message = $request->message; + $message->save(); + + return response()->json(['message' => $message]); } - $message = new Message(); - $message->user_id = auth()->id(); - $message->chat_id = $chatId; - $message->message = $request->message; - $message->save(); + public function storeCapsule(Request $request, $chatId) + { + // Validation + $request->validate([ + 'file' => 'required|file|mimes:jpeg,png,jpg,gif,mp3,mp4|max:1024', + 'message' => 'required|string', + ]); + + // Vérification de la présence du fichier + if ($request->hasFile('file') && $request->file('file')->isValid()) { + $media = $request->file('file'); + $mediaName = time() . '_' . $media->getClientOriginalName(); - return response()->json(['message' => $message]); -} + // Déplacer le fichier vers le répertoire public/source/media + $media->move(public_path('source/media'), $mediaName); + + // Créer un nouveau message et l'enregistrer dans la base de données + $message = new Message(); + $message->user_id = auth()->id(); + $message->chat_id = $chatId; + $message->message = $request->message; + $message->media_url = $mediaName; + + $message->save(); + + return response()->json(['message' => $message]); + } + + return response()->json(['error' => 'Le fichier n\'a pas été envoyé ou est invalide.'], 400); + } public function storeChat(Request $request) { diff --git a/resources/views/components/messaging/chatbar.blade.php b/resources/views/components/messaging/chatbar.blade.php index c77ed11..c934e1a 100644 --- a/resources/views/components/messaging/chatbar.blade.php +++ b/resources/views/components/messaging/chatbar.blade.php @@ -1,13 +1,115 @@
- - + +
+ @csrf + +

Créer une capsule

+ +
+
+ + +
+
+ + +
+ + +
+ +
+ + Annuler + + + Envoyer la capsule + +
+
+
+ + \ No newline at end of file diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php index d7956de..4f908c1 100644 --- a/resources/views/dashboard.blade.php +++ b/resources/views/dashboard.blade.php @@ -31,6 +31,118 @@ function loadChat(chatId, discussionName, discussionPicture, newOpening = true) if (currentChatId !== chatId) { allMessages = []; messagesContainer.innerHTML = ''; + // Vérifier si la discussion est déjà chargée + if (currentChatId !== chatId) { + // Réinitialiser la liste de tout les messages + allMessages = []; + document.getElementById('messages').innerHTML = ''; + + // Récupérer le champ contenant l'id pour la création de capsule via son id et mettre à jour l'action + const hiddenInput = document.getElementById('discussion-id'); + if (hiddenInput) hiddenInput.value = chatId; + } + + // Mettre à jour l'ID de la discussion actuelle + currentChatId = chatId; + + // Mettre à jour le titre du header si nécessaire + if (newOpening) { + const headerTitle = document.querySelector('.headerTitle'); + if (headerTitle) headerTitle.textContent = discussionName; + + const headerImage = document.querySelector('.headerImage'); + if(headerImage) headerImage.src = discussionPicture; + } + + fetch(`/chat/${chatId}/messages`, { + method: 'GET', + headers: { + 'X-Requested-With': 'XMLHttpRequest', + 'X-CSRF-TOKEN': '{{ csrf_token() }}' + } + }) + .then(response => response.json()) + .then(data => { + let newMessages = []; + // Si la liste de tout les messages correspond à la liste actuelle + if (JSON.stringify(allMessages) === JSON.stringify(data.messages)) { + return; + } else if (allMessages.length === 0) { + // Si la liste de tout les messages est vide + newMessages = data.messages; + } else { + // Récupérer la liste des messages qui ne sont pas déjà affichés + newMessages = data.messages.filter(message => !allMessages.some(m => m.id === message.id)); + } + + // Récupérer la position dans le scroll et vérifier si on est tout en bas + // Utile pour savoir si on doit défiler jusqu'en bas après l'ajout des nouveaux messages ou si l'utilisateur est entrain de consulter des anciens messages + const isAtBottom = messagesContainer.scrollHeight - messagesContainer.scrollTop === messagesContainer.clientHeight; + + // Parcourir les messages et les ajouter + newMessages.forEach(message => { + const isCurrentUser = message.user_id === {{ auth()->id() }}; + const messageElement = document.createElement('div'); + messageElement.className = `flex ${isCurrentUser ? 'justify-end' : 'justify-start'} mb-2`; + messageElement.innerHTML = ` + +

+ + ${message.user.name} + ${message.message} +

`; + + // Gestion des médias + if (message.media_url) { + let mediaElement = + ` +
+ ${message.user.name}`; + if (message.media_url.endsWith('.mp4')) { + mediaElement += ` + `; + } else if (message.media_url.endsWith('.mp3')) { + mediaElement += ` + `; + } else { + mediaElement += ` + `; + } + + mediaElement += ` +

+ ${message.message} +

+
`; + messageElement.innerHTML = mediaElement; + } + messagesContainer.appendChild(messageElement); + }); + + // Mettre à jour la liste de tout les messages + allMessages = data.messages; + + // Attendre que tout les médias soient chargés avant de faire défiler + const mediaElements = document.querySelectorAll('img, video'); + mediaElements.forEach(mediaElement => { + mediaElement.addEventListener('load', () => { + if (isAtBottom) { + scrollToBottom() + }; + }); + }); + + // Faire défiler jusqu'en bas (utile si il y a pas de médias) + if (isAtBottom) { + scrollToBottom() + }; + }) + .catch(error => console.error('Erreur:', error)) } currentChatId = chatId; @@ -172,4 +284,4 @@ function scrollToBottom() { } startAutoRefresh(); - \ No newline at end of file + diff --git a/routes/web.php b/routes/web.php index 3529a1f..4e44660 100644 --- a/routes/web.php +++ b/routes/web.php @@ -22,6 +22,7 @@ Route::get('/dashboard', [ChatController::class, 'index'])->name('dashboard'); Route::get('/chat/{discussion}/messages', [ChatController::class, 'getMessages']); Route::post('/chat/{discussion}/messages', [ChatController::class, 'storeMessage']); + Route::post('/chat/{discussion}/capsule', [ChatController::class, 'storeCapsule']); Route::post('/chats', [ChatController::class, 'storeChat'])->name('chats.store'); Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit'); Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');