69 lines
2.6 KiB
Go
69 lines
2.6 KiB
Go
package chat
|
|
|
|
import (
|
|
"context"
|
|
"mime"
|
|
"net/http"
|
|
"time"
|
|
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
|
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
func (h *Chat) WithAttachments(service *attachment.Service) *Chat { h.attachments = service; return h }
|
|
func (h *Chat) uploadAttachment(c echo.Context) error {
|
|
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: c.Param("chat_id")})
|
|
if err != nil || !ok {
|
|
return err
|
|
}
|
|
filename, present, err := oneQueryValue(c, "filename")
|
|
if err != nil || !present {
|
|
return h.invalid(c, "Требуется один filename")
|
|
}
|
|
if c.Request().ContentLength > attachment.MaxBytes {
|
|
return h.writeError(c, 413, "payload_too_large", "Файл превышает 10 MiB")
|
|
}
|
|
// Both socket reads and the application operation have a fixed deadline.
|
|
deadline := time.Now().Add(attachment.UploadTimeout)
|
|
_ = http.NewResponseController(c.Response().Writer).SetReadDeadline(deadline)
|
|
defer http.NewResponseController(c.Response().Writer).SetReadDeadline(time.Time{})
|
|
c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, attachment.MaxBytes+1)
|
|
a, err := h.attachments.Upload(c.Request().Context(), chat.ID, authenticatedUser(c).ID, filename, c.Request().Header.Get("Content-Type"), c.Request().Body)
|
|
if err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
return c.JSON(http.StatusCreated, a)
|
|
}
|
|
func (h *Chat) getAttachment(c echo.Context) error {
|
|
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
|
if err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
return c.JSON(http.StatusOK, a)
|
|
}
|
|
func (h *Chat) attachmentContent(c echo.Context) error {
|
|
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
|
if err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
variant, present, err := oneQueryValue(c, "variant")
|
|
if err != nil {
|
|
return h.invalid(c, "Некорректный variant")
|
|
}
|
|
if present && variant != "original" {
|
|
return h.writeError(c, 404, "not_found", "Вариант не найден")
|
|
}
|
|
ctx, cancel := context.WithTimeout(c.Request().Context(), 45*time.Second)
|
|
defer cancel()
|
|
obj, err := h.attachments.Content(ctx, a)
|
|
if err != nil {
|
|
return h.useCaseError(c, err)
|
|
}
|
|
defer obj.Close()
|
|
c.Response().Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
|
|
c.Response().Header().Set("X-Content-Type-Options", "nosniff")
|
|
c.Response().Header().Set("Cache-Control", "private, no-store")
|
|
return c.Stream(http.StatusOK, a.ContentType, obj)
|
|
}
|