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