Files
mtusi2026lab4/internal/attachment/handler.go
T

122 lines
3.7 KiB
Go

package attachment
import (
"encoding/hex"
"io"
"log/slog"
"mime"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
)
type Handler struct{ s *Service }
func NewHandler(s *Service) *Handler { return &Handler{s} }
func (h *Handler) Register(protected, binary gin.IRouter) {
binary.POST("/chats/:chat_id/attachments", httpx.WithUser(h.upload))
protected.GET("/attachments/:attachment_id", httpx.WithUser(h.metadata))
binary.GET("/attachments/:attachment_id/content", httpx.WithUser(h.content))
}
type Response 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 string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func toResponse(a Attachment) Response {
return Response{
ID: a.ID.String(), ChatID: a.ChatID.String(), OwnerID: a.OwnerID.String(), Filename: a.Filename, ContentType: a.MIMEType, SizeBytes: a.SizeBytes, SHA256: hex.EncodeToString(a.FileHash), Status: a.Status, Variants: []any{}, CreatedAt: httpx.Timestamp(a.CreatedAt), UpdatedAt: httpx.Timestamp(a.CreatedAt),
}
}
func (h *Handler) upload(c *gin.Context, actor uuid.UUID) {
id, err := ident.Parse(c.Param("chat_id"))
if err != nil {
httpx.Error(c, apperr.Invalid("chat_id must be a UUID"))
return
}
names := c.Request.URL.Query()["filename"]
if len(names) != 1 {
httpx.Error(c, apperr.Invalid("one filename is required"))
return
}
if err := ValidateFilename(names[0]); err != nil {
httpx.Error(c, err)
return
}
media, params, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || len(params) > 0 {
httpx.Error(c, apperr.UnsupportedMedia("Content-Type must be image/png or image/jpeg"))
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.s.maxBytes)
a, err := h.s.Upload(c.Request.Context(), actor, id, names[0], media, c.Request.ContentLength, c.Request.Body)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusCreated, toResponse(a))
}
func attachmentID(c *gin.Context) (uuid.UUID, error) {
id, err := ident.Parse(c.Param("attachment_id"))
if err != nil {
return uuid.Nil, apperr.Invalid("attachment_id must be a UUID")
}
return id, nil
}
func (h *Handler) metadata(c *gin.Context, actor uuid.UUID) {
id, err := attachmentID(c)
if err != nil {
httpx.Error(c, err)
return
}
a, err := h.s.Get(c.Request.Context(), actor, id)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, toResponse(a))
}
func (h *Handler) content(c *gin.Context, actor uuid.UUID) {
id, err := attachmentID(c)
if err != nil {
httpx.Error(c, err)
return
}
variant, present := c.GetQuery("variant")
if present && variant != "original" {
httpx.Error(c, apperr.Invalid("variant must be original"))
return
}
a, r, err := h.s.Content(c.Request.Context(), actor, id)
if err != nil {
httpx.Error(c, err)
return
}
defer r.Close()
c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Content-Type", a.MIMEType)
c.Header("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
c.Status(http.StatusOK)
if _, err := io.CopyN(c.Writer, r, a.SizeBytes); err != nil {
slog.Error("download interrupted", "request_id", httpx.RequestID(c), "error", err)
}
}