from __future__ import annotations
import ipaddress
import urllib.parse
from dataclasses import dataclass
from eggfetch.compat.httpx._urls import QueryParams
from eggfetch.compat.httpx._urls import URL as _BaseURL
try:
import idna as _idna
except ImportError: _idna = None
_ORIGIN_DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}
@dataclass(frozen=True, slots=True, init=False)
class Origin:
scheme: str
host: str
port: int | None
def __init__(self, url) -> None:
from eggfetch.compat.httpx2._urls import URL as _H2URL
if isinstance(url, Origin):
object.__setattr__(self, "scheme", url.scheme)
object.__setattr__(self, "host", url.host)
object.__setattr__(self, "port", url.port)
return
if not isinstance(url, _BaseURL):
url = _H2URL(str(url))
if url.is_relative_url:
raise ValueError("URL must be absolute to have an origin")
host = url.host or ""
host = host.lower()
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
try:
parsed_ip = ipaddress.ip_address(host)
host = str(parsed_ip)
except ValueError:
if _idna is not None and "xn--" in host:
try:
host = _idna.decode(host)
except Exception:
pass
port = url.port
if port is None:
port = _ORIGIN_DEFAULT_PORTS.get(url.scheme)
object.__setattr__(self, "scheme", url.scheme)
object.__setattr__(self, "host", host)
object.__setattr__(self, "port", port)
class URL(_BaseURL):
__slots__ = ()
def __new__(cls, url="", *, base_url=None):
if isinstance(url, _BaseURL) and not isinstance(url, cls):
instance = object.__new__(cls)
instance._parts = url._parts
instance._raw = url._raw
return instance
return super().__new__(cls, url, base_url=base_url)
@property
def origin(self) -> Origin:
return Origin(self)
def copy_with(self, url=None, params=None):
return _as_httpx2_url(super().copy_with(url=url, params=params))
def join(self, other: "URL") -> "URL":
return _as_httpx2_url(super().join(other))
def _as_httpx2_url(value) -> URL:
if isinstance(value, URL):
return value
if isinstance(value, _BaseURL):
adopted = object.__new__(URL)
adopted._parts = value._parts
adopted._raw = value._raw
return adopted
return URL(value)
def _upgrade_httpx2_url(value):
if isinstance(value, _BaseURL):
return _as_httpx2_url(value)
return value
__all__ = ["Origin", "QueryParams", "URL"]