1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTTP do
7 Wrapper for `Tesla.request/2`.
10 alias Pleroma.HTTP.Connection
11 alias Pleroma.HTTP.Request
12 alias Pleroma.HTTP.RequestBuilder, as: Builder
23 See `Pleroma.HTTP.request/5`
25 @spec get(Request.url() | nil, Request.headers(), keyword()) ::
26 nil | {:ok, Env.t()} | {:error, any()}
27 def get(url, headers \\ [], options \\ [])
28 def get(nil, _, _), do: nil
29 def get(url, headers, options), do: request(:get, url, "", headers, options)
32 Performs POST request.
34 See `Pleroma.HTTP.request/5`
36 @spec post(Request.url(), String.t(), Request.headers(), keyword()) ::
37 {:ok, Env.t()} | {:error, any()}
38 def post(url, body, headers \\ [], options \\ []),
39 do: request(:post, url, body, headers, options)
42 Builds and performs http request.
45 `method` - :get, :post, :put, :delete
48 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
49 `options` - custom, per-request middleware or adapter options
52 `{:ok, %Tesla.Env{}}` or `{:error, error}`
55 @spec request(atom(), Request.url(), String.t(), Request.headers(), keyword()) ::
56 {:ok, Env.t()} | {:error, any()}
57 def request(method, url, body, headers, options) when is_binary(url) do
59 adapter_opts = Connection.options(uri, options[:adapter] || [])
60 options = put_in(options[:adapter], adapter_opts)
61 params = options[:params] || []
62 request = build_request(method, headers, options, url, body, params)
64 adapter = Application.get_env(:tesla, :adapter)
65 client = Tesla.client([Tesla.Middleware.FollowRedirects], adapter)
67 pid = Process.whereis(adapter_opts[:pool])
70 if adapter == Tesla.Adapter.Gun && pid do
79 |> Map.put(:env, Pleroma.Config.get([:env]))
80 |> Map.put(:pool_alive?, pool_alive?)
82 response = request(client, request, request_opts)
84 Connection.after_request(adapter_opts)
89 @spec request(Client.t(), keyword(), map()) :: {:ok, Env.t()} | {:error, any()}
90 def request(%Client{} = client, request, %{env: :test}), do: request(client, request)
92 def request(%Client{} = client, request, %{body_as: :chunks}), do: request(client, request)
94 def request(%Client{} = client, request, %{pool_alive?: false}), do: request(client, request)
96 def request(%Client{} = client, request, %{pool: pool, timeout: timeout}) do
99 &Pleroma.Pool.Request.execute(&1, client, request, timeout),
104 @spec request(Client.t(), keyword()) :: {:ok, Env.t()} | {:error, any()}
105 def request(client, request), do: Tesla.request(client, request)
107 defp build_request(method, headers, options, url, body, params) do
109 |> Builder.method(method)
110 |> Builder.headers(headers)
111 |> Builder.opts(options)
113 |> Builder.add_param(:body, :body, body)
114 |> Builder.add_param(:query, :query, params)
115 |> Builder.convert_to_keyword()