adapter.ex (1885B)
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.Adapter do 6 alias Pleroma.HTTP.Connection 7 8 @type proxy :: 9 {Connection.host(), pos_integer()} 10 | {Connection.proxy_type(), pos_integer()} 11 @type host_type :: :domain | :ip 12 13 @callback options(keyword(), URI.t()) :: keyword() 14 @callback after_request(keyword()) :: :ok 15 16 @spec options(keyword(), URI.t()) :: keyword() 17 def options(opts, _uri) do 18 proxy = Pleroma.Config.get([:http, :proxy_url], nil) 19 maybe_add_proxy(opts, format_proxy(proxy)) 20 end 21 22 @spec maybe_get_conn(URI.t(), keyword()) :: keyword() 23 def maybe_get_conn(_uri, opts), do: opts 24 25 @spec after_request(keyword()) :: :ok 26 def after_request(_opts), do: :ok 27 28 @spec format_proxy(String.t() | tuple() | nil) :: proxy() | nil 29 def format_proxy(nil), do: nil 30 31 def format_proxy(proxy_url) do 32 with {:ok, host, port} <- Connection.parse_proxy(proxy_url) do 33 {host, port} 34 else 35 {:ok, type, host, port} -> {type, host, port} 36 _ -> nil 37 end 38 end 39 40 @spec maybe_add_proxy(keyword(), proxy() | nil) :: keyword() 41 def maybe_add_proxy(opts, nil), do: opts 42 def maybe_add_proxy(opts, proxy), do: Keyword.put_new(opts, :proxy, proxy) 43 44 @spec domain_or_fallback(String.t()) :: charlist() 45 def domain_or_fallback(host) do 46 case domain_or_ip(host) do 47 {:domain, domain} -> domain 48 {:ip, _ip} -> to_charlist(host) 49 end 50 end 51 52 @spec domain_or_ip(String.t()) :: {host_type(), Connection.host()} 53 def domain_or_ip(host) do 54 charlist = to_charlist(host) 55 56 case :inet.parse_address(charlist) do 57 {:error, :einval} -> 58 {:domain, :idna.encode(charlist)} 59 60 {:ok, ip} when is_tuple(ip) and tuple_size(ip) in [4, 8] -> 61 {:ip, ip} 62 end 63 end 64 end