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