Files
mtusi2026lab4/service/internal/adapter/controller/http/attachmentHandler.go
2026-11-13 11:05:05 +03:00

92 lines
2.8 KiB
Go

package http
import (
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/auth/jwtprovider"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/router"
"gitea.privcloud.tech/mtusi2026/internal/service/attachment"
"io"
"net/http"
"strconv"
"strings"
)
type AttachmentHandler struct {
router router.Router
provider jwtprovider.Provider
svc *attachment.Service
}
func NewAttachmentHandler(r router.Router, p jwtprovider.Provider, s *attachment.Service) Handler {
return &AttachmentHandler{r, p, s}
}
func (h *AttachmentHandler) RegisterRoutes() {
h.router.Private("POST", "/api/v1/chats/{chat_id}/attachments", h.Upload)
h.router.Private("GET", "/api/v1/attachments/{attachment_id}", h.Get)
h.router.Private("GET", "/api/v1/attachments/{attachment_id}/content", h.Get)
}
func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
user, e := framework.ParseToken(r, h.provider)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
id, e := framework.ParseIDFromPathParam(r.Context(), w, r, "chat_id")
if e != nil {
return
}
values := r.URL.Query()["filename"]
if len(values) != 1 {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one filename"))
return
}
a, e := h.svc.Upload(w, r, user.UserID, id, values[0])
if e != nil {
if apperr.CodeFromError(e) == apperr.CodeTooManyRequests {
w.Header().Set("Retry-After", "1")
}
framework.JSONError(r.Context(), w, e)
return
}
framework.JSONResponse(w, http.StatusCreated, a)
}
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
user, e := framework.ParseToken(r, h.provider)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
id, e := framework.ParseIDFromPathParam(r.Context(), w, r, "attachment_id")
if e != nil {
return
}
a, e := h.svc.Get(r.Context(), user.UserID, id)
if e != nil {
framework.JSONError(r.Context(), w, e)
return
}
if !strings.HasSuffix(r.URL.Path, "/content") {
framework.JSONResponse(w, 200, a.Public)
return
}
if v := r.URL.Query().Get("variant"); v != "" && v != "original" {
framework.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "invalid variant"))
return
}
obj, e := h.svc.Store.Get(r.Context(), a.Key)
if e != nil {
framework.JSONError(r.Context(), w, attachment.Unavailable())
return
}
defer obj.Body.Close()
w.Header().Set("Content-Type", string(a.Public.ContentType))
w.Header().Set("Content-Length", strconv.Itoa(a.Public.SizeBytes))
w.Header().Set("X-Content-Type-Options", "nosniff")
// Once streaming has started a transport failure terminates the response; no JSON
// error can be appended to an image. Content-Length exposes incomplete downloads.
if _, e = io.Copy(w, obj.Body); e != nil {
panic(http.ErrAbortHandler)
}
}