"""Buryan Hub Core: шина событий и граф сущностей. Один процесс, три задачи: 1) принимать события от сервисов и складывать в общую базу; 2) хранить карточки сущностей и связи между ними; 3) публиковать значимое в Matrix (личка владельцу). Запуск: python3 core.py (HTTP на порту 9120) """ import json import json as _json import os import threading import time import urllib.request from datetime import datetime, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer 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", "monitor.down", "monitor.up", "camera.detection", "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) ROUTES_FILE = "/etc/hub-core/routes.json" _ROUTES = None def load_routes(): """Куда какое событие отправлять: тип → бот.""" global _ROUTES if _ROUTES is not None: return _ROUTES try: _ROUTES = json.load(open(ROUTES_FILE, encoding="utf-8")) except Exception: _ROUTES = {} return _ROUTES def route_for(etype): """Выбрать получателя по типу события.""" routes = load_routes() for prefix in sorted(routes, key=len, reverse=True): if etype.startswith(prefix): return routes[prefix] return {"token": NOTIFY_TOKEN, "room": NOTIFY_ROOM} def publish(text, etype=""): """Короткое уведомление в личку владельцу.""" target = route_for(etype) if etype else {"token": NOTIFY_TOKEN, "room": NOTIFY_ROOM} token, room = target.get("token") or NOTIFY_TOKEN, target.get("room") or NOTIFY_ROOM if not (token and room): return txn = int(datetime.now().timestamp() * 1000) import urllib.parse rid = urllib.parse.quote(room, safe="") body = json.dumps({"msgtype": "m.text", "body": text, "format": "org.matrix.custom.html", "formatted_body": text.replace("\n", "
")}).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: 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 def stem_ru(text): """Грубая основа русского слова: «Дюну» → «дюн».""" t = (text or "").lower().strip() for suf in ("ами", "ями", "ого", "его", "ому", "ему", "ыми", "ими", "ая", "яя", "ое", "ее", "ые", "ие", "ой", "ый", "ий", "ах", "ях", "ам", "ям", "ом", "ем", "ов", "ев", "ии", "у", "ю", "а", "я", "ы", "и", "е", "о", "ь"): if len(t) >= len(suf) + 3 and t.endswith(suf): return t[:-len(suf)] return t def do_search(q, limit=20): """Поиск по карточкам: название и внешние ключи.""" like = f"%{q.strip().lower()}%" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select id, kind, title, status, external_ids, updated_at from entities where search_text like %s order by updated_at desc limit %s""", (like, limit)) items = [dict(r) for r in cur.fetchall()] if not items: stem = stem_ru(q) if stem and len(stem) >= 3: cur.execute("""select id, kind, title, status from entities where search_text like %s order by length(title) limit %s""", (f"%{stem}%", limit)) items = [dict(r) for r in cur.fetchall()] con.close() return {"query": q, "count": len(items), "items": items} def do_entity(eid): """Карточка: сама сущность, её связи и история событий.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("select * from entities where id = %s", (eid,)) row = cur.fetchone() if not row: con.close() return None card = dict(row) cur.execute("""select e.id, e.kind, e.title, l.relation from entity_links l join entities e on e.id = case when l.from_id = %s then l.to_id else l.from_id end where l.from_id = %s or l.to_id = %s""", (eid, eid, eid)) links = [dict(r) for r in cur.fetchall()] cur.execute("""select at, source, type, payload from events where entity_id = %s order by id desc limit 50""", (eid,)) history = [dict(r) for r in cur.fetchall()] con.close() return {"card": card, "links": links, "history": history} DATA_DIR = os.environ.get("PROJECT_DATA", "/root/buryan-infra/data") def _ensure_doc_table(): con = db() with con.cursor() as cur: cur.execute(""" create table if not exists data_docs ( id bigserial primary key, collection text not null, key text not null, payload jsonb not null, tags text[] not null default '{}', created_at timestamptz not null default now(), updated_at timestamptz not null default now(), unique (collection, key) )""") cur.execute("create index if not exists idx_docs_collection on data_docs (collection)") con.close() def do_data_put(collection, data): """Сохранить документ: {key, payload, tags}.""" _ensure_doc_table() key = str(data.get("key") or "").strip() if not key: return None, "нужен key" payload = data.get("payload") or {} tags = data.get("tags") or [] con = db() cur = con.cursor() cur.execute("""insert into data_docs (collection, key, payload, tags) values (%s, %s, %s, %s) on conflict (collection, key) do update set payload = excluded.payload, tags = excluded.tags, updated_at = now() returning id, updated_at""", (collection, key, json.dumps(payload, ensure_ascii=False), tags)) row = cur.fetchone() con.close() return {"id": row[0], "updated_at": str(row[1])}, None def do_data_list(collection, limit=100, tag=None): _ensure_doc_table() con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) if tag: cur.execute("""select id, key, payload, tags, updated_at from data_docs where collection=%s and %s = any(tags) order by updated_at desc limit %s""", (collection, tag, limit)) else: cur.execute("""select id, key, payload, tags, updated_at from data_docs where collection=%s order by updated_at desc limit %s""", (collection, limit)) items = [dict(r) for r in cur.fetchall()] con.close() return {"collection": collection, "count": len(items), "items": items}, None def _jsonable(obj): if isinstance(obj, dict): return {k: _jsonable(v) for k, v in obj.items()} if isinstance(obj, list): return [_jsonable(v) for v in obj] return str(obj) if hasattr(obj, "isoformat") else obj def do_export(collection, fmt="json", filename=None, limit=500): """Выгрузить коллекцию в папку проекта.""" data, err = do_data_list(collection, limit=limit) if err: return None, err items = _jsonable(data["items"]) folder = os.path.join(DATA_DIR, collection) os.makedirs(folder, exist_ok=True) stamp = datetime.now().strftime("%Y-%m-%d") if fmt == "md": name = filename or f"{collection}-{stamp}.md" lines = [f"# {collection}", "", f"записей: {len(items)}", ""] for it in items: lines.append(f"## {it.get('key')}") lines.append(f"обновлено: {it.get('updated_at')}") payload = it.get("payload") or {} for k, v in payload.items(): lines.append(f"* **{k}**: {v}") lines.append("") open(os.path.join(folder, name), "w", encoding="utf-8").write("\n".join(lines)) else: name = filename or f"{collection}-{stamp}.json" with open(os.path.join(folder, name), "w", encoding="utf-8") as f: json.dump({"collection": collection, "exported_at": str(datetime.now()), "count": len(items), "items": items}, f, ensure_ascii=False, indent=1, default=str) path = os.path.join(folder, name) return {"path": path, "count": len(items), "format": fmt}, None def do_services(): """Источники событий: сколько, когда последнее.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select source, count(*) as total, max(at) as last_at, count(*) filter (where at > now() - interval '24 hours') as last24 from events group by source order by total desc""") rows = [dict(r) for r in cur.fetchall()] con.close() return {"count": len(rows), "items": rows} def do_service_history(source, limit=50): """История по одному сервису.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select e.id, e.at, e.type, e.entity->>'title' as title, e.payload from events e where e.source = %s order by e.id desc limit %s""", (source, limit)) rows = [dict(r) for r in cur.fetchall()] con.close() return {"source": source, "count": len(rows), "items": rows} def do_metrics(): """Метрики в формате Prometheus.""" lines = [] con = db() cur = con.cursor() cur.execute("select source, count(*) from events group by source") lines.append("# HELP hub_events_total События по источникам") lines.append("# TYPE hub_events_total counter") for src, n in cur.fetchall(): lines.append(f'hub_events_total{{source="{src}"}} {n}') cur.execute("select count(*) from events where at > now() - interval '24 hours'") lines.append("# HELP hub_events_24h События за сутки") lines.append("# TYPE hub_events_24h gauge") lines.append(f"hub_events_24h {cur.fetchone()[0]}") cur.execute("select kind, count(*) from entities group by kind") lines.append("# HELP hub_entities Карточки по видам") lines.append("# TYPE hub_entities gauge") for kind, n in cur.fetchall(): safe = (kind or "unknown").replace('"', "") lines.append(f'hub_entities{{kind="{safe}"}} {n}') cur.execute("select count(*) from problems where resolved_at is null") lines.append("# HELP hub_problems_open Открытые проблемы") lines.append("# TYPE hub_problems_open gauge") lines.append(f"hub_problems_open {cur.fetchone()[0]}") cur.execute("select kind, status, count(*) from actions group by kind, status") lines.append("# HELP hub_actions Действия автоматики") lines.append("# TYPE hub_actions counter") for kind, status, n in cur.fetchall(): lines.append(f'hub_actions{{kind="{kind}",status="{status}"}} {n}') cur.execute("select count(*) from entity_links") lines.append("# HELP hub_links Связи между карточками") lines.append("# TYPE hub_links gauge") lines.append(f"hub_links {cur.fetchone()[0]}") con.close() # хранилища try: import subprocess out = subprocess.run(["pvesm", "status"], capture_output=True, text=True, timeout=15) lines.append("# HELP hub_storage_percent Заполненность хранилищ") lines.append("# TYPE hub_storage_percent gauge") for line in out.stdout.splitlines()[1:]: parts = line.split() if len(parts) >= 7 and parts[6].endswith("%"): try: lines.append(f'hub_storage_percent{{name="{parts[0]}",type="{parts[1]}"}} ' f'{float(parts[6].rstrip("%"))}') except ValueError: pass except Exception: pass # возраст бэкапов try: import time lines.append("# HELP hub_backup_age_hours Возраст последнего бэкапа") lines.append("# TYPE hub_backup_age_hours gauge") checks = { "postgresql": "/var/log/hub-pg-verify.log", "matrix": "/var/log/hub-matrix-backup.log", "bots": "/var/log/hub-bots-verify.log", "offsite": "/var/log/hub-offsite-verify.log", "core": "/mnt/backups/hub-core", } for name, path in checks.items(): try: if os.path.isdir(path): files = [os.path.join(path, f) for f in os.listdir(path)] mtime = max(os.path.getmtime(f) for f in files) if files else 0 else: mtime = os.path.getmtime(path) lines.append(f'hub_backup_age_hours{{name="{name}"}} ' f'{round((time.time() - mtime) / 3600, 1)}') except OSError: pass except Exception: pass return "\n".join(lines) + "\n" JOBS = { "коннекторы": ("/var/log/hub-connectors.log", 1), "сверка": ("/var/log/hub-reconcile.log", 30), "связка карточек": ("/var/log/hub-linker.log", 30), "дайджест": ("/var/log/hub-digest.log", 30), "инвентаризация": ("/var/log/hub-inventory.log", 30), "каталог": ("/var/log/hub-catalog.log", 30), "экспорт": ("/var/log/hub-export.log", 30), "бэкап базы": ("/var/log/hub-backup.log", 30), "проверка бэкапа PG": ("/var/log/hub-pg-verify.log", 30), "проверка бэкапа ботов": ("/var/log/hub-bots-verify.log", 30), "бэкап Matrix": ("/var/log/hub-matrix-backup.log", 30), "офсайт": ("/var/log/hub-offsite-verify.log", 24 * 8), "просмотр": ("/var/log/hub-resume.log", 30), "недельный отчёт": ("/var/log/hub-weekly-core.log", 24 * 8), "аудит доступов": ("/var/log/hub-identity.log", 24 * 8), "восстановление CT": ("/var/log/hub-lxc-verify.log", 24 * 8), } def jobs_status(): """Состояние задач: когда последний раз отработали.""" now = time.time() rows = [] for name, (path, limit_h) in JOBS.items(): try: age_h = (now - os.path.getmtime(path)) / 3600 state = "ок" if age_h <= limit_h else "просрочено" except OSError: age_h, state = None, "не запускалась" rows.append((name, age_h, limit_h, state)) return rows def do_links(limit=200): """Связи контента: список и сводка по типам.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("select relation, count(*) as n from entity_links group by relation order by n desc") summary = {r["relation"]: r["n"] for r in cur.fetchall()} cur.execute("""select a.title as from_title, a.kind as from_kind, b.title as to_title, b.kind as to_kind, l.relation from entity_links l join entities a on a.id = l.from_id join entities b on b.id = l.to_id order by l.relation, a.title limit %s""", (limit,)) items = [dict(r) for r in cur.fetchall()] con.close() return {"total": sum(summary.values()), "by_relation": summary, "items": items} def do_entities(kind=None, limit=200, q=None): con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) sql = "select id, kind, title, status, updated_at from entities where 1=1" args = [] if kind: sql += " and kind = %s" args.append(kind) if q: sql += " and search_text like %s" args.append(f"%{q.lower()}%") sql += " order by updated_at desc limit %s" args.append(limit) cur.execute(sql, args) items = [dict(r) for r in cur.fetchall()] con.close() return {"count": len(items), "items": items} def do_similar(eid, limit=10): """Похожие карточки: общие темы, жанры и прямые связи «похож».""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("select id, kind, title from entities where id = %s", (eid,)) root = cur.fetchone() if not root: con.close() return None # два шага: фильм → темы/жанры → другие фильмы с теми же темами cur.execute(""" with mine as ( select l.to_id as node from entity_links l where l.from_id = %s and l.relation in ('тема', 'жанр') union select l.from_id as node from entity_links l where l.to_id = %s and l.relation in ('тема', 'жанр') ), hits as ( select l.from_id as film_id, count(*) as shared from entity_links l where l.to_id in (select node from mine) and l.relation in ('тема', 'жанр') and l.from_id <> %s group by l.from_id ) select e.id, e.kind, e.title, h.shared from hits h join entities e on e.id = h.film_id where e.kind in ('фильм', 'книга') order by h.shared desc, e.title limit %s """, (eid, eid, eid, limit)) items = [dict(r) for r in cur.fetchall()] # прямые связи «похож» cur.execute(""" select e.id, e.kind, e.title from entity_links l join entities e on e.id = case when l.from_id = %s then l.to_id else l.from_id end where (l.from_id = %s or l.to_id = %s) and l.relation = 'похож' """, (eid, eid, eid)) direct = [dict(r) for r in cur.fetchall()] con.close() return {"root": dict(root), "similar": items, "direct": direct} def do_person(query, limit=20): """Персона и её фильмы.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select id, kind, title from entities where kind in ('актёр','режиссёр','композитор') and search_text like %s order by length(title) limit 1""", (f"%{query.lower()}%",)) person = cur.fetchone() if not person: con.close() return None cur.execute(""" select e.title, e.kind, l.relation from entity_links l join entities e on e.id = case when l.from_id = %s then l.to_id else l.from_id end where (l.from_id = %s or l.to_id = %s) order by e.title """, (person["id"], person["id"], person["id"])) films = [dict(r) for r in cur.fetchall()] con.close() return {"person": dict(person), "films": films, "count": len(films)} def do_pick2(genre=None, theme=None, decade=None, kind="фильм", person=None, rating=None, limit=10): """Подбор из медиатеки с любыми фильтрами графа.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) conds = ["e.kind = %s"] args = [kind] def add_relation(rel, value): conds.append("""exists ( select 1 from entity_links li join entities ni on ni.id = li.to_id where li.from_id = e.id and li.relation = %s and ni.search_text like %s)""") args.extend([rel, f"%{value.lower()}%"]) if genre: add_relation("жанр", genre) if theme: add_relation("тема", theme) if decade: add_relation("снят в", decade) if rating: add_relation("оценка", rating) if person: conds.append("""exists ( select 1 from entity_links lp join entities np on np.id = lp.to_id where lp.from_id = e.id and np.kind in ('актёр','режиссёр','композитор') and np.search_text like %s)""") args.append(f"%{person.lower()}%") sql = ("select e.id, e.title, e.kind, e.status from entities e where " + " and ".join(conds) + " order by e.title limit %s") args.append(limit) cur.execute(sql, args) items = [dict(r) for r in cur.fetchall()] for it in items: cur.execute("""select n.title from entity_links l join entities n on n.id = l.to_id where l.from_id = %s and l.relation = 'оценка' limit 1""", (it["id"],)) row = cur.fetchone() it["rating"] = row["title"] if row else None cur.execute("""select string_agg(n.title, ', ') from entity_links l join entities n on n.id = l.to_id where l.from_id = %s and l.relation = 'жанр'""", (it["id"],)) it["genres"] = cur.fetchone()["string_agg"] con.close() return {"count": len(items), "items": items} def do_compare(book_query, film_query): """Сравнение книги и фильма: что общего.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) def find(kind, q): cur.execute("""select id, kind, title from entities where kind = %s and search_text like %s order by length(title) limit 1""", (kind, f"%{q.lower()}%")) return cur.fetchone() book = find("книга", book_query) film = find("фильм", film_query) if not book or not film: con.close() return None def related(eid, rel): cur.execute("""select n.title from entity_links l join entities n on n.id = l.to_id where l.from_id = %s and l.relation = %s""", (eid, rel)) return {r["title"] for r in cur.fetchall()} b_genres, b_themes = related(book["id"], "жанр"), related(book["id"], "тема") f_genres, f_themes = related(film["id"], "жанр"), related(film["id"], "тема") b_authors = related(book["id"], "написал") cur.execute("""select 1 from entity_links l where l.from_id = %s and l.to_id = %s and l.relation = 'экранизация'""", (book["id"], film["id"])) linked = cur.fetchone() is not None con.close() return { "book": dict(book), "film": dict(film), "linked": linked, "common_genres": sorted(b_genres & f_genres), "only_book_genres": sorted(b_genres - f_genres), "only_film_genres": sorted(f_genres - b_genres), "common_themes": sorted(b_themes & f_themes), "authors": sorted(b_authors), } def do_timeline(node_query, kind="тема"): """Тема или жанр по десятилетиям.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select id, title from entities where kind = %s and search_text like %s order by length(title) limit 1""", (kind, f"%{node_query.lower()}%")) node = cur.fetchone() if not node: con.close() return None cur.execute(""" with items as ( select case when l.from_id = %s then l.to_id else l.from_id end as item_id from entity_links l where (l.from_id = %s or l.to_id = %s) and l.relation = %s ) select d.title as decade, count(*) as n, string_agg(e.title, ',' order by e.title) as items from items i join entity_links l on (l.from_id = i.item_id and l.relation = 'снят в') join entities d on d.id = l.to_id join entities e on e.id = i.item_id group by d.title order by d.title """, (node["id"], node["id"], node["id"], kind)) rows = [dict(r) for r in cur.fetchall()] con.close() return {"node": dict(node), "decades": rows} def do_cross(limit=50): """Книги с экранизацией и авторы, чьи книги экранизированы.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute(""" select b.title as book, f.title as film from entity_links l join entities b on b.id = l.from_id and b.kind = 'книга' join entities f on f.id = l.to_id and f.kind = 'фильм' where l.relation = 'экранизация' order by b.title limit %s """, (limit,)) books_with_film = [dict(r) for r in cur.fetchall()] cur.execute(""" select a.title as author, f.title as film from entity_links l join entities a on a.id = l.from_id and a.kind = 'автор' join entities f on f.id = l.to_id and f.kind = 'фильм' where l.relation = 'экранирован' order by a.title limit %s """, (limit,)) authors_screened = [dict(r) for r in cur.fetchall()] con.close() return {"books_with_film": books_with_film, "authors_screened": authors_screened} def do_top_persons(kind="актёр", limit=10): """Персоны с наибольшим числом фильмов.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute(""" select e.id, e.title, count(*) as films from entity_links l join entities e on e.id = case when l.from_id = e.id then e.id else l.to_id end where e.kind = %s and l.relation in ('снялся','снял','музыка') group by e.id, e.title order by films desc, e.title limit %s """, (kind, limit)) items = [dict(r) for r in cur.fetchall()] con.close() return {"kind": kind, "items": items} def do_graph_stats(): con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("select kind, count(*) as n from entities group by kind order by n desc") cards = [dict(r) for r in cur.fetchall()] cur.execute("select relation, count(*) as n from entity_links group by relation order by n desc") relations = [dict(r) for r in cur.fetchall()] con.close() return {"cards": cards, "relations": relations, "total_cards": sum(c["n"] for c in cards), "total_links": sum(r["n"] for r in relations)} def do_graph_json(limit=150): """Узлы и рёбра для визуализации.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute(""" select e.id, e.kind, e.title, count(l.id) as degree from entities e left join entity_links l on l.from_id = e.id or l.to_id = e.id group by e.id, e.kind, e.title order by degree desc limit %s """, (limit,)) nodes = [dict(r) for r in cur.fetchall()] ids = [n["id"] for n in nodes] edges = [] if ids: cur.execute(""" select l.from_id as source, l.to_id as target, l.relation from entity_links l where l.from_id = any(%s) and l.to_id = any(%s) limit 500 """, (ids, ids)) edges = [dict(r) for r in cur.fetchall()] con.close() return {"nodes": nodes, "edges": edges} MOODS = { "мрачн": ["dystopia", "noir", "dark", "survival", "horror", "thriller", "drama"], "мрач": ["dystopia", "noir", "dark", "survival", "horror", "thriller", "drama"], "тяжёл": ["drama", "war", "thriller", "mystery"], "лёгк": ["comedy", "family", "adventure", "romance"], "легк": ["comedy", "family", "adventure", "romance"], "добр": ["family", "friendship", "adventure", "comedy"], "умн": ["artificial intelligence", "based on novel", "mystery", "science fiction"], "эпичн": ["epic", "space opera", "adventure", "science fiction", "war"], "страшн": ["horror", "monster", "thriller", "mystery"], "смешн": ["comedy"], "романтич": ["romance", "drama"], "детектив": ["detective", "mystery", "crime", "thriller"], } def do_mood(mood, limit=10): """Подбор по настроению: темы и жанры из словаря MOODS.""" low = (mood or "").lower() hints = [] for key, words in MOODS.items(): if key in low: hints = words break if not hints: return {"mood": mood, "count": 0, "items": [], "hints": []} con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) like = ["%" + h.lower() + "%" for h in hints] cur.execute(""" select e.id, e.title, count(distinct n.id) as score from entities e join entity_links l on l.from_id = e.id join entities n on n.id = l.to_id where e.kind = 'фильм' and n.search_text like any(%s) and l.relation in ('тема', 'жанр') group by e.id, e.title order by score desc, e.title limit %s """, (like, limit)) items = [dict(r) for r in cur.fetchall()] for it in items: cur.execute("""select n.title from entity_links l join entities n on n.id = l.to_id where l.from_id = %s and l.relation = 'оценка' limit 1""", (it["id"],)) row = cur.fetchone() it["rating"] = row["title"] if row else None con.close() return {"mood": mood, "count": len(items), "items": items, "hints": hints} def do_candidates(limit=20): """Кандидаты из рекомендаций: чего нет в медиатеке.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select e.id, e.title, e.key, e.status, count(l.id) as votes from entities e left join entity_links l on l.to_id = e.id and l.relation = 'рекомендует' where e.kind = 'кандидат' group by e.id, e.title, e.key, e.status order by votes desc, e.title limit %s""", (limit,)) items = [dict(r) for r in cur.fetchall()] for it in items: it["tmdb"] = (it.get("key") or "").replace("candidate:", "") con.close() return {"count": len(items), "items": items} def do_coworkers(query, limit=12): """С кем вместе снимался: партнёры по фильмам.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select id, title from entities where kind in ('актёр','режиссёр','композитор') and search_text like %s order by length(title) limit 1""", (f"%{query.lower()}%",)) person = cur.fetchone() if not person: con.close() return None cur.execute(""" with films as ( select case when l.from_id = %s then l.to_id else l.from_id end as fid from entity_links l where (l.from_id = %s or l.to_id = %s) ) select p.id, p.title, p.kind, count(*) as together, string_agg(f.title, ', ' order by f.title) as films from films x join entity_links l on (l.from_id = x.fid) join entities p on p.id = l.to_id and p.kind in ('актёр','режиссёр','композитор') join entities f on f.id = x.fid where l.relation in ('снялся','снял','музыка') and p.id <> %s group by p.id, p.title, p.kind order by together desc, p.title limit %s """, (person["id"], person["id"], person["id"], person["id"], limit)) partners = [dict(r) for r in cur.fetchall()] con.close() return {"person": dict(person), "partners": partners} def do_suggest(q, limit=8): """Подсказки по началу названия: для автодополнения.""" if not q or len(q.strip()) < 2: return {"query": q, "items": []} con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select id, kind, title from entities where search_text like %s order by length(title) limit %s""", (f"%{q.strip().lower()}%", limit)) items = [dict(r) for r in cur.fetchall()] con.close() return {"query": q, "items": items} def snapshot_graph(day=None): """Снимок размеров графа за день.""" from datetime import date day = day or date.today().isoformat() con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""create table if not exists graph_history ( day date primary key, cards integer, links integer, persons integer)""") cur.execute("select count(*) as n from entities") cards = cur.fetchone()["n"] cur.execute("select count(*) as n from entity_links") links = cur.fetchone()["n"] cur.execute("select count(*) as n from entities where kind in ('актёр','режиссёр','композитор')") persons = cur.fetchone()["n"] cur.execute("""insert into graph_history (day, cards, links, persons) values (%s, %s, %s, %s) on conflict (day) do update set cards = %s, links = %s, persons = %s""", (day, cards, links, persons, cards, links, persons)) con.commit() con.close() return {"day": str(day), "cards": cards, "links": links, "persons": persons} def do_history(days=30): con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select day, cards, links, persons from graph_history order by day desc limit %s""", (days,)) rows = [dict(r) for r in cur.fetchall()] con.close() rows.reverse() growth = None if len(rows) >= 2: growth = {"cards": rows[-1]["cards"] - rows[0]["cards"], "links": rows[-1]["links"] - rows[0]["links"]} return {"items": rows, "growth": growth} def do_seasons(query): """Сериал и его сезоны с числом эпизодов.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select id, title from entities where kind = 'сериал' and search_text like %s order by length(title) limit 1""", (f"%{query.lower()}%",)) series = cur.fetchone() if not series: con.close() return None cur.execute("""select b.title, b.status, l.relation from entity_links l join entities b on b.id = l.to_id where l.from_id = %s and b.kind = 'сезон' order by b.title""", (series["id"],)) seasons = [dict(r) for r in cur.fetchall()] con.close() return {"series": dict(series), "seasons": seasons, "count": len(seasons)} def do_watchlist(mark=None, note=None): """Список «хочу посмотреть»: карточки со статусом.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) if mark: cur.execute("""select id, kind, title from entities where search_text like %s order by length(title) limit 1""", (f"%{mark.lower()}%",)) row = cur.fetchone() if not row: con.close() return None cur.execute("""update entities set status = %s, updated_at = now() where id = %s""", ("хочу посмотреть", row["id"])) con.commit() con.close() return {"marked": dict(row), "status": "хочу посмотреть"} cur.execute("""select id, kind, title, updated_at from entities where status in ('хочу посмотреть', 'смотрю') order by updated_at desc limit 50""") items = [dict(r) for r in cur.fetchall()] con.close() return {"count": len(items), "items": items} def do_rate(title, score): """Личная оценка карточки (1–10).""" try: score = max(1, min(10, int(score))) except (TypeError, ValueError): return None con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""create table if not exists user_ratings ( entity_id integer, score integer, updated_at timestamptz default now(), primary key (entity_id))""") cur.execute("""select id, kind, title from entities where search_text like %s order by length(title) limit 1""", (f"%{title.lower()}%",)) row = cur.fetchone() if not row: con.close() return None cur.execute("""insert into user_ratings (entity_id, score, updated_at) values (%s, %s, now()) on conflict (entity_id) do update set score = %s, updated_at = now()""", (row["id"], score, score)) con.commit() con.close() return {"rated": dict(row), "score": score} def do_rated(limit=30): """Мои оценки: от высокой к низкой.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("""select e.id, e.kind, e.title, r.score from user_ratings r join entities e on e.id = r.entity_id order by r.score desc, e.title limit %s""", (limit,)) items = [dict(r) for r in cur.fetchall()] con.close() avg = round(sum(i["score"] for i in items) / len(items), 2) if items else None return {"count": len(items), "average": avg, "items": items} def do_for_me(limit=10): """Рекомендации на основе высоких личных оценок.""" con = db() cur = con.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # что я оценил высоко cur.execute("""select e.id, e.title, r.score from user_ratings r join entities e on e.id = r.entity_id where r.score >= 8 order by r.score desc limit 10""") liked = cur.fetchall() if not liked: con.close() return {"liked": [], "items": [], "reason": "нет высоких оценок"} liked_ids = [r["id"] for r in liked] rated_ids = set() cur.execute("select entity_id from user_ratings") for r in cur.fetchall(): rated_ids.add(r["entity_id"]) # темы и жанры любимых cur.execute("""select distinct l.to_id as node from entity_links l where l.from_id = any(%s) and l.relation in ('тема','жанр')""", (liked_ids,)) nodes = [r["node"] for r in cur.fetchall()] items = [] if nodes: cur.execute(""" select e.id, e.title, e.kind, count(*) as score from entity_links l join entities e on e.id = l.from_id where l.to_id = any(%s) and l.relation in ('тема','жанр') and e.kind in ('фильм','сериал') group by e.id, e.title, e.kind order by score desc, e.title limit %s """, (nodes, limit * 3)) for r in cur.fetchall(): if r["id"] not in rated_ids and r["id"] not in liked_ids: items.append(dict(r)) # добить кандидатами, которых нет в медиатеке if len(items) < limit: cur.execute("""select e.id, e.title, count(l.id) as votes from entities e left join entity_links l on l.to_id = e.id and l.relation = 'рекомендует' where e.kind = 'кандидат' group by e.id, e.title order by votes desc limit %s""", (limit,)) for r in cur.fetchall(): cand = {"id": r["id"], "title": r["title"], "kind": "кандидат", "score": r["votes"]} if not any(i["id"] == cand["id"] for i in items): items.append(cand) con.close() return {"liked": [dict(r) for r in liked], "items": items[:limit], "reason": "по темам и жанрам любимых"} def yandex_status(): """Есть ли токен Яндекс Музыки и что он даёт.""" import os as _os import json as _json import urllib.request as _rq path = "/root/.yandex-token" if not _os.path.exists(path): return {"has_token": False} tok = open(path, encoding="utf-8").read().strip() req = _rq.Request("https://api.music.yandex.net/account/status", headers={"Authorization": "OAuth " + tok}) try: with _rq.urlopen(req, timeout=15) as r: d = _json.loads(r.read() or b"{}") res = d.get("result") or {} acc = res.get("account") or {} if not acc.get("uid"): return {"has_token": False, "error": "токен не принят: Яндекс вернул гостевой аккаунт"} return {"has_token": True, "login": acc.get("displayName") or acc.get("login"), "uid": acc.get("uid"), "plus": bool((res.get("plus") or {}).get("hasPlus"))} except Exception as e: return {"has_token": True, "error": str(e)[:120]} def extract_token(raw): """Достаёт токен из строки: поддерживает URL с #access_token=...""" import re as _re raw = (raw or "").strip() m = _re.search(r"access_token=([A-Za-z0-9._~+/=-]+)", raw) if m: return m.group(1) m = _re.search(r"OAuth\s+([A-Za-z0-9._~+/=-]+)", raw) if m: return m.group(1) return raw.split()[0] if raw else "" def yandex_save(tok): """Сохраняет токен и сразу проверяет его.""" import os as _os tok = extract_token(tok) if not tok or len(tok) < 20: return {"error": "токен слишком короткий — вставьте саму строку токена или ссылку"} # сначала проверяем, потом сохраняем import json as _j import urllib.request as _r req = _r.Request("https://api.music.yandex.net/account/status", headers={"Authorization": "OAuth " + tok}) try: with _r.urlopen(req, timeout=15) as resp: d = _j.loads(resp.read() or b"{}") except Exception as e: return {"error": "Яндекс не принял токен: " + str(e)[:80]} res = d.get("result") or {} acc = res.get("account") or {} if not acc.get("uid"): return {"error": "Яндекс вернул гостевой аккаунт — токен не подходит"} path = "/root/.yandex-token" with open(path, "w", encoding="utf-8") as f: f.write(tok) _os.chmod(path, 0o600) return yandex_status() YANDEX_KEYS = "/root/.yandex-keys.json" YANDEX_TOKENS_DIR = "/root/.yandex-tokens" YANDEX_USERS = ["roman", "elena", "polina", "nikita", "daniil", "sergey", "alextest"] def yandex_keys(): """Ключи-ссылки для пользователей: имя → секрет.""" import os as _os import secrets as _sec if _os.path.exists(YANDEX_KEYS): try: return json.load(open(YANDEX_KEYS, encoding="utf-8")) except Exception: pass keys = {u: _sec.token_urlsafe(16) for u in YANDEX_USERS} with open(YANDEX_KEYS, "w", encoding="utf-8") as f: json.dump(keys, f, ensure_ascii=False, indent=2) _os.chmod(YANDEX_KEYS, 0o600) return keys def yandex_user_by_key(key): if not key: return None for user, k in yandex_keys().items(): if k == key: return user return None def yandex_token_path(user): import os as _os _os.makedirs(YANDEX_TOKENS_DIR, exist_ok=True) return _os.path.join(YANDEX_TOKENS_DIR, user + ".json") def yandex_user_status(user): import os as _os import urllib.request as _rq path = yandex_token_path(user) if not _os.path.exists(path): return {"user": user, "has_token": False} try: data = json.load(open(path, encoding="utf-8")) except Exception: return {"user": user, "has_token": False} tok = data.get("token") or "" if not tok: return {"user": user, "has_token": False} req = _rq.Request("https://api.music.yandex.net/account/status", headers={"Authorization": "OAuth " + tok}) try: with _rq.urlopen(req, timeout=15) as r: d = json.loads(r.read() or b"{}") except Exception as e: return {"user": user, "has_token": True, "error": str(e)[:100]} res = d.get("result") or {} acc = res.get("account") or {} return {"user": user, "has_token": bool(acc.get("uid")), "login": acc.get("displayName") or acc.get("login"), "plus": bool((res.get("plus") or {}).get("hasPlus"))} def yandex_save_for(user, tok): import os as _os import urllib.request as _rq tok = extract_token(tok) if not tok or len(tok) < 20: return {"error": "токен слишком короткий"} req = _rq.Request("https://api.music.yandex.net/account/status", headers={"Authorization": "OAuth " + tok}) try: with _rq.urlopen(req, timeout=15) as r: d = json.loads(r.read() or b"{}") except Exception as e: return {"error": "Яндекс не принял токен: " + str(e)[:80]} res = d.get("result") or {} acc = res.get("account") or {} if not acc.get("uid"): return {"error": "Яндекс вернул гостевой аккаунт — токен не подходит"} path = yandex_token_path(user) payload = {"token": tok, "login": acc.get("displayName") or acc.get("login"), "uid": acc.get("uid"), "plus": bool((res.get("plus") or {}).get("hasPlus"))} with open(path, "w", encoding="utf-8") as f: json.dump(payload, f, ensure_ascii=False) _os.chmod(path, 0o600) return {"user": user, "has_token": True, "login": payload["login"], "plus": payload["plus"]} def render_panel(): """HTML-страница: состояние системы в одном месте.""" try: con = db() cur = con.cursor() cur.execute("select count(*) from entities") entities = cur.fetchone()[0] cur.execute("select count(*) from events") events = cur.fetchone()[0] cur.execute("select count(*) from events where at > now() - interval '24 hours'") events24 = cur.fetchone()[0] cur.execute("select count(*) from problems where resolved_at is null") open_problems = cur.fetchone()[0] cur.execute("""select check_name, detail, at from problems where resolved_at is null order by at desc limit 10""") problems = cur.fetchall() cur.execute("""select at, source, type, entity->>'title' from events order by id desc limit 25""") recent = cur.fetchall() cur.execute("""select source, count(*) as total, count(*) filter (where at > now() - interval '24 hours') as last24, max(at) as last_at from events group by source order by total desc""") by_source = cur.fetchall() try: cur.execute("""select payload from data_docs where collection='inventory' order by updated_at desc limit 1""") invrow = cur.fetchone() inventory = invrow[0] if invrow else None except Exception: inventory = None try: cur.execute("""select payload from data_docs where collection='identity' order by updated_at desc limit 1""") idrow = cur.fetchone() identity = idrow[0] if idrow else None except Exception: identity = None jobs = jobs_status() try: gstats = do_graph_stats() except Exception: gstats = {"cards": [], "relations": [], "total_cards": 0, "total_links": 0} try: tl = do_timeline("science fiction", "жанр") except Exception: tl = None try: hist = do_history(30) growth = hist.get("growth") except Exception: growth = None try: dev_data, _de = None, None import urllib.request as _dreq with _dreq.urlopen("http://127.0.0.1:9120/data/devices", timeout=10) as _dr: _dj = json.loads(_dr.read() or b"{}") _items = (_dj.get("items") or []) dev_data = ((_items[0].get("payload") if _items else {}) or {}) except Exception: dev_data = {} try: personal = {"watch": do_watchlist().get("items") or [], "rated": do_rated(5).get("items") or [], "forme": do_for_me(5).get("items") or []} except Exception: personal = {"watch": [], "rated": [], "forme": []} try: cross = do_cross(limit=10) except Exception: cross = {"books_with_film": [], "authors_screened": []} try: top_genres = do_pick(limit=100) if False else [] except Exception: top_genres = [] cur.execute("select count(*) from entity_links") links = cur.fetchone()[0] cur.execute("""select at, kind, target, detail, status from actions order by id desc limit 10""") actions = cur.fetchall() con.close() err = None except Exception as e: entities = events = events24 = open_problems = 0 problems, recent, by_source, actions, links, inventory, identity = [], [], [], [], 0, None, None jobs = [] gstats = {"cards": [], "relations": [], "total_cards": 0, "total_links": 0} cross = {"books_with_film": [], "authors_screened": []} err = str(e)[:200] def esc(x): return (str(x) if x is not None else "—").replace("&", "&").replace("<", "<") rows = "".join( f"{esc(at.strftime('%d.%m %H:%M'))}{esc(src)}" f"{esc(typ)}{esc(title)}" for at, src, typ, title in recent) or "событий пока нет" media_kinds = {"фильм", "книга", "жанр", "тема", "актёр", "режиссёр", "композитор", "студия", "коллекция", "серия книг", "автор", "эпоха", "кандидат", "оценка", "язык", "рейтинг"} g_cards = sum(c["n"] for c in gstats.get("cards") or [] if c["kind"] in media_kinds) g_links = gstats.get("total_links") or 0 max_rel = max([r["n"] for r in gstats.get("relations") or []] or [1]) g_rel_rows = "".join( f"{esc(r['relation'])}{r['n']}" f"
" for r in (gstats.get("relations") or [])[:12]) or "пусто" cross_rows = [] for b in (cross.get("books_with_film") or [])[:6]: cross_rows.append(f"📖 {esc(b['book'])}↔🎬 {esc(b['film'])}") for a in (cross.get("authors_screened") or [])[:6]: cross_rows.append(f"✍️ {esc(a['author'])}→🎬 {esc(a['film'])}") devs = dev_data.get("devices") or [] dev_online = sum(1 for x in devs if x.get("online")) dev_types = {} for x in devs: t = x.get("type") or "устройство" dev_types[t] = dev_types.get(t, 0) + 1 g_dev_summary = (f"всего {len(devs)}, онлайн {dev_online} · " + " · ".join(f"{t} {n}" for t, n in sorted(dev_types.items(), key=lambda kv: -kv[1])[:5])) g_dev_rows = "".join( f"{'●' if x.get('online') else '○'}{esc(x.get('ip') or '—')}" f"{esc(x.get('name') or '—')}{esc(x.get('type') or '')}" for x in sorted([d for d in devs if d.get("online") and d.get("type") != "контейнер"], key=lambda y: y.get("type") or "")[:10]) or "нет данных" rows = [] for w in personal.get("watch") or []: rows.append(f"🎯{esc(w['title'])}хочу посмотреть") for r in personal.get("rated") or []: rows.append(f"⭐{esc(r['title'])}{r['score']}/10") for f in personal.get("forme") or []: rows.append(f"💡{esc(f['title'])}{esc(str(f.get('kind') or ''))}") g_personal = "".join(rows) or "пока пусто: !хочу и !оценка" g_timeline = "
нет данных
" if tl and tl.get("decades"): mx = max(d["n"] for d in tl["decades"]) or 1 bars = [] for d in tl["decades"]: w = int(220 * d["n"] / mx) bars.append( f"
" f"{esc(d['decade'])}" f"
" f"{d['n']}
") g_timeline = "".join(bars) g_growth = "" if growth: g_growth = (" · рост за период: карточек " + str(growth.get("cards")) + ", связей " + str(growth.get("links"))) g_cross_rows = "".join(cross_rows) or "пока нет совпадений" job_rows = "".join( f"{esc(n)}{(str(round(a, 1)) + ' ч') if a is not None else '—'}" f"{lim} ч{esc(st)}" for n, a, lim, st in jobs) or "нет данных" identity_text = "аудит ещё не запускался" if isinstance(identity, dict) and identity.get("table"): identity_text = identity["table"] inv_rows = "" if isinstance(inventory, dict): jf = inventory.get("jellyfin") or {} nv = inventory.get("navidrome") or {} cb = inventory.get("calibre") or {} im = inventory.get("immich") or {} pl = inventory.get("paperless") or {} fr = inventory.get("frigate") or {} inv_rows = ( f"Jellyfin{jf.get('Movie')} фильмов, {jf.get('Series')} сериалов, " f"{jf.get('Episode')} серий" f"Navidrome{nv.get('albums')} альбомов, {nv.get('tracks')} треков" f"Calibre{cb.get('books')} книг" f"Immich{im.get('assets')} снимков, {im.get('albums')} альбомов" f"Paperless{pl.get('documents')} документов" f"Frigate{fr.get('cameras')} камер") if not inv_rows: inv_rows = 'инвентаризация ещё не собиралась' arows = "".join( f"{esc(at.strftime('%d.%m %H:%M'))}{esc(kind)}" f"{esc(target)}{esc(detail)}" f"{esc(st)}" for at, kind, target, detail, st in actions) or "действий не было" prow = "".join( f"{esc(name)}{esc(detail)}" for name, detail, _ in problems) or "открытых проблем нет" src_rows = "".join( f"{esc(src)}{total}{last24}{esc(str(last_at)[:16])}" for src, total, last24, last_at in by_source) or "событий пока нет" return f""" Buryan Hub

