logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

uploader.ex (2726B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Uploaders.Uploader do
  5. import Pleroma.Web.Gettext
  6. @moduledoc """
  7. Defines the contract to put and get an uploaded file to any backend.
  8. """
  9. @doc """
  10. Instructs how to get the file from the backend.
  11. Used by `Pleroma.Web.Plugs.UploadedMedia`.
  12. """
  13. @type get_method :: {:static_dir, directory :: String.t()} | {:url, url :: String.t()}
  14. @callback get_file(file :: String.t()) :: {:ok, get_method()}
  15. @doc """
  16. Put a file to the backend.
  17. Returns:
  18. * `:ok` which assumes `{:ok, upload.path}`
  19. * `{:ok, spec}` where spec is:
  20. * `{:file, filename :: String.t}` to handle reads with `get_file/1` (recommended)
  21. This allows to correctly proxy or redirect requests to the backend, while allowing to migrate backends without breaking any URL.
  22. * `{url, url :: String.t}` to bypass `get_file/2` and use the `url` directly in the activity.
  23. * `{:error, String.t}` error information if the file failed to be saved to the backend.
  24. * `:wait_callback` will wait for an http post request at `/api/pleroma/upload_callback/:upload_path` and call the uploader's `http_callback/3` method.
  25. """
  26. @type file_spec :: {:file | :url, String.t()}
  27. @callback put_file(upload :: struct()) ::
  28. :ok | {:ok, file_spec()} | {:error, String.t()} | :wait_callback
  29. @callback delete_file(file :: String.t()) :: :ok | {:error, String.t()}
  30. @callback http_callback(Plug.Conn.t(), map()) ::
  31. {:ok, Plug.Conn.t()}
  32. | {:ok, Plug.Conn.t(), file_spec()}
  33. | {:error, Plug.Conn.t(), String.t()}
  34. @optional_callbacks http_callback: 2
  35. @spec put_file(module(), upload :: struct()) :: {:ok, file_spec()} | {:error, String.t()}
  36. def put_file(uploader, upload) do
  37. case uploader.put_file(upload) do
  38. :ok -> {:ok, {:file, upload.path}}
  39. :wait_callback -> handle_callback(uploader, upload)
  40. {:ok, _} = ok -> ok
  41. {:error, _} = error -> error
  42. end
  43. end
  44. defp handle_callback(uploader, upload) do
  45. :global.register_name({__MODULE__, upload.path}, self())
  46. receive do
  47. {__MODULE__, pid, conn, params} ->
  48. case uploader.http_callback(conn, params) do
  49. {:ok, conn, ok} ->
  50. send(pid, {__MODULE__, conn})
  51. {:ok, ok}
  52. {:error, conn, error} ->
  53. send(pid, {__MODULE__, conn})
  54. {:error, error}
  55. end
  56. after
  57. callback_timeout() -> {:error, dgettext("errors", "Uploader callback timeout")}
  58. end
  59. end
  60. defp callback_timeout, do: Application.get_env(:pleroma, __MODULE__)[:timeout]
  61. end