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