Buryan Hub

ядро событий и карточек · обновлено сейчас
{'

Ошибка базы: ' + esc(err) + '

' if err else ''}
{entities}карточек
{events}событий всего
{events24}за 24 часа
{open_problems}проблем
{links}связей

Задачи

{job_rows}
задачапоследний запускпределсостояние

Проблемы

{prow}
проверкачто не так

Графики

Дашборд: Grafana — Buryan Hub · метрики Prometheus

Медиа: граф контента

устройства сети · интерактивный граф · спросить агента
карточек {g_cards} · связей {g_links}{g_growth}
{g_rel_rows}
связьсколько

Фантастика по десятилетиям

{g_timeline}

Книги и экранизации

{g_cross_rows}

Устройства сети

{g_dev_summary}
{g_dev_rows}
полный список →

Личное

хочу посмотреть · мои оценки · для вас
{g_personal}

Доступы по сервисам

аудит по понедельникам, команда !users у бота Инфраструктура
{identity_text}

Что есть в сервисах

{inv_rows}
сервисчто есть

Действия сверки и автоисправлений

{arows}
когдачтоцельрезультатстатус

Последние события

{rows}
когдаисточниктипобъект

Источники событий

{src_rows}
источниквсегоза суткипоследнее
""" JELLYFIN_URL = os.environ.get("JELLYFIN_URL", "http://192.168.1.103:8096") JELLYFIN_KEY = os.environ.get("JELLYFIN_KEY", "") def _jellyfin_scan(): """Просим Jellyfin пересканировать библиотеку.""" if not JELLYFIN_KEY: return False, "нет ключа Jellyfin" req = urllib.request.Request( f"{JELLYFIN_URL}/Library/Refresh", data=b"", method="POST", headers={"Authorization": f'MediaBrowser Token="{JELLYFIN_KEY}"'}) try: with urllib.request.urlopen(req, timeout=20) as r: return r.status in (200, 204), f"HTTP {r.status}" except urllib.error.HTTPError as e: return False, f"HTTP {e.code}" except Exception as e: return False, str(e)[:100] def _journal(kind, target, detail, status="done", rollback=None): try: con = db() with con.cursor() as cur: cur.execute("""insert into actions (kind, target, detail, status, rollback) values (%s,%s,%s,%s,%s)""", (kind, target, detail, status, rollback)) con.close() except Exception: pass def auto_actions(ev, etype): """Что сделать сразу после события.""" ent = ev.get("entity") or {} title = ent.get("title") or ent.get("key") or "объект" if etype == "media.imported": ok, detail = _jellyfin_scan() _journal("scan", "jellyfin", f"после импорта «{title}»: {detail}", "done" if ok else "failed", None) return ok if etype == "media.requested": # заявку просто фиксируем: одобрение — решение человека _journal("note", "seerr", f"заявка «{title}» принята", "done", None) return True return False _STATUS_CACHE = {"ts": 0, "data": None} def _parse_registry(): """Читает services.yaml и достаёт имя, группу, CT и первый host-порт.""" import re as _re path = "/opt/hub-core/services.yaml" try: text = open(path, encoding="utf-8").read() except Exception: return [] items = [] cur = None for line in text.splitlines(): if line.startswith(" - key:"): if cur: items.append(cur) cur = {"key": line.split(":", 1)[1].strip().strip('"')} elif cur is not None and line.startswith(" "): k, _, v = line.strip().partition(":") cur[k] = v.strip().strip('"') if cur: items.append(cur) out = [] for it in items: _mon = it.get("monitoring") if _mon is False or str(_mon).strip().lower() in ("off", "false", "no"): continue ports = it.get("ports") or "" m = _re.search(r":(\d+)->", ports) internal = False if not m: m2 = _re.search(r"(\d+)/tcp", ports) if m2: internal = True m = m2 else: internal = True m = None ct = int(it.get("ct") or 0) ip = "192.168.1.10" if ct == 0 else f"192.168.1.{ct}" out.append({ "name": it.get("name"), "group": it.get("group", "other"), "criticality": it.get("criticality", "normal"), "ct": ct, "ip": ip, "port": int(m.group(1)) if m else 0, "internal": internal, }) return out def _tcp_ok(ip, port, timeout=1.2): import socket as _socket try: with _socket.create_connection((ip, port), timeout=timeout): return True except Exception: return False def _docker_states(): """Возвращает {(ct, name): up} по всем CT и хосту; CT опрашиваются параллельно.""" import subprocess as _sp from concurrent.futures import ThreadPoolExecutor states = {} def parse(text, ct): for line in text.splitlines(): if "|" not in line: continue name, status = line.split("|", 1) states[(ct, name.strip())] = status.strip().lower().startswith("up") try: out = _sp.run(["docker", "ps", "--format", "{{.Names}}|{{.Status}}"], capture_output=True, text=True, timeout=10).stdout parse(out, 0) except Exception: pass try: cts = _sp.run(["pct", "list"], capture_output=True, text=True, timeout=10).stdout ids = [] for line in cts.splitlines()[1:]: parts = line.split() if len(parts) >= 3: try: ids.append(int(parts[0])) except ValueError: pass def probe(ct): try: out = _sp.run(["pct", "exec", str(ct), "--", "docker", "ps", "--format", "{{.Names}}|{{.Status}}"], capture_output=True, text=True, timeout=15).stdout return ct, out except Exception: return ct, None with ThreadPoolExecutor(max_workers=4) as ex: for ct, out in ex.map(probe, ids): if out is not None: parse(out, ct) except Exception: pass return states def _media_event(payload): """Webhook от Radarr/Sonarr: уведомление о новинке в Matrix.""" try: etype = payload.get("eventType") or payload.get("event") or "media" movie = payload.get("movie") or {} series = payload.get("series") or {} title = movie.get("title") or series.get("title") or "Медиа" year = movie.get("year") or series.get("year") or "" if etype in ("Download", "Grab", "Test"): icon = {"Download": "🎬", "Grab": "⬇️", "Test": "🔔"}.get(etype, "🎬") text = f"{icon} **{title}**" if year: text += f" ({year})" if etype == "Download": text += "\n\nФайл загружен и добавлен в библиотеку." elif etype == "Grab": text += "\n\nНачалась загрузка." else: text += "\n\nПроверка связи прошла." _matrix_notify(text) return {"ok": True, "sent": True} return {"ok": True, "ignored": etype} except Exception as e: return {"ok": False, "error": str(e)[:120]} def _fts_search(q, limit=6, only_source=None): """Полнотекстовый поиск по индексу книг, документов и рецептов.""" import sqlite3 as _sq try: c = _sq.connect("/var/lib/hub-search/index.db") except Exception: return [] try: if only_source: rows = c.execute( "select source, title, ref, round(bm25(docs), 2) from docs " "where docs match ? and source = ? order by bm25(docs) limit ?", (q.strip() + "*", only_source, limit)).fetchall() else: rows = c.execute( "select source, title, ref, round(bm25(docs), 2) from docs " "where docs match ? order by bm25(docs) limit ?", (q.strip() + "*", limit)).fetchall() except Exception: return [] finally: c.close() out = [] for source, title, ref, rank in rows: out.append({"title": title, "source": source, "ref": ref}) return out def _hub_search(q, limit=5, only_source=None): """Единый поиск по сервисам: книги, фильмы, сериалы, документы, продукты.""" import json as _json import subprocess as _sp import urllib.parse as _up import urllib.request as _rq q = (q or "").strip() if not q: return {"query": q, "groups": []} ql = q.lower() groups = [] def add(title, items): if items: groups.append({"title": title, "items": items}) # полнотекстовый индекс — один блок fts = _fts_search(q, limit=limit, only_source=only_source) if fts: items = [] for item in fts: label = {"book": "книга", "doc": "документ", "recipe": "рецепт"}.get(item["source"], "") title = item["title"] + (f" ({label})" if label else "") items.append({"title": title}) groups.append({"title": "🔎 Точное совпадение", "items": items}) # книги (Calibre внутри CT111) try: code = ( "import sqlite3,json,sys\n" "q=sys.argv[1].lower()\n" "c=sqlite3.connect('/opt/books/library/metadata.db')\n" "rows=c.execute('select title,author_sort from books').fetchall()\n" "out=[{'title':t,'author':a} for t,a in rows if q in (t or '').lower() or q in (a or '').lower()]\n" "print(json.dumps(out[:10], ensure_ascii=False))\n" ) r = _sp.run(["pct", "exec", "111", "--", "python3", "-c", code, q], capture_output=True, text=True, timeout=40) add("📚 Книги", _json.loads(r.stdout or "[]")) except Exception: pass # Комбайн: каталог устройств if not only_source or only_source == "combine": try: with _rq.urlopen("http://127.0.0.1:8101/devices", timeout=12) as r: dev = _json.loads(r.read() or b"[]") devs = dev.get("devices") if isinstance(dev, dict) else dev items = [] for d in (devs or []): name = (d.get("name") or d.get("model") or "") if ql and ql in name.lower(): items.append({"title": name + " (комбайн)", "ref": d.get("key") or ""}) add("📐 Комбайн", items[:limit]) except Exception: pass # Gitea: репозитории if not only_source or only_source == "gitea": try: tok = "" for p in ("/root/.gitea-token", "/root/.gitea-admin-token"): try: tok = open(p, encoding="utf-8").read().strip() break except Exception: continue url = ("http://192.168.1.140:3000/api/v1/repos/search?limit=%d&q=%s" % (limit, _up.quote(q))) hdr = {"Authorization": "token " + tok} if tok else {} req = _rq.Request(url, headers=hdr) with _rq.urlopen(req, timeout=15) as r: gd = _json.loads(r.read() or b"{}") items = [{"title": (x.get("full_name") or "") + " (репозиторий)", "ref": x.get("html_url") or ""} for x in (gd.get("data") or [])[:limit]] if not items: for org in ("infrastructure", "root"): try: oreq = _rq.Request( "http://192.168.1.140:3000/api/v1/orgs/%s/repos?limit=20" % org, headers=hdr) with _rq.urlopen(oreq, timeout=10) as r2: orep = _json.loads(r2.read() or b"[]") for x in (orep or []): nm = x.get("full_name") or "" if ql in nm.lower(): items.append({"title": nm + " (репозиторий)", "ref": x.get("html_url") or ""}) except Exception: continue add("🧩 Gitea", items[:limit]) except Exception: pass # Nextcloud: файлы (helper внутри CT109) if not only_source or only_source == "nextcloud": try: r = _sp.run(["pct", "exec", "109", "--", "sh", "/usr/local/bin/nc_search.sh", q, str(limit)], capture_output=True, text=True, timeout=45) rows = [x for x in (r.stdout or "").splitlines() if x.strip()] add("📁 Nextcloud", [{"title": x} for x in rows[:limit]]) except Exception: pass # Radarr / Sonarr for title, base, keyfile, path, field in ( ("🎬 Фильмы", "http://192.168.1.118:7878", "/etc/hub-bots/bots.env", "/api/v3/movie", "RADARR_KEY"), ("📺 Сериалы", "http://192.168.1.117:8989", "/etc/hub-bots/bots.env", "/api/v3/series", "SONARR_KEY"), ): try: key = "" for line in open(keyfile, encoding="utf-8"): if line.startswith(field + "="): key = line.split("=", 1)[1].strip() req = _rq.Request(base + path, headers={"X-Api-Key": key}) with _rq.urlopen(req, timeout=20) as rr: data = _json.loads(rr.read() or b"[]") items = [{"title": x.get("title"), "year": x.get("year"), "have": bool(x.get("hasFile"))} for x in data if ql in (x.get("title") or "").lower()] add(title, items[:6]) except Exception: pass # Paperless try: tok = open("/root/.paperless-token", encoding="utf-8").read().strip() url = ("http://192.168.1.105:8000/api/documents/?page_size=6&query=" + _up.quote(q)) req = _rq.Request(url, headers={"Authorization": "Token " + tok}) with _rq.urlopen(req, timeout=20) as rr: data = _json.loads(rr.read() or b"{}") add("🧾 Документы", [{"title": d.get("title"), "id": d.get("id")} for d in data.get("results", [])]) except Exception: pass # Grocy продукты try: key = "" for line in open("/root/.mealie-grocy.json", encoding="utf-8"): key = "" cfg = _json.load(open("/root/.mealie-grocy.json")) req = _rq.Request("http://192.168.1.110:9283/api/objects/products", headers={"GROCY-API-KEY": cfg.get("grocy_key", ""), "X-Auth-Request-Email": "roman@buryans.ru"}) with _rq.urlopen(req, timeout=20) as rr: data = _json.loads(rr.read() or b"[]") items = [{"title": p.get("name")} for p in data if ql in (p.get("name") or "").lower()] add("🛒 Продукты", items[:6]) except Exception: pass # Mealie рецепты (Postgres) try: sql = ("select name from recipes where name ilike '%" + q.replace("'", "''") + "%' limit 6") r = _sp.run(["bash", "-lc", "PGPASSWORD='Buryan20261016mrAzbQ5SWdxwYg' psql -h 192.168.1.151 " "-U postgres -d mealie_db -t -A -c \"" + sql + "\""], capture_output=True, text=True, timeout=30) add("🍳 Рецепты", [{"title": x} for x in r.stdout.splitlines() if x.strip()]) except Exception: pass return {"query": q, "groups": groups} ME_WEATHER = {"partlycloudy": "переменная облачность", "cloudy": "облачно", "sunny": "ясно", "clear-night": "ясная ночь", "rainy": "дождь", "snowy": "снег", "fog": "туман", "windy": "ветер", "lightning": "гроза", "pouring": "ливень", "partlycloudy-night": "переменная облачность"} def _me_weather(): """Погода из Home Assistant.""" import json as _j import urllib.request as _rq try: token = open("/root/.ha-token", encoding="utf-8").read().strip() except Exception: return None try: req = _rq.Request("http://192.168.1.106:8123/api/states/weather.forecast_dom", headers={"Authorization": "Bearer " + token}) with _rq.urlopen(req, timeout=12) as r: d = _j.loads(r.read() or b"{}") a = d.get("attributes") or {} return {"temp": a.get("temperature"), "state": ME_WEATHER.get(d.get("state"), d.get("state")), "humidity": a.get("humidity"), "wind": a.get("wind_speed")} except Exception: return None def _me_tasks(): """Задачи Vikunja: просроченные и на 3 дня.""" import datetime as _dt import json as _j import subprocess as _sp sql = ("select title, due_date from tasks where done = 0 and due_date is not null " "order by due_date limit 20") inner = ("import sqlite3,json\n" "c=sqlite3.connect('/opt/lifestyle-lxc/vikunja/db/vikunja.db')\n" f"rows=c.execute({sql!r}).fetchall()\n" "print(json.dumps(rows))\n") try: r = _sp.run(["pct", "exec", "110", "--", "python3", "-c", inner], capture_output=True, text=True, timeout=30) rows = _j.loads(r.stdout or "[]") except Exception: return [] today = _dt.date.today() out = [] for title, due in rows: try: d = _dt.datetime.fromisoformat(str(due).replace("Z", "+00:00")).date() except Exception: continue if d <= today + _dt.timedelta(days=3): out.append({"title": title, "date": f"{d:%d.%m}", "overdue": d < today}) return out[:6] def _me_data(): """Собирает «моё»: продолжить просмотр, покупки, документы, книги.""" import json as _json import subprocess as _sp import urllib.request as _rq out = {"resume": [], "shopping": [], "docs": [], "books": 0, "tasks": [], "weather": _me_weather()} # Jellyfin: продолжить просмотр try: key = open("/root/.jellyfin-key", encoding="utf-8").read().strip() hdr = {"Authorization": f'MediaBrowser Token="{key}"'} req = _rq.Request("http://192.168.1.103:8096/Users", headers=hdr) with _rq.urlopen(req, timeout=15) as r: users = _json.loads(r.read() or b"[]") if users: uid = users[0]["Id"] req = _rq.Request( f"http://192.168.1.103:8096/Users/{uid}/Items/Resume" "?Limit=5&MediaTypes=Video", headers=hdr) with _rq.urlopen(req, timeout=15) as r: d = _json.loads(r.read() or b"{}") for it in d.get("Items", [])[:5]: pos = (it.get("UserData") or {}).get("PlaybackPositionTicks") or 0 out["resume"].append({"title": it.get("Name"), "min": int(pos / 600000000)}) except Exception: pass # Grocy: список покупок try: cfg = _json.load(open("/root/.mealie-grocy.json")) hdr = {"GROCY-API-KEY": cfg.get("grocy_key", ""), "X-Auth-Request-Email": "roman@buryans.ru"} req = _rq.Request("http://192.168.1.110:9283/api/objects/shopping_list", headers=hdr) with _rq.urlopen(req, timeout=15) as r: items = _json.loads(r.read() or b"[]") req = _rq.Request("http://192.168.1.110:9283/api/objects/products", headers=hdr) with _rq.urlopen(req, timeout=15) as r: prods = {p["id"]: p["name"] for p in _json.loads(r.read() or b"[]")} for it in items[:10]: out["shopping"].append(prods.get(it.get("product_id"), "—")) except Exception: pass # Paperless: последние документы try: tok = open("/root/.paperless-token", encoding="utf-8").read().strip() req = _rq.Request( "http://192.168.1.105:8000/api/documents/?page_size=5&ordering=-created", headers={"Authorization": "Token " + tok}) with _rq.urlopen(req, timeout=15) as r: d = _json.loads(r.read() or b"{}") for doc in d.get("results", [])[:5]: out["docs"].append(doc.get("title")) except Exception: pass # Immich: фото try: key = open("/root/.immich-key-new", encoding="utf-8").read().strip() hdr = {"x-api-key": key} req = _rq.Request("http://192.168.1.104:2283/api/server/statistics", headers=hdr) with _rq.urlopen(req, timeout=12) as r: st = _json.loads(r.read() or b"{}") out["photos"] = {"total": st.get("photos", 0), "videos": st.get("videos", 0), "usage_gb": round((st.get("usage") or 0) / 1073741824, 1)} except Exception: pass # Firefly: финансы за месяц try: for p in ("/root/.firefly-token", "/root/.firefly-key"): if os.path.exists(p): tok = open(p, encoding="utf-8").read().strip() req = _rq.Request( "http://192.168.1.110:8080/api/v1/summary/basic?start=" + __import__("datetime").date.today().replace(day=1).isoformat() + "&end=" + __import__("datetime").date.today().isoformat(), headers={"Authorization": "Bearer " + tok, "Accept": "application/json"}) with _rq.urlopen(req, timeout=12) as r: fin = _json.loads(r.read() or b"{}") out["finance"] = {"spent": fin.get("spent", [])[:1], "earned": fin.get("earned", [])[:1]} break except Exception: pass # Комбайн: проекты try: with _rq.urlopen("http://127.0.0.1:8103/list", timeout=8) as r: d = _json.loads(r.read() or b"{}") out["projects"] = (d.get("projects") or [])[:4] except Exception: pass # Книги: сколько в библиотеке try: r = _sp.run(["pct", "exec", "111", "--", "python3", "-c", "import sqlite3;c=sqlite3.connect('/opt/books/library/metadata.db');" "print(c.execute('select count(*) from books').fetchone()[0])"], capture_output=True, text=True, timeout=30) out["books"] = int((r.stdout or "0").strip() or 0) except Exception: pass out["tasks"] = _me_tasks() return out def _me_extra_blocks(d): """Дополнительные блоки «Моё»: фото, финансы, проекты комбайна.""" def sec(title, rows, empty): body = "".join(f"
  • {r}
  • " for r in rows) if rows else f"
  • {empty}
  • " return f"

    {title}

    " out = [] ph = d.get("photos") if ph: out.append(sec("📷 Фото", [f"всего {ph['total']}, видео {ph['videos']}, занято {ph['usage_gb']} ГБ"], "нет данных")) fin = d.get("finance") if fin: rows = [] for key, label in (("spent", "потрачено"), ("earned", "получено")): for it in (fin.get(key) or []): v = it.get("monetary_value") or it.get("value") or "" cur = (it.get("currency_code") or "") rows.append(f"{label}: {v} {cur}".strip()) out.append(sec("💰 Финансы (месяц)", rows, "нет данных")) pr = d.get("projects") if pr: rows = [f"{p.get('name')} — {p.get('rooms', 0)} комн., {p.get('units', 0)} ед." for p in pr] out.append(sec("📐 Проекты", rows, "нет проектов")) return "".join(out) ROOM_RENDER_DIR = "/root/buryan-infra/ops/home/renders/web" ROOM_TITLES = { "bedroom": "Спальня · 11.45 м²", "kitchen-living": "Кухня-гостиная · 27.65 м²", "office": "Кабинет · 11.14 м²", "bathroom": "Санузел · 6.29 м²", "corridor": "Коридор + тамбур · 6.32 м²", "danina": "Данина (детская) · 14.34 м²", "laundry": "Прачечная · 1.30 м²", } def _rooms_css(): return """ body{font-family:system-ui,sans-serif;background:#0f1317;color:#dce4ec;margin:0;padding:26px} h1{font-size:24px;margin:0 0 4px} p.sub{color:#7d8fa3;margin:0 0 20px;font-size:14px} .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:18px} a.card{display:block;background:#151b21;border:1px solid #1f2830;border-radius:12px; overflow:hidden;text-decoration:none;color:#dce4ec;transition:.15s} a.card:hover{border-color:#6ab0f3;transform:translateY(-2px)} a.card img{display:block;width:100%;height:auto} a.card span{display:block;padding:10px 14px;font-size:14px;color:#9fb3c8} @media(max-width:760px){body{padding:14px 12px} .grid{grid-template-columns:1fr;gap:12px}h1{font-size:20px}} """ HOTSPOTS = "/root/buryan-infra/ops/home/renders/hotspots.json" ROOM_META = { "kitchen-living": ("Кухня-гостиная", "27.65", "2 трека · бра · подсветка рабочей зоны и стеллажа"), "bedroom": ("Спальня", "11.45", "трек · 2 бра · гардеробная 2.99"), "office": ("Кабинет", "11.14", "трек · 2 бра · подсветка"), "danina": ("Данина (детская)", "14.34", "трек по балке · свет антресоли"), "bathroom": ("Санузел", "6.29", "LED-профиль"), "corridor": ("Коридор + тамбур", "6.83", "трек · бра · прихожая · тамбур"), "laundry": ("Прачечная / кладовая", "1.30", "общий свет"), "hall-way": ("Прихожая", "3.36", "свет прихожей"), } HA_TOKEN_FILE = "/root/.ha-token" HA_URL = "http://192.168.1.106:8123" ROOM_HOTSPOTS = "/root/buryan-infra/ops/home/renders/room-hotspots.json" ROOM_RENDER_HOST = "/root/buryan-infra/ops/home/renders/web" def _ha_call(entity, action): """action: toggle|turn_on|turn_off""" import urllib.request as _r try: tok = open(HA_TOKEN_FILE).read().strip() except Exception: return {"ok": False, "error": "нет токена HA"} dom = entity.split(".")[0] body = _json.dumps({"entity_id": entity}).encode() url = "%s/api/services/%s/%s" % (HA_URL, dom, action) req = _r.Request(url, data=body, headers={ "Authorization": "Bearer " + tok, "Content-Type": "application/json"}, method="POST") try: with _r.urlopen(req, timeout=15) as r: r.read() return {"ok": True} except Exception as e: return {"ok": False, "error": str(e)[:120]} def _ha_state(entity): import urllib.request as _r try: tok = open(HA_TOKEN_FILE).read().strip() req = _r.Request("%s/api/states/%s" % (HA_URL, entity), headers={"Authorization": "Bearer " + tok}) with _r.urlopen(req, timeout=10) as r: d = _json.loads(r.read()) return {"entity": entity, "state": d.get("state"), "name": (d.get("attributes") or {}).get("friendly_name")} except Exception as e: return {"entity": entity, "state": "?", "error": str(e)[:80]} def _room_ctl_css(): return """ *{box-sizing:border-box} body{font-family:system-ui,sans-serif;background:#0f1317;color:#dce4ec;margin:0;padding:20px} h1{font-size:22px;margin:0 0 4px} p.sub{color:#7d8fa3;margin:0 0 14px;font-size:13.5px} .stage{position:relative;max-width:960px;margin:0 auto;background:#12181e; border:1px solid #1f2830;border-radius:14px;overflow:hidden} .stage img{display:block;width:100%;height:auto} .hot{position:absolute;border:2px solid rgba(106,176,243,.55);border-radius:10px; background:rgba(106,176,243,.12);cursor:pointer;transition:.15s;display:flex; align-items:center;justify-content:center;font-size:12px;color:#cfe4f7;font-weight:600; text-shadow:0 1px 4px #000} .hot:hover{background:rgba(106,176,243,.34);border-color:#6ab0f3;box-shadow:0 0 20px rgba(106,176,243,.6)} .hot.on{border-color:#5ec26a;background:rgba(94,194,106,.22)} .hot.off{border-color:#7d8fa3;background:rgba(125,143,163,.12)} .hot.na{border-color:#e0b341;background:rgba(224,179,65,.12);cursor:help} .panel{max-width:960px;margin:16px auto 0;display:flex;gap:10px;flex-wrap:wrap;font-size:13px} .panel span{background:#151b21;border:1px solid #1f2830;border-radius:8px;padding:6px 10px;color:#9fb3c8} @media(max-width:760px){body{padding:12px}.hot{font-size:10px}} """ def _room_ctl_page(key): import os as _os try: spec = _json.load(open(ROOM_HOTSPOTS, encoding="utf-8")) except Exception: spec = {} room = (spec.get("rooms") or {}).get(key) or {} name = room.get("name", key) img = room.get("image", key + ".jpg") spots = room.get("spots") or [] parts = [] for sp in spots: cls = "na" if sp.get("na") else "hot" label = sp.get("label", "") parts.append( '
    %s
    ' % (cls, sp.get("entity", ""), sp.get("x", 0), sp.get("y", 0), sp.get("w", 10), sp.get("h", 10), label)) return ('' '' '' + name + ' — управление' '

    ' + name + '

    ' '

    Нажмите на объект, чтобы включить/выключить · ' 'все комнаты

    ' '
    ' + name + '' + "".join(parts) + '
    ' '
    ' '') def _home_css(): return """ *{box-sizing:border-box} body{font-family:system-ui,sans-serif;background:#0f1317;color:#dce4ec;margin:0;padding:24px} h1{font-size:24px;margin:0 0 4px} p.sub{color:#7d8fa3;margin:0 0 18px;font-size:14px} .plan{position:relative;background:#12181e;border:1px solid #1f2830;border-radius:12px; overflow:hidden;margin-bottom:22px} .plan img{display:block;width:100%;height:auto;opacity:.92} .hot{position:absolute;transform:translate(-50%,-50%);width:11%;padding-top:7%; border:2px solid rgba(106,176,243,.45);border-radius:10px; background:rgba(106,176,243,.10);transition:.15s;text-decoration:none} .hot:hover{border-color:#6ab0f3;background:rgba(106,176,243,.28);box-shadow:0 0 22px rgba(106,176,243,.5)} .hot span{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%); font-size:11px;color:#cfe4f7;white-space:nowrap;font-weight:600;text-shadow:0 1px 4px #000} .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:16px} a.card{display:block;background:#151b21;border:1px solid #1f2830;border-radius:12px; overflow:hidden;text-decoration:none;color:#dce4ec;transition:.15s} a.card:hover{border-color:#6ab0f3;transform:translateY(-2px)} a.card img{display:block;width:100%;height:auto} a.card div{padding:10px 14px} a.card b{display:block;font-size:15px;margin-bottom:2px} a.card small{color:#8ba0b5;font-size:12.5px} @media(max-width:760px){body{padding:12px}.hot{width:16%;padding-top:10%} .hot span{font-size:9px}.grid{grid-template-columns:1fr}} """ def _home_page(): import os as _os try: import json as _j spec = _j.load(open(HOTSPOTS, encoding="utf-8")) except Exception: spec = {"image": "plan-house.png", "rooms": {}} rooms = spec.get("rooms") or {} hots = [] for key, pos in rooms.items(): title = ROOM_META.get(key, (key, "?", ""))[0] short = title.split(" ")[0] hots.append('' + short + '') cards = [] for key in rooms: name, area, light = ROOM_META.get(key, (key, "?", "")) img = "/rooms_img/" + key + ".jpg" p = _os.path.join("/root/buryan-infra/ops/home/renders/web", key + ".jpg") if not _os.path.exists(p): img = "/plan_img/" + spec.get("image", "plan-house.png") cards.append('' '' + name + '' '
    ' + name + '' + area + ' м² · ' + light + '
    ') return ('' '' 'Дом — Buryans Hub' '

    Дом

    ' '

    План первого этажа · нажмите комнату · ' 'все рендеры · ' 'дашборд

    ' '
    план' + "".join(hots) + '
    ' '
    ' + "".join(cards) + '
    ') def _rooms_page(): import os as _os files = [] try: files = sorted(f for f in _os.listdir(ROOM_RENDER_DIR) if f.endswith((".jpg", ".png"))) except Exception: pass cards = [] for f in files: key = f.rsplit(".", 1)[0] title = ROOM_TITLES.get(key, key) cards.append('' '' + title + '' '' + title + '') if not cards: cards.append('

    Рендеры не найдены

    ') return ('' '' 'Комнаты — Buryans Hub' '' '

    Комнаты

    ' '

    Изометрические рендеры по данным дома Барнева · ' 'дашборд · ' 'моё

    ' '
    ' + "".join(cards) + '
    ') def _dash_llm(): """Прогресс LLM-сбора.""" import glob as _g import re as _re done = total = facts = 0 maxpos = 0 for f in _g.glob("/opt/work-hub/research/worker-*.log"): try: last = None for line in open(f, encoding="utf-8", errors="ignore"): m = _re.search(r"\[(\d+)/(\d+)\]", line) if m: last = (int(m.group(1)), int(m.group(2))) if last: done += last[0] total = max(total, last[1]) maxpos = max(maxpos, last[0]) except Exception: continue try: for f in _g.glob("/opt/work-hub/research/results-*.jsonl"): for line in open(f, encoding="utf-8", errors="ignore"): line = line.strip() if not line: continue try: row = _json.loads(line) except Exception: continue rec = (row.get("data") or [{}])[0] if row.get("data") else {} facts += len(rec.get("facts") or []) except Exception: pass return {"done": done, "of": total or 1, "facts": facts, "maxpos": maxpos} def _dash_projects(): try: import urllib.request as _r with _r.urlopen("http://127.0.0.1:8103/list", timeout=8) as r: d = _json.loads(r.read() or b"{}") return (d.get("projects") or [])[:5] except Exception: return [] def _dash_cameras(): try: import urllib.request as _r with _r.urlopen("http://192.168.1.126:5000/api/stats", timeout=8) as r: d = _json.loads(r.read() or b"{}") cams = d.get("cameras") or {} online = sum(1 for c in cams.values() if c.get("camera_fps", 0) > 0) return {"total": len(cams), "online": online} except Exception: return None def _dash_backup(): import glob as _g import os as _o import time as _t dirs = sorted(_g.glob("/mnt/backups/services/*"), reverse=True) if not dirs: return None age = round((_t.time() - _o.path.getmtime(dirs[0])) / 3600, 1) return {"dir": _o.path.basename(dirs[0]), "age_h": age} def _dash_page(): d = _me_data() llm = _dash_llm() projs = _dash_projects() cams = _dash_cameras() bk = _dash_backup() w = d.get("weather") or {} weather = ("🌤 " + str(w.get("state", "")) + (", %s°" % w["temp"] if w.get("temp") is not None else "") if w else "погода недоступна") def sec(title, rows, empty="—"): body = "".join("
  • %s
  • " % r for r in rows) if rows else "
  • %s
  • " % empty return "

    %s

    " % (title, body) resume = ["%s — с %s мин" % (x["title"], x["min"]) for x in d["resume"]] pct = round(min(100.0, 100.0 * llm.get("maxpos", llm["done"]) / max(llm["of"], 1)), 1) html = f""" Дашборд — Buryans Hub

    Дашборд

    {weather} · обновлено сейчас

    {sec("▶️ Продолжить", resume, "ничего не начато")}
    {sec("🛒 Купить", d["shopping"], "список пуст")}
    {sec("🧾 Документы", d["docs"], "нет документов")}
    {sec("📐 Проекты ВКС", ["%s — %s комн., %s ед." % (pj.get("name"), pj.get("rooms", 0), pj.get("units", 0)) for pj in projs], "нет проектов")}

    🎥 Камеры

    {cams["online"] if cams else "—"}/{cams["total"] if cams else "—"}

    Frigate

    🤖 LLM-сбор

    {pct}%

    {llm["facts"]} фактов извлечено

    💾 Бэкап

    {(bk or {}).get('age_h', '—')} ч

    {(bk or {}).get('dir', 'нет данных')}

    {sec("📚 Книги", ["в библиотеке: %s" % d["books"]], "—")}

    Моё · Статус · Поиск · Медиа · Gitea · Документы

    """ return html def _me_page(): d = _me_data() def block(title, items, empty): rows = "".join(f"
  • {i}
  • " for i in items) if items else f"
  • {empty}
  • " return f"

    {title}

    " resume = [f"{x['title']} — с {x['min']} мин" for x in d["resume"]] w = d.get("weather") or {} weather = ("🌤 " + str(w.get("state", "")) + (f", {w['temp']}°" if w.get("temp") is not None else "") if w else "погода недоступна") html = f""" Моё — Buryans Hub

    Моё

    {weather}

    {block("▶️ Продолжить просмотр", resume, "пока ничего не начато")} {block("🛒 Купить", d["shopping"], "список пуст")}
    {block("✅ Задачи", [f"{t['title']} — {t['date']}" for t in d.get("tasks", [])], "задач нет")} {block("🧾 Документы", d["docs"], "нет документов")} {_me_extra_blocks(d)}

    Медиа · Продукты · Задачи · Документы · Поиск · Книги · Мониторинг · Логи · Графики · Аудио · Инвентарь · Контакты · Заметки

    """ return html # ---------- Маршрутизатор уведомлений ---------- NOTIFY_STATE = "/var/lib/hub-notify" NOTIFY_LOG = NOTIFY_STATE + "/log.jsonl" NOTIFY_QUEUE = NOTIFY_STATE + "/queue.json" QUIET_START, QUIET_END = 23, 8 DAILY_LIMIT = 3 def _notify_load_queue(): import json as _j try: return _j.load(open(NOTIFY_QUEUE, encoding="utf-8")) except Exception: return [] def _notify_save_queue(q): import json as _j import os as _os _os.makedirs(NOTIFY_STATE, exist_ok=True) _j.dump(q, open(NOTIFY_QUEUE, "w", encoding="utf-8"), ensure_ascii=False, indent=1) def _notify_today_count(): import datetime as _dt import json as _j today = _dt.date.today().isoformat() n = 0 try: for line in open(NOTIFY_LOG, encoding="utf-8"): try: rec = _j.loads(line) except Exception: continue if rec.get("ts", "").startswith(today) and rec.get("action") == "sent": n += 1 except Exception: pass return n def _notify_dupe(title, message): import json as _j import time as _t try: lines = open(NOTIFY_LOG, encoding="utf-8").read().splitlines()[-40:] except Exception: return False for line in lines: try: rec = _j.loads(line) except Exception: continue if rec.get("title") == title and rec.get("message") == message: if _t.time() - rec.get("epoch", 0) < 600: return True return False def _notify_log(rec): import json as _j import os as _os import time as _t _os.makedirs(NOTIFY_STATE, exist_ok=True) rec["ts"] = _t.strftime("%Y-%m-%dT%H:%M:%S") rec["epoch"] = _t.time() with open(NOTIFY_LOG, "a", encoding="utf-8") as f: f.write(_j.dumps(rec, ensure_ascii=False) + "\n") def _notify_policy(payload): import datetime as _dt title = (payload.get("title") or "").strip() message = (payload.get("message") or "").strip() priority = (payload.get("priority") or "normal").lower() if not message: return {"ok": False, "error": "empty"} if _notify_dupe(title, message): _notify_log({"action": "dupe", "title": title, "message": message}) return {"ok": True, "action": "dupe"} hour = _dt.datetime.now().hour quiet = hour >= QUIET_START or hour < QUIET_END # Решение владельца 15.11.2026: в Matrix — ТОЛЬКО критическое. # normal/low уходят в журнал и очередь для дайджеста, в чат не идут. if priority not in ("high", "critical"): q = _notify_load_queue() q.append({"title": title, "message": message, "priority": priority, "why": "not-critical"}) _notify_save_queue(q[-100:]) _notify_log({"action": "queued", "title": title, "message": message, "priority": priority, "why": "not-critical"}) return {"ok": True, "action": "queued", "reason": "not-critical"} text = message if not title else f"**{title}**\n\n{message}" # ── LLM-триаж (Фаза 1, 16.11.2026) ── # Критический алерт дополняется вердиктом модели: что это, насколько # срочно, что делать. Модель не решает, отправлять ли — только дополняет. # Если модель недоступна/не уверена — уходит исходный текст. if os.environ.get("TRIAGE_ENABLED", "1") == "1": try: import alert_triage as _tri _verdict = _tri.triage(title, message) if _verdict: text = _tri.merge(text, _verdict) _notify_log({"action": "triage", "title": title, "model": _verdict.get("model"), "confidence": _verdict.get("confidence")}) except Exception as _e: _notify_log({"action": "triage_skip", "title": title, "error": str(_e)[:120]}) sent = _matrix_notify(text) _notify_log({"action": "sent" if sent else "failed", "title": title, "message": message, "priority": priority}) # ── LLM-RCA (Фаза 2, 16.11.2026) ── # Алерт уже ушёл; разбор считаем в фоне и присылаем вторым сообщением, # чтобы не задерживать тревогу на минуту. if sent and priority in ("high", "critical") and \ os.environ.get("RCA_ENABLED", "1") == "1": def _rca_followup(_t=title, _m=message): try: import incident_rca as _rca _r = _rca.rca(_t, _m) if not _r: return _aid = _rca.make_approval(_r, _t) _txt = _rca.format_rca(_r, _aid) if _txt: _matrix_notify(_txt) _notify_log({"action": "rca", "title": _t, "model": _r.get("model"), "approval": _aid}) except Exception as _e: _notify_log({"action": "rca_skip", "title": _t, "error": str(_e)[:120]}) import threading as _th _th.Thread(target=_rca_followup, daemon=True).start() return {"ok": sent, "action": "sent" if sent else "failed"} def _alert_from_am(payload): """Разбирает вебхук Alertmanager и отправляет через маршрутизатор.""" alerts = payload.get("alerts") or [] if not alerts: return {"ok": False, "error": "no alerts"} lines = [] worst = "normal" for a in alerts[:10]: labels = a.get("labels") or {} name = labels.get("alertname") or "алерт" status = a.get("status") summary = (a.get("annotations") or {}).get("summary") or "" icon = "🔥" if status == "firing" else "✅" lines.append(f"{icon} {name}: {summary}"[:180]) sev = (labels.get("severity") or "").lower() if sev in ("critical", "page"): worst = "critical" elif sev == "warning" and worst != "critical": worst = "high" res = _notify_policy({ "title": "Prometheus", "message": "\n".join(lines), "priority": worst, }) return res def _collect_status(): import time as _time from concurrent.futures import ThreadPoolExecutor if _time.time() - _STATUS_CACHE["ts"] < 60 and _STATUS_CACHE["data"]: return _STATUS_CACHE["data"] services = _parse_registry() states = _docker_states() def probe(s): ct = s.get("ct", 0) name = s.get("name") or "" up = states.get((ct, name)) if up is None: up = any(v for (c, n), v in states.items() if n == name) if up is None and not s.get("internal"): up = _tcp_ok(s["ip"], s["port"]) return dict(s, up=bool(up)) with ThreadPoolExecutor(max_workers=4) as ex: result = list(ex.map(probe, services)) groups = {} for s in result: g = s["group"] groups.setdefault(g, {"total": 0, "up": 0}) groups[g]["total"] += 1 groups[g]["up"] += 1 if s["up"] else 0 data = {"services": result, "groups": groups, "total": len(result), "up": sum(1 for x in result if x["up"])} _STATUS_CACHE["ts"] = _time.time() _STATUS_CACHE["data"] = data return data def _status_page(): data = _collect_status() rows = [] order = ["core", "automation", "observability", "home", "media", "knowledge", "support", "other"] for g in order: items = [s for s in data["services"] if s["group"] == g] if not items: continue up = sum(1 for x in items if x["up"]) rows.append(f"

    {g} {up}/{len(items)}

    ") rows.append("") for s in sorted(items, key=lambda x: x["name"] or ""): mark = ("работает" if s["up"] else "не отвечает") rows.append(f"" f"") rows.append("
    СервисАдресСостояние
    {s['name']}{s['ip']}:{s['port']}{mark}
    ") pct = round(100 * data["up"] / data["total"]) if data["total"] else 0 return f""" Статус Buryans Hub

    Статус сервисов

    обновляется каждую минуту
    {pct}% {data['up']} из {data['total']} отвечают
    {''.join(rows)} """ def _matrix_notify(text: str) -> bool: """Отправляет сообщение в Matrix-чат владельца (MEDIA-бот).""" import json as _json import time as _time import urllib.parse as _urlparse import urllib.request as _rq env = {} try: with open("/etc/hub-bots/bots.env", encoding="utf-8") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: k, v = line.split("=", 1) env[k] = v except Exception: return False # Алерты идут в ALERT-комнату через @bot_alert (единая точка), # MEDIA — запасной вариант. token = env.get("ALERT_TOKEN") or env.get("MEDIA_TOKEN") hs = env.get("HS", "https://matrix.buryans.ru").rstrip("/") room = None try: with open("/etc/hub-bots/dm.env", encoding="utf-8") as f: env2 = {} for line in f: if "=" in line: k2, v2 = line.strip().split("=", 1) env2[k2] = v2.strip() room = env2.get("ALERT") or env2.get("MEDIA") except Exception: pass if not (token and room): return False body = _json.dumps({"msgtype": "m.text", "body": text}).encode() # Публичный домен изнутри хоста упирается в DPI/hairpin (SSL-handshake # timeout), поэтому сначала пробуем локальный Synapse, затем публичный. # 16.11.2026: из-за этого уведомления молча терялись. hosts = [] local_hs = env.get("HS_LOCAL") or "http://192.168.1.155:8008" if local_hs: hosts.append(local_hs.rstrip("/")) if hs and hs not in hosts: hosts.append(hs) for base in hosts: txn = int(_time.time() * 1000) url = (base + "/_matrix/client/r0/rooms/" + _urlparse.quote(room, safe="") + "/send/m.room.message/" + str(txn)) req = _rq.Request(url, data=body, method="PUT", headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"}) try: _rq.urlopen(req, timeout=12).read() return True except Exception: continue return False def _speak_ha(text): """Озвучивает ответ на Яндекс-колонке через Home Assistant.""" station = "media_player.yandex_station_lg00000000000049282300004309d886" try: token = open("/root/.ha-token", encoding="utf-8").read().strip() except Exception: return False if not token or not text: return False try: payload = json.dumps({"entity_id": station, "message": str(text)[:500]}).encode() req = urllib.request.Request( "http://192.168.1.106:8123/api/services/tts/yandex_station_say", data=payload, method="POST", headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=20) as r: return r.status == 200 except Exception: return False class Handler(BaseHTTPRequestHandler): def log_message(self, *a): pass def _json(self, code, obj): body = json.dumps(obj, ensure_ascii=False, default=str).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 == "/" or self.path.startswith("/panel"): body = render_panel().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return if self.path.startswith("/data/"): import urllib.parse as up parts = self.path.split("?")[0].split("/data/") coll = parts[1] if len(parts) > 1 else "" qs = up.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} tag = (qs.get("tag") or [None])[0] limit = int((qs.get("limit") or ["100"])[0]) try: res, err = do_data_list(coll, limit, tag) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if not err else 500, res or {"error": err}) if self.path.startswith("/health"): # быстрый liveness-ответ (мониторинг): без опроса всех служб if not self.path.startswith("/health/full"): try: with db() as con, con.cursor() as cur: cur.execute("select count(*) from events") _n = cur.fetchone()[0] except Exception: _n = -1 try: _load = [float(x) for x in open("/proc/loadavg").read().split()[:3]] except Exception: _load = [] return self._json(200, {"ok": True, "events": _n, "load": _load}) try: with db() as con, con.cursor() as cur: cur.execute("select count(*) from events") n = cur.fetchone()[0] st = _collect_status() alerts = 0 try: import urllib.request as _ur with _ur.urlopen("http://192.168.1.134:9093/api/v2/alerts", timeout=4) as _r: import json as _j alerts = len(_j.loads(_r.read())) except Exception: alerts = -1 try: load = [float(x) for x in open("/proc/loadavg").read().split()[:3]] except Exception: load = [] import shutil as _sh du = _sh.disk_usage("/") bad = [x["name"] for x in st["services"] if not x.get("up")] return self._json(200, { "ok": st["up"] == st["total"] and alerts == 0, "events": n, "services_up": st["up"], "services_total": st["total"], "services_down": bad[:10], "alerts": alerts, "load": load, "disk_root_pct": round(100 * du.used / du.total, 1), }) except Exception as e: return self._json(500, {"ok": False, "error": str(e)[:200]}) if self.path.startswith("/metrics"): try: body = do_metrics().encode("utf-8") except Exception as e: body = f"# error: {e}".encode() self.send_response(200) self.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return if self.path.startswith("/compare"): import urllib.parse as _uc qs = _uc.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} b = (qs.get("book") or [""])[0] f = (qs.get("film") or [""])[0] if not b or not f: return self._json(400, {"error": "нужны book и film"}) try: data = do_compare(b, f) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if data else 404, data or {"error": "не найдено"}) if self.path.startswith("/timeline"): import urllib.parse as _u1 qs = _u1.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} q = (qs.get("q") or [""])[0] k = (qs.get("kind") or ["тема"])[0] if not q: return self._json(400, {"error": "нужен q"}) try: data = do_timeline(q, k) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if data else 404, data or {"error": "не найдено"}) if self.path.startswith("/cross"): try: return self._json(200, do_cross()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/persons"): import urllib.parse as _u2 qs = _u2.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} k = (qs.get("kind") or ["актёр"])[0] try: return self._json(200, do_top_persons(k)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/yandex.html"): try: with open("/opt/hub-core/yandex.html", encoding="utf-8") as f: body = f.read().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/yandex/user-status"): import urllib.parse as _uy qs = _uy.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} user = yandex_user_by_key((qs.get("k") or [""])[0]) if not user: return self._json(403, {"error": "неверная ссылка"}) try: return self._json(200, yandex_user_status(user)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/yandex/users"): out = {} for u in YANDEX_USERS: try: out[u] = yandex_user_status(u) except Exception as e: out[u] = {"user": u, "error": str(e)[:60]} return self._json(200, {"users": out}) if self.path.startswith("/yandex/status"): try: return self._json(200, yandex_status()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/yandex/save"): length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"{}" try: data = json.loads(raw or b"{}") except Exception: return self._json(400, {"error": "плохой json"}) try: return self._json(200, yandex_save(data.get("token"))) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/voice.html"): try: with open("/opt/hub-core/voice.html", encoding="utf-8") as f: body = f.read().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/ask.html"): try: with open("/opt/hub-core/ask.html", encoding="utf-8") as f: body = f.read().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/rag"): import urllib.parse as _ur qs = _ur.parse_qs(_ur.urlparse(self.path).query) q = (qs.get("q") or [""])[0].strip() if not q: return self._json(400, {"error": "нужен q"}) try: import sys as _s2 if "/opt/hub-core" not in _s2.path: _s2.path.insert(0, "/opt/hub-core") import rag as _ragmod mode = (qs.get("mode") or ["find"])[0] if mode != "ask": return self._json(200, {"question": q, "found": _ragmod.find(q), "note": "для генерации добавьте &mode=ask " "(медленно на CPU)"}) ans, srcs = _ragmod.ask(q) return self._json(200, {"question": q, "answer": ans, "sources": srcs}) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/ask"): import urllib.parse as _ua qs = _ua.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} q = (qs.get("q") or [""])[0] if not q: return self._json(400, {"error": "нужен q"}) try: import sys as _sys if "/opt/hub-bots" not in _sys.path: _sys.path.insert(0, "/opt/hub-bots") from hub import agent as _agent answer, plan = _agent.run(q) spoke = False if (qs.get("speak") or [""])[0] in ("1", "true", "yes"): short = (qs.get("short") or [""])[0] in ("1", "true", "yes") text = answer if short: lines = [x.strip(" •-\t") for x in str(answer).splitlines() if x.strip()] text = ". ".join(lines[:4])[:400] spoke = _speak_ha(text) return self._json(200, {"answer": answer, "plan": _agent.describe(plan), "spoken": spoke}) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/intent"): import urllib.parse as _ui qs = _ui.parse_qs(_ui.urlparse(self.path).query) q = (qs.get("q") or [""])[0].strip() if not q: return self._json(400, {"error": "нужен q"}) try: import sys as _si if "/opt/hub-core" not in _si.path: _si.path.insert(0, "/opt/hub-core") import intents as _int answer, plan = _int.execute(q) return self._json(200, {"query": q, "answer": answer, "plan": plan}) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/aliases"): import urllib.parse as _ua qs = _ua.parse_qs(_ua.urlparse(self.path).query) try: import sys as _sa if "/opt/hub-core" not in _sa.path: _sa.path.insert(0, "/opt/hub-core") import media_catalog as _ma if self.command == "POST": length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") res = _ma.add_alias(payload.get("latin"), payload.get("russian")) return self._json(200, res) latin = (qs.get("latin") or [""])[0] russian = (qs.get("russian") or [""])[0] if latin and russian: return self._json(200, _ma.add_alias(latin, russian)) import json as _ja d = _ja.load(open("/opt/hub-core/data/title_aliases.json", encoding="utf-8")) return self._json(200, {"count": len(d), "aliases": d}) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/catalog"): import urllib.parse as _uc qs = _uc.parse_qs(_uc.urlparse(self.path).query) try: import sys as _sc if "/opt/hub-core" not in _sc.path: _sc.path.insert(0, "/opt/hub-core") import media_catalog as _mc if self.path.startswith("/catalog/stats"): d = _mc.load() return self._json(200, {"total": d.get("total"), "stats": d.get("stats"), "by_state": d.get("by_state"), "ts": d.get("ts")}) if self.path.startswith("/catalog/rebuild"): d = _mc.build() return self._json(200, {"total": d.get("total"), "stats": d.get("stats"), "by_state": d.get("by_state")}) q = (qs.get("q") or [""])[0] kind = (qs.get("kind") or [None])[0] state = (qs.get("state") or [None])[0] try: lim = int((qs.get("limit") or ["20"])[0]) except ValueError: lim = 20 items = _mc.search(q, kind=kind, limit=lim, state=state) return self._json(200, {"query": q, "count": len(items), "items": items}) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/yandex/webhook"): # протокол Яндекс.Диалогов try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") except Exception: payload = {} request = (payload.get("request") or {}) command = (request.get("command") or request.get("original_utterance") or "").strip() session = payload.get("session") or {} user_id = (session.get("user") or {}).get("user_id") or "yandex" if not command: return self._json(200, { "version": payload.get("version", "1.0"), "session": session, "response": {"text": "Слушаю.", "tts": "Слушаю.", "end_session": False}}) answer = "" try: import sys as _sy if "/opt/hub-core" not in _sy.path: _sy.path.insert(0, "/opt/hub-core") import intents as _iy answer, plan = _iy.execute(command) if not answer or answer.startswith("Не понял"): answer = ("Не понял команду. Скажите: включи фильм Дюна, " "найди матрицу, что посмотреть, кто дома.") except Exception as e: answer = "Ошибка обработки: " + str(e)[:80] # логируем обращения к Алисе try: import datetime, os path = "/var/lib/hub-bots/yandex_skill.jsonl" os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "a", encoding="utf-8") as f: f.write(json.dumps({"at": datetime.datetime.now().isoformat(timespec="seconds"), "user": user_id, "command": command, "answer": answer[:200]}, ensure_ascii=False) + "\n") except Exception: pass return self._json(200, { "version": payload.get("version", "1.0"), "session": session, "response": {"text": answer[:900], "tts": answer[:900], "end_session": False}}) if self.path.startswith("/voice"): import urllib.parse as _uv qs = _uv.parse_qs(_uv.urlparse(self.path).query) q = (qs.get("q") or [""])[0].strip() if not q: return self._json(400, {"error": "нужен q"}) try: import sys as _sv if "/opt/hub-bots" not in _sv.path: _sv.path.insert(0, "/opt/hub-bots") import sys as _svr if "/opt/hub-core" not in _svr.path: _svr.path.insert(0, "/opt/hub-core") import voice_router as _vr text, short, intent = _vr.answer(q) spoke = False if (qs.get("speak") or [""])[0] in ("1", "true", "yes"): spoke = _speak_ha(short) return self._json(200, {"query": q, "text": text, "speak": short, "spoken": spoke, "plan": "намерение: " + intent}) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/notify"): from urllib.parse import parse_qs, urlparse as _up qs = parse_qs(_up(self.path).query) _raw = " ".join(str(x) for x in qs.values()) if ("[✅ Up]" in _raw or "✅ Up" in _raw) and \ (qs.get("title") or qs.get("name") or [""])[0] in ("", "Событие"): return self._json(200, {"ok": True, "skipped": "up-event"}) title = (qs.get("title") or qs.get("name") or ["Событие"])[0] msg = (qs.get("message") or qs.get("msg") or [""])[0] prio = (qs.get("priority") or ["normal"])[0] # Uptime Kuma шлёт monitor/heartbeat — разбираем и здесь if qs.get("monitor") or qs.get("heartbeat"): mon = (qs.get("monitor") or [""])[0] up = (qs.get("heartbeat") or ["1"])[0] title = "Монитор: %s" % (mon or "?") msg = (qs.get("msg") or [""])[0] or ("поднялся" if up == "1" else "упал") prio = "high" if up != "1" else "low" res = _notify_policy({"title": title, "message": msg, "priority": prio}) return self._json(200, res) if self.path.startswith("/alert"): try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") except Exception: return self._json(400, {"error": "bad json"}) return self._json(200, _alert_from_am(payload)) if self.path.startswith("/media/event"): try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") except Exception: return self._json(400, {"error": "bad json"}) return self._json(200, _media_event(payload)) if self.path.startswith("/dash_weather"): w = _me_weather() self._json(200, w if w else {"state": "—"}) return if self.path.startswith("/dash_llm"): llm = _dash_llm() self._json(200, {"percent": round(min(100.0, 100.0 * llm.get("maxpos", llm["done"]) / max(llm["of"], 1)), 1), "facts": llm["facts"], "done": llm["done"], "of": llm["of"]}) return if self.path.startswith("/ha/toggle"): import urllib.parse as _up q = _up.parse_qs(_up.urlparse(self.path).query) ent = (q.get("entity") or [""])[0] if not ent or "." not in ent: self._json(400, {"ok": False, "error": "bad entity"}) return self._json(200, _ha_call(ent, "toggle")) return if self.path.startswith("/ha/states"): import urllib.parse as _up q = _up.parse_qs(_up.urlparse(self.path).query) key = (q.get("room") or [""])[0] try: spec = _json.load(open(ROOM_HOTSPOTS, encoding="utf-8")) except Exception: spec = {} room = (spec.get("rooms") or {}).get(key) or {} ents = [s.get("entity") for s in (room.get("spots") or []) if s.get("entity")] self._json(200, {"entities": [_ha_state(e) for e in ents]}) return if self.path.startswith("/room/"): key = self.path.split("/room/")[1].split("?")[0] html = _room_ctl_page(key).encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(html))) self.end_headers() self.wfile.write(html) return if self.path.startswith("/plan_img/"): import os as _os fn = self.path.split("/plan_img/")[1].split("?")[0] if "/" in fn or ".." in fn: self._json(400, {"error": "bad name"}) return p = _os.path.join("/root/buryan-infra/ops/home/renders/web", fn) if not _os.path.exists(p): self._json(404, {"error": "not found"}) return data = open(p, "rb").read() ctype = "image/png" if fn.lower().endswith(".png") else "image/jpeg" self.send_response(200) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) return if self.path.startswith("/home"): html = _home_page().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(html))) self.end_headers() self.wfile.write(html) return if self.path.startswith("/rooms_img/"): import os as _os fn = self.path.split("/rooms_img/")[1].split("?")[0] if "/" in fn or ".." in fn: self._json(400, {"error": "bad name"}) return p = _os.path.join(ROOM_RENDER_DIR, fn) if not _os.path.exists(p): self._json(404, {"error": "not found"}) return data = open(p, "rb").read() ctype = "image/jpeg" if fn.lower().endswith((".jpg", ".jpeg")) else "image/png" self.send_response(200) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) return if self.path.startswith("/rooms"): html = _rooms_page().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(html))) self.end_headers() self.wfile.write(html) return if self.path.startswith("/dash"): html = _dash_page().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(html))) self.end_headers() self.wfile.write(html) return if self.path.startswith("/me"): html = _me_page().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(html))) self.end_headers() self.wfile.write(html) return if self.path.startswith("/search"): import urllib.parse as _up qs = _up.parse_qs(_up.urlparse(self.path).query) q = (qs.get("q") or [""])[0] src = (qs.get("source") or [None])[0] try: lim = int((qs.get("limit") or ["6"])[0]) except ValueError: lim = 6 return self._json(200, _hub_search(q, limit=lim, only_source=src)) if self.path.startswith("/status"): if self.path.startswith("/status.json"): data = _collect_status() return self._json(200, data) html = _status_page().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(html))) self.end_headers() self.wfile.write(html) return if self.path.startswith("/devices.html"): try: with open("/opt/hub-core/devices.html", encoding="utf-8") as f: body = f.read().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/graph.html"): try: with open("/opt/hub-core/graph.html", encoding="utf-8") as f: body = f.read().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/graph"): try: if "json" in self.path: return self._json(200, do_graph_json()) return self._json(200, do_graph_stats()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/person.html"): try: with open("/opt/hub-core/person.html", encoding="utf-8") as f: body = f.read().encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/coworkers"): import urllib.parse as _ucw qs = _ucw.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} q = (qs.get("q") or [""])[0] if not q: return self._json(400, {"error": "нужен q"}) try: data = do_coworkers(q) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if data else 404, data or {"error": "не найдено"}) if self.path.startswith("/history"): import urllib.parse as _uh qs = _uh.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} try: days = int((qs.get("days") or ["30"])[0]) except ValueError: days = 30 try: return self._json(200, do_history(days)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/snapshot"): try: return self._json(200, snapshot_graph()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/for-me"): import urllib.parse as _ufm qs = _ufm.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} try: lim = int((qs.get("limit") or ["10"])[0]) except ValueError: lim = 10 try: return self._json(200, do_for_me(lim)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/watchlist"): import urllib.parse as _uw qs = _uw.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} mark = (qs.get("mark") or [None])[0] if mark: try: data = do_watchlist(mark=mark) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if data else 404, data or {"error": "не найдено"}) try: return self._json(200, do_watchlist()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path == "/rate" or self.path.startswith("/rate?"): import urllib.parse as _ur qs = _ur.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} t = (qs.get("title") or [""])[0] sc = (qs.get("score") or ["0"])[0] if not t: return self._json(400, {"error": "нужен title"}) try: data = do_rate(t, sc) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if data else 404, data or {"error": "не найдено"}) if self.path.startswith("/rated"): try: return self._json(200, do_rated()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/seasons"): import urllib.parse as _use qs = _use.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} q = (qs.get("q") or [""])[0] if not q: return self._json(400, {"error": "нужен q"}) try: data = do_seasons(q) except Exception as e: return self._json(500, {"error": str(e)[:200]}) return self._json(200 if data else 404, data or {"error": "не найдено"}) if self.path.startswith("/suggest"): import urllib.parse as _usg qs = _usg.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} q = (qs.get("q") or [""])[0] try: lim = int((qs.get("limit") or ["8"])[0]) except ValueError: lim = 8 try: return self._json(200, do_suggest(q, lim)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/candidates"): import urllib.parse as _ucd qs = _ucd.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} try: lim = int((qs.get("limit") or ["20"])[0]) except ValueError: lim = 20 try: return self._json(200, do_candidates(lim)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/mood"): import urllib.parse as _um qs = _um.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} m = (qs.get("mood") or [""])[0] if not m: return self._json(400, {"error": "нужен mood"}) try: return self._json(200, do_mood(m)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/pick"): import urllib.parse as _upp qs = _upp.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} g = (qs.get("genre") or [None])[0] t = (qs.get("theme") or [None])[0] d = (qs.get("decade") or [None])[0] k = (qs.get("kind") or ["фильм"])[0] per = (qs.get("person") or [None])[0] rat = (qs.get("rating") or [None])[0] try: lim = int((qs.get("limit") or ["10"])[0]) except ValueError: lim = 10 try: return self._json(200, do_pick2(g, t, d, k, per, rat, lim)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/similar"): import urllib.parse as _up2 qs = _up2.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} try: eid = int((qs.get("id") or ["0"])[0]) except ValueError: eid = 0 if not eid: return self._json(400, {"error": "нужен id"}) try: data = do_similar(eid) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if not data: return self._json(404, {"error": "карточка не найдена"}) return self._json(200, data) if self.path == "/person" or self.path.startswith("/person?"): import urllib.parse as _up3 qs = _up3.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} q = (qs.get("q") or [""])[0] if not q: return self._json(400, {"error": "нужен q"}) try: data = do_person(q) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if not data: return self._json(404, {"error": "персона не найдена"}) return self._json(200, data) if self.path.startswith("/links"): try: return self._json(200, do_links()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path == "/services": try: return self._json(200, do_services()) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/service/"): src = self.path.split("/service/")[1].split("?")[0] if not src: return self._json(400, {"error": "нужно имя сервиса"}) try: return self._json(200, do_service_history(src)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/search"): import urllib.parse as up q = (up.parse_qs(self.path.split("?", 1)[1]).get("q") or [""])[0] if "?" in self.path else "" if not q: return self._json(400, {"error": "нужен параметр q"}) try: return self._json(200, do_search(q)) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/entity/"): try: eid = int(self.path.split("/entity/")[1].split("?")[0]) except ValueError: return self._json(400, {"error": "нужен числовой id"}) try: data = do_entity(eid) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if data is None: return self._json(404, {"error": "карточка не найдена"}) return self._json(200, data) if self.path.startswith("/entities"): import urllib.parse as _up qs = _up.parse_qs(self.path.split("?")[1]) if "?" in self.path else {} kind = (qs.get("kind") or [None])[0] q = (qs.get("q") or [None])[0] try: limit = int((qs.get("limit") or ["200"])[0]) except ValueError: limit = 200 try: return self._json(200, do_entities(kind, limit, q)) 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): if self.path.startswith("/yandex/webhook"): try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") except Exception: payload = {} try: import sys as _sy if "/opt/hub-core" not in _sy.path: _sy.path.insert(0, "/opt/hub-core") import yandex_skill as _ys return self._json(200, _ys.handle(payload)) except Exception as e: return self._json(200, {"version": "1.0", "session": {}, "response": {"text": "Ошибка: " + str(e)[:80], "tts": "Ошибка", "end_session": False}}) if self.path.startswith("/alert"): try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") except Exception: return self._json(400, {"error": "bad json"}) return self._json(200, _alert_from_am(payload)) if self.path.startswith("/media/event"): try: length = int(self.headers.get("Content-Length") or 0) payload = json.loads(self.rfile.read(length) or b"{}") except Exception: return self._json(400, {"error": "bad json"}) return self._json(200, _media_event(payload)) 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("/yandex/save"): try: key = data.get("key") or "" user = yandex_user_by_key(key) if user: return self._json(200, yandex_save_for(user, data.get("token"))) return self._json(200, yandex_save(data.get("token"))) except Exception as e: return self._json(500, {"error": str(e)[:200]}) if self.path.startswith("/yandex/save"): try: key = data.get("key") or "" user = yandex_user_by_key(key) if user: return self._json(200, yandex_save_for(user, data.get("token"))) return self._json(200, yandex_save(data.get("token"))) except Exception as e: return self._json(500, {"error": str(e)[:200]}) 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() prio = data.get("priority", "normal") # Uptime Kuma: {monitor: {name}, heartbeat: {status}, msg} if isinstance(data.get("monitor"), dict) or isinstance(data.get("heartbeat"), dict): mon = (data.get("monitor") or {}).get("name") or "?" st = (data.get("heartbeat") or {}).get("status") up = (st == 1) if st is not None else True title = "Монитор: %s" % mon msg = data.get("msg") or (mon + (" поднялся" if up else " упал")) prio = "high" if not up else "low" if "✅ Up" in msg and title.strip() in ("", "Событие"): return self._json(200, {"ok": True, "skipped": "up-event"}) res = _notify_policy({"title": title, "message": msg, "priority": prio}) return self._json(200, res) 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) if self.path.startswith("/data/"): coll = self.path.split("/data/")[1].split("?")[0] if not coll: return self._json(400, {"error": "нужна коллекция"}) res, err = do_data_put(coll, data) return self._json(201 if not err else 500, res or {"error": err}) if self.path.startswith("/export"): coll = data.get("collection") or "" if not coll: return self._json(400, {"error": "нужна collection"}) res, err = do_export(coll, data.get("format") or "json", data.get("filename")) return self._json(200 if not err else 500, res or {"error": err}) 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)) threading.Thread(target=auto_actions, args=(ev, typ), daemon=True).start() if typ in LOUD: threading.Thread(target=publish, args=(human_event(ev), typ), 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 aliases = " ".join(str(a) for a in (data.get("aliases") or []) if a) 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 = case when entities.status in ('хочу посмотреть', 'смотрю') and coalesce(excluded.status, '') in ('', 'в медиатеке', 'не в медиатеке') then entities.status else coalesce(excluded.status, entities.status) end, 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} {aliases}".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 (from_id, to_id, relation) 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 = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) print(f"hub-core слушает {PORT}", flush=True) srv.serve_forever() if __name__ == "__main__": main()