Merge branch 'feature/new-user-routes' into 'develop'
[akkoma] / lib / pleroma / upload.ex
1 defmodule Pleroma.Upload do
2 @moduledoc """
3 # Upload
4
5 Options:
6 * `:type`: presets for activity type (defaults to Document) and size limits from app configuration
7 * `:description`: upload alternative text
8 * `:base_url`: override base url
9 * `:uploader`: override uploader
10 * `:filters`: override filters
11 * `:size_limit`: override size limit
12 * `:activity_type`: override activity type
13
14 The `%Pleroma.Upload{}` struct: all documented fields are meant to be overwritten in filters:
15
16 * `:id` - the upload id.
17 * `:name` - the upload file name.
18 * `:path` - the upload path: set at first to `id/name` but can be changed. Keep in mind that the path
19 is once created permanent and changing it (especially in uploaders) is probably a bad idea!
20 * `:tempfile` - path to the temporary file. Prefer in-place changes on the file rather than changing the
21 path as the temporary file is also tracked by `Plug.Upload{}` and automatically deleted once the request is over.
22
23 Related behaviors:
24
25 * `Pleroma.Uploaders.Uploader`
26 * `Pleroma.Upload.Filter`
27
28 """
29 alias Ecto.UUID
30 require Logger
31
32 @type source ::
33 Plug.Upload.t() | data_uri_string ::
34 String.t() | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
35
36 @type option ::
37 {:type, :avatar | :banner | :background}
38 | {:description, String.t()}
39 | {:activity_type, String.t()}
40 | {:size_limit, nil | non_neg_integer()}
41 | {:uploader, module()}
42 | {:filters, [module()]}
43
44 @type t :: %__MODULE__{
45 id: String.t(),
46 name: String.t(),
47 tempfile: String.t(),
48 content_type: String.t(),
49 path: String.t()
50 }
51 defstruct [:id, :name, :tempfile, :content_type, :path]
52
53 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
54 def store(upload, opts \\ []) do
55 opts = get_opts(opts)
56
57 with {:ok, upload} <- prepare_upload(upload, opts),
58 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
59 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
60 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
61 {:ok,
62 %{
63 "type" => opts.activity_type,
64 "url" => [
65 %{
66 "type" => "Link",
67 "mediaType" => upload.content_type,
68 "href" => url_from_spec(opts.base_url, url_spec)
69 }
70 ],
71 "name" => Map.get(opts, :description) || upload.name
72 }}
73 else
74 {:error, error} ->
75 Logger.error(
76 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
77 )
78
79 {:error, error}
80 end
81 end
82
83 defp get_opts(opts) do
84 {size_limit, activity_type} =
85 case Keyword.get(opts, :type) do
86 :banner ->
87 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
88
89 :avatar ->
90 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
91
92 :background ->
93 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
94
95 _ ->
96 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
97 end
98
99 opts = %{
100 activity_type: Keyword.get(opts, :activity_type, activity_type),
101 size_limit: Keyword.get(opts, :size_limit, size_limit),
102 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
103 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
104 description: Keyword.get(opts, :description),
105 base_url:
106 Keyword.get(
107 opts,
108 :base_url,
109 Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
110 )
111 }
112
113 # TODO: 1.0+ : remove old config compatibility
114 opts =
115 if Pleroma.Config.get([__MODULE__, :strip_exif]) == true &&
116 !Enum.member?(opts.filters, Pleroma.Upload.Filter.Mogrify) do
117 Logger.warn("""
118 Pleroma: configuration `:instance, :strip_exif` is deprecated, please instead set:
119
120 :pleroma, Pleroma.Upload, [filters: [Pleroma.Upload.Filter.Mogrify]]
121
122 :pleroma, Pleroma.Upload.Filter.Mogrify, args: "strip"
123 """)
124
125 Pleroma.Config.put([Pleroma.Upload.Filter.Mogrify], args: "strip")
126 Map.put(opts, :filters, opts.filters ++ [Pleroma.Upload.Filter.Mogrify])
127 else
128 opts
129 end
130
131 if Pleroma.Config.get([:instance, :dedupe_media]) == true &&
132 !Enum.member?(opts.filters, Pleroma.Upload.Filter.Dedupe) do
133 Logger.warn("""
134 Pleroma: configuration `:instance, :dedupe_media` is deprecated, please instead set:
135
136 :pleroma, Pleroma.Upload, [filters: [Pleroma.Upload.Filter.Dedupe]]
137 """)
138
139 Map.put(opts, :filters, opts.filters ++ [Pleroma.Upload.Filter.Dedupe])
140 else
141 opts
142 end
143 end
144
145 defp prepare_upload(%Plug.Upload{} = file, opts) do
146 with :ok <- check_file_size(file.path, opts.size_limit),
147 {:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
148 {:ok,
149 %__MODULE__{
150 id: UUID.generate(),
151 name: name,
152 tempfile: file.path,
153 content_type: content_type
154 }}
155 end
156 end
157
158 defp prepare_upload(%{"img" => "data:image/" <> image_data}, opts) do
159 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
160 data = Base.decode64!(parsed["data"], ignore: :whitespace)
161 hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data)))
162
163 with :ok <- check_binary_size(data, opts.size_limit),
164 tmp_path <- tempfile_for_image(data),
165 {:ok, content_type, name} <-
166 Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do
167 {:ok,
168 %__MODULE__{
169 id: UUID.generate(),
170 name: name,
171 tempfile: tmp_path,
172 content_type: content_type
173 }}
174 end
175 end
176
177 # For Mix.Tasks.MigrateLocalUploads
178 defp prepare_upload(upload = %__MODULE__{tempfile: path}, _opts) do
179 with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) 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(base_url, {:file, path}) do
214 [base_url, "media", path]
215 |> Path.join()
216 end
217
218 defp url_from_spec(_base_url, {:url, url}), do: url
219 end