Merge branch 'develop' of git.pleroma.social:pleroma/pleroma into remake-remodel
[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 Manage user uploads
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(upload, 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 def char_unescaped?(char) do
89 URI.char_unreserved?(char) or char == ?/
90 end
91
92 defp get_opts(opts) do
93 {size_limit, activity_type} =
94 case Keyword.get(opts, :type) do
95 :banner ->
96 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
97
98 :avatar ->
99 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
100
101 :background ->
102 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
103
104 _ ->
105 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
106 end
107
108 %{
109 activity_type: Keyword.get(opts, :activity_type, activity_type),
110 size_limit: Keyword.get(opts, :size_limit, size_limit),
111 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
112 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
113 description: Keyword.get(opts, :description),
114 base_url:
115 Keyword.get(
116 opts,
117 :base_url,
118 Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
119 )
120 }
121 end
122
123 defp prepare_upload(%Plug.Upload{} = file, opts) do
124 with :ok <- check_file_size(file.path, opts.size_limit),
125 {:ok, content_type, name} <- Pleroma.MIME.file_mime_type(file.path, file.filename) do
126 {:ok,
127 %__MODULE__{
128 id: UUID.generate(),
129 name: name,
130 tempfile: file.path,
131 content_type: content_type
132 }}
133 end
134 end
135
136 defp prepare_upload(%{"img" => "data:image/" <> image_data}, opts) do
137 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
138 data = Base.decode64!(parsed["data"], ignore: :whitespace)
139 hash = String.downcase(Base.encode16(:crypto.hash(:sha256, data)))
140
141 with :ok <- check_binary_size(data, opts.size_limit),
142 tmp_path <- tempfile_for_image(data),
143 {:ok, content_type, name} <-
144 Pleroma.MIME.bin_mime_type(data, hash <> "." <> parsed["filetype"]) do
145 {:ok,
146 %__MODULE__{
147 id: UUID.generate(),
148 name: name,
149 tempfile: tmp_path,
150 content_type: content_type
151 }}
152 end
153 end
154
155 # For Mix.Tasks.MigrateLocalUploads
156 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
157 with {:ok, content_type} <- Pleroma.MIME.file_mime_type(path) do
158 {:ok, %__MODULE__{upload | content_type: content_type}}
159 end
160 end
161
162 defp check_binary_size(binary, size_limit)
163 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
164 {:error, :file_too_large}
165 end
166
167 defp check_binary_size(_, _), do: :ok
168
169 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
170 with {:ok, %{size: size}} <- File.stat(path),
171 true <- size <= size_limit do
172 :ok
173 else
174 false -> {:error, :file_too_large}
175 error -> error
176 end
177 end
178
179 defp check_file_size(_, _), do: :ok
180
181 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
182 # automatically.
183 defp tempfile_for_image(data) do
184 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
185 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
186 IO.binwrite(tmp_file, data)
187
188 tmp_path
189 end
190
191 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
192 path =
193 URI.encode(path, &char_unescaped?/1) <>
194 if Pleroma.Config.get([__MODULE__, :link_name], false) do
195 "?name=#{URI.encode(name, &char_unescaped?/1)}"
196 else
197 ""
198 end
199
200 prefix =
201 if is_nil(Pleroma.Config.get([__MODULE__, :base_url])) do
202 "media"
203 else
204 ""
205 end
206
207 [base_url, prefix, path]
208 |> Path.join()
209 end
210
211 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
212 end