LCOV - code coverage report
Current view: top level - matchscore/api - media.clj Coverage Total Hit
Test: lcov.info Lines: 84.8 % 112 95
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.api.media
       2              :   "Authenticated media configuration and one-file multipart upload endpoints."
       3              :   (:require
       4              :    [matchscore.access.core :as access]
       5              :    [matchscore.access.resource :as access-resource]
       6              :    [matchscore.media.db :as media-db]
       7              :    [matchscore.media.image :as image]
       8              :    [matchscore.media.service :as media]
       9              :    [ring.middleware.multipart-params :as multipart]
      10              :    [ring.util.http-status :as status]
      11              :    [schemas.api.core :as api-schemas])
      12              :   (:import
      13              :    (java.nio.file Files)))
      14              : 
      15              : 
      16            4 : (defn media-config-handler
      17              :  {:summary "Get media upload limits and availability"}
      18              :  [{:keys [config]}]
      19            4 :  {:status status/ok
      20            9 :   :body   {:data {:uploads-enabled (media/uploads-enabled? config)
      21            1 :                   :max-images      media-db/max-images
      22            3 :                   :max-file-bytes  (:max-file-bytes image/default-limits)}}})
      23              : 
      24              : 
      25            4 : (defn- param
      26              :   [params kebab snake]
      27           26 :   (or (get params kebab) (get params snake) (get params (name kebab)) (get params (name snake))))
      28              : 
      29              : 
      30            4 : (defn- upload-scope
      31              :   [request]
      32           10 :   {:resource-type (param (:params request) :resource-type :resource_type)
      33            7 :    :resource-id   (param (:params request) :resource-id :resource_id)})
      34              : 
      35              : 
      36            4 : (defn- authorize-scope!
      37              :   [{:keys [ctx auth-headers]
      38              :     :as   request}]
      39            1 :   (let [{:keys [resource-type resource-id]
      40              :          :as   scope}
      41            3 :         (upload-scope request)
      42            3 :         user-id (:user/uuid auth-headers)
      43            5 :         ctx (assoc ctx :auth-headers auth-headers)]
      44            8 :     (when-not (contains? #{"event" "template"} resource-type)
      45            0 :       (throw (ex-info "resource_type must be event or template" {:type :media/invalid-scope})))
      46            2 :     (if resource-id
      47            1 :       (let [obj
      48            7 :             ((if (= resource-type "event") access-resource/event-obj access-resource/template-obj)
      49            1 :              ctx
      50            1 :              resource-id)]
      51            3 :         (when-not obj (throw (ex-info "Resource not found" {:type :api-not-found})))
      52              :         ;; Use the same entity-local object and :update policy as each form
      53              :         ;; endpoint. Event uploads intentionally do not inherit template-admin
      54              :         ;; management rights.
      55            7 :         (access/authorize! ctx user-id "*" obj :update))
      56           10 :       (access/authorize! ctx user-id "*" (access-resource/create-obj ctx resource-type) :create))
      57            1 :     scope))
      58              : 
      59              : 
      60            4 : (defn- upload-error-response
      61              :   [e]
      62            4 :   (let [{:keys [type code]} (ex-data e)
      63            5 :         response-status     (cond (= type :api-not-found) status/not-found
      64            4 :                                   (= type :api-forbidden) status/forbidden
      65            0 :                                   (= type :media/quota-exceeded) status/too-many-requests
      66            0 :                                   (or (= code :too-large) (= code :too-many-pixels)) 413
      67            0 :                                   (contains? #{:media/invalid-scope :media/invalid-asset} type)
      68            0 :                                   status/unprocessable-entity
      69              : 
      70            0 :                                   (= code :invalid-image) status/unprocessable-entity
      71            0 :                                   (contains? #{:media/unavailable :media/storage-unavailable} type)
      72            0 :                                   status/service-unavailable
      73              : 
      74            0 :                                   :else status/unprocessable-entity)]
      75            4 :     {:status response-status
      76            3 :      :body   {:message (.getMessage e)}}))
      77              : 
      78              : 
      79            4 : (defn media-upload-handler
      80              :  {:summary "Upload one event/template gallery image"}
      81              :  [{:keys [ctx auth-headers]
      82              :    :as   request}]
      83            1 :  (try
      84              :    ;; Query scope is authorized before the multipart iterator reads any bytes.
      85            1 :    (let [{:keys [resource-type resource-id]
      86              :           :as   query-scope}
      87            3 :          (authorize-scope! request)
      88            2 :          parsed (multipart/multipart-params-request
      89            1 :                  request
      90            7 :                  {:max-file-size  (:max-file-bytes image/default-limits)
      91              :                   ;; Ring counts form fields as items too; allow file +
      92              :                   ;; the two optional repeated scope fields, then enforce
      93              :                   ;; exactly one actual file below.
      94              :                   :max-file-count 3})
      95            3 :          form (:multipart-params parsed)
      96            5 :          form-type (param form :resource-type :resource_type)
      97            5 :          form-id (param form :resource-id :resource_id)
      98            7 :          file (or (get form "file") (get form :file))
      99           15 :          files (filter #(and (map? %) (:tempfile %)) (vals form))]
     100            1 :      (when
     101           13 :        (or (and form-type (not= form-type resource-type)) (and form-id (not= form-id resource-id)))
     102            0 :        (throw
     103            0 :         (ex-info
     104              :          "Query and multipart upload scopes disagree"
     105            0 :          {:type  :media/invalid-scope
     106            0 :           :query query-scope})))
     107           18 :      (when-not (and (= 1 (count files)) (map? file) (:tempfile file))
     108            0 :        (throw (ex-info "Multipart field file is required" {:type :media/invalid-image})))
     109            7 :      (let [bytes  (Files/readAllBytes (.toPath ^java.io.File (:tempfile file)))
     110            9 :            result (media/upload! ctx (:user/uuid auth-headers) resource-type resource-id bytes)]
     111            4 :        {:status status/created
     112            3 :         :body   {:data result}}))
     113              :    (catch org.apache.commons.fileupload2.core.FileUploadException _e
     114            0 :      {:status 413
     115            0 :       :body   {:message "Uploaded content exceeded limits."}})
     116            3 :    (catch clojure.lang.ExceptionInfo e (upload-error-response e))))
     117              : 
     118              : 
     119            4 : (defn- fraction
     120              :   "A focus coordinate from the JSON body: a number in 0..1, or nil."
     121              :   [v]
     122           32 :   (when (and (number? v) (<= 0 v 1)) (double v)))
     123              : 
     124              : 
     125            4 : (defn- authorize-focus!
     126              :   "The uploader may always set the focus (covers images not saved into a gallery
     127              :   yet). Anyone else needs the same :update right the gallery form save needs on
     128              :   an event or template whose gallery contains the image."
     129              :   [ctx user-id asset]
     130            3 :   (when-not
     131            5 :     (or
     132            9 :      (= (str user-id) (str (:uploader-uuid asset)))
     133            8 :      (let [{:keys [event template]} (media-db/asset-gallery-owners (:pg ctx) (:uuid asset))
     134            1 :            allowed? (fn [obj-fn id]
     135           10 :                      (when-let [obj (obj-fn ctx id)]
     136           11 :                        (true? (access/allowed? (:enforcer ctx) user-id "*" obj :update))))]
     137            5 :        (or
     138            8 :         (some #(allowed? access-resource/event-obj %) event)
     139            3 :         (some #(allowed? access-resource/template-obj %) template))))
     140            7 :     (throw (ex-info "Forbidden" {:type :api-forbidden}))))
     141              : 
     142              : 
     143            4 : (defn media-focus-handler
     144              :  {:malli/schema [:=>
     145              :                  [:cat api-schemas/RingRequest api-schemas/MediaFocusRequestSchema]
     146              :                  api-schemas/MediaFocusResponseSchema]
     147              :   :malli/parameters {:path api-schemas/MediaFocusPathParamsSchema}
     148              :   :summary "Set the focus point of a gallery image"
     149              :   :description
     150              :   "Body {x, y}: fractions of the image width/height (0..1) that must stay visible when a
     151              :    card crops the image; both null clear it. Allowed for the uploader and for editors of an
     152              :    event or template whose gallery contains the image."}
     153            0 :  ([request] (media-focus-handler request (:body request)))
     154              :  ([{:keys [ctx auth-headers route-params]} body]
     155           10 :   (media/ensure-gallery-mutations-enabled! (:config ctx))
     156            8 :   (let [user-id (:user/uuid auth-headers)
     157            6 :         asset-id (:asset-id route-params)
     158           10 :         ctx (assoc ctx :auth-headers auth-headers)
     159            6 :         raw-x (get body :x)
     160            6 :         raw-y (get body :y)
     161            6 :         x (fraction raw-x)
     162            6 :         y (fraction raw-y)
     163           65 :         clear? (and (map? body) (contains? body :x) (contains? body :y) (nil? raw-x) (nil? raw-y))]
     164           30 :     (cond (not (or clear? (and x y)))
     165            8 :           {:status status/unprocessable-entity
     166            6 :            :body   {:message "x and y must both be numbers between 0 and 1, or both null"}}
     167              : 
     168           16 :           (nil? (parse-uuid (str asset-id)))
     169            8 :           {:status status/not-found
     170            6 :            :body   {:message "Image not found."}}
     171              : 
     172              :           :else
     173            7 :           (let [asset (media-db/asset-by-id (:pg ctx) asset-id)]
     174           17 :             (if-not (and asset (= "ready" (:state asset)) user-id)
     175            6 :               {:status (if asset status/forbidden status/not-found)
     176            5 :                :body   {:message (if asset "Forbidden" "Image not found.")}}
     177            1 :               (do
     178            5 :                 (authorize-focus! ctx user-id asset)
     179            9 :                 (let [updated (media-db/set-focus! (:pg ctx) asset-id x y)]
     180            4 :                   {:status status/ok
     181           11 :                    :body   {:data {:id      (str (:uuid updated))
     182            9 :                                    :focus-x (some->
     183            3 :                                               (:focus-x updated)
     184              :                                               double)
     185            9 :                                    :focus-y (some->
     186            3 :                                               (:focus-y updated)
     187              :                                               double)}}}))))))))
        

Generated by: LCOV version 2.0-1