Merge branch 'develop' into 'oembed_provider'
[akkoma] / lib / pleroma / uploaders / uploader.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Uploaders.Uploader do
6 @moduledoc """
7 Defines the contract to put and get an uploaded file to any backend.
8 """
9
10 @doc """
11 Instructs how to get the file from the backend.
12
13 Used by `Pleroma.Plugs.UploadedMedia`.
14 """
15 @type get_method :: {:static_dir, directory :: String.t()} | {:url, url :: String.t()}
16 @callback get_file(file :: String.t()) :: {:ok, get_method()}
17
18 @doc """
19 Put a file to the backend.
20
21 Returns:
22
23 * `:ok` which assumes `{:ok, upload.path}`
24 * `{:ok, spec}` where spec is:
25 * `{:file, filename :: String.t}` to handle reads with `get_file/1` (recommended)
26
27 This allows to correctly proxy or redirect requests to the backend, while allowing to migrate backends without breaking any URL.
28 * `{url, url :: String.t}` to bypass `get_file/2` and use the `url` directly in the activity.
29 * `{:error, String.t}` error information if the file failed to be saved to the backend.
30 * `: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.
31
32
33 """
34 @type file_spec :: {:file | :url, String.t()}
35 @callback put_file(Pleroma.Upload.t()) ::
36 :ok | {:ok, file_spec()} | {:error, String.t()} | :wait_callback
37
38 @callback http_callback(Plug.Conn.t(), Map.t()) ::
39 {:ok, Plug.Conn.t()}
40 | {:ok, Plug.Conn.t(), file_spec()}
41 | {:error, Plug.Conn.t(), String.t()}
42 @optional_callbacks http_callback: 2
43
44 @spec put_file(module(), Pleroma.Upload.t()) :: {:ok, file_spec()} | {:error, String.t()}
45
46 def put_file(uploader, upload) do
47 case uploader.put_file(upload) do
48 :ok -> {:ok, {:file, upload.path}}
49 :wait_callback -> handle_callback(uploader, upload)
50 {:ok, _} = ok -> ok
51 {:error, _} = error -> error
52 end
53 end
54
55 defp handle_callback(uploader, upload) do
56 :global.register_name({__MODULE__, upload.path}, self())
57
58 receive do
59 {__MODULE__, pid, conn, params} ->
60 case uploader.http_callback(conn, params) do
61 {:ok, conn, ok} ->
62 send(pid, {__MODULE__, conn})
63 {:ok, ok}
64
65 {:error, conn, error} ->
66 send(pid, {__MODULE__, conn})
67 {:error, error}
68 end
69 after
70 30_000 -> {:error, "Uploader callback timeout"}
71 end
72 end
73 end