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