http.ex 1.75 KB
Newer Older
1
defmodule Pleroma.HTTP do
Maksim's avatar
Maksim committed
2
3
4
5
  @moduledoc """

  """

6
7
  alias Pleroma.HTTP.Connection
  alias Pleroma.HTTP.RequestBuilder, as: Builder
kaniini's avatar
kaniini committed
8

Maksim's avatar
Maksim committed
9
10
  @doc """
  Builds and perform http request.
Maksim's avatar
Maksim committed
11
12
13
14
15
16
17
18
19
20
21

  # Arguments:
  `method` - :get, :post, :put, :delete
  `url`
  `body`
  `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
  `options` - custom, per-request middleware or adapter options

  # Returns:
  `{:ok, %Tesla.Env{}}` or `{:error, error}`

Maksim's avatar
Maksim committed
22
  """
kaniini's avatar
kaniini committed
23
24
25
26
27
  def request(method, url, body \\ "", headers \\ [], options \\ []) do
    options =
      process_request_options(options)
      |> process_sni_options(url)

28
29
30
31
32
33
34
35
    %{}
    |> Builder.method(method)
    |> Builder.headers(headers)
    |> Builder.opts(options)
    |> Builder.url(url)
    |> Builder.add_param(:body, :body, body)
    |> Enum.into([])
    |> (&Tesla.request(Connection.new(), &1)).()
kaniini's avatar
kaniini committed
36
37
  end

Maksim's avatar
Maksim committed
38
  defp process_sni_options(options, nil), do: options
Maksim's avatar
Maksim committed
39

kaniini's avatar
kaniini committed
40
41
42
43
44
45
46
47
48
  defp process_sni_options(options, url) do
    uri = URI.parse(url)
    host = uri.host |> to_charlist()

    case uri.scheme do
      "https" -> options ++ [ssl: [server_name_indication: host]]
      _ -> options
    end
  end
49

kaniini's avatar
kaniini committed
50
  def process_request_options(options) do
51
    config = Application.get_env(:pleroma, :http, [])
jeff's avatar
jeff committed
52
    proxy = Keyword.get(config, :proxy_url, nil)
53
    options = options ++ [adapter: [pool: :default]]
lain's avatar
lain committed
54

55
    case proxy do
jeff's avatar
jeff committed
56
      nil -> options
57
58
59
      _ -> options ++ [proxy: proxy]
    end
  end
kaniini's avatar
kaniini committed
60

Maksim's avatar
Maksim committed
61
62
63
64
65
  @doc """
  Performs GET request.

  See `Pleroma.HTTP.request/5`
  """
66
67
  def get(url, headers \\ [], options \\ []),
    do: request(:get, url, "", headers, options)
kaniini's avatar
kaniini committed
68

Maksim's avatar
Maksim committed
69
70
71
72
73
  @doc """
  Performs POST request.

  See `Pleroma.HTTP.request/5`
  """
kaniini's avatar
kaniini committed
74
75
  def post(url, body, headers \\ [], options \\ []),
    do: request(:post, url, body, headers, options)
76
end