26214ef3feca94c4af8e12b2b07c832b0a3c0c7d
[akkoma] / lib / pleroma / http / http.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.HTTP do
6 @moduledoc """
7
8 """
9
10 alias Pleroma.HTTP.Connection
11 alias Pleroma.HTTP.RequestBuilder, as: Builder
12
13 @type t :: __MODULE__
14
15 @doc """
16 Builds and perform http request.
17
18 # Arguments:
19 `method` - :get, :post, :put, :delete
20 `url`
21 `body`
22 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
23 `options` - custom, per-request middleware or adapter options
24
25 # Returns:
26 `{:ok, %Tesla.Env{}}` or `{:error, error}`
27
28 """
29 def request(method, url, body \\ "", headers \\ [], options \\ []) do
30 options =
31 process_request_options(options)
32 |> process_sni_options(url)
33 |> process_adapter_options()
34
35 params = Keyword.get(options, :params, [])
36
37 %{}
38 |> Builder.method(method)
39 |> Builder.headers(headers)
40 |> Builder.opts(options)
41 |> Builder.url(url)
42 |> Builder.add_param(:body, :body, body)
43 |> Builder.add_param(:query, :query, params)
44 |> Enum.into([])
45 |> (&Tesla.request(Connection.new(), &1)).()
46 end
47
48 defp process_sni_options(options, nil), do: options
49
50 defp process_sni_options(options, url) do
51 uri = URI.parse(url)
52 host = uri.host |> to_charlist()
53
54 case uri.scheme do
55 "https" -> options ++ [ssl: [server_name_indication: host]]
56 _ -> options
57 end
58 end
59
60 def process_adapter_options(options) do
61 adapter_options = Pleroma.Config.get([:http, :adapter], [])
62
63 options ++ [adapter: adapter_options]
64 end
65
66 def process_request_options(options) do
67 config = Application.get_env(:pleroma, :http, [])
68 proxy = Keyword.get(config, :proxy_url, nil)
69
70 case proxy do
71 nil -> options
72 _ -> options ++ [proxy: proxy]
73 end
74 end
75
76 @doc """
77 Performs GET request.
78
79 See `Pleroma.HTTP.request/5`
80 """
81 def get(url, headers \\ [], options \\ []),
82 do: request(:get, url, "", headers, options)
83
84 @doc """
85 Performs POST request.
86
87 See `Pleroma.HTTP.request/5`
88 """
89 def post(url, body, headers \\ [], options \\ []),
90 do: request(:post, url, body, headers, options)
91 end