"""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}
Проблемы
Графики
Медиа: граф контента
карточек {g_cards} · связей {g_links}{g_growth}
Фантастика по десятилетиям
{g_timeline}
Книги и экранизации
Устройства сети
{g_dev_summary}
полный список →
Личное
хочу посмотреть · мои оценки · для вас
Доступы по сервисам
аудит по понедельникам, команда !users у бота Инфраструктура
{identity_text}
Что есть в сервисах
Действия сверки и автоисправлений
| когда | что | цель | результат | статус |
{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""
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 + '
'
'Нажмите на объект, чтобы включить/выключить · '
'все комнаты
'
'
'
+ "".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 + '' + area + ' м² · ' + light + '
')
return (''
''
'Дом — Buryans Hub'
'Дом
'
'План первого этажа · нажмите комнату · '
'все рендеры · '
'дашборд
'
'
'
+ "".join(hots) + '
'
'' + "".join(cards) + '