Extend FileServer to accept options (:expires, :filename)

next
Marcin Kulik 7 years ago
parent 70aedbf12c
commit c1c1ffde70

@ -1,4 +1,4 @@
(ns asciinema.boundary.file-server)
(defprotocol FileServer
(serve [this path]))
(serve [this path] [this path opts]))

@ -6,7 +6,12 @@
(defrecord LocalFileServer [file-store]
file-server/FileServer
(serve [this path]
(response/ok (file-store/input-stream file-store path))))
(file-server/serve this path {}))
(serve [this path {:keys [filename]}]
(let [resp (response/ok (file-store/input-stream file-store path))]
(if filename
(response/header resp "Content-Disposition" (str "attachment; filename=" filename))
resp))))
(defn local-file-server [{:keys [file-store]}]
(->LocalFileServer file-store))

@ -1,15 +1,38 @@
(ns asciinema.component.s3-file-server
(:require [asciinema.boundary.file-server :as file-server]
[aws.sdk.s3 :as s3]
[ring.util.http-response :as response]))
[clj-time.core :as time]
[clj-time.coerce :as timec]
[ring.util.http-response :as response])
(:import com.amazonaws.services.s3.model.ResponseHeaderOverrides
com.amazonaws.services.s3.AmazonS3Client
com.amazonaws.auth.BasicAWSCredentials
com.amazonaws.services.s3.model.GeneratePresignedUrlRequest))
;; TODO support custom expiry date (it's 1 day now)
(defn- s3-client* [cred]
(let [credentials (BasicAWSCredentials. (:access-key cred) (:secret-key cred))]
(AmazonS3Client. credentials)))
(def ^:private s3-client (memoize s3-client*))
(defn- generate-presigned-url [cred bucket path {:keys [expires filename]
:or {expires (-> 1 time/days time/from-now)}}]
(let [client (s3-client cred)
request (GeneratePresignedUrlRequest. bucket path)]
(.setExpiration request (timec/to-date expires))
(when filename
(let [header-overrides (doto (ResponseHeaderOverrides.)
(.setContentDisposition (str "attachment; filename=" filename)))]
(.setResponseHeaders request header-overrides)))
(.toString (.generatePresignedUrl client request))))
(defrecord S3FileServer [cred bucket path-prefix]
file-server/FileServer
(serve [this path]
(file-server/serve this path {}))
(serve [this path opts]
(let [path (str path-prefix path)]
(response/found (s3/generate-presigned-url cred bucket path)))))
(response/found (generate-presigned-url cred bucket path opts)))))
(defn s3-file-server [{:keys [cred bucket path-prefix]}]
(->S3FileServer cred bucket path-prefix))

Loading…
Cancel
Save