🎉 Create add-image-from-url service

This commit is contained in:
Andrés Moya 2020-06-24 11:37:07 +02:00 committed by Andrey Antukh
parent c0cbb5877b
commit 85bae6cf26
4 changed files with 86 additions and 18 deletions

View file

@ -10,6 +10,7 @@
(ns uxbox.services.mutations.images
(:require
[clojure.spec.alpha :as s]
[clojure.java.io :as io]
[datoteka.core :as fs]
[uxbox.common.exceptions :as ex]
[uxbox.common.spec :as us]
@ -22,7 +23,8 @@
[uxbox.services.queries.teams :as teams]
[uxbox.tasks :as tasks]
[uxbox.util.storage :as ust]
[uxbox.util.time :as dt]))
[uxbox.util.time :as dt]
[uxbox.util.http :as http]))
(def thumbnail-options
{:width 800
@ -35,7 +37,7 @@
(s/def ::profile-id ::us/uuid)
(s/def ::library-id ::us/uuid)
(s/def ::team-id ::us/uuid)
(s/def ::url ::us/url)
;; --- Create Library
@ -108,6 +110,7 @@
;; --- Create Image (Upload)
(declare download-image)
(declare create-image)
(declare persist-image-on-fs)
(declare persist-image-thumbnail-on-fs)
@ -128,10 +131,43 @@
(s/def ::content ::upload)
(s/def ::upload-image
(s/keys :req-un [::profile-id ::name ::content ::library-id]
(s/def ::add-image-from-url
(s/keys :req-un [::profile-id ::library-id ::name ::url]
:opt-un [::id]))
(s/def ::upload-image
(s/keys :req-un [::profile-id ::library-id ::name ::content]
:opt-un [::id]))
(sm/defmutation ::add-image-from-url
[{:keys [library-id profile-id url] :as params}]
(db/with-atomic [conn db/pool]
(let [lib (select-library-for-update conn library-id)]
(teams/check-edition-permissions! conn profile-id (:team-id lib))
(let [content (download-image url)
params' (merge params {:content content})]
(create-image conn params')))))
(defn download-image
[url]
(let [result (http/get! url {:as :byte-array})
data (:body result)
content-type (get (:headers result) "content-type")
format (images/mtype->format content-type)]
(if (nil? format)
(ex/raise :type :validation
:code :image-type-not-allowed
:hint "Seems like the url points to an invalid image.")
(let [tempfile (fs/create-tempfile)
base-filename (get (fs/split-ext (fs/name tempfile)) 0)
filename (str base-filename (images/format->extension format))]
(with-open [ostream (io/output-stream tempfile)]
(.write ostream data))
{:filename filename
:size (count data)
:tempfile tempfile
:content-type content-type}))))
(sm/defmutation ::upload-image
[{:keys [library-id profile-id] :as params}]
(db/with-atomic [conn db/pool]

View file

@ -14,6 +14,11 @@
(def default-client
(delay (http/build-client {:executor @px/default-executor})))
(defn get!
[url opts]
(let [opts' (merge {:client @default-client :as :string} opts)]
(http/get url nil opts')))
(defn send!
[req]
(http/send req {:client @default-client :as :string}))