package handlers import ( "errors" "io" "mime" "net/http" "strconv" "mtusi2026lab4/internal/application" "mtusi2026lab4/internal/domain" "mtusi2026lab4/internal/transport/http/dto" "mtusi2026lab4/internal/transport/http/middleware" "mtusi2026lab4/internal/transport/http/response" "github.com/google/uuid" ) func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) { requestID := middleware.GetRequestID(r.Context()) currentUser := middleware.GetCurrentUser(r.Context()) attachmentID, ok := parseAttachmentID(w, r, requestID) if !ok { return } attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID) if errors.Is(err, domain.ErrNotFound) { response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "attachment not found", requestID) return } if err != nil { response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, "service is temporarily unavailable", requestID) return } response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID) } func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) { requestID := middleware.GetRequestID(r.Context()) currentUser := middleware.GetCurrentUser(r.Context()) attachmentID, ok := parseAttachmentID(w, r, requestID) if !ok { return } download, err := h.service.DownloadAttachment( r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"), ) switch { case errors.Is(err, domain.ErrNotFound): response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "attachment or variant not found", requestID) return case errors.Is(err, application.ErrAttachmentNotReady): response.WriteError(w, http.StatusConflict, response.CodeConflict, "attachment is not ready", requestID) return case errors.Is(err, application.ErrStorageUnavailable): response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable, "object storage is temporarily unavailable", requestID) return case err != nil: response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "unexpected internal error", requestID) return } defer download.Body.Close() w.Header().Set("Content-Type", download.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10)) w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Content-Disposition", mime.FormatMediaType( "attachment", map[string]string{"filename": download.Filename}, )) w.WriteHeader(http.StatusOK) _, _ = io.Copy(w, download.Body) } func parseAttachmentID( w http.ResponseWriter, r *http.Request, requestID string, ) (string, bool) { parsedID, err := uuid.Parse(r.PathValue("attachment_id")) if err != nil { response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid attachment_id uuid", requestID) return "", false } return parsedID.String(), true }