+ require Logger
+
+ @type source ::
+ Plug.Upload.t()
+ | (data_uri_string :: String.t())
+ | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
+
+ @type option ::
+ {:type, :avatar | :banner | :background}
+ | {:description, String.t()}
+ | {:activity_type, String.t()}
+ | {:size_limit, nil | non_neg_integer()}
+ | {:uploader, module()}
+ | {:filters, [module()]}
+
+ @type t :: %__MODULE__{
+ id: String.t(),
+ name: String.t(),
+ tempfile: String.t(),
+ content_type: String.t(),
+ path: String.t()
+ }
+ defstruct [:id, :name, :tempfile, :content_type, :path]
+
+ @spec store(source, options :: [option()]) :: {:ok, Map.t()} | {:error, any()}
+ def store(upload, opts \\ []) do
+ opts = get_opts(opts)
+
+ with {:ok, upload} <- prepare_upload(upload, opts),
+ upload = %__MODULE__{upload | path: upload.path || "#{upload.id}/#{upload.name}"},
+ {:ok, upload} <- Pleroma.Upload.Filter.filter(opts.filters, upload),
+ {:ok, url_spec} <- Pleroma.Uploaders.Uploader.put_file(opts.uploader, upload) do
+ {:ok,
+ %{
+ "type" => opts.activity_type,
+ "url" => [
+ %{
+ "type" => "Link",
+ "mediaType" => upload.content_type,
+ "href" => url_from_spec(upload, opts.base_url, url_spec)
+ }
+ ],
+ "name" => Map.get(opts, :description) || upload.name
+ }}
+ else
+ {:error, error} ->
+ Logger.error(
+ "#{__MODULE__} store (using #{inspect(opts.uploader)}) failed: #{inspect(error)}"
+ )
+
+ {:error, error}
+ end
+ end
+
+ def char_unescaped?(char) do
+ URI.char_unreserved?(char) or char == ?/
+ end
+
+ defp get_opts(opts) do
+ {size_limit, activity_type} =
+ case Keyword.get(opts, :type) do
+ :banner ->
+ {Pleroma.Config.get!([:instance, :banner_upload_limit]), "Image"}
+
+ :avatar ->
+ {Pleroma.Config.get!([:instance, :avatar_upload_limit]), "Image"}
+
+ :background ->
+ {Pleroma.Config.get!([:instance, :background_upload_limit]), "Image"}
+
+ _ ->
+ {Pleroma.Config.get!([:instance, :upload_limit]), "Document"}
+ end
+
+ opts = %{
+ activity_type: Keyword.get(opts, :activity_type, activity_type),
+ size_limit: Keyword.get(opts, :size_limit, size_limit),
+ uploader: Keyword.get(opts, :uploader, Pleroma.Config.get([__MODULE__, :uploader])),
+ filters: Keyword.get(opts, :filters, Pleroma.Config.get([__MODULE__, :filters])),
+ description: Keyword.get(opts, :description),
+ base_url:
+ Keyword.get(
+ opts,
+ :base_url,
+ Pleroma.Config.get([__MODULE__, :base_url], Pleroma.Web.base_url())
+ )