1
0
Fork 0
mirror of https://framagit.org/framasoft/mobilizon.git synced 2024-12-28 10:52:11 +00:00
mobilizon/lib/web/upload/uploader/local.ex

68 lines
1.7 KiB
Elixir
Raw Normal View History

# 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
2020-01-26 20:36:50 +00:00
defmodule Mobilizon.Web.Upload.Uploader.Local do
@moduledoc """
Local uploader for files
"""
2019-09-07 22:05:54 +00:00
2020-01-26 20:36:50 +00:00
@behaviour Mobilizon.Web.Upload.Uploader
2019-09-07 22:05:54 +00:00
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
2019-09-07 22:05:54 +00:00
Config.get!([__MODULE__, :uploads])
end
end