Files
2026-11-04 20:56:35 +03:00

187 lines
5.6 KiB
Go

package httpapi
import (
"errors"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
)
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
started := time.Now()
result := "client_error"
defer func() {
attributes := metric.WithAttributes(attribute.String("result", result))
s.metrics.attachmentUploads.Add(r.Context(), 1, attributes)
s.metrics.attachmentDuration.Record(r.Context(), time.Since(started).Seconds(), attributes)
}()
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return invalidRequest()
}
filename, valid := attachmentFilename(query)
if !valid {
return invalidRequest()
}
uploaded, err := s.attachments.Upload(r.Context(), attachment.Upload{
ChatID: chatID, OwnerID: user.ID, Filename: filename,
ContentType: r.Header.Get("Content-Type"), ContentLength: r.ContentLength, Body: r.Body,
TraceContext: telemetry.ContextCarrier(r.Context()),
})
if err != nil {
if errors.Is(err, model.ErrCapacity) {
result = "capacity_rejected"
w.Header().Set("Retry-After", "1")
} else if errors.Is(err, model.ErrUnavailable) {
result = "dependency_error"
}
return attachmentError(err)
}
result = "success"
s.metrics.attachmentBytes.Add(r.Context(), uploaded.SizeBytes)
writeJSON(w, http.StatusAccepted, uploaded)
return nil
}
func attachmentFilename(query url.Values) (string, bool) {
if len(query) != 1 || len(query["filename"]) != 1 {
return "", false
}
filename := query["filename"][0]
length := utf8.RuneCountInString(filename)
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
return "", false
}
for _, char := range filename {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", false
}
}
return filename, true
}
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
attachmentID, apiErr := attachmentIDFromRequest(r)
if apiErr != nil {
return apiErr
}
value, err := s.attachments.Metadata(r.Context(), attachmentID, user.ID)
if err != nil {
return attachmentError(err)
}
writeJSON(w, http.StatusOK, value)
return nil
}
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
query, err := url.ParseQuery(r.URL.RawQuery)
variant, valid := attachmentVariant(query)
if err != nil || !valid {
return invalidRequest()
}
attachmentID, apiErr := attachmentIDFromRequest(r)
if apiErr != nil {
return apiErr
}
content, err := s.attachments.Content(r.Context(), attachmentID, user.ID, variant)
if err != nil {
return attachmentError(err)
}
defer func() { _ = content.Body.Close() }()
w.Header().Set("Content-Type", content.Variant.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(content.Variant.SizeBytes, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": content.Attachment.Filename}))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, content.Body); err != nil {
span := trace.SpanFromContext(r.Context())
span.RecordError(err)
span.SetStatus(codes.Error, "response body write failed")
s.logger.WarnContext(r.Context(), "attachment download interrupted", "event", "attachment_download_interrupted", "attachment_id", content.Attachment.ID, "error", err)
}
return nil
}
func attachmentVariant(query url.Values) (string, bool) {
if len(query) == 0 {
return "original", true
}
if len(query) != 1 || len(query["variant"]) != 1 {
return "", false
}
switch query["variant"][0] {
case "original", "thumbnail", "crop", "optimized":
return query["variant"][0], true
default:
return "", false
}
}
func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
attachmentID, valid := canonicalID(parts[3])
if !valid {
return "", invalidRequest()
}
return attachmentID, nil
}
func attachmentError(err error) *apiError {
switch {
case errors.Is(err, model.ErrNotFound):
return notFound()
case errors.Is(err, model.ErrInvalidInput):
return invalidRequest()
case errors.Is(err, model.ErrUnsupportedMedia):
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
case errors.Is(err, model.ErrPayloadTooLarge):
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
case errors.Is(err, model.ErrCapacity):
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
case errors.Is(err, model.ErrConflict):
return &apiError{http.StatusConflict, errorCodeConflict, "attachment is not ready"}
default:
return unavailable()
}
}