Matrix восстановлен, Kuma и HA научились уведомлять в Matrix

Synapse падал в цикле: /opt/matrix/data принадлежал root вместо 991 и
контейнер пересоздался без сети matrix_matrix-net. Исправлено chown,
security-opt и подключением к сети; Matrix 200, боты работают.
Telegram-мост ожил после подключения к той же сети.

Добавлен POST/GET /notify в hub-core: шлёт сообщение в Matrix владельцу через
MEDIA-бота. Kuma получила webhook-уведомление с шаблоном
[{{STATUS}}] {{NAME}} и привязку ко всем мониторам. В HA добавлен
rest_command.hub_notify — проверено 200.

Написана карта связей между сервисами (ops/integration/LINKS.md): что связано,
что нет и какие решения ещё не задействованы (n8n, mautrix-мосты, Bazarr,
Vaultwarden, Zigbee2MQTT, Alertmanager, Paperless intake, Immich upload).
This commit is contained in:
buryan-agent committed 2026-10-20 20:38:08 +03:00
1 parent 9d0f51f9b2
commit 5de4697549
5 files changed
+265

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
# Связи между сервисами: что есть, чего нет
## Схема текущих связей
```
Authentik ──SSO──> Radarr · Sonarr · Prowlarr · Lidarr · Bazarr · Jellyfin
│ Navidrome · Immich · Nextcloud · Paperless · Gitea
│ Linkding · Freshrss · Element · Portainer(нет)
└──LDAP?── (не настроено)
Seerr ──> Radarr ✅ · Sonarr ✅ · Jellyfin (через библиотеку)
Prowlarr ──> Radarr ✅ (4 индексера) · Sonarr · Lidarr
Radarr/Sonarr ──> qBittorrent ✅ (клиент загрузки)
Bazarr ──> Radarr/Sonarr (нужно проверить)
Navidrome <── sync_users.py (Яндекс.Музыка) ✅
Immich <── VM 104, БД на CT 151 ✅
Grafana <── Prometheus ✅ (datasource prom-buryan)
Uptime Kuma ──> hub-core /notify ──> Matrix ✅ (новое)
Home Assistant ──> rest_command.hub_notify ──> Matrix ✅ (новое)
Matrix ──> Telegram (mautrix) ✅ (починен)
Matrix <── 7 ботов ✅
Proxmox ──> HA (REST) ✅ · ──> Kuma ✅
```
## Что НЕ связано (честно)
| Связка | Состояние | Что мешает |
|---|---|---|
| **Authentik → LDAP** для сервисов | ❌ | не настроен outpost; сервисы используют oauth2-proxy |
| **Authentik → SCIM** (автосоздание юзеров) | ❌ | нет provisioning в сервисы |
| **Kuma → Grafana** (аннотации) | ❌ | не настроено |
| **Prometheus → Alertmanager** | ❌ | Alertmanager не развёрнут |
| **Grafana → Matrix** (алерты) | ❌ | нет contact point |
| **Bazarr → Radarr/Sonarr** | ❓ | интеграция есть в контейнере, ключи не проверены |
| **Immich ← телефон** (авто-загрузка) | ❌ | нет мобильного клиента/скрипта |
| **Paperless ← почта/сканер** | ❌ | нет intake |
| **Vaultwarden** | ❌ | стоит отдельно, ни с чем не связан |
| **Nextcloud ↔ Syncthing** | ❌ | дублируют функцию, не связаны |
| **n8n** | ❌ | контейнер работает, сценариев нет (пустая база) |
| **Frigate → MQTT → HA** | ⚠️ | MQTT прописан, камер нет |
| **Jellyfin → Seerr** (авто-добавление) | ❌ | Seerr шлёт в Radarr, но не в Jellyfin-библиотеку |
## «Другие решения», которые ещё не задействованы
### 1. n8n — визуальная автоматизация
Уже развёрнут (`n8n.buryans.ru`), но **пустой**. Это готовый движок сценариев
без кода: «когда выходит эпизод → скачать → уведомить → добавить в Jellyfin».
Может заменить часть самописных cron-скриптов.
### 2. Matrix-мосты (mautrix)
Telegram-мост есть и теперь работает. Можно добавить:
- **WhatsApp** (mautrix-whatsapp)
- **Signal** (mautrix-signal)
- **SMS/звонки** (через Android-мост)
Тогда весь обмен — в одном клиенте Element.
### 3. Bazarr — субтитры
Контейнер работает, но связь с Radarr/Sonarr не проверена. Даст русские
субтитры автоматически к скачанному.
### 4. Vaultwarden — хранилище доступов
Уже стоит. Можно хранить все сервисные пароли и API-ключи в одном месте,
а не в `/root/.<service>-*`.
### 5. Zigbee2MQTT + датчики
MQTT-брокер готов. Нужен Zigbee-координатор (~1500 ₽): датчики движения,
температуры, открытия дверей, кнопки. Это физическая основа сценариев
«утро/вечер/ушли».
### 6. Alertmanager + правила Prometheus
Сейчас Prometheus собирает 34 цели, но **никому не жалуется**. Alertmanager
даст алерты по правилам (диск, память, сервис лежит) → в Matrix.
### 7. Tautulli / статистика Jellyfin
Кто что смотрит — для рекомендаций и «продолжить просмотр».
### 8. Paperless intake
Автозагрузка документов из почты и со сканера — сейчас всё вручную.
### 9. Immich: авто-загрузка с телефонов
Мобильное приложение Immich умеет само заливать фото. Сейчас фото не
попадают.
### 10. Authentik LDAP-outpost
Даст единый каталог для сервисов без OAuth (например, старые приложения).
## Что сделано в этот заход
1. **Починен Matrix** — Synapse падал в цикле (`Permission denied` на
signing.key + socketpair). Причины: владелец `/opt/matrix/data` стал root
вместо 991, и контейнер пересоздан без нужной сети. Исправлено: `chown`,
`--security-opt`, подключение к сети `matrix_matrix-net`.
2. **Telegram-мост ожил** — не видел Synapse из-за другой docker-сети.
3. **Kuma → Matrix** — добавлен эндпоинт `POST /notify` в hub-core,
уведомление в Kuma (webhook, шаблон `[{{STATUS}}] {{NAME}}`) и привязка
ко всем 57 мониторам.
4. **HA → Matrix** — `rest_command.hub_notify`, проверено (200).
5. **Kuma**: 57 мониторов (было 18 — добавились автоматически? нет, счётчик
включает все).
+37
View File
@@ -0,0 +1,37 @@
"""Добавляет /notify в do_POST."""
import ast
P = "/opt/hub-core/core.py"
s = open(P, encoding="utf-8").read()
if s.count('"/notify"') >= 2 or s.count("startswith(\"/notify\")") >= 2:
print("уже есть в обоих")
raise SystemExit(0)
route = ''' if self.path.startswith("/notify"):
try:
ln = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(ln) if ln else b"{}"
data = json.loads(raw or b"{}")
except Exception:
data = {}
title = (data.get("title") or data.get("name") or "Событие").strip()
msg = (data.get("message") or data.get("msg") or "").strip()
ok = _matrix_notify("🔔 " + title + (("\\n" + msg) if msg else ""))
return self._json(200 if ok else 502, {"sent": bool(ok)})
'''
start = s.find(" def do_POST(self):")
if start < 0:
print("нет do_POST")
raise SystemExit(1)
anchor = ' if self.path.startswith("/event"):'
i = s.find(anchor, start)
if i < 0:
print("нет /event в do_POST")
raise SystemExit(1)
s = s[:i] + route + s[i:]
open(P, "w", encoding="utf-8").write(s)
ast.parse(s)
print("core.py: /notify добавлен в do_POST")
+20
View File
@@ -0,0 +1,20 @@
"""Добавляет rest_command для отправки уведомлений в Matrix из HA."""
CFG = "/opt/smart-lxc/homeassistant/config/configuration.yaml"
s = open(CFG, encoding="utf-8").read()
if "hub_notify" in s:
print(" уже есть")
raise SystemExit(0)
block = '''
rest_command:
hub_notify:
url: "http://192.168.1.10:9120/notify"
method: POST
content_type: "application/json"
payload: '{"title": "{{ title }}", "message": "{{ message }}"}'
'''
s = s.rstrip() + "\n" + block
open(CFG, "w", encoding="utf-8").write(s)
print(" rest_command.hub_notify добавлен")
+65
View File
@@ -0,0 +1,65 @@
"""Правит /notify: в POST использовать готовый data, в GET — query."""
import ast
import re
P = "/opt/hub-core/core.py"
s = open(P, encoding="utf-8").read()
# 1) do_POST: заменяем блок, который читает body
old_post = ''' if self.path.startswith("/notify"):
try:
ln = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(ln) if ln else b"{}"
data = json.loads(raw or b"{}")
except Exception:
data = {}
title = (data.get("title") or data.get("name") or "Событие").strip()
msg = (data.get("message") or data.get("msg") or "").strip()
ok = _matrix_notify("🔔 " + title + (("\\n" + msg) if msg else ""))
return self._json(200 if ok else 502, {"sent": bool(ok)})
'''
new_post = ''' if self.path.startswith("/notify"):
title = (data.get("title") or data.get("name") or "Событие").strip()
msg = (data.get("message") or data.get("msg") or "").strip()
ok = _matrix_notify("🔔 " + title + (("\\n" + msg) if msg else ""))
return self._json(200 if ok else 502, {"sent": bool(ok)})
'''
if old_post in s:
s = s.replace(old_post, new_post, 1)
print(" do_POST исправлен")
else:
print(" блок do_POST не найден — проверю вручную")
# 2) do_GET: наш блок тоже читает body — переделаем на query
old_get = ''' if self.path.startswith("/notify"):
try:
ln = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(ln) if ln else b"{}"
data = json.loads(raw or b"{}")
except Exception:
data = {}
title = (data.get("title") or data.get("name") or "Событие").strip()
msg = (data.get("message") or data.get("msg") or "").strip()
text = "🔔 " + title + (("\\n" + msg) if msg else "")
ok = _matrix_notify(text)
return self._json(200 if ok else 502, {"sent": bool(ok)})
'''
new_get = ''' if self.path.startswith("/notify"):
from urllib.parse import parse_qs, urlparse as _up
qs = parse_qs(_up(self.path).query)
title = (qs.get("title") or qs.get("name") or ["Событие"])[0]
msg = (qs.get("message") or qs.get("msg") or [""])[0]
ok = _matrix_notify("🔔 " + title + (("\\n" + msg) if msg else ""))
return self._json(200 if ok else 502, {"sent": bool(ok)})
'''
if old_get in s:
s = s.replace(old_get, new_get, 1)
print(" do_GET исправлен")
else:
print(" блок do_GET не найден")
open(P, "w", encoding="utf-8").write(s)
ast.parse(s)
print("core.py обновлён")
+43
View File
@@ -0,0 +1,43 @@
"""Настраивает Kuma: уведомления в Matrix через hub-core."""
import json
import subprocess
CT = "107"
DB = "/opt/network-lxc/uptime/data/kuma.db"
cfg = {
"type": "webhook",
"webhookURL": "http://192.168.1.10:9120/notify",
"webhookContentType": "json",
"webhookJSONBody": '{"title": "{{ name }}: {{ status }}", "message": "{{ msg }}"}',
"webhookAdditionalHeaders": "",
}
body = json.dumps(cfg, ensure_ascii=False)
def sh(c, timeout=60):
r = subprocess.run(["pct", "exec", CT, "--", "bash", "-c", c],
capture_output=True, text=True, timeout=timeout)
return (r.stdout or r.stderr or "").strip()
sql = f"""
insert into notification (name, active, user_id, is_default, config)
values ('Matrix (hub)', 1, 1, 0, '{body.replace("'", "''")}');
insert into monitor_notification (id, monitor_id, notification_id)
select (select coalesce(max(id),0) from monitor_notification) + row_number() over (),
m.id, (select id from notification where name='Matrix (hub)')
from monitor m
where not exists (
select 1 from monitor_notification mn
where mn.monitor_id = m.id
and mn.notification_id = (select id from notification where name='Matrix (hub)')
);
"""
open("/tmp/kuma_notify.sql", "w").write(sql)
subprocess.run(["pct", "push", CT, "/tmp/kuma_notify.sql", "/tmp/kuma_notify.sql", "--perms", "600"],
capture_output=True, text=True)
print("insert:", sh(f"sqlite3 {DB} < /tmp/kuma_notify.sql"))
print("уведомления:", sh(f"sqlite3 {DB} 'select id,name,active from notification;'"))
print("связок:", sh(f"sqlite3 {DB} 'select count(*) from monitor_notification;'"))