added chats with another users

This commit is contained in:
SlimusMinus
2026-06-22 01:08:47 +03:00
parent 194b7efb8a
commit 236d00f2f9
19 changed files with 433 additions and 177 deletions

View File

@@ -1,37 +1,45 @@
package com.krylov.refound.controller;
import com.krylov.refound.dto.ChatMessage;
import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.User;
import com.krylov.refound.repository.UserRepository;
import com.krylov.refound.service.MessageService;
import java.security.Principal;
import java.util.Optional;
import com.krylov.refound.dto.*;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/chats")
public class ChatController {
private final MessageService service;
private final SimpMessagingTemplate messagingTemplate;
private final UserRepository userRepository;
private final UserService userService;
private final ChatService chatService;
@MessageMapping("/chat")
public void send(@Payload ChatMessage message, Principal principal) {
// Создать чат с пользователем или получить существующий
@PostMapping("/with/{otherUserId}")
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
Long currentUserId = extractUserId(auth); // см. ниже как достать id
return chatService.getOrCreateChat(currentUserId, otherUserId, postId);
}
Optional<User> sender = userRepository.findByLogin(principal.getName());
Message saved = new Message();
if(sender.isPresent()){
saved = service.send(message.getReceiverId(), message.getContent());
}
// Список всех чатов текущего пользователя
@GetMapping
public List<ChatDto> getMyChats(Authentication auth) {
return chatService.getUserChats(extractUserId(auth));
}
// отправка получателю
messagingTemplate.convertAndSend("/topic/messages/" + message.getReceiverId(), saved);
// История сообщений конкретного чата
@GetMapping("/{chatId}/messages")
public List<MessageDto> getMessages(@PathVariable Long chatId) {
return chatService.getMessages(chatId);
}
private Long extractUserId(Authentication auth) {
// Подставь свою логику получения userId из JWT/Authentication
// Например если в токене login, а не id - подтяни через UserService
String login = auth.getName();
return userService.getUserIdByLogin(login);
}
}