Merge branch 'fix/credo-issues' into 'develop'
[akkoma] / lib / pleroma / upload.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Upload do
6 @moduledoc """
7 # Upload
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
41 @type option ::
42 {:type, :avatar | :banner | :background}
43 | {:description, String.t()}
44 | {:activity_type, String.t()}
45 | {:size_limit, nil | non_neg_integer()}
46 | {:uploader, module()}
47 | {:filters, [module()]}
48
49 @type t :: %__MODULE__{
50 id: String.t(),
51 name: String.t(),
52 tempfile: String.t(),
53 content_type: String.t(),
54 path: String.t()
55 }
56 defstruct [:id, :name, :tempfile, :content_type, :path]
57
58 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
59 def store(upload, opts \\ []) do
60 opts = get_opts(opts)
61
62 with {:ok, upload} <- prepare_upload(upload, opts),
63 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
64 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
65 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
66 {:ok,
67 %{
68 "type" => opts.activity_type,
69 "url" => [
70 %{
71 "type" => "Link",
72 "mediaType" => upload.content_type,
73 "href" => url_from_spec(opts.base_url, url_spec)
74 }
75 ],
76 "name" => Map.get(opts, :description) || upload.name
77 }}
78 else
79 {:error, error} ->
80 Logger.error(
81 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
82 )
83
84 {:error, error}
85 end
86 end
87
88 defp get_opts(opts) do
89 {size_limit, activity_type} =
90 case Keyword.get(opts, :type) do
91 :banner ->
92 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
93
94 :avatar ->
95 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
96
97 :background ->
98 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
99
100 _ ->
101 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
102 end
103
104 opts = %{
105 activity_type: Keyword.get(opts, :activity_type, activity_type),
106 size_limit: Keyword.get(opts, :size_limit, size_limit),
107 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
108 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
109 description: Keyword.get(opts, :description),
110 base_url:
111 Keyword.get(
112 opts,
113 :base_url,
114 Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
115 )
116 }
117
118 # TODO: 1.0+ : remove old config compatibility
119 opts =
120 if Pleroma.Config.get([__MODULE__, :strip_exif]) == true &&
121 !Enum.member?(opts.filters, Pleroma.Upload.Filter.Mogrify) do
122 Logger.warn("""
123 Pleroma: configuration `:instance, :strip_exif` is deprecated, please instead set:
124
125 :pleroma, Pleroma.Upload, [filters: [Pleroma.Upload.Filter.Mogrify]]
126
127 :pleroma, Pleroma.Upload.Filter.Mogrify, args: ["strip", "auto-orient"]
128 """)
129
130 Pleroma.Config.put([Pleroma.Upload.Filter.Mogrify], args: ["strip", "auto-orient"])
131 Map.put(opts, :filters, opts.filters ++ [Pleroma.Upload.Filter.Mogrify])
132 else
133 opts
134 end
135
136 if Pleroma.Config.get([:instance, :dedupe_media]) == true &&
137 !Enum.member?(opts.filters, Pleroma.Upload.Filter.Dedupe) do
138 Logger.warn("""
139 Pleroma: configuration `:instance, :dedupe_media` is deprecated, please instead set:
140
141 :pleroma, Pleroma.Upload, [filters: [Pleroma.Upload.Filter.Dedupe]]
142 """)
143
144 Map.put(opts, :filters, opts.filters ++ [Pleroma.Upload.Filter.Dedupe])
145 else
146 opts
147 end
148 end
149
150 defp prepare_upload(%Plug.Upload{} = file, opts) do
151 with :ok <- check_file_size(file.path, opts.size_limit),
152 {:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
153 {:ok,
154 %__MODULE__{
155 id: UUID.generate(),
156 name: name,
157 tempfile: file.path,
158 content_type: content_type
159 }}
160 end
161 end
162
163 defp prepare_upload(%{"img" => "data:image/" <> image_data}, opts) do
164 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
165 data = Base.decode64!(parsed["data"], ignore: :whitespace)
166 hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data)))
167
168 with :ok <- check_binary_size(data, opts.size_limit),
169 tmp_path <- tempfile_for_image(data),
170 {:ok, content_type, name} <-
171 Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do
172 {:ok,
173 %__MODULE__{
174 id: UUID.generate(),
175 name: name,
176 tempfile: tmp_path,
177 content_type: content_type
178 }}
179 end
180 end
181
182 # For Mix.Tasks.MigrateLocalUploads
183 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
184 with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) do
185 {:ok, %__MODULE__{upload | content_type: content_type}}
186 end
187 end
188
189 defp check_binary_size(binary, size_limit)
190 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
191 {:error, :file_too_large}
192 end
193
194 defp check_binary_size(_, _), do: :ok
195
196 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
197 with {:ok, %{size: size}} <- File.stat(path),
198 true <- size <= size_limit do
199 :ok
200 else
201 false -> {:error, :file_too_large}
202 error -> error
203 end
204 end
205
206 defp check_file_size(_, _), do: :ok
207
208 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
209 # automatically.
210 defp tempfile_for_image(data) do
211 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
212 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
213 IO.binwrite(tmp_file, data)
214
215 tmp_path
216 end
217
218 defp url_from_spec(base_url, {:file, path}) do
219 path =
220 path
221 |> URI.encode()
222 |> String.replace("?", "%3F")
223 |> String.replace(":", "%3A")
224
225 [base_url, "media", path]
226 |> Path.join()
227 end
228
229 defp url_from_spec(_base_url, {:url, url}), do: url
230 end