Frigate развёрнут без камер: контейнер, MQTT, сверка, коннектор
CT 126 (frigate-lxc): 2 ядра, 2 ГБ, 16 ГБ, /mnt/media/frigate под записи.
Образ 6.3 ГБ, версия 0.18.2, контейнер healthy, /api/stats отдаёт
cameras: {} — камер пока нет по договорённости.
Подключено: MQTT (mosquitto 192.168.1.106:1883, префикс frigate),
проверка в сверке (18 проверок, 0 проблем), коннектор событий
camera.detection для шины.
Отдельно зафиксирована проблема загрузки: ghcr.io из этой сети почти
недоступен, образ получен через зеркало ghcr.nju.edu.cn с последующим
перетегированием.
This commit is contained in:
1 parent
50cfd813ce
commit
51442a2e47
12 files changed
+1093
No files matched your search
@@ -0,0 +1,38 @@
|
||||
# Frigate: сервер наблюдения (без камер)
|
||||
|
||||
Контейнер развёрнут и работает; камеры подключаются отдельным спринтом.
|
||||
|
||||
## Что есть
|
||||
|
||||
| Параметр | Значение |
|
||||
|---|---|
|
||||
| Контейнер | CT 126 (`frigate-lxc`), 2 ядра, 2 ГБ RAM, 16 ГБ диск |
|
||||
| Образ | `ghcr.io/blakeblackshear/frigate:stable` (6.3 ГБ) |
|
||||
| WebUI / API | `http://192.168.1.126:5000` |
|
||||
| Auth UI | `http://192.168.1.126:8971` |
|
||||
| RTSP / WebRTC | 8554 / 8555 |
|
||||
| Записи | `/mnt/media/frigate` → `/media/frigate` |
|
||||
| Конфиг | `/opt/frigate/config/config.yml` |
|
||||
| MQTT | `192.168.1.106:1883` (mosquitto), префикс `frigate` |
|
||||
|
||||
Проверено: контейнер `healthy`, `/api/version` → `0.18.2-cfa08c5`,
|
||||
`/api/stats` → `cameras: {}` (камер пока нет), сверка видит службу
|
||||
(18 проверок, 0 проблем).
|
||||
|
||||
## Важная деталь: загрузка образа
|
||||
|
||||
`ghcr.io` из этой сети почти недоступен: прямые попытки уходят в
|
||||
бесконечные retry, `curl` к реестру не отвечает. Рабочий путь — зеркало:
|
||||
|
||||
```
|
||||
docker pull ghcr.nju.edu.cn/blakeblackshear/frigate:stable
|
||||
docker tag ghcr.nju.edu.cn/blakeblackshear/frigate:stable ghcr.io/blakeblackshear/frigate:stable
|
||||
```
|
||||
|
||||
## Что осталось (спринт камер)
|
||||
|
||||
1. RTSP-адреса камер от владельца.
|
||||
2. Добавить в `config.yml` блок `cameras:` с `ffmpeg.inputs`.
|
||||
3. Включить `record` и `snapshots`.
|
||||
4. Проверить, что Home Assistant видит Frigate по MQTT (обнаружение).
|
||||
5. События детекции пойдут в шину (`camera.detection`) — коннектор готов.
|
||||
@@ -0,0 +1,20 @@
|
||||
mqtt:
|
||||
enabled: true
|
||||
host: 192.168.1.106
|
||||
port: 1883
|
||||
topic_prefix: frigate
|
||||
|
||||
database:
|
||||
path: /media/frigate/frigate.db
|
||||
|
||||
record:
|
||||
enabled: false
|
||||
|
||||
snapshots:
|
||||
enabled: false
|
||||
|
||||
detect:
|
||||
enabled: false
|
||||
|
||||
cameras: {}
|
||||
version: 0.18-0
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Коннекторы: опрашиваем сервисы и превращаем изменения в события ядра.
|
||||
|
||||
Почему опрос, а не вебхуки: вебхуки надо настраивать в каждом сервисе
|
||||
отдельно и они ломаются при обновлениях. Опрос работает сразу и не
|
||||
требует правок в сервисах. Состояние храним в sync_state, поэтому каждое
|
||||
изменение превращается ровно в одно событие.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
|
||||
SONARR = os.environ.get("SONARR_URL", "http://192.168.1.117:8989")
|
||||
SONARR_KEY = os.environ.get("SONARR_KEY", "")
|
||||
RADARR = os.environ.get("RADARR_URL", "http://192.168.1.118:7878")
|
||||
RADARR_KEY = os.environ.get("RADARR_KEY", "")
|
||||
SEERR = os.environ.get("SEERR_URL", "http://192.168.1.121:5055")
|
||||
SEERR_KEY = os.environ.get("SEERR_KEY", "")
|
||||
JELLYFIN = os.environ.get("JELLYFIN_URL", "http://192.168.1.103:8096")
|
||||
JELLYFIN_KEY = os.environ.get("JELLYFIN_KEY", "")
|
||||
KUMA = os.environ.get("KUMA_URL", "http://192.168.1.107:3001")
|
||||
KUMA_KEY = os.environ.get("KUMA_KEY", "")
|
||||
ALERTMANAGER = os.environ.get("ALERTMANAGER_URL", "http://192.168.1.134:9093")
|
||||
|
||||
STATE_FILE = os.environ.get("STATE_FILE", "/var/lib/hub-core/state.json")
|
||||
|
||||
|
||||
def http(url, headers=None, timeout=20):
|
||||
req = urllib.request.Request(url, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def send_event(source, etype, kind, key, title, detail=None):
|
||||
payload = {"entity": {"kind": kind, "key": key, "title": title},
|
||||
"payload": {"detail": detail} if detail else {}}
|
||||
body = json.dumps({"source": source, "type": etype, **payload}).encode()
|
||||
req = urllib.request.Request(f"{CORE}/event", data=body, method="POST",
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status in (200, 201)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def load_state():
|
||||
try:
|
||||
return json.load(open(STATE_FILE, encoding="utf-8"))
|
||||
except OSError:
|
||||
return {}
|
||||
|
||||
|
||||
def save_state(state):
|
||||
os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
|
||||
json.dump(state, open(STATE_FILE, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
||||
|
||||
|
||||
# ─────────────────────── источники ───────────────────────
|
||||
|
||||
def arr_history(base, key, source, count=20):
|
||||
data, err = http(f"{base}/api/v3/history?page=1&pageSize={count}&sortKey=date&sortDirection=descending",
|
||||
{"X-Api-Key": key})
|
||||
if err:
|
||||
return [], err
|
||||
out = []
|
||||
for rec in (data or []).get("records", []):
|
||||
if rec.get("eventType") not in ("downloadFolderImported", "grabbed"):
|
||||
continue
|
||||
out.append({
|
||||
"id": rec.get("id"),
|
||||
"title": (rec.get("sourceTitle") or rec.get("series", {}).get("title")
|
||||
or rec.get("movie", {}).get("title") or "без названия"),
|
||||
"when": rec.get("date"),
|
||||
"type": "media.imported" if rec["eventType"] == "downloadFolderImported" else "media.grabbed",
|
||||
})
|
||||
return out, None
|
||||
|
||||
|
||||
def seerr_requests():
|
||||
data, err = http(f"{SEERR}/api/v1/request?take=20&filter=all&sort=added", {"X-Api-Key": SEERR_KEY})
|
||||
if err:
|
||||
return [], err
|
||||
out = []
|
||||
for r in (data or {}).get("results", []):
|
||||
media = r.get("media") or {}
|
||||
title = media.get("title") or media.get("name") or "заявка"
|
||||
out.append({
|
||||
"id": r.get("id"),
|
||||
"title": title,
|
||||
"status": r.get("status"),
|
||||
"when": r.get("createdAt"),
|
||||
"type": "media.requested",
|
||||
})
|
||||
return out, None
|
||||
|
||||
|
||||
def jellyfin_recent():
|
||||
data, err = http(f"{JELLYFIN}/Items?Recursive=true&IncludeItemTypes=Movie,Series&SortBy=DateCreated"
|
||||
f"&SortOrder=Descending&Limit=10&Fields=DateCreated",
|
||||
{"Authorization": f'MediaBrowser Token="{JELLYFIN_KEY}"'})
|
||||
if err:
|
||||
return [], err
|
||||
out = []
|
||||
for it in (data or {}).get("Items", []):
|
||||
out.append({
|
||||
"id": it.get("Id"),
|
||||
"title": it.get("Name"),
|
||||
"when": it.get("DateCreated"),
|
||||
"type": "media.added",
|
||||
})
|
||||
return out, None
|
||||
|
||||
|
||||
def alertmanager_alerts():
|
||||
data, err = http(f"{ALERTMANAGER}/api/v2/alerts")
|
||||
if err:
|
||||
return [], err
|
||||
out = []
|
||||
for a in data or []:
|
||||
labels = a.get("labels") or {}
|
||||
out.append({
|
||||
"id": f"{labels.get('alertname')}|{labels.get('host','')}",
|
||||
"title": labels.get("alertname", "тревога"),
|
||||
"status": (a.get("status") or {}).get("state"),
|
||||
"when": a.get("startsAt"),
|
||||
"type": "service.alert",
|
||||
})
|
||||
return out, None
|
||||
|
||||
|
||||
SOURCES = [
|
||||
("sonarr", lambda: arr_history(SONARR, SONARR_KEY, "sonarr"), "сериал"),
|
||||
("radarr", lambda: arr_history(RADARR, RADARR_KEY, "radarr"), "фильм"),
|
||||
("seerr", seerr_requests, "заявка"),
|
||||
("jellyfin", jellyfin_recent, "фильм"),
|
||||
("alertmanager", alertmanager_alerts, "тревога"),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
state = load_state()
|
||||
total = 0
|
||||
report = []
|
||||
for name, fetch, kind in SOURCES:
|
||||
try:
|
||||
items, err = fetch()
|
||||
except Exception as e:
|
||||
items, err = [], f"{type(e).__name__}: {e}"
|
||||
if err:
|
||||
report.append(f"{name}: ошибка {err}")
|
||||
continue
|
||||
seen = set(state.get(name, []))
|
||||
new = 0
|
||||
for it in items:
|
||||
key = str(it.get("id"))
|
||||
if not key or key in seen:
|
||||
continue
|
||||
etype = it.get("type") or f"{name}.event"
|
||||
detail = f"статус {it.get('status')}" if it.get("status") else None
|
||||
if send_event(name, etype, kind, f"{name}:{key}", it.get("title") or key, detail):
|
||||
seen.add(key)
|
||||
new += 1
|
||||
# храним только последние 500 ключей, чтобы файл не рос
|
||||
state[name] = list(seen)[-500:]
|
||||
total += new
|
||||
report.append(f"{name}: {new} новых")
|
||||
save_state(state)
|
||||
print(f"[{datetime.now(timezone.utc).isoformat(timespec='seconds')}] "
|
||||
f"событий: {total} | " + "; ".join(report))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,239 @@
|
||||
"""Buryan Hub Core: шина событий и граф сущностей.
|
||||
|
||||
Один процесс, три задачи:
|
||||
1) принимать события от сервисов и складывать в общую базу;
|
||||
2) хранить карточки сущностей и связи между ними;
|
||||
3) публиковать значимое в Matrix (личка владельцу).
|
||||
|
||||
Запуск: python3 core.py (HTTP на порту 9120)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
|
||||
DSN = os.environ.get("CORE_DSN", "dbname=hub_core user=hub_core password=hub_core host=127.0.0.1")
|
||||
PORT = int(os.environ.get("CORE_PORT", "9120"))
|
||||
MATRIX_HS = os.environ.get("MATRIX_HS", "https://matrix.buryans.ru")
|
||||
NOTIFY_TOKEN = os.environ.get("NOTIFY_TOKEN", "")
|
||||
NOTIFY_ROOM = os.environ.get("NOTIFY_ROOM", "")
|
||||
|
||||
# какие события стоит показывать человеку сразу
|
||||
LOUD = {
|
||||
"media.imported", "media.requested", "media.failed",
|
||||
"backup.done", "backup.failed", "service.down", "service.up",
|
||||
"photo.imported", "book.added", "document.added",
|
||||
}
|
||||
|
||||
|
||||
def db():
|
||||
con = psycopg2.connect(DSN, connect_timeout=10)
|
||||
con.autocommit = True
|
||||
return con
|
||||
|
||||
|
||||
def ensure_schema():
|
||||
sql = open(os.path.join(os.path.dirname(__file__), "schema.sql"), encoding="utf-8").read()
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
|
||||
|
||||
def publish(text):
|
||||
"""Короткое уведомление в личку владельцу."""
|
||||
if not (NOTIFY_TOKEN and NOTIFY_ROOM):
|
||||
return
|
||||
txn = int(datetime.now().timestamp() * 1000)
|
||||
import urllib.parse
|
||||
rid = urllib.parse.quote(NOTIFY_ROOM, safe="")
|
||||
body = json.dumps({"msgtype": "m.text", "body": text,
|
||||
"format": "org.matrix.custom.html",
|
||||
"formatted_body": text.replace("\n", "<br>")}).encode()
|
||||
req = urllib.request.Request(
|
||||
f"{MATRIX_HS}/_matrix/client/v3/rooms/{rid}/send/m.room.message/{txn}",
|
||||
data=body, method="PUT",
|
||||
headers={"Authorization": f"Bearer {NOTIFY_TOKEN}", "Content-Type": "application/json"})
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=10)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def human_event(ev):
|
||||
e = ev.get("entity") or {}
|
||||
title = e.get("title") or e.get("key") or "объект"
|
||||
t = ev.get("type", "")
|
||||
icons = {"media.imported": "🎬", "media.requested": "🕓", "media.failed": "⚠️",
|
||||
"backup.done": "💾", "backup.failed": "⚠️",
|
||||
"service.down": "🔴", "service.up": "✅",
|
||||
"photo.imported": "📷", "book.added": "📚", "document.added": "📄"}
|
||||
icon = icons.get(t, "•")
|
||||
src = ev.get("source", "?")
|
||||
extra = ev.get("payload") or {}
|
||||
line = f"{icon} **{title}** — {t} ({src})"
|
||||
if extra.get("detail"):
|
||||
line += f"\n{extra['detail']}"
|
||||
return line
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _json(self, code, obj):
|
||||
body = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/health"):
|
||||
try:
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute("select count(*) from events")
|
||||
n = cur.fetchone()[0]
|
||||
return self._json(200, {"ok": True, "events": n})
|
||||
except Exception as e:
|
||||
return self._json(500, {"ok": False, "error": str(e)[:200]})
|
||||
if self.path.startswith("/entities"):
|
||||
q = ""
|
||||
if "?" in self.path:
|
||||
import urllib.parse
|
||||
q = (urllib.parse.parse_qs(self.path.split("?", 1)[1]).get("q") or [""])[0]
|
||||
try:
|
||||
with db() as con, con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
|
||||
if q:
|
||||
cur.execute("""select id, kind, title, status, external_ids, updated_at
|
||||
from entities where search_text like %s
|
||||
order by updated_at desc limit 20""", (f"%{q.lower()}%",))
|
||||
else:
|
||||
cur.execute("""select id, kind, title, status, external_ids, updated_at
|
||||
from entities order by updated_at desc limit 20""")
|
||||
return self._json(200, {"items": [dict(r) for r in cur.fetchall()]})
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
if self.path.startswith("/events"):
|
||||
try:
|
||||
with db() as con, con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
|
||||
cur.execute("""select id, at, source, type, entity, payload
|
||||
from events order by id desc limit 30""")
|
||||
return self._json(200, {"items": [dict(r) for r in cur.fetchall()]})
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
return self._json(404, {"error": "нет такого пути"})
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
raw = self.rfile.read(length) if length else b"{}"
|
||||
try:
|
||||
data = json.loads(raw or b"{}")
|
||||
except json.JSONDecodeError:
|
||||
return self._json(400, {"error": "не JSON"})
|
||||
|
||||
if self.path.startswith("/event"):
|
||||
return self._event(data)
|
||||
if self.path.startswith("/entity"):
|
||||
return self._entity(data)
|
||||
if self.path.startswith("/link"):
|
||||
return self._link(data)
|
||||
return self._json(404, {"error": "нет такого пути"})
|
||||
|
||||
# ── события ──
|
||||
def _event(self, ev):
|
||||
src = (ev.get("source") or "").strip()
|
||||
typ = (ev.get("type") or "").strip()
|
||||
if not (src and typ):
|
||||
return self._json(400, {"error": "нужны source и type"})
|
||||
now = datetime.now(timezone.utc)
|
||||
ent = ev.get("entity") or {}
|
||||
payload = ev.get("payload") or {}
|
||||
try:
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute(
|
||||
"""insert into events (at, source, type, entity, payload, actor)
|
||||
values (%s, %s, %s, %s, %s, %s) returning id""",
|
||||
(now, src, typ, json.dumps(ent, ensure_ascii=False),
|
||||
json.dumps(payload, ensure_ascii=False), ev.get("actor") or "system"))
|
||||
eid = cur.fetchone()[0]
|
||||
|
||||
# событие, связанное с сущностью, обновляет её статус
|
||||
if ent.get("kind") and ent.get("key"):
|
||||
cur.execute(
|
||||
"""insert into entities (kind, key, title, status, external_ids, search_text, updated_at)
|
||||
values (%s, %s, %s, %s, %s, %s, %s)
|
||||
on conflict (kind, key) do update
|
||||
set status = excluded.status,
|
||||
title = coalesce(excluded.title, entities.title),
|
||||
updated_at = excluded.updated_at
|
||||
returning id""",
|
||||
(ent["kind"], ent["key"], ent.get("title") or ent["key"],
|
||||
typ, json.dumps({src: ent.get("key")}, ensure_ascii=False),
|
||||
f"{ent.get('title') or ''} {ent.get('key')}".lower(), now))
|
||||
ent_id = cur.fetchone()[0]
|
||||
cur.execute("update events set entity_id = %s where id = %s", (ent_id, eid))
|
||||
if typ in LOUD:
|
||||
threading.Thread(target=publish, args=(human_event(ev),), daemon=True).start()
|
||||
return self._json(201, {"ok": True, "id": eid})
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
|
||||
# ── сущности ──
|
||||
def _entity(self, data):
|
||||
kind = (data.get("kind") or "").strip()
|
||||
key = (data.get("key") or "").strip()
|
||||
if not (kind and key):
|
||||
return self._json(400, {"error": "нужны kind и key"})
|
||||
now = datetime.now(timezone.utc)
|
||||
title = data.get("title") or key
|
||||
try:
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute(
|
||||
"""insert into entities (kind, key, title, status, external_ids, search_text, updated_at)
|
||||
values (%s, %s, %s, %s, %s, %s, %s)
|
||||
on conflict (kind, key) do update
|
||||
set title = excluded.title,
|
||||
status = coalesce(excluded.status, entities.status),
|
||||
external_ids = entities.external_ids || excluded.external_ids,
|
||||
search_text = excluded.search_text,
|
||||
updated_at = excluded.updated_at
|
||||
returning id""",
|
||||
(kind, key, title, data.get("status"),
|
||||
json.dumps(data.get("external_ids") or {}, ensure_ascii=False),
|
||||
f"{title} {key}".lower(), now))
|
||||
rid = cur.fetchone()[0]
|
||||
return self._json(201, {"ok": True, "id": rid})
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
|
||||
def _link(self, data):
|
||||
a, b = data.get("from"), data.get("to")
|
||||
rel = data.get("relation") or "related"
|
||||
if not (a and b):
|
||||
return self._json(400, {"error": "нужны from и to (id)"})
|
||||
try:
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute(
|
||||
"""insert into entity_links (from_id, to_id, relation)
|
||||
values (%s, %s, %s) on conflict do nothing returning id""",
|
||||
(a, b, rel))
|
||||
row = cur.fetchone()
|
||||
return self._json(201, {"ok": True, "id": row[0] if row else None})
|
||||
except Exception as e:
|
||||
return self._json(500, {"error": str(e)[:200]})
|
||||
|
||||
|
||||
def main():
|
||||
ensure_schema()
|
||||
srv = HTTPServer(("0.0.0.0", PORT), Handler)
|
||||
print(f"hub-core слушает {PORT}", flush=True)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Дневной дайджест по событиям ядра."""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg2
|
||||
|
||||
DSN = os.environ.get("CORE_DSN",
|
||||
"dbname=hub_core user=hub_core password=hub_core host=192.168.1.151 client_encoding=utf8")
|
||||
MATRIX_HS = os.environ.get("MATRIX_HS", "https://matrix.buryans.ru")
|
||||
TOKEN = os.environ.get("NOTIFY_TOKEN", "")
|
||||
ROOM = os.environ.get("NOTIFY_ROOM", "")
|
||||
|
||||
|
||||
def send(text):
|
||||
if not (TOKEN and ROOM):
|
||||
print("нет настроек Matrix")
|
||||
return False
|
||||
txn = int(datetime.now().timestamp() * 1000)
|
||||
rid = urllib.parse.quote(ROOM, safe="")
|
||||
body = json.dumps({"msgtype": "m.text", "body": text,
|
||||
"format": "org.matrix.custom.html",
|
||||
"formatted_body": text.replace("\n", "<br>")}).encode()
|
||||
req = urllib.request.Request(
|
||||
f"{MATRIX_HS}/_matrix/client/v3/rooms/{rid}/send/m.room.message/{txn}",
|
||||
data=body, method="PUT",
|
||||
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15):
|
||||
return True
|
||||
except Exception as e:
|
||||
print("не отправилось:", str(e)[:100])
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
con = psycopg2.connect(DSN, connect_timeout=10)
|
||||
cur = con.cursor()
|
||||
|
||||
cur.execute("""select source, type, count(*) from events
|
||||
where at > now() - interval '24 hours'
|
||||
group by source, type order by 3 desc""")
|
||||
rows = cur.fetchall()
|
||||
|
||||
cur.execute("""select count(*) from entities""")
|
||||
entities = cur.fetchone()[0]
|
||||
|
||||
cur.execute("""select count(*) from problems where resolved_at is null""")
|
||||
open_problems = cur.fetchone()[0]
|
||||
|
||||
cur.execute("""select count(*) from actions where at > now() - interval '24 hours'""")
|
||||
actions = cur.fetchone()[0]
|
||||
|
||||
cur.execute("""select source, type, entity->>'title' from events
|
||||
where at > now() - interval '24 hours'
|
||||
and type in ('media.imported','media.requested','service.alert','document.added','book.added')
|
||||
order by id desc limit 8""")
|
||||
notable = cur.fetchall()
|
||||
con.close()
|
||||
|
||||
lines = [f"**Сводка · {datetime.now(timezone.utc).strftime('%d.%m')}**", ""]
|
||||
if not rows:
|
||||
lines.append("_За сутки событий не было._")
|
||||
else:
|
||||
total = sum(r[2] for r in rows)
|
||||
lines.append(f"**Событий за сутки: {total}**")
|
||||
for src, typ, n in rows[:8]:
|
||||
lines.append(f"• {src}: {typ} — {n}")
|
||||
if notable:
|
||||
lines.append("\n**Заметное**")
|
||||
for src, typ, title in notable:
|
||||
lines.append(f"• {title or '—'} ({typ}, {src})")
|
||||
lines.append("")
|
||||
lines.append(f"Карточек: {entities} · открытых проблем: {open_problems} · действий: {actions}")
|
||||
|
||||
text = "\n".join(lines)
|
||||
ok = send(text)
|
||||
print(text.replace("\n", " | ")[:500])
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Связка карточек: один объект в разных сервисах — одна связь.
|
||||
|
||||
Ищем сущности с похожими названиями в разных видах (фильм, книга, сериал,
|
||||
заявка) и связываем их. Это и есть «одна карточка на объект».
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import psycopg2
|
||||
|
||||
DSN = os.environ.get("CORE_DSN",
|
||||
"dbname=hub_core user=hub_core password=hub_core host=192.168.1.151 client_encoding=utf8")
|
||||
BASE = "/opt/hub-core"
|
||||
|
||||
|
||||
def norm(s):
|
||||
"""Нормализация названия: нижний регистр, без года, знаков и лишних слов."""
|
||||
s = (s or "").lower().replace("ё", "е")
|
||||
s = re.sub(r"\(\d{4}\)", " ", s)
|
||||
s = re.sub(r"[^a-zа-я0-9 ]+", " ", s)
|
||||
for w in ("часть", "part", "фильм", "сериал", "книга"):
|
||||
s = s.replace(f" {w} ", " ")
|
||||
return " ".join(s.split())
|
||||
|
||||
|
||||
KINDS_PAIR = ("фильм", "книга", "сериал", "заявка", "музыка", "фотоальбом")
|
||||
|
||||
|
||||
def main():
|
||||
con = psycopg2.connect(DSN, connect_timeout=10)
|
||||
con.autocommit = True
|
||||
cur = con.cursor()
|
||||
|
||||
cur.execute("select id, kind, title from entities where kind = any(%s)", (list(KINDS_PAIR),))
|
||||
rows = cur.fetchall()
|
||||
|
||||
by_title = {}
|
||||
for eid, kind, title in rows:
|
||||
key = norm(title)
|
||||
if len(key) < 3:
|
||||
continue
|
||||
by_title.setdefault(key, []).append((eid, kind, title))
|
||||
|
||||
made = 0
|
||||
for key, items in by_title.items():
|
||||
if len(items) < 2:
|
||||
continue
|
||||
kinds = {k for _, k, _ in items}
|
||||
if len(kinds) < 2:
|
||||
continue
|
||||
items.sort()
|
||||
base = items[0]
|
||||
for other in items[1:]:
|
||||
cur.execute("""insert into entity_links (from_id, to_id, relation)
|
||||
values (%s, %s, 'одно_название')
|
||||
on conflict do nothing returning id""", (base[0], other[0]))
|
||||
if cur.fetchone():
|
||||
made += 1
|
||||
print(f" связал: {base[2]} ({base[1]}) ↔ {other[2]} ({other[1]})")
|
||||
|
||||
cur.execute("select count(*) from entity_links")
|
||||
total = cur.fetchone()[0]
|
||||
con.close()
|
||||
print(f"[связка] новых связей: {made} | всего: {total}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Дополняем коннекторы источниками из баз сервисов."""
|
||||
import re
|
||||
|
||||
p = "/opt/hub-core/connectors.py"
|
||||
src = open(p, encoding="utf-8").read()
|
||||
|
||||
if "def local_sources" in src:
|
||||
print("уже дополнено")
|
||||
raise SystemExit(0)
|
||||
|
||||
new_funcs = '''
|
||||
|
||||
# ─────────────────────── источники из баз ───────────────────────
|
||||
import subprocess
|
||||
|
||||
|
||||
def pct(ct, args, timeout=40):
|
||||
cmd = ["pct", "exec", str(ct), "--"] + args
|
||||
try:
|
||||
out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
||||
if out.returncode != 0:
|
||||
return None, (out.stderr or out.stdout).strip()[:120]
|
||||
return out.stdout.strip(), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def paperless_docs():
|
||||
data, err = http(f"{PAPERLESS}/api/documents/?page_size=20&ordering=-created",
|
||||
{"Authorization": f"Token {PAPERLESS_TOKEN}"})
|
||||
if err:
|
||||
return [], err
|
||||
out = []
|
||||
for d in (data or {}).get("results", []):
|
||||
out.append({"id": d.get("id"), "title": d.get("title") or "документ",
|
||||
"when": d.get("created"), "type": "document.added"})
|
||||
return out, None
|
||||
|
||||
|
||||
def calibre_books():
|
||||
script = ("import json,sqlite3;c=sqlite3.connect('/opt/books/library/metadata.db');"
|
||||
"rows=c.execute('select id,title from books order by id desc limit 15').fetchall();"
|
||||
"print(json.dumps(rows, ensure_ascii=False))")
|
||||
out, err = pct(111, ["python3", "-c", script])
|
||||
if err:
|
||||
return [], err
|
||||
try:
|
||||
rows = json.loads(out or "[]")
|
||||
except json.JSONDecodeError:
|
||||
return [], "не разобрал ответ"
|
||||
return [{"id": r[0], "title": r[1] or "книга", "type": "book.added"} for r in rows]
|
||||
|
||||
|
||||
def navidrome_albums():
|
||||
out, err = pct(125, ["docker", "exec", "navidrome", "sqlite3", "-separator", "|",
|
||||
"/data/navidrome.db",
|
||||
"select id, name from album order by created_at desc limit 15"])
|
||||
if err:
|
||||
return [], err
|
||||
rows = []
|
||||
for line in (out or "").splitlines():
|
||||
parts = line.split("|")
|
||||
if len(parts) >= 2:
|
||||
rows.append({"id": parts[0], "title": parts[1], "type": "music.added"})
|
||||
return rows, None
|
||||
|
||||
|
||||
def immich_albums():
|
||||
sql = ('select id, "albumName" from album order by "createdAt" desc limit 15')
|
||||
out, err = pct(151, ["su", "-", "postgres", "-c",
|
||||
f"psql -d immich_db -tA -F'|' -c '{sql}'"])
|
||||
if err:
|
||||
return [], err
|
||||
rows = []
|
||||
for line in (out or "").splitlines():
|
||||
parts = line.split("|")
|
||||
if len(parts) >= 2:
|
||||
rows.append({"id": parts[0], "title": parts[1], "type": "photo.album"})
|
||||
return rows, None
|
||||
|
||||
|
||||
def kuma_monitors():
|
||||
script = ("import json,sqlite3;"
|
||||
"c=sqlite3.connect('/var/lib/docker/volumes/uptime-kuma-data/_data/kuma.db');"
|
||||
"rows=c.execute('select id,name,active from monitor where active=1 limit 60').fetchall();"
|
||||
"print(json.dumps(rows, ensure_ascii=False))")
|
||||
out, err = pct(107, ["python3", "-c", script])
|
||||
if err:
|
||||
return [], err
|
||||
try:
|
||||
rows = json.loads(out or "[]")
|
||||
except json.JSONDecodeError:
|
||||
return [], "не разобрал ответ"
|
||||
return [{"id": r[0], "title": r[1] or f"монитор {r[0]}", "type": "monitor.active"} for r in rows]
|
||||
|
||||
'''
|
||||
|
||||
src = src.replace("\nSOURCES = [", new_funcs + "\nSOURCES = [")
|
||||
|
||||
# новые переменные окружения
|
||||
src = src.replace(
|
||||
'ALERTMANAGER = os.environ.get("ALERTMANAGER_URL", "http://192.168.1.134:9093")',
|
||||
'ALERTMANAGER = os.environ.get("ALERTMANAGER_URL", "http://192.168.1.134:9093")\n'
|
||||
'PAPERLESS = os.environ.get("PAPERLESS_URL", "http://192.168.1.105:8000")\n'
|
||||
'PAPERLESS_TOKEN = os.environ.get("PAPERLESS_TOKEN", "")')
|
||||
|
||||
# расширяем список источников
|
||||
src = re.sub(
|
||||
r"SOURCES = \[.*?\]",
|
||||
'''SOURCES = [
|
||||
("sonarr", lambda: arr_history(SONARR, SONARR_KEY, "sonarr"), "сериал"),
|
||||
("radarr", lambda: arr_history(RADARR, RADARR_KEY, "radarr"), "фильм"),
|
||||
("seerr", seerr_requests, "заявка"),
|
||||
("jellyfin", jellyfin_recent, "фильм"),
|
||||
("alertmanager", alertmanager_alerts, "тревога"),
|
||||
("paperless", paperless_docs, "документ"),
|
||||
("calibre", calibre_books, "книга"),
|
||||
("navidrome", navidrome_albums, "музыка"),
|
||||
("immich", immich_albums, "фотоальбом"),
|
||||
("kuma", kuma_monitors, "монитор"),
|
||||
]''',
|
||||
src, flags=re.S)
|
||||
|
||||
open(p, "w", encoding="utf-8").write(src)
|
||||
print("коннекторы дополнены: 10 источников")
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Дополняем коннекторы Home Assistant (чтение реестра без токена)."""
|
||||
p = "/opt/hub-core/connectors.py"
|
||||
src = open(p, encoding="utf-8").read()
|
||||
|
||||
if "ha_entities" in src:
|
||||
print("HA уже подключён")
|
||||
raise SystemExit(0)
|
||||
|
||||
funcs = '''
|
||||
|
||||
def ha_entities():
|
||||
"""HA без токена: читаем реестр сущностей из хранилища."""
|
||||
script = ("import json;"
|
||||
"d=json.load(open('/config/.storage/core.entity_registry'))['data']['entities'];"
|
||||
"rows=[[e.get('entity_id'), e.get('name') or e.get('original_name') or e.get('entity_id')]"
|
||||
" for e in d if not e.get('disabled_by')][:80];"
|
||||
"print(json.dumps(rows, ensure_ascii=False))")
|
||||
out, err = pct(106, ["docker", "exec", "homeassistant", "sh", "-c", f"python3 -c \\"{script}\\""])
|
||||
if err:
|
||||
return [], err
|
||||
try:
|
||||
rows = json.loads(out or "[]")
|
||||
except json.JSONDecodeError:
|
||||
return [], "не разобрал ответ"
|
||||
return [{"id": r[0], "title": r[1], "type": "ha.entity"} for r in rows], None
|
||||
|
||||
'''
|
||||
|
||||
src = src.replace("\nSOURCES = [", funcs + "\nSOURCES = [")
|
||||
src = src.replace(' ("kuma", kuma_monitors, "монитор"),',
|
||||
' ("kuma", kuma_monitors, "монитор"),\n ("homeassistant", ha_entities, "устройство"),')
|
||||
open(p, "w", encoding="utf-8").write(src)
|
||||
print("HA подключён")
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Ночная сверка: проверяем реальность и чиним безопасное.
|
||||
|
||||
Каждое действие пишется в журнал `actions` — с типом, целью и тем,
|
||||
как откатить. Опасное (удаление, смена настроек) не делаем автоматически.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg2
|
||||
|
||||
DSN = os.environ.get("CORE_DSN",
|
||||
"dbname=hub_core user=hub_core password=hub_core host=192.168.1.151 client_encoding=utf8")
|
||||
STATE = "/var/lib/hub-core/reconcile.json"
|
||||
|
||||
# проверяемая служба → (URL, контейнер, хост CT)
|
||||
CHECKS = [
|
||||
("authentik", "http://192.168.1.114:9000/-/health/live/", None, 114),
|
||||
("jellyfin", "http://192.168.1.103:8096/health", "jellyfin", 103),
|
||||
("paperless", "http://192.168.1.105:8000/api/", "paperless", 105),
|
||||
("homeassistant", "http://192.168.1.106:8123/manifest.json", "homeassistant", 106),
|
||||
("uptime-kuma", "http://192.168.1.107:3001/", "uptime_kuma", 107),
|
||||
("n8n", "http://192.168.1.108:5678/healthz", "n8n", 108),
|
||||
("nextcloud", "http://192.168.1.109:8080/status.php", "nextcloud", 109),
|
||||
("vaultwarden", "http://192.168.1.109:8081/alive", "vaultwarden", 109),
|
||||
("sonarr", "http://192.168.1.117:8989/ping", "sonarr", 117),
|
||||
("radarr", "http://192.168.1.118:7878/ping", "radarr", 118),
|
||||
("prowlarr", "http://192.168.1.119:9696/ping", "prowlarr", 119),
|
||||
("bazarr", "http://192.168.1.120:6767/", "bazarr", 120),
|
||||
("seerr", "http://192.168.1.121:5055/api/v1/settings/public", "seerr", 121),
|
||||
("navidrome", "http://192.168.1.125:4533/ping", "navidrome", 125),
|
||||
("linkding", "http://192.168.1.127:3000/", "linkding", 127),
|
||||
("prometheus", "http://192.168.1.134:9090/-/healthy", "prometheus", 134),
|
||||
("qBittorrent", "http://192.168.1.123:8085/", "qbittorrent", 123),
|
||||
]
|
||||
|
||||
|
||||
def db():
|
||||
con = psycopg2.connect(DSN, connect_timeout=10)
|
||||
con.autocommit = True
|
||||
return con
|
||||
|
||||
|
||||
def ensure_journal():
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute("""
|
||||
create table if not exists actions (
|
||||
id bigserial primary key,
|
||||
at timestamptz not null default now(),
|
||||
kind text not null,
|
||||
target text not null,
|
||||
detail text,
|
||||
status text not null default 'done',
|
||||
rollback text
|
||||
)""")
|
||||
cur.execute("""
|
||||
create table if not exists problems (
|
||||
id bigserial primary key,
|
||||
at timestamptz not null default now(),
|
||||
check_name text not null,
|
||||
state text not null,
|
||||
detail text,
|
||||
resolved_at timestamptz
|
||||
)""")
|
||||
|
||||
|
||||
def journal(kind, target, detail, status="done", rollback=None):
|
||||
with db() as con, con.cursor() as cur:
|
||||
cur.execute("""insert into actions (kind, target, detail, status, rollback)
|
||||
values (%s,%s,%s,%s,%s) returning id""",
|
||||
(kind, target, detail, status, rollback))
|
||||
return cur.fetchone()[0]
|
||||
|
||||
|
||||
def probe(url, timeout=8):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "hub-reconcile"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return True, r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
# 401/403/404 — служба жива, просто закрыта
|
||||
return e.code < 500, e.code
|
||||
except Exception as e:
|
||||
return False, str(e)[:80]
|
||||
|
||||
|
||||
def container_state(ct, name):
|
||||
try:
|
||||
out = subprocess.run(["pct", "exec", str(ct), "--", "docker", "inspect", name,
|
||||
"--format", "{{.State.Status}}"],
|
||||
capture_output=True, text=True, timeout=25)
|
||||
return out.stdout.strip() or "нет"
|
||||
except Exception:
|
||||
return "нет"
|
||||
|
||||
|
||||
def fix(ct, name):
|
||||
"""Безопасное исправление: поднять контейнер, если он остановлен."""
|
||||
try:
|
||||
r = subprocess.run(["pct", "exec", str(ct), "--", "docker", "start", name],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
return r.returncode == 0, (r.stderr or r.stdout).strip()[:120]
|
||||
except Exception as e:
|
||||
return False, str(e)[:100]
|
||||
|
||||
|
||||
def main():
|
||||
ensure_journal()
|
||||
problems, fixed, checked = [], 0, 0
|
||||
report = []
|
||||
|
||||
for name, url, container, ct in CHECKS:
|
||||
alive, code = probe(url)
|
||||
checked += 1
|
||||
if alive:
|
||||
continue
|
||||
|
||||
state = container_state(ct, container) if container else "?"
|
||||
detail = f"не отвечает ({code}); контейнер: {state}"
|
||||
problems.append((name, detail))
|
||||
|
||||
# чиним только если контейнер реально не работает
|
||||
if container and state in ("exited", "created", "dead", "нет"):
|
||||
ok, out = fix(ct, container)
|
||||
if ok:
|
||||
alive2, code2 = probe(url, timeout=15)
|
||||
journal("restart", f"{ct}:{container}",
|
||||
f"был {state}, теперь {'отвечает' if alive2 else 'всё ещё молчит'} ({code2})",
|
||||
status="done" if alive2 else "failed",
|
||||
rollback=f"pct exec {ct} -- docker stop {container}")
|
||||
fixed += 1 if alive2 else 0
|
||||
report.append(f"{name}: поднят контейнер → {'ок' if alive2 else 'не помогло'}")
|
||||
else:
|
||||
journal("restart", f"{ct}:{container}", f"ошибка запуска: {out}", status="failed")
|
||||
report.append(f"{name}: не смог поднять ({out})")
|
||||
else:
|
||||
report.append(f"{name}: {detail}")
|
||||
|
||||
# фиксируем проблемы в базе
|
||||
with db() as con, con.cursor() as cur:
|
||||
for name, detail in problems:
|
||||
cur.execute("""select id from problems where check_name=%s and resolved_at is null""", (name,))
|
||||
if cur.fetchone():
|
||||
continue
|
||||
cur.execute("""insert into problems (check_name, state, detail) values (%s,%s,%s)""",
|
||||
(name, "down", detail))
|
||||
# закрываем те, что уже не проблема
|
||||
names_down = [p[0] for p in problems]
|
||||
if names_down:
|
||||
cur.execute("""update problems set resolved_at = now()
|
||||
where resolved_at is null and check_name <> all(%s)""", (names_down,))
|
||||
else:
|
||||
cur.execute("update problems set resolved_at = now() where resolved_at is null")
|
||||
cur.execute("select count(*) from problems where resolved_at is null")
|
||||
open_now = cur.fetchone()[0]
|
||||
|
||||
print(f"[{datetime.now(timezone.utc).isoformat(timespec='seconds')}] "
|
||||
f"проверено {checked}, проблем {len(problems)}, исправлено {fixed}, открытых {open_now}")
|
||||
for line in report:
|
||||
print(" -", line)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Продолжить просмотр: что не досмотрено — по всем пользователям Jellyfin.
|
||||
|
||||
Отдаём в Matrix (личка), потому что на Android это и есть уведомления:
|
||||
Element/FluffyChat показывают push. На Google TV работает родное приложение
|
||||
Jellyfin по той же ссылке.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
JF = os.environ.get("JELLYFIN_URL", "http://192.168.1.103:8096")
|
||||
JF_KEY = os.environ.get("JELLYFIN_KEY", "")
|
||||
PUBLIC = os.environ.get("JELLYFIN_PUBLIC", "https://media.buryans.ru")
|
||||
MATRIX_HS = os.environ.get("MATRIX_HS", "https://matrix.buryans.ru")
|
||||
TOKEN = os.environ.get("NOTIFY_TOKEN", "")
|
||||
ROOM = os.environ.get("NOTIFY_ROOM", "")
|
||||
|
||||
|
||||
def jf(path):
|
||||
req = urllib.request.Request(f"{JF}{path}",
|
||||
headers={"Authorization": f'MediaBrowser Token="{JF_KEY}"'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return json.loads(r.read() or b"{}"), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def send(text):
|
||||
if not (TOKEN and ROOM):
|
||||
print("нет настроек Matrix")
|
||||
return False
|
||||
txn = int(datetime.now().timestamp() * 1000)
|
||||
rid = urllib.parse.quote(ROOM, safe="")
|
||||
body = json.dumps({"msgtype": "m.text", "body": text,
|
||||
"format": "org.matrix.custom.html",
|
||||
"formatted_body": text.replace("\n", "<br>")}).encode()
|
||||
req = urllib.request.Request(
|
||||
f"{MATRIX_HS}/_matrix/client/v3/rooms/{rid}/send/m.room.message/{txn}",
|
||||
data=body, method="PUT",
|
||||
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15):
|
||||
return True
|
||||
except Exception as e:
|
||||
print("не отправилось:", str(e)[:100])
|
||||
return False
|
||||
|
||||
|
||||
def human_ticks(ticks):
|
||||
if not ticks:
|
||||
return "0 мин"
|
||||
minutes = int(ticks / 10_000_000 / 60)
|
||||
if minutes < 60:
|
||||
return f"{minutes} мин"
|
||||
return f"{minutes // 60} ч {minutes % 60} мин"
|
||||
|
||||
|
||||
def collect():
|
||||
users, err = jf("/Users")
|
||||
if err:
|
||||
return None, f"Jellyfin не ответил: {err}"
|
||||
rows = []
|
||||
for u in users or []:
|
||||
uid = u.get("Id")
|
||||
name = u.get("Name")
|
||||
resume, err = jf(f"/Users/{uid}/Items/Resume?Limit=10&MediaTypes=Video")
|
||||
if err:
|
||||
continue
|
||||
for it in (resume or {}).get("Items", []):
|
||||
pos = it.get("UserData", {}).get("PlaybackPositionTicks", 0)
|
||||
total = it.get("RunTimeTicks") or 0
|
||||
pct = int(100 * pos / total) if total else 0
|
||||
rows.append({
|
||||
"user": name,
|
||||
"title": it.get("Name"),
|
||||
"type": it.get("Type"),
|
||||
"pct": pct,
|
||||
"left": human_ticks(max(total - pos, 0)),
|
||||
"url": f"{PUBLIC}/web/index.html#!/details?id={it.get('Id')}",
|
||||
})
|
||||
return rows, None
|
||||
|
||||
|
||||
def main():
|
||||
rows, err = collect()
|
||||
if err:
|
||||
print(err)
|
||||
return 1
|
||||
if not rows:
|
||||
text = ("**Продолжить просмотр**\n\n"
|
||||
"_Сейчас ничего не досмотрено._ Когда начнёте смотреть — "
|
||||
"здесь появится список с прогрессом и ссылкой.")
|
||||
else:
|
||||
lines = ["**Продолжить просмотр**", ""]
|
||||
for r in rows[:10]:
|
||||
lines.append(f"• {r['title']} — {r['pct']}%, осталось {r['left']} ({r['user']})\n {r['url']}")
|
||||
text = "\n".join(lines)
|
||||
ok = send(text)
|
||||
print(text.replace("\n", " | ")[:400])
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -25,6 +25,7 @@ JELLYFIN_KEY = os.environ.get("JELLYFIN_KEY", "")
|
||||
KUMA = os.environ.get("KUMA_URL", "http://192.168.1.107:3001")
|
||||
KUMA_KEY = os.environ.get("KUMA_KEY", "")
|
||||
ALERTMANAGER = os.environ.get("ALERTMANAGER_URL", "http://192.168.1.134:9093")
|
||||
FRIGATE = os.environ.get("FRIGATE_URL", "http://192.168.1.126:5000")
|
||||
PAPERLESS = os.environ.get("PAPERLESS_URL", "http://192.168.1.105:8000")
|
||||
PAPERLESS_TOKEN = os.environ.get("PAPERLESS_TOKEN", "")
|
||||
|
||||
@@ -243,6 +244,21 @@ def ha_entities():
|
||||
return [{"id": r[0], "title": r[1], "type": "ha.entity"} for r in rows], None
|
||||
|
||||
|
||||
|
||||
def frigate_events():
|
||||
"""Frigate: события детекции (когда появятся камеры)."""
|
||||
data, err = http(f"{FRIGATE}/api/events?limit=20")
|
||||
if err:
|
||||
return [], err
|
||||
out = []
|
||||
for e in data or []:
|
||||
label = e.get("label") or e.get("sub_label") or "объект"
|
||||
cam = e.get("camera") or "камера"
|
||||
out.append({"id": e.get("id"), "title": f"{label} — {cam}",
|
||||
"when": e.get("start_time"), "type": "camera.detection"})
|
||||
return out, None
|
||||
|
||||
|
||||
SOURCES = [
|
||||
("sonarr", lambda: arr_history(SONARR, SONARR_KEY, "sonarr"), "сериал"),
|
||||
("radarr", lambda: arr_history(RADARR, RADARR_KEY, "radarr"), "фильм"),
|
||||
@@ -254,6 +270,7 @@ SOURCES = [
|
||||
("navidrome", navidrome_albums, "музыка"),
|
||||
("immich", immich_albums, "фотоальбом"),
|
||||
("kuma", kuma_monitors, "монитор"),
|
||||
("frigate", frigate_events, "камера"),
|
||||
("homeassistant", ha_entities, "устройство"),
|
||||
]
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ CHECKS = [
|
||||
("linkding", "http://192.168.1.127:3000/", "linkding", 127),
|
||||
("prometheus", "http://192.168.1.134:9090/-/healthy", "prometheus", 134),
|
||||
("qBittorrent", "http://192.168.1.123:8085/", "qbittorrent", 123),
|
||||
("frigate", "http://192.168.1.126:5000/api/version", "frigate", 126),
|
||||
]
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user