defmodule CartosnapApp.Storage.Local do
@moduledoc """
Storage on local disk, for development without a bucket. Files live under
the configured root (`uploads/` by default) and the endpoint serves them
at `/uploads` (dev only; see `CartosnapAppWeb.Endpoint`).
config :cartosnap_app, :storage, CartosnapApp.Storage.Local
config :cartosnap_app, CartosnapApp.Storage.Local, root: "uploads"
"""
@behaviour CartosnapApp.Storage
@url_prefix "/uploads"
@impl true
def put(key, body, _content_type) do
with {:ok, path} <- path(key),
:ok <- File.mkdir_p(Path.dirname(path)) do
File.write(path, body)
end
end
@impl true
def get(key) do
with {:ok, path} <- path(key), do: File.read(path)
end
@impl true
def delete(key) do
with {:ok, path} <- path(key) do
case File.rm(path) do
:ok -> :ok
{:error, :enoent} -> :ok
error -> error
end
end
end
@impl true
def url(key), do: "#{@url_prefix}/#{key}"
@doc "The directory files are kept under, absolute."
def root do
:cartosnap_app
|> Application.get_env(__MODULE__, [])
|> Keyword.get(:root, "uploads")
|> Path.expand()
end
# Keys are ours (`<user>/<photo>/<variant>.<ext>`), but never let one
# reach outside the root.
defp path(key) do
root = root()
path = Path.expand(key, root)
if String.starts_with?(path, root <> "/"), do: {:ok, path}, else: {:error, :invalid_key}
end
end
neiam
/cartosnap_ex
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
1.4 KiB · text
History
e569b6d