From 713d92a58f8b9c782a9e3d64790324165139183a Mon Sep 17 00:00:00 2001 From: Marcin Kulik Date: Wed, 7 Jun 2017 19:53:12 +0200 Subject: [PATCH] Add FileStore.put_file/3 --- lib/asciinema/file_store.ex | 7 +++++++ lib/asciinema/file_store/local.ex | 10 ++++++++++ lib/asciinema/file_store/s3.ex | 13 +++++++++++++ 3 files changed, 30 insertions(+) diff --git a/lib/asciinema/file_store.ex b/lib/asciinema/file_store.ex index b5fc602..e36b503 100644 --- a/lib/asciinema/file_store.ex +++ b/lib/asciinema/file_store.ex @@ -1,4 +1,7 @@ defmodule Asciinema.FileStore do + @doc "Puts file at given path in store" + @callback put_file(dst_path :: String.t, src_local_path :: String.t, content_type :: String.t) :: :ok | {:error, term} + @doc "Serves file at given path in store" @callback serve_file(conn :: %Plug.Conn{}, path :: String.t, filename :: String.t) :: %Plug.Conn{} @@ -7,4 +10,8 @@ defmodule Asciinema.FileStore do @doc "Opens the given path in store, executes given fn and closes the file" @callback open(path :: String.t, function :: (File.io_device -> res)) :: {:ok, res} | {:error, File.posix} when res: var + + def put_file(dst_path, src_local_path, content_type) do + Application.get_env(:asciinema, :file_store).put_file(dst_path, src_local_path, content_type) + end end diff --git a/lib/asciinema/file_store/local.ex b/lib/asciinema/file_store/local.ex index 8dc0ec6..69225d1 100644 --- a/lib/asciinema/file_store/local.ex +++ b/lib/asciinema/file_store/local.ex @@ -3,6 +3,16 @@ defmodule Asciinema.FileStore.Local do import Plug.Conn alias Plug.MIME + def put_file(dst_path, src_local_path, _content_type) do + full_dst_path = base_path() <> dst_path + parent_dir = Path.dirname(full_dst_path) + + with :ok <- File.mkdir_p(parent_dir), + {:ok, _} <- File.copy(src_local_path, full_dst_path) do + :ok + end + end + def serve_file(conn, path, nil) do do_serve_file(conn, path) end diff --git a/lib/asciinema/file_store/s3.ex b/lib/asciinema/file_store/s3.ex index 07efd73..fac1d78 100644 --- a/lib/asciinema/file_store/s3.ex +++ b/lib/asciinema/file_store/s3.ex @@ -3,6 +3,12 @@ defmodule Asciinema.FileStore.S3 do import Phoenix.Controller, only: [redirect: 2] alias ExAws.S3 + def put_file(dst_path, src_local_path, content_type) do + body = File.read!(src_local_path) + opts = [{:content_type, content_type}] + make_request(S3.put_object(bucket(), base_path() <> dst_path, body, opts)) + end + def serve_file(conn, path, nil) do do_serve_file(conn, path) end @@ -21,6 +27,7 @@ defmodule Asciinema.FileStore.S3 do def open(path, function \\ nil) do response = S3.get_object(bucket(), base_path() <> path) |> ExAws.request(region: region()) + # TODO: use make_request case response do {:ok, %{body: body}} -> @@ -34,6 +41,12 @@ defmodule Asciinema.FileStore.S3 do end end + defp make_request(request) do + with {:ok, _} <- ExAws.request(request, region: region()) do + :ok + end + end + defp config do Application.get_env(:asciinema, Asciinema.FileStore.S3) end