- 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>
107 lines
5.5 KiB
Java
107 lines
5.5 KiB
Java
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;
|
||
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;
|
||
import org.springframework.web.bind.annotation.PathVariable;
|
||
import org.springframework.web.bind.annotation.PostMapping;
|
||
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
|
||
@RequestMapping("/api/v1/files")
|
||
@RequiredArgsConstructor
|
||
public class FileStorageController {
|
||
/**
|
||
* Сколько браузер помнит редирект на presigned URL и не ходит за ним на бэк.
|
||
* Вместе с кэшем ссылки (12ч) укладывается в её срок жизни (24ч).
|
||
*/
|
||
private static final Duration REDIRECT_CACHE_MAX_AGE = Duration.ofHours(6);
|
||
private static final long MAX_PRESIGNED_TTL_HOURS = 7 * 24;
|
||
|
||
private final FileStorageService fileStorageService;
|
||
|
||
@PostMapping
|
||
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
|
||
log.info("uploadFile");
|
||
String objectName = fileStorageService.uploadFile(file);
|
||
return ResponseEntity.ok(objectName); // фронт сохранит objectName как ключ картинки
|
||
}
|
||
|
||
@GetMapping("/{*objectName}")
|
||
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
|
||
String key = publicKey(objectName);
|
||
return fileStorageService.downloadFile(key);
|
||
}
|
||
|
||
/**
|
||
* Редирект на presigned URL для прямой загрузки файла с MinIO (Вариант B).
|
||
* Браузер перейдёт по 302 на временную ссылку и скачает картинку напрямую с MinIO.
|
||
* Ссылка стабильна (кэшируется) и сам редирект кэшируется браузером — повторный
|
||
* показ картинки не требует ни запроса на бэк, ни повторной загрузки.
|
||
*/
|
||
@GetMapping(value = "/{*objectName}", params = "presigned=true")
|
||
public ResponseEntity<Void> redirectToPresigned(@PathVariable String objectName) {
|
||
String key = publicKey(objectName);
|
||
String url = fileStorageService.getCachedPresignedDownloadUrl(key);
|
||
return ResponseEntity.status(302)
|
||
.header(HttpHeaders.LOCATION, url)
|
||
.cacheControl(CacheControl.maxAge(REDIRECT_CACHE_MAX_AGE).cachePrivate())
|
||
.build();
|
||
}
|
||
|
||
/**
|
||
* Возвращает presigned URL в JSON.
|
||
* PathPatternParser не допускает ничего после {*...}, поэтому "url" вынесен в префикс:
|
||
* GET /api/v1/files/url/avatars/cf80aebe-...jpg?ttlHours=24
|
||
*/
|
||
@GetMapping("/url/{*objectName}")
|
||
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
|
||
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);
|
||
return ResponseEntity.ok(Map.of("url", url));
|
||
}
|
||
|
||
@DeleteMapping("/{*objectName}")
|
||
public ResponseEntity<Void> deleteFile(@PathVariable String objectName) {
|
||
log.info("deleteFile {}", objectName);
|
||
// objectName может прийти как "/avatars/cf80aebe-...jpg" — обрежем ведущий слэш
|
||
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;
|
||
}
|
||
}
|