Merge branch 'runtime-config' into 'develop'
[akkoma] / lib / pleroma / upload.ex
1 defmodule Pleroma.Upload do
2 alias Ecto.UUID
3
4 def check_file_size(path, nil), do: true
5
6 def check_file_size(path, size_limit) do
7 {:ok, %{size: size}} = File.stat(path)
8 size <= size_limit
9 end
10
11 def store(file, should_dedupe, size_limit \\ nil)
12
13 def store(%Plug.Upload{} = file, should_dedupe, size_limit) do
14 content_type = get_content_type(file.path)
15
16 with uuid <- get_uuid(file, should_dedupe),
17 name <- get_name(file, uuid, content_type, should_dedupe),
18 true <- check_file_size(file.path, size_limit) do
19 strip_exif_data(content_type, file.path)
20
21 {:ok, url_path} = uploader().put_file(name, uuid, file.path, content_type, should_dedupe)
22
23 %{
24 "type" => "Document",
25 "url" => [
26 %{
27 "type" => "Link",
28 "mediaType" => content_type,
29 "href" => url_path
30 }
31 ],
32 "name" => name
33 }
34 else
35 _e -> nil
36 end
37 end
38
39 def store(%{"img" => "data:image/" <> image_data}, should_dedupe, size_limit) do
40 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
41 data = Base.decode64!(parsed["data"], ignore: :whitespace)
42
43 with tmp_path <- tempfile_for_image(data),
44 uuid <- UUID.generate(),
45 true <- check_file_size(tmp_path, size_limit) do
46 content_type = get_content_type(tmp_path)
47 strip_exif_data(content_type, tmp_path)
48
49 name =
50 create_name(
51 String.downcase(Base.encode16(:crypto.hash(:sha256, data))),
52 parsed["filetype"],
53 content_type
54 )
55
56 {:ok, url_path} = uploader().put_file(name, uuid, tmp_path, content_type, should_dedupe)
57
58 %{
59 "type" => "Image",
60 "url" => [
61 %{
62 "type" => "Link",
63 "mediaType" => content_type,
64 "href" => url_path
65 }
66 ],
67 "name" => name
68 }
69 else
70 _e -> nil
71 end
72 end
73
74 @doc """
75 Creates a tempfile using the Plug.Upload Genserver which cleans them up
76 automatically.
77 """
78 def tempfile_for_image(data) do
79 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
80 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
81 IO.binwrite(tmp_file, data)
82
83 tmp_path
84 end
85
86 def strip_exif_data(content_type, file) do
87 settings = Application.get_env(:pleroma, Pleroma.Upload)
88 do_strip = Keyword.fetch!(settings, :strip_exif)
89 [filetype, _ext] = String.split(content_type, "/")
90
91 if filetype == "image" and do_strip == true do
92 Mogrify.open(file) |> Mogrify.custom("strip") |> Mogrify.save(in_place: true)
93 end
94 end
95
96 defp create_name(uuid, ext, type) do
97 case type do
98 "application/octet-stream" ->
99 String.downcase(Enum.join([uuid, ext], "."))
100
101 "audio/mpeg" ->
102 String.downcase(Enum.join([uuid, "mp3"], "."))
103
104 _ ->
105 String.downcase(Enum.join([uuid, List.last(String.split(type, "/"))], "."))
106 end
107 end
108
109 defp get_uuid(file, should_dedupe) do
110 if should_dedupe do
111 Base.encode16(:crypto.hash(:sha256, File.read!(file.path)))
112 else
113 UUID.generate()
114 end
115 end
116
117 defp get_name(file, uuid, type, should_dedupe) do
118 if should_dedupe do
119 create_name(uuid, List.last(String.split(file.filename, ".")), type)
120 else
121 parts = String.split(file.filename, ".")
122
123 new_filename =
124 if length(parts) > 1 do
125 Enum.drop(parts, -1) |> Enum.join(".")
126 else
127 Enum.join(parts)
128 end
129
130 case type do
131 "application/octet-stream" -> file.filename
132 "audio/mpeg" -> new_filename <> ".mp3"
133 "image/jpeg" -> new_filename <> ".jpg"
134 _ -> Enum.join([new_filename, String.split(type, "/") |> List.last()], ".")
135 end
136 end
137 end
138
139 def get_content_type(file) do
140 match =
141 File.open(file, [:read], fn f ->
142 case IO.binread(f, 8) do
143 <<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A>> ->
144 "image/png"
145
146 <<0x47, 0x49, 0x46, 0x38, _, 0x61, _, _>> ->
147 "image/gif"
148
149 <<0xFF, 0xD8, 0xFF, _, _, _, _, _>> ->
150 "image/jpeg"
151
152 <<0x1A, 0x45, 0xDF, 0xA3, _, _, _, _>> ->
153 "video/webm"
154
155 <<0x00, 0x00, 0x00, _, 0x66, 0x74, 0x79, 0x70>> ->
156 "video/mp4"
157
158 <<0x49, 0x44, 0x33, _, _, _, _, _>> ->
159 "audio/mpeg"
160
161 <<255, 251, _, 68, 0, 0, 0, 0>> ->
162 "audio/mpeg"
163
164 <<0x4F, 0x67, 0x67, 0x53, 0x00, 0x02, 0x00, 0x00>> ->
165 "audio/ogg"
166
167 <<0x52, 0x49, 0x46, 0x46, _, _, _, _>> ->
168 "audio/wav"
169
170 _ ->
171 "application/octet-stream"
172 end
173 end)
174
175 case match do
176 {:ok, type} -> type
177 _e -> "application/octet-stream"
178 end
179 end
180
181 defp uploader() do
182 Pleroma.Config.get!([Pleroma.Upload, :uploader])
183 end
184 end