Merge branch '210_twitter_api_uploads_alt_text' into 'develop'
[akkoma] / lib / pleroma / http / http.ex
1 defmodule Pleroma.HTTP do
2 @moduledoc """
3
4 """
5
6 alias Pleroma.HTTP.Connection
7 alias Pleroma.HTTP.RequestBuilder, as: Builder
8
9 @doc """
10 Builds and perform http request.
11
12 # Arguments:
13 `method` - :get, :post, :put, :delete
14 `url`
15 `body`
16 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
17 `options` - custom, per-request middleware or adapter options
18
19 # Returns:
20 `{:ok, %Tesla.Env{}}` or `{:error, error}`
21
22 """
23 def request(method, url, body \\ "", headers \\ [], options \\ []) do
24 options =
25 process_request_options(options)
26 |> process_sni_options(url)
27
28 %{}
29 |> Builder.method(method)
30 |> Builder.headers(headers)
31 |> Builder.opts(options)
32 |> Builder.url(url)
33 |> Builder.add_param(:body, :body, body)
34 |> Enum.into([])
35 |> (&Tesla.request(Connection.new(), &1)).()
36 end
37
38 defp process_sni_options(options, nil), do: options
39
40 defp process_sni_options(options, url) do
41 uri = URI.parse(url)
42 host = uri.host |> to_charlist()
43
44 case uri.scheme do
45 "https" -> options ++ [ssl: [server_name_indication: host]]
46 _ -> options
47 end
48 end
49
50 def process_request_options(options) do
51 config = Application.get_env(:pleroma, :http, [])
52 proxy = Keyword.get(config, :proxy_url, nil)
53 options = options ++ [adapter: [pool: :default]]
54
55 case proxy do
56 nil -> options
57 _ -> options ++ [proxy: proxy]
58 end
59 end
60
61 @doc """
62 Performs GET request.
63
64 See `Pleroma.HTTP.request/5`
65 """
66 def get(url, headers \\ [], options \\ []),
67 do: request(:get, url, "", headers, options)
68
69 @doc """
70 Performs POST request.
71
72 See `Pleroma.HTTP.request/5`
73 """
74 def post(url, body, headers \\ [], options \\ []),
75 do: request(:post, url, body, headers, options)
76 end