2017-03-29 01:39:01 +02:00
|
|
|
defmodule Pleroma.Upload do
|
2017-04-27 15:18:50 +02:00
|
|
|
alias Ecto.UUID
|
|
|
|
alias Pleroma.Web
|
2017-03-29 01:39:01 +02:00
|
|
|
def store(%Plug.Upload{} = file) do
|
2017-04-27 15:18:50 +02:00
|
|
|
uuid = UUID.generate
|
2017-03-29 01:39:01 +02:00
|
|
|
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)
|
|
|
|
|
2017-11-09 13:11:37 +01:00
|
|
|
# fix content type on some image uploads
|
|
|
|
matches = Regex.named_captures(~r/\.(?<ext>(jpg|jpeg|png|gif))$/i, file.filename)
|
|
|
|
content_type = if file.content_type == "application/octet-stream" and matches do
|
|
|
|
if matches["ext"] == "jpg", do: "image/jpeg", else: "image/#{matches["ext"]}"
|
|
|
|
else
|
|
|
|
file.content_type
|
|
|
|
end
|
|
|
|
|
2017-03-29 01:39:01 +02:00
|
|
|
%{
|
|
|
|
"type" => "Image",
|
2017-03-30 16:08:23 +02:00
|
|
|
"url" => [%{
|
|
|
|
"type" => "Link",
|
2017-11-09 13:11:37 +01:00
|
|
|
"mediaType" => content_type,
|
2017-08-09 16:45:05 +02:00
|
|
|
"href" => url_for(Path.join(uuid, :cow_uri.urlencode(file.filename)))
|
2017-03-30 16:08:23 +02:00
|
|
|
}],
|
2017-03-29 01:39:01 +02:00
|
|
|
"name" => file.filename,
|
|
|
|
"uuid" => uuid
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2017-04-16 14:23:30 +02: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"])
|
2017-04-27 15:18:50 +02:00
|
|
|
uuid = UUID.generate
|
2017-04-16 14:23:30 +02:00
|
|
|
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,
|
2017-08-09 16:45:05 +02:00
|
|
|
"href" => url_for(Path.join(uuid, :cow_uri.urlencode(filename)))
|
2017-04-16 14:23:30 +02:00
|
|
|
}],
|
|
|
|
"name" => filename,
|
|
|
|
"uuid" => uuid
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2017-03-29 01:39:01 +02:00
|
|
|
defp upload_path do
|
2017-04-27 15:18:50 +02:00
|
|
|
settings = Application.get_env(:pleroma, Pleroma.Upload)
|
|
|
|
Keyword.fetch!(settings, :uploads)
|
2017-03-29 01:39:01 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
defp url_for(file) do
|
2017-04-27 15:18:50 +02:00
|
|
|
"#{Web.base_url()}/media/#{file}"
|
2017-03-29 01:39:01 +02:00
|
|
|
end
|
|
|
|
end
|