1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Upload do
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
18 The `%Pleroma.Upload{}` struct: all documented fields are meant to be overwritten in filters:
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 * `:width` - width of the media in pixels
27 * `:height` - height of the media in pixels
28 * `:blurhash` - string hash of the image encoded with the blurhash algorithm (https://blurha.sh/)
32 * `Pleroma.Uploaders.Uploader`
33 * `Pleroma.Upload.Filter`
38 alias Pleroma.Web.ActivityPub.Utils
43 | (data_uri_string :: String.t())
44 | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
48 {:type, :avatar | :banner | :background}
49 | {:description, String.t()}
50 | {:activity_type, String.t()}
51 | {:size_limit, nil | non_neg_integer()}
52 | {:uploader, module()}
53 | {:filters, [module()]}
54 | {:actor, String.t()}
56 @type t :: %__MODULE__{
60 content_type: String.t(),
64 description: String.t(),
79 @config_impl Application.compile_env(:pleroma, [__MODULE__, :config_impl], Pleroma.Config)
81 defp get_description(upload) do
82 case {upload.description, Pleroma.Config.get([Pleroma.Upload, :default_description])} do
83 {description, _} when is_binary(description) -> description
84 {_, :filename} -> upload.name
85 {_, str} when is_binary(str) -> str
90 @spec store(source, options :: [option()]) :: {:ok, map()} | {:error, any()}
91 @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."
92 def store(upload, opts \\ []) do
95 with {:ok, upload} <- prepare_upload(upload, opts),
96 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
97 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
98 description = get_description(upload),
101 String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
102 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
105 "id" => Utils.generate_object_id(),
106 "type" => opts.activity_type,
107 "mediaType" => upload.content_type,
111 "mediaType" => upload.content_type,
112 "href" => url_from_spec(upload, opts.base_url, url_spec)
114 |> Maps.put_if_present("width", upload.width)
115 |> Maps.put_if_present("height", upload.height)
117 "name" => description
119 |> Maps.put_if_present("blurhash", upload.blurhash)}
121 {:description_limit, _} ->
122 {:error, :description_too_long}
126 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
133 def char_unescaped?(char) do
134 URI.char_unreserved?(char) or char == ?/
137 defp get_opts(opts) do
138 {size_limit, activity_type} =
139 case Keyword.get(opts, :type) do
141 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
144 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
147 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
150 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
154 activity_type: Keyword.get(opts, :activity_type, activity_type),
155 size_limit: Keyword.get(opts, :size_limit, size_limit),
156 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
157 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
158 description: Keyword.get(opts, :description),
163 defp prepare_upload(%Plug.Upload{} = file, opts) do
164 with :ok <- check_file_size(file.path, opts.size_limit) do
170 content_type: file.content_type,
171 description: opts.description
176 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
177 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
178 data = Base.decode64!(parsed["data"], ignore: :whitespace)
179 hash = Base.encode16(:crypto.hash(:sha256, data), case: :upper)
181 with :ok <- check_binary_size(data, opts.size_limit),
182 tmp_path <- tempfile_for_image(data),
183 {:ok, %{mime_type: content_type}} <-
184 Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
185 [ext | _] <- MIME.extensions(content_type) do
189 name: hash <> "." <> ext,
191 content_type: content_type,
192 description: opts.description
197 # For Mix.Tasks.MigrateLocalUploads
198 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
199 with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
200 {:ok, %__MODULE__{upload | content_type: content_type}}
204 defp check_binary_size(binary, size_limit)
205 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
206 {:error, :file_too_large}
209 defp check_binary_size(_, _), do: :ok
211 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
212 with {:ok, %{size: size}} <- File.stat(path),
213 true <- size <= size_limit do
216 false -> {:error, :file_too_large}
221 defp check_file_size(_, _), do: :ok
223 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
225 defp tempfile_for_image(data) do
226 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
227 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
228 IO.binwrite(tmp_file, data)
233 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
235 URI.encode(path, &char_unescaped?/1) <>
236 if Pleroma.Config.get([__MODULE__, :link_name], false) do
237 "?name=#{URI.encode(name, &char_unescaped?/1)}"
246 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
249 uploader = @config_impl.get([Pleroma.Upload, :uploader])
250 upload_base_url = @config_impl.get([Pleroma.Upload, :base_url])
251 public_endpoint = @config_impl.get([uploader, :public_endpoint])
254 Pleroma.Uploaders.Local ->
255 upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"
257 Pleroma.Uploaders.S3 ->
258 bucket = @config_impl.get([Pleroma.Uploaders.S3, :bucket])
259 truncated_namespace = @config_impl.get([Pleroma.Uploaders.S3, :truncated_namespace])
260 namespace = @config_impl.get([Pleroma.Uploaders.S3, :bucket_namespace])
262 bucket_with_namespace =
264 !is_nil(truncated_namespace) ->
267 !is_nil(namespace) ->
268 namespace <> ":" <> bucket
274 if public_endpoint do
275 Path.join([public_endpoint, bucket_with_namespace])
277 Path.join([upload_base_url, bucket_with_namespace])
281 public_endpoint || upload_base_url || Pleroma.Web.Endpoint.url() <> "/media/"