"""Small shared helpers.""" from __future__ import annotations import socket import time _CACHED_IP: tuple[float, str] | None = None def local_ip() -> str: """Best guess of the LAN address of this machine (cached for 60s).""" global _CACHED_IP now = time.monotonic() if _CACHED_IP and now - _CACHED_IP[0] < 60: return _CACHED_IP[1] address = "127.0.0.1" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 80)) address = sock.getsockname()[0] except OSError: try: address = socket.gethostbyname(socket.gethostname()) except OSError: address = "127.0.0.1" finally: sock.close() _CACHED_IP = (now, address) return address def parse_host_port(text: str, default_port: int = 0) -> tuple[str, int]: """Parse ``host``, ``host:port`` or ``[v6]:port`` into a (host, port) pair.""" text = (text or "").strip() if not text: raise ValueError("empty address") if text.startswith("["): host, _, rest = text[1:].partition("]") port = rest.lstrip(":") return host, int(port) if port else default_port if text.count(":") == 1: host, _, port = text.partition(":") return host, int(port) if port else default_port if ":" in text: return text, default_port return text, default_port def format_duration(seconds: float) -> str: seconds = max(0, int(seconds)) if seconds < 60: return f"{seconds}s" if seconds < 3600: return f"{seconds // 60}m{seconds % 60:02d}s" return f"{seconds // 3600}h{(seconds % 3600) // 60:02d}m"