ЛР5: реализована асинхронная обработка изображений (оценка 3)
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class MessengerApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MessengerApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import ru.mtusi.messenger.entity.SessionEntity;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
public class BearerTokenFilter extends OncePerRequestFilter {
|
||||
|
||||
private final SessionRepository sessionRepository;
|
||||
|
||||
public BearerTokenFilter(SessionRepository sessionRepository) {
|
||||
this.sessionRepository = sessionRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
|
||||
Optional<SessionEntity> sessionOpt = sessionRepository.findById(token);
|
||||
|
||||
if (sessionOpt.isPresent() && sessionOpt.get().getExpiresAt().isAfter(OffsetDateTime.now(ZoneOffset.UTC))) {
|
||||
// Токен валиден! Кладем ID пользователя в контекст безопасности Spring
|
||||
SessionEntity session = sessionOpt.get();
|
||||
|
||||
// В Spring Security Principal - это объект, представляющий пользователя.
|
||||
// Мы будем использовать UUID пользователя как Principal.
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(session.getUserId(), null, Collections.emptyList());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
|
||||
// Пропускаем запрос дальше
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Configuration
|
||||
public class InstanceConfig {
|
||||
private static final Logger log = LoggerFactory.getLogger(InstanceConfig.class);
|
||||
|
||||
@Bean
|
||||
public String instanceId() {
|
||||
String id = UUID.randomUUID().toString().substring(0, 8);
|
||||
log.info("STARTED API INSTANCE WITH ID: {}", id);
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import org.springframework.amqp.core.*;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class RabbitConfig {
|
||||
|
||||
public static final String QUEUE_NAME = "image-processing-queue";
|
||||
public static final String EXCHANGE_NAME = "image-exchange";
|
||||
public static final String ROUTING_KEY = "image.process";
|
||||
|
||||
@Bean
|
||||
public Queue imageQueue() {
|
||||
// durable = true (сохраняется при перезапуске RabbitMQ)
|
||||
return new Queue(QUEUE_NAME, true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DirectExchange exchange() {
|
||||
return new DirectExchange(EXCHANGE_NAME);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding binding(Queue imageQueue, DirectExchange exchange) {
|
||||
return BindingBuilder.bind(imageQueue).to(exchange).with(ROUTING_KEY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.dto.ErrorResponse;
|
||||
import ru.mtusi.messenger.filter.RequestIdFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public RestAuthenticationEntryPoint(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
|
||||
throws IOException, ServletException {
|
||||
|
||||
// Достаем X-Request-Id, который сгенерировал наш фильтр ранее
|
||||
String requestId = (String) request.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
|
||||
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setHeader("WWW-Authenticate", "Bearer realm=\"messenger\"");
|
||||
|
||||
ErrorResponse error = ErrorResponse.of("unauthorized", "No valid bearer token", requestId);
|
||||
response.getWriter().write(objectMapper.writeValueAsString(error));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.S3Configuration;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
@Configuration
|
||||
public class S3Config {
|
||||
|
||||
@Value("${S3_ENDPOINT:http://minio:9000}")
|
||||
private String endpoint;
|
||||
|
||||
@Value("${S3_ACCESS_KEY:minioadmin}")
|
||||
private String accessKey;
|
||||
|
||||
@Value("${S3_SECRET_KEY:minioadmin}")
|
||||
private String secretKey;
|
||||
|
||||
@Value("${S3_REGION:us-east-1}")
|
||||
private String region;
|
||||
|
||||
@Bean
|
||||
public S3Client s3Client() {
|
||||
return S3Client.builder()
|
||||
.endpointOverride(URI.create(endpoint))
|
||||
.credentialsProvider(StaticCredentialsProvider.create(
|
||||
AwsBasicCredentials.create(accessKey, secretKey)))
|
||||
.region(Region.of(region))
|
||||
// MinIO требует path-style access (не virtual-hosted)
|
||||
.serviceConfiguration(S3Configuration.builder()
|
||||
.pathStyleAccessEnabled(true)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
private final SessionRepository sessionRepository;
|
||||
private final RestAuthenticationEntryPoint authEntryPoint; // ДОБАВЛЕНО
|
||||
|
||||
public SecurityConfig(SessionRepository sessionRepository, RestAuthenticationEntryPoint authEntryPoint) {
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.authEntryPoint = authEntryPoint; // ДОБАВЛЕНО
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
// ДОБАВЛЕНО: обработчик ошибок безопасности
|
||||
.exceptionHandling(ex -> ex.authenticationEntryPoint(authEntryPoint))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/v1/users", "/api/v1/auth/sessions", "/health/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.addFilterBefore(new BearerTokenFilter(sessionRepository), UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.Attachment;
|
||||
import ru.mtusi.messenger.entity.AttachmentEntity;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.service.AttachmentService;
|
||||
import ru.mtusi.messenger.service.StorageService;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1")
|
||||
public class AttachmentController {
|
||||
|
||||
private final AttachmentService attachmentService;
|
||||
private final AttachmentRepository attachmentRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final StorageService storageService;
|
||||
|
||||
public AttachmentController(AttachmentService attachmentService,
|
||||
AttachmentRepository attachmentRepository,
|
||||
ChatRepository chatRepository,
|
||||
StorageService storageService) {
|
||||
this.attachmentService = attachmentService;
|
||||
this.attachmentRepository = attachmentRepository;
|
||||
this.chatRepository = chatRepository;
|
||||
this.storageService = storageService;
|
||||
}
|
||||
|
||||
@PostMapping("/chats/{chat_id}/attachments")
|
||||
@ResponseStatus(HttpStatus.ACCEPTED)
|
||||
public Attachment upload(
|
||||
Authentication auth,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestParam("filename") String filename,
|
||||
@RequestHeader("Content-Type") String contentType,
|
||||
InputStream inputStream,
|
||||
HttpServletRequest request) throws Exception {
|
||||
|
||||
UUID callerId = getUserId(auth);
|
||||
long size = request.getContentLengthLong();
|
||||
|
||||
return attachmentService.upload(callerId, chatId, filename, contentType, inputStream, size);
|
||||
}
|
||||
|
||||
@GetMapping("/attachments/{attachment_id}")
|
||||
public Attachment getMetadata(
|
||||
Authentication auth,
|
||||
@PathVariable("attachment_id") UUID attachmentId) {
|
||||
|
||||
UUID callerId = getUserId(auth);
|
||||
AttachmentEntity entity = attachmentRepository.findById(attachmentId)
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found"));
|
||||
|
||||
verifyAccess(callerId, entity.getChatId());
|
||||
return attachmentService.toDto(entity);
|
||||
}
|
||||
|
||||
@GetMapping("/attachments/{attachment_id}/content")
|
||||
public ResponseEntity<InputStreamResource> download(
|
||||
Authentication auth,
|
||||
@PathVariable("attachment_id") UUID attachmentId,
|
||||
@RequestParam(value = "variant", required = false) String variantName) {
|
||||
|
||||
UUID callerId = getUserId(auth);
|
||||
AttachmentEntity entity = attachmentRepository.findById(attachmentId)
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found"));
|
||||
|
||||
verifyAccess(callerId, entity.getChatId());
|
||||
|
||||
String keyToDownload = entity.getObjectKey();
|
||||
String contentType = entity.getContentType();
|
||||
String filename = entity.getFilename();
|
||||
|
||||
if (variantName != null && !variantName.isBlank()) {
|
||||
var variantOpt = entity.getVariants().stream()
|
||||
.filter(v -> v.getName().equals(variantName))
|
||||
.findFirst();
|
||||
|
||||
if (variantOpt.isPresent()) {
|
||||
var variant = variantOpt.get();
|
||||
keyToDownload = variant.getObjectKey();
|
||||
contentType = variant.getContentType();
|
||||
filename = variantName + ".jpg";
|
||||
}
|
||||
}
|
||||
|
||||
InputStream stream = storageService.download(keyToDownload);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||
.body(new InputStreamResource(stream));
|
||||
}
|
||||
|
||||
private void verifyAccess(UUID callerId, UUID chatId) {
|
||||
ChatEntity chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
|
||||
if (!isMember) throw new NotFoundException("Chat not found");
|
||||
}
|
||||
|
||||
private UUID getUserId(Authentication auth) {
|
||||
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
return (UUID) auth.getPrincipal();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.SessionResponse;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
import ru.mtusi.messenger.service.SessionService;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final SessionService sessionService;
|
||||
private final SessionRepository sessionRepository; // <-- ДОБАВЛЕНО
|
||||
|
||||
public AuthController(SessionService sessionService, SessionRepository sessionRepository) {
|
||||
this.sessionService = sessionService;
|
||||
this.sessionRepository = sessionRepository; // <-- ДОБАВЛЕНО
|
||||
}
|
||||
|
||||
@PostMapping("/sessions")
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public SessionResponse createSession(
|
||||
@RequestHeader(value = "Authorization", required = false) String authHeader) {
|
||||
|
||||
if (authHeader == null || !authHeader.startsWith("Basic ")) {
|
||||
throw new UnauthorizedException("Missing or invalid Authorization header");
|
||||
}
|
||||
|
||||
String base64Credentials = authHeader.substring(6);
|
||||
String credentials = new String(Base64.getDecoder().decode(base64Credentials), StandardCharsets.UTF_8);
|
||||
|
||||
int colonIndex = credentials.indexOf(':');
|
||||
if (colonIndex == -1) {
|
||||
throw new UnauthorizedException("Invalid Basic Auth format");
|
||||
}
|
||||
|
||||
String username = credentials.substring(0, colonIndex);
|
||||
String password = credentials.substring(colonIndex + 1);
|
||||
|
||||
return sessionService.createSession(username, password);
|
||||
}
|
||||
|
||||
@DeleteMapping("/sessions/current")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void logout(@RequestHeader("Authorization") String authHeader) {
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
sessionRepository.deleteById(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.Chat;
|
||||
import ru.mtusi.messenger.dto.CreateChat;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.ChatService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats")
|
||||
public class ChatController {
|
||||
|
||||
private final ChatService chatService;
|
||||
|
||||
public ChatController(ChatService chatService) {
|
||||
this.chatService = chatService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Chat createChat(Authentication auth, @Valid @RequestBody CreateChat body) {
|
||||
return chatService.createChat(getUserId(auth), body);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public Object listChats(Authentication auth) {
|
||||
// Упрощенная версия без курсора для lab2, если тесты не требуют обратного
|
||||
return new ChatPage(chatService.getUserChats(getUserId(auth)), null);
|
||||
}
|
||||
|
||||
@GetMapping("/{chat_id}")
|
||||
public Chat getChat(Authentication auth, @PathVariable("chat_id") UUID chatId) {
|
||||
return chatService.getChat(getUserId(auth), chatId);
|
||||
}
|
||||
|
||||
private UUID getUserId(Authentication auth) {
|
||||
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
return (UUID) auth.getPrincipal();
|
||||
}
|
||||
|
||||
// Заглушка для DTO, чтобы не ломать компиляцию
|
||||
public record ChatPage(java.util.List<Chat> items, String nextCursor) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.mtusi.messenger.filter.RequestIdFilter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
|
||||
@GetMapping("/health/live")
|
||||
public ResponseEntity<Map<String, String>> liveness(HttpServletRequest request) {
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
|
||||
@GetMapping("/health/ready")
|
||||
public ResponseEntity<Map<String, String>> readiness(HttpServletRequest request) {
|
||||
return ResponseEntity.ok(Map.of("status", "ok"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.CreateMessage;
|
||||
import ru.mtusi.messenger.dto.Message;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.MessageService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/chats/{chat_id}/messages")
|
||||
public class MessageController {
|
||||
|
||||
private final MessageService messageService;
|
||||
|
||||
public MessageController(MessageService messageService) {
|
||||
this.messageService = messageService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public Message createMessage(
|
||||
Authentication auth,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey,
|
||||
@Valid @RequestBody CreateMessage body) {
|
||||
|
||||
if (idempotencyKey == null || idempotencyKey.isBlank()) {
|
||||
throw new InvalidRequestException("Idempotency-Key header is required");
|
||||
}
|
||||
if (!idempotencyKey.matches("^[A-Za-z0-9._:-]{1,128}$")) {
|
||||
throw new InvalidRequestException("Invalid Idempotency-Key format");
|
||||
}
|
||||
|
||||
return messageService.createMessage(getUserId(auth), chatId, body.text(), body.attachmentIds(), idempotencyKey);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public MessagePage listMessages(
|
||||
Authentication auth,
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@RequestParam(value = "limit", required = false) Integer limit,
|
||||
@RequestParam(value = "cursor", required = false) String cursor) {
|
||||
|
||||
int effectiveLimit = (limit == null) ? 50 : limit;
|
||||
if (effectiveLimit < 1 || effectiveLimit > 100) {
|
||||
throw new InvalidRequestException("limit must be between 1 and 100");
|
||||
}
|
||||
|
||||
java.time.OffsetDateTime lastCreatedAt = null;
|
||||
UUID lastId = null;
|
||||
|
||||
if (cursor != null && !cursor.isBlank()) {
|
||||
try {
|
||||
String decoded = new String(java.util.Base64.getUrlDecoder().decode(cursor), java.nio.charset.StandardCharsets.UTF_8);
|
||||
String[] parts = decoded.split("\\|");
|
||||
lastCreatedAt = java.time.OffsetDateTime.parse(parts[0]);
|
||||
lastId = UUID.fromString(parts[1]);
|
||||
} catch (Exception e) {
|
||||
throw new InvalidRequestException("Invalid cursor format");
|
||||
}
|
||||
}
|
||||
|
||||
// Берем на 1 больше, чтобы понять, есть ли следующая страница
|
||||
List<Message> msgs = messageService.getMessagesPage(getUserId(auth), chatId, lastCreatedAt, lastId, effectiveLimit + 1);
|
||||
|
||||
boolean hasMore = msgs.size() > effectiveLimit;
|
||||
List<Message> pageItems = hasMore ? msgs.subList(0, effectiveLimit) : msgs;
|
||||
|
||||
String nextCursor = null;
|
||||
if (hasMore && !pageItems.isEmpty()) {
|
||||
Message lastMsg = pageItems.get(pageItems.size() - 1);
|
||||
String rawCursor = lastMsg.createdAt().toString() + "|" + lastMsg.id().toString();
|
||||
nextCursor = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(rawCursor.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
return new MessagePage(pageItems, nextCursor);
|
||||
}
|
||||
|
||||
private UUID getUserId(Authentication auth) {
|
||||
if (auth == null || !(auth.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
return (UUID) auth.getPrincipal();
|
||||
}
|
||||
|
||||
public record MessagePage(List<Message> items, String nextCursor) {}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.CreateUser;
|
||||
import ru.mtusi.messenger.dto.User;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.UserService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.CREATED)
|
||||
public User createUser(@Valid @RequestBody CreateUser body) {
|
||||
return userService.createUser(body);
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public User currentUser(Authentication authentication) {
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof UUID)) {
|
||||
throw new UnauthorizedException("Not authenticated");
|
||||
}
|
||||
UUID userId = (UUID) authentication.getPrincipal();
|
||||
|
||||
return userService.findById(userId)
|
||||
.orElseThrow(() -> new UnauthorizedException("Unknown user"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Attachment(
|
||||
@JsonProperty("id") UUID id,
|
||||
@JsonProperty("chat_id") UUID chatId,
|
||||
@JsonProperty("owner_id") UUID ownerId,
|
||||
@JsonProperty("filename") String filename,
|
||||
@JsonProperty("content_type") String contentType,
|
||||
@JsonProperty("size_bytes") long sizeBytes,
|
||||
@JsonProperty("sha256") String sha256,
|
||||
@JsonProperty("status") String status,
|
||||
@JsonProperty("variants") List<Variant> variants, // <-- Изменили тип
|
||||
@JsonProperty("error_code") String errorCode,
|
||||
@JsonProperty("created_at") OffsetDateTime createdAt,
|
||||
@JsonProperty("updated_at") OffsetDateTime updatedAt
|
||||
) {
|
||||
public record Variant(
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("content_type") String contentType,
|
||||
@JsonProperty("size_bytes") long sizeBytes,
|
||||
@JsonProperty("sha256") String sha256,
|
||||
@JsonProperty("width") int width,
|
||||
@JsonProperty("height") int height
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Chat(
|
||||
@JsonProperty("id") UUID id,
|
||||
@JsonProperty("title") String title,
|
||||
@JsonProperty("member_ids") List<UUID> memberIds,
|
||||
@JsonProperty("created_at") OffsetDateTime createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
|
||||
public record ChatPage(
|
||||
@JsonProperty("items") List<Chat> items,
|
||||
@JsonProperty("next_cursor") String nextCursor
|
||||
) {}
|
||||
@@ -0,0 +1,21 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record CreateChat(
|
||||
@JsonProperty("title")
|
||||
@NotBlank(message = "title must not be blank")
|
||||
@Size(min = 1, max = 100, message = "title must be 1..100 characters")
|
||||
String title,
|
||||
|
||||
@JsonProperty("member_ids")
|
||||
@NotEmpty(message = "member_ids must not be empty")
|
||||
@Size(min = 1, max = 100, message = "member_ids must contain 1..100 items")
|
||||
List<UUID> memberIds
|
||||
) {}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record CreateMessage(
|
||||
@JsonProperty("text")
|
||||
@Size(max = 4000, message = "text must be up to 4000 characters")
|
||||
String text,
|
||||
|
||||
@JsonProperty("attachment_ids")
|
||||
@Size(max = 10, message = "attachment_ids can contain up to 10 items")
|
||||
List<UUID> attachmentIds
|
||||
) {
|
||||
public CreateMessage {
|
||||
if (attachmentIds == null) {
|
||||
attachmentIds = List.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record CreateUser(
|
||||
@JsonProperty("username")
|
||||
@NotBlank(message = "username must not be blank")
|
||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$", message = "username must match ^[a-z0-9_]{3,32}$")
|
||||
String username,
|
||||
|
||||
@JsonProperty("display_name")
|
||||
@NotBlank(message = "display_name must not be blank")
|
||||
@Size(min = 1, max = 100, message = "display_name must be 1..100 characters")
|
||||
String displayName,
|
||||
|
||||
@JsonProperty("password")
|
||||
@NotBlank(message = "password must not be blank")
|
||||
@Size(min = 12, max = 128, message = "password must be 12..128 characters")
|
||||
String password
|
||||
) {}
|
||||
@@ -0,0 +1,17 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record ErrorResponse(
|
||||
@JsonProperty("error") ErrorBody error
|
||||
) {
|
||||
public record ErrorBody(
|
||||
@JsonProperty("code") String code,
|
||||
@JsonProperty("message") String message,
|
||||
@JsonProperty("request_id") String requestId
|
||||
) {}
|
||||
|
||||
public static ErrorResponse of(String code, String message, String requestId) {
|
||||
return new ErrorResponse(new ErrorBody(code, message, requestId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
public record Health(String status) {
|
||||
public static Health ok() {
|
||||
return new Health("ok");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record Message(
|
||||
@JsonProperty("id") UUID id,
|
||||
@JsonProperty("chat_id") UUID chatId,
|
||||
@JsonProperty("sender_id") UUID senderId,
|
||||
@JsonProperty("text") String text,
|
||||
@JsonProperty("attachment_ids") List<UUID> attachmentIds,
|
||||
@JsonProperty("created_at") OffsetDateTime createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
|
||||
public record MessagePage(
|
||||
@JsonProperty("items") List<Message> items,
|
||||
@JsonProperty("next_cursor") String nextCursor
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.List;
|
||||
|
||||
public record Page<T>(
|
||||
@JsonProperty("items") List<T> items,
|
||||
@JsonProperty("next_cursor") String nextCursor
|
||||
) {}
|
||||
@@ -0,0 +1,15 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public record SessionResponse(
|
||||
@JsonProperty("token") String token,
|
||||
@JsonProperty("token_type") String tokenType,
|
||||
@JsonProperty("expires_at") OffsetDateTime expiresAt,
|
||||
@JsonProperty("user") User user
|
||||
) {
|
||||
public SessionResponse(String token, OffsetDateTime expiresAt, User user) {
|
||||
this(token, "Bearer", expiresAt, user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
public record User(
|
||||
@JsonProperty("id") UUID id,
|
||||
@JsonProperty("username") String username,
|
||||
@JsonProperty("display_name") String displayName,
|
||||
@JsonProperty("created_at") OffsetDateTime createdAt
|
||||
) {}
|
||||
@@ -0,0 +1,82 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attachments")
|
||||
public class AttachmentEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "owner_id", nullable = false)
|
||||
private UUID ownerId;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String filename;
|
||||
|
||||
@Column(name = "content_type", nullable = false, length = 100)
|
||||
private String contentType;
|
||||
|
||||
@Column(name = "size_bytes", nullable = false)
|
||||
private long sizeBytes;
|
||||
|
||||
@Column(nullable = false, length = 64)
|
||||
private String sha256;
|
||||
|
||||
@Column(name = "object_key", nullable = false, length = 255)
|
||||
private String objectKey;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// === НОВЫЕ ПОЛЯ ===
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status = "queued";
|
||||
|
||||
@Column(name = "error_code", length = 50)
|
||||
private String errorCode;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private OffsetDateTime updatedAt;
|
||||
// ==================
|
||||
|
||||
// Связь с вариантами (thumbnail)
|
||||
@OneToMany(mappedBy = "attachment", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
private List<AttachmentVariantEntity> variants = new ArrayList<>();
|
||||
|
||||
// --- Геттеры и сеттеры ---
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public UUID getChatId() { return chatId; }
|
||||
public void setChatId(UUID chatId) { this.chatId = chatId; }
|
||||
public UUID getOwnerId() { return ownerId; }
|
||||
public void setOwnerId(UUID ownerId) { this.ownerId = ownerId; }
|
||||
public String getFilename() { return filename; }
|
||||
public void setFilename(String filename) { this.filename = filename; }
|
||||
public String getContentType() { return contentType; }
|
||||
public void setContentType(String contentType) { this.contentType = contentType; }
|
||||
public long getSizeBytes() { return sizeBytes; }
|
||||
public void setSizeBytes(long sizeBytes) { this.sizeBytes = sizeBytes; }
|
||||
public String getSha256() { return sha256; }
|
||||
public void setSha256(String sha256) { this.sha256 = sha256; }
|
||||
public String getObjectKey() { return objectKey; }
|
||||
public void setObjectKey(String objectKey) { this.objectKey = objectKey; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getErrorCode() { return errorCode; }
|
||||
public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
|
||||
public OffsetDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
public List<AttachmentVariantEntity> getVariants() { return variants; }
|
||||
public void setVariants(List<AttachmentVariantEntity> variants) { this.variants = variants; }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attachment_variants")
|
||||
@IdClass(AttachmentVariantId.class)
|
||||
public class AttachmentVariantEntity {
|
||||
|
||||
@Id
|
||||
@Column(name = "attachment_id")
|
||||
private UUID attachmentId;
|
||||
|
||||
@Id
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "object_key", nullable = false, length = 255)
|
||||
private String objectKey;
|
||||
|
||||
@Column(name = "content_type", nullable = false, length = 100)
|
||||
private String contentType;
|
||||
|
||||
@Column(name = "size_bytes", nullable = false)
|
||||
private long sizeBytes;
|
||||
|
||||
@Column(nullable = false, length = 64)
|
||||
private String sha256;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int width;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int height;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "attachment_id", insertable = false, updatable = false)
|
||||
private AttachmentEntity attachment;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public UUID getAttachmentId() { return attachmentId; }
|
||||
public void setAttachmentId(UUID attachmentId) { this.attachmentId = attachmentId; }
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public String getObjectKey() { return objectKey; }
|
||||
public void setObjectKey(String objectKey) { this.objectKey = objectKey; }
|
||||
public String getContentType() { return contentType; }
|
||||
public void setContentType(String contentType) { this.contentType = contentType; }
|
||||
public long getSizeBytes() { return sizeBytes; }
|
||||
public void setSizeBytes(long sizeBytes) { this.sizeBytes = sizeBytes; }
|
||||
public String getSha256() { return sha256; }
|
||||
public void setSha256(String sha256) { this.sha256 = sha256; }
|
||||
public int getWidth() { return width; }
|
||||
public void setWidth(int width) { this.width = width; }
|
||||
public int getHeight() { return height; }
|
||||
public void setHeight(int height) { this.height = height; }
|
||||
public AttachmentEntity getAttachment() { return attachment; }
|
||||
public void setAttachment(AttachmentEntity attachment) { this.attachment = attachment; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class AttachmentVariantId implements Serializable {
|
||||
private UUID attachmentId;
|
||||
private String name;
|
||||
|
||||
public AttachmentVariantId() {}
|
||||
|
||||
public AttachmentVariantId(UUID attachmentId, String name) {
|
||||
this.attachmentId = attachmentId;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
AttachmentVariantId that = (AttachmentVariantId) o;
|
||||
return Objects.equals(attachmentId, that.attachmentId) && Objects.equals(name, that.name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(attachmentId, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "chats")
|
||||
public class ChatEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
@ManyToMany
|
||||
@JoinTable(
|
||||
name = "chat_members",
|
||||
joinColumns = @JoinColumn(name = "chat_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "user_id")
|
||||
)
|
||||
private Set<UserEntity> members;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
public Set<UserEntity> getMembers() { return members; }
|
||||
public void setMembers(Set<UserEntity> members) { this.members = members; }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "idempotency_keys")
|
||||
@IdClass(IdempotencyId.class)
|
||||
public class IdempotencyEntity {
|
||||
@Id
|
||||
private String key;
|
||||
|
||||
@Id
|
||||
@Column(name = "user_id")
|
||||
private UUID userId;
|
||||
|
||||
@Id
|
||||
@Column(name = "chat_id")
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "request_hash", nullable = false)
|
||||
private String requestHash;
|
||||
|
||||
@Column(name = "message_id", nullable = false)
|
||||
private UUID messageId;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public String getKey() { return key; }
|
||||
public void setKey(String key) { this.key = key; }
|
||||
public UUID getUserId() { return userId; }
|
||||
public void setUserId(UUID userId) { this.userId = userId; }
|
||||
public UUID getChatId() { return chatId; }
|
||||
public void setChatId(UUID chatId) { this.chatId = chatId; }
|
||||
public String getRequestHash() { return requestHash; }
|
||||
public void setRequestHash(String requestHash) { this.requestHash = requestHash; }
|
||||
public UUID getMessageId() { return messageId; }
|
||||
public void setMessageId(UUID messageId) { this.messageId = messageId; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class IdempotencyId implements Serializable {
|
||||
private String key;
|
||||
private UUID userId;
|
||||
private UUID chatId;
|
||||
|
||||
public IdempotencyId() {}
|
||||
public IdempotencyId(String key, UUID userId, UUID chatId) {
|
||||
this.key = key;
|
||||
this.userId = userId;
|
||||
this.chatId = chatId;
|
||||
}
|
||||
|
||||
// equals и hashCode обязательны для JPA
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
IdempotencyId that = (IdempotencyId) o;
|
||||
return Objects.equals(key, that.key) && Objects.equals(userId, that.userId) && Objects.equals(chatId, that.chatId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(key, userId, chatId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "messages")
|
||||
public class MessageEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "sender_id", nullable = false)
|
||||
private UUID senderId;
|
||||
|
||||
@Column(nullable = false, length = 4000)
|
||||
private String text;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public UUID getChatId() { return chatId; }
|
||||
public void setChatId(UUID chatId) { this.chatId = chatId; }
|
||||
public UUID getSenderId() { return senderId; }
|
||||
public void setSenderId(UUID senderId) { this.senderId = senderId; }
|
||||
public String getText() { return text; }
|
||||
public void setText(String text) { this.text = text; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "sessions")
|
||||
public class SessionEntity {
|
||||
@Id
|
||||
private String token;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private OffsetDateTime expiresAt;
|
||||
|
||||
// Геттеры и сеттеры
|
||||
public String getToken() { return token; }
|
||||
public void setToken(String token) { this.token = token; }
|
||||
public UUID getUserId() { return userId; }
|
||||
public void setUserId(UUID userId) { this.userId = userId; }
|
||||
public OffsetDateTime getExpiresAt() { return expiresAt; }
|
||||
public void setExpiresAt(OffsetDateTime expiresAt) { this.expiresAt = expiresAt; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.messenger.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity {
|
||||
@Id
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 32)
|
||||
private String username;
|
||||
|
||||
@Column(name = "password_hash", nullable = false)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
// Геттеры и сеттеры (или используй Lombok, если он есть)
|
||||
public UUID getId() { return id; }
|
||||
public void setId(UUID id) { this.id = id; }
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
public String getPasswordHash() { return passwordHash; }
|
||||
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class ConflictException extends RuntimeException {
|
||||
public ConflictException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import ru.mtusi.messenger.dto.ErrorResponse;
|
||||
import ru.mtusi.messenger.filter.RequestIdFilter;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(InvalidRequestException.class)
|
||||
public ResponseEntity<ErrorResponse> handleInvalid(InvalidRequestException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.BAD_REQUEST, "invalid_request", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnauthorizedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnauthorized(UnauthorizedException ex, HttpServletRequest req) {
|
||||
String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
|
||||
ErrorResponse body = ErrorResponse.of("unauthorized", ex.getMessage(), requestId);
|
||||
|
||||
// Контракт требует заголовок WWW-Authenticate
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"")
|
||||
.body(body);
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.NOT_FOUND, "not_found", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
public ResponseEntity<ErrorResponse> handleConflict(ConflictException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.CONFLICT, "conflict", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex, HttpServletRequest req) {
|
||||
String message = ex.getBindingResult().getFieldErrors().stream()
|
||||
.findFirst()
|
||||
.map(fe -> fe.getField() + ": " + fe.getDefaultMessage())
|
||||
.orElse("Validation failed");
|
||||
return error(HttpStatus.BAD_REQUEST, "invalid_request", message, req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMalformed(HttpMessageNotReadableException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.BAD_REQUEST, "invalid_request", "Malformed JSON or invalid field type", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMissingHeader(MissingRequestHeaderException ex, HttpServletRequest req) {
|
||||
// Мы не бросаем это явно, но если понадобится required=true в @RequestHeader
|
||||
return error(HttpStatus.UNAUTHORIZED, "unauthorized", "Missing required header", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleAll(Exception ex, HttpServletRequest req) {
|
||||
// Не логируем stack trace в ответ; для отладки — в stdout
|
||||
ex.printStackTrace();
|
||||
return error(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "Internal server error", req);
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorResponse> error(HttpStatus status, String code, String message,
|
||||
HttpServletRequest req) {
|
||||
String requestId = (String) req.getAttribute(RequestIdFilter.REQUEST_ID_ATTR);
|
||||
return ResponseEntity.status(status).body(ErrorResponse.of(code, message, requestId));
|
||||
}
|
||||
|
||||
@ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrity(org.springframework.dao.DataIntegrityViolationException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.CONFLICT, "conflict", "Resource already exists", req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(PayloadTooLargeException.class)
|
||||
public ResponseEntity<ErrorResponse> handlePayloadTooLarge(PayloadTooLargeException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.PAYLOAD_TOO_LARGE, "payload_too_large", ex.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnsupportedMediaTypeException.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnsupportedMedia(UnsupportedMediaTypeException ex, HttpServletRequest req) {
|
||||
return error(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type", ex.getMessage(), req);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class InvalidRequestException extends RuntimeException {
|
||||
public InvalidRequestException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
public class PayloadTooLargeException extends RuntimeException {
|
||||
public PayloadTooLargeException(String message) { super(message); }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class UnauthorizedException extends RuntimeException {
|
||||
public UnauthorizedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
public class UnsupportedMediaTypeException extends RuntimeException {
|
||||
public UnsupportedMediaTypeException(String message) { super(message); }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.mtusi.messenger.filter;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(-200)
|
||||
public class RequestIdFilter implements Filter {
|
||||
|
||||
public static final String REQUEST_ID_ATTR = "requestId";
|
||||
public static final String REQUEST_ID_HEADER = "X-Request-Id";
|
||||
|
||||
private final String instanceId;
|
||||
|
||||
public RequestIdFilter(String instanceId) {
|
||||
this.instanceId = instanceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
httpRequest.setAttribute(REQUEST_ID_ATTR, requestId);
|
||||
httpResponse.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
|
||||
// Добавляем X-Instance-Id
|
||||
httpResponse.setHeader("X-Instance-Id", instanceId);
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.AttachmentEntity;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttachmentRepository extends JpaRepository<AttachmentEntity, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ChatRepository extends JpaRepository<ChatEntity, UUID> {
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.IdempotencyEntity;
|
||||
import ru.mtusi.messenger.entity.IdempotencyId;
|
||||
|
||||
public interface IdempotencyRepository extends JpaRepository<IdempotencyEntity, IdempotencyId> {
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying; // <-- ДОБАВЛЕНО
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import ru.mtusi.messenger.entity.MessageEntity;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface MessageRepository extends JpaRepository<MessageEntity, UUID> {
|
||||
|
||||
@Query("SELECT m FROM MessageEntity m WHERE m.chatId = :chatId " +
|
||||
"AND (m.createdAt > :createdAt OR (m.createdAt = :createdAt AND m.id > :id)) " +
|
||||
"ORDER BY m.createdAt ASC, m.id ASC")
|
||||
List<MessageEntity> findNextPage(
|
||||
@Param("chatId") UUID chatId,
|
||||
@Param("createdAt") OffsetDateTime createdAt,
|
||||
@Param("id") UUID id,
|
||||
Pageable pageable
|
||||
);
|
||||
|
||||
@Modifying
|
||||
@Query(value = "INSERT INTO message_attachments (message_id, attachment_id) VALUES (:messageId, :attachmentId)", nativeQuery = true)
|
||||
void linkAttachment(@Param("messageId") UUID messageId, @Param("attachmentId") UUID attachmentId);
|
||||
|
||||
@Query(value = "SELECT attachment_id FROM message_attachments WHERE message_id = :messageId", nativeQuery = true)
|
||||
List<UUID> findAttachmentIdsByMessageId(@Param("messageId") UUID messageId);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.SessionEntity;
|
||||
|
||||
public interface SessionRepository extends JpaRepository<SessionEntity, String> {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRepository extends JpaRepository<UserEntity, UUID> {
|
||||
Optional<UserEntity> findByUsername(String username);
|
||||
boolean existsByUsername(String username);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.Attachment;
|
||||
import ru.mtusi.messenger.entity.AttachmentEntity;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import ru.mtusi.messenger.config.RabbitConfig;
|
||||
|
||||
@Service
|
||||
public class AttachmentService {
|
||||
|
||||
private final AttachmentRepository attachmentRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final StorageService storageService;
|
||||
|
||||
private static final long MAX_SIZE = 10 * 1024 * 1024; // 10 MiB
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public AttachmentService(AttachmentRepository attachmentRepository, ChatRepository chatRepository, StorageService storageService, RabbitTemplate rabbitTemplate) {
|
||||
this.attachmentRepository = attachmentRepository;
|
||||
this.chatRepository = chatRepository;
|
||||
this.storageService = storageService;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Attachment upload(UUID callerId, UUID chatId, String filename, String contentType, InputStream inputStream, long size) throws Exception {
|
||||
verifyAccess(callerId, chatId);
|
||||
|
||||
if (size > MAX_SIZE) {
|
||||
throw new ru.mtusi.messenger.exception.PayloadTooLargeException("File exceeds 10 MiB");
|
||||
}
|
||||
if (filename == null || filename.isBlank() || filename.contains("/") || filename.contains("\\") || filename.contains("\0")) {
|
||||
throw new InvalidRequestException("Invalid filename");
|
||||
}
|
||||
|
||||
// Читаем байты в память (для 10 MiB это безопасно)
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
byte[] data = new byte[8192];
|
||||
int nRead;
|
||||
long totalRead = 0;
|
||||
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
|
||||
buffer.write(data, 0, nRead);
|
||||
totalRead += nRead;
|
||||
if (totalRead > MAX_SIZE) throw new ru.mtusi.messenger.exception.PayloadTooLargeException("File exceeds 10 MiB");
|
||||
}
|
||||
byte[] bytes = buffer.toByteArray();
|
||||
|
||||
// Проверяем MIME по магическим байтам
|
||||
String detectedMime = detectMime(bytes);
|
||||
if (!detectedMime.equals("image/png") && !detectedMime.equals("image/jpeg")) {
|
||||
throw new ru.mtusi.messenger.exception.UnsupportedMediaTypeException("Only PNG and JPEG are allowed");
|
||||
}
|
||||
if (!detectedMime.equals(contentType)) {
|
||||
throw new ru.mtusi.messenger.exception.UnsupportedMediaTypeException("MIME type mismatch");
|
||||
}
|
||||
|
||||
// Считаем SHA-256
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
String sha256 = HexFormat.of().formatHex(digest.digest(bytes));
|
||||
|
||||
// Загружаем в S3 в папку staging (временное хранилище)
|
||||
String objectKey = "staging/" + UUID.randomUUID().toString();
|
||||
storageService.upload(objectKey, new ByteArrayInputStream(bytes), bytes.length, detectedMime);
|
||||
|
||||
// Сохраняем метаданные в БД со статусом queued
|
||||
AttachmentEntity entity = new AttachmentEntity();
|
||||
entity.setId(UUID.randomUUID());
|
||||
entity.setChatId(chatId);
|
||||
entity.setOwnerId(callerId);
|
||||
entity.setFilename(filename);
|
||||
entity.setContentType(detectedMime);
|
||||
entity.setSizeBytes(bytes.length);
|
||||
entity.setSha256(sha256);
|
||||
entity.setObjectKey(objectKey);
|
||||
entity.setStatus("queued");
|
||||
entity.setErrorCode(null);
|
||||
|
||||
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
|
||||
entity.setCreatedAt(now);
|
||||
entity.setUpdatedAt(now);
|
||||
|
||||
attachmentRepository.save(entity);
|
||||
|
||||
rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY, entity.getId().toString());
|
||||
|
||||
// TODO: Здесь на Шаге 3 мы будем отправлять сообщение в RabbitMQ
|
||||
// Пока что просто возвращаем ответ.
|
||||
|
||||
return toDto(entity);
|
||||
}
|
||||
|
||||
private void verifyAccess(UUID callerId, UUID chatId) {
|
||||
ChatEntity chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
|
||||
if (!isMember) throw new NotFoundException("Chat not found");
|
||||
}
|
||||
|
||||
private String detectMime(byte[] bytes) {
|
||||
if (bytes.length < 4) return "unknown";
|
||||
if ((bytes[0] & 0xFF) == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47) return "image/png";
|
||||
if ((bytes[0] & 0xFF) == 0xFF && (bytes[1] & 0xFF) == 0xD8 && (bytes[2] & 0xFF) == 0xFF) return "image/jpeg";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
public Attachment toDto(AttachmentEntity e) {
|
||||
// Маппим варианты из БД (пока их нет, вернется пустой список)
|
||||
List<Attachment.Variant> variantDtos = e.getVariants().stream()
|
||||
.map(v -> new Attachment.Variant(
|
||||
v.getName(),
|
||||
v.getContentType(),
|
||||
v.getSizeBytes(),
|
||||
v.getSha256(),
|
||||
v.getWidth(),
|
||||
v.getHeight()
|
||||
))
|
||||
.toList();
|
||||
|
||||
return new Attachment(
|
||||
e.getId(), e.getChatId(), e.getOwnerId(), e.getFilename(),
|
||||
e.getContentType(), e.getSizeBytes(), e.getSha256(),
|
||||
e.getStatus(),
|
||||
variantDtos,
|
||||
e.getErrorCode(),
|
||||
e.getCreatedAt(),
|
||||
e.getUpdatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.Chat;
|
||||
import ru.mtusi.messenger.dto.CreateChat;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class ChatService {
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public ChatService(ChatRepository chatRepository, UserRepository userRepository) {
|
||||
this.chatRepository = chatRepository;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Chat createChat(UUID callerId, CreateChat request) {
|
||||
Set<UUID> uniqueMembers = new HashSet<>(request.memberIds());
|
||||
if (uniqueMembers.size() != request.memberIds().size()) {
|
||||
throw new InvalidRequestException("member_ids must be unique");
|
||||
}
|
||||
if (!uniqueMembers.contains(callerId)) {
|
||||
throw new InvalidRequestException("caller must be a member of the chat");
|
||||
}
|
||||
|
||||
List<UserEntity> members = userRepository.findAllById(request.memberIds());
|
||||
if (members.size() != request.memberIds().size()) {
|
||||
throw new InvalidRequestException("Some members do not exist");
|
||||
}
|
||||
|
||||
ChatEntity chat = new ChatEntity();
|
||||
chat.setId(UUID.randomUUID());
|
||||
chat.setTitle(request.title());
|
||||
chat.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
chat.setMembers(new HashSet<>(members));
|
||||
|
||||
chatRepository.save(chat);
|
||||
return toDto(chat);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Chat getChat(UUID callerId, UUID chatId) {
|
||||
ChatEntity chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
|
||||
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
|
||||
if (!isMember) throw new NotFoundException("Chat not found");
|
||||
|
||||
return toDto(chat);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Chat> getUserChats(UUID callerId) {
|
||||
// В реальном проекте лучше сделать кастомный запрос, но для lab2 сойдет
|
||||
return chatRepository.findAll().stream()
|
||||
.filter(c -> c.getMembers().stream().anyMatch(u -> u.getId().equals(callerId)))
|
||||
.map(this::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Chat toDto(ChatEntity entity) {
|
||||
return new Chat(
|
||||
entity.getId(),
|
||||
entity.getTitle(),
|
||||
entity.getMembers().stream().map(UserEntity::getId).toList(),
|
||||
entity.getCreatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.Message;
|
||||
import ru.mtusi.messenger.entity.AttachmentEntity;
|
||||
import ru.mtusi.messenger.entity.ChatEntity;
|
||||
import ru.mtusi.messenger.entity.MessageEntity;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.repository.IdempotencyRepository;
|
||||
import ru.mtusi.messenger.repository.MessageRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class MessageService {
|
||||
|
||||
private final MessageRepository messageRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final IdempotencyRepository idempotencyRepository;
|
||||
private final AttachmentRepository attachmentRepository;
|
||||
|
||||
public MessageService(MessageRepository messageRepository,
|
||||
ChatRepository chatRepository,
|
||||
IdempotencyRepository idempotencyRepository,
|
||||
AttachmentRepository attachmentRepository) {
|
||||
this.messageRepository = messageRepository;
|
||||
this.chatRepository = chatRepository;
|
||||
this.idempotencyRepository = idempotencyRepository;
|
||||
this.attachmentRepository = attachmentRepository;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Message createMessage(UUID callerId, UUID chatId, String text, List<UUID> attachmentIds, String idempotencyKey) {
|
||||
verifyAccess(callerId, chatId);
|
||||
|
||||
if (text == null) text = "";
|
||||
if (text.isBlank() && (attachmentIds == null || attachmentIds.isEmpty())) {
|
||||
throw new InvalidRequestException("Message must have text or attachments");
|
||||
}
|
||||
|
||||
// Проверяем вложения
|
||||
if (attachmentIds != null && !attachmentIds.isEmpty()) {
|
||||
for (UUID attId : attachmentIds) {
|
||||
AttachmentEntity att = attachmentRepository.findById(attId)
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found: " + attId));
|
||||
if (!att.getChatId().equals(chatId)) {
|
||||
throw new NotFoundException("Attachment not found in this chat");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Считаем хеш тела запроса
|
||||
String requestHash = org.springframework.util.DigestUtils.md5DigestAsHex(
|
||||
(text + attachmentIds).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
|
||||
if (idempotencyKey != null && !idempotencyKey.isBlank()) {
|
||||
var existing = idempotencyRepository.findById(new ru.mtusi.messenger.entity.IdempotencyId(idempotencyKey, callerId, chatId));
|
||||
if (existing.isPresent()) {
|
||||
if (!existing.get().getRequestHash().equals(requestHash)) {
|
||||
throw new ConflictException("Idempotency key reused with different body");
|
||||
}
|
||||
return messageRepository.findById(existing.get().getMessageId())
|
||||
.map(this::toDto)
|
||||
.orElseThrow(() -> new NotFoundException("Message not found"));
|
||||
}
|
||||
}
|
||||
|
||||
MessageEntity msg = new MessageEntity();
|
||||
msg.setId(UUID.randomUUID());
|
||||
msg.setChatId(chatId);
|
||||
msg.setSenderId(callerId);
|
||||
msg.setText(text);
|
||||
msg.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS));
|
||||
messageRepository.save(msg);
|
||||
|
||||
// Связываем вложения
|
||||
if (attachmentIds != null && !attachmentIds.isEmpty()) {
|
||||
for (UUID attId : attachmentIds) {
|
||||
messageRepository.linkAttachment(msg.getId(), attId);
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем ключ идемпотентности
|
||||
if (idempotencyKey != null && !idempotencyKey.isBlank()) {
|
||||
var idem = new ru.mtusi.messenger.entity.IdempotencyEntity();
|
||||
idem.setKey(idempotencyKey);
|
||||
idem.setUserId(callerId);
|
||||
idem.setChatId(chatId);
|
||||
idem.setRequestHash(requestHash);
|
||||
idem.setMessageId(msg.getId());
|
||||
idem.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
idempotencyRepository.save(idem);
|
||||
}
|
||||
|
||||
return toDto(msg);
|
||||
}
|
||||
|
||||
private void verifyAccess(UUID callerId, UUID chatId) {
|
||||
ChatEntity chat = chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
boolean isMember = chat.getMembers().stream().anyMatch(u -> u.getId().equals(callerId));
|
||||
if (!isMember) throw new NotFoundException("Chat not found");
|
||||
}
|
||||
|
||||
private Message toDto(MessageEntity e) {
|
||||
List<UUID> attachments = messageRepository.findAttachmentIdsByMessageId(e.getId());
|
||||
return new Message(
|
||||
e.getId(),
|
||||
e.getChatId(),
|
||||
e.getSenderId(),
|
||||
e.getText(),
|
||||
attachments,
|
||||
e.getCreatedAt()
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<Message> getMessagesPage(UUID callerId, UUID chatId, OffsetDateTime lastCreatedAt, UUID lastId, int limit) {
|
||||
verifyAccess(callerId, chatId);
|
||||
|
||||
OffsetDateTime startTime = (lastCreatedAt != null) ? lastCreatedAt : OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
|
||||
UUID startId = (lastId != null) ? lastId : new UUID(0, 0);
|
||||
|
||||
return messageRepository.findNextPage(chatId, startTime, startId, org.springframework.data.domain.PageRequest.of(0, limit))
|
||||
.stream().map(this::toDto).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.SessionResponse;
|
||||
import ru.mtusi.messenger.entity.SessionEntity;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class SessionService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserService userService;
|
||||
|
||||
public SessionService(UserRepository userRepository,
|
||||
SessionRepository sessionRepository,
|
||||
PasswordEncoder passwordEncoder,
|
||||
UserService userService) {
|
||||
this.userRepository = userRepository;
|
||||
this.sessionRepository = sessionRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SessionResponse createSession(String username, String rawPassword) {
|
||||
// 1. Ищем пользователя
|
||||
UserEntity user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UnauthorizedException("Invalid credentials"));
|
||||
|
||||
// 2. Проверяем пароль
|
||||
if (!passwordEncoder.matches(rawPassword, user.getPasswordHash())) {
|
||||
throw new UnauthorizedException("Invalid credentials");
|
||||
}
|
||||
|
||||
// 3. Генерируем opaque токен (UUID)
|
||||
String token = UUID.randomUUID().toString();
|
||||
|
||||
// 4. Сохраняем сессию в БД (TTL 1 час)
|
||||
SessionEntity session = new SessionEntity();
|
||||
session.setToken(token);
|
||||
session.setUserId(user.getId());
|
||||
session.setExpiresAt(OffsetDateTime.now(ZoneOffset.UTC).plusHours(1));
|
||||
|
||||
sessionRepository.save(session);
|
||||
|
||||
// 5. Возвращаем ответ
|
||||
return new SessionResponse(
|
||||
token,
|
||||
session.getExpiresAt(),
|
||||
userService.toDto(user)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
|
||||
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
@Service
|
||||
public class StorageService {
|
||||
|
||||
private final S3Client s3Client;
|
||||
private final String bucketName;
|
||||
|
||||
public StorageService(S3Client s3Client, @Value("${S3_BUCKET:messenger-attachments}") String bucketName) {
|
||||
this.s3Client = s3Client;
|
||||
this.bucketName = bucketName;
|
||||
ensureBucketExists();
|
||||
}
|
||||
|
||||
private void ensureBucketExists() {
|
||||
try {
|
||||
s3Client.headBucket(b -> b.bucket(bucketName));
|
||||
} catch (Exception e) {
|
||||
// Бакета нет или нет доступа — пытаемся создать
|
||||
try {
|
||||
s3Client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build());
|
||||
} catch (Exception ex) {
|
||||
throw new RuntimeException("Failed to create S3 bucket", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void upload(String objectKey, InputStream inputStream, long contentLength, String contentType) {
|
||||
PutObjectRequest request = PutObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(objectKey)
|
||||
.contentType(contentType)
|
||||
.build();
|
||||
s3Client.putObject(request, RequestBody.fromInputStream(inputStream, contentLength));
|
||||
}
|
||||
|
||||
public InputStream download(String objectKey) {
|
||||
GetObjectRequest request = GetObjectRequest.builder()
|
||||
.bucket(bucketName)
|
||||
.key(objectKey)
|
||||
.build();
|
||||
return s3Client.getObject(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.mtusi.messenger.dto.CreateUser;
|
||||
import ru.mtusi.messenger.dto.User;
|
||||
import ru.mtusi.messenger.entity.UserEntity;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User createUser(CreateUser request) {
|
||||
// ... проверка username ...
|
||||
UserEntity entity = new UserEntity();
|
||||
entity.setId(UUID.randomUUID());
|
||||
entity.setUsername(request.username());
|
||||
entity.setDisplayName(request.displayName());
|
||||
entity.setPasswordHash(passwordEncoder.encode(request.password()));
|
||||
|
||||
// ВАЖНО: обрезаем до миллисекунд, чтобы PostgreSQL не изменил точность
|
||||
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
|
||||
entity.setCreatedAt(now);
|
||||
|
||||
userRepository.save(entity);
|
||||
return toDto(entity);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Optional<User> findById(UUID id) {
|
||||
return userRepository.findById(id).map(this::toDto);
|
||||
}
|
||||
|
||||
// Вспомогательный метод для конвертации Entity -> DTO
|
||||
public User toDto(UserEntity entity) {
|
||||
return new User(
|
||||
entity.getId(),
|
||||
entity.getUsername(),
|
||||
entity.getDisplayName(),
|
||||
entity.getCreatedAt()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/* package ru.mtusi.messenger.store;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.dto.Chat;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class ChatStore {
|
||||
|
||||
private final ConcurrentHashMap<UUID, Chat> byId = new ConcurrentHashMap<>();
|
||||
|
||||
public Chat create(String title, List<UUID> memberIds) {
|
||||
UUID id = UUID.randomUUID();
|
||||
Chat chat = new Chat(
|
||||
id,
|
||||
title,
|
||||
List.copyOf(memberIds),
|
||||
OffsetDateTime.now(ZoneOffset.UTC)
|
||||
);
|
||||
byId.put(id, chat);
|
||||
return chat;
|
||||
}
|
||||
|
||||
public Optional<Chat> findById(UUID id) {
|
||||
return Optional.ofNullable(byId.get(id));
|
||||
}
|
||||
|
||||
public List<Chat> findByMember(UUID userId) {
|
||||
List<Chat> result = new ArrayList<>();
|
||||
for (Chat chat : byId.values()) {
|
||||
if (chat.memberIds().contains(userId)) {
|
||||
result.add(chat);
|
||||
}
|
||||
}
|
||||
result.sort(Comparator
|
||||
.comparing(Chat::createdAt)
|
||||
.thenComparing(c -> c.id().toString()));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,43 @@
|
||||
/* package ru.mtusi.messenger.store;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.dto.Message;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
@Component
|
||||
public class MessageStore {
|
||||
|
||||
private static final Comparator<Message> ORDER =
|
||||
Comparator.comparing(Message::createdAt)
|
||||
.thenComparing(m -> m.id().toString());
|
||||
|
||||
private final ConcurrentHashMap<UUID, CopyOnWriteArrayList<Message>> byChat = new ConcurrentHashMap<>();
|
||||
|
||||
public Message create(UUID chatId, UUID senderId, String text) {
|
||||
Message message = new Message(
|
||||
UUID.randomUUID(), chatId, senderId, text,
|
||||
OffsetDateTime.now(ZoneOffset.UTC)
|
||||
);
|
||||
byChat.computeIfAbsent(chatId, k -> new CopyOnWriteArrayList<>()).add(message);
|
||||
return message;
|
||||
}
|
||||
|
||||
public List<Message> findByChat(UUID chatId) {
|
||||
CopyOnWriteArrayList<Message> messages = byChat.get(chatId);
|
||||
if (messages == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Message> sorted = new ArrayList<>(messages);
|
||||
sorted.sort(ORDER);
|
||||
return sorted;
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.util;
|
||||
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Кодирует/декодирует opaque cursor для keyset-пагинации.
|
||||
*
|
||||
* Формат (внутри base64url): scope | createdAt.toString() | uuid
|
||||
* scope — например "chat:<chat_id>", привязывает курсор к ресурсу
|
||||
* createdAt — ISO-8601 строкa UTC с наносекундной точностью
|
||||
* uuid — id последнего элемента
|
||||
*
|
||||
* Клиент видит только base64-строку и не должен её интерпретировать.
|
||||
*/
|
||||
public final class CursorCodec {
|
||||
|
||||
private CursorCodec() {}
|
||||
|
||||
public record Cursor(String scope, OffsetDateTime createdAt, UUID id) {}
|
||||
|
||||
public static String encode(String scope, OffsetDateTime createdAt, UUID id) {
|
||||
String raw = scope + "|" + createdAt.toString() + "|" + id;
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static Cursor decode(String encoded, String expectedScope) {
|
||||
try {
|
||||
String raw = new String(
|
||||
Base64.getUrlDecoder().decode(encoded),
|
||||
StandardCharsets.UTF_8
|
||||
);
|
||||
String[] parts = raw.split("\\|", 3);
|
||||
if (parts.length != 3) {
|
||||
throw new InvalidRequestException("Invalid cursor");
|
||||
}
|
||||
if (!parts[0].equals(expectedScope)) {
|
||||
throw new InvalidRequestException("Cursor belongs to another resource");
|
||||
}
|
||||
OffsetDateTime createdAt = OffsetDateTime.parse(parts[1]);
|
||||
UUID id = UUID.fromString(parts[2]);
|
||||
return new Cursor(parts[0], createdAt, id);
|
||||
} catch (InvalidRequestException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new InvalidRequestException("Invalid cursor");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package ru.mtusi.messenger.worker;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import ru.mtusi.messenger.config.RabbitConfig;
|
||||
import ru.mtusi.messenger.entity.AttachmentEntity;
|
||||
import ru.mtusi.messenger.entity.AttachmentVariantEntity;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.service.StorageService;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HexFormat;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class ImageProcessingWorker {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ImageProcessingWorker.class);
|
||||
private final AttachmentRepository attachmentRepository;
|
||||
private final StorageService storageService;
|
||||
|
||||
public ImageProcessingWorker(AttachmentRepository attachmentRepository, StorageService storageService) {
|
||||
this.attachmentRepository = attachmentRepository;
|
||||
this.storageService = storageService;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = RabbitConfig.QUEUE_NAME)
|
||||
public void processImage(String attachmentIdStr) {
|
||||
UUID attachmentId = UUID.fromString(attachmentIdStr);
|
||||
log.info("Worker received job for attachment: {}", attachmentId);
|
||||
|
||||
AttachmentEntity entity = attachmentRepository.findById(attachmentId).orElse(null);
|
||||
if (entity == null || !"queued".equals(entity.getStatus())) {
|
||||
log.warn("Attachment {} not found or not queued", attachmentId);
|
||||
return; // Сообщение будет подтверждено (ack) автоматически, так как метод завершился без ошибок
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Помечаем как processing
|
||||
entity.setStatus("processing");
|
||||
entity.setUpdatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
attachmentRepository.save(entity);
|
||||
|
||||
// 2. Скачиваем оригинал из staging
|
||||
InputStream stream = storageService.download(entity.getObjectKey());
|
||||
BufferedImage original = ImageIO.read(stream);
|
||||
if (original == null) throw new IllegalArgumentException("Not an image");
|
||||
|
||||
// 3. Делаем thumbnail 256x256 (сохраняя пропорции)
|
||||
BufferedImage thumbnail = createThumbnail(original, 256);
|
||||
ByteArrayOutputStream thumbBytes = new ByteArrayOutputStream();
|
||||
ImageIO.write(thumbnail, "jpg", thumbBytes);
|
||||
byte[] thumbData = thumbBytes.toByteArray();
|
||||
|
||||
// 4. Сохраняем thumbnail в S3 (в постоянный префикс)
|
||||
String thumbKey = "processed/" + attachmentId + "/thumbnail.jpg";
|
||||
storageService.upload(thumbKey, new ByteArrayInputStream(thumbData), thumbData.length, "image/jpeg");
|
||||
|
||||
// 5. Обновляем статус и создаем вариант
|
||||
entity.setStatus("ready");
|
||||
entity.setUpdatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
|
||||
AttachmentVariantEntity variant = new AttachmentVariantEntity();
|
||||
variant.setAttachmentId(entity.getId());
|
||||
variant.setName("thumbnail");
|
||||
variant.setObjectKey(thumbKey);
|
||||
variant.setContentType("image/jpeg");
|
||||
variant.setSizeBytes(thumbData.length);
|
||||
variant.setSha256(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(thumbData)));
|
||||
variant.setWidth(thumbnail.getWidth());
|
||||
variant.setHeight(thumbnail.getHeight());
|
||||
variant.setAttachment(entity);
|
||||
|
||||
entity.getVariants().add(variant);
|
||||
attachmentRepository.save(entity);
|
||||
|
||||
log.info("Successfully processed attachment: {}", attachmentId);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to process attachment: " + attachmentId, e);
|
||||
// При ошибке ставим failed
|
||||
entity.setStatus("failed");
|
||||
entity.setErrorCode("processing_error");
|
||||
entity.setUpdatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
attachmentRepository.save(entity);
|
||||
}
|
||||
}
|
||||
|
||||
private BufferedImage createThumbnail(BufferedImage original, int maxSize) {
|
||||
int width = original.getWidth();
|
||||
int height = original.getHeight();
|
||||
|
||||
// Вычисляем новые размеры, сохраняя пропорции
|
||||
if (width > height) {
|
||||
height = (int) ((double) height / width * maxSize);
|
||||
width = maxSize;
|
||||
} else {
|
||||
width = (int) ((double) width / height * maxSize);
|
||||
height = maxSize;
|
||||
}
|
||||
|
||||
BufferedImage thumbnail = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = thumbnail.createGraphics();
|
||||
g2d.drawImage(original, 0, 0, width, height, null);
|
||||
g2d.dispose();
|
||||
return thumbnail;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user