akkoma/lib/pleroma/upload.ex

55 lines
1.5 KiB
Elixir
Raw Normal View History

2017-03-28 17:39:01 -06:00
defmodule Pleroma.Upload do
def store(%Plug.Upload{} = file) do
uuid = Ecto.UUID.generate
upload_folder = Path.join(upload_path(), uuid)
File.mkdir_p!(upload_folder)
result_file = Path.join(upload_folder, file.filename)
File.cp!(file.path, result_file)
%{
"type" => "Image",
2017-03-30 08:08:23 -06:00
"url" => [%{
"type" => "Link",
"mediaType" => file.content_type,
"href" => url_for(Path.join(uuid, file.filename))
}],
2017-03-28 17:39:01 -06:00
"name" => file.filename,
"uuid" => uuid
}
end
2017-04-16 06:23:30 -06:00
def store(%{"img" => "data:image/" <> image_data}) do
parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
data = Base.decode64!(parsed["data"])
uuid = Ecto.UUID.generate
upload_folder = Path.join(upload_path(), uuid)
File.mkdir_p!(upload_folder)
filename = Base.encode16(:crypto.hash(:sha256, data)) <> ".#{parsed["filetype"]}"
result_file = Path.join(upload_folder, filename)
File.write!(result_file, data)
content_type = "image/#{parsed["filetype"]}"
%{
"type" => "Image",
"url" => [%{
"type" => "Link",
"mediaType" => content_type,
"href" => url_for(Path.join(uuid, filename))
}],
"name" => filename,
"uuid" => uuid
}
end
2017-03-28 17:39:01 -06:00
defp upload_path do
Application.get_env(:pleroma, Pleroma.Upload)
|> Keyword.fetch!(:uploads)
end
defp url_for(file) do
2017-03-30 06:32:36 -06:00
"#{Pleroma.Web.base_url()}/media/#{file}"
2017-03-28 17:39:01 -06:00
end
end