Serve asciicast files from Phoenix
parent
51d6559b27
commit
867509a328
@ -0,0 +1,4 @@
|
||||
defmodule Asciinema.FileStore do
|
||||
@doc "Serves file at given path in store"
|
||||
@callback serve_file(conn :: %Plug.Conn{}, path :: String.t, filename :: String.t) :: %Plug.Conn{}
|
||||
end
|
@ -0,0 +1,29 @@
|
||||
defmodule Asciinema.FileStore.Local do
|
||||
@behaviour Asciinema.FileStore
|
||||
import Plug.Conn
|
||||
alias Plug.MIME
|
||||
|
||||
def serve_file(conn, path, nil) do
|
||||
do_serve_file(conn, path)
|
||||
end
|
||||
def serve_file(conn, path, filename) do
|
||||
conn
|
||||
|> put_resp_header("content-disposition", "attachment; filename=#{filename}")
|
||||
|> do_serve_file(path)
|
||||
end
|
||||
|
||||
defp do_serve_file(conn, path) do
|
||||
conn
|
||||
|> put_resp_header("content-type", MIME.path(path))
|
||||
|> send_file(200, base_path() <> path)
|
||||
|> halt
|
||||
end
|
||||
|
||||
defp config do
|
||||
Application.get_env(:asciinema, Asciinema.FileStore.Local)
|
||||
end
|
||||
|
||||
defp base_path do
|
||||
Keyword.get(config(), :path)
|
||||
end
|
||||
end
|
@ -0,0 +1,36 @@
|
||||
defmodule Asciinema.FileStore.S3 do
|
||||
@behaviour Asciinema.FileStore
|
||||
import Phoenix.Controller, only: [redirect: 2]
|
||||
|
||||
def serve_file(conn, path, nil) do
|
||||
do_serve_file(conn, path)
|
||||
end
|
||||
def serve_file(conn, path, filename) do
|
||||
do_serve_file(conn, path, ["response-content-disposition": "attachment; filename=#{filename}"])
|
||||
end
|
||||
|
||||
defp do_serve_file(conn, path, query_params \\ []) do
|
||||
{:ok, url} =
|
||||
ExAws.Config.new(:s3, region: region())
|
||||
|> ExAws.S3.presigned_url(:get, bucket(), base_path() <> path, query_params: query_params)
|
||||
|
||||
conn
|
||||
|> redirect(external: url)
|
||||
end
|
||||
|
||||
defp config do
|
||||
Application.get_env(:asciinema, Asciinema.FileStore.S3)
|
||||
end
|
||||
|
||||
defp region do
|
||||
Keyword.get(config(), :region)
|
||||
end
|
||||
|
||||
defp bucket do
|
||||
Keyword.get(config(), :bucket)
|
||||
end
|
||||
|
||||
defp base_path do
|
||||
Keyword.get(config(), :path)
|
||||
end
|
||||
end
|
@ -0,0 +1,23 @@
|
||||
defmodule Asciinema.AsciicastFileController do
|
||||
use Asciinema.Web, :controller
|
||||
alias Asciinema.{Repo, Asciicast}
|
||||
|
||||
def show(conn, %{"id" => id} = params) do
|
||||
asciicast = Repo.one!(Asciicast.by_id_or_secret_token(id))
|
||||
path = Asciicast.json_store_path(asciicast)
|
||||
filename = download_filename(asciicast, params)
|
||||
|
||||
file_store().serve_file(conn, path, filename)
|
||||
end
|
||||
|
||||
defp download_filename(%Asciicast{id: id}, %{"dl" => _}) do
|
||||
"asciicast-#{id}.json"
|
||||
end
|
||||
defp download_filename(_asciicast, _params) do
|
||||
nil
|
||||
end
|
||||
|
||||
defp file_store do
|
||||
Application.get_env(:asciinema, :file_store)
|
||||
end
|
||||
end
|
Loading…
Reference in New Issue