Files
buryan-infra/ops/media-alpha/media_alpha.py
T
architect bb2c594cbf
lint / hygiene (pull_request) Failing after 34s
standard / check (pull_request) Successful in 15s
lint / hygiene (push) Failing after 43s
standard / check (push) Successful in 14s
[ARCH] Seerr session cache: requests stable 200
2026-11-27 10:10:15 +03:00

371 lines
17 KiB
Python

#!/usr/bin/env python3
"""Read-only Buryans Media Alpha: Jellyfin search + minimal UI."""
import html
import http.cookiejar
import json
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 = {"maloyakapg@gmail.com"}
_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 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", "not_verified"),
("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 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()
out["fitness"] = {"pass": 3, "total": 18}
return out
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 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/fitness":
self.out(200, fitness())
return
if u.path == "/v1/home/status":
self.out(200, home_status())
return
if u.path == "/v1/media/requests":
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]))
self.out(code, body)
return
if u.path in ("/v1/media/continue", "/v1/media/releases", "/v1/media/recommendations"):
self.out(501, {"ok": False, "error": "not_configured",
"endpoint": u.path})
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 == "/":
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 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>`).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>Режим</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>`).join('')}catch(e){}}
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});boot();
</script></body></html>"""
if __name__ == "__main__":
ThreadingHTTPServer((HOST, PORT), H).serve_forever()