Files
nahodka-back/src/main/java/com/krylov/refound/controller/ChatController.java
SlimusMinus 871b16a038 Add video attachments to chat messages
- browser uploads the source straight to MinIO via presigned PUT (type and
  exact size are signed, up to 100 MB); upload is confirmed once by its owner
- message is created with a PROCESSING video, transcoded in the background
  (chatVideoExecutor): H.264/AAC, short side up to 720px, faststart,
  metadata (incl. location) stripped, poster frame; up to 60 s
- the updated message is re-broadcast over WebSocket when READY or FAILED;
  stuck processing is failed after 30 min
- message_attachments: status, poster_key, duration_ms, processing_started_at
- chat deletion and orphan cleanup handle video posters; rate limit chat-video

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 23:00:11 +03:00

146 lines
7.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.krylov.refound.controller;
import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.dto.MessageAttachmentDto;
import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.dto.SendVideoRequest;
import com.krylov.refound.dto.StartChatRequest;
import com.krylov.refound.dto.VideoUploadRequest;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.ChatVideoUploadService;
import com.krylov.refound.service.UserService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/chats")
public class ChatController {
private final UserService userService;
private final ChatService chatService;
// Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
@GetMapping("/with/{otherUserId}")
public ResponseEntity<ChatDto> findChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("findChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return ResponseEntity.of(chatService.findChat(currentUserId, otherUserId, postId));
}
// Первое сообщение: чат создаётся (или находится) вместе с сообщением — пустых чатов не бывает
@PostMapping("/with/{otherUserId}/messages")
public ChatDto startChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId,
@RequestBody StartChatRequest request, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("startChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
}
// Список всех чатов текущего пользователя
@GetMapping
public List<ChatDto> getMyChats(Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("getMyChats for user {}", currentUserId);
return chatService.getUserChats(currentUserId);
}
// История сообщений конкретного чата, с пагинацией
@GetMapping("/{chatId}/messages")
public Page<MessageDto> getMessages(@PathVariable Long chatId, @PageableDefault(size = 30, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("getMessages for chatId {} page {} by user {}", chatId, pageable.getPageNumber(), currentUserId);
return chatService.getMessages(chatId, currentUserId, pageable);
}
/**
* Сообщение с фото (до 10) и необязательным текстом. Текстовые сообщения
* по-прежнему идут через WebSocket; это сообщение тоже разошлётся по
* /topic/chat/{chatId}, а отправителю вернётся в ответе.
*/
@PostMapping(value = "/{chatId}/messages", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public MessageDto sendMessageWithPhotos(@PathVariable Long chatId,
@RequestParam(value = "content", required = false) String content,
@RequestParam(value = "files", required = false) List<MultipartFile> files, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("sendMessageWithPhotos chatId {} by user {}, files {}", chatId, currentUserId, files == null ? 0 : files.size());
return chatService.sendMessageWithPhotos(currentUserId, chatId, content, files);
}
/**
* Свежие временные ссылки на вложение (выданные с сообщением живут несколько
* часов): url и, у видео, posterUrl.
*/
@GetMapping("/{chatId}/attachments/{attachmentId}/url")
public MessageAttachmentDto getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) {
Long currentUserId = extractUserId(auth);
return chatService.getAttachment(chatId, attachmentId, currentUserId);
}
/**
* Видео, шаг 1: ссылка для загрузки исходника прямо в MinIO (PUT с тем же
* Content-Type и размером, что указаны в запросе).
*/
@PostMapping("/{chatId}/videos/upload-url")
public ChatVideoUploadService.UploadTicket requestVideoUpload(@PathVariable Long chatId,
@RequestBody VideoUploadRequest request, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("requestVideoUpload chatId {} by user {}, {} bytes", chatId, currentUserId, request.sizeBytes());
return chatService.requestVideoUpload(currentUserId, chatId, request.contentType(), request.sizeBytes());
}
/**
* Видео, шаг 2: исходник загружен — создаётся сообщение с видео в обработке.
* Готовое видео придёт по /topic/chat/{chatId} тем же сообщением (тот же id).
*/
@PostMapping("/{chatId}/videos")
public MessageDto sendVideoMessage(@PathVariable Long chatId, @RequestBody SendVideoRequest request, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("sendVideoMessage chatId {} by user {}", chatId, currentUserId);
return chatService.sendVideoMessage(currentUserId, chatId, request.content(), request.sourceKey());
}
@DeleteMapping("/{chatId}")
public void deleteChat(@PathVariable Long chatId, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("user {} deleteChat {}", currentUserId, chatId);
chatService.deleteChat(chatId, currentUserId);
}
@PostMapping("/{chatId}/read")
public void markAsRead(@PathVariable Long chatId, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("markAsRead chatId {} by user {}", chatId, currentUserId);
chatService.markAsRead(chatId, currentUserId);
}
private Long extractUserId(Authentication authentication) {
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
return null;
}
String login = authentication.getName();
log.info("extractUserId by login {}", login);
return userService.getUserIdByLogin(login);
}
}