forked from mtusi2026/mtusi2026lab4
лаба 4 на оценку 5
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentVariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status domain.AttachmentStatus `json:"status"`
|
||||
Variants []AttachmentVariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func AttachmentFromDomain(attachment domain.Attachment) AttachmentResponse {
|
||||
variants := make([]AttachmentVariantResponse, 0, len(attachment.Variants))
|
||||
for _, variant := range attachment.Variants {
|
||||
variants = append(variants, AttachmentVariantResponse{
|
||||
Name: variant.Name,
|
||||
ContentType: variant.ContentType,
|
||||
SizeBytes: variant.SizeBytes,
|
||||
Width: variant.Width,
|
||||
Height: variant.Height,
|
||||
SHA256: variant.SHA256,
|
||||
})
|
||||
}
|
||||
return AttachmentResponse{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256,
|
||||
Status: attachment.Status,
|
||||
Variants: variants,
|
||||
ErrorCode: attachment.ErrorCode,
|
||||
CreatedAt: attachment.CreatedAt,
|
||||
UpdatedAt: attachment.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,17 @@ import (
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
@@ -24,9 +26,14 @@ type MessagePageResponse struct {
|
||||
}
|
||||
|
||||
func MessageFromDomain(message domain.Message) MessageResponse {
|
||||
attachmentIDs := append([]string(nil), message.AttachmentIDs...)
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = make([]string, 0)
|
||||
}
|
||||
|
||||
return MessageResponse{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, CreatedAt: message.CreatedAt,
|
||||
Text: message.Text, AttachmentIDs: attachmentIDs, CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: chatID,
|
||||
Text: request.Text,
|
||||
AttachmentIDs: request.AttachmentIDs,
|
||||
Method: http.MethodPost,
|
||||
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
|
||||
IdempotencyKey: idempotencyKey,
|
||||
@@ -53,6 +54,11 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
"Idempotency-Key is already used for another request", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrAttachmentNotReady) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab4/internal/application"
|
||||
"mtusi2026lab4/internal/domain"
|
||||
"mtusi2026lab4/internal/transport/http/dto"
|
||||
"mtusi2026lab4/internal/transport/http/middleware"
|
||||
"mtusi2026lab4/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
download, err := h.service.DownloadAttachment(
|
||||
r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"),
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment or variant not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrAttachmentNotReady):
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError,
|
||||
"unexpected internal error", requestID)
|
||||
return
|
||||
}
|
||||
defer download.Body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", download.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType(
|
||||
"attachment", map[string]string{"filename": download.Filename},
|
||||
))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.Copy(w, download.Body)
|
||||
}
|
||||
|
||||
func parseAttachmentID(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
requestID string,
|
||||
) (string, bool) {
|
||||
parsedID, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid attachment_id uuid", requestID)
|
||||
return "", false
|
||||
}
|
||||
return parsedID.String(), true
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab4/internal/application"
|
||||
"mtusi2026lab4/internal/domain"
|
||||
"mtusi2026lab4/internal/transport/http/dto"
|
||||
"mtusi2026lab4/internal/transport/http/middleware"
|
||||
"mtusi2026lab4/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if filename == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"filename query parameter is required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
contentType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || len(parameters) != 0 ||
|
||||
(contentType != "image/png" && contentType != "image/jpeg") {
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be image/png or image/jpeg", requestID)
|
||||
return
|
||||
}
|
||||
if r.ContentLength > domain.MaxAttachmentSizeBytes {
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB", requestID)
|
||||
return
|
||||
}
|
||||
if r.Body == nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"attachment body is required", requestID)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
attachment, err := h.service.UploadAttachment(
|
||||
r.Context(),
|
||||
application.UploadAttachmentCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: parsedChatID.String(),
|
||||
Filename: filename,
|
||||
DeclaredContentType: contentType,
|
||||
Body: r.Body,
|
||||
},
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, application.ErrPayloadTooLarge):
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB or 40 million pixels", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrUnsupportedMediaType), errors.Is(err, application.ErrInvalidImage):
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"body is not a valid PNG/JPEG matching the declared Content-Type", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrInvalidInput):
|
||||
message := strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": ")
|
||||
response.WriteError(w, http.StatusBadRequest,
|
||||
response.CodeInvalidRequest, message, requestID)
|
||||
return
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound,
|
||||
response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusCreated, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
Reference in New Issue
Block a user