revert ae54c06bb4bd2389d6eb1502b842c6b632e12e40
[akkoma] / lib / pleroma / upload.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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 * `:width` - width of the media in pixels
27 * `:height` - height of the media in pixels
28 * `:blurhash` - string hash of the image encoded with the blurhash algorithm (https://blurha.sh/)
29
30 Related behaviors:
31
32 * `Pleroma.Uploaders.Uploader`
33 * `Pleroma.Upload.Filter`
34
35 """
36 alias Ecto.UUID
37 alias Pleroma.Config
38 alias Pleroma.Maps
39 alias Pleroma.Web.ActivityPub.Utils
40 require Logger
41
42 @type source ::
43 Plug.Upload.t()
44 | (data_uri_string :: String.t())
45 | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
46 | map()
47
48 @type option ::
49 {:type, :avatar | :banner | :background}
50 | {:description, String.t()}
51 | {:activity_type, String.t()}
52 | {:size_limit, nil | non_neg_integer()}
53 | {:uploader, module()}
54 | {:filters, [module()]}
55
56 @type t :: %__MODULE__{
57 id: String.t(),
58 name: String.t(),
59 tempfile: String.t(),
60 content_type: String.t(),
61 width: integer(),
62 height: integer(),
63 blurhash: String.t(),
64 path: String.t()
65 }
66 defstruct [:id, :name, :tempfile, :content_type, :width, :height, :blurhash, :path]
67
68 defp get_description(opts, upload) do
69 case {opts[:description], Pleroma.Config.get([Pleroma.Upload, :default_description])} do
70 {description, _} when is_binary(description) -> description
71 {_, :filename} -> upload.name
72 {_, str} when is_binary(str) -> str
73 _ -> ""
74 end
75 end
76
77 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
78 @doc "Store a file. If using a `Plug.Upload{}` as the source, be sure to use `Majic.Plug` to ensure its content_type and filename is correct."
79 def store(upload, opts \\ []) do
80 opts = get_opts(opts)
81
82 with {:ok, upload} <- prepare_upload(upload, opts),
83 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
84 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
85 description = get_description(opts, upload),
86 {_, true} <-
87 {:description_limit,
88 String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
89 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
90 {:ok,
91 %{
92 "id" => Utils.generate_object_id(),
93 "type" => opts.activity_type,
94 "mediaType" => upload.content_type,
95 "url" => [
96 %{
97 "type" => "Link",
98 "mediaType" => upload.content_type,
99 "href" => url_from_spec(upload, opts.base_url, url_spec)
100 }
101 |> Maps.put_if_present("width", upload.width)
102 |> Maps.put_if_present("height", upload.height)
103 ],
104 "name" => description
105 }
106 |> Maps.put_if_present("blurhash", upload.blurhash)}
107 else
108 {:description_limit, _} ->
109 {:error, :description_too_long}
110
111 {:error, error} ->
112 Logger.error(
113 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
114 )
115
116 {:error, error}
117 end
118 end
119
120 def char_unescaped?(char) do
121 URI.char_unreserved?(char) or char == ?/
122 end
123
124 defp get_opts(opts) do
125 {size_limit, activity_type} =
126 case Keyword.get(opts, :type) do
127 :banner ->
128 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
129
130 :avatar ->
131 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
132
133 :background ->
134 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
135
136 _ ->
137 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
138 end
139
140 %{
141 activity_type: Keyword.get(opts, :activity_type, activity_type),
142 size_limit: Keyword.get(opts, :size_limit, size_limit),
143 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
144 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
145 description: Keyword.get(opts, :description),
146 base_url: base_url()
147 }
148 end
149
150 defp prepare_upload(%Plug.Upload{} = file, opts) do
151 with :ok <- check_file_size(file.path, opts.size_limit) do
152 {:ok,
153 %__MODULE__{
154 id: UUID.generate(),
155 name: file.filename,
156 tempfile: file.path,
157 content_type: file.content_type
158 }}
159 end
160 end
161
162 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
163 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
164 data = Base.decode64!(parsed["data"], ignore: :whitespace)
165 hash = Base.encode16(:crypto.hash(:sha256, data), case: :lower)
166
167 with :ok <- check_binary_size(data, opts.size_limit),
168 tmp_path <- tempfile_for_image(data),
169 {:ok, %{mime_type: content_type}} <-
170 Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
171 [ext | _] <- MIME.extensions(content_type) do
172 {:ok,
173 %__MODULE__{
174 id: UUID.generate(),
175 name: hash <> "." <> ext,
176 tempfile: tmp_path,
177 content_type: content_type
178 }}
179 end
180 end
181
182 # For Mix.Tasks.MigrateLocalUploads
183 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
184 with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
185 {:ok, %__MODULE__{upload | content_type: content_type}}
186 end
187 end
188
189 defp check_binary_size(binary, size_limit)
190 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
191 {:error, :file_too_large}
192 end
193
194 defp check_binary_size(_, _), do: :ok
195
196 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
197 with {:ok, %{size: size}} <- File.stat(path),
198 true <- size <= size_limit do
199 :ok
200 else
201 false -> {:error, :file_too_large}
202 error -> error
203 end
204 end
205
206 defp check_file_size(_, _), do: :ok
207
208 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
209 # automatically.
210 defp tempfile_for_image(data) do
211 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
212 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
213 IO.binwrite(tmp_file, data)
214
215 tmp_path
216 end
217
218 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
219 path =
220 URI.encode(path, &char_unescaped?/1) <>
221 if Pleroma.Config.get([__MODULE__, :link_name], false) do
222 "?name=#{URI.encode(name, &char_unescaped?/1)}"
223 else
224 ""
225 end
226
227 [base_url, path]
228 |> Path.join()
229 end
230
231 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
232
233 def base_url do
234 uploader = Config.get([Pleroma.Upload, :uploader])
235 upload_base_url = Config.get([Pleroma.Upload, :base_url])
236 public_endpoint = Config.get([uploader, :public_endpoint])
237
238 case uploader do
239 Pleroma.Uploaders.Local ->
240 upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
241
242 Pleroma.Uploaders.S3 ->
243 bucket = Config.get([Pleroma.Uploaders.S3, :bucket])
244 truncated_namespace = Config.get([Pleroma.Uploaders.S3, :truncated_namespace])
245 namespace = Config.get([Pleroma.Uploaders.S3, :bucket_namespace])
246
247 bucket_with_namespace =
248 cond do
249 !is_nil(truncated_namespace) ->
250 truncated_namespace
251
252 !is_nil(namespace) ->
253 namespace <> ":" <> bucket
254
255 true ->
256 bucket
257 end
258
259 if public_endpoint do
260 Path.join([public_endpoint, bucket_with_namespace])
261 else
262 Path.join([upload_base_url, bucket_with_namespace])
263 end
264
265 _ ->
266 public_endpoint || upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
267 end
268 end
269 end