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