- alias Pleroma.Web
- def store(%Plug.Upload{} = file) do
- uuid = UUID.generate
- upload_folder = Path.join(upload_path(), uuid)
- File.mkdir_p!(upload_folder)
- result_file = Path.join(upload_folder, file.filename)
- File.cp!(file.path, result_file)
-
- # fix content type on some image uploads
- matches = Regex.named_captures(~r/\.(?<ext>(jpg|jpeg|png|gif))$/i, file.filename)
- content_type = if file.content_type == "application/octet-stream" and matches do
- if matches["ext"] == "jpg", do: "image/jpeg", else: "image/#{matches["ext"]}"
+ require Logger
+
+ @type source ::
+ Plug.Upload.t()
+ | (data_uri_string :: String.t())
+ | {:from_local, name :: String.t(), id :: String.t(), path :: String.t()}
+ | map()
+
+ @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
+ }}