Files
buryan-infra/ops/media-alpha/media_alpha.py
T
architect 68c35b4897
lint / hygiene (push) Failing after 19s
lint / hygiene (pull_request) Failing after 22s
standard / check (pull_request) Successful in 9s
[ARCH] Media API: explicit requests/continue/releases/recommendations statuses
2026-11-26 23:45:37 +03:00

257 lines
12 KiB
Python

#!/usr/bin/env python3
"""Read-only Buryans Media Alpha: Jellyfin search + minimal UI."""
import html
import json
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"}
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 seerr(path):
keyfile = Path("/root/.seerr-key")
if not keyfile.exists():
return 503, {"ok": False, "error": "seerr_key_missing"}
req = urllib.request.Request(
"http://192.168.1.121:5055" + path,
headers={"X-Api-Key": keyfile.read_text().strip(), "Accept": "application/json"})
try:
with urllib.request.urlopen(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}
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/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 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 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()