diff --git a/ops/hub-core/core.py b/ops/hub-core/core.py index 002f5ed..8b213e3 100644 --- a/ops/hub-core/core.py +++ b/ops/hub-core/core.py @@ -8,12 +8,13 @@ Запуск: 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, HTTPServer +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import psycopg2 import psycopg2.extras @@ -113,6 +114,20 @@ def human_event(ev): + + +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()}%" @@ -122,6 +137,14 @@ def do_search(q, limit=20): 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} @@ -426,6 +449,798 @@ def do_links(limit=200): 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: @@ -465,6 +1280,42 @@ def render_panel(): 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 @@ -476,6 +1327,8 @@ def render_panel(): 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): @@ -486,6 +1339,64 @@ def render_panel(): f"
| связь | сколько |
|---|
{identity_text}
@@ -621,6 +1551,1323 @@ def auto_actions(ev, etype):
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"Нажмите на объект, чтобы включить/выключить · ' + 'все комнаты
' + '