package handlers import ( "context" "errors" "github.com/google/uuid" "io" "log" "messenger/src/backend/repositories" "messenger/src/backend/services" "net/http" "net/url" "strconv" "strings" "time" ) func uploadAttachmentHandler(chats *services.ChatService, attachments *services.AttachmentService) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { requestID := newRequestID() w.Header().Set("X-Request-Id", requestID) if r.Method != http.MethodPost { writeError(w, 405, "method_not_allowed", "method not allowed", requestID) return } userID, ok := requestUserID(w, r, requestID) if !ok { return } raw := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/v1/chats/"), "/attachments") chatID, err := uuid.Parse(raw) if err != nil { writeError(w, 400, "invalid_request", "invalid chat id", requestID) return } if _, err = chats.Get(r.Context(), userID, chatID.String()); err != nil { writeServiceError(w, err, requestID) return } query, err := urlQuery(r) if err != nil { writeServiceError(w, err, requestID) return } filenames := query["filename"] if len(filenames) != 1 { writeError(w, 400, "invalid_request", "exactly one filename is required", requestID) return } if err = services.ValidateFilename(filenames[0]); err != nil { writeServiceError(w, err, requestID) return } if r.ContentLength > services.MaxUploadBytes { writeServiceError(w, services.ErrPayloadTooLarge, requestID) return } r.Body = http.MaxBytesReader(w, r.Body, services.MaxUploadBytes) ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) defer cancel() attachment, err := attachments.Upload(ctx, userID, chatID.String(), filenames[0], r.Header.Get("Content-Type"), r.Body) var tooLarge *http.MaxBytesError if errors.As(err, &tooLarge) { err = services.ErrPayloadTooLarge } if err != nil { writeServiceError(w, err, requestID) return } writeJSON(w, 202, attachment) } } func attachmentHandler(attachments *services.AttachmentService) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { requestID := newRequestID() w.Header().Set("X-Request-Id", requestID) if r.Method != http.MethodGet { writeError(w, 405, "method_not_allowed", "method not allowed", requestID) return } userID, ok := requestUserID(w, r, requestID) if !ok { return } path := strings.TrimPrefix(r.URL.Path, "/api/v1/attachments/") parts := strings.Split(path, "/") if len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") { writeServiceError(w, services.ErrAttachmentNotFound, requestID) return } id, err := uuid.Parse(parts[0]) if err != nil { writeError(w, 400, "invalid_request", "invalid attachment id", requestID) return } a, err := attachments.Get(r.Context(), id.String(), userID) if err != nil { writeServiceError(w, err, requestID) return } if len(parts) == 1 { writeJSON(w, 200, a) return } query, err := urlQuery(r) if err != nil { writeServiceError(w, err, requestID) return } if a.Status != "ready" { writeServiceError(w, services.ErrConflict, requestID) return } if variants, exists := query["variant"]; exists { if len(variants) != 1 { writeError(w, 400, "invalid_request", "invalid variant", requestID) return } if variants[0] == "thumbnail" || variants[0] == "crop" || variants[0] == "optimized" { found := false for _, raw := range a.Variants { if v, ok := raw.(map[string]any); ok && v["name"] == variants[0] { a.ObjectKey = repositories.VariantObjectKey(a.ID, a.PipelineVersion, variants[0]) a.ContentType = v["content_type"].(string) a.SizeBytes = int64(v["size_bytes"].(float64)) found = true break } } if !found { writeServiceError(w, services.ErrAttachmentNotFound, requestID) return } } else if variants[0] != "original" { writeServiceError(w, services.ErrAttachmentNotFound, requestID) return } } ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) defer cancel() content, err := attachments.Content(ctx, a) if err != nil { writeServiceError(w, err, requestID) return } defer content.Close() w.Header().Set("Content-Type", a.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10)) w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Cache-Control", "private, no-store") w.WriteHeader(200) if _, err = io.Copy(w, content); err != nil { log.Printf("attachment download interrupted, request %s", requestID) } } } func urlQuery(r *http.Request) (url.Values, error) { q, err := url.ParseQuery(r.URL.RawQuery) if err != nil { return nil, services.InvalidInput{Message: "invalid query"} } return q, nil }