Merge branch 'develop' of https://git.pleroma.social/pleroma/pleroma into develop
[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 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
60 def store(upload, opts \\ []) do
61 opts = get_opts(opts)
62
63 with {:ok, upload} <- prepare_upload(upload, opts),
64 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
65 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
66 description = Map.get(opts, :description) || upload.name,
67 {_, true} <-
68 {:description_limit,
69 String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
70 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
71 {:ok,
72 %{
73 "type" => opts.activity_type,
74 "mediaType" => upload.content_type,
75 "url" => [
76 %{
77 "type" => "Link",
78 "mediaType" => upload.content_type,
79 "href" => url_from_spec(upload, opts.base_url, url_spec)
80 }
81 ],
82 "name" => description
83 }}
84 else
85 {:description_limit, _} ->
86 {:error, :description_too_long}
87
88 {:error, error} ->
89 Logger.error(
90 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
91 )
92
93 {:error, error}
94 end
95 end
96
97 def char_unescaped?(char) do
98 URI.char_unreserved?(char) or char == ?/
99 end
100
101 defp get_opts(opts) do
102 {size_limit, activity_type} =
103 case Keyword.get(opts, :type) do
104 :banner ->
105 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
106
107 :avatar ->
108 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
109
110 :background ->
111 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
112
113 _ ->
114 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
115 end
116
117 %{
118 activity_type: Keyword.get(opts, :activity_type, activity_type),
119 size_limit: Keyword.get(opts, :size_limit, size_limit),
120 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
121 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
122 description: Keyword.get(opts, :description),
123 base_url:
124 Keyword.get(
125 opts,
126 :base_url,
127 Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
128 )
129 }
130 end
131
132 defp prepare_upload(%Plug.Upload{} = file, opts) do
133 with :ok <- check_file_size(file.path, opts.size_limit),
134 {:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
135 {:ok,
136 %__MODULE__{
137 id: UUID.generate(),
138 name: name,
139 tempfile: file.path,
140 content_type: content_type
141 }}
142 end
143 end
144
145 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
146 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
147 data = Base.decode64!(parsed["data"], ignore: :whitespace)
148 hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data)))
149
150 with :ok <- check_binary_size(data, opts.size_limit),
151 tmp_path <- tempfile_for_image(data),
152 {:ok, content_type, name} <-
153 Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do
154 {:ok,
155 %__MODULE__{
156 id: UUID.generate(),
157 name: name,
158 tempfile: tmp_path,
159 content_type: content_type
160 }}
161 end
162 end
163
164 # For Mix.Tasks.MigrateLocalUploads
165 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
166 with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) do
167 {:ok, %__MODULE__{upload | content_type: content_type}}
168 end
169 end
170
171 defp check_binary_size(binary, size_limit)
172 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
173 {:error, :file_too_large}
174 end
175
176 defp check_binary_size(_, _), do: :ok
177
178 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
179 with {:ok, %{size: size}} <- File.stat(path),
180 true <- size <= size_limit do
181 :ok
182 else
183 false -> {:error, :file_too_large}
184 error -> error
185 end
186 end
187
188 defp check_file_size(_, _), do: :ok
189
190 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
191 # automatically.
192 defp tempfile_for_image(data) do
193 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
194 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
195 IO.binwrite(tmp_file, data)
196
197 tmp_path
198 end
199
200 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
201 path =
202 URI.encode(path, &char_unescaped?/1) <>
203 if Pleroma.Config.get([__MODULE__, :link_name], false) do
204 "?name=#{URI.encode(name, &char_unescaped?/1)}"
205 else
206 ""
207 end
208
209 prefix =
210 if is_nil(Pleroma.Config.get([__MODULE__, :base_url])) do
211 "media"
212 else
213 ""
214 end
215
216 [base_url, prefix, path]
217 |> Path.join()
218 end
219
220 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
221 end