Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7b1a90e9c | ||
|
|
2fbe23476c | ||
|
|
8b78cd9a61 | ||
|
|
e6a29a5cda | ||
|
|
3636be5ddd | ||
|
|
2be898d584 | ||
|
|
304db34ac2 | ||
|
|
6ab94962ac | ||
|
|
8940671aa3 | ||
|
|
f57684399c | ||
|
|
64e3c95667 | ||
|
|
5ff027fc42 | ||
|
|
e6fc2cb3aa | ||
|
|
2f0017a663 | ||
|
|
46761c0142 | ||
|
|
a221d71971 |
No files matched your search
@@ -39,9 +39,14 @@
|
||||
| S2-02 | S2 | Outbox schema + enqueue | done | | architect | ops/events/schema.sql; enqueue | 0 | |
|
||||
| S2-03 | S2 | Inbox + effects idempotency | done | | architect | repeat_test 100→1 | 0 | |
|
||||
| S2-04 | S2 | NATS JetStream relay | done | | architect | enqueue1 relayed1 processed1; inbox/effects 1 | 1 | |
|
||||
| S2-05 | S2 | Adapters + ownership matrix | in_progress | | architect | ownership matrix 13 types | 1 | |
|
||||
| S2-06 | S2 | pgvector pilot | open | | architect | pending | 0 | |
|
||||
| S2-05 | S2 | Adapters + ownership matrix | done | | architect | pipeline active; jellyfin 7 events; ownership.yaml | 3 | |
|
||||
| S2-06 | S2 | pgvector pilot | done | | architect | nearest pilot-a, top2 pilot-a/pilot-c | 1 | |
|
||||
| S2-07 | S2 | Gate G2 proof | done | YES | architect | 100→1; loss recovered | 1 | G2 |
|
||||
| S3-01 | S3 | Аудит RU/direct-play | done | | architect | /v1/media/coverage | 0 | |
|
||||
| S3-02 | S3 | RU-дорожки/субтитры | blocked | | architect | 0/7 RU; und/eng only | 1 | |
|
||||
| S3-03 | S3 | Direct-play 7/7 | done | | architect | coverage total6 direct6 | 2 | |
|
||||
| S3-04 | S3 | Запрос из Alpha/Telegram/Matrix | in_progress | | architect | /alpha/request 200; !request deployed; requests 301 | 2 | |
|
||||
| S3-05 | S3 | Gate G3 | open | YES | architect | pending | 0 | G3 |
|
||||
| U-01 | U | Approve PR #192 | done | | roman | chat approval 2026-11-26 · Открыть PR #192 и подтвердить архитектуру | 2 | none |
|
||||
| U-02 | U | Seerr vs Jellyseerr decision | dropped | YES | roman | Seerr audit · Выбрать после evidence | 2 | none |
|
||||
| U-03 | U | RAM/GPU/disk data | dropped | YES | roman | resource baseline · Прислать/подтвердить параметры | 2 | none |
|
||||
@@ -54,14 +59,17 @@
|
||||
- M / done: 7
|
||||
- S0 / done: 10
|
||||
- S1 / done: 10
|
||||
- S2 / done: 5
|
||||
- S2 / in_progress: 1
|
||||
- S2 / open: 1
|
||||
- S2 / done: 7
|
||||
- S3 / blocked: 1
|
||||
- S3 / done: 2
|
||||
- S3 / in_progress: 1
|
||||
- S3 / open: 1
|
||||
- U / done: 2
|
||||
- U / dropped: 3
|
||||
|
||||
## Пользовательская очередь
|
||||
|
||||
- **S3-05** — Gate G3:
|
||||
- **U-02** — Seerr vs Jellyseerr decision: Выбрать после evidence
|
||||
- **U-03** — RAM/GPU/disk data: Прислать/подтвердить параметры
|
||||
- **U-04** — Approve Stage1 write actions: Разрешить только после Gate G1
|
||||
@@ -18,7 +18,7 @@ Gate G2: повтор события 100 раз = один эффект; пот
|
||||
| S2-02 | Outbox schema + enqueue | done |
|
||||
| S2-03 | Inbox + effects idempotency | done |
|
||||
| S2-04 | NATS JetStream relay | done |
|
||||
| S2-05 | Adapters contract + ownership matrix | in_progress |
|
||||
| S2-05 | Adapters: Audit360/Jellyfin/Seerr | done |
|
||||
| S2-06 | pgvector pilot | done (synthetic infrastructure) |
|
||||
| S2-07 | Gate G2 proof | done |
|
||||
|
||||
@@ -73,6 +73,39 @@ Consumer: `buryans-worker`
|
||||
|
||||
Важно: это инфраструктурный пилот, не production semantic search.
|
||||
|
||||
## Durable pipeline
|
||||
|
||||
Сервис:
|
||||
|
||||
```text
|
||||
events-pipeline.service
|
||||
```
|
||||
|
||||
Делает:
|
||||
|
||||
1. Audit 360 adapter → outbox;
|
||||
2. outbox → NATS JetStream;
|
||||
3. NATS → idempotent inbox/effects;
|
||||
4. повторяет каждые 5 секунд.
|
||||
|
||||
Факт:
|
||||
|
||||
```text
|
||||
outbox published = 43
|
||||
pending = 0
|
||||
inbox = 46
|
||||
effects = 45
|
||||
```
|
||||
|
||||
## Adapters
|
||||
|
||||
- Audit 360 — real;
|
||||
- Jellyfin — real, 7 events emitted and consumed;
|
||||
- Seerr — real read-only session adapter (0 requests currently, valid empty).
|
||||
|
||||
Примечание: `rag` в SQL_ASCII, поэтому кириллица в payload передаётся
|
||||
как `title_utf8_b64`; ASCII-поле `title_ascii` остаётся для совместимости.
|
||||
|
||||
## Следующий инкремент
|
||||
|
||||
NATS JetStream:
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Stage 3 — Media Product
|
||||
|
||||
Статус: начат 2026-11-27.
|
||||
Gate G3: семья делает запрос → смотрит с RU-озвучкой; 0 дублей.
|
||||
|
||||
## Факт на старте
|
||||
|
||||
Jellyfin:
|
||||
|
||||
```text
|
||||
всего медиа 6
|
||||
RU audio 0
|
||||
RU субтитры 0
|
||||
direct-play 6
|
||||
```
|
||||
|
||||
Direct-play исправлен: сериал считается по эпизодам, BoxSet исключён из playable-медиа.
|
||||
|
||||
Это честный gap, не «всё хорошо».
|
||||
|
||||
## Задачи
|
||||
|
||||
| Код | Задача | Статус |
|
||||
|---|---|---|
|
||||
| S3-01 | Аудит RU/direct-play | done (0/7 RU, 6/7 direct) |
|
||||
| S3-02 | RU-дорожки/субтитры | blocked: нет источника RU |
|
||||
| S3-03 | Direct-play 6/6 | done |
|
||||
| S3-04 | Запрос из Alpha/Matrix | in_progress (Alpha + Matrix; Telegram bot отсутствует) |
|
||||
| S3-05 | Gate G3 | open |
|
||||
|
||||
## Проверка
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/acceptance
|
||||
```
|
||||
|
||||
Карточка «RU-озвучка» сейчас **FAIL** — специально, пока нет RU-дорожек.
|
||||
|
||||
```text
|
||||
GET /v1/media/coverage
|
||||
```
|
||||
|
||||
Запрос из Alpha:
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/request
|
||||
```
|
||||
|
||||
Alpha ищет по Jellyfin; кнопка открывает Seerr. Alpha не пишет в Seerr/медиатеку.
|
||||
|
||||
Matrix:
|
||||
|
||||
```text
|
||||
!request Дюна
|
||||
```
|
||||
|
||||
Бот даёт ссылку на `https://requests.buryans.ru`, заявку создаёт семья в Seerr.
|
||||
Telegram-бота в текущем контуре нет.
|
||||
@@ -23,6 +23,7 @@
|
||||
## Остальные
|
||||
|
||||
* **Медиа** — статистика, новинки, поиск, очередь, заявки, место, пробелы.
|
||||
- `!request <название>` — даёт ссылку на заявку в `https://requests.buryans.ru`; бот сам заявку не создаёт.
|
||||
* **Фото** — статистика, альбомы, место.
|
||||
* **Книги** — статистика, новинки, поиск.
|
||||
* **Дом** — статистика, состояние.
|
||||
|
||||
+10
-1
@@ -656,6 +656,7 @@ class MediaBot(Bot):
|
||||
self.cmd("now", "кто что смотрит прямо сейчас")(lambda a: self._now(jf))
|
||||
self.cmd("queue", "очередь загрузок в Sonarr и Radarr")(lambda a: self._queue())
|
||||
self.cmd("requests", "последние заявки в Seerr")(lambda a: self._requests(seerr))
|
||||
self.cmd("request", "ссылка на заявку в Seerr: `!request Дюна`")(lambda a: self._request_link(a))
|
||||
self.cmd("disk", "место на дисках медиасервисов")(lambda a: self._disk())
|
||||
self.cmd("wanted", "сколько ещё не найдено")(lambda a: self._wanted())
|
||||
self.cmd("paths", "где лежат файлы и куда их класть")(lambda a: self._paths())
|
||||
@@ -764,7 +765,7 @@ class MediaBot(Bot):
|
||||
if err:
|
||||
return f"Seerr не ответил: {err}"
|
||||
if not reqs:
|
||||
return "Заявок пока нет. Заказать можно на https://ombi.buryans.ru"
|
||||
return "Заявок пока нет. Заказать можно на https://requests.buryans.ru"
|
||||
lines = ["**Последние заявки**", ""]
|
||||
for r in reqs:
|
||||
media = r.get("media", {}) or {}
|
||||
@@ -774,6 +775,14 @@ class MediaBot(Bot):
|
||||
lines.append(f"• {title} — {status} (просил {who})")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _request_link(self, query):
|
||||
q = (query or "").strip()
|
||||
if not q:
|
||||
return "Использование: `!request Дюна`"
|
||||
return (f"**Заявка в Seerr**\n{q}\n"
|
||||
"Открой https://requests.buryans.ru, найди этот тайтл и отправь заявку.\n"
|
||||
"Alpha и бот не создают запрос сами — это защита от дублей.")
|
||||
|
||||
def _disk(self):
|
||||
lines = ["**Диски**", ""]
|
||||
for svc in (SONARR, RADARR):
|
||||
|
||||
@@ -24,6 +24,16 @@ Consumer: `buryans-worker`
|
||||
- 100 workers same event → `first_effects=1`, `effects=1`.
|
||||
- NATS e2e: 1 outbox → 1 published → 1 inbox → 1 effect.
|
||||
|
||||
## Durable service
|
||||
|
||||
```text
|
||||
events-pipeline.service
|
||||
```
|
||||
|
||||
Adapter Audit 360 → outbox → NATS → inbox/effects, tick 5s.
|
||||
|
||||
SQL_ASCII note: Cyrillic title is carried as `title_utf8_b64`.
|
||||
|
||||
## Next
|
||||
|
||||
- durable consumer/scheduler service;
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Polling adapters for the Stage 2 event fabric."""
|
||||
import base64
|
||||
import http.cookiejar
|
||||
import json
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from event_store import enqueue, event
|
||||
|
||||
|
||||
def _ascii_text(value):
|
||||
return value.encode("ascii", "ignore").decode("ascii")
|
||||
|
||||
|
||||
def _utf8_b64(value):
|
||||
return base64.b64encode(value.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def _iso(dt):
|
||||
if isinstance(dt, str):
|
||||
return dt
|
||||
return dt.astimezone(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def seerr_requests(conn):
|
||||
"""Read-only Seerr request adapter using the local breakglass session."""
|
||||
base = "http://192.168.1.121:5055"
|
||||
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="))
|
||||
cj = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
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:
|
||||
return 0
|
||||
req = urllib.request.Request(base + "/api/v1/request?take=50",
|
||||
headers={"Accept": "application/json"})
|
||||
with op.open(req, timeout=8) as r:
|
||||
data = json.load(r)
|
||||
except Exception:
|
||||
return 0
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter='seerr'")
|
||||
row = cur.fetchone()
|
||||
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
|
||||
emitted = 0
|
||||
last = cursor
|
||||
for x in data.get("results") or []:
|
||||
stamp = x.get("updatedAt") or x.get("createdAt") or ""
|
||||
if not stamp or stamp <= cursor:
|
||||
continue
|
||||
ev = event(idempotency_key="seerr:request:%s:%s" % (x.get("id"), stamp),
|
||||
source="seerr", type_="media.request.created",
|
||||
subject=str(x.get("id")),
|
||||
data={"id": x.get("id"), "status": x.get("status"),
|
||||
"tmdbId": (x.get("media") or {}).get("tmdbId")})
|
||||
if enqueue(conn, ev):
|
||||
emitted += 1
|
||||
if stamp > last:
|
||||
last = stamp
|
||||
if emitted:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values ('seerr',%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (last,))
|
||||
conn.commit()
|
||||
return emitted
|
||||
|
||||
|
||||
def jellyfin_media(conn, limit=50):
|
||||
"""Emit media.work.added for newly created Jellyfin items."""
|
||||
key = Path("/root/.jellyfin-key").read_text().strip()
|
||||
qs = urllib.parse.urlencode({
|
||||
"SortBy": "DateCreated", "SortOrder": "Descending",
|
||||
"IncludeItemTypes": "Movie,Series", "Recursive": "true",
|
||||
"Limit": str(limit), "Fields": "DateCreated,ProductionYear,Overview",
|
||||
})
|
||||
req = urllib.request.Request(
|
||||
"http://192.168.1.103:8096/Items?" + qs,
|
||||
headers={"Authorization": 'MediaBrowser Token="%s"' % key,
|
||||
"Accept": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
data = json.load(r)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter='jellyfin'")
|
||||
row = cur.fetchone()
|
||||
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
|
||||
emitted = 0
|
||||
last = cursor
|
||||
for item in data.get("Items") or []:
|
||||
created = item.get("DateCreated") or ""
|
||||
if created <= cursor:
|
||||
continue
|
||||
name = item.get("Name") or ""
|
||||
ev = event(idempotency_key="jellyfin:work:" + item.get("Id", ""),
|
||||
source="jellyfin", type_="media.work.added",
|
||||
subject=item.get("Id"),
|
||||
data={"id": item.get("Id"), "type": item.get("Type"),
|
||||
"year": item.get("ProductionYear"),
|
||||
"title_ascii": _ascii_text(name),
|
||||
"title_utf8_b64": _utf8_b64(name)})
|
||||
if enqueue(conn, ev):
|
||||
emitted += 1
|
||||
if created > last:
|
||||
last = created
|
||||
if emitted:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values ('jellyfin',%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (last,))
|
||||
conn.commit()
|
||||
return emitted
|
||||
|
||||
|
||||
def audit360(conn, limit=100):
|
||||
"""Emit one event per changed Audit 360 item."""
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter='audit360'")
|
||||
row = cur.fetchone()
|
||||
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00+00:00"
|
||||
cur.execute("""
|
||||
select code,status,title,updated_at
|
||||
from audit.sprint_items
|
||||
where updated_at > %s::timestamptz
|
||||
order by updated_at, code
|
||||
limit %s
|
||||
""", (cursor, limit))
|
||||
rows = cur.fetchall()
|
||||
emitted = 0
|
||||
last = cursor
|
||||
for code, status, title, updated in rows:
|
||||
key = "audit:%s:%s" % (code, _iso(updated))
|
||||
etype = ("audit.finding.closed" if status in ("done", "dropped")
|
||||
else "audit.finding.opened" if status in ("open", "waiting_user")
|
||||
else "audit.finding.updated")
|
||||
ev = event(idempotency_key=key, source="audit360", type_=etype,
|
||||
subject=code, data={"code": code, "status": status,
|
||||
"title_ascii": _ascii_text(title),
|
||||
"title_utf8_b64": _utf8_b64(title)})
|
||||
if enqueue(conn, ev):
|
||||
emitted += 1
|
||||
last = _iso(updated)
|
||||
if rows:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values ('audit360',%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (last,))
|
||||
conn.commit()
|
||||
return emitted
|
||||
@@ -24,6 +24,7 @@ def connect():
|
||||
dbname=os.getenv("PGDATABASE", "rag"),
|
||||
user=os.getenv("PGUSER", "postgres"),
|
||||
password=pw,
|
||||
client_encoding="UTF8",
|
||||
connect_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Buryans Stage 2 events pipeline
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment=PYTHONPATH=/opt/events-nats
|
||||
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/events/pipeline.py
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
ProtectHome=read-only
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Durable Stage 2 pipeline: adapter → outbox → JetStream → idempotent consumer."""
|
||||
import asyncio
|
||||
import signal
|
||||
import time
|
||||
|
||||
from adapters import audit360, jellyfin_media, seerr_requests
|
||||
from event_store import connect, init
|
||||
from nats_relay import consume_once, relay_once
|
||||
|
||||
STOP = False
|
||||
|
||||
|
||||
def _stop(*_):
|
||||
global STOP
|
||||
STOP = True
|
||||
|
||||
|
||||
def main():
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
conn = connect()
|
||||
init(conn)
|
||||
conn.close()
|
||||
print("events-pipeline start", flush=True)
|
||||
while not STOP:
|
||||
try:
|
||||
conn = connect()
|
||||
init(conn)
|
||||
emitted = audit360(conn) + jellyfin_media(conn) + seerr_requests(conn)
|
||||
conn.close()
|
||||
relayed = asyncio.run(relay_once())
|
||||
consumed = asyncio.run(consume_once(timeout=2))
|
||||
print("tick emitted=%s relayed=%s consumed=%s" % (emitted, relayed, consumed), flush=True)
|
||||
except Exception as e:
|
||||
print("tick_error", str(e)[:300], flush=True)
|
||||
for _ in range(5):
|
||||
if STOP:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -40,6 +40,12 @@ CREATE TABLE IF NOT EXISTS events.inbox (
|
||||
CREATE INDEX IF NOT EXISTS inbox_key_idx
|
||||
ON events.inbox (idempotency_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.adapter_state (
|
||||
adapter text PRIMARY KEY,
|
||||
cursor text,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.effects (
|
||||
idempotency_key text PRIMARY KEY,
|
||||
consumer text NOT NULL,
|
||||
|
||||
@@ -101,6 +101,48 @@ def fitness():
|
||||
"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
|
||||
@@ -134,6 +176,11 @@ def home_status():
|
||||
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
|
||||
|
||||
|
||||
@@ -171,6 +218,12 @@ def acceptance_status():
|
||||
{"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}"},
|
||||
@@ -389,6 +442,12 @@ class H(BaseHTTPRequestHandler):
|
||||
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
|
||||
@@ -450,6 +509,9 @@ class H(BaseHTTPRequestHandler):
|
||||
if u.path == "/acceptance":
|
||||
self.out(200, PAGE_ACCEPTANCE, "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
|
||||
@@ -476,7 +538,7 @@ button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#ff
|
||||
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></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></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>
|
||||
@@ -499,6 +561,7 @@ async function boot(){try{const m=await (await fetch('v1/me')).json();document.g
|
||||
<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();
|
||||
@@ -523,6 +586,7 @@ a{color:#58a6ff}code{background:#161b22;padding:2px 5px;border-radius:4px}
|
||||
<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="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>
|
||||
@@ -565,5 +629,28 @@ async function boot(){try{const d=await (await fetch('v1/acceptance')).json();do
|
||||
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=>({'&':'&','<':'<','>':'>','"':'"'}[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||[];document.getElementById('msg').textContent=xs.length?'':'ничего не найдено';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>"""
|
||||
|
||||
if __name__ == "__main__":
|
||||
ThreadingHTTPServer((HOST, PORT), H).serve_forever()
|
||||
Reference in new issue
Block a user