"""Общие утилиты: HTTP с кэшем и разбор ответов.""" import json import time import urllib.error import urllib.parse import urllib.request from urllib.parse import quote # noqa: F401 (имя используется ботами) _CACHE = {} TTL_DEFAULT = 120 def get(url, headers=None, ttl=TTL_DEFAULT, timeout=12): """GET с кэшем на ttl секунд. Возвращает (данные|None, ошибка|None).""" key = url now = time.time() if key in _CACHE and now - _CACHE[key][0] < ttl: return _CACHE[key][1], _CACHE[key][2] req = urllib.request.Request(url, headers=headers or {}) try: with urllib.request.urlopen(req, timeout=timeout) as r: raw = r.read() try: data = json.loads(raw) except json.JSONDecodeError: data = raw.decode("utf-8", "replace") _CACHE[key] = (now, data, None) return data, None except urllib.error.HTTPError as e: body = "" try: body = e.read().decode("utf-8", "replace")[:200] except Exception: pass _CACHE[key] = (now, None, f"HTTP {e.code} {body}") return None, f"HTTP {e.code} {body}" except Exception as e: _CACHE[key] = (now, None, str(e)[:120]) return None, str(e)[:120] def post(url, payload=None, headers=None, form=False, timeout=15): hdrs = dict(headers or {}) if form: body = urllib.parse.urlencode(payload or {}).encode() hdrs["Content-Type"] = "application/x-www-form-urlencoded" else: body = json.dumps(payload or {}).encode() hdrs.setdefault("Content-Type", "application/json") req = urllib.request.Request(url, data=body, headers=hdrs, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as r: raw = r.read() try: return json.loads(raw), None except json.JSONDecodeError: return raw.decode("utf-8", "replace"), None except urllib.error.HTTPError as e: return None, f"HTTP {e.code} {e.read().decode('utf-8', 'replace')[:160]}" except Exception as e: return None, str(e)[:120] def human_bytes(n): try: n = float(n) except (TypeError, ValueError): return "—" for unit in ("Б", "КБ", "МБ", "ГБ", "ТБ"): if abs(n) < 1024: return f"{n:.1f} {unit}" n /= 1024 return f"{n:.1f} ПБ" def human_time(seconds): try: s = int(float(seconds)) except (TypeError, ValueError): return "—" if s < 60: return f"{s} с" if s < 3600: return f"{s // 60} мин" if s < 86400: return f"{s // 3600} ч {s % 3600 // 60} мин" return f"{s // 86400} дн {s % 86400 // 3600} ч"