4ab12ed3ade7041f2d0572dd6db8648ed387f15f
[akkoma] / lib / pleroma / http / http.ex
1 defmodule Pleroma.HTTP do
2 alias Pleroma.HTTP.Connection
3 alias Pleroma.HTTP.RequestBuilder, as: Builder
4
5 @doc """
6 Builds and perform http request.
7 """
8 def request(method, url, body \\ "", headers \\ [], options \\ []) do
9 options =
10 process_request_options(options)
11 |> process_sni_options(url)
12
13 %{}
14 |> Builder.method(method)
15 |> Builder.headers(headers)
16 |> Builder.opts(options)
17 |> Builder.url(url)
18 |> Builder.add_param(:body, :body, body)
19 |> Enum.into([])
20 |> (&Tesla.request(Connection.new(), &1)).()
21 end
22
23 defp process_sni_options(options, nil), do: options
24
25 defp process_sni_options(options, url) do
26 uri = URI.parse(url)
27 host = uri.host |> to_charlist()
28
29 case uri.scheme do
30 "https" -> options ++ [ssl: [server_name_indication: host]]
31 _ -> options
32 end
33 end
34
35 def process_request_options(options) do
36 config = Application.get_env(:pleroma, :http, [])
37 proxy = Keyword.get(config, :proxy_url, nil)
38 options = options ++ [adapter: [pool: :default]]
39
40 case proxy do
41 nil -> options
42 _ -> options ++ [proxy: proxy]
43 end
44 end
45
46 def get(url, headers \\ [], options \\ []),
47 do: request(:get, url, "", headers, options)
48
49 def post(url, body, headers \\ [], options \\ []),
50 do: request(:post, url, body, headers, options)
51 end