import json import subprocess def env(name): out = subprocess.run(["bash", "-lc", f"grep -m1 '^{name}=' /etc/hub-bots/bots.env | cut -d= -f2-"], capture_output=True, text=True, timeout=20).stdout.strip() return out def read_file(path): try: return open(path, encoding="utf-8").read().strip() except Exception: return "" def lidarr_key(): out = subprocess.run(["pct", "exec", "111", "--", "docker", "exec", "lidarr", "sh", "-c", "grep -o '[^<]*' /config/config.xml"], capture_output=True, text=True, timeout=30).stdout return out.split("")[1].strip() if "" in out else "" TEMPLATE = '''"""Добавляет сервисы в HA (ключи подставлены).""" import json, urllib.error, urllib.request TOK = open("/root/.ha-token", encoding="utf-8").read().strip() BASE = "http://127.0.0.1:8123" HDR = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"} TARGETS = json.loads(__TARGETS__) def call(path, method="GET", body=None): data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR) try: with urllib.request.urlopen(req, timeout=40) as r: raw = r.read() return (json.loads(raw) if raw else {}), None except urllib.error.HTTPError as e: return None, f"HTTP {e.code}: {e.read()[:160].decode('utf-8', 'replace')}" except Exception as e: return None, str(e)[:120] def fill(schema, hints): payload = {} for f in (schema or []): name = f.get("name") if name and name in hints and hints[name] not in (None, ""): payload[name] = hints[name] return payload for domain, hints in TARGETS: flow, err = call("/api/config/config_entries/flow", "POST", {"handler": domain}) if err: print(f" {domain}: старт — {err}") continue fid = flow.get("flow_id") schema = flow.get("data_schema") payload = fill(schema, hints) res, err2 = call(f"/api/config/config_entries/flow/{fid}", "POST", payload) if err2: missing = [f.get("name") for f in (schema or []) if f.get("required") and f.get("name") not in payload] print(f" {domain}: {err2} | не хватило: {missing}") continue t = (res or {}).get("type") for _ in range(3): if t != "form": break schema2 = res.get("data_schema") p2 = fill(schema2, hints) if not p2: print(f" {domain}: нужны поля {[f.get('name') for f in (schema2 or [])]}") break res, err3 = call(f"/api/config/config_entries/flow/{fid}", "POST", p2) if err3: print(f" {domain}: шаг2 — {err3}") break t = (res or {}).get("type") print(f" {domain}: {t}") ''' jf_pass = read_file("/root/.jellyfin-akadmin-password") or "admin" TARGETS = [ ["radarr", {"url": "http://192.168.1.118:7878", "api_key": env("RADARR_KEY"), "verify_ssl": False}], ["sonarr", {"url": "http://192.168.1.117:8989", "api_key": env("SONARR_KEY")}], ["lidarr", {"url": "http://192.168.1.240:8686", "api_key": lidarr_key()}], ["jellyfin", {"url": "http://192.168.1.103:8096", "username": "akadmin", "password": jf_pass}], ["paperless_ngx", {"url": "http://192.168.1.105:8000", "api_key": env("PAPERLESS_TOKEN"), "verify_ssl": False}], ["speedtestdotnet", {}], ] code = TEMPLATE.replace("__TARGETS__", repr(json.dumps(TARGETS, ensure_ascii=False))) open("/tmp/add_services3.py", "w", encoding="utf-8").write(code) print("собрано:", len(code), "байт") for d, _ in TARGETS: print(" -", d)