1 defmodule Pleroma.Upload do
4 def store(%Plug.Upload{} = file) do
6 upload_folder = Path.join(upload_path(), uuid)
7 File.mkdir_p!(upload_folder)
8 result_file = Path.join(upload_folder, file.filename)
9 File.cp!(file.path, result_file)
11 # fix content type on some image uploads
12 content_type = if file.content_type == "application/octet-stream" do
13 get_content_type(file.path)
22 "mediaType" => content_type,
23 "href" => url_for(Path.join(uuid, :cow_uri.urlencode(file.filename)))
25 "name" => file.filename,
30 def store(%{"img" => "data:image/" <> image_data}) do
31 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
32 data = Base.decode64!(parsed["data"])
34 upload_folder = Path.join(upload_path(), uuid)
35 File.mkdir_p!(upload_folder)
36 filename = Base.encode16(:crypto.hash(:sha256, data)) <> ".#{parsed["filetype"]}"
37 result_file = Path.join(upload_folder, filename)
39 File.write!(result_file, data)
41 content_type = "image/#{parsed["filetype"]}"
47 "mediaType" => content_type,
48 "href" => url_for(Path.join(uuid, :cow_uri.urlencode(filename)))
56 settings = Application.get_env(:pleroma, Pleroma.Upload)
57 Keyword.fetch!(settings, :uploads)
61 "#{Web.base_url()}/media/#{file}"
64 def get_content_type(file) do
65 match = File.open(file, [:read], fn(f) ->
66 case IO.binread(f, 8) do
67 <<0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a>> ->
69 <<0x47, 0x49, 0x46, 0x38, _, 0x61, _, _>> ->
71 <<0xff, 0xd8, 0xff, _, _, _, _, _>> ->
73 <<0x1a, 0x45, 0xdf, 0xa3, _, _, _, _>> ->
75 <<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70>> ->
77 <<0x49, 0x44, 0x33, _, _, _, _, _>> ->
79 <<0x4f, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00>> ->
81 <<0x52, 0x49, 0x46, 0x46, _, _, _, _>> ->
84 "application/octet-stream"
90 _e -> "application/octet-stream"