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