Remove "default" image description
[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 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
69 @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."
70 def store(upload, opts \\ []) do
71 opts = get_opts(opts)
72
73 with {:ok, upload} <- prepare_upload(upload, opts),
74 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
75 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
76 description = Map.get(opts, :description) || "",
77 {_, true} <-
78 {:description_limit,
79 String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
80 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
81 {:ok,
82 %{
83 "id" => Utils.generate_object_id(),
84 "type" => opts.activity_type,
85 "mediaType" => upload.content_type,
86 "url" => [
87 %{
88 "type" => "Link",
89 "mediaType" => upload.content_type,
90 "href" => url_from_spec(upload, opts.base_url, url_spec)
91 }
92 |> Maps.put_if_present("width", upload.width)
93 |> Maps.put_if_present("height", upload.height)
94 ],
95 "name" => description
96 }
97 |> Maps.put_if_present("blurhash", upload.blurhash)}
98 else
99 {:description_limit, _} ->
100 {:error, :description_too_long}
101
102 {:error, error} ->
103 Logger.error(
104 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
105 )
106
107 {:error, error}
108 end
109 end
110
111 def char_unescaped?(char) do
112 URI.char_unreserved?(char) or char == ?/
113 end
114
115 defp get_opts(opts) do
116 {size_limit, activity_type} =
117 case Keyword.get(opts, :type) do
118 :banner ->
119 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
120
121 :avatar ->
122 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
123
124 :background ->
125 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
126
127 _ ->
128 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
129 end
130
131 %{
132 activity_type: Keyword.get(opts, :activity_type, activity_type),
133 size_limit: Keyword.get(opts, :size_limit, size_limit),
134 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
135 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
136 description: Keyword.get(opts, :description),
137 base_url: base_url()
138 }
139 end
140
141 defp prepare_upload(%Plug.Upload{} = file, opts) do
142 with :ok <- check_file_size(file.path, opts.size_limit) do
143 {:ok,
144 %__MODULE__{
145 id: UUID.generate(),
146 name: file.filename,
147 tempfile: file.path,
148 content_type: file.content_type
149 }}
150 end
151 end
152
153 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
154 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
155 data = Base.decode64!(parsed["data"], ignore: :whitespace)
156 hash = Base.encode16(:crypto.hash(:sha256, data), case: :lower)
157
158 with :ok <- check_binary_size(data, opts.size_limit),
159 tmp_path <- tempfile_for_image(data),
160 {:ok, %{mime_type: content_type}} <-
161 Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
162 [ext | _] <- MIME.extensions(content_type) do
163 {:ok,
164 %__MODULE__{
165 id: UUID.generate(),
166 name: hash <> "." <> ext,
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, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) 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 [base_url, path]
219 |> Path.join()
220 end
221
222 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
223
224 def base_url do
225 uploader = Config.get([Pleroma.Upload, :uploader])
226 upload_base_url = Config.get([Pleroma.Upload, :base_url])
227 public_endpoint = Config.get([uploader, :public_endpoint])
228
229 case uploader do
230 Pleroma.Uploaders.Local ->
231 upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
232
233 Pleroma.Uploaders.S3 ->
234 bucket = Config.get([Pleroma.Uploaders.S3, :bucket])
235 truncated_namespace = Config.get([Pleroma.Uploaders.S3, :truncated_namespace])
236 namespace = Config.get([Pleroma.Uploaders.S3, :bucket_namespace])
237
238 bucket_with_namespace =
239 cond do
240 !is_nil(truncated_namespace) ->
241 truncated_namespace
242
243 !is_nil(namespace) ->
244 namespace <> ":" <> bucket
245
246 true ->
247 bucket
248 end
249
250 if public_endpoint do
251 Path.join([public_endpoint, bucket_with_namespace])
252 else
253 Path.join([upload_base_url, bucket_with_namespace])
254 end
255
256 _ ->
257 public_endpoint || upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
258 end
259 end
260 end