Merge branch 'develop' into feature/gen-magic
[akkoma] / lib / pleroma / upload.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 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 require Logger
35
36 @type source ::
37 Plug.Upload.t()
38 | (data_uri_string :: String.t())
39 | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
40 | map()
41
42 @type option ::
43 {:type, :avatar | :banner | :background}
44 | {:description, String.t()}
45 | {:activity_type, String.t()}
46 | {:size_limit, nil | non_neg_integer()}
47 | {:uploader, module()}
48 | {:filters, [module()]}
49
50 @type t :: %__MODULE__{
51 id: String.t(),
52 name: String.t(),
53 tempfile: String.t(),
54 content_type: String.t(),
55 path: String.t()
56 }
57 defstruct [:id, :name, :tempfile, :content_type, :path]
58
59 defp get_description(opts, upload) do
60 case {opts[:description], Pleroma.Config.get([Pleroma.Upload, :default_description])} do
61 {description, _} when is_binary(description) -> description
62 {_, :filename} -> upload.name
63 {_, str} when is_binary(str) -> str
64 _ -> ""
65 end
66 end
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 = get_description(opts, upload),
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 "type" => opts.activity_type,
84 "mediaType" => upload.content_type,
85 "url" => [
86 %{
87 "type" => "Link",
88 "mediaType" => upload.content_type,
89 "href" => url_from_spec(upload, opts.base_url, url_spec)
90 }
91 ],
92 "name" => description
93 }}
94 else
95 {:description_limit, _} ->
96 {:error, :description_too_long}
97
98 {:error, error} ->
99 Logger.error(
100 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
101 )
102
103 {:error, error}
104 end
105 end
106
107 def char_unescaped?(char) do
108 URI.char_unreserved?(char) or char == ?/
109 end
110
111 defp get_opts(opts) do
112 {size_limit, activity_type} =
113 case Keyword.get(opts, :type) do
114 :banner ->
115 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
116
117 :avatar ->
118 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
119
120 :background ->
121 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
122
123 _ ->
124 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
125 end
126
127 %{
128 activity_type: Keyword.get(opts, :activity_type, activity_type),
129 size_limit: Keyword.get(opts, :size_limit, size_limit),
130 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
131 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
132 description: Keyword.get(opts, :description),
133 base_url:
134 Keyword.get(
135 opts,
136 :base_url,
137 Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
138 )
139 }
140 end
141
142 defp prepare_upload(%Plug.Upload{} = file, opts) do
143 with :ok <- check_file_size(file.path, opts.size_limit) do
144 {:ok,
145 %__MODULE__{
146 id: UUID.generate(),
147 name: file.filename,
148 tempfile: file.path,
149 content_type: file.content_type
150 }}
151 end
152 end
153
154 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
155 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
156 data = Base.decode64!(parsed["data"], ignore: :whitespace)
157 hash = Base.encode16(:crypto.hash(:sha256, data), lower: true)
158
159 with :ok <- check_binary_size(data, opts.size_limit),
160 tmp_path <- tempfile_for_image(data),
161 {:ok, %{mime_type: content_type}} <-
162 Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
163 [ext | _] <- MIME.extensions(content_type) do
164 {:ok,
165 %__MODULE__{
166 id: UUID.generate(),
167 name: hash <> "." <> ext,
168 tempfile: tmp_path,
169 content_type: content_type
170 }}
171 end
172 end
173
174 # For Mix.Tasks.MigrateLocalUploads
175 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
176 with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
177 {:ok, %__MODULE__{upload | content_type: content_type}}
178 end
179 end
180
181 defp check_binary_size(binary, size_limit)
182 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
183 {:error, :file_too_large}
184 end
185
186 defp check_binary_size(_, _), do: :ok
187
188 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
189 with {:ok, %{size: size}} <- File.stat(path),
190 true <- size <= size_limit do
191 :ok
192 else
193 false -> {:error, :file_too_large}
194 error -> error
195 end
196 end
197
198 defp check_file_size(_, _), do: :ok
199
200 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
201 # automatically.
202 defp tempfile_for_image(data) do
203 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
204 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
205 IO.binwrite(tmp_file, data)
206
207 tmp_path
208 end
209
210 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
211 path =
212 URI.encode(path, &char_unescaped?/1) <>
213 if Pleroma.Config.get([__MODULE__, :link_name], false) do
214 "?name=#{URI.encode(name, &char_unescaped?/1)}"
215 else
216 ""
217 end
218
219 prefix =
220 if is_nil(Pleroma.Config.get([__MODULE__, :base_url])) do
221 "media"
222 else
223 ""
224 end
225
226 [base_url, prefix, path]
227 |> Path.join()
228 end
229
230 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
231 end