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