phase 2
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
import ru.mtusi.messenger.service.AttachmentService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class AttachmentController implements AttachmentsApi {
|
||||
private final AttachmentService service;
|
||||
|
||||
@Override
|
||||
public ResponseEntity<AttachmentDTO> uploadAttachment(UUID chatId, String filename, byte[] body, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.status(201).body(service.upload(chatId, principal.userId(), filename, body));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<AttachmentDTO> getAttachment(UUID attachmentId, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return ResponseEntity.ok(service.getMetadata(attachmentId, principal.userId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<byte[]> downloadAttachment(UUID attachmentId, String variant, SessionPrincipal principal) {
|
||||
var downloaded = service.download(attachmentId, principal.userId(), variant);
|
||||
|
||||
byte[] bytes;
|
||||
try (var in = downloaded.stream()) {
|
||||
bytes = in.readAllBytes();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to read attachment stream", e);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(downloaded.contentType()))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + downloaded.filename() + "\"")
|
||||
.body(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Validated
|
||||
@Tag(name = "Attachments", description = "Загрузка и скачивание вложений (PNG/JPEG) в чатах.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface AttachmentsApi {
|
||||
|
||||
@Operation(
|
||||
operationId = "uploadAttachment",
|
||||
summary = "Принять один PNG/JPEG, до 10 MiB",
|
||||
tags = { "Attachments" },
|
||||
responses = {
|
||||
@ApiResponse(responseCode = "201", description = "Успех", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = AttachmentDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "400", description = "Неверный запрос", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "413", description = "Превышен лимит", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "415", description = "Неподдерживаемый тип", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = { @SecurityRequirement(name = "bearerAuth") }
|
||||
)
|
||||
@RequestMapping(
|
||||
method = RequestMethod.POST,
|
||||
value = "/api/v1/chats/{chat_id}/attachments",
|
||||
consumes = { MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE },
|
||||
produces = { MediaType.APPLICATION_JSON_VALUE }
|
||||
)
|
||||
ResponseEntity<AttachmentDTO> uploadAttachment(
|
||||
@Parameter(name = "chat_id", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("chat_id") UUID chatId,
|
||||
@Parameter(name = "filename", required = true, in = ParameterIn.QUERY)
|
||||
@Size(min = 1, max = 255) @RequestParam("filename") String filename,
|
||||
@RequestBody byte[] body,
|
||||
@AuthenticationPrincipal SessionPrincipal principal
|
||||
);
|
||||
|
||||
@Operation(
|
||||
operationId = "getAttachment",
|
||||
summary = "Метаданные вложения, доступ участникам чата",
|
||||
tags = { "Attachments" },
|
||||
responses = {
|
||||
@ApiResponse(responseCode = "200", description = "Успех", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = AttachmentDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "400", description = "Неверный запрос", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "409", description = "Конфликт", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = { @SecurityRequirement(name = "bearerAuth") }
|
||||
)
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/attachments/{attachment_id}",
|
||||
produces = { MediaType.APPLICATION_JSON_VALUE }
|
||||
)
|
||||
ResponseEntity<AttachmentDTO> getAttachment(
|
||||
@Parameter(name = "attachment_id", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("attachment_id") UUID attachmentId,
|
||||
@AuthenticationPrincipal SessionPrincipal principal
|
||||
);
|
||||
|
||||
@Operation(
|
||||
operationId = "downloadAttachment",
|
||||
summary = "Скачать байты через авторизованный API",
|
||||
tags = { "Attachments" },
|
||||
responses = {
|
||||
@ApiResponse(responseCode = "200", description = "Успех", content = {
|
||||
@Content(mediaType = "image/png", schema = @Schema(type = "string", format = "binary")),
|
||||
@Content(mediaType = "image/jpeg", schema = @Schema(type = "string", format = "binary")),
|
||||
@Content(mediaType = "image/webp", schema = @Schema(type = "string", format = "binary"))
|
||||
}),
|
||||
@ApiResponse(responseCode = "400", description = "Неверный запрос", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "401", description = "Нет действительной аутентификации", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "404", description = "Объект отсутствует или недоступен", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "409", description = "Конфликт", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "429", description = "Ограничение частоты запросов", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "503", description = "Зависимость недоступна", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(responseCode = "500", description = "Неожиданная ошибка без внутренних деталей", content = {
|
||||
@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = { @SecurityRequirement(name = "bearerAuth") }
|
||||
)
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/attachments/{attachment_id}/content",
|
||||
produces = { "image/png", "image/jpeg", "image/webp" }
|
||||
)
|
||||
ResponseEntity<byte[]> downloadAttachment(
|
||||
@Parameter(name = "attachment_id", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("attachment_id") UUID attachmentId,
|
||||
@Parameter(name = "variant", in = ParameterIn.QUERY)
|
||||
@RequestParam(value = "variant", required = false, defaultValue = "original") String variant,
|
||||
@AuthenticationPrincipal SessionPrincipal principal
|
||||
);
|
||||
}
|
||||
+12
@@ -147,6 +147,18 @@ public class GlobalExceptionHandler {
|
||||
"Missing header: " + e.getHeaderName(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnsupportedMediaTypeException.class)
|
||||
public ResponseEntity<ErrorDTO> unsupportedMedia(UnsupportedMediaTypeException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(StorageUnavailableException.class)
|
||||
public ResponseEntity<ErrorDTO> storageUnavailable(StorageUnavailableException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE, e.getMessage(), req);
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorDTO> respond(HttpStatus status,
|
||||
ErrorErrorDTO.CodeEnum code,
|
||||
String message,
|
||||
|
||||
Reference in New Issue
Block a user