Files
mtusi2026lab5/internal/attachment/handler.go
T

169 lines
4.9 KiB
Go

package attachment
import (
"encoding/hex"
"io"
"log/slog"
"mime"
"net/http"
"strconv"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Handler struct{ s *Service }
func NewHandler(s *Service) *Handler { return &Handler{s} }
func (h *Handler) Register(protected, binaryProtected gin.IRouter) {
binaryProtected.POST("/chats/:chat_id/attachments", httpx.WithUser(h.upload))
protected.GET("/attachments/:attachment_id", httpx.WithUser(h.metadata))
binaryProtected.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 []VariantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type VariantResponse 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"`
}
func toResponse(a Attachment) Response {
variants := make([]VariantResponse, 0, len(a.Variants))
for _, v := range a.Variants {
variants = append(variants, VariantResponse{
Name: v.Name, ContentType: v.MIMEType, SizeBytes: v.SizeBytes,
Width: v.Width, Height: v.Height, SHA256: hex.EncodeToString(v.Hash),
})
}
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: string(a.Status),
Variants: variants,
ErrorCode: a.ErrorCode,
CreatedAt: httpx.Timestamp(a.CreatedAt),
UpdatedAt: httpx.Timestamp(a.UpdatedAt),
}
}
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.config.MaxBytes)
input := UploadInput{
ChatID: id,
Filename: names[0],
MIMEType: media,
SizeBytes: c.Request.ContentLength,
}
a, err := h.s.Upload(c.Request.Context(), actor, input, c.Request.Body)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusAccepted, 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 := "original"
if values, ok := c.Request.URL.Query()["variant"]; ok {
if len(values) != 1 {
httpx.Error(c, apperr.Invalid("one variant is required"))
return
}
variant = values[0]
switch variant {
case "original", "thumbnail", "crop", "optimized":
default:
httpx.Error(c, apperr.Invalid("unknown variant"))
return
}
}
a, r, err := h.s.Content(c.Request.Context(), actor, id, variant)
if err != nil {
httpx.Error(c, err)
return
}
defer func() {
if err := r.Close(); err != nil {
slog.Warn("download reader close failed", "request_id", httpx.RequestID(c), "error", err)
}
}()
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)
}
}