fix http request in Salmon
[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 opts =
132 if Pleroma.Config.get([:instance, :dedupe_media]) == true &&
133 !Enum.member?(opts.filters, Pleroma.Upload.Filter.Dedupe) do
134 Logger.warn("""
135 Pleroma: configuration `:instance, :dedupe_media` is deprecated, please instead set:
136
137 :pleroma, Pleroma.Upload, [filters: [Pleroma.Upload.Filter.Dedupe]]
138 """)
139
140 Map.put(opts, :filters, opts.filters ++ [Pleroma.Upload.Filter.Dedupe])
141 else
142 opts
143 end
144 end
145
146 defp prepare_upload(%Plug.Upload{} = file, opts) do
147 with :ok <- check_file_size(file.path, opts.size_limit),
148 {:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
149 {:ok,
150 %__MODULE__{
151 id: UUID.generate(),
152 name: name,
153 tempfile: file.path,
154 content_type: content_type
155 }}
156 end
157 end
158
159 defp prepare_upload(%{"img" => "data:image/" <> image_data}, opts) do
160 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
161 data = Base.decode64!(parsed["data"], ignore: :whitespace)
162 hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data)))
163
164 with :ok <- check_binary_size(data, opts.size_limit),
165 tmp_path <- tempfile_for_image(data),
166 {:ok, content_type, name} <-
167 Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do
168 {:ok,
169 %__MODULE__{
170 id: UUID.generate(),
171 name: name,
172 tempfile: tmp_path,
173 content_type: content_type
174 }}
175 end
176 end
177
178 # For Mix.Tasks.MigrateLocalUploads
179 defp prepare_upload(upload = %__MODULE__{tempfile: path}, _opts) do
180 with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) do
181 {:ok, %__MODULE__{upload | content_type: content_type}}
182 end
183 end
184
185 defp check_binary_size(binary, size_limit)
186 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
187 {:error, :file_too_large}
188 end
189
190 defp check_binary_size(_, _), do: :ok
191
192 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
193 with {:ok, %{size: size}} <- File.stat(path),
194 true <- size <= size_limit do
195 :ok
196 else
197 false -> {:error, :file_too_large}
198 error -> error
199 end
200 end
201
202 defp check_file_size(_, _), do: :ok
203
204 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
205 # automatically.
206 defp tempfile_for_image(data) do
207 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
208 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
209 IO.binwrite(tmp_file, data)
210
211 tmp_path
212 end
213
214 defp url_from_spec(base_url, {:file, path}) do
215 [base_url, "media", path]
216 |> Path.join()
217 end
218
219 defp url_from_spec({:url, url}) do
220 url
221 end
222 end