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