1 defmodule Pleroma.Upload do
5 def store(%Plug.Upload{} = file) do
7 upload_folder = Path.join(upload_path(), uuid)
8 File.mkdir_p!(upload_folder)
9 result_file = Path.join(upload_folder, file.filename)
10 File.cp!(file.path, result_file)
12 # fix content type on some image uploads
14 if file.content_type in [nil, "application/octet-stream"] do
15 get_content_type(file.path)
25 "mediaType" => content_type,
26 "href" => url_for(Path.join(uuid, :cow_uri.urlencode(file.filename)))
29 "name" => file.filename,
34 def store(%{"img" => "data:image/" <> image_data}) do
35 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
36 data = Base.decode64!(parsed["data"])
37 uuid = UUID.generate()
38 upload_folder = Path.join(upload_path(), uuid)
39 File.mkdir_p!(upload_folder)
40 filename = Base.encode16(:crypto.hash(:sha256, data)) <> ".#{parsed["filetype"]}"
41 result_file = Path.join(upload_folder, filename)
43 File.write!(result_file, data)
45 content_type = "image/#{parsed["filetype"]}"
52 "mediaType" => content_type,
53 "href" => url_for(Path.join(uuid, :cow_uri.urlencode(filename)))
62 settings = Application.get_env(:pleroma, Pleroma.Upload)
63 Keyword.fetch!(settings, :uploads)
67 "#{Web.base_url()}/media/#{file}"
70 def get_content_type(file) do
72 File.open(file, [:read], fn f ->
73 case IO.binread(f, 8) do
74 <<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A>> ->
77 <<0x47, 0x49, 0x46, 0x38, _, 0x61, _, _>> ->
80 <<0xFF, 0xD8, 0xFF, _, _, _, _, _>> ->
83 <<0x1A, 0x45, 0xDF, 0xA3, _, _, _, _>> ->
86 <<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70>> ->
89 <<0x49, 0x44, 0x33, _, _, _, _, _>> ->
92 <<0x4F, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00>> ->
95 <<0x52, 0x49, 0x46, 0x46, _, _, _, _>> ->
99 "application/octet-stream"
105 _e -> "application/octet-stream"