Rename MobilizonWeb to Mobilizon.Web
This commit is contained in:
31
lib/web/upload/filter/anonymize_filename.ex
Normal file
31
lib/web/upload/filter/anonymize_filename.ex
Normal file
@@ -0,0 +1,31 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/upload/filter/anonymize_filename.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.Filter.AnonymizeFilename do
|
||||
@moduledoc """
|
||||
Replaces the original filename with a pre-defined text or randomly generated string.
|
||||
|
||||
Should be used after `Mobilizon.Web.Upload.Filter.Dedupe`.
|
||||
"""
|
||||
|
||||
@behaviour Mobilizon.Web.Upload.Filter
|
||||
|
||||
alias Mobilizon.Config
|
||||
|
||||
def filter(upload) do
|
||||
extension = List.last(String.split(upload.name, "."))
|
||||
name = Config.get([__MODULE__, :text], random(extension))
|
||||
{:ok, %Mobilizon.Web.Upload{upload | name: name}}
|
||||
end
|
||||
|
||||
defp random(extension) do
|
||||
string =
|
||||
10
|
||||
|> :crypto.strong_rand_bytes()
|
||||
|> Base.url_encode64(padding: false)
|
||||
|
||||
string <> "." <> extension
|
||||
end
|
||||
end
|
||||
20
lib/web/upload/filter/dedupe.ex
Normal file
20
lib/web/upload/filter/dedupe.ex
Normal file
@@ -0,0 +1,20 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/upload/filter/dedupe.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.Filter.Dedupe do
|
||||
@moduledoc """
|
||||
Names the file after its hash to avoid dedupes
|
||||
"""
|
||||
@behaviour Mobilizon.Web.Upload.Filter
|
||||
alias Mobilizon.Web.Upload
|
||||
|
||||
def filter(%Upload{name: name} = upload) do
|
||||
extension = name |> String.split(".") |> List.last()
|
||||
shasum = :crypto.hash(:sha256, File.read!(upload.tempfile)) |> Base.encode16(case: :lower)
|
||||
filename = shasum <> "." <> extension
|
||||
|
||||
{:ok, %Upload{upload | id: shasum, path: filename}}
|
||||
end
|
||||
end
|
||||
42
lib/web/upload/filter/filter.ex
Normal file
42
lib/web/upload/filter/filter.ex
Normal file
@@ -0,0 +1,42 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/upload/filter.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.Filter do
|
||||
@moduledoc """
|
||||
Upload Filter behaviour
|
||||
|
||||
This behaviour allows to run filtering actions just before a file is uploaded. This allows to:
|
||||
|
||||
* morph in place the temporary file
|
||||
* change any field of a `Mobilizon.Upload` struct
|
||||
* cancel/stop the upload
|
||||
"""
|
||||
|
||||
require Logger
|
||||
|
||||
@callback filter(Mobilizon.Web.Upload.t()) ::
|
||||
:ok | {:ok, Mobilizon.Web.Upload.t()} | {:error, any()}
|
||||
|
||||
@spec filter([module()], Mobilizon.Web.Upload.t()) ::
|
||||
{:ok, Mobilizon.Web.Upload.t()} | {:error, any()}
|
||||
|
||||
def filter([], upload) do
|
||||
{:ok, upload}
|
||||
end
|
||||
|
||||
def filter([filter | rest], upload) do
|
||||
case filter.filter(upload) do
|
||||
:ok ->
|
||||
filter(rest, upload)
|
||||
|
||||
{:ok, upload} ->
|
||||
filter(rest, upload)
|
||||
|
||||
error ->
|
||||
Logger.error("#{__MODULE__}: Filter #{filter} failed: #{inspect(error)}")
|
||||
error
|
||||
end
|
||||
end
|
||||
end
|
||||
48
lib/web/upload/filter/mogrify.ex
Normal file
48
lib/web/upload/filter/mogrify.ex
Normal file
@@ -0,0 +1,48 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/upload/filter/mogrify.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.Filter.Mogrify do
|
||||
@moduledoc """
|
||||
Handle mogrify transformations
|
||||
"""
|
||||
|
||||
@behaviour Mobilizon.Web.Upload.Filter
|
||||
|
||||
alias Mobilizon.Config
|
||||
|
||||
@type conversion :: action :: String.t() | {action :: String.t(), opts :: String.t()}
|
||||
@type conversions :: conversion() | [conversion()]
|
||||
|
||||
def filter(%Mobilizon.Web.Upload{tempfile: file, content_type: "image" <> _}) do
|
||||
filters = Config.get!([__MODULE__, :args])
|
||||
|
||||
file
|
||||
|> Mogrify.open()
|
||||
|> mogrify_filter(filters)
|
||||
|> Mogrify.save(in_place: true)
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
def filter(_), do: :ok
|
||||
|
||||
defp mogrify_filter(mogrify, nil), do: mogrify
|
||||
|
||||
defp mogrify_filter(mogrify, [filter | rest]) do
|
||||
mogrify
|
||||
|> mogrify_filter(filter)
|
||||
|> mogrify_filter(rest)
|
||||
end
|
||||
|
||||
defp mogrify_filter(mogrify, []), do: mogrify
|
||||
|
||||
defp mogrify_filter(mogrify, {action, options}) do
|
||||
Mogrify.custom(mogrify, action, options)
|
||||
end
|
||||
|
||||
defp mogrify_filter(mogrify, action) when is_binary(action) do
|
||||
Mogrify.custom(mogrify, action)
|
||||
end
|
||||
end
|
||||
41
lib/web/upload/filter/optimize.ex
Normal file
41
lib/web/upload/filter/optimize.ex
Normal file
@@ -0,0 +1,41 @@
|
||||
defmodule Mobilizon.Web.Upload.Filter.Optimize do
|
||||
@moduledoc """
|
||||
Handle picture optimizations
|
||||
"""
|
||||
|
||||
@behaviour Mobilizon.Web.Upload.Filter
|
||||
|
||||
alias Mobilizon.Config
|
||||
|
||||
@default_optimizers [
|
||||
JpegOptim,
|
||||
PngQuant,
|
||||
Optipng,
|
||||
Svgo,
|
||||
Gifsicle,
|
||||
Cwebp
|
||||
]
|
||||
|
||||
def filter(%Mobilizon.Web.Upload{tempfile: file, content_type: "image" <> _}) do
|
||||
optimizers = Config.get([__MODULE__, :optimizers], @default_optimizers)
|
||||
|
||||
case ExOptimizer.optimize(file, deps: optimizers) do
|
||||
{:ok, _res} ->
|
||||
:ok
|
||||
|
||||
{:error, err} ->
|
||||
require Logger
|
||||
|
||||
Logger.warn(
|
||||
"Unable to optimize file #{file}. The return from the process was #{inspect(err)}"
|
||||
)
|
||||
|
||||
:ok
|
||||
|
||||
err ->
|
||||
err
|
||||
end
|
||||
end
|
||||
|
||||
def filter(_), do: :ok
|
||||
end
|
||||
123
lib/web/upload/mime.ex
Normal file
123
lib/web/upload/mime.ex
Normal file
@@ -0,0 +1,123 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/mime.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.MIME do
|
||||
@moduledoc """
|
||||
Returns the mime-type of a binary and optionally a normalized file-name.
|
||||
"""
|
||||
@default "application/octet-stream"
|
||||
@read_bytes 35
|
||||
|
||||
@spec file_mime_type(String.t()) ::
|
||||
{:ok, content_type :: String.t(), filename :: String.t()} | {:error, any()} | :error
|
||||
def file_mime_type(path, filename) do
|
||||
with {:ok, content_type} <- file_mime_type(path),
|
||||
filename <- fix_extension(filename, content_type) do
|
||||
{:ok, content_type, filename}
|
||||
end
|
||||
end
|
||||
|
||||
@spec file_mime_type(String.t()) :: {:ok, String.t()} | {:error, any()} | :error
|
||||
def file_mime_type(filename) do
|
||||
File.open(filename, [:read], fn f ->
|
||||
check_mime_type(IO.binread(f, @read_bytes))
|
||||
end)
|
||||
end
|
||||
|
||||
def bin_mime_type(binary, filename) do
|
||||
with {:ok, content_type} <- bin_mime_type(binary),
|
||||
filename <- fix_extension(filename, content_type) do
|
||||
{:ok, content_type, filename}
|
||||
end
|
||||
end
|
||||
|
||||
@spec bin_mime_type(binary()) :: {:ok, String.t()} | :error
|
||||
def bin_mime_type(<<head::binary-size(@read_bytes), _::binary>>) do
|
||||
{:ok, check_mime_type(head)}
|
||||
end
|
||||
|
||||
def bin_mime_type(_), do: :error
|
||||
|
||||
def mime_type(<<_::binary>>), do: {:ok, @default}
|
||||
|
||||
defp fix_extension(filename, content_type) do
|
||||
parts = String.split(filename, ".")
|
||||
|
||||
new_filename =
|
||||
if length(parts) > 1 do
|
||||
parts |> Enum.drop(-1) |> Enum.join(".")
|
||||
else
|
||||
Enum.join(parts)
|
||||
end
|
||||
|
||||
cond do
|
||||
content_type == "application/octet-stream" ->
|
||||
filename
|
||||
|
||||
ext = List.first(MIME.extensions(content_type)) ->
|
||||
new_filename <> "." <> ext
|
||||
|
||||
true ->
|
||||
extension = content_type |> String.split("/") |> List.last()
|
||||
|
||||
Enum.join([new_filename, extension], ".")
|
||||
end
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, _::binary>>) do
|
||||
"image/png"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0x47, 0x49, 0x46, 0x38, _, 0x61, _::binary>>) do
|
||||
"image/gif"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0xFF, 0xD8, 0xFF, _::binary>>) do
|
||||
"image/jpeg"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0x1A, 0x45, 0xDF, 0xA3, _::binary>>) do
|
||||
"video/webm"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70, _::binary>>) do
|
||||
"video/mp4"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0x49, 0x44, 0x33, _::binary>>) do
|
||||
"audio/mpeg"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<255, 251, _, 68, 0, 0, 0, 0, _::binary>>) do
|
||||
"audio/mpeg"
|
||||
end
|
||||
|
||||
defp check_mime_type(
|
||||
<<0x4F, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00, _::size(160), 0x80, 0x74, 0x68, 0x65,
|
||||
0x6F, 0x72, 0x61, _::binary>>
|
||||
) do
|
||||
"video/ogg"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<0x4F, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00, _::binary>>) do
|
||||
"audio/ogg"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<"RIFF", _::binary-size(4), "WAVE", _::binary>>) do
|
||||
"audio/wav"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<"RIFF", _::binary-size(4), "WEBP", _::binary>>) do
|
||||
"image/webp"
|
||||
end
|
||||
|
||||
defp check_mime_type(<<"RIFF", _::binary-size(4), "AVI.", _::binary>>) do
|
||||
"video/avi"
|
||||
end
|
||||
|
||||
defp check_mime_type(_) do
|
||||
@default
|
||||
end
|
||||
end
|
||||
209
lib/web/upload/upload.ex
Normal file
209
lib/web/upload/upload.ex
Normal file
@@ -0,0 +1,209 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/upload.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload do
|
||||
@moduledoc """
|
||||
Manage user uploads
|
||||
|
||||
Options:
|
||||
* `:type`: presets for activity type (defaults to Document) and size limits from app configuration
|
||||
* `:description`: upload alternative text
|
||||
* `:base_url`: override base url
|
||||
* `:uploader`: override uploader
|
||||
* `:filters`: override filters
|
||||
* `:size_limit`: override size limit
|
||||
* `:activity_type`: override activity type
|
||||
|
||||
The `%Mobilizon.Web.Upload{}` struct: all documented fields are meant to be overwritten in filters:
|
||||
|
||||
* `:id` - the upload id.
|
||||
* `:name` - the upload file name.
|
||||
* `:path` - the upload path: set at first to `id/name` but can be changed. Keep in mind that the path
|
||||
is once created permanent and changing it (especially in uploaders) is probably a bad idea!
|
||||
* `:tempfile` - path to the temporary file. Prefer in-place changes on the file rather than changing the
|
||||
path as the temporary file is also tracked by `Plug.Upload{}` and automatically deleted once the request is over.
|
||||
|
||||
Related behaviors:
|
||||
|
||||
* `Mobilizon.Web.Upload.Uploader`
|
||||
* `Mobilizon.Web.Upload.Filter`
|
||||
|
||||
"""
|
||||
|
||||
alias Ecto.UUID
|
||||
|
||||
alias Mobilizon.Config
|
||||
|
||||
alias Mobilizon.Web.Upload.{Filter, MIME, Uploader}
|
||||
|
||||
require Logger
|
||||
|
||||
@type source ::
|
||||
Plug.Upload.t()
|
||||
| (data_uri_string :: String.t())
|
||||
| {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
|
||||
|
||||
@type option ::
|
||||
{:type, :avatar | :banner | :background}
|
||||
| {:description, String.t()}
|
||||
| {:activity_type, String.t()}
|
||||
| {:size_limit, nil | non_neg_integer()}
|
||||
| {:uploader, module()}
|
||||
| {:filters, [module()]}
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
id: String.t(),
|
||||
name: String.t(),
|
||||
tempfile: String.t(),
|
||||
content_type: String.t(),
|
||||
path: String.t(),
|
||||
size: integer()
|
||||
}
|
||||
defstruct [:id, :name, :tempfile, :content_type, :path, :size]
|
||||
|
||||
@spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
|
||||
def store(upload, opts \\ []) do
|
||||
opts = get_opts(opts)
|
||||
|
||||
with {:ok, upload} <- prepare_upload(upload, opts),
|
||||
upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
|
||||
{:ok, upload} <- Filter.filter(opts.filters, upload),
|
||||
{:ok, url_spec} <- Uploader.put_file(opts.uploader, upload) do
|
||||
{:ok,
|
||||
%{
|
||||
name: Map.get(opts, :description) || upload.name,
|
||||
url: url_from_spec(upload, opts.base_url, url_spec),
|
||||
content_type: upload.content_type,
|
||||
size: upload.size
|
||||
}}
|
||||
else
|
||||
{:error, error} ->
|
||||
Logger.error(
|
||||
"#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
|
||||
)
|
||||
|
||||
{:error, error}
|
||||
end
|
||||
end
|
||||
|
||||
def remove(url, opts \\ []) do
|
||||
with opts <- get_opts(opts),
|
||||
%URI{path: "/media/" <> path, host: host} <- URI.parse(url),
|
||||
{:same_host, true} <- {:same_host, host == Mobilizon.Web.Endpoint.host()} do
|
||||
Uploader.remove_file(opts.uploader, path)
|
||||
else
|
||||
%URI{} = _uri ->
|
||||
{:error, "URL doesn't match pattern"}
|
||||
|
||||
{:same_host, _} ->
|
||||
Logger.error("Media can't be deleted because its URL doesn't match current host")
|
||||
end
|
||||
end
|
||||
|
||||
def char_unescaped?(char) do
|
||||
URI.char_unreserved?(char) or char == ?/
|
||||
end
|
||||
|
||||
defp get_opts(opts) do
|
||||
{size_limit, activity_type} =
|
||||
case Keyword.get(opts, :type) do
|
||||
:banner ->
|
||||
{Config.get!([:instance, :banner_upload_limit]), "Image"}
|
||||
|
||||
:avatar ->
|
||||
{Config.get!([:instance, :avatar_upload_limit]), "Image"}
|
||||
|
||||
_ ->
|
||||
{Config.get!([:instance, :upload_limit]), nil}
|
||||
end
|
||||
|
||||
%{
|
||||
activity_type: Keyword.get(opts, :activity_type, activity_type),
|
||||
size_limit: Keyword.get(opts, :size_limit, size_limit),
|
||||
uploader: Keyword.get(opts, :uploader, Config.get([__MODULE__, :uploader])),
|
||||
filters: Keyword.get(opts, :filters, Config.get([__MODULE__, :filters])),
|
||||
description: Keyword.get(opts, :description),
|
||||
base_url:
|
||||
Keyword.get(
|
||||
opts,
|
||||
:base_url,
|
||||
Config.get([__MODULE__, :base_url], Mobilizon.Web.Endpoint.url())
|
||||
)
|
||||
}
|
||||
end
|
||||
|
||||
defp prepare_upload(%Plug.Upload{} = file, opts) do
|
||||
with {:ok, size} <- check_file_size(file.path, opts.size_limit),
|
||||
{:ok, content_type, name} <- MIME.file_mime_type(file.path, file.filename) do
|
||||
{:ok,
|
||||
%__MODULE__{
|
||||
id: UUID.generate(),
|
||||
name: name,
|
||||
tempfile: file.path,
|
||||
content_type: content_type,
|
||||
size: size
|
||||
}}
|
||||
end
|
||||
end
|
||||
|
||||
defp prepare_upload(%{body: body, name: name} = _file, opts) do
|
||||
with :ok <- check_binary_size(body, opts.size_limit),
|
||||
tmp_path <- tempfile_for_image(body),
|
||||
{:ok, content_type, name} <- MIME.file_mime_type(tmp_path, name) do
|
||||
{:ok,
|
||||
%__MODULE__{
|
||||
id: UUID.generate(),
|
||||
name: name,
|
||||
tempfile: tmp_path,
|
||||
content_type: content_type,
|
||||
size: byte_size(body)
|
||||
}}
|
||||
end
|
||||
end
|
||||
|
||||
defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
|
||||
with {:ok, %{size: size}} <- File.stat(path),
|
||||
true <- size <= size_limit do
|
||||
{:ok, size}
|
||||
else
|
||||
false -> {:error, :file_too_large}
|
||||
error -> error
|
||||
end
|
||||
end
|
||||
|
||||
defp check_file_size(_, _), do: :ok
|
||||
|
||||
defp check_binary_size(binary, size_limit)
|
||||
when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
|
||||
{:error, :file_too_large}
|
||||
end
|
||||
|
||||
defp check_binary_size(_, _), do: :ok
|
||||
|
||||
# Creates a tempfile using the Plug.Upload Genserver which cleans them up
|
||||
# automatically.
|
||||
defp tempfile_for_image(data) do
|
||||
{:ok, tmp_path} = Plug.Upload.random_file("temp_files")
|
||||
{:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
|
||||
IO.binwrite(tmp_file, data)
|
||||
|
||||
tmp_path
|
||||
end
|
||||
|
||||
defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
|
||||
path =
|
||||
URI.encode(path, &char_unescaped?/1) <>
|
||||
if Config.get([__MODULE__, :link_name], false) do
|
||||
"?name=#{URI.encode(name, &char_unescaped?/1)}"
|
||||
else
|
||||
""
|
||||
end
|
||||
|
||||
[base_url, "media", path]
|
||||
|> Path.join()
|
||||
end
|
||||
|
||||
defp url_from_spec(_upload, _base_url, {:url, url}), do: url
|
||||
end
|
||||
67
lib/web/upload/uploader/local.ex
Normal file
67
lib/web/upload/uploader/local.ex
Normal file
@@ -0,0 +1,67 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/uploaders/local.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.Uploader.Local do
|
||||
@moduledoc """
|
||||
Local uploader for files
|
||||
"""
|
||||
|
||||
@behaviour Mobilizon.Web.Upload.Uploader
|
||||
|
||||
alias Mobilizon.Config
|
||||
|
||||
def get_file(_) do
|
||||
{:ok, {:static_dir, upload_path()}}
|
||||
end
|
||||
|
||||
def put_file(upload) do
|
||||
{path, file} = local_path(upload.path)
|
||||
result_file = Path.join(path, file)
|
||||
|
||||
unless File.exists?(result_file) do
|
||||
File.cp!(upload.tempfile, result_file)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
def remove_file(path) do
|
||||
with {path, file} <- local_path(path),
|
||||
full_path <- Path.join(path, file),
|
||||
true <- File.exists?(full_path),
|
||||
:ok <- File.rm(full_path),
|
||||
:ok <- remove_folder(path) do
|
||||
{:ok, path}
|
||||
else
|
||||
false -> {:error, "File #{path} doesn't exist"}
|
||||
end
|
||||
end
|
||||
|
||||
defp remove_folder(path) do
|
||||
with {:subfolder, true} <- {:subfolder, path != upload_path()},
|
||||
{:empty_folder, {:ok, [] = _files}} <- {:empty_folder, File.ls(path)} do
|
||||
File.rmdir(path)
|
||||
else
|
||||
{:subfolder, _} -> :ok
|
||||
{:empty_folder, _} -> {:error, "Error: Folder is not empty"}
|
||||
end
|
||||
end
|
||||
|
||||
defp local_path(path) do
|
||||
case Enum.reverse(String.split(path, "/", trim: true)) do
|
||||
[file] ->
|
||||
{upload_path(), file}
|
||||
|
||||
[file | folders] ->
|
||||
path = Path.join([upload_path()] ++ Enum.reverse(folders))
|
||||
File.mkdir_p!(path)
|
||||
{path, file}
|
||||
end
|
||||
end
|
||||
|
||||
def upload_path do
|
||||
Config.get!([__MODULE__, :uploads])
|
||||
end
|
||||
end
|
||||
78
lib/web/upload/uploader/uploader.ex
Normal file
78
lib/web/upload/uploader/uploader.ex
Normal file
@@ -0,0 +1,78 @@
|
||||
# Portions of this file are derived from Pleroma:
|
||||
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social>
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Upstream: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/uploaders/uploader.ex
|
||||
|
||||
defmodule Mobilizon.Web.Upload.Uploader do
|
||||
@moduledoc """
|
||||
Defines the contract to put and get an uploaded file to any backend.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Instructs how to get the file from the backend.
|
||||
|
||||
Used by `Mobilizon.Web.Plugs.UploadedMedia`.
|
||||
"""
|
||||
@type get_method :: {:static_dir, directory :: String.t()} | {:url, url :: String.t()}
|
||||
@callback get_file(file :: String.t()) :: {:ok, get_method()}
|
||||
|
||||
@doc """
|
||||
Put a file to the backend.
|
||||
|
||||
Returns:
|
||||
|
||||
* `:ok` which assumes `{:ok, upload.path}`
|
||||
* `{:ok, spec}` where spec is:
|
||||
* `{:file, filename :: String.t}` to handle reads with `get_file/1` (recommended)
|
||||
|
||||
This allows to correctly proxy or redirect requests to the backend, while allowing to migrate backends without breaking any URL.
|
||||
* `{url, url :: String.t}` to bypass `get_file/2` and use the `url` directly in the activity.
|
||||
* `{:error, String.t}` error information if the file failed to be saved to the backend.
|
||||
* `:wait_callback` will wait for an http post request at `/api/pleroma/upload_callback/:upload_path` and call the uploader's `http_callback/3` method.
|
||||
|
||||
"""
|
||||
@type file_spec :: {:file | :url, String.t()}
|
||||
@callback put_file(Mobilizon.Web.Upload.t()) ::
|
||||
:ok | {:ok, file_spec()} | {:error, String.t()} | :wait_callback
|
||||
|
||||
@callback remove_file(file_spec()) :: :ok | {:ok, file_spec()} | {:error, String.t()}
|
||||
|
||||
@callback http_callback(Plug.Conn.t(), Map.t()) ::
|
||||
{:ok, Plug.Conn.t()}
|
||||
| {:ok, Plug.Conn.t(), file_spec()}
|
||||
| {:error, Plug.Conn.t(), String.t()}
|
||||
@optional_callbacks http_callback: 2
|
||||
|
||||
@spec put_file(module(), Mobilizon.Web.Upload.t()) :: {:ok, file_spec()} | {:error, String.t()}
|
||||
def put_file(uploader, upload) do
|
||||
case uploader.put_file(upload) do
|
||||
:ok -> {:ok, {:file, upload.path}}
|
||||
:wait_callback -> handle_callback(uploader, upload)
|
||||
{:ok, _} = ok -> ok
|
||||
{:error, _} = error -> error
|
||||
end
|
||||
end
|
||||
|
||||
def remove_file(uploader, path) do
|
||||
uploader.remove_file(path)
|
||||
end
|
||||
|
||||
defp handle_callback(uploader, upload) do
|
||||
:global.register_name({__MODULE__, upload.path}, self())
|
||||
|
||||
receive do
|
||||
{__MODULE__, pid, conn, params} ->
|
||||
case uploader.http_callback(conn, params) do
|
||||
{:ok, conn, ok} ->
|
||||
send(pid, {__MODULE__, conn})
|
||||
{:ok, ok}
|
||||
|
||||
{:error, conn, error} ->
|
||||
send(pid, {__MODULE__, conn})
|
||||
{:error, error}
|
||||
end
|
||||
after
|
||||
30_000 -> {:error, "Uploader callback timeout"}
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user