Add photo attachments to chat messages

- message_attachments table (cascade with messages); files stored under
  chat/{chatId}/ in the images bucket
- POST /api/v1/chats/{chatId}/messages (multipart, up to 10 photos + text);
  message is broadcast over WebSocket as before
- photos are always re-encoded so EXIF (geotag, device) never reaches storage
- presigned links (6h) only in participant-checked responses, refresh via
  GET /api/v1/chats/{chatId}/attachments/{id}/url
- public /api/v1/files no longer serves or deletes chat/ keys
- chat deletion removes files; orphan cleanup keeps referenced attachments
- rate limit chat-photo: 60/hour

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-28 22:26:37 +03:00
parent 3eab2f30e0
commit 2f6aa0cd1e
21 changed files with 832 additions and 22 deletions

View File

@@ -6,12 +6,14 @@ import com.krylov.refound.dto.StartChatRequest;
import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService;
import java.util.List;
import java.util.Map;
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;
@@ -22,6 +24,7 @@ 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
@@ -65,6 +68,27 @@ public class ChatController {
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);
}
/** Свежая временная ссылка на вложение (выданная с сообщением живёт несколько часов). */
@GetMapping("/{chatId}/attachments/{attachmentId}/url")
public Map<String, String> getAttachmentUrl(@PathVariable Long chatId, @PathVariable Long attachmentId, Authentication auth) {
Long currentUserId = extractUserId(auth);
return Map.of("url", chatService.getAttachmentUrl(chatId, attachmentId, currentUserId));
}
@DeleteMapping("/{chatId}")
public void deleteChat(@PathVariable Long chatId, Authentication auth) {
Long currentUserId = extractUserId(auth);

View File

@@ -1,5 +1,8 @@
package com.krylov.refound.controller;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.service.ChatAttachmentService;
import com.krylov.refound.service.FileStorageService;
import java.time.Duration;
import java.util.Map;
@@ -7,6 +10,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@@ -40,8 +44,7 @@ public class FileStorageController {
@GetMapping("/{*objectName}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
// objectName придёт как "/avatars/cf80aebe-...jpg" — обрежь ведущий слэш
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String key = publicKey(objectName);
return fileStorageService.downloadFile(key);
}
@@ -53,7 +56,7 @@ public class FileStorageController {
*/
@GetMapping(value = "/{*objectName}", params = "presigned=true")
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String key = publicKey(objectName);
String url = fileStorageService.getCachedPresignedDownloadUrl(key);
return ResponseEntity.status(302)
.header(HttpHeaders.LOCATION, url)
@@ -68,7 +71,7 @@ public class FileStorageController {
*/
@GetMapping("/url/{*objectName}")
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String key = publicKey(objectName);
// SigV4 не подписывает ссылки дольше 7 дней: больший ttlHours ронял presigner с 500
Duration ttl = ttlHours > 0 ? Duration.ofHours(Math.min(ttlHours, MAX_PRESIGNED_TTL_HOURS)) : Duration.ofHours(24);
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
@@ -79,8 +82,25 @@ public class FileStorageController {
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
log.info("deleteFile {}", objectName);
// objectName может прийти как "/avatars/cf80aebe-...jpg" — обрежем ведущий слэш
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
String key = publicKey(objectName);
fileStorageService.deleteFileAsCurrentUser(key);
return ResponseEntity.noContent().build();
}
}
/**
* Ключ объекта из пути: objectName приходит как "/avatars/cf80aebe-...jpg",
* ведущий слэш обрезаем. Вложения чатов этот публичный контроллер не отдаёт и
* не удаляет — их ссылки получают только участники через /api/v1/chats.
* Отвечаем 404, а не 403, чтобы не подтверждать, что такой файл есть.
*/
static String publicKey(String objectName) {
String key = objectName.replaceFirst("^/+", "");
// Ключи — UUID (иногда с папкой), точек-сегментов и двойных слэшей в них нет.
// Такие пути отклоняем: хранилище может их нормализовать в chat/...
boolean suspicious = key.contains("..") || key.contains("//") || key.startsWith("./") || key.contains("/./");
if (suspicious || ChatAttachmentService.isChatKey(key)) {
throw new ApiException(ErrorCode.NOT_FOUND, "Файл не найден.", HttpStatus.NOT_FOUND);
}
return key;
}
}