From 20541df9b668f91acd25eaed177e78eb77b34605 Mon Sep 17 00:00:00 2001 From: buryan-agent Date: Tue, 20 Oct 2026 19:28:20 +0300 Subject: [PATCH] =?UTF-8?q?=D0=95=D1=89=D1=91=20=D0=B8=D0=BD=D1=82=D0=B5?= =?UTF-8?q?=D0=B3=D1=80=D0=B0=D1=86=D0=B8=D0=B8:=20Syncthing,=20Seerr,=20G?= =?UTF-8?q?itea,=20Paperless?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Syncthing подключён ядровой интеграцией по API-ключу из config.xml. Seerr — через HaSeerr (ставили вручную, HACS не качал). Gitea и Paperless — REST-сенсорами, потому что интеграция Gitea 2022 года без config flow, а Paperless-интеграция не понимает версию 3.3.2. Итого 35 интеграций и 246 сущностей. Не удалось: Immich (нет пароля, БД на хосте пустая), Linkding (токен недействителен), Navidrome (нет пользователей), Nextcloud и Portainer (нет учёток). --- ops/homeassistant/INTEGRATIONS-2.md | 40 +++++++++++++++++++++ ops/homeassistant/add_gitea_sensors.py | 49 ++++++++++++++++++++++++++ ops/homeassistant/add_haseerr.py | 39 ++++++++++++++++++++ ops/homeassistant/add_paperless.py | 49 ++++++++++++++++++++++++++ ops/homeassistant/add_syncthing.py | 35 ++++++++++++++++++ 5 files changed, 212 insertions(+) create mode 100644 ops/homeassistant/INTEGRATIONS-2.md create mode 100644 ops/homeassistant/add_gitea_sensors.py create mode 100644 ops/homeassistant/add_haseerr.py create mode 100644 ops/homeassistant/add_paperless.py create mode 100644 ops/homeassistant/add_syncthing.py diff --git a/ops/homeassistant/INTEGRATIONS-2.md b/ops/homeassistant/INTEGRATIONS-2.md new file mode 100644 index 0000000..ed6c5ee --- /dev/null +++ b/ops/homeassistant/INTEGRATIONS-2.md @@ -0,0 +1,40 @@ +# Интеграции: второй заход + +Добавлено после MQTT-брокера. + +## Подключено + +| Сервис | Как | Сущности | +|---|---|---| +| **Syncthing** | ядровая, API-ключ из `config.xml` | синхронизация | +| **Seerr** | `svilendotorg/HaSeerr` (HACS-репо, ставили вручную) | `sensor.haseerr_status` | +| **Gitea** | REST-сенсоры (интеграция 2022 г. без config flow) | репозиториев 5 | +| **Paperless** | REST-сенсоры с токеном | документов 0, тегов 0 | +| **Proxmox** | REST-сенсоры + токен `monitoring@pve` | CPU/RAM/uptime/диск | +| **Authentik** | REST-сенсор | 11 пользователей | +| **Prometheus** | REST-сенсор | 34 цели | +| **MQTT** | ядровая | брокер 192.168.1.107 | +| **Frigate** | кастомная 5.15.6 | `update.frigate_server` | + +Итого: **35 интеграций, 246 сущностей**. + +## Где нужны ваши доступы + +| Сервис | Что нужно | Почему не вышло | +|---|---|---| +| **Immich** | пароль админа или API-ключ | `PHOTO_TOKEN` — это Matrix-токен, не Immich. База `immich_database` на хосте пустая (нет таблиц) — реальная БД в VM 104 | +| **Linkding** | новый токен | токен `e8425190…` → `Invalid token` (401) | +| **Navidrome** | логин/пароль | `navidrome user list` пуст — пользователей нет | +| **Nextcloud** | логин/пароль | не нашли учётку | +| **Portainer** | логин/пароль | не нашли инстанс/учётку | +| **Jackett** | ключ есть, интеграции нет | HACS-вариант слабый (1★) | + +## Ловушки + +1. Интеграция `youdroid/home-assistant-gitea` (2022) не имеет `config_flow` — + в HA 2026 не поднимается, поэтому Gitea сделана REST-сенсорами. +2. HACS отказывается скачивать часть репозиториев + (`This integration is not available for download`) — ставили вручную + архивом с ветки. +3. `sensor.haseerr_status = unmapped_user` — нужно сопоставить пользователя + Seerr с пользователем HA; options-flow у HaSeerr отдаёт 500. diff --git a/ops/homeassistant/add_gitea_sensors.py b/ops/homeassistant/add_gitea_sensors.py new file mode 100644 index 0000000..9779042 --- /dev/null +++ b/ops/homeassistant/add_gitea_sensors.py @@ -0,0 +1,49 @@ +"""Добавляет Gitea-сенсоры через REST.""" +import re + +CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml" +SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml" +GT = open("/tmp/gitea-token", encoding="utf-8").read().strip() + +sec = open(SEC, encoding="utf-8").read() +if "gitea_token" not in sec: + with open(SEC, "a", encoding="utf-8") as f: + f.write(f'\ngitea_token: "token {GT}"\n') + print(" секрет Gitea добавлен") + +block = ''' - resource: http://192.168.1.140:3000/api/v1/repos/search?limit=50 + headers: + Authorization: !secret gitea_token + scan_interval: 600 + sensor: + - name: "Gitea репозиториев" + unique_id: gitea_repos_count + value_template: "{{ (value_json.data or []) | count }}" + - resource: http://192.168.1.140:3000/api/v1/user + headers: + Authorization: !secret gitea_token + scan_interval: 600 + sensor: + - name: "Gitea пользователь" + unique_id: gitea_user + value_template: "{{ value_json.login }}" +''' + +s = open(CFG, encoding="utf-8").read() +if "gitea_user" in s: + print(" сенсоры уже есть") +else: + lines = s.split("\n") + start = next((i for i, l in enumerate(lines) if re.match(r"^rest:\s*$", l)), None) + if start is None: + s = s.rstrip() + "\n\nrest:\n" + block + else: + end = len(lines) + for j in range(start + 1, len(lines)): + if lines[j] and not lines[j].startswith((" ", "\t")) and not lines[j].startswith("#"): + end = j + break + lines[end:end] = block.split("\n") + s = "\n".join(lines) + open(CFG, "w", encoding="utf-8").write(s) + print(" сенсоры добавлены") diff --git a/ops/homeassistant/add_haseerr.py b/ops/homeassistant/add_haseerr.py new file mode 100644 index 0000000..3461528 --- /dev/null +++ b/ops/homeassistant/add_haseerr.py @@ -0,0 +1,39 @@ +import json +import subprocess +import urllib.error +import 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"} + + +def sh(c): + return subprocess.run(["bash", "-lc", c], capture_output=True, text=True, timeout=30).stdout.strip() + + +def call(path, method="GET", body=None): + data = json.dumps(body).encode() if body is not None else None + r = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR) + try: + with urllib.request.urlopen(r, timeout=60) as x: + raw = x.read() + return (json.loads(raw) if raw else {}), None + except urllib.error.HTTPError as e: + return None, f"HTTP {e.code}: {e.read()[:200].decode('utf-8', 'replace')}" + except Exception as e: + return None, str(e)[:120] + + +SEERR = sh("grep -m1 '^SEERR_KEY=' /etc/hub-bots/bots.env | cut -d= -f2-") + +flow, err = call("/api/config/config_entries/flow", "POST", {"handler": "haseerr"}) +if err: + print("haseerr старт:", err) +else: + fid = flow["flow_id"] + res, err2 = call(f"/api/config/config_entries/flow/{fid}", "POST", { + "url": "http://192.168.1.121:5055", + "api_key": SEERR, + }) + print("haseerr:", err2 or (res or {}).get("type"), (res or {}).get("errors")) diff --git a/ops/homeassistant/add_paperless.py b/ops/homeassistant/add_paperless.py new file mode 100644 index 0000000..85ea2ff --- /dev/null +++ b/ops/homeassistant/add_paperless.py @@ -0,0 +1,49 @@ +"""Сенсоры Paperless в HA.""" +import re + +CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml" +SEC = "/opt/smart-lxc/homeassistant/config/secrets.yaml" +PT = open("/tmp/paperless-token", encoding="utf-8").read().strip() + +sec = open(SEC, encoding="utf-8").read() +if "paperless_token" not in sec: + with open(SEC, "a", encoding="utf-8") as f: + f.write(f'\npaperless_token: "Token {PT}"\n') + print(" секрет добавлен") + +block = ''' - resource: http://192.168.1.105:8000/api/documents/?page_size=1 + headers: + Authorization: !secret paperless_token + scan_interval: 600 + sensor: + - name: "Paperless документов" + unique_id: paperless_documents + value_template: "{{ value_json.count }}" + - resource: http://192.168.1.105:8000/api/tags/?page_size=1 + headers: + Authorization: !secret paperless_token + scan_interval: 600 + sensor: + - name: "Paperless тегов" + unique_id: paperless_tags + value_template: "{{ value_json.count }}" +''' + +s = open(CFG, encoding="utf-8").read() +if "paperless_documents" in s: + print(" сенсоры уже есть") +else: + lines = s.split("\n") + start = next((i for i, l in enumerate(lines) if re.match(r"^rest:\s*$", l)), None) + if start is None: + s = s.rstrip() + "\n\nrest:\n" + block + else: + end = len(lines) + for j in range(start + 1, len(lines)): + if lines[j] and not lines[j].startswith((" ", "\t")) and not lines[j].startswith("#"): + end = j + break + lines[end:end] = block.split("\n") + s = "\n".join(lines) + open(CFG, "w", encoding="utf-8").write(s) + print(" сенсоры добавлены") diff --git a/ops/homeassistant/add_syncthing.py b/ops/homeassistant/add_syncthing.py new file mode 100644 index 0000000..863e96a --- /dev/null +++ b/ops/homeassistant/add_syncthing.py @@ -0,0 +1,35 @@ +"""Syncthing в HA.""" +import json +import urllib.error +import urllib.request + +TOK = open("/root/.ha-token", encoding="utf-8").read().strip() +KEY = open("/tmp/syncthing-key", encoding="utf-8").read().strip() +BASE = "http://127.0.0.1:8123" +HDR = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"} + + +def call(path, method="GET", body=None): + data = json.dumps(body).encode() if body is not None else None + r = urllib.request.Request(BASE + path, data=data, method=method, headers=HDR) + try: + with urllib.request.urlopen(r, timeout=60) as x: + raw = x.read() + return (json.loads(raw) if raw else {}), None + except urllib.error.HTTPError as e: + return None, f"HTTP {e.code}: {e.read()[:200].decode('utf-8', 'replace')}" + except Exception as e: + return None, str(e)[:120] + + +flow, err = call("/api/config/config_entries/flow", "POST", {"handler": "syncthing"}) +if err: + print("старт:", err) + raise SystemExit(1) +fid = flow["flow_id"] +res, err2 = call(f"/api/config/config_entries/flow/{fid}", "POST", { + "url": "http://192.168.1.105:8384", + "token": KEY, + "verify_ssl": False, +}) +print("итог:", err2 or (res or {}).get("type"), (res or {}).get("errors"))