[Credo][CI] Add readability as it’s fixed
[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 @type file_spec :: {:file | :url, String.t()}
34 @callback put_file(Pleroma.Upload.t()) ::
35 :ok | {:ok, file_spec()} | {:error, String.t()} | :wait_callback
36
37 @callback http_callback(Plug.Conn.t(), Map.t()) ::
38 {:ok, Plug.Conn.t()}
39 | {:ok, Plug.Conn.t(), file_spec()}
40 | {:error, Plug.Conn.t(), String.t()}
41 @optional_callbacks http_callback: 2
42
43 @spec put_file(module(), Pleroma.Upload.t()) :: {:ok, file_spec()} | {:error, String.t()}
44
45 def put_file(uploader, upload) do
46 case uploader.put_file(upload) do
47 :ok -> {:ok, {:file, upload.path}}
48 :wait_callback -> handle_callback(uploader, upload)
49 {:ok, _} = ok -> ok
50 {:error, _} = error -> error
51 end
52 end
53
54 defp handle_callback(uploader, upload) do
55 :global.register_name({__MODULE__, upload.path}, self())
56
57 receive do
58 {__MODULE__, pid, conn, params} ->
59 case uploader.http_callback(conn, params) do
60 {:ok, conn, ok} ->
61 send(pid, {__MODULE__, conn})
62 {:ok, ok}
63
64 {:error, conn, error} ->
65 send(pid, {__MODULE__, conn})
66 {:error, error}
67 end
68 after
69 30_000 -> {:error, "Uploader callback timeout"}
70 end
71 end
72 end