Files
mtusi2026lab5/internal/attachment/handler.go
T

144 lines
4.1 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"`
// Lab4's shared response contract requires variants=[], even without processing.
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: string(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.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.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 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)
}
}