Files
buryan-infra/ops/media-alpha/media_alpha.py
T
architect 7ef5b02698
lint / hygiene (push) Failing after 19s
lint / hygiene (pull_request) Failing after 22s
standard / check (pull_request) Successful in 7s
[STAGE4] Mission Control v0 + Matrix internal homeserver
2026-11-27 20:36:54 +03:00

757 lines
41 KiB
Python

#!/usr/bin/env python3
"""Read-only Buryans Media Alpha: Jellyfin search + minimal UI."""
import html
import http.cookiejar
import json
import socket
import time
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
JF = "http://192.168.1.103:8096"
KEY = Path("/root/.jellyfin-key").read_text().strip()
HOST, PORT = "127.0.0.1", 9180
ALLOWED = {"[email protected]"}
_SEERR_OP = None
_SEERR_TS = 0.0
def jf(path):
req = urllib.request.Request(JF + path, headers={
"Authorization": 'MediaBrowser Token="%s"' % KEY,
"Accept": "application/json",
})
with urllib.request.urlopen(req, timeout=10) as r:
return json.load(r)
def recent():
params = urllib.parse.urlencode({
"SortBy": "DateCreated", "SortOrder": "Descending",
"IncludeItemTypes": "Movie,Series", "Recursive": "true",
"Limit": "6", "Fields": "ProductionYear,Overview,ImageTags",
})
data = jf("/Items?" + params)
out = []
for item in data.get("Items") or []:
out.append({
"id": item.get("Id"), "name": item.get("Name"),
"year": item.get("ProductionYear"), "type": item.get("Type"),
"overview": (item.get("Overview") or "")[:200],
})
return out
def breakglass_auth():
lines = Path("/root/.jellyfin-breakglass").read_text().splitlines()
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
req = urllib.request.Request(
JF + "/Users/AuthenticateByName",
data=json.dumps({"Username": user, "Pw": pw}).encode(),
headers={"Content-Type": "application/json",
"Authorization": 'MediaBrowser Client="Alpha", Device="Host", DeviceId="alpha", Version="1.0"'},
method="POST")
with urllib.request.urlopen(req, timeout=10) as r:
d = json.load(r)
return d.get("AccessToken"), (d.get("User") or {}).get("Id")
def continue_items():
tok, uid = breakglass_auth()
if not tok or not uid:
return []
h = {"Authorization": 'MediaBrowser Token="%s"' % tok, "Accept": "application/json"}
req = urllib.request.Request(JF + "/Users/%s/Items/Resume?Limit=10&MediaTypes=Video" % uid, headers=h)
with urllib.request.urlopen(req, timeout=10) as r:
data = json.load(r)
return [{"id": x.get("Id"), "name": x.get("Name"), "type": x.get("Type")}
for x in (data.get("Items") or [])]
def prism_stats():
with urllib.request.urlopen("http://127.0.0.1:8095/api/prism/llm", timeout=6) as r:
return json.load(r)
def fitness():
items = [
("FIT-01", "media without LLM", "pass"),
("FIT-02", "media without Hub", "not_verified"),
("FIT-03", "duplicate event", "not_implemented"),
("FIT-04", "lost response", "not_implemented"),
("FIT-05", "outbox recovery", "not_implemented"),
("FIT-06", "projection rebuild", "not_implemented"),
("FIT-07", "entity unmerge", "not_implemented"),
("FIT-08", "ACL revocation from cache", "pass"),
("FIT-09", "lease expiry/fencing", "not_implemented"),
("FIT-10", "playback during AI load", "not_verified"),
("FIT-11", "backup restore", "pass"),
("FIT-12", "expired approval", "not_implemented"),
("FIT-13", "prompt injection", "not_verified"),
("FIT-14", "missing media mount", "not_verified"),
("FIT-15", "catalog staleness", "not_implemented"),
("FIT-16", "contract compatibility", "pass"),
("FIT-17", "private facets", "not_implemented"),
("FIT-18", "cancel/partial failure", "not_implemented"),
]
return {"ok": True, "total": len(items), "pass": sum(1 for x in items if x[2] == "pass"),
"items": [{"id": i, "name": n, "status": s} for i, n, s in items]}
def media_coverage():
qs = urllib.parse.urlencode({
"Recursive": "true", "IncludeItemTypes": "Movie,Series",
"Fields": "MediaStreams,MediaSources", "Limit": "200"})
data = jf("/Items?" + qs)
items = data.get("Items") or []
rus = {"ru", "rus", "russian", "русский"}
rows = []
for x in items:
if x.get("Type") in ("BoxSet", "Folder", "CollectionFolder"):
continue
streams = x.get("MediaStreams") or []
sources = x.get("MediaSources") or []
if x.get("Type") == "Series" and not sources:
try:
ep = jf("/Shows/%s/Episodes?Fields=MediaStreams,MediaSources&Limit=200"
% x.get("Id"))
eps = ep.get("Items") or []
streams = [s for e in eps for s in (e.get("MediaStreams") or [])]
sources = [s for e in eps for s in (e.get("MediaSources") or [])]
except Exception:
pass
audio = [s for s in streams if s.get("Type") == "Audio"]
subs = [s for s in streams if s.get("Type") == "Subtitle" or s.get("IsTextSubtitleStream")]
has_ru_audio = any((s.get("Language") or "").lower() in rus or
any(w in (s.get("DisplayTitle") or "").lower() for w in ("russian", "русск"))
for s in audio)
has_ru_subs = any((s.get("Language") or "").lower() in rus or
any(w in (s.get("DisplayTitle") or "").lower() for w in ("russian", "русск"))
for s in subs)
direct = bool(sources) and all(
bool(s.get("SupportsDirectPlay") or s.get("SupportsDirectStream")) for s in sources)
rows.append({"id": x.get("Id"), "name": x.get("Name"), "type": x.get("Type"),
"ru_audio": has_ru_audio, "ru_subs": has_ru_subs, "direct_play": direct})
return {"ok": True, "total": len(rows),
"ru_audio": sum(1 for x in rows if x["ru_audio"]),
"ru_subs": sum(1 for x in rows if x["ru_subs"]),
"direct_play": sum(1 for x in rows if x["direct_play"]),
"missing_ru_audio": sum(1 for x in rows if not x["ru_audio"]),
"items": rows}
def audit_status():
try:
import psycopg2
pw = Path("/root/.pg-superuser-pass").read_text().strip()
conn = psycopg2.connect(host="192.168.1.151", dbname="rag",
user="postgres", password=pw, connect_timeout=4)
cur = conn.cursor()
cur.execute("select status,count(*) from audit.sprint_items group by status")
out = {k: int(v) for k, v in cur.fetchall()}
cur.close()
conn.close()
return out
except Exception as e:
return {"error": str(e)[:80]}
def home_status():
out = {"ok": True, "alpha": "read-only", "links": {
"audit": "/", "prism": "http://192.168.1.10:9161/",
"jellyfin": "https://media.buryans.ru"}}
try:
jf("/System/Info/Public")
out["jellyfin"] = "ok"
except Exception:
out["jellyfin"] = "down"
try:
p = prism_stats()
out["prism"] = {k: p.get(k) for k in ("pending_tasks", "done_tasks", "error_tasks", "runs")}
except Exception:
out["prism"] = {"error": "unavailable"}
out["audit"] = audit_status()
fs = fitness()
out["fitness"] = {"pass": fs["pass"], "total": fs["total"]}
try:
c = media_coverage()
out["coverage"] = {"total": c["total"], "ru_audio": c["ru_audio"], "ru_subs": c["ru_subs"]}
except Exception:
out["coverage"] = {"error": "unavailable"}
return out
def http_ok(url, timeout=6):
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return r.status
except Exception:
return 0
def acceptance_status():
h = home_status()
audit_code = http_ok("http://127.0.0.1:9160/")
gitea_code = http_ok("http://192.168.1.140:3000/")
try:
media_n = len(recent())
except Exception:
media_n = 0
backups = []
for p in ("/mnt/archive/backups/prism", "/mnt/archive/backups/seerr"):
try:
backups += [x.name for x in Path(p).glob("*") if x.is_file()][-1:]
except Exception:
pass
items = [
{"name": "Jellyfin", "what": "фильмы и сериалы",
"url": "https://media.buryans.ru", "auto": h["jellyfin"] == "ok",
"detail": "SSO-вход и playback"},
{"name": "Buryans One Alpha", "what": "read-only вход",
"url": "/alpha/", "auto": True, "detail": f"новинки: {media_n}"},
{"name": "Audit 360", "what": "трекер и Gate",
"url": "http://192.168.1.10:9161/", "auto": audit_code == 200,
"detail": f"HTTP {audit_code}; done={(h.get('audit') or {}).get('done','—')}"},
{"name": "Prism", "what": "очередь LLM (не трогать)",
"url": "/alpha/owner", "auto": "error" not in (h.get("prism") or {}),
"detail": f"pending={(h.get('prism') or {}).get('pending_tasks','—')} errors={(h.get('prism') or {}).get('error_tasks','—')}"},
{"name": "RU-озвучка", "what": "русская дорожка/субтитры",
"url": "/alpha/", "auto": (h.get("coverage") or {}).get("ru_audio", 0) > 0,
"detail": "RU audio %s/%s · subs %s" % (
(h.get("coverage") or {}).get("ru_audio", "—"),
(h.get("coverage") or {}).get("total", "—"),
(h.get("coverage") or {}).get("ru_subs", "—"))},
{"name": "Gitea", "what": "код и PR",
"url": "http://192.168.1.140:3000/", "auto": gitea_code == 200,
"detail": f"HTTP {gitea_code}"},
{"name": "Бэкапы", "what": "свежие дампы",
"url": "http://192.168.1.10:9161/", "auto": bool(backups),
"detail": ", ".join(backups) if backups else "не найдены"},
]
return {"ok": all(x["auto"] for x in items), "items": items}
SERVICES_PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/services.yaml")
def service_health(svc):
endpoint = (svc.get("endpoint") or "").strip()
started = time.time()
try:
if endpoint.startswith("http"):
try:
with urllib.request.urlopen(endpoint, timeout=4) as r:
code = r.status
except urllib.error.HTTPError as e:
code = e.code
up = code < 400
return {"up": up, "code": code, "ms": int((time.time() - started) * 1000)}
if endpoint.startswith(("tcp://", "nats://")):
u = urllib.parse.urlsplit(endpoint)
host, port = u.hostname, u.port or 0
with socket.create_connection((host, port), timeout=3):
pass
return {"up": True, "code": None, "ms": int((time.time() - started) * 1000)}
return {"up": None, "code": None, "ms": None, "error": "no endpoint"}
except Exception as e:
return {"up": False, "code": None, "ms": int((time.time() - started) * 1000),
"error": str(e)[:120]}
def mission_services():
import yaml
data = yaml.safe_load(SERVICES_PATH.read_text())
rows = []
for s in data.get("services") or []:
h = service_health(s)
rows.append({
"id": s.get("id"), "tier": s.get("tier"), "owner": s.get("owner"),
"endpoint": s.get("endpoint"), "public": s.get("public"),
"health": s.get("health"), "up": h.get("up"), "code": h.get("code"),
"ms": h.get("ms"), "error": h.get("error"),
})
return {"ok": all(x["up"] is not False for x in rows),
"total": len(rows), "up": sum(1 for x in rows if x["up"] is True),
"down": sum(1 for x in rows if x["up"] is False), "items": rows}
def request_check(q):
qn = (q or "").strip().lower()
if not qn:
return {"ok": False, "error": "query_required"}
code, body = seerr("/api/v1/request?take=50")
if code != 200:
return {"ok": False, "error": "seerr_unavailable", "code": code}
for x in body.get("results") or []:
media = x.get("media") or {}
title = (media.get("title") or media.get("name") or "").lower()
if qn in title or title in qn:
return {"ok": True, "requested": True, "id": x.get("id"),
"title": media.get("title") or media.get("name"),
"status": x.get("status")}
return {"ok": True, "requested": False}
def seerr(path):
"""Read-only Seerr requests via the local breakglass Jellyfin login."""
global _SEERR_OP, _SEERR_TS
base = "http://192.168.1.121:5055"
if _SEERR_OP is not None and time.time() - _SEERR_TS < 1800:
try:
req = urllib.request.Request(base + path, headers={"Accept": "application/json"})
with _SEERR_OP.open(req, timeout=8) as r:
return 200, json.load(r)
except Exception:
_SEERR_OP = None
cred = Path("/root/.jellyfin-breakglass")
try:
lines = cred.read_text().splitlines()
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
ok = False
for attempt in range(3):
login = urllib.request.Request(
base + "/api/v1/auth/jellyfin",
data=json.dumps({"username": user, "password": pw}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
try:
with op.open(login, timeout=8) as r:
if r.status == 200:
ok = True
break
except urllib.error.HTTPError as e:
if e.code not in (401, 403):
raise
time.sleep(0.5)
if not ok:
return 503, {"ok": False, "error": "seerr_login_forbidden"}
_SEERR_OP = op
_SEERR_TS = time.time()
req = urllib.request.Request(base + path, headers={"Accept": "application/json"})
with op.open(req, timeout=8) as r:
return 200, json.load(r)
except urllib.error.HTTPError as e:
return (503 if e.code in (401, 403) else e.code), {
"ok": False, "error": "seerr_%s" % e.code}
except Exception as e:
return 503, {"ok": False, "error": "seerr_unavailable", "detail": str(e)[:120]}
def releases():
import datetime
key = Path("/root/.radarr-key").read_text().strip()
today = datetime.date.today()
end = today + datetime.timedelta(days=14)
url = ("http://192.168.1.118:7878/api/v3/calendar?start=%s&end=%s"
% (today.isoformat(), end.isoformat()))
req = urllib.request.Request(url, headers={"X-Api-Key": key, "Accept": "application/json"})
with urllib.request.urlopen(req, timeout=8) as r:
data = json.load(r)
return [{"title": x.get("title"), "date": x.get("physicalRelease") or x.get("digitalRelease"),
"type": "movie"} for x in data]
def recommendations():
seed = recent()
out = []
seen = set(x.get("id") for x in seed)
for s in seed[:3]:
qs = urllib.parse.urlencode({
"SimilarTo": s["id"], "Recursive": "true",
"IncludeItemTypes": "Movie,Series", "Limit": "6"})
data = jf("/Items?" + qs)
for x in data.get("Items") or []:
if x.get("Id") in seen:
continue
seen.add(x.get("Id"))
out.append({"id": x.get("Id"), "title": x.get("Name"),
"year": x.get("ProductionYear"), "type": x.get("Type")})
if not out:
out = [{"id": x["id"], "title": x["name"], "year": x["year"], "type": x["type"]}
for x in seed]
return 200, {"ok": True, "items": out[:12], "source": "jellyfin_similar"}
def item(i):
qs = urllib.parse.urlencode({"Ids": i, "Fields": "Overview,ProductionYear,MediaSources"})
data = jf("/Items?" + qs)
items = data.get("Items") or []
if not items:
raise RuntimeError("item not found")
data = items[0]
sources = data.get("MediaSources") or []
return {
"id": data.get("Id"), "name": data.get("Name"),
"year": data.get("ProductionYear"), "type": data.get("Type"),
"overview": data.get("Overview") or "",
"available": bool(sources),
"source_count": len(sources),
}
def editions(i):
qs = urllib.parse.urlencode({"Ids": i, "Fields": "MediaSources"})
data = jf("/Items?" + qs)
items = data.get("Items") or []
if not items:
raise RuntimeError("item not found")
src = items[0].get("MediaSources") or []
return [{"id": s.get("Id"), "name": s.get("Name"), "container": s.get("Container"),
"size": s.get("Size"), "bitrate": s.get("Bitrate")} for s in src]
def search(q):
if not q.strip():
return []
params = urllib.parse.urlencode({
"searchTerm": q, "IncludeItemTypes": "Movie,Series",
"Recursive": "true", "Limit": "24",
"Fields": "ProductionYear,Overview,ImageTags,RunTimeTicks",
})
data = jf("/Items?" + params)
out = []
for item in data.get("Items") or []:
out.append({
"id": item.get("Id"),
"name": item.get("Name"),
"year": item.get("ProductionYear"),
"type": item.get("Type"),
"overview": (item.get("Overview") or "")[:280],
"has_image": bool((item.get("ImageTags") or {}).get("Primary")),
})
return out
class H(BaseHTTPRequestHandler):
def out(self, code, body, ctype="application/json"):
if isinstance(body, (dict, list)):
body = json.dumps(body, ensure_ascii=False)
data = body.encode() if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", ctype + "; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def allowed(self):
user = (self.headers.get("X-Audit-User") or "").strip().lower()
gateway = self.headers.get("X-Audit-Gateway") == "1"
if not gateway and self.client_address[0] in ("127.0.0.1", "::1"):
return True
return user in ALLOWED
def do_POST(self):
if not self.allowed():
self.out(403, {"ok": False, "error": "forbidden"})
return
u = urllib.parse.urlparse(self.path)
if u.path != "/v1/media/playback/resolve":
self.out(404, {"ok": False, "error": "not found"})
return
try:
n = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(n).decode() or "{}")
iid = body.get("id")
if not iid:
self.out(400, {"ok": False, "error": "id required"})
return
it = item(iid)
self.out(200, {"ok": True, "provider": "jellyfin",
"url": "https://media.buryans.ru/web/index.html#!/details?id=" + urllib.parse.quote(iid),
"name": it["name"]})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
def do_GET(self):
if not self.allowed():
self.out(403, {"ok": False, "error": "forbidden"})
return
u = urllib.parse.urlparse(self.path)
if u.path == "/health":
try:
jf("/System/Info/Public")
self.out(200, {"ok": True, "jellyfin": True})
except Exception as e:
self.out(503, {"ok": False, "error": str(e)[:200]})
return
parts = [x for x in u.path.split("/") if x]
if len(parts) == 4 and parts[:3] == ["v1", "media", "works"]:
try:
it = item(parts[3])
if parts[3] and u.path.endswith("/availability"):
self.out(200, {"ok": True, "available": it["available"], "source_count": it["source_count"]})
else:
self.out(200, {"ok": True, "item": it})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if len(parts) == 5 and parts[:3] == ["v1", "media", "works"] and parts[4] == "availability":
try:
it = item(parts[3])
self.out(200, {"ok": True, "available": it["available"], "source_count": it["source_count"]})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if len(parts) == 5 and parts[:3] == ["v1", "media", "works"] and parts[4] == "editions":
try:
self.out(200, {"ok": True, "editions": editions(parts[3])})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/media/coverage":
try:
self.out(200, media_coverage())
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/fitness":
self.out(200, fitness())
return
if u.path == "/v1/home/status":
self.out(200, home_status())
return
if u.path == "/v1/media/request/check":
q = urllib.parse.parse_qs(u.query).get("q", [""])[0]
try:
self.out(200, request_check(q))
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/requests":
code, body = seerr("/api/v1/request?take=20")
if code == 503:
time.sleep(1)
code, body = seerr("/api/v1/request?take=20")
self.out(code, body)
return
if len(parts) == 4 and parts[:3] == ["v1", "media", "requests"]:
code, body = seerr("/api/v1/request/%s" % urllib.parse.quote(parts[3]))
if code == 503:
time.sleep(1)
code, body = seerr("/api/v1/request/%s" % urllib.parse.quote(parts[3]))
self.out(code, body)
return
if u.path == "/v1/media/continue":
try:
self.out(200, {"ok": True, "items": continue_items()})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/releases":
try:
self.out(200, {"ok": True, "items": releases()})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/recommendations":
try:
code, body = recommendations()
self.out(code, body)
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:200]})
return
if u.path == "/v1/media/recent":
try:
self.out(200, {"ok": True, "items": recent()})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/me":
self.out(200, {"ok": True, "email": self.headers.get("X-Audit-User") or "local", "read_only": True})
return
if u.path == "/v1/media/search":
q = urllib.parse.parse_qs(u.query).get("q", [""])[0]
try:
self.out(200, {"ok": True, "query": q, "items": search(q)})
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/v1/acceptance":
self.out(200, acceptance_status())
return
if u.path == "/acceptance":
self.out(200, PAGE_ACCEPTANCE, "text/html")
return
if u.path == "/v1/services":
try:
self.out(200, mission_services())
except Exception as e:
self.out(502, {"ok": False, "error": str(e)[:300]})
return
if u.path == "/mission":
self.out(200, PAGE_MISSION, "text/html")
return
if u.path == "/request":
self.out(200, PAGE_REQUEST, "text/html")
return
if u.path == "/owner":
self.out(200, PAGE_OWNER, "text/html")
return
if u.path == "/":
self.out(200, PAGE, "text/html")
return
self.out(404, {"ok": False, "error": "not found"})
def log_message(self, fmt, *args):
pass
PAGE = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Buryans One Alpha — read-only</title>
<style>
body{background:#0d1117;color:#e6edf3;font:15px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:24px;margin:0 0 4px}.mut{color:#8b949e}
input{width:min(600px,80%);padding:12px;border-radius:8px;border:1px solid #30363d;background:#161b22;color:#e6edf3;font-size:16px}
button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#fff;font-size:16px;cursor:pointer}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px;margin-top:18px}
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
.card h3{margin:0 0 4px;font-size:16px}.tag{color:#8b949e;font-size:12px}
a{color:#58a6ff}
</style></head><body>
<h1>Buryans One Alpha</h1><div class=mut id=me>read-only</div>
<div style="margin:8px 0"><a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/owner">Owner-пульт →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/acceptance">Опросник приёмки →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/request">Запросить фильм →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/mission">Mission Control →</a></div>
<div class=grid id=status style="margin:16px 0"></div>
<div class=grid style="margin:16px 0">
<a class=card href="https://media.buryans.ru" target=_blank><h3>Jellyfin</h3><div class=tag>фильмы и сериалы</div></a>
<a class=card href="https://requests.buryans.ru" target=_blank><h3>Seerr</h3><div class=tag>заявки</div></a>
<a class=card href="https://music.buryans.ru" target=_blank><h3>Navidrome</h3><div class=tag>музыка</div></a>
<a class=card href="https://element.buryans.ru" target=_blank><h3>Element</h3><div class=tag>Matrix</div></a>
<a class=card href="http://192.168.1.10:9161/" target=_blank><h3>Audit 360</h3><div class=tag>аудит</div></a>
<a class=card href="http://192.168.1.140:3000/" target=_blank><h3>Gitea</h3><div class=tag>код и решения</div></a>
</div>
<h2 style="font-size:18px;margin:24px 0 8px">Недавно добавлено</h2><div id=recent class=grid></div>
<div style="margin:18px 0"><input id=q placeholder="Фильм или сериал..." autofocus> <button onclick="go()">Найти</button></div>
<div id=msg class=mut></div><div id=out class=grid></div>
<div class=mut style="margin-top:18px">Alpha read-only. Запросы и изменения — только после Gate G1.</div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();if(!d.ok){document.getElementById('msg').textContent=d.error||'ошибка';return}document.getElementById('msg').textContent=d.items.length?'':'ничего не найдено';document.getElementById('out').innerHTML=d.items.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div><div style="margin-top:8px"><a href="https://media.buryans.ru/web/index.html#!/details?id=${e(x.id)}" target=_blank>Открыть в Jellyfin →</a></div></div>`).join('')}
async function boot(){try{const m=await (await fetch('v1/me')).json();document.getElementById('me').textContent='read-only · '+(m.email||'local')}catch(e){}
try{const s=await (await fetch('v1/home/status')).json();const p=s.prism||{};document.getElementById('status').innerHTML=`
<div class=card><h3>Jellyfin</h3><div class=tag>${s.jellyfin==='ok'?'работает':'недоступен'}</div></div>
<div class=card><h3>Prism</h3><div class=tag>pending ${p.pending_tasks??'—'} · running ${p.running_tasks??'—'} · errors ${p.error_tasks??'—'}</div></div>
<div class=card><h3>Audit 360</h3><div class=tag>done ${(s.audit||{}).done??'—'} · review ${(s.audit||{}).review_pending??'—'} · open ${(s.audit||{}).in_progress??'—'}</div><div class=tag><a href="http://192.168.1.10:9161/">открыть трекер</a></div></div>
<div class=card><h3>Fitness</h3><div class=tag>${(s.fitness||{}).pass??'—'}/${(s.fitness||{}).total??'—'} pass</div></div>
<div class=card><h3>RU-озвучка</h3><div class=tag>${(s.coverage||{}).ru_audio??'—'}/${(s.coverage||{}).total??'—'} · субтитры ${(s.coverage||{}).ru_subs??'—'}</div></div>
<div class=card><h3>Режим</h3><div class=tag>read-only · без записи</div></div>`}catch(e){}
try{const r=await (await fetch('v1/media/recent')).json();const xs=r.items||[];document.getElementById('recent').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div><div style="margin-top:8px"><a href="https://media.buryans.ru/web/index.html#!/details?id=${e(x.id)}" target=_blank>Открыть в Jellyfin →</a></div></div>`).join('')}catch(e){}}
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});boot();
</script></body></html>"""
PAGE_OWNER = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Buryans Owner-пульт</title>
<style>
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;margin:18px 0}
.big{display:block;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:18px;text-decoration:none;color:#e6edf3}
.big:hover{border-color:#2f81f7}.big h3{margin:0 0 6px;font-size:19px;color:#58a6ff}
.big .tag{color:#8b949e;font-size:13px}.status{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:12px;margin:12px 0}
a{color:#58a6ff}code{background:#161b22;padding:2px 5px;border-radius:4px}
</style></head><body>
<h1>Owner-пульт</h1><div class=mut>Крупные кнопки. Всё read-only, кроме Audit 360.</div>
<div id=status class=status>загрузка статуса…</div>
<div class=grid>
<a class=big href="https://media.buryans.ru" target=_blank><h3>Jellyfin</h3><div class=tag>фильмы, сериалы, playback. Вход через Authentik.</div></a>
<a class=big href="https://media.buryans.ru/sso/OID/start/authentik" target=_blank><h3>Войти в Jellyfin</h3><div class=tag>прямой SSO-вход, если кнопка не видна.</div></a>
<a class=big href="http://192.168.1.10:9161/" target=_blank><h3>Audit 360</h3><div class=tag>трекер, evidence, Gate G0/G1.</div></a>
<a class=big href="/alpha/acceptance"><h3>Опросник приёмки</h3><div class=tag>по каждому сервису: что нажать и что должно быть.</div></a>
<a class=big href="/alpha/request"><h3>Запросить фильм</h3><div class=tag>поиск по Jellyfin и кнопка запроса в Seerr.</div></a>
<a class=big href="/alpha/mission"><h3>Mission Control</h3><div class=tag>карта сервисов, health, owners, ссылки.</div></a>
<a class=big href="http://192.168.1.10:9161/alpha/"><h3>На главную Alpha</h3><div class=tag>поиск, новинки, сервисы.</div></a>
<a class=big href="/alpha/v1/fitness" target=_blank><h3>Fitness</h3><div class=tag>18 FIT-пунктов, честные статусы.</div></a>
<a class=big href="http://192.168.1.140:3000/" target=_blank><h3>Gitea</h3><div class=tag>код, PR, решения.</div></a>
</div>
<div class=status><b>Порядок:</b> 1) проверить Alpha; 2) Jellyfin; 3) Audit 360 → S0-10; 4) S1-10. Prism не трогать.</div>
<div class=mut>Если что-то не работает — не чинить, зафиксировать и передать.</div>
<script>
async function boot(){try{const s=await (await fetch('v1/home/status')).json();const p=s.prism||{},a=s.audit||{},f=s.fitness||{};document.getElementById('status').innerHTML=`
<b>Jellyfin:</b> ${s.jellyfin==='ok'?'работает':'недоступен'} ·
<b>Prism:</b> pending ${p.pending_tasks??'—'} / errors ${p.error_tasks??'—'} ·
<b>Audit:</b> done ${a.done??'—'} / review ${a.review_pending??'—'} ·
<b>Fitness:</b> ${f.pass??'—'}/${f.total??'—'}`}catch(e){document.getElementById('status').textContent='статус недоступен'}}
boot();
</script></body></html>"""
PAGE_ACCEPTANCE = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Приёмка сервисов — Buryans</title>
<style>
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;margin:18px 0}
.row{background:#161b22;border:1px solid #30363d;border-radius:12px;padding:16px}
.row h3{margin:0 0 4px;font-size:19px}.ok{color:#3fb950}.bad{color:#f85149}.tag{color:#8b949e;font-size:13px}
a{color:#58a6ff}.auto{font-size:13px;margin-top:8px}.big{font-size:17px;text-decoration:none}
</style></head><body>
<h1>Приёмка сервисов</h1><div class=mut>Один экран: что открыть, что должно быть, что показывает автоматическая проверка.</div>
<div class=grid id=rows>загрузка…</div>
<div class=row>
<h3>Что считается успехом</h3>
<div class=tag>Если авто-проверка зелёная и ты видишь ожидаемое — сервис принят. Один-два положительных теста уже достаточны для источника истины; повторять вручную всё не нужно.</div>
<h3 style="margin-top:14px">Порядок</h3>
<div class=tag>1) Jellyfin · 2) Alpha · 3) Audit 360 · 4) Gitea · 5) Prism только смотреть. Бэкапы проверяются автоматически.</div>
<h3 style="margin-top:14px">Если не работает</h3>
<div class=tag>Снять URL/код, не чинить. Написать: «сервис, что нажал, что ожидал, что увидел».</div>
</div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function boot(){try{const d=await (await fetch('v1/acceptance')).json();document.getElementById('rows').innerHTML=(d.items||[]).map(x=>`<div class=row><h3>${e(x.name)}</h3><div class=tag>${e(x.what)}</div><div class=auto>${x.auto?'<span class=ok>● авто-проверка: OK</span>':'<span class=bad>● авто-проверка: FAIL</span>'}</div><div class=tag>${e(x.detail||'')}</div><div style="margin-top:10px"><a class=big href="${e(x.url)}" target=_blank>Открыть →</a></div></div>`).join('')}catch(e){document.getElementById('rows').textContent='не удалось получить статус'}}
boot();
</script></body></html>"""
PAGE_REQUEST = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Запрос фильма — Buryans</title>
<style>
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
input{width:min(600px,80%);padding:12px;border-radius:8px;border:1px solid #30363d;background:#161b22;color:#e6edf3;font-size:16px}
button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#fff;font-size:16px;cursor:pointer}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;margin-top:18px}
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
.card h3{margin:0 0 4px;font-size:16px}.tag{color:#8b949e;font-size:13px}
a{color:#58a6ff}.warn{background:#161b22;border:1px solid #9e6a03;border-radius:10px;padding:12px;color:#d29922}
</style></head><body>
<h1>Запрос фильма</h1><div class=mut>Alpha только ищет. Запрос создаётся в Seerr, не в медиатеке.</div>
<div style="margin:16px 0"><input id=q placeholder="Название фильма или сериала..." autofocus> <button onclick="go()">Найти</button></div>
<div id=msg class=mut></div><div id=out class=grid></div>
<div class=warn style="margin-top:18px">Если запрос уже существует, Seerr покажет это сам. Дубли в Jellyfin не создаются.</div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();const xs=d.items||[];let warn='';try{const c=await (await fetch('v1/media/request/check?q='+encodeURIComponent(q))).json();if(c.requested)warn='⚠️ Похоже, заявка уже есть: '+e(c.title||q)+' (статус '+e(c.status)+').';}catch(e){}document.getElementById('msg').textContent=xs.length?'':'ничего не найдено';if(warn)document.getElementById('msg').textContent=warn;document.getElementById('out').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div style="margin-top:8px"><a href="https://requests.buryans.ru/search?query=${encodeURIComponent(x.name)}" target=_blank>Запросить в Seerr →</a></div></div>`).join('')}
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});
</script></body></html>"""
PAGE_MISSION = """<!doctype html><html lang=ru><head><meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<title>Mission Control — Buryans</title>
<style>
body{background:#0d1117;color:#e6edf3;font:15px/1.5 system-ui,Arial;margin:0;padding:28px}
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px;margin:18px 0}
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
.card h3{margin:0 0 4px;font-size:17px}.tag{color:#8b949e;font-size:13px}
.ok{color:#3fb950}.bad{color:#f85149}.unk{color:#d29922}
a{color:#58a6ff}
</style></head><body>
<h1>Mission Control</h1><div class=mut>Read-only карта сервисов. Health, tier, owner, endpoints. Без изменения сервисов.</div>
<div class=mut id=summary style="margin-top:10px">загрузка…</div>
<div class=grid id=rows></div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
async function boot(){try{const d=await (await fetch('v1/services')).json();document.getElementById('summary').textContent=`сервисов ${d.total} · up ${d.up} · down ${d.down}`;const xs=(d.items||[]).slice().sort((a,b)=>(a.tier-b.tier)||String(a.id).localeCompare(b.id));document.getElementById('rows').innerHTML=xs.map(x=>{const st=x.up===true?'<span class=ok>● up</span>':x.up===false?'<span class=bad>● down</span>':'<span class=unk>● unknown</span>';const url=x.public||x.endpoint||'';return `<div class=card><h3>${e(x.id)}</h3><div class=tag>tier ${e(x.tier)} · ${e(x.owner||'—')}</div><div style="margin-top:6px">${st} ${x.code?`HTTP ${e(x.code)}`:''} ${x.ms!=null?`· ${e(x.ms)}ms`:''}</div><div class=tag>${e(x.health||'')}</div>${url?`<div style="margin-top:8px"><a href="${e(url)}" target=_blank>${e(url)}</a></div>`:''}${x.error?`<div class=tag>${e(x.error)}</div>`:''}</div>`}).join('')}catch(e){document.getElementById('summary').textContent='не удалось получить карту сервисов'}}
boot();
</script></body></html>"""
if __name__ == "__main__":
ThreadingHTTPServer((HOST, PORT), H).serve_forever()