1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 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
31 * `Pleroma.Uploaders.Uploader`
32 * `Pleroma.Upload.Filter`
42 | (data_uri_string :: String.t())
43 | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
47 {:type, :avatar | :banner | :background}
48 | {:description, String.t()}
49 | {:activity_type, String.t()}
50 | {:size_limit, nil | non_neg_integer()}
51 | {:uploader, module()}
52 | {:filters, [module()]}
54 @type t :: %__MODULE__{
58 content_type: String.t(),
63 defstruct [:id, :name, :tempfile, :content_type, :width, :height, :path]
65 defp get_description(opts, upload) do
66 case {opts[:description], Pleroma.Config.get([Pleroma.Upload, :default_description])} do
67 {description, _} when is_binary(description) -> description
68 {_, :filename} -> upload.name
69 {_, str} when is_binary(str) -> str
74 @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
75 @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."
76 def store(upload, opts \\ []) do
79 with {:ok, upload} <- prepare_upload(upload, opts),
80 upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
81 {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
82 description = get_description(opts, upload),
85 String.length(description) <= Pleroma.Config.get([:instance, :description_limit])},
86 {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
89 "type" => opts.activity_type,
90 "mediaType" => upload.content_type,
94 "mediaType" => upload.content_type,
95 "href" => url_from_spec(upload, opts.base_url, url_spec)
97 |> Maps.put_if_present("width", upload.width)
98 |> Maps.put_if_present("height", upload.height)
100 "name" => description
103 {:description_limit, _} ->
104 {:error, :description_too_long}
108 "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
115 def char_unescaped?(char) do
116 URI.char_unreserved?(char) or char == ?/
119 defp get_opts(opts) do
120 {size_limit, activity_type} =
121 case Keyword.get(opts, :type) do
123 {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
126 {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
129 {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
132 {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
136 activity_type: Keyword.get(opts, :activity_type, activity_type),
137 size_limit: Keyword.get(opts, :size_limit, size_limit),
138 uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
139 filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
140 description: Keyword.get(opts, :description),
145 defp prepare_upload(%Plug.Upload{} = file, opts) do
146 with :ok <- check_file_size(file.path, opts.size_limit) do
152 content_type: file.content_type
157 defp prepare_upload(%{img: "data:image/" <> image_data}, opts) do
158 parsed = Regex.named_captures(~r/(?<filetype>jpeg|png|gif);base64,(?<data>.*)/, image_data)
159 data = Base.decode64!(parsed["data"], ignore: :whitespace)
160 hash = Base.encode16(:crypto.hash(:sha256, data), lower: true)
162 with :ok <- check_binary_size(data, opts.size_limit),
163 tmp_path <- tempfile_for_image(data),
164 {:ok, %{mime_type: content_type}} <-
165 Majic.perform({:bytes, data}, pool: Pleroma.MajicPool),
166 [ext | _] <- MIME.extensions(content_type) do
170 name: hash <> "." <> ext,
172 content_type: content_type
177 # For Mix.Tasks.MigrateLocalUploads
178 defp prepare_upload(%__MODULE__{tempfile: path} = upload, _opts) do
179 with {:ok, %{mime_type: content_type}} <- Majic.perform(path, pool: Pleroma.MajicPool) do
180 {:ok, %__MODULE__{upload | content_type: content_type}}
184 defp check_binary_size(binary, size_limit)
185 when is_integer(size_limit) and size_limit > 0 and byte_size(binary) >= size_limit do
186 {:error, :file_too_large}
189 defp check_binary_size(_, _), do: :ok
191 defp check_file_size(path, size_limit) when is_integer(size_limit) and size_limit > 0 do
192 with {:ok, %{size: size}} <- File.stat(path),
193 true <- size <= size_limit do
196 false -> {:error, :file_too_large}
201 defp check_file_size(_, _), do: :ok
203 # Creates a tempfile using the Plug.Upload Genserver which cleans them up
205 defp tempfile_for_image(data) do
206 {:ok, tmp_path} = Plug.Upload.random_file("profile_pics")
207 {:ok, tmp_file} = File.open(tmp_path, [:write, :raw, :binary])
208 IO.binwrite(tmp_file, data)
213 defp url_from_spec(%__MODULE__{name: name}, base_url, {:file, path}) do
215 URI.encode(path, &char_unescaped?/1) <>
216 if Pleroma.Config.get([__MODULE__, :link_name], false) do
217 "?name=#{URI.encode(name, &char_unescaped?/1)}"
226 defp url_from_spec(_upload, _base_url, {:url, url}), do: url
229 uploader = Config.get([Pleroma.Upload, :uploader])
230 upload_base_url = Config.get([Pleroma.Upload, :base_url])
231 public_endpoint = Config.get([uploader, :public_endpoint])
234 Pleroma.Uploaders.Local ->
235 upload_base_url || Pleroma.Web.base_url() <> "/media/"
237 Pleroma.Uploaders.S3 ->
238 bucket = Config.get([Pleroma.Uploaders.S3, :bucket])
239 truncated_namespace = Config.get([Pleroma.Uploaders.S3, :truncated_namespace])
240 namespace = Config.get([Pleroma.Uploaders.S3, :bucket_namespace])
242 bucket_with_namespace =
244 !is_nil(truncated_namespace) ->
247 !is_nil(namespace) ->
248 namespace <> ":" <> bucket
254 if public_endpoint do
255 Path.join([public_endpoint, bucket_with_namespace])
257 Path.join([upload_base_url, bucket_with_namespace])
261 public_endpoint || upload_base_url || Pleroma.Web.base_url() <> "/media/"