Merge branch 'oban-overuse' into 'develop'
[akkoma] / lib / pleroma / upload.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Upload do
6 @moduledoc """
7 Manage user uploads
8
9 Options:
10 * `:type`: presets for activity type (defaults to Document) and size limits from app configuration
11 * `:description`: upload alternative text
12 * `:base_url`: override base url
13 * `:uploader`: override uploader
14 * `:filters`: override filters
15 * `:size_limit`: override size limit
16 * `:activity_type`: override activity type
17
18 The `%Pleroma.Upload{}` struct: all documented fields are meant to be overwritten in filters:
19
20 * `:id` - the upload id.
21 * `:name` - the upload file name.
22 * `:path` - the upload path: set at first to `id/name` but can be changed. Keep in mind that the path
23 is once created permanent and changing it (especially in uploaders) is probably a bad idea!
24 * `:tempfile` - path to the temporary file. Prefer in-place changes on the file rather than changing the
25 path as the temporary file is also tracked by `Plug.Upload{}` and automatically deleted once the request is over.
26
27 Related behaviors:
28
29 * `Pleroma.Uploaders.Uploader`
30 * `Pleroma.Upload.Filter`
31
32 """
33 alias Ecto.UUID
34 require Logger
35
36 @type source ::
37 Plug.Upload.t()
38 | (data_uri_string :: String.t())
39 | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
40 | map()
41
42 @type option ::
43 {:type, :avatar | :banner | :background}
44 | {:description, String.t()}
45 | {:activity_type, String.t()}
46 | {:size_limit, nil | non_neg_integer()}
47 | {:uploader, module()}
48 | {:filters, [module()]}
49
50 @type t :: %__MODULE__{
51 id: String.t(),
52 name: String.t(),
53 tempfile: String.t(),
54 content_type: String.t(),
55 path: String.t()
56 }
57 defstruct [:id, :name, :tempfile, :content_type, :path]
58
59 defp get_description(opts, upload) do
60 case {opts[:description], Pleroma.Config.get([Pleroma.Upload, :default_description])} do
61 {description, _} when is_binary(description) -> description
62 {_, :filename} -> upload.name
63 {_, str} when is_binary(str) -> str
64 _ -> ""
65 end
66 end
67
68 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
69 def store(upload, opts \\ []) do
70 opts = get_opts(opts)
71
72 with {:ok, upload} <- prepare_upload(upload, opts),
73 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
74 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
75 description = get_description(opts, upload),
76 {_, true} <-
77 {:description_limit,
78 String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
79 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
80 {:ok,
81 %{
82 "type" => opts.activity_type,
83 "mediaType" => upload.content_type,
84 "url" => [
85 %{
86 "type" => "Link",
87 "mediaType" => upload.content_type,
88 "href" => url_from_spec(upload, opts.base_url, url_spec)
89 }
90 ],
91 "name" => description
92 }}
93 else
94 {:description_limit, _} ->
95 {:error, :description_too_long}
96
97 {:error, error} ->
98 Logger.error(
99 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
100 )
101
102 {:error, error}
103 end
104 end
105
106 def char_unescaped?(char) do
107 URI.char_unreserved?(char) or char == ?/
108 end
109
110 defp get_opts(opts) do
111 {size_limit, activity_type} =
112 case Keyword.get(opts, :type) do
113 :banner ->
114 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
115
116 :avatar ->
117 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
118
119 :background ->
120 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
121
122 _ ->
123 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
124 end
125
126 %{
127 activity_type: Keyword.get(opts, :activity_type, activity_type),
128 size_limit: Keyword.get(opts, :size_limit, size_limit),
129 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
130 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
131 description: Keyword.get(opts, :description),
132 base_url:
133 Keyword.get(
134 opts,
135 :base_url,
136 Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
137 )
138 }
139 end
140
141 defp prepare_upload(%Plug.Upload{} = file, opts) do
142 with :ok <- check_file_size(file.path, opts.size_limit),
143 {:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
144 {:ok,
145 %__MODULE__{
146 id: UUID.generate(),
147 name: name,
148 tempfile: file.path,
149 content_type: content_type
150 }}
151 end
152 end
153
154 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
155 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
156 data = Base.decode64!(parsed["data"], ignore: :whitespace)
157 hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data)))
158
159 with :ok <- check_binary_size(data, opts.size_limit),
160 tmp_path <- tempfile_for_image(data),
161 {:ok, content_type, name} <-
162 Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do
163 {:ok,
164 %__MODULE__{
165 id: UUID.generate(),
166 name: name,
167 tempfile: tmp_path,
168 content_type: content_type
169 }}
170 end
171 end
172
173 # For Mix.Tasks.MigrateLocalUploads
174 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
175 with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) do
176 {:ok, %__MODULE__{upload | content_type: content_type}}
177 end
178 end
179
180 defp check_binary_size(binary, size_limit)
181 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
182 {:error, :file_too_large}
183 end
184
185 defp check_binary_size(_, _), do: :ok
186
187 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
188 with {:ok, %{size: size}} <- File.stat(path),
189 true <- size <= size_limit do
190 :ok
191 else
192 false -> {:error, :file_too_large}
193 error -> error
194 end
195 end
196
197 defp check_file_size(_, _), do: :ok
198
199 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
200 # automatically.
201 defp tempfile_for_image(data) do
202 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
203 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
204 IO.binwrite(tmp_file, data)
205
206 tmp_path
207 end
208
209 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
210 path =
211 URI.encode(path, &char_unescaped?/1) <>
212 if Pleroma.Config.get([__MODULE__, :link_name], false) do
213 "?name=#{URI.encode(name, &char_unescaped?/1)}"
214 else
215 ""
216 end
217
218 prefix =
219 if is_nil(Pleroma.Config.get([__MODULE__, :base_url])) do
220 "media"
221 else
222 ""
223 end
224
225 [base_url, prefix, path]
226 |> Path.join()
227 end
228
229 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
230 end