Ship dual-VPS live/shorts/neko hardening: receiving-first, SIGILL auto-heal, quota UX, stream keys.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
c5863c1f74
commit
fc5361a0cc
@ -297,7 +297,7 @@ async def cascade_from_yt_long(job: dict[str, Any], cfg: dict[str, Any] | None =
|
||||
# ── Shorts (15–20s) ────────────────────────────────────────────────
|
||||
if bool(settings_map.get("shorts_enabled", False)):
|
||||
try:
|
||||
if room_id and settings_map.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(room_id, day):
|
||||
if room_id and settings_map.get("shorts_dedupe_room_day", False) and db.has_shorts_job_for_room_day(room_id, day):
|
||||
out["shorts"] = "dedupe"
|
||||
else:
|
||||
ch = db.pick_shorts_channel(day, settings_map, require_upload_quota=True)
|
||||
@ -305,43 +305,52 @@ async def cascade_from_yt_long(job: dict[str, Any], cfg: dict[str, Any] | None =
|
||||
out["shorts"] = "no_quota"
|
||||
else:
|
||||
sec = shorts_cut_sec(settings_map)
|
||||
start = _pick_start(master_sec, sec, (0.45, 0.70))
|
||||
jtmp = db.create_shorts_job(
|
||||
session_id="",
|
||||
room_pk=room_pk,
|
||||
room_id=room_id,
|
||||
source_url=source_url,
|
||||
anchor_name=anchor,
|
||||
stream_url=stream_url,
|
||||
channel_pk=str(ch.get("id") or ""),
|
||||
push_date=day,
|
||||
)
|
||||
if not jtmp:
|
||||
out["shorts"] = "create_failed"
|
||||
ch_id = str(ch.get("id") or "")
|
||||
if room_id and ch_id and db.has_shorts_job_for_room_day(room_id, day, ch_id):
|
||||
out["shorts"] = "channel_room_dedupe"
|
||||
else:
|
||||
jid = str(jtmp["id"])
|
||||
dst = str(clips_root / f"{jid}.mp4")
|
||||
cut = await asyncio.to_thread(
|
||||
cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec
|
||||
offset = db.next_shorts_room_clip_offset(room_id, day, clip_sec=sec) if room_id else 0
|
||||
# From master file: pick a non-overlapping window near mid, shifted by offset.
|
||||
start = _pick_start(master_sec, sec, (0.45, 0.70))
|
||||
start = min(max(0.0, start + float(offset)), max(0.0, master_sec - sec))
|
||||
jtmp = db.create_shorts_job(
|
||||
session_id="",
|
||||
room_pk=room_pk,
|
||||
room_id=room_id,
|
||||
source_url=source_url,
|
||||
anchor_name=anchor,
|
||||
stream_url=stream_url,
|
||||
channel_pk=ch_id,
|
||||
push_date=day,
|
||||
clip_offset_sec=offset,
|
||||
dedupe_room_global=bool(settings_map.get("shorts_dedupe_room_day", False)),
|
||||
)
|
||||
if not cut.get("ok"):
|
||||
db.update_shorts_job(
|
||||
jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time()
|
||||
)
|
||||
out["shorts"] = f"cut_fail:{cut.get('error')}"
|
||||
if not jtmp:
|
||||
out["shorts"] = "create_failed"
|
||||
else:
|
||||
from .shorts_schedule import pick_upload_at
|
||||
|
||||
upload_at = pick_upload_at(channel_pk=str(ch.get("id") or ""), cfg=settings_map)
|
||||
db.update_shorts_job(
|
||||
jid,
|
||||
status="scheduled",
|
||||
clip_path=str(cut["path"]),
|
||||
clip_seconds=float(cut.get("seconds") or sec),
|
||||
upload_at=upload_at,
|
||||
error="cascade_from_yt_long",
|
||||
jid = str(jtmp["id"])
|
||||
dst = str(clips_root / f"{jid}.mp4")
|
||||
cut = await asyncio.to_thread(
|
||||
cut_segment, src=master, dst=dst, start_sec=start, duration_sec=sec
|
||||
)
|
||||
out["shorts"] = jid
|
||||
if not cut.get("ok"):
|
||||
db.update_shorts_job(
|
||||
jid, status="failed", error=f"cascade_cut:{cut.get('error')}", finished_at=time.time()
|
||||
)
|
||||
out["shorts"] = f"cut_fail:{cut.get('error')}"
|
||||
else:
|
||||
from .shorts_schedule import pick_upload_at
|
||||
|
||||
upload_at = pick_upload_at(channel_pk=str(ch.get("id") or ""), cfg=settings_map)
|
||||
db.update_shorts_job(
|
||||
jid,
|
||||
status="scheduled",
|
||||
clip_path=str(cut["path"]),
|
||||
clip_seconds=float(cut.get("seconds") or sec),
|
||||
upload_at=upload_at,
|
||||
error="cascade_from_yt_long",
|
||||
)
|
||||
out["shorts"] = jid
|
||||
except Exception as exc:
|
||||
out["shorts"] = f"err:{exc}"[:120]
|
||||
|
||||
|
||||
@ -116,7 +116,28 @@ def _clear_path_refs(path: str, now: float) -> None:
|
||||
with db._lock:
|
||||
conn = db._connect()
|
||||
try:
|
||||
for table in ("shorts_jobs", "tiktok_jobs", "x_clip_jobs", "yt_long_jobs"):
|
||||
# Shorts: clearing the file must also unstick scheduled/recorded jobs
|
||||
# so they re-enter pending (otherwise quota is consumed forever).
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE shorts_jobs
|
||||
SET clip_path = '', status = 'pending', upload_at = 0,
|
||||
clip_seconds = 0, error = '成片被清理,已重新排队录制',
|
||||
updated_at = ?
|
||||
WHERE clip_path = ?
|
||||
AND status IN ('recorded', 'scheduled')
|
||||
AND IFNULL(youtube_video_id, '') = ''
|
||||
""",
|
||||
(now, path),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE shorts_jobs SET clip_path = '', updated_at = ? WHERE clip_path = ?",
|
||||
(now, path),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
for table in ("tiktok_jobs", "x_clip_jobs", "yt_long_jobs"):
|
||||
try:
|
||||
conn.execute(
|
||||
f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?",
|
||||
@ -250,6 +271,18 @@ def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
if under_pressure and disk_free_gb() >= min_free:
|
||||
break
|
||||
|
||||
covers_purge: dict[str, Any] = {}
|
||||
try:
|
||||
from . import s3_storage
|
||||
|
||||
try:
|
||||
keep_days = float(settings_map.get("covers_s3_keep_days") or 2)
|
||||
except Exception:
|
||||
keep_days = 2.0
|
||||
covers_purge = s3_storage.purge_covers_older_than(keep_days=keep_days)
|
||||
except Exception as exc:
|
||||
covers_purge = {"ok": False, "error": str(exc)[:160]}
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"examined": examined,
|
||||
@ -260,4 +293,5 @@ def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"free_gb_before": round(free_before, 2),
|
||||
"free_gb_after": round(disk_free_gb(), 2),
|
||||
"min_free_gb": min_free,
|
||||
"covers_s3": covers_purge,
|
||||
}
|
||||
|
||||
@ -81,6 +81,9 @@ class Settings(BaseSettings):
|
||||
neko_nat1to1: str = "" # empty → auto-detect public IP
|
||||
neko_webrtc_icelite: str = "0" # sh2: OFF for remote ICE stability
|
||||
neko_shm_size: str = "512mb"
|
||||
# Hard cap per Neko container (Docker). Empty/0 = unlimited.
|
||||
# VPS ~4Gi: keep one Live Studio under ~1.5Gi so host+API+FFmpeg survive.
|
||||
neko_mem_limit: str = "1536m"
|
||||
neko_desktop_screen: str = "1024x576@10"
|
||||
neko_max_fps: str = "10"
|
||||
neko_video_bitrate: str = "700"
|
||||
|
||||
@ -237,12 +237,20 @@ def init_db() -> None:
|
||||
sj_cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()}
|
||||
if "upload_at" not in sj_cols:
|
||||
conn.execute("ALTER TABLE shorts_jobs ADD COLUMN upload_at REAL NOT NULL DEFAULT 0")
|
||||
if "clip_offset_sec" not in sj_cols:
|
||||
conn.execute(
|
||||
"ALTER TABLE shorts_jobs ADD COLUMN clip_offset_sec REAL NOT NULL DEFAULT 0"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_shorts_jobs_upload ON shorts_jobs(status, upload_at)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_shorts_jobs_room_day ON shorts_jobs(room_id, push_date, status)"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_shorts_jobs_room_ch_day "
|
||||
"ON shorts_jobs(room_id, channel_pk, push_date, status)"
|
||||
)
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS tiktok_channels (
|
||||
@ -582,12 +590,15 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"youtube_relay_exclusive_live": True,
|
||||
# Time-slot mode: N=keyed channels → each gets 24/N Beijing hours; source=live Douyin rooms.
|
||||
"youtube_relay_time_slot_mode": False,
|
||||
# Manual rotate for quick time_slot testing (ignores real 24/N clock).
|
||||
"youtube_relay_timeslot_test": False,
|
||||
"youtube_relay_timeslot_test_group_id": "",
|
||||
# Shorts pipeline
|
||||
"shorts_enabled": False,
|
||||
"shorts_clip_sec": 15,
|
||||
"shorts_trigger": "tagged",
|
||||
"shorts_tag": "shorts",
|
||||
"shorts_dedupe_room_day": True,
|
||||
"shorts_dedupe_room_day": False,
|
||||
"shorts_max_concurrent": 1,
|
||||
"shorts_auto_upload": True,
|
||||
"shorts_live_sample": True,
|
||||
@ -595,8 +606,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"shorts_live_sample_batch": 1,
|
||||
"shorts_sample_any_live": True,
|
||||
"shorts_upload_spread": True,
|
||||
"shorts_upload_min_gap_sec": 720,
|
||||
"shorts_channel_min_gap_sec": 2400,
|
||||
"shorts_upload_min_gap_sec": 600,
|
||||
"shorts_channel_min_gap_sec": 600,
|
||||
"shorts_delete_clip_after_upload": True,
|
||||
"shorts_auto_retry_failed": True,
|
||||
"shorts_auto_retry_max_attempts": 3,
|
||||
@ -620,6 +631,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"yt_studio_cookies_by_profile": {},
|
||||
"shorts_gcp_project_id": "live-473104",
|
||||
"shorts_yt_daily_upload_limit": 90,
|
||||
# After real YouTube 429, auto-upload cool-down per Client (sec); manual never gated
|
||||
"shorts_yt_quota_cooldown_sec": 3600,
|
||||
"shorts_yt_upload_blocked_until": 0,
|
||||
"shorts_yt_uploads_pt_date": "",
|
||||
"shorts_yt_uploads_pt_count": 0,
|
||||
@ -710,6 +723,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"clip_cascade_enabled": True,
|
||||
"clips_max_age_hours": 24,
|
||||
"clips_min_free_gb": 12,
|
||||
# Seaweed/S3 session covers (covers/*.jpg); avatars kept. Default 2 days.
|
||||
"covers_s3_keep_days": 2,
|
||||
"yt_long_monetize_when_ypp": True,
|
||||
"tiktok_auto_retry_failed": False,
|
||||
"tiktok_auto_retry_max_attempts": 3,
|
||||
@ -3783,7 +3798,7 @@ def shorts_live_channel_stats(*, date_from: str = "", date_to: str = "") -> list
|
||||
conn.close()
|
||||
|
||||
|
||||
# Jobs that consume a channel's Beijing-day quota (aligned with schedule_board.used).
|
||||
# Jobs that occupy a Beijing-day pipeline slot (pending→done). Cap enqueue with this.
|
||||
_SHORTS_QUOTA_STATUSES = (
|
||||
"pending",
|
||||
"recording",
|
||||
@ -3793,9 +3808,45 @@ _SHORTS_QUOTA_STATUSES = (
|
||||
"uploaded",
|
||||
"done",
|
||||
)
|
||||
# Progress / 已满 / daily_min: only successful uploads count.
|
||||
_SHORTS_UPLOADED_STATUSES = ("uploaded", "done")
|
||||
|
||||
|
||||
def shorts_channel_last_slot_ts(channel_pk: str, push_date: str) -> float:
|
||||
"""Latest upload slot time for channel today (scheduled/uploading/finished)."""
|
||||
cid = str(channel_pk or "").strip()
|
||||
day = str(push_date or "").strip()
|
||||
if not cid or not day:
|
||||
return 0.0
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT status, upload_at, finished_at, updated_at FROM shorts_jobs
|
||||
WHERE channel_pk = ? AND push_date = ?
|
||||
AND status IN ('scheduled', 'recorded', 'uploading', 'uploaded', 'done')
|
||||
""",
|
||||
(cid, day),
|
||||
).fetchall()
|
||||
best = 0.0
|
||||
for r in rows:
|
||||
st = str(r["status"] or "")
|
||||
if st in {"uploaded", "done"}:
|
||||
ts = float(r["finished_at"] or r["updated_at"] or 0)
|
||||
elif st == "uploading":
|
||||
ts = float(r["updated_at"] or r["upload_at"] or 0)
|
||||
else:
|
||||
ts = float(r["upload_at"] or r["updated_at"] or 0)
|
||||
if ts > best:
|
||||
best = ts
|
||||
return best
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int:
|
||||
"""Pipeline occupancy (pending…done). Used to cap new enqueues."""
|
||||
placeholders = ",".join("?" for _ in _SHORTS_QUOTA_STATUSES)
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
@ -3813,8 +3864,27 @@ def shorts_channel_upload_count(channel_pk: str, push_date: str) -> int:
|
||||
conn.close()
|
||||
|
||||
|
||||
def shorts_channel_uploaded_count(channel_pk: str, push_date: str) -> int:
|
||||
"""Successful uploads only (uploaded/done). Progress bar / 已满 / daily_min."""
|
||||
placeholders = ",".join("?" for _ in _SHORTS_UPLOADED_STATUSES)
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
f"""
|
||||
SELECT COUNT(*) AS c FROM shorts_jobs
|
||||
WHERE channel_pk = ? AND push_date = ?
|
||||
AND status IN ({placeholders})
|
||||
""",
|
||||
(channel_pk, push_date, *_SHORTS_UPLOADED_STATUSES),
|
||||
).fetchone()
|
||||
return int(row["c"] if row else 0)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]:
|
||||
"""Per enabled channel: used/gap toward daily_max for the Beijing day."""
|
||||
"""Per enabled channel: progress = uploaded; pipeline caps enqueue."""
|
||||
day = push_date or push_date_from_ts(time.time())
|
||||
rows: list[dict[str, Any]] = []
|
||||
for ch in list_shorts_channels(enabled=True):
|
||||
@ -3823,17 +3893,21 @@ def shorts_channels_quota_summary(push_date: str = "") -> list[dict[str, Any]]:
|
||||
daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||||
if daily_max < daily_min:
|
||||
daily_max = daily_min
|
||||
used = shorts_channel_upload_count(cid, day)
|
||||
pipeline = shorts_channel_upload_count(cid, day)
|
||||
uploaded = shorts_channel_uploaded_count(cid, day)
|
||||
rows.append(
|
||||
{
|
||||
"id": cid,
|
||||
"name": ch.get("name"),
|
||||
"daily_min": daily_min,
|
||||
"daily_max": daily_max,
|
||||
"used": used,
|
||||
"gap": max(0, daily_max - used),
|
||||
"min_met": used >= daily_min,
|
||||
"max_met": used >= daily_max,
|
||||
"used": uploaded,
|
||||
"uploaded": uploaded,
|
||||
"pipeline": pipeline,
|
||||
"gap": max(0, daily_max - uploaded),
|
||||
"min_met": uploaded >= daily_min,
|
||||
"max_met": uploaded >= daily_max,
|
||||
"pipeline_full": pipeline >= daily_max,
|
||||
}
|
||||
)
|
||||
rows.sort(key=lambda r: (0 if not r["min_met"] else 1, r["used"], r["id"]))
|
||||
@ -3998,13 +4072,16 @@ def pick_shorts_channel(
|
||||
pid = profile_id_for_channel(ch)
|
||||
if require_upload_quota and not project_uploads_available(cfg, profile_id=pid):
|
||||
continue
|
||||
used = shorts_channel_upload_count(str(ch["id"]), push_date)
|
||||
cid = str(ch["id"])
|
||||
pipeline = shorts_channel_upload_count(cid, push_date)
|
||||
uploaded = shorts_channel_uploaded_count(cid, push_date)
|
||||
daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||||
if used >= daily_max:
|
||||
# Cap new jobs by pipeline; progress target is uploaded.
|
||||
if pipeline >= daily_max or uploaded >= daily_max:
|
||||
continue
|
||||
daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE)
|
||||
under = 0 if used < daily_min else 1
|
||||
scored.append((under, used, float(ch.get("last_assigned_at") or 0), ch))
|
||||
under = 0 if uploaded < daily_min else 1
|
||||
scored.append((under, uploaded, float(ch.get("last_assigned_at") or 0), ch))
|
||||
if not scored:
|
||||
return None
|
||||
scored.sort(key=lambda x: (x[0], x[1], x[2]))
|
||||
@ -4061,6 +4138,45 @@ def get_shorts_job(job_id: str) -> dict[str, Any] | None:
|
||||
conn.close()
|
||||
|
||||
|
||||
def next_shorts_room_clip_offset(
|
||||
room_id: str,
|
||||
push_date: str,
|
||||
*,
|
||||
clip_sec: int = 15,
|
||||
) -> int:
|
||||
"""Next non-overlapping live window for this room today (0, 15, 30, …)."""
|
||||
rid = str(room_id or "").strip()
|
||||
day = str(push_date or "").strip() or push_date_from_ts(time.time())
|
||||
sec = max(10, min(int(clip_sec or 15), 60))
|
||||
if not rid:
|
||||
return 0
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()}
|
||||
if "clip_offset_sec" not in cols:
|
||||
return 0
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT clip_offset_sec FROM shorts_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
""",
|
||||
(rid, day),
|
||||
).fetchall()
|
||||
if not rows:
|
||||
return 0
|
||||
best = 0.0
|
||||
for r in rows:
|
||||
try:
|
||||
best = max(best, float(r["clip_offset_sec"] or 0))
|
||||
except (TypeError, ValueError, KeyError):
|
||||
continue
|
||||
return int(best) + sec
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def create_shorts_job(
|
||||
*,
|
||||
session_id: str,
|
||||
@ -4072,38 +4188,64 @@ def create_shorts_job(
|
||||
channel_pk: str = "",
|
||||
push_date: str = "",
|
||||
force: bool = False,
|
||||
clip_offset_sec: float | int = 0,
|
||||
dedupe_room_global: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Create a Shorts job. Same room_id + Beijing day is unique unless force=True.
|
||||
"""Create a Shorts job.
|
||||
|
||||
Returns None when a non-failed/skipped job already exists for that room/day.
|
||||
Default: unique per (room_id, channel_pk, Beijing day) — different channels may
|
||||
share one Douyin room if each gets a distinct clip_offset_sec (sequential live
|
||||
windows: 0–15s, 15–30s, …).
|
||||
|
||||
dedupe_room_global=True restores legacy one-job-per-room-per-day.
|
||||
"""
|
||||
now = time.time()
|
||||
jid = str(uuid.uuid4())
|
||||
day = push_date or push_date_from_ts(now)
|
||||
rid = str(room_id or "").strip()
|
||||
ch = str(channel_pk or "").strip()
|
||||
offset = max(0, int(float(clip_offset_sec or 0)))
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(shorts_jobs)").fetchall()}
|
||||
if "clip_offset_sec" not in cols:
|
||||
conn.execute(
|
||||
"ALTER TABLE shorts_jobs ADD COLUMN clip_offset_sec REAL NOT NULL DEFAULT 0"
|
||||
)
|
||||
if rid and not force:
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT * FROM shorts_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(rid, day),
|
||||
).fetchone()
|
||||
if existing:
|
||||
return None
|
||||
if dedupe_room_global:
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id FROM shorts_jobs
|
||||
WHERE room_id = ? AND push_date = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
LIMIT 1
|
||||
""",
|
||||
(rid, day),
|
||||
).fetchone()
|
||||
if existing:
|
||||
return None
|
||||
elif ch:
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id FROM shorts_jobs
|
||||
WHERE room_id = ? AND push_date = ? AND channel_pk = ?
|
||||
AND status NOT IN ('failed', 'skipped')
|
||||
LIMIT 1
|
||||
""",
|
||||
(rid, day, ch),
|
||||
).fetchone()
|
||||
if existing:
|
||||
return None
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO shorts_jobs(
|
||||
id, session_id, room_pk, room_id, source_url, anchor_name, stream_url,
|
||||
channel_pk, status, clip_path, clip_seconds, youtube_video_id, youtube_url,
|
||||
error, push_date, attempts, created_at, updated_at, started_at, finished_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', ?, 0, ?, ?, 0, 0)
|
||||
error, push_date, attempts, created_at, updated_at, started_at, finished_at,
|
||||
clip_offset_sec
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', ?, 0, ?, ?, 0, 0, ?)
|
||||
""",
|
||||
(
|
||||
jid,
|
||||
@ -4117,6 +4259,7 @@ def create_shorts_job(
|
||||
day,
|
||||
now,
|
||||
now,
|
||||
float(offset),
|
||||
),
|
||||
)
|
||||
if channel_pk:
|
||||
@ -4135,11 +4278,17 @@ def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
|
||||
"status",
|
||||
"clip_path",
|
||||
"clip_seconds",
|
||||
"clip_offset_sec",
|
||||
"youtube_video_id",
|
||||
"youtube_url",
|
||||
"error",
|
||||
"channel_pk",
|
||||
"stream_url",
|
||||
"source_url",
|
||||
"anchor_name",
|
||||
"room_id",
|
||||
"room_pk",
|
||||
"session_id",
|
||||
"attempts",
|
||||
"started_at",
|
||||
"finished_at",
|
||||
@ -4219,9 +4368,40 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict
|
||||
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
|
||||
if pid in skip:
|
||||
continue
|
||||
jid = row["id"]
|
||||
status = row["status"]
|
||||
ch_pk = str(row["channel_pk"] or "")
|
||||
day = str(row["push_date"] or "")
|
||||
# Enforce >10min same-channel spacing at claim time.
|
||||
if ch_pk and day:
|
||||
sibs = conn.execute(
|
||||
"""
|
||||
SELECT status, upload_at, finished_at, updated_at FROM shorts_jobs
|
||||
WHERE channel_pk = ? AND push_date = ? AND id != ?
|
||||
AND status IN ('uploading', 'uploaded', 'done')
|
||||
""",
|
||||
(ch_pk, day, jid),
|
||||
).fetchall()
|
||||
last_ts = 0.0
|
||||
for r in sibs:
|
||||
st = str(r["status"] or "")
|
||||
if st in {"uploaded", "done"}:
|
||||
ts = float(r["finished_at"] or r["updated_at"] or 0)
|
||||
else:
|
||||
ts = float(r["updated_at"] or r["upload_at"] or 0)
|
||||
if ts > last_ts:
|
||||
last_ts = ts
|
||||
if last_ts > 0 and (now - last_ts) < 600.0:
|
||||
defer_to = last_ts + 600.0 + 15.0
|
||||
conn.execute(
|
||||
"UPDATE shorts_jobs SET upload_at = ?, updated_at = ? WHERE id = ? AND status = ?",
|
||||
(defer_to, now, jid, status),
|
||||
)
|
||||
continue
|
||||
picked = row
|
||||
break
|
||||
if not picked:
|
||||
conn.commit()
|
||||
return None
|
||||
jid = picked["id"]
|
||||
status = picked["status"]
|
||||
@ -4243,7 +4423,6 @@ def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def claim_pending_shorts_record() -> dict[str, Any] | None:
|
||||
"""Claim one pending job for recording."""
|
||||
now = time.time()
|
||||
@ -4384,37 +4563,45 @@ def reconcile_false_failed_shorts(*, limit: int = 200) -> int:
|
||||
|
||||
|
||||
def reconcile_missing_shorts_clips(*, limit: int = 200) -> int:
|
||||
"""Reset jobs whose clip_path points to a deleted file → pending re-record."""
|
||||
"""Reset jobs whose clip is missing or empty → pending re-record.
|
||||
|
||||
Retention may clear clip_path while leaving status=scheduled; those jobs
|
||||
consume daily quota but can never upload — reclaim them.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
lim = max(1, min(int(limit), 500))
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, clip_path FROM shorts_jobs
|
||||
WHERE clip_path != ''
|
||||
AND status IN ('recorded', 'scheduled', 'uploading')
|
||||
SELECT id, clip_path, status FROM shorts_jobs
|
||||
WHERE status IN ('recorded', 'scheduled', 'uploading')
|
||||
AND IFNULL(youtube_video_id, '') = ''
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(max(1, min(int(limit), 500)),),
|
||||
(lim,),
|
||||
).fetchall()
|
||||
fixed = 0
|
||||
now = time.time()
|
||||
for row in rows:
|
||||
path = str(row["clip_path"] or "").strip()
|
||||
if not path or Path(path).is_file():
|
||||
missing = (not path) or (not Path(path).is_file())
|
||||
if not missing:
|
||||
continue
|
||||
reason = "成片路径为空,已重新排队录制" if not path else "成片已丢失,已重新排队录制"
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE shorts_jobs
|
||||
SET status = 'pending', clip_path = '', clip_seconds = 0,
|
||||
upload_at = 0, error = '成片已丢失,已重新排队录制',
|
||||
upload_at = 0, error = ?,
|
||||
finished_at = 0, updated_at = ?
|
||||
WHERE id = ? AND status IN ('recorded', 'scheduled', 'uploading')
|
||||
AND IFNULL(youtube_video_id, '') = ''
|
||||
""",
|
||||
(now, row["id"]),
|
||||
(reason, now, row["id"]),
|
||||
)
|
||||
if conn.total_changes:
|
||||
fixed += 1
|
||||
@ -4828,6 +5015,13 @@ def list_auto_retry_failed_jobs(*, max_attempts: int = 3, limit: int = 8) -> lis
|
||||
continue
|
||||
if _classify_shorts_error(err) == "quota":
|
||||
continue
|
||||
# Offline / dead stream — do not burn record slots retrying.
|
||||
if "无法获取直播流" in err or "已停播" in err or "已释放名额" in err:
|
||||
continue
|
||||
if "probe 404" in low or "server returned 404" in low:
|
||||
continue
|
||||
if "connection timed out" in low and ("stream" in low or "http" in low or "opening input" in low):
|
||||
continue
|
||||
out.append(job)
|
||||
return out
|
||||
finally:
|
||||
|
||||
@ -61,11 +61,38 @@ def _pick_stream_url(room: dict[str, Any]) -> str:
|
||||
return cands[0] if cands else ""
|
||||
|
||||
|
||||
def _is_uhd_stream_url(url: str) -> bool:
|
||||
"""True when CDN path/query looks like origin/UHD (expensive to software-decode)."""
|
||||
u = str(url or "").lower()
|
||||
if not u:
|
||||
return False
|
||||
return (
|
||||
"_uhd" in u
|
||||
or "/uhd" in u
|
||||
or "uhd." in u
|
||||
or "_flv_uhd" in u
|
||||
or "unique_id=" in u and "_uhd" in u
|
||||
)
|
||||
|
||||
|
||||
def _demote_uhd_urls(urls: list[str]) -> list[str]:
|
||||
"""Stable partition: non-UHD first, UHD/ORIGIN last (fallback only)."""
|
||||
good: list[str] = []
|
||||
uhd: list[str] = []
|
||||
for u in urls:
|
||||
(uhd if _is_uhd_stream_url(u) else good).append(u)
|
||||
return good + uhd
|
||||
|
||||
|
||||
def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list[str]:
|
||||
"""Build ordered playable URLs — aligned with DouyinLiveRecorder stream.get_douyin_stream_url.
|
||||
|
||||
Prefer FLV for Douyin (DLR select_source_url), but keep HLS fallbacks because CDN FLV
|
||||
lines often 404; quality ladder ORIGIN → FULL_HD1 → HD1 → SD1 → SD2.
|
||||
lines often 404.
|
||||
|
||||
Quality ladder prefers **non-UHD** to keep FFmpeg CPU sane on VPS:
|
||||
HD1 → FULL_HD1 → SD1 → SD2 → ORIGIN (last). Any URL whose path looks like `_uhd`
|
||||
is demoted to the end even if Douyin labeled it otherwise.
|
||||
"""
|
||||
stream = room.get("stream_url") or {}
|
||||
if not isinstance(stream, dict):
|
||||
@ -76,7 +103,8 @@ def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list
|
||||
flv_map = {}
|
||||
if not isinstance(hls_map, dict):
|
||||
hls_map = {}
|
||||
order = ("ORIGIN", "FULL_HD1", "HD1", "SD1", "SD2")
|
||||
# ORIGIN last — often maps to UHD and burns a full core on soft decode.
|
||||
order = ("HD1", "FULL_HD1", "SD1", "SD2", "ORIGIN")
|
||||
flv_list: list[str] = []
|
||||
hls_list: list[str] = []
|
||||
for key in order:
|
||||
@ -101,6 +129,8 @@ def pick_stream_candidates(room: dict[str, Any], *, prefer: str = "flv") -> list
|
||||
single_hls = str(stream.get("hls_pull_url") or "").strip()
|
||||
if single_hls.startswith("http") and single_hls not in hls_list:
|
||||
hls_list.append(single_hls)
|
||||
flv_list = _demote_uhd_urls(flv_list)
|
||||
hls_list = _demote_uhd_urls(hls_list)
|
||||
if prefer == "hls":
|
||||
return hls_list + flv_list
|
||||
return flv_list + hls_list
|
||||
|
||||
@ -27,6 +27,7 @@ import httpx
|
||||
|
||||
from . import cookie_loader, db, pb_sync, shorts_oauth, tiktok_db, youtube_client, youtube_manage
|
||||
from . import yt_assign_db
|
||||
from . import yt_stream_key_db
|
||||
from .config import settings
|
||||
from .cover import cover_path_for, ensure_session_cover
|
||||
from .douyin import check_room
|
||||
@ -65,6 +66,9 @@ from .models import (
|
||||
YtAssignGroupUpdate,
|
||||
YtAssignPoolAdd,
|
||||
YtAssignPoolUpdate,
|
||||
YtStreamKeyEntryUpsert,
|
||||
YtStreamKeyImportAssignBody,
|
||||
YtStreamKeyImportBody,
|
||||
)
|
||||
from .monitor import monitor
|
||||
from .stats import summarize_anchor_schedule, summarize_sessions
|
||||
@ -131,13 +135,19 @@ async def lifespan(_: FastAPI):
|
||||
raise
|
||||
while True:
|
||||
try:
|
||||
await asyncio.wait_for(youtube_live.build_live_map(force=True), timeout=30)
|
||||
# Skip pile-up when a rebuild is already running (force waits on same lock).
|
||||
task = getattr(youtube_live, "_REFRESH_TASK", None)
|
||||
lock = youtube_live._refresh_lock() # noqa: SLF001
|
||||
if (task is not None and not task.done()) or lock.locked():
|
||||
pass
|
||||
else:
|
||||
await asyncio.wait_for(youtube_live.build_live_map(force=True), timeout=30)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
await asyncio.sleep(30)
|
||||
await asyncio.sleep(45)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
|
||||
@ -174,6 +184,12 @@ async def lifespan(_: FastAPI):
|
||||
asyncio.create_task(_ops_background_loops())
|
||||
|
||||
async def _start_workers() -> None:
|
||||
# Let uvicorn bind + serve /api/health before heavy sync boots (docker/neko/SQLite).
|
||||
# Otherwise Recv-Q climbs for minutes while the event loop is wedged in worker start.
|
||||
try:
|
||||
await asyncio.sleep(3)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
if _desktop_light:
|
||||
return
|
||||
|
||||
@ -303,9 +319,13 @@ async def ping() -> dict[str, Any]:
|
||||
return {"ok": True, "t": time.time(), "desktop_light": _DESKTOP_LIGHT}
|
||||
|
||||
|
||||
_HEALTH_DEPS_CACHE: dict[str, Any] = {"at": 0.0, "payload": None}
|
||||
_HEALTH_DEPS_TTL = float(os.environ.get("DY_HEALTH_DEPS_TTL", "5") or "5")
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
"""Fast health — no full pipeline builders unless ?detail=1."""
|
||||
"""Fast health — default path must not touch thread pools or SQLite."""
|
||||
if _DESKTOP_LIGHT:
|
||||
return {"ok": True, "time": time.time(), "desktop_light": True}
|
||||
out: dict[str, Any] = {
|
||||
@ -348,20 +368,95 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]:
|
||||
},
|
||||
}
|
||||
|
||||
# Default liveness stays cheap, but still expose the fields the ops panel reads
|
||||
# so a missing youtube/pb/s3 key is not shown as "异常/已停".
|
||||
if not detail:
|
||||
try:
|
||||
out["monitor"] = {
|
||||
"running": bool(
|
||||
getattr(monitor, "_task", None) and not monitor._task.done() # noqa: SLF001
|
||||
),
|
||||
}
|
||||
out["youtube_monitor"] = {
|
||||
"running": bool(
|
||||
getattr(yt_monitor, "_task", None) and not yt_monitor._task.done() # noqa: SLF001
|
||||
),
|
||||
}
|
||||
out["shorts"] = {
|
||||
"running": bool(
|
||||
getattr(shorts_pipeline, "_task", None) and not shorts_pipeline._task.done() # noqa: SLF001
|
||||
),
|
||||
}
|
||||
out["youtube_relay"] = {
|
||||
"running": bool(
|
||||
getattr(youtube_relay_pipeline, "_task", None)
|
||||
and not youtube_relay_pipeline._task.done() # noqa: SLF001
|
||||
),
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
# Cache youtube/pb/s3 pulses — ops/UI poll health often; identical shape, ≤TTL lag.
|
||||
now_deps = time.time()
|
||||
cached_deps = _HEALTH_DEPS_CACHE.get("payload")
|
||||
if (
|
||||
isinstance(cached_deps, dict)
|
||||
and now_deps - float(_HEALTH_DEPS_CACHE.get("at") or 0) < _HEALTH_DEPS_TTL
|
||||
):
|
||||
out.update(cached_deps)
|
||||
out["deps_cached"] = True
|
||||
return out
|
||||
deps: dict[str, Any] = {}
|
||||
try:
|
||||
deps["youtube"] = await asyncio.wait_for(youtube_client.health(), timeout=0.6)
|
||||
except Exception as exc:
|
||||
deps["youtube"] = {"ok": False, "error": str(exc)[:120], "service": "youtube-svc"}
|
||||
try:
|
||||
deps["pocketbase"] = await asyncio.wait_for(pb_sync.health(), timeout=0.5)
|
||||
except Exception as exc:
|
||||
deps["pocketbase"] = {"ok": False, "error": str(exc)[:120]}
|
||||
try:
|
||||
from . import s3_storage
|
||||
|
||||
enabled = bool(s3_storage.s3_enabled())
|
||||
s3_info: dict[str, Any] = {
|
||||
"enabled": enabled,
|
||||
"ok": False,
|
||||
"endpoint": settings.s3_endpoint,
|
||||
"bucket": settings.s3_bucket,
|
||||
"public_base": settings.s3_public_base,
|
||||
}
|
||||
if enabled:
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(
|
||||
lambda: s3_storage._client().head_bucket(Bucket=settings.s3_bucket) # noqa: SLF001
|
||||
),
|
||||
timeout=0.6,
|
||||
)
|
||||
s3_info["ok"] = True
|
||||
except Exception as exc:
|
||||
s3_info["error"] = str(exc)[:80]
|
||||
deps["s3"] = s3_info
|
||||
except Exception:
|
||||
deps["s3"] = {"enabled": False, "ok": False}
|
||||
_HEALTH_DEPS_CACHE["at"] = now_deps
|
||||
_HEALTH_DEPS_CACHE["payload"] = deps
|
||||
out.update(deps)
|
||||
out["deps_cached"] = False
|
||||
return out
|
||||
|
||||
try:
|
||||
if detail:
|
||||
out["monitor"] = await asyncio.to_thread(monitor.status)
|
||||
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
|
||||
out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status)
|
||||
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
|
||||
out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||
cfg = await _db(db.get_settings_map)
|
||||
out["tiktok"] = {"enabled": bool(cfg.get("tiktok_enabled"))}
|
||||
else:
|
||||
light = await asyncio.to_thread(_light_health)
|
||||
out.update(light)
|
||||
out["monitor"] = await asyncio.to_thread(monitor.status)
|
||||
out["shorts"] = await asyncio.to_thread(shorts_pipeline.status)
|
||||
out["yt_long"] = await asyncio.to_thread(yt_long_pipeline.status)
|
||||
out["youtube_monitor"] = await asyncio.to_thread(yt_monitor.status)
|
||||
out["youtube_relay"] = await asyncio.to_thread(youtube_relay_pipeline.status)
|
||||
cfg = await _db(db.get_settings_map)
|
||||
out["tiktok"] = {"enabled": bool(cfg.get("tiktok_enabled"))}
|
||||
out.update({k: v for k, v in _light_health().items() if k not in out})
|
||||
except Exception as exc:
|
||||
out["status_error"] = str(exc)[:120]
|
||||
return out
|
||||
|
||||
async def _pb() -> dict[str, Any]:
|
||||
try:
|
||||
@ -2503,14 +2598,15 @@ async def patch_settings(body: SettingsUpdate, request: Request) -> dict[str, An
|
||||
@app.post("/api/settings/sync-cookie")
|
||||
async def sync_cookie_from_sh2() -> dict[str, Any]:
|
||||
"""Pull 抖音cookie from sh2 d2ypp2/config/config.ini into settings."""
|
||||
result = cookie_loader.force_sync_cookie_from_sh2()
|
||||
result = await _db(cookie_loader.force_sync_cookie_from_sh2)
|
||||
if not result.get("ok"):
|
||||
raise HTTPException(404, "未找到 sh2 config.ini 中的抖音cookie")
|
||||
cfg = db.get_settings_map()
|
||||
cfg = await _db(db.get_settings_map)
|
||||
mon = await asyncio.to_thread(monitor.status)
|
||||
return {
|
||||
**result,
|
||||
"has_cookie": bool(str(cfg.get("dy_cookie") or "").strip()),
|
||||
"monitor": monitor.status(),
|
||||
"monitor": mon,
|
||||
}
|
||||
|
||||
|
||||
@ -3015,7 +3111,7 @@ async def yt_assign_list_groups() -> dict[str, Any]:
|
||||
yt_assign_db.ensure_default_assign_data()
|
||||
except Exception:
|
||||
pass
|
||||
return yt_assign_db.list_groups(include_urls=True)
|
||||
return yt_assign_db.list_groups(include_urls=True, include_secret=True)
|
||||
|
||||
return {"groups": await _db(_load)}
|
||||
|
||||
@ -3027,11 +3123,99 @@ async def yt_assign_schedule() -> dict[str, Any]:
|
||||
yt_assign_db.ensure_default_assign_data()
|
||||
except Exception:
|
||||
pass
|
||||
return yt_assign_db.build_rotation_schedule(include_urls=True)
|
||||
sched = yt_assign_db.build_rotation_schedule(include_urls=True)
|
||||
try:
|
||||
cfg = db.get_settings_map()
|
||||
if bool(cfg.get("youtube_relay_timeslot_test")):
|
||||
return yt_assign_db.overlay_timeslot_test_schedule(
|
||||
sched,
|
||||
test_on=True,
|
||||
test_group_id=str(cfg.get("youtube_relay_timeslot_test_group_id") or ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return yt_assign_db.overlay_timeslot_test_schedule(sched, test_on=False)
|
||||
|
||||
return await _db(_load)
|
||||
|
||||
|
||||
# ---------- YouTube stream-key registry (archive only; never touches Neko) ----------
|
||||
|
||||
|
||||
@app.get("/api/youtube/stream-keys")
|
||||
async def yt_stream_keys_list(
|
||||
include_secret: bool = Query(True),
|
||||
) -> dict[str, Any]:
|
||||
return await asyncio.to_thread(yt_stream_key_db.list_entries, include_secret=bool(include_secret))
|
||||
|
||||
|
||||
@app.get("/api/youtube/stream-keys/export")
|
||||
async def yt_stream_keys_export() -> dict[str, Any]:
|
||||
return await asyncio.to_thread(yt_stream_key_db.export_all)
|
||||
|
||||
|
||||
@app.post("/api/youtube/stream-keys")
|
||||
async def yt_stream_keys_upsert(body: YtStreamKeyEntryUpsert) -> dict[str, Any]:
|
||||
try:
|
||||
row = await asyncio.to_thread(
|
||||
yt_stream_key_db.upsert_entry,
|
||||
entry_id=body.id,
|
||||
name=body.name,
|
||||
youtube_channel_id=body.youtube_channel_id,
|
||||
channel_pk=body.channel_pk,
|
||||
assign_group_id=body.assign_group_id,
|
||||
stream_key=body.stream_key,
|
||||
note=body.note,
|
||||
sort_order=body.sort_order,
|
||||
)
|
||||
return {"ok": True, "item": row}
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/youtube/stream-keys/{entry_id}")
|
||||
async def yt_stream_keys_get(
|
||||
entry_id: str,
|
||||
include_secret: bool = Query(True),
|
||||
) -> dict[str, Any]:
|
||||
row = await asyncio.to_thread(
|
||||
yt_stream_key_db.get_entry, entry_id, include_secret=bool(include_secret)
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(404, "not found")
|
||||
return {"ok": True, "item": row}
|
||||
|
||||
|
||||
@app.delete("/api/youtube/stream-keys/{entry_id}")
|
||||
async def yt_stream_keys_delete(entry_id: str) -> dict[str, Any]:
|
||||
ok = await asyncio.to_thread(yt_stream_key_db.delete_entry, entry_id)
|
||||
if not ok:
|
||||
raise HTTPException(404, "not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/youtube/stream-keys/import-assign")
|
||||
async def yt_stream_keys_import_assign(
|
||||
body: YtStreamKeyImportAssignBody | None = None,
|
||||
) -> dict[str, Any]:
|
||||
raw = body or YtStreamKeyImportAssignBody()
|
||||
return await asyncio.to_thread(
|
||||
yt_stream_key_db.import_from_assign_groups, replace=bool(raw.replace)
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/youtube/stream-keys/import")
|
||||
async def yt_stream_keys_import(body: YtStreamKeyImportBody) -> dict[str, Any]:
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
yt_stream_key_db.import_payload,
|
||||
body.items or [],
|
||||
replace=bool(body.replace),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.post("/api/youtube/assign/groups")
|
||||
async def yt_assign_create_group(body: YtAssignGroupCreate) -> dict[str, Any]:
|
||||
try:
|
||||
@ -3068,6 +3252,12 @@ async def yt_assign_update_group(group_id: str, body: YtAssignGroupUpdate) -> di
|
||||
)
|
||||
if prev and prev.get("enabled") and not g.get("enabled"):
|
||||
await youtube_relay_pipeline.stop_group(group_id)
|
||||
# Disarm time-slot ⇒ leave 24/N like missing key — stop auto push if any.
|
||||
if prev and yt_assign_db.group_is_time_slot(prev):
|
||||
was_armed = yt_assign_db.group_time_slot_armed(prev)
|
||||
now_armed = yt_assign_db.group_time_slot_armed(g)
|
||||
if was_armed and not now_armed:
|
||||
await youtube_relay_pipeline.stop_group(group_id)
|
||||
return {"ok": True, "group": g}
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
@ -3135,7 +3325,7 @@ async def youtube_relay_exclusive_live(body: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
@app.post("/api/youtube/relay/time-slot-mode")
|
||||
async def youtube_relay_time_slot_mode(body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Toggle 时间段模式: keyed channels share 24h; source = live Douyin rooms; exclusive Neko/FFmpeg."""
|
||||
"""Toggle 时间段模式: keyed「时间段」频道平分 24h;源=监控在播抖音。不强制独占、不开自动推流。"""
|
||||
enabled = body.get("enabled")
|
||||
if enabled is None:
|
||||
enabled = body.get("on")
|
||||
@ -3144,6 +3334,29 @@ async def youtube_relay_time_slot_mode(body: dict[str, Any]) -> dict[str, Any]:
|
||||
return await youtube_relay_pipeline.set_time_slot_mode(bool(enabled))
|
||||
|
||||
|
||||
@app.post("/api/youtube/relay/timeslot-test")
|
||||
async def youtube_relay_timeslot_test(body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Toggle time_slot test mode: force one channel as winner (ignore real 24/N clock)."""
|
||||
enabled = body.get("enabled")
|
||||
if enabled is None:
|
||||
enabled = body.get("on")
|
||||
if enabled is None:
|
||||
raise HTTPException(400, "缺少 enabled")
|
||||
try:
|
||||
return await youtube_relay_pipeline.set_timeslot_test_mode(bool(enabled))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.post("/api/youtube/relay/timeslot-test/next")
|
||||
async def youtube_relay_timeslot_test_next() -> dict[str, Any]:
|
||||
"""Advance test winner to the next time_slot channel (starts auto relay + Neko/FFmpeg rotate)."""
|
||||
try:
|
||||
return await youtube_relay_pipeline.timeslot_test_next()
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/youtube/relay/process_monitor")
|
||||
async def youtube_relay_process_monitor() -> dict[str, Any]:
|
||||
"""PM2-compatible process monitor snapshot (cloud pipeline)."""
|
||||
@ -3216,8 +3429,12 @@ async def youtube_neko_status() -> dict[str, Any]:
|
||||
@app.post("/api/youtube/studio/ingest")
|
||||
@app.post("/hub/youtube/live/ingest")
|
||||
async def youtube_studio_ingest(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""Ingest from Neko live-ops Chrome extension (sh2-compatible)."""
|
||||
return await asyncio.to_thread(youtube_neko.ingest_studio_telemetry, body or {})
|
||||
"""Ingest from Neko live-ops Chrome extension (sh2-compatible).
|
||||
|
||||
Memory path is cheap; avoid default thread-pool saturation under many tabs.
|
||||
Occasional disk rewrite stays debounced inside ingest_studio_telemetry.
|
||||
"""
|
||||
return youtube_neko.ingest_studio_telemetry(body or {})
|
||||
|
||||
|
||||
@app.get("/api/youtube/studio/samples")
|
||||
@ -3242,6 +3459,25 @@ async def youtube_studio_samples(
|
||||
return {"ok": True, "count": len(rows), "samples": rows}
|
||||
|
||||
|
||||
@app.get("/api/youtube/assign/groups/{group_id}/analytics")
|
||||
async def youtube_assign_group_analytics(group_id: str, days: int = 30) -> dict[str, Any]:
|
||||
"""Per-channel live analytics: Studio sessions, daily rollup, rooms, relay pushes."""
|
||||
from . import yt_studio_db
|
||||
|
||||
data = await asyncio.to_thread(yt_studio_db.build_group_analytics, group_id, days=days)
|
||||
if not data.get("ok"):
|
||||
raise HTTPException(404 if data.get("error") == "group_not_found" else 400, data.get("error") or "error")
|
||||
return data
|
||||
|
||||
|
||||
@app.get("/api/youtube/assign/analytics/sources")
|
||||
async def youtube_assign_fleet_source_analytics(days: int = 30) -> dict[str, Any]:
|
||||
"""Fleet matrix: which Douyin room performs best on which YouTube channel (for scheduling)."""
|
||||
from . import yt_studio_db
|
||||
|
||||
return await asyncio.to_thread(yt_studio_db.build_fleet_source_matrix, days=days)
|
||||
|
||||
|
||||
@app.post("/api/youtube/neko/instances/{instance_id}/{action}")
|
||||
async def youtube_neko_instance_action(instance_id: int, action: str) -> dict[str, Any]:
|
||||
try:
|
||||
|
||||
@ -373,6 +373,8 @@ class YtAssignGroupCreate(BaseModel):
|
||||
enabled: bool = True
|
||||
# normal = 手动推流(精选); time_slot = 时间段排班推流
|
||||
category: str = "normal"
|
||||
# time_slot cards: participate in 24/N (off ≡ no stream key for schedule)
|
||||
time_slot_armed: bool = True
|
||||
|
||||
|
||||
class YtAssignGroupUpdate(BaseModel):
|
||||
@ -385,6 +387,7 @@ class YtAssignGroupUpdate(BaseModel):
|
||||
sort_order: Optional[int] = None
|
||||
neko_enabled: Optional[bool] = None
|
||||
category: Optional[str] = None
|
||||
time_slot_armed: Optional[bool] = None
|
||||
|
||||
|
||||
class YtAssignPoolAdd(BaseModel):
|
||||
@ -428,6 +431,26 @@ class YtAssignAutoFillBody(BaseModel):
|
||||
force: bool = False
|
||||
|
||||
|
||||
class YtStreamKeyEntryUpsert(BaseModel):
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
youtube_channel_id: str = ""
|
||||
channel_pk: str = ""
|
||||
assign_group_id: str = ""
|
||||
stream_key: str = ""
|
||||
note: str = ""
|
||||
sort_order: Optional[int] = None
|
||||
|
||||
|
||||
class YtStreamKeyImportBody(BaseModel):
|
||||
items: list[dict[str, Any]] = Field(default_factory=list)
|
||||
replace: bool = False
|
||||
|
||||
|
||||
class YtStreamKeyImportAssignBody(BaseModel):
|
||||
replace: bool = False
|
||||
|
||||
|
||||
class YouTubeVideoUpdate(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
|
||||
@ -130,7 +130,20 @@ def _wg_handshake_age_sec() -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
_ping_wg_cache: tuple[float, dict[str, Any]] | None = None
|
||||
_PING_WG_CACHE_TTL_SEC = 15.0
|
||||
|
||||
|
||||
def _ping_wg_peer() -> dict[str, Any]:
|
||||
global _ping_wg_cache
|
||||
import time as _time
|
||||
|
||||
now = _time.time()
|
||||
if _ping_wg_cache is not None:
|
||||
cached_at, cached = _ping_wg_cache
|
||||
if now - cached_at < _PING_WG_CACHE_TTL_SEC:
|
||||
return dict(cached)
|
||||
|
||||
if Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False:
|
||||
peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1"
|
||||
else:
|
||||
@ -143,7 +156,9 @@ def _ping_wg_peer() -> dict[str, Any]:
|
||||
m = re.search(r"time[=<]([0-9.]+)\s*ms", out)
|
||||
if m:
|
||||
rtt = m.group(1) + "ms"
|
||||
return {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]}
|
||||
result = {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]}
|
||||
_ping_wg_cache = (now, result)
|
||||
return dict(result)
|
||||
|
||||
|
||||
def wireguard_watch_status() -> dict[str, Any]:
|
||||
@ -175,16 +190,18 @@ def network_overview() -> dict[str, Any]:
|
||||
frp = frp_status()
|
||||
from . import egress_hub
|
||||
|
||||
# One ShellCrash status for this request (status() itself is also TTL-cached).
|
||||
sc = shellcrash_hub.status()
|
||||
return {
|
||||
"ok": True,
|
||||
"path_roles": path_roles(),
|
||||
"wireguard": wg,
|
||||
"frp": frp,
|
||||
"shellcrash": shellcrash_hub.status(),
|
||||
"shellcrash": sc,
|
||||
"socks": socks_status(),
|
||||
"egress": egress_hub.status(),
|
||||
"deploy_shape": _deploy_shape_hint(),
|
||||
"physical_checklist": physical_checklist(wg=wg, frp=frp),
|
||||
"physical_checklist": physical_checklist(wg=wg, frp=frp, shellcrash=sc),
|
||||
}
|
||||
|
||||
|
||||
@ -192,6 +209,7 @@ def physical_checklist(
|
||||
*,
|
||||
wg: dict[str, Any] | None = None,
|
||||
frp: dict[str, Any] | None = None,
|
||||
shellcrash: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Operator checklist — WireGuard primary, FRP auxiliary."""
|
||||
checks: list[dict[str, Any]] = []
|
||||
@ -247,7 +265,7 @@ def physical_checklist(
|
||||
f"role=auxiliary state={frp_unit.get('state') or 'n/a'} — 仅应急 SSH,不扛业务",
|
||||
)
|
||||
|
||||
sc = shellcrash_hub.status()
|
||||
sc = shellcrash if isinstance(shellcrash, dict) else shellcrash_hub.status()
|
||||
if shape.startswith("physical"):
|
||||
add(
|
||||
"shellcrash",
|
||||
|
||||
@ -16,6 +16,11 @@ from .config import settings
|
||||
|
||||
_token: str = ""
|
||||
_token_expire: float = 0
|
||||
_pb_fail_count: int = 0
|
||||
_pb_circuit_until: float = 0.0
|
||||
_PB_TIMEOUT_SEC = 6.0
|
||||
_PB_CIRCUIT_FAILS = 3
|
||||
_PB_CIRCUIT_COOLDOWN_SEC = 60.0
|
||||
|
||||
|
||||
def _pb_id(sqlite_id: str) -> str:
|
||||
@ -23,10 +28,28 @@ def _pb_id(sqlite_id: str) -> str:
|
||||
return hashlib.md5(str(sqlite_id).encode("utf-8")).hexdigest()[:15]
|
||||
|
||||
|
||||
def _pb_circuit_open() -> bool:
|
||||
return time.time() < _pb_circuit_until
|
||||
|
||||
|
||||
def _pb_note_success() -> None:
|
||||
global _pb_fail_count, _pb_circuit_until
|
||||
_pb_fail_count = 0
|
||||
_pb_circuit_until = 0.0
|
||||
|
||||
|
||||
def _pb_note_failure() -> None:
|
||||
global _pb_fail_count, _pb_circuit_until
|
||||
_pb_fail_count += 1
|
||||
if _pb_fail_count >= _PB_CIRCUIT_FAILS:
|
||||
_pb_circuit_until = time.time() + _PB_CIRCUIT_COOLDOWN_SEC
|
||||
_pb_fail_count = 0
|
||||
|
||||
|
||||
async def _client() -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(
|
||||
base_url=settings.pb_url.rstrip("/"),
|
||||
timeout=20.0,
|
||||
timeout=_PB_TIMEOUT_SEC,
|
||||
trust_env=False,
|
||||
)
|
||||
|
||||
@ -34,39 +57,58 @@ async def _client() -> httpx.AsyncClient:
|
||||
async def ensure_admin() -> None:
|
||||
global _token, _token_expire
|
||||
async with await _client() as client:
|
||||
try:
|
||||
resp = await client.post(
|
||||
"/api/collections/_superusers/auth-with-password",
|
||||
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
_token = data.get("token") or ""
|
||||
_token_expire = time.time() + 3600
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
auth_paths = (
|
||||
"/api/collections/_superusers/auth-with-password",
|
||||
"/api/admins/auth-with-password",
|
||||
)
|
||||
for path in auth_paths:
|
||||
try:
|
||||
resp = await client.post(
|
||||
path,
|
||||
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
_token = data.get("token") or ""
|
||||
_token_expire = time.time() + 3600
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
resp = await client.post(
|
||||
create_attempts = (
|
||||
(
|
||||
"/api/collections/_superusers/records",
|
||||
json={
|
||||
{
|
||||
"email": settings.pb_admin_email,
|
||||
"password": settings.pb_admin_password,
|
||||
"passwordConfirm": settings.pb_admin_password,
|
||||
},
|
||||
)
|
||||
if resp.status_code in (200, 201):
|
||||
login = await client.post(
|
||||
"/api/collections/_superusers/auth-with-password",
|
||||
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
|
||||
)
|
||||
if login.status_code == 200:
|
||||
_token = login.json().get("token") or ""
|
||||
_token_expire = time.time() + 3600
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
),
|
||||
(
|
||||
"/api/admins",
|
||||
{
|
||||
"email": settings.pb_admin_email,
|
||||
"password": settings.pb_admin_password,
|
||||
"passwordConfirm": settings.pb_admin_password,
|
||||
},
|
||||
),
|
||||
)
|
||||
for create_path, payload in create_attempts:
|
||||
try:
|
||||
resp = await client.post(create_path, json=payload)
|
||||
if resp.status_code not in (200, 201):
|
||||
continue
|
||||
for path in auth_paths:
|
||||
login = await client.post(
|
||||
path,
|
||||
json={"identity": settings.pb_admin_email, "password": settings.pb_admin_password},
|
||||
)
|
||||
if login.status_code == 200:
|
||||
_token = login.json().get("token") or ""
|
||||
_token_expire = time.time() + 3600
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
# keep previous token only if still valid; otherwise clear
|
||||
if time.time() > _token_expire:
|
||||
_token = ""
|
||||
@ -253,62 +295,75 @@ async def ensure_collections() -> dict[str, Any]:
|
||||
|
||||
|
||||
async def upsert_record(collection: str, sqlite_id: str, data: dict[str, Any]) -> Optional[str]:
|
||||
headers = await _auth_headers()
|
||||
if not headers:
|
||||
headers = await _auth_headers(force=True)
|
||||
if not headers:
|
||||
if _pb_circuit_open():
|
||||
return None
|
||||
async with await _client() as client:
|
||||
filt = f'sqlite_id="{sqlite_id}"'
|
||||
found = await client.get(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
params={"filter": filt, "perPage": 1},
|
||||
)
|
||||
if found.status_code == 401:
|
||||
try:
|
||||
headers = await _auth_headers()
|
||||
if not headers:
|
||||
headers = await _auth_headers(force=True)
|
||||
if not headers:
|
||||
return None
|
||||
if not headers:
|
||||
_pb_note_failure()
|
||||
return None
|
||||
async with await _client() as client:
|
||||
filt = f'sqlite_id="{sqlite_id}"'
|
||||
found = await client.get(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
params={"filter": filt, "perPage": 1},
|
||||
)
|
||||
body = {**data, "sqlite_id": sqlite_id}
|
||||
if found.status_code == 200 and (found.json().get("items") or []):
|
||||
rid = found.json()["items"][0]["id"]
|
||||
resp = await client.patch(
|
||||
f"/api/collections/{collection}/records/{rid}",
|
||||
if found.status_code == 401:
|
||||
headers = await _auth_headers(force=True)
|
||||
if not headers:
|
||||
_pb_note_failure()
|
||||
return None
|
||||
found = await client.get(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
params={"filter": filt, "perPage": 1},
|
||||
)
|
||||
body = {**data, "sqlite_id": sqlite_id}
|
||||
if found.status_code == 200 and (found.json().get("items") or []):
|
||||
rid = found.json()["items"][0]["id"]
|
||||
resp = await client.patch(
|
||||
f"/api/collections/{collection}/records/{rid}",
|
||||
headers=headers,
|
||||
json=body,
|
||||
)
|
||||
if resp.status_code in (200, 204):
|
||||
_pb_note_success()
|
||||
return rid
|
||||
_pb_note_failure()
|
||||
return None
|
||||
# PocketBase text PK collections require explicit id on create
|
||||
body["id"] = _pb_id(sqlite_id)
|
||||
resp = await client.post(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
json=body,
|
||||
)
|
||||
if resp.status_code in (200, 204):
|
||||
return rid
|
||||
return None
|
||||
# PocketBase text PK collections require explicit id on create
|
||||
body["id"] = _pb_id(sqlite_id)
|
||||
resp = await client.post(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
json=body,
|
||||
)
|
||||
if resp.status_code in (200, 201):
|
||||
return resp.json().get("id") or body["id"]
|
||||
# conflict: try fetch again / patch
|
||||
if resp.status_code in (400, 409):
|
||||
found2 = await client.get(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
params={"filter": filt, "perPage": 1},
|
||||
)
|
||||
if found2.status_code == 200 and (found2.json().get("items") or []):
|
||||
rid = found2.json()["items"][0]["id"]
|
||||
await client.patch(
|
||||
f"/api/collections/{collection}/records/{rid}",
|
||||
if resp.status_code in (200, 201):
|
||||
_pb_note_success()
|
||||
return resp.json().get("id") or body["id"]
|
||||
# conflict: try fetch again / patch
|
||||
if resp.status_code in (400, 409):
|
||||
found2 = await client.get(
|
||||
f"/api/collections/{collection}/records",
|
||||
headers=headers,
|
||||
json={k: v for k, v in body.items() if k != "id"},
|
||||
params={"filter": filt, "perPage": 1},
|
||||
)
|
||||
return rid
|
||||
if found2.status_code == 200 and (found2.json().get("items") or []):
|
||||
rid = found2.json()["items"][0]["id"]
|
||||
await client.patch(
|
||||
f"/api/collections/{collection}/records/{rid}",
|
||||
headers=headers,
|
||||
json={k: v for k, v in body.items() if k != "id"},
|
||||
)
|
||||
_pb_note_success()
|
||||
return rid
|
||||
_pb_note_failure()
|
||||
return None
|
||||
except Exception:
|
||||
_pb_note_failure()
|
||||
return None
|
||||
|
||||
|
||||
@ -479,7 +534,11 @@ async def delete_channel_group(sqlite_id: str) -> bool:
|
||||
|
||||
async def health() -> dict[str, Any]:
|
||||
try:
|
||||
async with await _client() as client:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=settings.pb_url.rstrip("/"),
|
||||
timeout=1.0,
|
||||
trust_env=False,
|
||||
) as client:
|
||||
resp = await client.get("/api/health")
|
||||
ok = resp.status_code == 200
|
||||
body: Any
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import quote
|
||||
@ -120,6 +121,86 @@ def delete_object(key: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def purge_covers_older_than(*, keep_days: float = 2.0, max_delete: int = 5000) -> dict[str, Any]:
|
||||
"""Delete session cover objects older than keep_days.
|
||||
|
||||
Scope: ``covers/*.jpg`` session frames only — never touches ``covers/avatars/``.
|
||||
Permanent project policy: keep at most ~2 days of cover blobs in Seaweed/S3.
|
||||
"""
|
||||
out: dict[str, Any] = {
|
||||
"ok": False,
|
||||
"enabled": s3_enabled(),
|
||||
"keep_days": float(keep_days),
|
||||
"listed": 0,
|
||||
"deleted": 0,
|
||||
"skipped_avatar": 0,
|
||||
"skipped_fresh": 0,
|
||||
"errors": 0,
|
||||
"bytes_deleted": 0,
|
||||
}
|
||||
if not s3_enabled():
|
||||
return out
|
||||
try:
|
||||
days = max(0.5, min(30.0, float(keep_days)))
|
||||
except Exception:
|
||||
days = 2.0
|
||||
out["keep_days"] = days
|
||||
cutoff = time.time() - days * 86400.0
|
||||
limit = max(1, min(20000, int(max_delete)))
|
||||
client = _client()
|
||||
bucket = settings.s3_bucket
|
||||
token: str | None = None
|
||||
try:
|
||||
while out["deleted"] < limit:
|
||||
kwargs: dict[str, Any] = {
|
||||
"Bucket": bucket,
|
||||
"Prefix": "covers/",
|
||||
"MaxKeys": 1000,
|
||||
}
|
||||
if token:
|
||||
kwargs["ContinuationToken"] = token
|
||||
resp = client.list_objects_v2(**kwargs)
|
||||
contents = resp.get("Contents") or []
|
||||
if not contents and not resp.get("IsTruncated"):
|
||||
break
|
||||
for obj in contents:
|
||||
key = str(obj.get("Key") or "")
|
||||
if not key or key.endswith("/"):
|
||||
continue
|
||||
out["listed"] += 1
|
||||
# stable room avatars — not session covers
|
||||
if key.startswith("covers/avatars/"):
|
||||
out["skipped_avatar"] += 1
|
||||
continue
|
||||
lm = obj.get("LastModified")
|
||||
try:
|
||||
ts = float(lm.timestamp()) if lm is not None else 0.0
|
||||
except Exception:
|
||||
ts = 0.0
|
||||
if ts >= cutoff:
|
||||
out["skipped_fresh"] += 1
|
||||
continue
|
||||
try:
|
||||
client.delete_object(Bucket=bucket, Key=key)
|
||||
out["deleted"] += 1
|
||||
out["bytes_deleted"] += int(obj.get("Size") or 0)
|
||||
except Exception:
|
||||
out["errors"] += 1
|
||||
if out["deleted"] >= limit:
|
||||
break
|
||||
if out["deleted"] >= limit:
|
||||
break
|
||||
if not resp.get("IsTruncated"):
|
||||
break
|
||||
token = resp.get("NextContinuationToken")
|
||||
if not token:
|
||||
break
|
||||
out["ok"] = True
|
||||
except Exception as exc:
|
||||
out["error"] = str(exc)[:240]
|
||||
return out
|
||||
|
||||
|
||||
def upload_cover(session_id: str, local_path: str | Path) -> str:
|
||||
key = f"covers/{session_id}.jpg"
|
||||
return upload_file(local_path, key, content_type="image/jpeg")
|
||||
|
||||
@ -27,6 +27,7 @@ _PUBLIC_API_PREFIXES = (
|
||||
)
|
||||
_PUBLIC_API_EXACT = {
|
||||
"/api/health",
|
||||
"/api/ping",
|
||||
"/api/shorts/oauth/callback",
|
||||
"/api/tiktok/oauth/callback/",
|
||||
"/api/tiktok/oauth/callback",
|
||||
@ -204,12 +205,9 @@ class SessionAuthMiddleware:
|
||||
if method in {"GET", "HEAD"} and path.startswith("/api/sessions/") and path.endswith("/cover"):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
# Static cover files — allow <img> without cookie (same as /api/sessions/.../cover).
|
||||
if path.startswith("/covers/"):
|
||||
if session_user_from_request(request):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
resp = JSONResponse({"detail": "未登录"}, status_code=401)
|
||||
await resp(scope, receive, send)
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
if not path.startswith("/api/"):
|
||||
|
||||
@ -15,22 +15,52 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
CONTROLLER = "http://127.0.0.1:9999"
|
||||
DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_hysteria5")
|
||||
# Physical YouTube Live egress: TUIC only (hy2 often dead). Auto-pick must NEVER
|
||||
# prefer VLESS — VLESS IP changes trigger YouTube Live channel verification popups.
|
||||
DEFAULT_NODE = os.environ.get("DY_SHELLCRASH_DEFAULT_NODE", "1d2da142-singbox_tuic5")
|
||||
DEFAULT_PROFILE = os.environ.get("DY_SHELLCRASH_DEFAULT_PROFILE", "config.yaml")
|
||||
ALLOW_VLESS_AUTOPICK = str(os.environ.get("DY_SHELLCRASH_ALLOW_VLESS", "") or "").strip().lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
"on",
|
||||
}
|
||||
# Order = preference for pick_best_node (TUIC → hy2/hysteria → optional VLESS).
|
||||
CANDIDATE_NODES = (
|
||||
"1d2da142-singbox_hysteria5",
|
||||
"1d2da142-singbox_tuic5",
|
||||
"1d2da142-VLESS_Reality_Vision5",
|
||||
"e3ea3b30-singbox_hysteria_vultr",
|
||||
"e3ea3b30-singbox_tuic_vultr",
|
||||
"242af835-singbox_hysteria",
|
||||
"hackrobot-singbox_tuic",
|
||||
"1d2da142-singbox_hysteria5",
|
||||
"e3ea3b30-singbox_hysteria_vultr",
|
||||
"242af835-singbox_hysteria",
|
||||
"1d2da142-VLESS_Reality_Vision5",
|
||||
"e3ea3b30-VLESS_Reality_Vision_vultr",
|
||||
"VLESS_Reality_Vision",
|
||||
"VLESS_Reality_Vision2",
|
||||
"socks5",
|
||||
"proxycheap",
|
||||
)
|
||||
SELECT_GROUPS = ("GLOBAL", "🚀 节点选择")
|
||||
|
||||
|
||||
def _node_family(name: str) -> str:
|
||||
u = str(name or "").upper()
|
||||
if "TUIC" in u:
|
||||
return "tuic"
|
||||
if "HYSTERIA" in u or "HY2" in u or "SINGBOX_HYSTERIA" in u:
|
||||
return "hy2"
|
||||
if "VLESS" in u:
|
||||
return "vless"
|
||||
return "other"
|
||||
|
||||
|
||||
def _family_rank(family: str) -> int:
|
||||
"""Lower = preferred for auto-pick."""
|
||||
order = {"tuic": 0, "hy2": 1, "other": 2, "vless": 9}
|
||||
if family == "vless" and not ALLOW_VLESS_AUTOPICK:
|
||||
return 100 # effectively excluded
|
||||
return order.get(family, 2)
|
||||
|
||||
MANAGED_ROOTS: dict[str, tuple[str, str]] = {
|
||||
"shellcrash-yamls": ("yamls", "YAML 配置"),
|
||||
"shellcrash-configs": ("configs", "配置文件"),
|
||||
@ -292,6 +322,11 @@ def apply_profile(rel_path: str | None = None, target_node: str | None = None) -
|
||||
"""SH2-compatible: stage YAML → config.yaml → restart → select node."""
|
||||
rel = (rel_path or DEFAULT_PROFILE).strip() or DEFAULT_PROFILE
|
||||
node = (target_node or DEFAULT_NODE).strip() or DEFAULT_NODE
|
||||
blocked_vless = False
|
||||
if _node_family(node) == "vless" and not ALLOW_VLESS_AUTOPICK:
|
||||
# Physical Live: never land on VLESS via apply_profile (YouTube channel verify).
|
||||
node = DEFAULT_NODE
|
||||
blocked_vless = True
|
||||
yamls = shellcrash_dir() / "yamls"
|
||||
yamls.mkdir(parents=True, exist_ok=True)
|
||||
source = _safe_rel(yamls, rel)
|
||||
@ -327,6 +362,7 @@ def apply_profile(rel_path: str | None = None, target_node: str | None = None) -
|
||||
"path": rel,
|
||||
"target_node": node,
|
||||
"selected": st.get("selected_node") or node,
|
||||
"blocked_vless": blocked_vless,
|
||||
"applied_groups": applied,
|
||||
"command_ok": bool(run.get("ok")),
|
||||
"shellcrash": st,
|
||||
@ -498,23 +534,64 @@ def probe_mixed(*, timeout: float = 10.0) -> dict[str, Any]:
|
||||
|
||||
|
||||
def pick_best_node(*, timeout_ms: int = 5000) -> dict[str, Any]:
|
||||
"""Pick a working egress node with TUIC > hy2 preference.
|
||||
|
||||
Never auto-selects VLESS unless DY_SHELLCRASH_ALLOW_VLESS=1 — VLESS egress
|
||||
has triggered YouTube Live verification on all physical channels.
|
||||
Does not change business DB/settings; only Clash selector now-node.
|
||||
"""
|
||||
listed = _http_json(f"{CONTROLLER}/proxies", timeout=5.0)
|
||||
if not listed.get("ok"):
|
||||
return {"ok": False, "error": listed.get("error") or "controller unreachable", "picked": None}
|
||||
proxies = (listed.get("data") or {}).get("proxies") or {}
|
||||
|
||||
# Sticky: if current selector is already an allowed healthy family, keep it.
|
||||
current = None
|
||||
try:
|
||||
current = (proxies.get("🚀 节点选择") or {}).get("now") or (proxies.get("GLOBAL") or {}).get("now")
|
||||
except Exception:
|
||||
current = None
|
||||
if current and _family_rank(_node_family(current)) < 100:
|
||||
enc = urllib.parse.quote(str(current), safe="")
|
||||
url = f"{CONTROLLER}/proxies/{enc}/delay?timeout={timeout_ms}&url=http://www.gstatic.com/generate_204"
|
||||
res = _http_json(url, timeout=(timeout_ms / 1000.0) + 3.0)
|
||||
delay = int((res.get("data") or {}).get("delay") or 0) if res.get("ok") else 0
|
||||
if delay > 0:
|
||||
egress = probe_mixed()
|
||||
if egress.get("ok"):
|
||||
return {
|
||||
"ok": True,
|
||||
"picked": current,
|
||||
"delay_ms": delay,
|
||||
"sticky": True,
|
||||
"family": _node_family(str(current)),
|
||||
"delays": [{"name": current, "delay": delay, "ok": True}],
|
||||
"applied": [],
|
||||
"egress": egress,
|
||||
}
|
||||
|
||||
delays: list[dict[str, Any]] = []
|
||||
best_name: str | None = None
|
||||
best_delay = 10**9
|
||||
best_key: tuple[int, int] | None = None # (family_rank, delay)
|
||||
for name in CANDIDATE_NODES:
|
||||
if name not in proxies:
|
||||
continue
|
||||
fam = _node_family(name)
|
||||
rank = _family_rank(fam)
|
||||
if rank >= 100:
|
||||
delays.append({"name": name, "delay": 0, "ok": False, "skipped": "vless_blocked"})
|
||||
continue
|
||||
enc = urllib.parse.quote(name, safe="")
|
||||
url = f"{CONTROLLER}/proxies/{enc}/delay?timeout={timeout_ms}&url=http://www.gstatic.com/generate_204"
|
||||
res = _http_json(url, timeout=(timeout_ms / 1000.0) + 3.0)
|
||||
delay = int((res.get("data") or {}).get("delay") or 0) if res.get("ok") else 0
|
||||
delays.append({"name": name, "delay": delay, "ok": delay > 0})
|
||||
if delay > 0 and delay < best_delay:
|
||||
best_name, best_delay = name, delay
|
||||
delays.append({"name": name, "delay": delay, "ok": delay > 0, "family": fam})
|
||||
if delay <= 0:
|
||||
continue
|
||||
key = (rank, delay)
|
||||
if best_key is None or key < best_key:
|
||||
best_key = key
|
||||
best_name = name
|
||||
applied: list[dict[str, Any]] = []
|
||||
if best_name:
|
||||
applied = _select_node_in_groups(best_name)
|
||||
@ -522,14 +599,30 @@ def pick_best_node(*, timeout_ms: int = 5000) -> dict[str, Any]:
|
||||
return {
|
||||
"ok": bool(best_name) and bool(egress.get("ok")),
|
||||
"picked": best_name,
|
||||
"delay_ms": best_delay if best_name else None,
|
||||
"delay_ms": (best_key[1] if best_key else None),
|
||||
"family": _node_family(best_name) if best_name else None,
|
||||
"allow_vless": ALLOW_VLESS_AUTOPICK,
|
||||
"delays": delays,
|
||||
"applied": applied,
|
||||
"egress": egress,
|
||||
}
|
||||
|
||||
|
||||
def status() -> dict[str, Any]:
|
||||
_STATUS_CACHE: dict[str, Any] = {"at": 0.0, "payload": None}
|
||||
_STATUS_CACHE_TTL = float(os.environ.get("DY_SHELLCRASH_STATUS_TTL", "5") or "5")
|
||||
|
||||
|
||||
def status(*, force: bool = False) -> dict[str, Any]:
|
||||
"""ShellCrash status — short TTL cache (network page used to call this 3–4×/request)."""
|
||||
now = time.time()
|
||||
cached = _STATUS_CACHE.get("payload")
|
||||
if (
|
||||
not force
|
||||
and isinstance(cached, dict)
|
||||
and now - float(_STATUS_CACHE.get("at") or 0) < _STATUS_CACHE_TTL
|
||||
):
|
||||
return dict(cached)
|
||||
|
||||
cfg_vals = _read_cfg()
|
||||
yaml = _config_yaml()
|
||||
unit_name = "shellcrash.service"
|
||||
@ -546,7 +639,7 @@ def status() -> dict[str, Any]:
|
||||
if prox.get("ok"):
|
||||
pdata = (prox.get("data") or {}).get("proxies") or {}
|
||||
selected = (pdata.get("🚀 节点选择") or {}).get("now") or (pdata.get("GLOBAL") or {}).get("now")
|
||||
return {
|
||||
out = {
|
||||
"ok": True,
|
||||
"available": yaml.get("available") or start_sh.is_file() or unit_active == "active",
|
||||
"installed": start_sh.is_file() or _unit_exists(unit_name),
|
||||
@ -559,12 +652,18 @@ def status() -> dict[str, Any]:
|
||||
"status": "online" if running else ("configured" if start_sh.is_file() or _unit_exists(unit_name) else "missing"),
|
||||
"mixed_port": mixed,
|
||||
"selected_node": selected,
|
||||
"selected_family": _node_family(str(selected or "")),
|
||||
"default_node": DEFAULT_NODE,
|
||||
"default_family": _node_family(DEFAULT_NODE),
|
||||
"allow_vless_autopick": ALLOW_VLESS_AUTOPICK,
|
||||
"default_profile": DEFAULT_PROFILE,
|
||||
"config": yaml,
|
||||
"roots": managed_roots(),
|
||||
"hint": "应用配置会写入 config.yaml 并重启;web 面板打开 mihomo UI。",
|
||||
}
|
||||
_STATUS_CACHE["at"] = now
|
||||
_STATUS_CACHE["payload"] = out
|
||||
return dict(out)
|
||||
|
||||
|
||||
def action(act: str) -> dict[str, Any]:
|
||||
@ -601,11 +700,15 @@ def action(act: str) -> dict[str, Any]:
|
||||
picked = None
|
||||
if act in {"start", "restart"}:
|
||||
time.sleep(1.0)
|
||||
# Prefer configured default node first, then pick if needed
|
||||
# Prefer configured default (TUIC). Only auto-pick among non-VLESS if default fails.
|
||||
_select_node_in_groups(DEFAULT_NODE)
|
||||
egress = probe_mixed(timeout=6.0)
|
||||
if not egress.get("ok"):
|
||||
picked = pick_best_node()
|
||||
# Never leave a restart on VLESS unless explicitly allowed.
|
||||
if picked.get("picked") and _node_family(str(picked.get("picked"))) == "vless" and not ALLOW_VLESS_AUTOPICK:
|
||||
_select_node_in_groups(DEFAULT_NODE)
|
||||
picked = {**picked, "ok": False, "blocked_vless": True, "reverted_to": DEFAULT_NODE}
|
||||
st = status()
|
||||
ok = bool(st.get("running")) if act in {"start", "restart"} else (not st.get("running") if act == "stop" else True)
|
||||
return {
|
||||
|
||||
@ -2,10 +2,17 @@
|
||||
"""Isolated Shorts pipeline — optional side path, never blocks Douyin monitor.
|
||||
|
||||
Enable only via settings.shorts_enabled=True.
|
||||
|
||||
Live-clip upload rules:
|
||||
1. Different channels MAY share one Douyin live room; each gets a distinct
|
||||
clip_offset window (0–15s / 15–30s / …) so materials are never identical.
|
||||
2. Same channel cannot reuse the same room twice per Beijing day.
|
||||
3. Same channel uploads spaced >10 minutes (hard floor).
|
||||
4. Within Beijing calendar day, aggressively fill until daily_min is met.
|
||||
|
||||
- On-live edge enqueue (optional)
|
||||
- Random sample from currently-live rooms (default on)
|
||||
Same room is only used once per Beijing day per channel pool.
|
||||
All public entrypoints swallow exceptions so callers (monitor) stay safe.
|
||||
- Quota fill toward daily_min first, then daily_max
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@ -20,9 +27,9 @@ from .shorts_upload import is_upload_quota_error, quota_error_message, upload_sh
|
||||
from .shorts_socks import resolve_upload_socks_proxy
|
||||
from .shorts_yt_quota import (
|
||||
any_profile_uploads_available,
|
||||
blocked_profile_ids,
|
||||
clear_all_upload_self_blocks,
|
||||
clear_stale_quota_errors_for_open_profiles,
|
||||
pause_uploads_until_reset,
|
||||
profile_id_for_channel,
|
||||
profile_id_for_job,
|
||||
quota_budgets_by_profile,
|
||||
@ -30,7 +37,8 @@ from .shorts_yt_quota import (
|
||||
yt_upload_budget,
|
||||
)
|
||||
from .timeutil import push_date_from_ts
|
||||
|
||||
from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota
|
||||
from .shorts_schedule import CHANNEL_GAP_FLOOR_SEC
|
||||
|
||||
def _room_tags(room: dict[str, Any]) -> list[str]:
|
||||
tags = room.get("tags") or []
|
||||
@ -52,6 +60,112 @@ def _room_eligible(room: dict[str, Any], cfg: dict[str, Any]) -> bool:
|
||||
return tag in tags or "shorts" in tags or "both" in tags
|
||||
|
||||
|
||||
def _is_offline_stream_error(err: str) -> bool:
|
||||
e = str(err or "")
|
||||
low = e.lower()
|
||||
if "无法获取直播流" in e or "已停播" in e:
|
||||
return True
|
||||
if "probe 404" in low or "server returned 404" in low:
|
||||
return True
|
||||
if "connection timed out" in low and ("opening input" in low or "http" in low):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _live_room_map() -> dict[str, dict[str, Any]]:
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
for r in db.list_live_douyin_rooms_for_shorts(limit=500):
|
||||
rid = str(r.get("room_id") or "").strip()
|
||||
if rid:
|
||||
out[rid] = r
|
||||
except Exception:
|
||||
return {}
|
||||
return out
|
||||
|
||||
|
||||
def _try_rebind_shorts_job_to_live(job: dict[str, Any], cfg: dict[str, Any] | None = None) -> bool:
|
||||
"""If job's room is offline, point it at another live room for the same channel."""
|
||||
jid = str(job.get("id") or "")
|
||||
ch_id = str(job.get("channel_pk") or "")
|
||||
day = str(job.get("push_date") or push_date_from_ts(time.time()))
|
||||
old_rid = str(job.get("room_id") or "")
|
||||
if not jid or not ch_id:
|
||||
return False
|
||||
live = _live_room_map()
|
||||
if old_rid and old_rid in live:
|
||||
return False
|
||||
settings = cfg or db.get_settings_map()
|
||||
clip_sec = int(settings.get("shorts_clip_sec") or 15)
|
||||
for room in live.values():
|
||||
new_rid = str(room.get("room_id") or "")
|
||||
if not new_rid or new_rid == old_rid:
|
||||
continue
|
||||
if db.has_shorts_job_for_room_day(new_rid, day, ch_id):
|
||||
continue
|
||||
try:
|
||||
clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts")
|
||||
except Exception:
|
||||
pass
|
||||
offset = db.next_shorts_room_clip_offset(new_rid, day, clip_sec=clip_sec)
|
||||
sid = str(room.get("active_session_id") or "")
|
||||
session = db.get_session(sid) if sid else None
|
||||
db.update_shorts_job(
|
||||
jid,
|
||||
status="pending",
|
||||
room_id=new_rid,
|
||||
room_pk=str(room.get("id") or ""),
|
||||
session_id=sid,
|
||||
source_url=str((session or {}).get("source_url") or room.get("url") or ""),
|
||||
anchor_name=str(
|
||||
(session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or ""
|
||||
),
|
||||
stream_url="",
|
||||
clip_path="",
|
||||
clip_seconds=0,
|
||||
clip_offset_sec=offset,
|
||||
error="原直播间已停播,已换源重录",
|
||||
finished_at=0,
|
||||
upload_at=0,
|
||||
youtube_video_id="",
|
||||
youtube_url="",
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _skip_offline_shorts_job(job: dict[str, Any], *, reason: str = "直播间已停播,已释放当日名额") -> None:
|
||||
db.update_shorts_job(
|
||||
str(job["id"]),
|
||||
status="skipped",
|
||||
error=reason,
|
||||
stream_url="",
|
||||
clip_path="",
|
||||
finished_at=time.time(),
|
||||
upload_at=0,
|
||||
)
|
||||
|
||||
|
||||
def skip_or_rebind_offline_pending(cfg: dict[str, Any] | None = None, *, limit: int = 40) -> dict[str, int]:
|
||||
"""Pending jobs whose rooms left live map → rebind or skip (free pipeline)."""
|
||||
settings = cfg or db.get_settings_map()
|
||||
day = push_date_from_ts(time.time())
|
||||
live = _live_room_map()
|
||||
data = db.list_shorts_jobs(push_date=day, status="pending", limit=max(1, min(limit, 120)), offset=0)
|
||||
rebound = 0
|
||||
skipped = 0
|
||||
for job in data.get("jobs") or []:
|
||||
rid = str(job.get("room_id") or "")
|
||||
if rid and rid in live:
|
||||
continue
|
||||
if _try_rebind_shorts_job_to_live(job, settings):
|
||||
rebound += 1
|
||||
else:
|
||||
_skip_offline_shorts_job(job)
|
||||
skipped += 1
|
||||
return {"rebound": rebound, "skipped": skipped}
|
||||
|
||||
|
||||
def _enqueue_job(
|
||||
*,
|
||||
session: dict[str, Any] | None,
|
||||
@ -72,8 +186,10 @@ def _enqueue_job(
|
||||
if room_id.startswith("yt:"):
|
||||
return None
|
||||
day = str(push_date or "").strip() or push_date_from_ts(time.time())
|
||||
# Global dedup: same room_id can only be enqueued ONCE per Beijing day across ALL channels
|
||||
if settings.get("shorts_dedupe_room_day", True) and room_id:
|
||||
# Legacy global room-day lock (off by default). Prefer channel-scoped uniqueness
|
||||
# so multiple channels can share one live room with distinct clip offsets.
|
||||
dedupe_global = bool(settings.get("shorts_dedupe_room_day", False))
|
||||
if dedupe_global and room_id:
|
||||
if db.has_shorts_job_for_room_day(room_id, day):
|
||||
return None
|
||||
channel: dict[str, Any] | None = None
|
||||
@ -81,13 +197,29 @@ def _enqueue_job(
|
||||
ch = db.get_shorts_channel(channel_pk)
|
||||
if ch and ch.get("enabled"):
|
||||
used = db.shorts_channel_upload_count(channel_pk, day)
|
||||
daily_max = db.SHORTS_DAILY_FORCE
|
||||
if used < daily_max:
|
||||
uploaded = db.shorts_channel_uploaded_count(channel_pk, day)
|
||||
daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||||
daily_min = _normalize_daily_quota(ch.get("daily_min"), default=SHORTS_DAILY_FORCE)
|
||||
if daily_max < daily_min:
|
||||
daily_max = daily_min
|
||||
if used < daily_max and uploaded < daily_max:
|
||||
channel = ch
|
||||
if not channel:
|
||||
channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota)
|
||||
if require_channel and not channel:
|
||||
return None
|
||||
# Same channel + same room today → skip (create_shorts_job also enforces).
|
||||
ch_id = str((channel or {}).get("id") or "")
|
||||
if room_id and ch_id and not dedupe_global and db.has_shorts_job_for_room_day(room_id, day, ch_id):
|
||||
return None
|
||||
clip_sec = int(settings.get("shorts_clip_sec") or 15)
|
||||
try:
|
||||
clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts")
|
||||
except Exception:
|
||||
pass
|
||||
offset = 0
|
||||
if room_id and not dedupe_global:
|
||||
offset = db.next_shorts_room_clip_offset(room_id, day, clip_sec=clip_sec)
|
||||
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
|
||||
job = db.create_shorts_job(
|
||||
session_id=sid,
|
||||
@ -98,8 +230,10 @@ def _enqueue_job(
|
||||
(session or {}).get("anchor_name") or room.get("last_anchor") or room.get("last_title") or ""
|
||||
),
|
||||
stream_url=str(stream_url or ""),
|
||||
channel_pk=str((channel or {}).get("id") or ""),
|
||||
channel_pk=ch_id,
|
||||
push_date=day,
|
||||
clip_offset_sec=offset,
|
||||
dedupe_room_global=dedupe_global,
|
||||
)
|
||||
if not job:
|
||||
return None
|
||||
@ -140,7 +274,8 @@ def try_enqueue_on_live(
|
||||
|
||||
|
||||
def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
||||
"""Pick random currently-live rooms and enqueue (dedupe room/day). Returns enqueued count."""
|
||||
"""Pick currently-live rooms and enqueue. Same room may feed multiple channels
|
||||
with distinct clip offsets unless shorts_dedupe_room_day is on."""
|
||||
try:
|
||||
settings = cfg or db.get_settings_map()
|
||||
if not settings.get("shorts_enabled"):
|
||||
@ -152,7 +287,8 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
||||
return 0
|
||||
batch = max(1, min(int(settings.get("shorts_live_sample_batch") or 1), 5))
|
||||
any_live = settings.get("shorts_sample_any_live", True)
|
||||
used = db.room_ids_with_shorts_job_today(day)
|
||||
dedupe_global = bool(settings.get("shorts_dedupe_room_day", False))
|
||||
used = db.room_ids_with_shorts_job_today(day) if dedupe_global else set()
|
||||
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
|
||||
candidates: list[dict[str, Any]] = []
|
||||
for room in rooms:
|
||||
@ -165,16 +301,27 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int:
|
||||
candidates.append(room)
|
||||
if not candidates:
|
||||
return 0
|
||||
random.shuffle(candidates)
|
||||
# Prefer rooms with fewer Shorts jobs today (still allow reuse when not global-dedupe).
|
||||
if not dedupe_global:
|
||||
candidates.sort(
|
||||
key=lambda r: db.has_shorts_job_for_room_day(str(r.get("room_id") or ""), day)
|
||||
and 1
|
||||
or 0
|
||||
)
|
||||
random.shuffle(candidates)
|
||||
else:
|
||||
random.shuffle(candidates)
|
||||
enqueued = 0
|
||||
for room in candidates[:batch]:
|
||||
for room in candidates[: max(batch * 3, batch)]:
|
||||
if enqueued >= batch:
|
||||
break
|
||||
sid = str(room.get("active_session_id") or "")
|
||||
session = db.get_session(sid) if sid else None
|
||||
job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings)
|
||||
if job:
|
||||
enqueued += 1
|
||||
used.add(str(room.get("room_id") or ""))
|
||||
# stop if channel full after this assign
|
||||
if dedupe_global:
|
||||
used.add(str(room.get("room_id") or ""))
|
||||
if not db.pick_shorts_channel(day, settings):
|
||||
break
|
||||
return enqueued
|
||||
@ -210,7 +357,7 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
continue
|
||||
if not any_live and not _room_eligible(room, settings):
|
||||
continue
|
||||
if settings.get("shorts_dedupe_room_day", True) and db.has_shorts_job_for_room_day(rid, day):
|
||||
if settings.get("shorts_dedupe_room_day", False) and db.has_shorts_job_for_room_day(rid, day):
|
||||
skipped += 1
|
||||
continue
|
||||
unused.append(room)
|
||||
@ -245,7 +392,12 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
|
||||
"""Enqueue live-room clips toward each channel's daily_max before Beijing midnight."""
|
||||
"""Enqueue live-room clips toward daily_min first, then daily_max (Beijing day).
|
||||
|
||||
Same live room may be shared across channels; each job gets a distinct clip_offset
|
||||
(0–15s / 15–30s / …) so materials are never identical. Prefer rooms with fewer
|
||||
jobs today for diversity. When behind daily_min, raise batch size.
|
||||
"""
|
||||
try:
|
||||
settings = cfg or db.get_settings_map()
|
||||
if not settings.get("shorts_enabled"):
|
||||
@ -253,8 +405,10 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
|
||||
if not any_profile_uploads_available(settings):
|
||||
return 0
|
||||
day = push_date_from_ts(time.time())
|
||||
gap_total = db.shorts_total_quota_gap(day)
|
||||
if gap_total <= 0:
|
||||
summary = db.shorts_channels_quota_summary(day)
|
||||
under_min = [r for r in summary if not r.get("min_met") and int(r.get("gap") or 0) > 0]
|
||||
need_any = [r for r in summary if int(r.get("gap") or 0) > 0]
|
||||
if not need_any:
|
||||
return 0
|
||||
if not db.pick_shorts_channel(day, settings):
|
||||
return 0
|
||||
@ -264,21 +418,27 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
|
||||
day_start, day_end = beijing_day_bounds(day)
|
||||
now = time.time()
|
||||
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
|
||||
gap_total = sum(int(r.get("gap") or 0) for r in need_any)
|
||||
min_gap = sum(max(0, int(r.get("daily_min") or 0) - int(r.get("used") or 0)) for r in under_min)
|
||||
|
||||
base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 9))
|
||||
if day_progress > 0.55:
|
||||
base_batch = max(base_batch, min(gap_total, 6))
|
||||
if day_progress > 0.75:
|
||||
base_batch = max(base_batch, min(gap_total, 10))
|
||||
if day_progress > 0.88:
|
||||
base_batch = max(base_batch, min(gap_total, 16))
|
||||
if under_min:
|
||||
base_batch = max(base_batch, min(max(min_gap, len(under_min)), 12))
|
||||
if day_progress > 0.45 and under_min:
|
||||
base_batch = max(base_batch, min(gap_total, max(8, min_gap)))
|
||||
if day_progress > 0.7:
|
||||
base_batch = max(base_batch, min(gap_total, 14))
|
||||
if day_progress > 0.85 or (day_progress > 0.6 and under_min):
|
||||
base_batch = max(base_batch, min(gap_total, 20))
|
||||
|
||||
any_live = settings.get("shorts_sample_any_live", True)
|
||||
used = db.room_ids_with_shorts_job_today(day)
|
||||
dedupe_global = bool(settings.get("shorts_dedupe_room_day", False))
|
||||
used_rooms = db.room_ids_with_shorts_job_today(day) if dedupe_global else set()
|
||||
rooms = db.list_live_douyin_rooms_for_shorts(limit=400)
|
||||
candidates: list[dict[str, Any]] = []
|
||||
for room in rooms:
|
||||
rid = str(room.get("room_id") or "")
|
||||
if not rid or rid in used:
|
||||
if not rid or rid in used_rooms:
|
||||
continue
|
||||
if not any_live and not _room_eligible(room, settings):
|
||||
continue
|
||||
@ -286,20 +446,71 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
|
||||
candidates.append(room)
|
||||
if not candidates:
|
||||
return 0
|
||||
random.shuffle(candidates)
|
||||
# Prefer less-used rooms first, then shuffle within similar load.
|
||||
if not dedupe_global:
|
||||
candidates.sort(
|
||||
key=lambda r: (
|
||||
1 if db.has_shorts_job_for_room_day(str(r.get("room_id") or ""), day) else 0,
|
||||
random.random(),
|
||||
)
|
||||
)
|
||||
else:
|
||||
random.shuffle(candidates)
|
||||
|
||||
target_ids = [str(r["id"]) for r in under_min] + [
|
||||
str(r["id"]) for r in need_any if r.get("min_met")
|
||||
]
|
||||
if not target_ids:
|
||||
return 0
|
||||
|
||||
enqueued = 0
|
||||
for room in candidates:
|
||||
if enqueued >= base_batch:
|
||||
break
|
||||
if not db.pick_shorts_channel(day, settings):
|
||||
break
|
||||
sid = str(room.get("active_session_id") or "")
|
||||
session = db.get_session(sid) if sid else None
|
||||
job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings)
|
||||
if job:
|
||||
enqueued += 1
|
||||
used.add(str(room.get("room_id") or ""))
|
||||
ti = 0
|
||||
# Allow cycling the same live rooms across channels (distinct offsets).
|
||||
room_cycle = list(candidates)
|
||||
if not room_cycle:
|
||||
return 0
|
||||
attempts = 0
|
||||
max_attempts = max(base_batch * 4, len(target_ids) * 2)
|
||||
while enqueued < base_batch and attempts < max_attempts:
|
||||
attempts += 1
|
||||
room = room_cycle[(attempts - 1) % len(room_cycle)]
|
||||
rid = str(room.get("room_id") or "")
|
||||
assigned = False
|
||||
for _ in range(len(target_ids)):
|
||||
tid = target_ids[ti % len(target_ids)]
|
||||
ti += 1
|
||||
ch = db.get_shorts_channel(tid)
|
||||
if not ch or not ch.get("enabled"):
|
||||
continue
|
||||
used = db.shorts_channel_upload_count(tid, day)
|
||||
uploaded = db.shorts_channel_uploaded_count(tid, day)
|
||||
daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||||
if used >= daily_max or uploaded >= daily_max:
|
||||
continue
|
||||
if rid and db.has_shorts_job_for_room_day(rid, day, tid):
|
||||
continue
|
||||
from .shorts_yt_quota import profile_id_for_channel, project_uploads_available
|
||||
|
||||
if not project_uploads_available(settings, profile_id=profile_id_for_channel(ch)):
|
||||
continue
|
||||
sid = str(room.get("active_session_id") or "")
|
||||
session = db.get_session(sid) if sid else None
|
||||
job = _enqueue_job(
|
||||
session=session,
|
||||
room=room,
|
||||
stream_url="",
|
||||
cfg=settings,
|
||||
channel_pk=tid,
|
||||
)
|
||||
if job:
|
||||
enqueued += 1
|
||||
if dedupe_global:
|
||||
used_rooms.add(rid)
|
||||
assigned = True
|
||||
break
|
||||
if not assigned and dedupe_global:
|
||||
# Exhausted unique rooms under legacy mode.
|
||||
continue
|
||||
return enqueued
|
||||
except Exception:
|
||||
return 0
|
||||
@ -460,16 +671,41 @@ class ShortsPipeline:
|
||||
continue
|
||||
return n
|
||||
|
||||
@staticmethod
|
||||
def _end_of_day_catchup(cfg: dict[str, Any] | None = None) -> bool:
|
||||
try:
|
||||
from .shorts_schedule import fleet_pace_plan
|
||||
|
||||
plan = fleet_pace_plan(cfg=cfg)
|
||||
if plan.get("behind") or plan.get("urgent"):
|
||||
return True
|
||||
from .timeutil import beijing_day_bounds
|
||||
|
||||
day = push_date_from_ts(time.time())
|
||||
_, day_end = beijing_day_bounds(day)
|
||||
if day_end - time.time() > 2400:
|
||||
return False
|
||||
return db.shorts_total_quota_gap(day) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _upload_max(cfg: dict[str, Any]) -> int:
|
||||
explicit = int(cfg.get("shorts_upload_max_concurrent") or 0)
|
||||
if explicit > 0:
|
||||
return max(1, min(explicit, 5))
|
||||
return max(2, int(cfg.get("shorts_max_concurrent") or 1))
|
||||
base = max(1, min(explicit, 5))
|
||||
else:
|
||||
base = max(2, int(cfg.get("shorts_max_concurrent") or 1))
|
||||
if ShortsPipeline._end_of_day_catchup(cfg):
|
||||
return min(5, max(base, 4))
|
||||
return base
|
||||
|
||||
@staticmethod
|
||||
def _record_max(cfg: dict[str, Any]) -> int:
|
||||
return max(1, int(cfg.get("shorts_max_concurrent") or 1))
|
||||
base = max(1, int(cfg.get("shorts_max_concurrent") or 1))
|
||||
if ShortsPipeline._end_of_day_catchup(cfg):
|
||||
return min(8, max(base, 5))
|
||||
return base
|
||||
|
||||
def status(self) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
@ -530,6 +766,8 @@ class ShortsPipeline:
|
||||
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
|
||||
yt_by_profile = quota_budgets_by_profile(cfg)
|
||||
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
|
||||
cool_profiles = [r for r in yt_by_profile if r.get("blocked")]
|
||||
cool_until = max((float(r.get("blocked_until") or 0) for r in cool_profiles), default=0)
|
||||
try:
|
||||
from . import douyin_live
|
||||
|
||||
@ -564,12 +802,18 @@ class ShortsPipeline:
|
||||
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
|
||||
"quota_gap": db.shorts_total_quota_gap(),
|
||||
"quota_defaults": db.shorts_quota_defaults(cfg),
|
||||
# Informational only — never gates manual/worker uploads
|
||||
"upload_quota_blocked": False,
|
||||
"upload_quota_blocked_until": 0,
|
||||
"upload_quota_blocked_profiles": [],
|
||||
# API cool-down only (real YouTube 429) — manual upload never gated
|
||||
"upload_quota_blocked": bool(cool_profiles),
|
||||
"upload_quota_blocked_until": cool_until,
|
||||
"upload_quota_blocked_profiles": [str(r.get("id") or "") for r in cool_profiles],
|
||||
"yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted],
|
||||
"yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0),
|
||||
"yt_quota_reset_at": max(
|
||||
(float(r.get("reset_at") or 0) for r in exhausted),
|
||||
default=0,
|
||||
),
|
||||
"yt_quota_cooldown_sec": int(
|
||||
float(cfg.get("shorts_yt_quota_cooldown_sec") or 3600)
|
||||
),
|
||||
"yt_upload_limit": yt_limit,
|
||||
"yt_upload_used": yt_used,
|
||||
"yt_upload_remaining": yt_remaining,
|
||||
@ -581,8 +825,8 @@ class ShortsPipeline:
|
||||
"douyin_live_count": live_count,
|
||||
"douyin_live_rooms": live_rooms,
|
||||
"upload_spread": bool(cfg.get("shorts_upload_spread", True)),
|
||||
"upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or 720),
|
||||
"channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or 2400),
|
||||
"upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC),
|
||||
"channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC),
|
||||
"max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)),
|
||||
"upload_max_concurrent": self._upload_max(cfg),
|
||||
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)),
|
||||
@ -594,6 +838,20 @@ class ShortsPipeline:
|
||||
"heatmap": heatmap,
|
||||
"oauth_issues": oauth_issues,
|
||||
}
|
||||
try:
|
||||
from .shorts_schedule import fleet_pace_plan
|
||||
|
||||
pace = fleet_pace_plan(cfg=cfg)
|
||||
payload["pace"] = pace
|
||||
if pace.get("behind") or pace.get("urgent"):
|
||||
payload["upload_min_gap_sec"] = float(
|
||||
pace.get("recommended_global_gap_sec") or payload["upload_min_gap_sec"]
|
||||
)
|
||||
payload["channel_min_gap_sec"] = float(
|
||||
pace.get("recommended_channel_gap_sec") or payload["channel_min_gap_sec"]
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
self._status_cache = payload
|
||||
self._status_cache_at = time.time()
|
||||
return payload
|
||||
@ -640,6 +898,8 @@ class ShortsPipeline:
|
||||
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
|
||||
yt_by_profile = quota_budgets_by_profile(cfg)
|
||||
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
|
||||
cool_profiles = [r for r in yt_by_profile if r.get("blocked")]
|
||||
cool_until = max((float(r.get("blocked_until") or 0) for r in cool_profiles), default=0)
|
||||
payload = {
|
||||
"running": bool(self._task and not self._task.done()),
|
||||
"busy": self._active_records > 0 or self._active_uploads > 0,
|
||||
@ -652,9 +912,12 @@ class ShortsPipeline:
|
||||
"quota_filled": self.quota_filled,
|
||||
"auto_retried": self.auto_retried,
|
||||
"quota_gap": db.shorts_total_quota_gap(),
|
||||
"upload_quota_blocked": False,
|
||||
"upload_quota_blocked": bool(cool_profiles),
|
||||
"upload_quota_blocked_until": cool_until,
|
||||
"upload_quota_blocked_profiles": [str(r.get("id") or "") for r in cool_profiles],
|
||||
"yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted],
|
||||
"yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0),
|
||||
"yt_quota_cooldown_sec": int(float(cfg.get("shorts_yt_quota_cooldown_sec") or 3600)),
|
||||
"yt_upload_limit": yt_limit,
|
||||
"yt_upload_used": yt_used,
|
||||
"yt_upload_remaining": yt_remaining,
|
||||
@ -744,6 +1007,20 @@ class ShortsPipeline:
|
||||
|
||||
quota_interval = float(cfg.get("shorts_quota_fill_interval_sec") or 120)
|
||||
quota_interval = max(60.0, quota_interval)
|
||||
try:
|
||||
day_now = push_date_from_ts(time.time())
|
||||
under = [r for r in db.shorts_channels_quota_summary(day_now) if not r.get("min_met")]
|
||||
if under:
|
||||
# Behind daily_min: fill more often so Beijing-day minimum is reachable.
|
||||
quota_interval = min(quota_interval, 60.0)
|
||||
from .timeutil import beijing_day_bounds
|
||||
|
||||
ds, de = beijing_day_bounds(day_now)
|
||||
prog = max(0.0, min(1.0, (time.time() - ds) / max(1.0, de - ds)))
|
||||
if prog > 0.7:
|
||||
quota_interval = 45.0
|
||||
except Exception:
|
||||
pass
|
||||
if (time.time() - self._last_quota_fill_at) >= quota_interval:
|
||||
self._last_quota_fill_at = time.time()
|
||||
qn = try_fill_daily_quota(cfg)
|
||||
@ -776,6 +1053,17 @@ class ShortsPipeline:
|
||||
self._backfill_schedules(cfg)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from .shorts_schedule import pull_forward_due_uploads
|
||||
|
||||
if pull_forward_due_uploads(cfg):
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
skip_or_rebind_offline_pending(cfg, limit=60)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
n = db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0)
|
||||
@ -803,8 +1091,9 @@ class ShortsPipeline:
|
||||
job: dict[str, Any] | None = None
|
||||
runner: str = ""
|
||||
if self._active_uploads < upload_max:
|
||||
# Never skip profiles for local quota — YouTube API decides
|
||||
job = db.claim_due_shorts_upload(skip_profile_ids=None)
|
||||
# Skip Clients in YouTube-API cool-down (manual upload still allowed).
|
||||
skip = blocked_profile_ids(cfg)
|
||||
job = db.claim_due_shorts_upload(skip_profile_ids=skip or None)
|
||||
if job:
|
||||
runner = "upload"
|
||||
if not job and self._active_records < record_max:
|
||||
@ -937,10 +1226,22 @@ class ShortsPipeline:
|
||||
pass
|
||||
|
||||
def _record_quota_api_feedback(self, job: dict[str, Any], raw_error: str) -> None:
|
||||
"""Surface YouTube 429 on the job only — never self-pause the Client."""
|
||||
"""On real YouTube 429: cool down this Client's auto-uploads; ntfy at most once per window."""
|
||||
from .shorts_yt_quota import defer_profile_shorts_uploads, mark_api_quota_cooldown
|
||||
|
||||
pid = profile_id_for_job(job)
|
||||
# Keep local counter in sync for UI; do not set blocked_until / defer siblings
|
||||
pause_uploads_until_reset(profile_id=pid, reason="")
|
||||
until, should_notify = mark_api_quota_cooldown(
|
||||
profile_id=pid,
|
||||
reason=str(raw_error or "")[:160],
|
||||
)
|
||||
try:
|
||||
defer_profile_shorts_uploads(
|
||||
pid,
|
||||
until,
|
||||
reason=f"Client {pid} 接口配额冷静至北京时间后重试",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from . import yt_long_db
|
||||
|
||||
@ -950,7 +1251,6 @@ class ShortsPipeline:
|
||||
except Exception:
|
||||
pass
|
||||
friendly = quota_error_message(pid)
|
||||
# Prefer raw API body when present so operators see the real interface reply
|
||||
api_snip = (raw_error or "").strip()
|
||||
if api_snip and api_snip != friendly:
|
||||
err_text = f"{friendly} | 接口:{api_snip[:280]}"
|
||||
@ -965,13 +1265,22 @@ class ShortsPipeline:
|
||||
finished_at=time.time(),
|
||||
)
|
||||
self.last_error = err_text[:300]
|
||||
self._emit_shorts_event(
|
||||
kind="shorts_quota",
|
||||
level="warn",
|
||||
message=f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传)",
|
||||
job=job,
|
||||
extra={"error": raw_error[:200], "oauth_profile_id": pid},
|
||||
)
|
||||
if should_notify:
|
||||
left_min = max(1, int((until - time.time()) / 60))
|
||||
self._emit_shorts_event(
|
||||
kind="shorts_quota",
|
||||
level="warn",
|
||||
message=(
|
||||
f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传);"
|
||||
f"自动上传冷静约 {left_min} 分钟后再试"
|
||||
),
|
||||
job=job,
|
||||
extra={
|
||||
"error": raw_error[:200],
|
||||
"oauth_profile_id": pid,
|
||||
"cool_until": until,
|
||||
},
|
||||
)
|
||||
|
||||
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
|
||||
"""Return True if handled as YouTube quota API feedback (no local pause)."""
|
||||
@ -1167,6 +1476,24 @@ class ShortsPipeline:
|
||||
|
||||
async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None:
|
||||
jid = str(job["id"])
|
||||
# Shared clips disk with yt-long — refuse record when critically low (no setting change).
|
||||
try:
|
||||
from .clip_retention import disk_ok_for_record, purge_stale_clips
|
||||
|
||||
ok_disk, free_gb = disk_ok_for_record(cfg)
|
||||
if not ok_disk:
|
||||
purge_stale_clips(cfg)
|
||||
ok_disk, free_gb = disk_ok_for_record(cfg)
|
||||
if not ok_disk:
|
||||
db.update_shorts_job(
|
||||
jid,
|
||||
status="pending",
|
||||
error=f"disk_low:{free_gb:.1f}GB",
|
||||
started_at=0,
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
# Isolated companion: enqueue 9:16 long-form master (never raises into Shorts).
|
||||
try:
|
||||
from .yt_long_pipeline import try_enqueue_from_shorts
|
||||
@ -1184,6 +1511,14 @@ class ShortsPipeline:
|
||||
)
|
||||
stream = candidates[0] if candidates else ""
|
||||
if not stream:
|
||||
# Room already offline → rebind to another live source or free the slot.
|
||||
if _try_rebind_shorts_job_to_live(job, cfg):
|
||||
return
|
||||
live = _live_room_map()
|
||||
rid = str(job.get("room_id") or "")
|
||||
if rid and rid not in live:
|
||||
_skip_offline_shorts_job(job)
|
||||
return
|
||||
err = str(job.get("error") or "")
|
||||
if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900:
|
||||
db.update_shorts_job(
|
||||
@ -1193,19 +1528,8 @@ class ShortsPipeline:
|
||||
stream_url="",
|
||||
)
|
||||
return
|
||||
db.update_shorts_job(
|
||||
jid,
|
||||
status="failed",
|
||||
error="无法获取直播流(可能已停播)",
|
||||
finished_at=time.time(),
|
||||
)
|
||||
self._emit_shorts_event(
|
||||
kind="shorts_fail",
|
||||
level="error",
|
||||
message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — 无法获取直播流",
|
||||
job=job,
|
||||
extra={"error": "无法获取直播流(可能已停播)"},
|
||||
)
|
||||
# Still listed live but no playable URL — free slot, don't keep failing.
|
||||
_skip_offline_shorts_job(job, reason="无法解析直播流,已释放当日名额")
|
||||
return
|
||||
sec = int(cfg.get("shorts_clip_sec") or 15)
|
||||
try:
|
||||
@ -1220,10 +1544,34 @@ class ShortsPipeline:
|
||||
sec = db.room_clip_seconds(room, default=sec, platform="shorts")
|
||||
except Exception:
|
||||
pass
|
||||
# Distinct live window relative to job create time:
|
||||
# offset 0 → capture immediately; 15 → wait until t0+15s; 30 → t0+30s …
|
||||
# So A/B/C from the same room never get the identical live segment.
|
||||
try:
|
||||
offset = max(0.0, float(job.get("clip_offset_sec") or 0))
|
||||
except (TypeError, ValueError):
|
||||
offset = 0.0
|
||||
if offset > 0:
|
||||
try:
|
||||
created = float(job.get("created_at") or time.time())
|
||||
except (TypeError, ValueError):
|
||||
created = time.time()
|
||||
delay = max(0.0, (created + offset) - time.time())
|
||||
delay = min(delay, float(15 * 20))
|
||||
if delay > 0.5:
|
||||
await asyncio.sleep(delay)
|
||||
outcome = await record_clip(job_id=jid, stream_urls=candidates, seconds=sec)
|
||||
stream = str(outcome.get("stream_url") or stream)
|
||||
if not outcome.get("ok"):
|
||||
err = str(outcome.get("error") or "录制失败")
|
||||
if _is_offline_stream_error(err):
|
||||
if _try_rebind_shorts_job_to_live(job, cfg):
|
||||
return
|
||||
live = _live_room_map()
|
||||
rid = str(job.get("room_id") or "")
|
||||
if not rid or rid not in live:
|
||||
_skip_offline_shorts_job(job, reason=f"直播流失效已停播,已释放名额({err[:80]})")
|
||||
return
|
||||
db.update_shorts_job(
|
||||
jid,
|
||||
status="failed",
|
||||
@ -1236,7 +1584,7 @@ class ShortsPipeline:
|
||||
level="error",
|
||||
message=f"Shorts 录制失败:{job.get('anchor_name') or job.get('room_id') or jid} — {err[:80]}",
|
||||
job=job,
|
||||
extra={"error": err},
|
||||
extra={"error": err[:200]},
|
||||
)
|
||||
return
|
||||
clip_path = str(outcome.get("path") or "")
|
||||
|
||||
@ -1,7 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Irregular 24h upload scheduling — avoid dense / metronomic YouTube uploads."""
|
||||
"""Irregular upload scheduling — meet Beijing-day quota without metronomic spam.
|
||||
|
||||
Operator rules (Shorts live clips):
|
||||
1. One Douyin room material → at most one Shorts channel (room-day uniqueness per channel).
|
||||
2. Same channel uploads spaced ≥10 minutes normally; may compress only when behind deadline pace.
|
||||
3. Prefer distinct Douyin rooms toward each channel's daily quota.
|
||||
4. Within Beijing calendar day, prioritize meeting daily_min before daily_max.
|
||||
5. Progress / 已满 = successful uploads only (not pending/queued).
|
||||
6. Pace target: finish ~90% of fleet daily_max by Beijing 20:00; remaining 10% may use 20–24h.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
import time
|
||||
from typing import Any
|
||||
@ -12,12 +22,119 @@ from . import db
|
||||
from . import youtube_manage
|
||||
from .timeutil import beijing_day_bounds, beijing_from_ts, beijing_now, push_date_from_ts
|
||||
|
||||
# Normal floor: same-channel upload interval must be >10 minutes.
|
||||
CHANNEL_GAP_FLOOR_SEC = 600.0
|
||||
GLOBAL_GAP_FLOOR_SEC = 300.0
|
||||
# Behind 20:00 front-load pace / day-end catch-up.
|
||||
EMERGENCY_CHANNEL_GAP_SEC = 90.0
|
||||
EMERGENCY_GLOBAL_GAP_SEC = 45.0
|
||||
|
||||
# Finish this fraction of fleet daily_max by Beijing deadline hour.
|
||||
QUOTA_DEADLINE_HOUR = 20
|
||||
QUOTA_FRONTLOAD_RATIO = 0.90
|
||||
|
||||
|
||||
def _day_end_ts(push_date: str) -> float:
|
||||
"""Exclusive end of Beijing calendar day for push_date (next midnight)."""
|
||||
return beijing_day_bounds(push_date)[1]
|
||||
|
||||
|
||||
def _deadline_ts(push_date: str) -> float:
|
||||
"""Beijing wall-clock target for front-loaded quota (default 20:00)."""
|
||||
day_start, day_end = beijing_day_bounds(push_date)
|
||||
return min(day_end - 30.0, day_start + float(QUOTA_DEADLINE_HOUR) * 3600.0)
|
||||
|
||||
|
||||
def fleet_pace_plan(
|
||||
push_date: str = "",
|
||||
*,
|
||||
now: float | None = None,
|
||||
cfg: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Derive upload gaps from channel count + daily quotas vs Beijing 20:00 / 90% target."""
|
||||
settings = cfg or db.get_settings_map()
|
||||
now_ts = float(now if now is not None else time.time())
|
||||
day = push_date or push_date_from_ts(now_ts)
|
||||
day_start, day_end = beijing_day_bounds(day)
|
||||
deadline = _deadline_ts(day)
|
||||
summary = db.shorts_channels_quota_summary(day)
|
||||
n_ch = max(1, len(summary))
|
||||
uploaded = sum(int(r.get("uploaded") or r.get("used") or 0) for r in summary)
|
||||
target = sum(int(r.get("daily_max") or 0) for r in summary)
|
||||
if target <= 0:
|
||||
target = n_ch * 9
|
||||
front_target = max(1, int(math.ceil(float(QUOTA_FRONTLOAD_RATIO) * target)))
|
||||
need_front = max(0, front_target - uploaded)
|
||||
total_gap = sum(int(r.get("gap") or 0) for r in summary)
|
||||
|
||||
before_deadline = now_ts < deadline
|
||||
span_to_deadline = max(1.0, deadline - day_start)
|
||||
if before_deadline:
|
||||
progress = max(0.0, min(1.0, (now_ts - day_start) / span_to_deadline))
|
||||
time_left = max(60.0, deadline - now_ts)
|
||||
else:
|
||||
progress = 1.0
|
||||
time_left = max(60.0, day_end - now_ts)
|
||||
|
||||
expected_by_now = int(front_target * progress) if before_deadline else front_target
|
||||
behind = uploaded < expected_by_now and (need_front > 0 or total_gap > 0)
|
||||
|
||||
# Ideal global spacing so remaining front-load fits before deadline (fleet-wide).
|
||||
ideal_global = time_left / max(1, need_front or total_gap or 1)
|
||||
# Ideal per-channel: each channel still needs ~front_ratio*daily_max - used
|
||||
per_ch_need = []
|
||||
for r in summary:
|
||||
dmax = max(1, int(r.get("daily_max") or 9))
|
||||
used = int(r.get("uploaded") or r.get("used") or 0)
|
||||
per_ch_need.append(max(0, int(math.ceil(QUOTA_FRONTLOAD_RATIO * dmax)) - used))
|
||||
avg_ch_need = max(1, int(round(sum(per_ch_need) / max(1, len(per_ch_need))))) if per_ch_need else 1
|
||||
ideal_channel = time_left / max(1, avg_ch_need)
|
||||
|
||||
configured_global = float(settings.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
configured_channel = float(settings.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
|
||||
# When behind: use computed gaps (still respect floors unless truly impossible).
|
||||
if behind or (before_deadline and need_front > 0 and progress > 0.15):
|
||||
global_gap = min(configured_global, max(EMERGENCY_GLOBAL_GAP_SEC, ideal_global * 0.92))
|
||||
channel_gap = min(configured_channel, max(CHANNEL_GAP_FLOOR_SEC, ideal_channel * 0.85))
|
||||
# If even 10min/channel cannot finish fleet front-load, allow compress later via urgent.
|
||||
slots_at_floor = (time_left / CHANNEL_GAP_FLOOR_SEC) * n_ch
|
||||
urgent = need_front > slots_at_floor * 0.92 or (not before_deadline and total_gap > 0)
|
||||
if urgent:
|
||||
# Parallel channels: wall-clock ≈ need/n_ch * gap
|
||||
per_wall = time_left / max(1.0, math.ceil(need_front / max(1, n_ch)))
|
||||
channel_gap = max(EMERGENCY_CHANNEL_GAP_SEC, min(channel_gap, per_wall * 0.9))
|
||||
global_gap = max(EMERGENCY_GLOBAL_GAP_SEC, min(global_gap, channel_gap * 0.75))
|
||||
else:
|
||||
# Ahead of pace: keep configured gaps, lightly stretch so we don't dump everything early.
|
||||
global_gap = max(GLOBAL_GAP_FLOOR_SEC, configured_global)
|
||||
channel_gap = max(CHANNEL_GAP_FLOOR_SEC, configured_channel, configured_global)
|
||||
urgent = False
|
||||
|
||||
per_hour = (3600.0 / max(global_gap, 1.0)) if global_gap else 0.0
|
||||
return {
|
||||
"push_date": day,
|
||||
"n_channels": n_ch,
|
||||
"uploaded": uploaded,
|
||||
"target": target,
|
||||
"front_target": front_target,
|
||||
"need_front": need_front,
|
||||
"total_gap": total_gap,
|
||||
"deadline_hour": QUOTA_DEADLINE_HOUR,
|
||||
"deadline_ts": deadline,
|
||||
"before_deadline": before_deadline,
|
||||
"deadline_progress": round(progress, 4),
|
||||
"expected_by_now": expected_by_now,
|
||||
"behind": behind,
|
||||
"urgent": urgent,
|
||||
"time_left_sec": time_left,
|
||||
"recommended_global_gap_sec": round(global_gap, 1),
|
||||
"recommended_channel_gap_sec": round(channel_gap, 1),
|
||||
"recommended_per_hour": round(per_hour, 2),
|
||||
"frontload_ratio": QUOTA_FRONTLOAD_RATIO,
|
||||
}
|
||||
|
||||
|
||||
def _occupied_slots(push_date: str) -> list[tuple[float, str]]:
|
||||
"""(upload_at_or_finished, channel_pk) for jobs that already claim a slot today."""
|
||||
data = db.list_shorts_jobs(push_date=push_date, limit=500, offset=0)
|
||||
@ -42,37 +159,71 @@ def _quota_pressure(
|
||||
push_date: str,
|
||||
now: float,
|
||||
) -> tuple[float, float, bool, bool]:
|
||||
"""Return (global_min_scale, channel_min_scale, behind_min, must_compress)."""
|
||||
"""Return (global_min_scale, channel_min_scale, behind_min, must_compress).
|
||||
|
||||
Scales against Beijing 20:00 / 90% front-load, not linear midnight pace.
|
||||
"""
|
||||
from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota
|
||||
|
||||
plan = fleet_pace_plan(push_date, now=now)
|
||||
ch = db.get_shorts_channel(channel_pk) if channel_pk else None
|
||||
used = db.shorts_channel_upload_count(channel_pk, push_date) if channel_pk else 0
|
||||
from .db import SHORTS_DAILY_FORCE
|
||||
|
||||
daily_max = SHORTS_DAILY_FORCE
|
||||
daily_min = SHORTS_DAILY_FORCE
|
||||
day_start, day_end = beijing_day_bounds(push_date)
|
||||
span = max(1.0, day_end - day_start)
|
||||
day_progress = max(0.0, min(1.0, (now - day_start) / span))
|
||||
time_left = max(0.0, day_end - now)
|
||||
remaining_slots = max(0, daily_max - used)
|
||||
|
||||
expected_min = daily_min * min(1.0, day_progress * 1.15 + 0.05)
|
||||
behind_min = used < daily_min and used < expected_min
|
||||
behind_max = remaining_slots > 0 and used < daily_max * day_progress * 0.9
|
||||
must_compress = remaining_slots > 0 and time_left < 3600 * remaining_slots * 0.55
|
||||
used = db.shorts_channel_uploaded_count(channel_pk, push_date) if channel_pk else 0
|
||||
daily_min = _normalize_daily_quota((ch or {}).get("daily_min"), default=SHORTS_DAILY_FORCE)
|
||||
daily_max = _normalize_daily_quota((ch or {}).get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||||
if daily_max < daily_min:
|
||||
daily_max = daily_min
|
||||
ch_front = max(1, int(math.ceil(QUOTA_FRONTLOAD_RATIO * daily_max)))
|
||||
progress = float(plan.get("deadline_progress") or 0)
|
||||
expected_ch = ch_front * progress if plan.get("before_deadline") else float(ch_front)
|
||||
behind_min = used < daily_min and used < expected_ch
|
||||
remaining_to_front = max(0, ch_front - used)
|
||||
time_left = float(plan.get("time_left_sec") or 1)
|
||||
must_compress = bool(plan.get("urgent")) or (
|
||||
remaining_to_front > 0 and time_left < remaining_to_front * CHANNEL_GAP_FLOOR_SEC * 1.05
|
||||
)
|
||||
|
||||
g_scale = 1.0
|
||||
c_scale = 1.0
|
||||
if behind_min:
|
||||
g_scale = min(g_scale, 0.45)
|
||||
c_scale = min(c_scale, 0.3)
|
||||
elif behind_max and day_progress > 0.35:
|
||||
g_scale = min(g_scale, 0.65)
|
||||
c_scale = min(c_scale, 0.5)
|
||||
if must_compress or (day_progress > 0.82 and remaining_slots > 0):
|
||||
per_slot = time_left / max(1, remaining_slots)
|
||||
c_scale = min(c_scale, max(0.15, per_slot / 2400.0))
|
||||
g_scale = min(g_scale, max(0.2, c_scale * 0.75))
|
||||
return g_scale, c_scale, behind_min, must_compress or (day_progress > 0.9 and remaining_slots > 0)
|
||||
if plan.get("behind") or behind_min:
|
||||
# Map recommended gaps onto configured floors via scale.
|
||||
rec_g = float(plan.get("recommended_global_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
rec_c = float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
g_scale = min(1.0, rec_g / max(CHANNEL_GAP_FLOOR_SEC, 1.0))
|
||||
c_scale = min(1.0, rec_c / max(CHANNEL_GAP_FLOOR_SEC, 1.0))
|
||||
if must_compress:
|
||||
g_scale = min(g_scale, 0.35)
|
||||
c_scale = min(c_scale, 0.35)
|
||||
return g_scale, c_scale, behind_min or bool(plan.get("behind")), must_compress
|
||||
|
||||
|
||||
def _effective_gaps(
|
||||
*,
|
||||
channel_pk: str,
|
||||
push_date: str,
|
||||
now: float,
|
||||
configured_global: float,
|
||||
configured_channel: float,
|
||||
) -> tuple[float, float, bool, bool]:
|
||||
"""Scaled global/channel gaps; prefer fleet_pace_plan recommendations when behind."""
|
||||
plan = fleet_pace_plan(push_date, now=now)
|
||||
g_scale, c_scale, behind_min, urgent = _quota_pressure(
|
||||
channel_pk=channel_pk, push_date=push_date, now=now
|
||||
)
|
||||
if plan.get("behind") or urgent:
|
||||
global_min = float(plan.get("recommended_global_gap_sec") or GLOBAL_GAP_FLOOR_SEC)
|
||||
channel_min = float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
global_min = max(EMERGENCY_GLOBAL_GAP_SEC, min(configured_global, global_min))
|
||||
channel_min = max(
|
||||
EMERGENCY_CHANNEL_GAP_SEC if urgent else CHANNEL_GAP_FLOOR_SEC,
|
||||
min(configured_channel, channel_min),
|
||||
)
|
||||
if not urgent:
|
||||
channel_min = max(CHANNEL_GAP_FLOOR_SEC, channel_min)
|
||||
global_min = max(GLOBAL_GAP_FLOOR_SEC, global_min)
|
||||
else:
|
||||
global_min = max(GLOBAL_GAP_FLOOR_SEC, configured_global * g_scale)
|
||||
channel_min = max(CHANNEL_GAP_FLOOR_SEC, configured_channel * c_scale)
|
||||
return global_min, channel_min, behind_min, urgent
|
||||
|
||||
|
||||
def pick_upload_at(
|
||||
@ -81,30 +232,50 @@ def pick_upload_at(
|
||||
push_date: str = "",
|
||||
cfg: dict[str, Any] | None = None,
|
||||
) -> float:
|
||||
"""Pick a jittered upload time within the Beijing day, avoiding clustering."""
|
||||
"""Pick upload time biased into Beijing 00:00–20:00 when still under 90% target."""
|
||||
settings = cfg or db.get_settings_map()
|
||||
now = time.time()
|
||||
day = push_date or push_date_from_ts(now)
|
||||
day_end = _day_end_ts(day)
|
||||
latest = day_end - 45
|
||||
deadline = _deadline_ts(day)
|
||||
plan = fleet_pace_plan(day, now=now, cfg=settings)
|
||||
# Soft cap: schedule inside front-load window while we still need 90% before 20:00.
|
||||
if plan.get("before_deadline") and int(plan.get("need_front") or 0) > 0:
|
||||
latest = min(day_end - 45.0, deadline - 30.0)
|
||||
else:
|
||||
latest = day_end - 45.0
|
||||
latest = max(now + 20.0, latest)
|
||||
|
||||
if not settings.get("shorts_upload_spread", True):
|
||||
return min(now + random.uniform(20, 120), latest)
|
||||
|
||||
global_min = max(300.0, float(settings.get("shorts_upload_min_gap_sec") or 720))
|
||||
channel_min = max(global_min, float(settings.get("shorts_channel_min_gap_sec") or 2400))
|
||||
g_scale, c_scale, behind_min, urgent = _quota_pressure(
|
||||
channel_pk=channel_pk, push_date=day, now=now
|
||||
configured_global = float(settings.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
configured_channel = float(settings.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC)
|
||||
global_min, channel_min, behind_min, urgent = _effective_gaps(
|
||||
channel_pk=channel_pk,
|
||||
push_date=day,
|
||||
now=now,
|
||||
configured_global=max(GLOBAL_GAP_FLOOR_SEC, configured_global),
|
||||
configured_channel=max(CHANNEL_GAP_FLOOR_SEC, configured_channel, configured_global),
|
||||
)
|
||||
global_min *= g_scale
|
||||
channel_min *= c_scale
|
||||
|
||||
if urgent or behind_min:
|
||||
earliest = now + random.uniform(45, 240)
|
||||
earliest = now + random.uniform(8, max(35.0, min(120.0, channel_min * 0.25)))
|
||||
else:
|
||||
earliest = now + random.uniform(180, 1500)
|
||||
# Ahead: mild jitter, still keep inside front-load window (not dump to 23:00).
|
||||
earliest = now + random.uniform(60, min(900.0, channel_min * 0.8))
|
||||
if earliest >= latest:
|
||||
earliest = now + random.uniform(30, max(90.0, global_min * 0.4))
|
||||
earliest = now + random.uniform(8, 45)
|
||||
|
||||
ch_last = db.shorts_channel_last_slot_ts(channel_pk, day) if channel_pk else 0.0
|
||||
if ch_last > 0:
|
||||
slotted = ch_last + channel_min + random.uniform(3, 25)
|
||||
if (urgent or behind_min) and slotted > latest:
|
||||
earliest = max(earliest, now + 8)
|
||||
else:
|
||||
earliest = max(earliest, slotted)
|
||||
if urgent and earliest > latest:
|
||||
return float(min(now + random.uniform(8, 25), max(now + 5, latest)))
|
||||
|
||||
slots = _occupied_slots(day)
|
||||
|
||||
@ -113,31 +284,110 @@ def pick_upload_at(
|
||||
gap = abs(ts - other_ts)
|
||||
if gap < global_min * random.uniform(0.85, 1.15):
|
||||
return True
|
||||
if other_ch == channel_pk and gap < channel_min * random.uniform(0.9, 1.2):
|
||||
if other_ch == channel_pk and gap < channel_min:
|
||||
return True
|
||||
return False
|
||||
|
||||
window_end = max(earliest + 60, latest)
|
||||
for _ in range(48):
|
||||
if random.random() < 0.35:
|
||||
span = max(600.0, (window_end - earliest) / 8)
|
||||
cand = earliest + random.expovariate(1.0 / span)
|
||||
cand = min(cand, window_end)
|
||||
# Prefer near-term slots when behind; never sample the whole day until midnight.
|
||||
if urgent or behind_min:
|
||||
window_end = min(latest, max(earliest + 600.0, now + max(global_min * 4, 1800.0)))
|
||||
else:
|
||||
window_end = min(latest, max(earliest + 1800.0, now + 3 * 3600.0))
|
||||
window_end = max(earliest + 60.0, window_end)
|
||||
|
||||
for _ in range(64):
|
||||
if urgent or behind_min:
|
||||
# Bias early: half near earliest, half uniform in short window.
|
||||
if random.random() < 0.55:
|
||||
cand = earliest + random.uniform(0, max(90.0, global_min * 1.2))
|
||||
else:
|
||||
cand = random.uniform(earliest, window_end)
|
||||
else:
|
||||
cand = random.uniform(earliest, window_end)
|
||||
if random.random() < 0.4:
|
||||
span = max(300.0, (window_end - earliest) / 6)
|
||||
cand = earliest + random.expovariate(1.0 / span)
|
||||
cand = min(cand, window_end)
|
||||
else:
|
||||
cand = random.uniform(earliest, window_end)
|
||||
if cand < earliest:
|
||||
cand = earliest + random.uniform(0, 120)
|
||||
cand = earliest + random.uniform(0, 90)
|
||||
if not conflicts(cand):
|
||||
return float(min(cand, latest))
|
||||
|
||||
last_ts = max((s[0] for s in slots), default=now)
|
||||
cand = max(earliest, last_ts + random.uniform(global_min, global_min * 2.8))
|
||||
ch_last = max((s[0] for s in slots if s[1] == channel_pk), default=0.0)
|
||||
if ch_last:
|
||||
cand = max(cand, ch_last + random.uniform(channel_min, channel_min * 1.8))
|
||||
cand = max(earliest, last_ts + random.uniform(global_min, global_min * 2.2))
|
||||
ch_last2 = max((s[0] for s in slots if s[1] == channel_pk), default=ch_last)
|
||||
if ch_last2:
|
||||
cand = max(cand, ch_last2 + channel_min + random.uniform(3, 40))
|
||||
return float(min(cand, latest))
|
||||
|
||||
|
||||
def pull_forward_due_uploads(cfg: dict[str, Any] | None = None) -> int:
|
||||
"""Reschedule far-future slots when behind Beijing 20:00 / 90% pace."""
|
||||
settings = cfg or db.get_settings_map()
|
||||
if not settings.get("shorts_auto_upload", True):
|
||||
return 0
|
||||
now = time.time()
|
||||
day = push_date_from_ts(now)
|
||||
plan = fleet_pace_plan(day, now=now, cfg=settings)
|
||||
if int(plan.get("total_gap") or 0) <= 0:
|
||||
return 0
|
||||
# Always pull when behind front-load; also near midnight if still gapped.
|
||||
if not plan.get("behind") and not plan.get("urgent"):
|
||||
if plan.get("before_deadline") and float(plan.get("deadline_progress") or 0) < 0.85:
|
||||
return 0
|
||||
if float(plan.get("time_left_sec") or 0) > 7200 and int(plan.get("total_gap") or 0) < 20:
|
||||
return 0
|
||||
slam = bool(plan.get("urgent")) or (
|
||||
not plan.get("before_deadline") and float(plan.get("time_left_sec") or 0) < 2400
|
||||
)
|
||||
behind = bool(plan.get("behind"))
|
||||
rec_g = max(EMERGENCY_GLOBAL_GAP_SEC, float(plan.get("recommended_global_gap_sec") or GLOBAL_GAP_FLOOR_SEC))
|
||||
rec_c = max(
|
||||
EMERGENCY_CHANNEL_GAP_SEC if slam else CHANNEL_GAP_FLOOR_SEC,
|
||||
float(plan.get("recommended_channel_gap_sec") or CHANNEL_GAP_FLOOR_SEC),
|
||||
)
|
||||
# When behind: anything parked beyond ~2× recommended global gap must come forward.
|
||||
park_limit = now + (max(120.0, rec_g * 2.5) if (behind or slam) else 3600.0)
|
||||
deadline = float(plan.get("deadline_ts") or _deadline_ts(day))
|
||||
latest = min(_day_end_ts(day) - 45.0, deadline - 30.0) if plan.get("before_deadline") else _day_end_ts(day) - 45.0
|
||||
|
||||
data = db.list_shorts_jobs(push_date=day, status="scheduled", limit=300, offset=0)
|
||||
extra = db.list_shorts_jobs(push_date=day, status="recorded", limit=100, offset=0)
|
||||
jobs = list(data.get("jobs") or []) + list(extra.get("jobs") or [])
|
||||
# Stable order: soonest first so we pack from "now"
|
||||
jobs.sort(key=lambda j: float(j.get("upload_at") or 0) or 1e18)
|
||||
|
||||
# Cursor per channel + global for packing
|
||||
next_global = now + random.uniform(5, 25)
|
||||
next_ch: dict[str, float] = {}
|
||||
moved = 0
|
||||
for job in jobs:
|
||||
if not str(job.get("clip_path") or "").strip():
|
||||
continue
|
||||
upload_at = float(job.get("upload_at") or 0)
|
||||
if upload_at <= 0:
|
||||
upload_at = now + 3600
|
||||
if not slam and not behind and upload_at <= park_limit:
|
||||
continue
|
||||
if (behind or slam) and upload_at <= park_limit:
|
||||
continue
|
||||
ch_pk = str(job.get("channel_pk") or "")
|
||||
if slam or behind:
|
||||
cand = max(next_global, next_ch.get(ch_pk, now))
|
||||
cand += random.uniform(2, 18)
|
||||
cand = min(cand, max(now + 30.0, latest))
|
||||
new_at = float(cand)
|
||||
next_global = new_at + rec_g
|
||||
next_ch[ch_pk] = new_at + rec_c
|
||||
else:
|
||||
new_at = pick_upload_at(channel_pk=ch_pk, push_date=day, cfg=settings)
|
||||
if slam or behind or new_at < upload_at - 30:
|
||||
db.update_shorts_job(str(job["id"]), upload_at=new_at, error="")
|
||||
moved += 1
|
||||
return moved
|
||||
|
||||
|
||||
def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||||
"""Upcoming scheduled uploads + per-channel today usage for UI."""
|
||||
day = push_date_from_ts(time.time())
|
||||
@ -150,14 +400,20 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||||
for j in data.get("jobs") or []:
|
||||
ch = str(j.get("channel_pk") or "")
|
||||
st = str(j.get("status") or "")
|
||||
bucket = by_ch.setdefault(ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0})
|
||||
bucket = by_ch.setdefault(
|
||||
ch, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0, "recorded": 0, "recording": 0}
|
||||
)
|
||||
if st in db._SHORTS_QUOTA_STATUSES:
|
||||
bucket["used"] += 1
|
||||
if st == "uploaded" or st == "done":
|
||||
bucket["uploaded"] += 1
|
||||
if st == "scheduled":
|
||||
bucket["scheduled"] += 1
|
||||
if st in {"pending", "recording"}:
|
||||
if st == "recorded":
|
||||
bucket["recorded"] += 1
|
||||
if st == "recording":
|
||||
bucket["recording"] += 1
|
||||
if st == "pending":
|
||||
bucket["pending"] += 1
|
||||
clip = str(j.get("clip_path") or "").strip()
|
||||
clip_ready = bool(clip) and Path(clip).is_file()
|
||||
@ -228,10 +484,14 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||||
daily_max = _normalize_daily_quota(c.get("daily_max"), default=SHORTS_DAILY_FORCE)
|
||||
if daily_max < daily_min:
|
||||
daily_max = daily_min
|
||||
stats = by_ch.get(cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0})
|
||||
used = int(stats["used"])
|
||||
gap = max(0, daily_max - used)
|
||||
min_met = used >= daily_min
|
||||
stats = by_ch.get(
|
||||
cid, {"used": 0, "scheduled": 0, "uploaded": 0, "pending": 0, "recorded": 0, "recording": 0}
|
||||
)
|
||||
pipeline = int(stats["used"])
|
||||
uploaded = int(stats["uploaded"])
|
||||
# UI progress / 缺 / 已满 = uploads only; pipeline stays in stats.used for ops.
|
||||
gap = max(0, daily_max - uploaded)
|
||||
min_met = uploaded >= daily_min
|
||||
if c.get("enabled") and not min_met:
|
||||
min_unmet += 1
|
||||
if c.get("enabled"):
|
||||
@ -250,8 +510,9 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||||
"daily_max": daily_max,
|
||||
"gap": gap,
|
||||
"min_met": min_met,
|
||||
"max_met": used >= daily_max,
|
||||
"behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min),
|
||||
"max_met": uploaded >= daily_max,
|
||||
"behind_pace": bool(c.get("enabled") and uploaded < expected_min and uploaded < daily_min),
|
||||
"pipeline": pipeline,
|
||||
"yt_profile": youtube_manage._snippet_from_channel_row(c),
|
||||
"last_status": str(c.get("last_status") or "offline"),
|
||||
"last_title": str(c.get("last_title") or ""),
|
||||
@ -266,21 +527,76 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
|
||||
else ypp_by_shorts.get(cid, -1)
|
||||
),
|
||||
**stats,
|
||||
# Progress fields must win over stats.used (pipeline occupancy).
|
||||
"used": uploaded,
|
||||
"uploaded": uploaded,
|
||||
"pipeline": pipeline,
|
||||
}
|
||||
)
|
||||
timeline = build_timeline(enriched, now=now, day_start=day_start, day_end=day_end)
|
||||
# Lightweight YT quota forecast: if many uploads still pending vs remaining day hours
|
||||
pending_uploads = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"})
|
||||
enabled_rows = [c for c in channel_rows if c.get("enabled")]
|
||||
uploaded_total = sum(int(c.get("uploaded") or 0) for c in enabled_rows)
|
||||
target_total = sum(int(c.get("daily_max") or 0) for c in enabled_rows)
|
||||
pending_record = sum(int(c.get("pending") or 0) + int(c.get("recording") or 0) for c in enabled_rows)
|
||||
queued_upload = sum(
|
||||
int(c.get("scheduled") or 0) + int(c.get("recorded") or 0) for c in enabled_rows
|
||||
)
|
||||
clip_ready = sum(1 for x in enriched if str(x.get("status") or "") in {"scheduled", "recorded"})
|
||||
plan = fleet_pace_plan(day, now=now)
|
||||
hours_left = max(0.1, (day_end - now) / 3600.0)
|
||||
hours_to_deadline = max(0.0, (float(plan["deadline_ts"]) - now) / 3600.0) if plan.get("before_deadline") else 0.0
|
||||
impossible = total_gap > 0 and hours_left * 3600.0 < total_gap * CHANNEL_GAP_FLOOR_SEC * 0.85
|
||||
warn = (
|
||||
bool(plan.get("behind"))
|
||||
or (total_gap >= 8 and hours_left < 4)
|
||||
or impossible
|
||||
or (pending_record >= 20 and hours_left < 2)
|
||||
)
|
||||
# Human order: uploaded/target first, then gap, then in-flight pipeline (not additive to gap).
|
||||
parts: list[str] = [f"已上传 {uploaded_total}/{target_total or '—'}"]
|
||||
if total_gap > 0:
|
||||
parts.append(f"缺口 {total_gap}")
|
||||
else:
|
||||
parts.append("已满")
|
||||
pipe_bits: list[str] = []
|
||||
if queued_upload > 0:
|
||||
pipe_bits.append(f"待传 {queued_upload}")
|
||||
if pending_record > 0:
|
||||
pipe_bits.append(f"待录 {pending_record}")
|
||||
if pipe_bits:
|
||||
parts.append("管道 " + " + ".join(pipe_bits))
|
||||
else:
|
||||
parts.append("管道空")
|
||||
parts.append(f"剩 {hours_left:.1f}h")
|
||||
parts.append(
|
||||
f"目标{QUOTA_DEADLINE_HOUR}:00前{int(QUOTA_FRONTLOAD_RATIO * 100)}%"
|
||||
f"({plan.get('uploaded')}/{plan.get('front_target')})"
|
||||
)
|
||||
if plan.get("behind"):
|
||||
parts.append(
|
||||
f"建议间隔≈{int(round(float(plan.get('recommended_global_gap_sec') or 0) / 60))}分"
|
||||
f"/同频道≈{int(round(float(plan.get('recommended_channel_gap_sec') or 0) / 60))}分"
|
||||
)
|
||||
if impossible:
|
||||
parts.append("日末加速中")
|
||||
elif plan.get("behind"):
|
||||
parts.append("落后已加速")
|
||||
elif warn:
|
||||
parts.append("节奏偏紧")
|
||||
quota_forecast = {
|
||||
"pending_uploads": pending_uploads,
|
||||
"uploaded": uploaded_total,
|
||||
"target": target_total,
|
||||
"total_gap": total_gap,
|
||||
"pending_record": pending_record,
|
||||
"queued_upload": queued_upload,
|
||||
"clip_ready": clip_ready,
|
||||
"pending_uploads": queued_upload,
|
||||
"hours_left": round(hours_left, 2),
|
||||
"per_hour_pace": round(pending_uploads / hours_left, 2) if hours_left else pending_uploads,
|
||||
"warn": pending_uploads >= 8 and hours_left < 4,
|
||||
"message": (
|
||||
f"今日仍有 {pending_uploads} 条待传,约剩 {hours_left:.1f} 小时"
|
||||
+ (",节奏偏紧,建议错开或延后低优任务" if pending_uploads >= 8 and hours_left < 4 else "")
|
||||
),
|
||||
"hours_to_deadline": round(hours_to_deadline, 2),
|
||||
"per_hour_pace": round(float(plan.get("recommended_per_hour") or 0), 2),
|
||||
"warn": warn,
|
||||
"pace": plan,
|
||||
"message": " · ".join(parts),
|
||||
}
|
||||
return {
|
||||
"push_date": day,
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""YouTube Data API upload counters — per OAuth Client profile (A/B/C/D).
|
||||
|
||||
Counters are display-only. This module must NEVER gate manual or worker uploads;
|
||||
YouTube API 429 responses are the sole authority. Client A exhaustion must NOT
|
||||
pause Client B either.
|
||||
Local upload *counts* are display-only and must not gate uploads by themselves.
|
||||
When YouTube returns a real 429 / quota-exceeded, we set a short API cool-down
|
||||
per Client so the worker stops hammering (and ntfy spam). Manual upload paths
|
||||
never consult that cool-down.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@ -11,11 +12,12 @@ import time
|
||||
from typing import Any
|
||||
|
||||
from . import db
|
||||
from .shorts_upload import quota_error_message
|
||||
from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts
|
||||
|
||||
YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90
|
||||
QUOTA_MAP_KEY = "shorts_yt_quota_by_profile"
|
||||
# After a real YouTube 429, pause auto-uploads for this Client (manual still OK).
|
||||
DEFAULT_API_COOLDOWN_SEC = 3600.0
|
||||
|
||||
|
||||
def normalize_profile_id(raw: Any) -> str:
|
||||
@ -40,8 +42,19 @@ def yt_daily_limit(cfg: dict[str, Any] | None = None) -> int:
|
||||
return max(1, int(settings.get("shorts_yt_daily_upload_limit") or YT_DAILY_UPLOAD_LIMIT_DEFAULT))
|
||||
|
||||
|
||||
def api_cooldown_sec(cfg: dict[str, Any] | None = None) -> float:
|
||||
settings = cfg if cfg is not None else db.get_settings_map()
|
||||
try:
|
||||
return max(
|
||||
300.0,
|
||||
min(12 * 3600.0, float(settings.get("shorts_yt_quota_cooldown_sec") or DEFAULT_API_COOLDOWN_SEC)),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_API_COOLDOWN_SEC
|
||||
|
||||
|
||||
def _empty_entry() -> dict[str, Any]:
|
||||
return {"date": "", "count": 0, "blocked_until": 0.0}
|
||||
return {"date": "", "count": 0, "blocked_until": 0.0, "quota_ntfy_at": 0.0}
|
||||
|
||||
|
||||
def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
@ -56,6 +69,7 @@ def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"date": str(v.get("date") or ""),
|
||||
"count": int(v.get("count") or 0),
|
||||
"blocked_until": float(v.get("blocked_until") or 0),
|
||||
"quota_ntfy_at": float(v.get("quota_ntfy_at") or 0),
|
||||
}
|
||||
# One-time migrate legacy global counters into profile A if map empty
|
||||
if not out:
|
||||
@ -67,6 +81,7 @@ def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"date": legacy_date,
|
||||
"count": legacy_count,
|
||||
"blocked_until": legacy_until if legacy_until > time.time() else 0.0,
|
||||
"quota_ntfy_at": 0.0,
|
||||
}
|
||||
return out
|
||||
|
||||
@ -92,7 +107,6 @@ def _count_uploads_from_db_pt_day(profile_id: str, day: str = "") -> int:
|
||||
with db._lock:
|
||||
conn = db._connect()
|
||||
try:
|
||||
# Channels on this profile (empty profile_id counts as A)
|
||||
if pid == "A":
|
||||
ch_rows = conn.execute(
|
||||
"""
|
||||
@ -162,15 +176,23 @@ def _sync_profile_entry(
|
||||
stored_day = str(entry.get("date") or "")
|
||||
stored_count = int(entry.get("count") or 0)
|
||||
blocked_until = float(entry.get("blocked_until") or 0)
|
||||
if blocked_until and blocked_until <= time.time():
|
||||
ntfy_at = float(entry.get("quota_ntfy_at") or 0)
|
||||
now = time.time()
|
||||
if blocked_until and blocked_until <= now:
|
||||
blocked_until = 0.0
|
||||
if stored_day != pt_day:
|
||||
db_count = _count_uploads_from_db_pt_day(pid, pt_day)
|
||||
stored_count = max(stored_count, db_count) if stored_day else db_count
|
||||
stored_day = pt_day
|
||||
# New Pacific day clears block
|
||||
# New Pacific day clears cool-down (YouTube quota also resets at PT midnight)
|
||||
blocked_until = 0.0
|
||||
entry = {"date": stored_day, "count": stored_count, "blocked_until": blocked_until}
|
||||
ntfy_at = 0.0
|
||||
entry = {
|
||||
"date": stored_day,
|
||||
"count": stored_count,
|
||||
"blocked_until": blocked_until,
|
||||
"quota_ntfy_at": ntfy_at,
|
||||
}
|
||||
quota_map[pid] = entry
|
||||
return entry
|
||||
|
||||
@ -185,7 +207,6 @@ def yt_upload_budget(
|
||||
limit = yt_daily_limit(settings)
|
||||
quota_map = _load_quota_map(settings)
|
||||
entry = _sync_profile_entry(profile_id, settings, quota_map)
|
||||
# Persist day roll if needed
|
||||
if settings.get(QUOTA_MAP_KEY) != quota_map:
|
||||
_save_quota_map(quota_map)
|
||||
settings[QUOTA_MAP_KEY] = quota_map
|
||||
@ -199,14 +220,13 @@ def note_yt_upload_attempt(
|
||||
*,
|
||||
profile_id: str = "A",
|
||||
) -> None:
|
||||
"""UI counter only — never gates uploads. YouTube API is the sole authority."""
|
||||
"""UI counter only — does not clear API cool-down."""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
pid = normalize_profile_id(profile_id)
|
||||
quota_map = _load_quota_map(settings)
|
||||
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||
entry["count"] = int(entry.get("count") or 0) + 1
|
||||
entry["date"] = pacific_day_from_ts(time.time())
|
||||
entry["blocked_until"] = 0.0
|
||||
quota_map[pid] = entry
|
||||
_save_quota_map(quota_map)
|
||||
|
||||
@ -216,7 +236,7 @@ def reserve_yt_upload_slot(
|
||||
*,
|
||||
profile_id: str = "A",
|
||||
) -> bool:
|
||||
"""Always allow. Local 90-count is informational only — never refuse uploads."""
|
||||
"""Always allow reservation for UI counter. Cool-down is enforced at claim time."""
|
||||
note_yt_upload_attempt(cfg, profile_id=profile_id)
|
||||
return True
|
||||
|
||||
@ -226,14 +246,21 @@ def project_uploads_available(
|
||||
*,
|
||||
profile_id: str = "A",
|
||||
) -> bool:
|
||||
"""Never self-block. Local budget is display-only."""
|
||||
_ = cfg, profile_id
|
||||
return True
|
||||
"""True unless this Client is in a YouTube-API cool-down window."""
|
||||
blocked, _ = profile_upload_blocked(cfg, profile_id=profile_id)
|
||||
return not blocked
|
||||
|
||||
|
||||
def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
|
||||
_ = cfg
|
||||
return True
|
||||
"""True if at least one Client is not in API cool-down (or map is empty)."""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
blocked = blocked_profile_ids(settings)
|
||||
if not blocked:
|
||||
return True
|
||||
for pid in ("A", "B", "C", "D"):
|
||||
if pid not in blocked:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def profile_upload_blocked(
|
||||
@ -241,22 +268,29 @@ def profile_upload_blocked(
|
||||
*,
|
||||
profile_id: str = "A",
|
||||
) -> tuple[bool, float]:
|
||||
"""Self-imposed pause removed: always unblocked. Clears stale blocked_until."""
|
||||
"""True while YouTube API cool-down is active for this Client."""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
pid = normalize_profile_id(profile_id)
|
||||
quota_map = _load_quota_map(settings)
|
||||
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||
if float(entry.get("blocked_until") or 0) > 0:
|
||||
entry["blocked_until"] = 0.0
|
||||
quota_map[pid] = entry
|
||||
_save_quota_map(quota_map)
|
||||
until = float(entry.get("blocked_until") or 0)
|
||||
if until > time.time():
|
||||
return True, until
|
||||
return False, 0.0
|
||||
|
||||
|
||||
def blocked_profile_ids(cfg: dict[str, Any] | None = None) -> set[str]:
|
||||
"""No local upload pause — never skip profiles in the worker."""
|
||||
_ = cfg
|
||||
return set()
|
||||
"""Clients currently in API cool-down (worker should skip auto-upload)."""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
quota_map = _load_quota_map(settings)
|
||||
out: set[str] = set()
|
||||
now = time.time()
|
||||
pids = set(quota_map.keys()) | {"A", "B", "C", "D"}
|
||||
for pid in pids:
|
||||
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||
if float(entry.get("blocked_until") or 0) > now:
|
||||
out.add(pid)
|
||||
return out
|
||||
|
||||
|
||||
def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
|
||||
@ -271,18 +305,19 @@ def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str
|
||||
rows = []
|
||||
for pid in profiles:
|
||||
limit, used, remaining = yt_upload_budget(settings, profile_id=pid)
|
||||
# Clear any legacy self-pause; never report blocked for local enforcement
|
||||
profile_upload_blocked(settings, profile_id=pid)
|
||||
blocked, until = profile_upload_blocked(settings, profile_id=pid)
|
||||
rows.append(
|
||||
{
|
||||
"id": pid,
|
||||
"limit": limit,
|
||||
"used": used,
|
||||
"remaining": remaining,
|
||||
"exhausted_hint": used >= limit,
|
||||
"blocked": False,
|
||||
"blocked_until": 0.0,
|
||||
"reset_at": next_youtube_quota_reset_ts() if used >= limit else 0.0,
|
||||
"exhausted_hint": bool(used >= limit and not blocked),
|
||||
"blocked": blocked,
|
||||
"blocked_until": until,
|
||||
"reset_at": until
|
||||
if blocked
|
||||
else (next_youtube_quota_reset_ts() if used >= limit else 0.0),
|
||||
}
|
||||
)
|
||||
return rows
|
||||
@ -297,32 +332,95 @@ def channel_ids_for_profile(profile_id: str) -> list[str]:
|
||||
return ids
|
||||
|
||||
|
||||
def mark_api_quota_cooldown(
|
||||
cfg: dict[str, Any] | None = None,
|
||||
*,
|
||||
profile_id: str = "A",
|
||||
reason: str = "",
|
||||
cooldown_sec: float | None = None,
|
||||
) -> tuple[float, bool]:
|
||||
"""Set cool-down after a real YouTube 429. Returns (until_ts, should_notify).
|
||||
|
||||
should_notify is True only when entering / refreshing a cool-down for ntfy (once per window).
|
||||
"""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
pid = normalize_profile_id(profile_id)
|
||||
cool = float(cooldown_sec) if cooldown_sec is not None else api_cooldown_sec(settings)
|
||||
now = time.time()
|
||||
reset_at = next_youtube_quota_reset_ts()
|
||||
until = min(now + cool, reset_at) if reset_at > now else now + cool
|
||||
quota_map = _load_quota_map(settings)
|
||||
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||
prev_until = float(entry.get("blocked_until") or 0)
|
||||
already = prev_until > now + 60
|
||||
entry["blocked_until"] = max(prev_until, until) if already else until
|
||||
limit = yt_daily_limit(settings)
|
||||
entry["count"] = max(int(entry.get("count") or 0), limit)
|
||||
entry["date"] = pacific_day_from_ts(now)
|
||||
last_ntfy = float(entry.get("quota_ntfy_at") or 0)
|
||||
should_notify = (not already) or (now - last_ntfy >= cool * 0.9)
|
||||
if should_notify:
|
||||
entry["quota_ntfy_at"] = now
|
||||
quota_map[pid] = entry
|
||||
_save_quota_map(quota_map)
|
||||
_ = reason
|
||||
return float(entry["blocked_until"]), should_notify
|
||||
|
||||
|
||||
def pause_uploads_until_reset(
|
||||
cfg: dict[str, Any] | None = None,
|
||||
*,
|
||||
profile_id: str = "A",
|
||||
reason: str = "",
|
||||
) -> float:
|
||||
"""Legacy no-op: do NOT self-pause or defer jobs. Snap UI counter only."""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
pid = normalize_profile_id(profile_id)
|
||||
until = next_youtube_quota_reset_ts()
|
||||
quota_map = _load_quota_map(settings)
|
||||
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||
entry["blocked_until"] = 0.0
|
||||
limit = yt_daily_limit(settings)
|
||||
entry["count"] = max(int(entry.get("count") or 0), limit)
|
||||
entry["date"] = pacific_day_from_ts(time.time())
|
||||
quota_map[pid] = entry
|
||||
_save_quota_map(quota_map)
|
||||
_ = reason
|
||||
"""Compatibility: apply default API cool-down."""
|
||||
until, _ = mark_api_quota_cooldown(cfg, profile_id=profile_id, reason=reason)
|
||||
return until
|
||||
|
||||
|
||||
def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
|
||||
"""No-op: never bulk-defer uploads for a Client. Manual upload must stay free."""
|
||||
_ = profile_id, until_ts, reason
|
||||
return 0
|
||||
"""Push due auto-uploads for this Client past cool-down (manual claim still free)."""
|
||||
pid = normalize_profile_id(profile_id)
|
||||
until = float(until_ts or 0)
|
||||
if until <= time.time():
|
||||
return 0
|
||||
ch_ids = channel_ids_for_profile(pid)
|
||||
if not ch_ids:
|
||||
return 0
|
||||
moved = 0
|
||||
now = time.time()
|
||||
with db._lock:
|
||||
conn = db._connect()
|
||||
try:
|
||||
placeholders = ",".join("?" for _ in ch_ids)
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT id, upload_at FROM shorts_jobs
|
||||
WHERE status IN ('scheduled', 'recorded')
|
||||
AND clip_path != ''
|
||||
AND youtube_video_id = ''
|
||||
AND channel_pk IN ({placeholders})
|
||||
AND upload_at > 0
|
||||
AND upload_at <= ?
|
||||
""",
|
||||
(*ch_ids, now + 30),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
conn.execute(
|
||||
"UPDATE shorts_jobs SET upload_at = ?, error = ?, updated_at = ? WHERE id = ?",
|
||||
(
|
||||
until + 15,
|
||||
(reason or "YouTube 接口配额冷静中,稍后自动重试")[:300],
|
||||
now,
|
||||
str(row["id"]),
|
||||
),
|
||||
)
|
||||
moved += 1
|
||||
if moved:
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return moved
|
||||
|
||||
|
||||
def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int:
|
||||
@ -332,18 +430,20 @@ def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None
|
||||
|
||||
|
||||
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]:
|
||||
"""No-op: never auto-pause Clients from local counters or past 429s."""
|
||||
"""No-op: cool-down is set only from live API 429 feedback."""
|
||||
_ = cfg
|
||||
return {}
|
||||
|
||||
|
||||
def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None:
|
||||
"""Wipe legacy blocked_until / global pause so uploads are never locally gated."""
|
||||
"""Clear expired cool-downs only — does not wipe an active API cool-down."""
|
||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||
quota_map = _load_quota_map(settings)
|
||||
changed = False
|
||||
now = time.time()
|
||||
for pid, entry in list(quota_map.items()):
|
||||
if float(entry.get("blocked_until") or 0) != 0:
|
||||
until = float(entry.get("blocked_until") or 0)
|
||||
if until and until <= now:
|
||||
entry = dict(entry)
|
||||
entry["blocked_until"] = 0.0
|
||||
quota_map[pid] = entry
|
||||
@ -352,6 +452,5 @@ def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None:
|
||||
_save_quota_map(quota_map)
|
||||
|
||||
|
||||
# Back-compat aliases used by older call sites (treat as profile A)
|
||||
def pause_uploads_until_reset_global(cfg: dict[str, Any] | None = None, *, reason: str = "") -> float:
|
||||
return pause_uploads_until_reset(cfg, profile_id="A", reason=reason)
|
||||
|
||||
@ -46,7 +46,8 @@ async def _request(
|
||||
|
||||
async def health() -> dict[str, Any]:
|
||||
try:
|
||||
return await _request("GET", "/health", timeout=12.0)
|
||||
# Callers wrap with ~0.6s; keep internal timeout short to avoid half-open churn.
|
||||
return await _request("GET", "/health", timeout=1.0)
|
||||
except YouTubeSvcError as exc:
|
||||
return {"ok": False, "error": str(exc), "service": "youtube-svc"}
|
||||
|
||||
|
||||
@ -20,6 +20,81 @@ _BATCH_SIZE = 20
|
||||
_REFRESH_LOCK: Optional[asyncio.Lock] = None
|
||||
_LAST_OAUTH_AT = 0.0
|
||||
_OAUTH_MIN_INTERVAL_SEC = 45.0
|
||||
# Studio samples older than this must not invent 在播 (edge_assign_live used to sticky-inflate).
|
||||
_STUDIO_SAMPLE_MAX_AGE_SEC = 60.0
|
||||
_STUDIO_DEAD_STATUSES = {
|
||||
"waiting",
|
||||
"ended",
|
||||
"signed_out",
|
||||
"offline",
|
||||
"encoder_lost",
|
||||
"preparing",
|
||||
"ready",
|
||||
}
|
||||
# Circular / untrusted for receiving: hub←edge assign_lives mirror.
|
||||
_UNTRUSTED_SAMPLE_SOURCES = {"edge_assign_live", "edge_assign", "hub_mirror"}
|
||||
|
||||
|
||||
def _studio_receiving_from_snap(studio_snap: dict[str, Any] | None) -> bool:
|
||||
"""True only for real Studio receiving — never Preparing / Excellent-alone / edge mirror junk."""
|
||||
snap = studio_snap if isinstance(studio_snap, dict) else {}
|
||||
if not snap:
|
||||
return False
|
||||
if snap.get("encoder_lost") or snap.get("preparing_stream"):
|
||||
return False
|
||||
st = str(snap.get("live_status") or "").strip().lower()
|
||||
if st in _STUDIO_DEAD_STATUSES:
|
||||
return False
|
||||
detect = str(snap.get("detect_source") or "").strip().lower()
|
||||
if detect in _UNTRUSTED_SAMPLE_SOURCES:
|
||||
return False
|
||||
# age_sec from live snap; samples stash received_at
|
||||
try:
|
||||
age = snap.get("age_sec")
|
||||
if age is None and snap.get("received_at"):
|
||||
age = time.time() - float(snap.get("received_at") or 0)
|
||||
if age is not None and float(age) > _STUDIO_SAMPLE_MAX_AGE_SEC:
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return bool(snap.get("encoder_receiving") or snap.get("on_air"))
|
||||
|
||||
|
||||
def _studio_snap_belongs_to_assign_group(
|
||||
studio_snap: dict[str, Any] | None,
|
||||
*,
|
||||
youtube_channel_id: str = "",
|
||||
neko_shared: bool = False,
|
||||
group_is_pushing: bool = False,
|
||||
studio_url_hint: str = "",
|
||||
) -> bool:
|
||||
"""Attribute Studio receiving only to the assign card that owns that session.
|
||||
|
||||
Several cards can share one Neko browser. Telemetry for /video/…/livestreaming then
|
||||
looks identical for every card on that instance — without this gate, a sibling's
|
||||
on-air stream marks unrelated cards 「频道在播」.
|
||||
"""
|
||||
snap = studio_snap if isinstance(studio_snap, dict) else {}
|
||||
if not snap:
|
||||
return False
|
||||
cid = str(youtube_channel_id or "").strip()
|
||||
url = str(snap.get("url") or "").strip()
|
||||
url_l = url.lower()
|
||||
if cid and f"/channel/{cid.lower()}" in url_l:
|
||||
return True
|
||||
hint = str(studio_url_hint or "").strip()
|
||||
if hint and "/video/" in hint and url:
|
||||
try:
|
||||
vid = hint.split("/video/", 1)[1].split("/", 1)[0].strip()
|
||||
except Exception:
|
||||
vid = ""
|
||||
if vid and vid in url:
|
||||
return True
|
||||
if group_is_pushing:
|
||||
return True
|
||||
if not neko_shared:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _http_channel_live_probe(channel_id: str) -> dict[str, Any]:
|
||||
@ -496,8 +571,15 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
seen_http.add(cid)
|
||||
http_cids.append(cid)
|
||||
if http_cids:
|
||||
# Cap fan-out — each probe may try multiple proxies with long urllib timeouts.
|
||||
sem = asyncio.Semaphore(int(os.environ.get("DY_LIVE_HTTP_PROBE_CONCURRENCY", "4") or "4"))
|
||||
|
||||
async def _bounded(cid: str) -> Any:
|
||||
async with sem:
|
||||
return await asyncio.to_thread(_http_channel_live_probe, cid)
|
||||
|
||||
http_results = await asyncio.gather(
|
||||
*[asyncio.to_thread(_http_channel_live_probe, cid) for cid in http_cids],
|
||||
*[_bounded(cid) for cid in http_cids],
|
||||
return_exceptions=True,
|
||||
)
|
||||
cid_to_targets: dict[str, list[dict[str, Any]]] = {}
|
||||
@ -705,6 +787,16 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
assign_ent["title"] = gid_to_name[gid]
|
||||
entries[f"assign:{gid}"] = assign_ent
|
||||
|
||||
# Count assign cards per Neko — shared browsers must not cross-attribute Studio.
|
||||
neko_share_count: dict[int, int] = {}
|
||||
for g in assign_groups:
|
||||
try:
|
||||
nid = int(g.get("neko_instance_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
nid = 0
|
||||
if nid > 0:
|
||||
neko_share_count[nid] = neko_share_count.get(nid, 0) + 1
|
||||
|
||||
for g in assign_groups:
|
||||
gid = str(g.get("id") or "").strip()
|
||||
if not gid:
|
||||
@ -712,6 +804,11 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
pk = str(g.get("channel_pk") or "").strip()
|
||||
row = relay_rows.get(gid) or {}
|
||||
cid = str(g.get("youtube_channel_id") or "").strip()
|
||||
try:
|
||||
group_neko_id = int(g.get("neko_instance_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
group_neko_id = 0
|
||||
neko_shared = bool(group_neko_id > 0 and neko_share_count.get(group_neko_id, 0) > 1)
|
||||
|
||||
# Already marked live via youtubei/OAuth for this shorts/channel → receiving-level truth.
|
||||
prev_live = entries.get(f"assign:{gid}") or {}
|
||||
@ -724,7 +821,9 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
studio_snap: dict[str, Any] = {}
|
||||
try:
|
||||
studio_snap = await asyncio.to_thread(
|
||||
lambda gg=g: youtube_neko.studio_snapshot_for_group(gg, max_age_sec=120.0)
|
||||
lambda gg=g: youtube_neko.studio_snapshot_for_group(
|
||||
gg, max_age_sec=120.0, include_minute_reports=False
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
studio_snap = {}
|
||||
@ -766,29 +865,43 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {}
|
||||
st = str(payload.get("live_status") or "").lower()
|
||||
health = str(payload.get("health") or "").lower()
|
||||
# Never invent receiving from Excellent/health alone (Preparing+Excellent bug).
|
||||
receiving = bool(
|
||||
signals.get("encoder_receiving")
|
||||
or signals.get("on_air")
|
||||
or st == "live"
|
||||
or health in {"excellent", "good"}
|
||||
) and not (
|
||||
signals.get("preparing_stream")
|
||||
or st in _STUDIO_DEAD_STATUSES
|
||||
or signals.get("encoder_lost")
|
||||
)
|
||||
if not receiving:
|
||||
continue
|
||||
if signals.get("encoder_lost") or st in {"encoder_lost", "waiting", "ended"}:
|
||||
if signals.get("encoder_lost") or st in _STUDIO_DEAD_STATUSES:
|
||||
continue
|
||||
age = None
|
||||
try:
|
||||
age = time.time() - float(ev.get("received_at") or 0)
|
||||
except (TypeError, ValueError):
|
||||
age = None
|
||||
if age is not None and age > _STUDIO_SAMPLE_MAX_AGE_SEC:
|
||||
continue
|
||||
studio_snap = {
|
||||
"on_air": True,
|
||||
"encoder_receiving": True,
|
||||
"encoder_receiving": bool(signals.get("encoder_receiving") or st == "live"),
|
||||
"live_page_open": True,
|
||||
"live_status": st or "live",
|
||||
"health": health,
|
||||
"viewer_count": payload.get("viewer_count"),
|
||||
"url": url[:200],
|
||||
"received_at": float(ev.get("received_at") or 0),
|
||||
"age_sec": round(age, 1) if age is not None else None,
|
||||
"detect_source": "telemetry_url_match",
|
||||
}
|
||||
break
|
||||
|
||||
# DB samples (physical local Neko CDP) — fill when in-memory snap is quiet.
|
||||
# DB samples (physical local Neko CDP / extension) — fill when in-memory snap is quiet.
|
||||
# Never trust edge_assign_live mirrors (circular sticky 在播).
|
||||
if not (
|
||||
studio_snap.get("on_air")
|
||||
or studio_snap.get("encoder_receiving")
|
||||
@ -799,46 +912,60 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]:
|
||||
|
||||
samples = await asyncio.to_thread(
|
||||
lambda: yt_studio_db.list_samples(
|
||||
group_id=gid, since_ts=now - 180.0, limit=5
|
||||
group_id=gid, since_ts=now - _STUDIO_SAMPLE_MAX_AGE_SEC, limit=5
|
||||
)
|
||||
)
|
||||
if not samples and cid:
|
||||
samples = await asyncio.to_thread(
|
||||
lambda: yt_studio_db.list_samples(
|
||||
youtube_channel_id=cid, since_ts=now - 180.0, limit=5
|
||||
youtube_channel_id=cid,
|
||||
since_ts=now - _STUDIO_SAMPLE_MAX_AGE_SEC,
|
||||
limit=5,
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
samples = []
|
||||
for s in samples or []:
|
||||
detect = str(s.get("detect_source") or "").strip().lower()
|
||||
if detect in _UNTRUSTED_SAMPLE_SOURCES:
|
||||
continue
|
||||
st = str(s.get("live_status") or "").lower()
|
||||
if st in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}:
|
||||
if st in _STUDIO_DEAD_STATUSES:
|
||||
continue
|
||||
if s.get("preparing_stream"):
|
||||
continue
|
||||
if not (s.get("on_air") or st == "live"):
|
||||
continue
|
||||
try:
|
||||
sample_age = now - float(s.get("ts") or 0)
|
||||
except (TypeError, ValueError):
|
||||
sample_age = 9999.0
|
||||
if sample_age > _STUDIO_SAMPLE_MAX_AGE_SEC:
|
||||
continue
|
||||
studio_snap = {
|
||||
"on_air": True,
|
||||
"encoder_receiving": True,
|
||||
"on_air": bool(s.get("on_air")),
|
||||
"encoder_receiving": bool(s.get("on_air") or st == "live"),
|
||||
"live_page_open": bool(s.get("live_page_open") or True),
|
||||
"live_status": st or "live",
|
||||
"health": str(s.get("health") or ""),
|
||||
"viewer_count": s.get("viewer_count"),
|
||||
"url": str(s.get("studio_url") or "")[:200],
|
||||
"received_at": float(s.get("ts") or 0),
|
||||
"detect_source": "yt_studio_samples",
|
||||
"age_sec": round(sample_age, 1),
|
||||
"detect_source": detect or "yt_studio_samples",
|
||||
"neko_ref": str(s.get("neko_ref") or ""),
|
||||
}
|
||||
break
|
||||
|
||||
receiving = bool(
|
||||
(
|
||||
studio_snap.get("encoder_receiving")
|
||||
or studio_snap.get("on_air")
|
||||
)
|
||||
and not studio_snap.get("encoder_lost")
|
||||
and str(studio_snap.get("live_status") or "").lower()
|
||||
not in {"waiting", "ended", "signed_out", "offline", "encoder_lost"}
|
||||
)
|
||||
receiving = _studio_receiving_from_snap(studio_snap)
|
||||
if receiving and not _studio_snap_belongs_to_assign_group(
|
||||
studio_snap,
|
||||
youtube_channel_id=cid,
|
||||
neko_shared=neko_shared,
|
||||
group_is_pushing=bool(row.get("is_pushing")),
|
||||
studio_url_hint=str(g.get("neko_studio_url") or ""),
|
||||
):
|
||||
receiving = False
|
||||
|
||||
# Collect public probe answers across assign / channel / shorts refs.
|
||||
public_sources = {
|
||||
|
||||
@ -673,3 +673,55 @@ async def channel_dashboard(channel_pk: str) -> dict[str, Any]:
|
||||
"recent_videos": listing.get("videos") or [],
|
||||
"shorts_today": {"push_date": day, "by_status": by_status, "total": local.get("total") or 0},
|
||||
}
|
||||
|
||||
|
||||
async def complete_active_live_broadcast(channel_pk: str) -> dict[str, Any]:
|
||||
"""Transition the channel's active liveBroadcast to ``complete`` (graceful End Stream via API).
|
||||
|
||||
Quota: liveBroadcasts.list (~1) + liveBroadcasts.transition (~50). Prefer CDP click first.
|
||||
"""
|
||||
pk = str(channel_pk or "").strip()
|
||||
if not pk:
|
||||
return {"ok": False, "error": "empty_channel_pk"}
|
||||
try:
|
||||
token, _ch = await _access_for_channel(pk)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": f"oauth:{str(exc)[:160]}"}
|
||||
try:
|
||||
data = await _get(
|
||||
"liveBroadcasts",
|
||||
token=token,
|
||||
params={"part": "id,status", "mine": "true", "maxResults": 25},
|
||||
)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "error": f"list:{str(exc)[:160]}"}
|
||||
items = data.get("items") or []
|
||||
live_ids: list[str] = []
|
||||
for it in items:
|
||||
st = str(((it.get("status") or {}).get("lifeCycleStatus") or "")).lower()
|
||||
bid = str(it.get("id") or "").strip()
|
||||
if bid and st in {"live", "testing", "ready"}:
|
||||
# Only complete truly live (or testing encoder) sessions.
|
||||
if st == "live" or st == "testing":
|
||||
live_ids.append(bid)
|
||||
if not live_ids:
|
||||
return {"ok": True, "skipped": "no_active_live", "count": 0}
|
||||
completed: list[str] = []
|
||||
errors: list[str] = []
|
||||
for bid in live_ids[:3]:
|
||||
try:
|
||||
await _post(
|
||||
"liveBroadcasts/transition",
|
||||
token=token,
|
||||
params={"broadcastStatus": "complete", "id": bid, "part": "status,id"},
|
||||
json_body={},
|
||||
)
|
||||
completed.append(bid)
|
||||
except Exception as exc:
|
||||
errors.append(f"{bid}:{str(exc)[:120]}")
|
||||
return {
|
||||
"ok": bool(completed) and not errors,
|
||||
"completed": completed,
|
||||
"errors": errors,
|
||||
"attempted": live_ids[:3],
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -208,6 +208,12 @@ def summarize_relay_group(
|
||||
elif raw_status == "error" and st.get("error") and not armed:
|
||||
business_status = "error"
|
||||
business_note = str(st.get("error") or "")[:240]
|
||||
elif raw_status == "paused_exclusive":
|
||||
business_status = "paused_exclusive"
|
||||
business_note = str(st.get("error") or "单路独占:其他频道推流中").strip()[:240]
|
||||
elif raw_status == "paused_studio":
|
||||
business_status = "paused_studio"
|
||||
business_note = str(st.get("error") or "Studio 未 on_air 熔断中").strip()[:240]
|
||||
elif raw_status == "reconnecting" and armed:
|
||||
business_status = "relay_starting"
|
||||
business_note = "推流中断,正在重连"
|
||||
@ -286,6 +292,7 @@ def summarize_relay_group(
|
||||
"url_count": len(featured_urls),
|
||||
"douyin_count": douyin_count,
|
||||
"has_stream_key": has_key,
|
||||
"stream_key": str(group.get("stream_key") or "").strip(),
|
||||
"stream_key_suffix": _key_suffix(group),
|
||||
"push_seconds": float(st.get("push_seconds") or 0) if is_pushing else 0.0,
|
||||
"started_at": float(st.get("started_at") or 0),
|
||||
|
||||
@ -107,6 +107,8 @@ def ensure_yt_assign_tables(conn: sqlite3.Connection) -> None:
|
||||
("neko_open_prefer", "TEXT NOT NULL DEFAULT 'local'"),
|
||||
# Push category: normal (manual / featured) | time_slot (24/N schedule + live sources)
|
||||
("category", "TEXT NOT NULL DEFAULT 'normal'"),
|
||||
# time_slot only: off ⇒ same as missing stream key (excluded from 24/N)
|
||||
("time_slot_armed", "INTEGER NOT NULL DEFAULT 1"),
|
||||
]:
|
||||
if col not in gcols:
|
||||
conn.execute(f"ALTER TABLE yt_assign_groups ADD COLUMN {col} {ddl}")
|
||||
@ -327,6 +329,31 @@ def group_is_time_slot(group: dict[str, Any] | None) -> bool:
|
||||
return normalize_assign_category(group.get("category")) == "time_slot"
|
||||
|
||||
|
||||
def group_time_slot_armed(group: dict[str, Any] | None) -> bool:
|
||||
"""Whether a time_slot card participates in 24/N. Default True (legacy rows)."""
|
||||
if group is None:
|
||||
return False
|
||||
if "time_slot_armed" not in group:
|
||||
return True
|
||||
v = group.get("time_slot_armed")
|
||||
if v is None:
|
||||
return True
|
||||
if isinstance(v, str):
|
||||
return v.strip().lower() not in {"0", "false", "no", "off", ""}
|
||||
return bool(v)
|
||||
|
||||
|
||||
def group_eligible_for_time_slot(group: dict[str, Any] | None) -> bool:
|
||||
"""时间段排班资格:分类=时间段 + 有 KEY + 右上角开关开。"""
|
||||
if not group or not group.get("enabled"):
|
||||
return False
|
||||
if not group_is_time_slot(group):
|
||||
return False
|
||||
if not _group_has_stream_key(group):
|
||||
return False
|
||||
return group_time_slot_armed(group)
|
||||
|
||||
|
||||
def _public_group(
|
||||
row: dict[str, Any],
|
||||
*,
|
||||
@ -340,6 +367,7 @@ def _public_group(
|
||||
out["neko_enabled"] = bool(out.get("neko_enabled"))
|
||||
out["category"] = normalize_assign_category(out.get("category"))
|
||||
out["category_label"] = ASSIGN_CATEGORY_LABELS.get(out["category"], "普通")
|
||||
out["time_slot_armed"] = group_time_slot_armed(out)
|
||||
neko_id = int(out.get("neko_instance_id") or 0)
|
||||
out["neko_instance_id"] = neko_id
|
||||
sk = str(out.get("stream_key") or "")
|
||||
@ -481,12 +509,13 @@ def _feat_select_sql() -> str:
|
||||
def list_groups(
|
||||
*,
|
||||
include_urls: bool = True,
|
||||
include_secret: bool = False,
|
||||
include_secret: bool = True,
|
||||
featured_only: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List assign groups.
|
||||
|
||||
featured_only=True: load featured URLs only (no pool/slots/enrich) — for relay status polls.
|
||||
include_secret=True by default so ops UI can show/copy live stream keys.
|
||||
"""
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
@ -730,6 +759,7 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
||||
"sort_order",
|
||||
"neko_enabled",
|
||||
"category",
|
||||
"time_slot_armed",
|
||||
}
|
||||
patch: dict[str, Any] = {}
|
||||
for k, v in fields.items():
|
||||
@ -739,6 +769,8 @@ def update_group(group_id: str, **fields: Any) -> dict[str, Any]:
|
||||
patch[k] = 1 if v else 0
|
||||
elif k == "neko_enabled":
|
||||
patch[k] = 1 if v else 0
|
||||
elif k == "time_slot_armed":
|
||||
patch[k] = 1 if v else 0
|
||||
elif k == "category":
|
||||
patch[k] = normalize_assign_category(v)
|
||||
elif k == "sort_order":
|
||||
@ -1716,9 +1748,7 @@ def group_in_rotation_slot(group_id: str, *, keyed_only: bool | None = None) ->
|
||||
keyed_only = bool(_db.get_settings_map().get("youtube_relay_time_slot_mode"))
|
||||
except Exception:
|
||||
keyed_only = False
|
||||
if keyed_only and not _group_has_stream_key(g):
|
||||
return False
|
||||
if keyed_only and not group_is_time_slot(g):
|
||||
if keyed_only and not group_eligible_for_time_slot(g):
|
||||
return False
|
||||
ch_key = _group_yt_channel_key(g)
|
||||
sched = build_rotation_schedule(include_urls=False, keyed_only=keyed_only)
|
||||
@ -1763,8 +1793,8 @@ def build_rotation_schedule(
|
||||
keyed_only = False
|
||||
enabled = [g for g in raw if g.get("enabled")]
|
||||
if keyed_only:
|
||||
# 时间段排班:仅「时间段」分类 + 有 KEY 的频道参与 24/N
|
||||
keyed = [g for g in enabled if _group_has_stream_key(g) and group_is_time_slot(g)]
|
||||
# 时间段排班:时间段分类 + 有 KEY + 开关开(关=等同无 KEY)
|
||||
keyed = [g for g in enabled if group_eligible_for_time_slot(g)]
|
||||
rotation_rows = _dedupe_groups_by_yt_channel(keyed)
|
||||
else:
|
||||
rotation_rows = [(g, []) for g in enabled]
|
||||
@ -1836,6 +1866,36 @@ def build_rotation_schedule(
|
||||
}
|
||||
|
||||
|
||||
def overlay_timeslot_test_schedule(
|
||||
schedule: dict[str, Any] | None,
|
||||
*,
|
||||
test_on: bool,
|
||||
test_group_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Mark forced test winner as active for UI; keep real clock in schedule_active."""
|
||||
out = dict(schedule or {})
|
||||
want = str(test_group_id or "").strip()
|
||||
out["test_mode"] = bool(test_on)
|
||||
out["test_group_id"] = want if test_on else ""
|
||||
channels: list[dict[str, Any]] = []
|
||||
for raw in out.get("channels") or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
c = dict(raw)
|
||||
c["schedule_active"] = bool(c.get("active"))
|
||||
if test_on and want:
|
||||
gid = str(c.get("group_id") or "")
|
||||
aliases = [str(x) for x in (c.get("alias_group_ids") or []) if x]
|
||||
forced = gid == want or want in aliases
|
||||
c["active"] = forced
|
||||
c["test_force"] = forced
|
||||
else:
|
||||
c["test_force"] = False
|
||||
channels.append(c)
|
||||
out["channels"] = channels
|
||||
return out
|
||||
|
||||
|
||||
def auto_fill_slots_from_live(*, group_id: str = "", limit: int = 24, all_groups: bool = False, force: bool = False) -> dict[str, Any]:
|
||||
"""Fill slot lists from Douyin live + 24h session stats; round-robin across groups."""
|
||||
ranked = _rank_douyin_rooms_for_relay(limit=max(8, min(int(limit), 80)))
|
||||
|
||||
@ -699,6 +699,11 @@ def list_yt_long_jobs(*, limit: int = 40, push_date: str = "") -> list[dict[str,
|
||||
|
||||
|
||||
def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]:
|
||||
"""Pending masters ready to record.
|
||||
|
||||
Channel may be empty when YouTube upload slots were full at enqueue time
|
||||
(cascade-only path). Those jobs must still be claimable for recording.
|
||||
"""
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
@ -706,9 +711,12 @@ def list_pending_yt_long_jobs(*, limit: int = 5) -> list[dict[str, Any]]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT j.* FROM yt_long_jobs j
|
||||
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||||
LEFT JOIN yt_long_channels c ON c.id = j.channel_pk AND j.channel_pk != ''
|
||||
WHERE j.status = 'pending'
|
||||
AND c.enabled = 1
|
||||
AND (
|
||||
IFNULL(j.channel_pk, '') = ''
|
||||
OR c.enabled = 1
|
||||
)
|
||||
ORDER BY j.created_at ASC
|
||||
LIMIT ?
|
||||
""",
|
||||
@ -760,15 +768,17 @@ def delete_yt_long_jobs_for_channel(channel_pk: str) -> dict[str, int]:
|
||||
conn.close()
|
||||
|
||||
|
||||
def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
||||
def claim_due_yt_long_upload(*, skip_profile_ids: set[str] | None = None) -> dict[str, Any] | None:
|
||||
now = time.time()
|
||||
skip = {str(x).strip().upper() for x in (skip_profile_ids or set()) if str(x).strip()}
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
row = conn.execute(
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT j.* FROM yt_long_jobs j
|
||||
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
|
||||
FROM yt_long_jobs j
|
||||
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||||
WHERE j.status = 'scheduled'
|
||||
AND c.enabled = 1
|
||||
@ -776,13 +786,20 @@ def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
||||
AND j.upload_at > 0
|
||||
AND j.upload_at <= ?
|
||||
ORDER BY j.upload_at ASC, j.created_at ASC
|
||||
LIMIT 1
|
||||
LIMIT 30
|
||||
""",
|
||||
(now,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
).fetchall()
|
||||
picked = None
|
||||
for row in rows:
|
||||
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
|
||||
if pid in skip:
|
||||
continue
|
||||
picked = row
|
||||
break
|
||||
if not picked:
|
||||
return None
|
||||
jid = str(row["id"])
|
||||
jid = str(picked["id"])
|
||||
cur = conn.execute(
|
||||
"""
|
||||
UPDATE yt_long_jobs
|
||||
@ -802,6 +819,43 @@ def claim_due_yt_long_upload() -> dict[str, Any] | None:
|
||||
conn.close()
|
||||
|
||||
|
||||
def defer_profile_yt_long_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
|
||||
"""Push due auto-uploads for this OAuth Client past cool-down."""
|
||||
pid = str(profile_id or "A").strip().upper() or "A"
|
||||
until = float(until_ts or 0)
|
||||
if until <= time.time():
|
||||
return 0
|
||||
now = time.time()
|
||||
moved = 0
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_yt_long_tables(conn)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT j.id FROM yt_long_jobs j
|
||||
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||||
WHERE j.status = 'scheduled'
|
||||
AND j.clip_path != ''
|
||||
AND j.upload_at > 0
|
||||
AND j.upload_at <= ?
|
||||
AND UPPER(TRIM(COALESCE(NULLIF(c.oauth_profile_id, ''), 'A'))) = ?
|
||||
""",
|
||||
(now + 30, pid),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
conn.execute(
|
||||
"UPDATE yt_long_jobs SET upload_at = ?, error = ?, updated_at = ? WHERE id = ?",
|
||||
(until + 15, (reason or "YouTube 接口配额冷静中,稍后自动重试")[:300], now, str(row["id"])),
|
||||
)
|
||||
moved += 1
|
||||
if moved:
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return moved
|
||||
|
||||
|
||||
def count_yt_long_jobs_by_status(status: str, *, push_date: str = "") -> int:
|
||||
day = push_date or ""
|
||||
with _lock:
|
||||
@ -1260,7 +1314,9 @@ def channel_board(push_date: str = "") -> dict[str, Any]:
|
||||
(day, cid),
|
||||
).fetchall()
|
||||
}
|
||||
gap = max(0, dmax - used) if ch.get("enabled") else 0
|
||||
uploaded = int(by.get("uploaded") or 0)
|
||||
# Progress / gap follow uploaded (Shorts parity); used keeps slot reservation.
|
||||
gap = max(0, dmax - uploaded) if ch.get("enabled") else 0
|
||||
total_gap += gap
|
||||
try:
|
||||
ypp_ok = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1)
|
||||
@ -1302,7 +1358,7 @@ def channel_board(push_date: str = "") -> dict[str, Any]:
|
||||
"daily_max": dmax,
|
||||
"used": used,
|
||||
"gap": gap,
|
||||
"uploaded": int(by.get("uploaded") or 0),
|
||||
"uploaded": uploaded,
|
||||
"scheduled": int(by.get("scheduled") or 0) + int(by.get("uploading") or 0),
|
||||
"pending": int(by.get("pending") or 0) + int(by.get("recording") or 0),
|
||||
"failed": int(by.get("failed") or 0),
|
||||
|
||||
@ -655,8 +655,11 @@ class YtLongPipeline:
|
||||
|
||||
if cfg.get("yt_long_auto_upload", True):
|
||||
max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
||||
from .shorts_yt_quota import blocked_profile_ids
|
||||
|
||||
skip = blocked_profile_ids(cfg)
|
||||
while self._active_uploads < max_up:
|
||||
job = yt_long_db.claim_due_yt_long_upload()
|
||||
job = yt_long_db.claim_due_yt_long_upload(skip_profile_ids=skip or None)
|
||||
if not job:
|
||||
break
|
||||
self._active_uploads += 1
|
||||
@ -818,29 +821,61 @@ class YtLongPipeline:
|
||||
except Exception as exc:
|
||||
self.last_error = str(exc)[:240]
|
||||
msg = str(exc)
|
||||
if "QUOTA_EXCEEDED" in msg or "quotaExceeded" in msg:
|
||||
from .shorts_upload import is_upload_quota_error
|
||||
|
||||
is_quota = (
|
||||
"QUOTA_EXCEEDED" in msg
|
||||
or "quotaExceeded" in msg
|
||||
or is_upload_quota_error(msg)
|
||||
)
|
||||
if is_quota:
|
||||
should_notify = True
|
||||
try:
|
||||
from .shorts_yt_quota import pause_uploads_until_reset, profile_id_for_channel
|
||||
from .shorts_yt_quota import mark_api_quota_cooldown, profile_id_for_channel
|
||||
|
||||
ch = yt_long_db.get_yt_long_channel(str(job.get("channel_pk") or ""))
|
||||
pid = profile_id_for_channel(ch) if ch else "A"
|
||||
pause_uploads_until_reset(profile_id=pid, reason=msg[:160])
|
||||
until, should_notify = mark_api_quota_cooldown(
|
||||
profile_id=pid, reason=msg[:160]
|
||||
)
|
||||
try:
|
||||
yt_long_db.defer_profile_yt_long_uploads(
|
||||
pid,
|
||||
until,
|
||||
reason=f"Client {pid} 接口配额冷静,稍后自动重试",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
yt_long_db.mark_yt_long_api_limited(reason=msg[:160])
|
||||
yt_long_db.reconcile_yt_long_upload_caps()
|
||||
except Exception:
|
||||
pass
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(job.get("id") or ""),
|
||||
status="failed",
|
||||
error=str(exc)[:500],
|
||||
finished_at=time.time(),
|
||||
)
|
||||
_emit(
|
||||
"yt_long_fail",
|
||||
"error",
|
||||
f"长视频上传失败:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}",
|
||||
job,
|
||||
)
|
||||
should_notify = True
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(job.get("id") or ""),
|
||||
status="failed",
|
||||
error=str(exc)[:500],
|
||||
finished_at=time.time(),
|
||||
)
|
||||
if should_notify:
|
||||
_emit(
|
||||
"yt_long_fail",
|
||||
"warn",
|
||||
f"长视频:YouTube 接口配额用尽(冷静后重试,不拦手动):{str(exc)[:80]}",
|
||||
job,
|
||||
)
|
||||
else:
|
||||
yt_long_db.update_yt_long_job(
|
||||
str(job.get("id") or ""),
|
||||
status="failed",
|
||||
error=str(exc)[:500],
|
||||
finished_at=time.time(),
|
||||
)
|
||||
_emit(
|
||||
"yt_long_fail",
|
||||
"error",
|
||||
f"长视频上传失败:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}",
|
||||
job,
|
||||
)
|
||||
finally:
|
||||
self._active_uploads = max(0, self._active_uploads - 1)
|
||||
|
||||
|
||||
346
backend/app/yt_stream_key_db.py
Normal file
346
backend/app/yt_stream_key_db.py
Normal file
@ -0,0 +1,346 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Standalone YouTube channel ↔ stream-key registry (archive / recovery).
|
||||
|
||||
Isolated from yt_assign_groups relay path and Neko. Editing this table never
|
||||
starts/stops Neko or mutates assign group stream_key unless an explicit
|
||||
write-back API is called later.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from .db import _connect, _lock, _row_to_dict
|
||||
from .yt_assign_db import _sanitize_stream_key
|
||||
|
||||
|
||||
def ensure_stream_key_tables(conn: sqlite3.Connection) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS yt_stream_key_registry (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
youtube_channel_id TEXT NOT NULL DEFAULT '',
|
||||
channel_pk TEXT NOT NULL DEFAULT '',
|
||||
assign_group_id TEXT NOT NULL DEFAULT '',
|
||||
stream_key TEXT NOT NULL DEFAULT '',
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at REAL NOT NULL,
|
||||
updated_at REAL NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_yt_stream_key_ycid "
|
||||
"ON yt_stream_key_registry(youtube_channel_id)"
|
||||
)
|
||||
|
||||
|
||||
def _mask(sk: str) -> dict[str, Any]:
|
||||
raw = str(sk or "")
|
||||
return {
|
||||
"has_stream_key": bool(raw.strip()),
|
||||
"stream_key_masked": ("***" + raw[-4:]) if len(raw) > 6 else ("***" if raw else ""),
|
||||
"stream_key_suffix": raw[-4:] if len(raw) >= 4 else raw,
|
||||
}
|
||||
|
||||
|
||||
def _public_row(row: dict[str, Any], *, include_secret: bool = False) -> dict[str, Any]:
|
||||
out = dict(row)
|
||||
sk = str(out.get("stream_key") or "")
|
||||
out.update(_mask(sk))
|
||||
if include_secret:
|
||||
out["stream_key"] = sk
|
||||
else:
|
||||
out.pop("stream_key", None)
|
||||
return out
|
||||
|
||||
|
||||
def list_entries(*, include_secret: bool = True) -> dict[str, Any]:
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_stream_key_tables(conn)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT * FROM yt_stream_key_registry
|
||||
ORDER BY sort_order ASC, updated_at DESC, name ASC
|
||||
"""
|
||||
).fetchall()
|
||||
items = [_public_row(_row_to_dict(r), include_secret=include_secret) for r in rows]
|
||||
return {"ok": True, "items": items, "total": len(items)}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_entry(entry_id: str, *, include_secret: bool = False) -> Optional[dict[str, Any]]:
|
||||
eid = str(entry_id or "").strip()
|
||||
if not eid:
|
||||
return None
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_stream_key_tables(conn)
|
||||
row = conn.execute(
|
||||
"SELECT * FROM yt_stream_key_registry WHERE id=?", (eid,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return _public_row(_row_to_dict(row), include_secret=include_secret)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_entry(
|
||||
*,
|
||||
entry_id: str = "",
|
||||
name: str = "",
|
||||
youtube_channel_id: str = "",
|
||||
channel_pk: str = "",
|
||||
assign_group_id: str = "",
|
||||
stream_key: str = "",
|
||||
note: str = "",
|
||||
sort_order: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
eid = str(entry_id or "").strip() or str(uuid.uuid4())
|
||||
sk = _sanitize_stream_key(stream_key)
|
||||
ycid = str(youtube_channel_id or "").strip()
|
||||
name_s = str(name or "").strip() or ycid or "未命名"
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_stream_key_tables(conn)
|
||||
existing = conn.execute(
|
||||
"SELECT * FROM yt_stream_key_registry WHERE id=?", (eid,)
|
||||
).fetchone()
|
||||
if existing:
|
||||
prev = _row_to_dict(existing)
|
||||
# Keep previous key if caller sent empty (edit other fields only)
|
||||
if not sk:
|
||||
sk = str(prev.get("stream_key") or "")
|
||||
so = int(prev.get("sort_order") or 0) if sort_order is None else int(sort_order)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE yt_stream_key_registry SET
|
||||
name=?, youtube_channel_id=?, channel_pk=?, assign_group_id=?,
|
||||
stream_key=?, note=?, sort_order=?, updated_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(
|
||||
name_s,
|
||||
ycid,
|
||||
str(channel_pk or "").strip(),
|
||||
str(assign_group_id or "").strip(),
|
||||
sk,
|
||||
str(note or "").strip(),
|
||||
so,
|
||||
now,
|
||||
eid,
|
||||
),
|
||||
)
|
||||
else:
|
||||
so = 0 if sort_order is None else int(sort_order)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_stream_key_registry(
|
||||
id, name, youtube_channel_id, channel_pk, assign_group_id,
|
||||
stream_key, note, sort_order, created_at, updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
eid,
|
||||
name_s,
|
||||
ycid,
|
||||
str(channel_pk or "").strip(),
|
||||
str(assign_group_id or "").strip(),
|
||||
sk,
|
||||
str(note or "").strip(),
|
||||
so,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute(
|
||||
"SELECT * FROM yt_stream_key_registry WHERE id=?", (eid,)
|
||||
).fetchone()
|
||||
return _public_row(_row_to_dict(row), include_secret=True)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete_entry(entry_id: str) -> bool:
|
||||
eid = str(entry_id or "").strip()
|
||||
if not eid:
|
||||
return False
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_stream_key_tables(conn)
|
||||
cur = conn.execute("DELETE FROM yt_stream_key_registry WHERE id=?", (eid,))
|
||||
conn.commit()
|
||||
return cur.rowcount > 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def import_from_assign_groups(*, replace: bool = False) -> dict[str, Any]:
|
||||
"""Snapshot current assign-group keys into registry. Does not modify assign/Neko."""
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_stream_key_tables(conn)
|
||||
# assign tables must exist
|
||||
try:
|
||||
from .yt_assign_db import ensure_yt_assign_tables
|
||||
|
||||
ensure_yt_assign_tables(conn)
|
||||
except Exception:
|
||||
pass
|
||||
if replace:
|
||||
conn.execute("DELETE FROM yt_stream_key_registry")
|
||||
assign_rows = conn.execute(
|
||||
"""
|
||||
SELECT id, name, channel_pk, youtube_channel_id, stream_key, note, sort_order
|
||||
FROM yt_assign_groups
|
||||
ORDER BY sort_order ASC, name ASC
|
||||
"""
|
||||
).fetchall()
|
||||
inserted = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
now = time.time()
|
||||
for r in assign_rows:
|
||||
d = _row_to_dict(r)
|
||||
sk = _sanitize_stream_key(str(d.get("stream_key") or ""))
|
||||
ycid = str(d.get("youtube_channel_id") or "").strip()
|
||||
gid = str(d.get("id") or "").strip()
|
||||
if not sk and not ycid:
|
||||
skipped += 1
|
||||
continue
|
||||
existing = None
|
||||
if gid:
|
||||
existing = conn.execute(
|
||||
"SELECT id, stream_key FROM yt_stream_key_registry WHERE assign_group_id=?",
|
||||
(gid,),
|
||||
).fetchone()
|
||||
if existing is None and ycid:
|
||||
existing = conn.execute(
|
||||
"SELECT id, stream_key FROM yt_stream_key_registry WHERE youtube_channel_id=? LIMIT 1",
|
||||
(ycid,),
|
||||
).fetchone()
|
||||
name_s = str(d.get("name") or "").strip() or ycid or "未命名"
|
||||
if existing:
|
||||
ed = _row_to_dict(existing)
|
||||
eid = str(ed["id"])
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE yt_stream_key_registry SET
|
||||
name=?, youtube_channel_id=?, channel_pk=?, assign_group_id=?,
|
||||
stream_key=?, note=?, sort_order=?, updated_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(
|
||||
name_s,
|
||||
ycid,
|
||||
str(d.get("channel_pk") or "").strip(),
|
||||
gid,
|
||||
sk or str(ed.get("stream_key") or ""),
|
||||
str(d.get("note") or "").strip(),
|
||||
int(d.get("sort_order") or 0),
|
||||
now,
|
||||
eid,
|
||||
),
|
||||
)
|
||||
updated += 1
|
||||
else:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_stream_key_registry(
|
||||
id, name, youtube_channel_id, channel_pk, assign_group_id,
|
||||
stream_key, note, sort_order, created_at, updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()),
|
||||
name_s,
|
||||
ycid,
|
||||
str(d.get("channel_pk") or "").strip(),
|
||||
gid,
|
||||
sk,
|
||||
str(d.get("note") or "").strip(),
|
||||
int(d.get("sort_order") or 0),
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
inserted += 1
|
||||
conn.commit()
|
||||
total = conn.execute("SELECT COUNT(*) FROM yt_stream_key_registry").fetchone()[0]
|
||||
return {
|
||||
"ok": True,
|
||||
"inserted": inserted,
|
||||
"updated": updated,
|
||||
"skipped": skipped,
|
||||
"total": int(total),
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def export_all() -> dict[str, Any]:
|
||||
return list_entries(include_secret=True)
|
||||
|
||||
|
||||
def import_payload(items: list[dict[str, Any]], *, replace: bool = False) -> dict[str, Any]:
|
||||
"""Merge/replace registry from peer export. Never touches assign/Neko."""
|
||||
if not isinstance(items, list):
|
||||
raise ValueError("items must be a list")
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_stream_key_tables(conn)
|
||||
if replace:
|
||||
conn.execute("DELETE FROM yt_stream_key_registry")
|
||||
now = time.time()
|
||||
n = 0
|
||||
for it in items:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
eid = str(it.get("id") or "").strip() or str(uuid.uuid4())
|
||||
sk = _sanitize_stream_key(str(it.get("stream_key") or ""))
|
||||
ycid = str(it.get("youtube_channel_id") or "").strip()
|
||||
name_s = str(it.get("name") or "").strip() or ycid or "未命名"
|
||||
conn.execute(
|
||||
"DELETE FROM yt_stream_key_registry WHERE id=?", (eid,)
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO yt_stream_key_registry(
|
||||
id, name, youtube_channel_id, channel_pk, assign_group_id,
|
||||
stream_key, note, sort_order, created_at, updated_at
|
||||
) VALUES (?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
eid,
|
||||
name_s,
|
||||
ycid,
|
||||
str(it.get("channel_pk") or "").strip(),
|
||||
str(it.get("assign_group_id") or "").strip(),
|
||||
sk,
|
||||
str(it.get("note") or "").strip(),
|
||||
int(it.get("sort_order") or 0),
|
||||
float(it.get("created_at") or now),
|
||||
now,
|
||||
),
|
||||
)
|
||||
n += 1
|
||||
conn.commit()
|
||||
total = conn.execute("SELECT COUNT(*) FROM yt_stream_key_registry").fetchone()[0]
|
||||
return {"ok": True, "imported": n, "total": int(total)}
|
||||
finally:
|
||||
conn.close()
|
||||
File diff suppressed because it is too large
Load Diff
@ -384,15 +384,34 @@ launch_browser() {
|
||||
--disable-default-apps \
|
||||
--disable-translate \
|
||||
--metrics-recording-only \
|
||||
--no-default-browser-check
|
||||
--no-default-browser-check \
|
||||
--renderer-process-limit=1 \
|
||||
--process-per-site \
|
||||
--disk-cache-size=1 \
|
||||
--media-cache-size=1 \
|
||||
--disable-features=IsolateOrigins,site-per-process,TranslateUI,BackForwardCache,WebAssemblySimd,WebAssemblyLazyCompilation,OptimizationGuideModelDownloading,OptimizationHints,PageContentAnnotations,PassageEmbeddings,WebAssembly,CalculateNativeWinOcclusion,CanvasOopRasterization,Vulkan,UseSkiaRenderer,InterestFeedContentSuggestions,OfflineAutoFetch,HeavyAdIntervention,AutofillServerCommunication,DialMediaRouteProvider \
|
||||
--js-flags="--max-old-space-size=160 --jitless --no-opt" \
|
||||
--disable-background-networking \
|
||||
--disable-component-update \
|
||||
--disable-sync \
|
||||
--disable-notifications \
|
||||
--mute-audio \
|
||||
--autoplay-policy=user-gesture-required \
|
||||
--memory-model=low
|
||||
if [ -n "$launch_window_flag" ]; then
|
||||
set -- "$@" "$launch_window_flag"
|
||||
fi
|
||||
if [ -n "$launch_url" ]; then
|
||||
set -- "$@" "$launch_url"
|
||||
fi
|
||||
# Prefer host OOM killer keep Chrome over API/ffmpeg (negative = protected).
|
||||
# Mask AVX512-ish paths that SIGILL on some colo CPUs / Chrome builds
|
||||
export OPENSSL_ia32cap="~0x200000200000000"
|
||||
export CHROME_FORCE_WAKE_ON_LAN=0
|
||||
echo -800 > /proc/self/oom_score_adj 2>/dev/null || true
|
||||
"$@" &
|
||||
browser_pid=$!
|
||||
echo -900 > "/proc/${browser_pid}/oom_score_adj" 2>/dev/null || true
|
||||
}
|
||||
|
||||
visible_window_count() {
|
||||
@ -430,12 +449,21 @@ focus_live_studio_tab_once() {
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
def fetch_tabs():
|
||||
with urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3) as resp:
|
||||
return json.loads(resp.read().decode("utf-8", "replace"))
|
||||
|
||||
def close_tab(tid: str) -> None:
|
||||
if not tid:
|
||||
return
|
||||
try:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for _ in range(40):
|
||||
try:
|
||||
tabs = fetch_tabs()
|
||||
@ -446,44 +474,126 @@ else:
|
||||
raise SystemExit(0)
|
||||
|
||||
def is_live(url: str) -> bool:
|
||||
return "studio.youtube.com" in url and "livestreaming" in url
|
||||
u = (url or "").lower()
|
||||
return "studio.youtube.com" in u and "livestreaming" in u
|
||||
|
||||
def is_junk(url: str) -> bool:
|
||||
return any(
|
||||
x in url
|
||||
for x in (
|
||||
"tampermonkey.net/changelog",
|
||||
"tampermonkey.net/installed",
|
||||
"accounts.google.com/ServiceLogin",
|
||||
"accounts.google.com/v3/signin",
|
||||
"accounts.google.com/accountchooser",
|
||||
"accounts.google.com/RotateCookiesPage",
|
||||
)
|
||||
)
|
||||
def is_keep(url: str) -> bool:
|
||||
u = (url or "").lower()
|
||||
if is_live(u):
|
||||
return True
|
||||
# Keep mid-login flows only.
|
||||
if "accounts.google.com" in u and any(x in u for x in ("signin", "accountchooser", "identifier", "challenge", "servicelogin")):
|
||||
return True
|
||||
return False
|
||||
|
||||
live = [t for t in tabs if is_live(t.get("url") or "")]
|
||||
for tab in tabs:
|
||||
if not is_junk(tab.get("url") or ""):
|
||||
pages = [t for t in tabs if (t.get("type") or "") == "page"]
|
||||
live = [t for t in pages if is_live(t.get("url") or "")]
|
||||
# Close every non-essential page (google.com / mail / random youtube / duplicates).
|
||||
keep_live_id = (live[0].get("id") if live else "") or ""
|
||||
for tab in pages:
|
||||
url = tab.get("url") or ""
|
||||
tid = tab.get("id") or ""
|
||||
if keep_live_id and tid == keep_live_id:
|
||||
continue
|
||||
tid = tab.get("id")
|
||||
if is_live(url) and keep_live_id and tid != keep_live_id:
|
||||
close_tab(tid)
|
||||
continue
|
||||
if is_keep(url):
|
||||
continue
|
||||
close_tab(tid)
|
||||
|
||||
if keep_live_id:
|
||||
try:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{keep_live_id}", timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
PY
|
||||
}
|
||||
|
||||
# Periodic GC: close junk tabs + soft-reload Studio Live to reclaim V8 heap.
|
||||
prune_and_soft_reload_studio() {
|
||||
case "${NEKO_STUDIO_MEM_GC:-1}" in
|
||||
0|false|FALSE|off|OFF|disable|disabled)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
command -v python3 >/dev/null 2>&1 || return 0
|
||||
DO_RELOAD="${1:-0}" python3 - <<'PY'
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
def fetch_tabs():
|
||||
with urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=3) as resp:
|
||||
return json.loads(resp.read().decode("utf-8", "replace"))
|
||||
|
||||
def close_tab(tid: str) -> None:
|
||||
if not tid:
|
||||
continue
|
||||
return
|
||||
try:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/close/{tid}", timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not live:
|
||||
def is_live(url: str) -> bool:
|
||||
u = (url or "").lower()
|
||||
return "studio.youtube.com" in u and "livestreaming" in u
|
||||
|
||||
def is_keep(url: str) -> bool:
|
||||
u = (url or "").lower()
|
||||
if is_live(u):
|
||||
return True
|
||||
if "accounts.google.com" in u and any(x in u for x in ("signin", "accountchooser", "identifier", "challenge", "servicelogin")):
|
||||
return True
|
||||
return False
|
||||
|
||||
try:
|
||||
tabs = fetch_tabs()
|
||||
except Exception:
|
||||
raise SystemExit(0)
|
||||
|
||||
target = live[0]
|
||||
tid = target.get("id")
|
||||
if not tid:
|
||||
raise SystemExit(0)
|
||||
try:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}", timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
pages = [t for t in tabs if (t.get("type") or "") == "page"]
|
||||
live = [t for t in pages if is_live(t.get("url") or "")]
|
||||
keep_live = live[0] if live else None
|
||||
keep_id = (keep_live or {}).get("id") or ""
|
||||
keep_url = (keep_live or {}).get("url") or ""
|
||||
|
||||
for tab in pages:
|
||||
tid = tab.get("id") or ""
|
||||
url = tab.get("url") or ""
|
||||
if keep_id and tid == keep_id:
|
||||
continue
|
||||
if is_live(url) and keep_id and tid != keep_id:
|
||||
close_tab(tid)
|
||||
continue
|
||||
if is_keep(url):
|
||||
continue
|
||||
close_tab(tid)
|
||||
|
||||
do_reload = str(os.environ.get("DO_RELOAD") or "0").strip() in {"1", "true", "TRUE", "yes"}
|
||||
if do_reload and keep_url:
|
||||
try:
|
||||
q = urllib.parse.quote(keep_url, safe="")
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/new?{q}", timeout=5)
|
||||
time.sleep(2.5)
|
||||
tabs2 = fetch_tabs()
|
||||
lives = [t for t in tabs2 if (t.get("type") or "") == "page" and is_live(t.get("url") or "")]
|
||||
# Keep newest live tab; close older duplicates.
|
||||
for tab in lives[:-1]:
|
||||
close_tab(tab.get("id") or "")
|
||||
if lives:
|
||||
tid = lives[-1].get("id") or ""
|
||||
if tid:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{tid}", timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
elif keep_id:
|
||||
try:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:9222/json/activate/{keep_id}", timeout=2)
|
||||
except Exception:
|
||||
pass
|
||||
PY
|
||||
}
|
||||
|
||||
@ -542,6 +652,10 @@ while :; do
|
||||
focused_live_tab=0
|
||||
startup_misses=0
|
||||
closed_misses=0
|
||||
loop_ticks=0
|
||||
# ~90s prune; ~12min soft-reload (sleep 2 per tick)
|
||||
prune_every="${NEKO_STUDIO_PRUNE_TICKS:-45}"
|
||||
reload_every="${NEKO_STUDIO_RELOAD_TICKS:-360}"
|
||||
while kill -0 "$browser_pid" 2>/dev/null; do
|
||||
if browser_healthy; then
|
||||
if [ "$focused_live_tab" -eq 0 ]; then
|
||||
@ -551,6 +665,22 @@ while :; do
|
||||
seen_window=1
|
||||
startup_misses=0
|
||||
closed_misses=0
|
||||
loop_ticks=$((loop_ticks + 1))
|
||||
if [ "$loop_ticks" -gt 0 ] && [ $((loop_ticks % prune_every)) -eq 0 ]; then
|
||||
# Default: only prune junk tabs. Soft-reload Studio is OPT-IN
|
||||
# (NEKO_STUDIO_SOFT_RELOAD=1) — never touch the RTMP push path;
|
||||
# soft-reload is Studio UI only and is disabled to avoid any ops risk
|
||||
# near live recommendation / stream continuity.
|
||||
do_reload=0
|
||||
case "${NEKO_STUDIO_SOFT_RELOAD:-0}" in
|
||||
1|true|TRUE|yes|YES|on|ON)
|
||||
if [ $((loop_ticks % reload_every)) -eq 0 ]; then
|
||||
do_reload=1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
prune_and_soft_reload_studio "$do_reload" || true
|
||||
fi
|
||||
else
|
||||
if [ "$seen_window" -eq 0 ]; then
|
||||
startup_misses=$((startup_misses + 1))
|
||||
|
||||
341
backend/neko/cdp_end_stream.py
Normal file
341
backend/neko/cdp_end_stream.py
Normal file
@ -0,0 +1,341 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""CDP: click YouTube Studio End Stream (+ confirm dialog End) inside Neko Chrome.
|
||||
|
||||
Handles the modal:
|
||||
End Stream
|
||||
Your stream will stop immediately...
|
||||
[Not yet] [End]
|
||||
|
||||
Run via: docker exec -i <neko> python3 - < this file
|
||||
Prints one JSON line to stdout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
|
||||
def ws_connect(url: str) -> socket.socket:
|
||||
assert url.startswith("ws://"), url
|
||||
hostport, path = url[5:].split("/", 1)
|
||||
path = "/" + path
|
||||
host, port_s = hostport.split(":")
|
||||
port = int(port_s)
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
sock = socket.create_connection((host, port), timeout=8)
|
||||
req = (
|
||||
f"GET {path} HTTP/1.1\r\n"
|
||||
f"Host: {hostport}\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Key: {key}\r\n"
|
||||
"Sec-WebSocket-Version: 13\r\n"
|
||||
"\r\n"
|
||||
).encode()
|
||||
sock.sendall(req)
|
||||
buf = b""
|
||||
while b"\r\n\r\n" not in buf:
|
||||
chunk = sock.recv(4096)
|
||||
if not chunk:
|
||||
raise RuntimeError("ws handshake closed")
|
||||
buf += chunk
|
||||
return sock
|
||||
|
||||
|
||||
def ws_send(sock: socket.socket, payload: dict) -> None:
|
||||
data = json.dumps(payload).encode()
|
||||
mask = os.urandom(4)
|
||||
header = bytearray([0x81])
|
||||
n = len(data)
|
||||
if n < 126:
|
||||
header.append(0x80 | n)
|
||||
elif n < 65536:
|
||||
header.append(0x80 | 126)
|
||||
header.extend(struct.pack("!H", n))
|
||||
else:
|
||||
header.append(0x80 | 127)
|
||||
header.extend(struct.pack("!Q", n))
|
||||
header.extend(mask)
|
||||
masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
|
||||
sock.sendall(bytes(header) + masked)
|
||||
|
||||
|
||||
def ws_recv(sock: socket.socket):
|
||||
def readexact(n: int) -> bytes:
|
||||
out = b""
|
||||
while len(out) < n:
|
||||
chunk = sock.recv(n - len(out))
|
||||
if not chunk:
|
||||
raise RuntimeError("ws closed")
|
||||
out += chunk
|
||||
return out
|
||||
|
||||
hdr = readexact(2)
|
||||
b1, b2 = hdr[0], hdr[1]
|
||||
opcode = b1 & 0x0F
|
||||
masked = (b2 & 0x80) != 0
|
||||
ln = b2 & 0x7F
|
||||
if ln == 126:
|
||||
ln = struct.unpack("!H", readexact(2))[0]
|
||||
elif ln == 127:
|
||||
ln = struct.unpack("!Q", readexact(8))[0]
|
||||
mask = readexact(4) if masked else b""
|
||||
data = readexact(ln)
|
||||
if masked:
|
||||
data = bytes(b ^ mask[i % 4] for i, b in enumerate(data))
|
||||
if opcode == 0x8:
|
||||
return None
|
||||
if opcode != 0x1:
|
||||
return {"id": None}
|
||||
return json.loads(data.decode())
|
||||
|
||||
|
||||
def eval_js(sock: socket.socket, expression: str, *, req_id: int, timeout: float = 6.0):
|
||||
ws_send(
|
||||
sock,
|
||||
{
|
||||
"id": req_id,
|
||||
"method": "Runtime.evaluate",
|
||||
"params": {
|
||||
"expression": expression,
|
||||
"returnByValue": True,
|
||||
"awaitPromise": True,
|
||||
},
|
||||
},
|
||||
)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
msg = ws_recv(sock)
|
||||
if not msg:
|
||||
break
|
||||
if msg.get("id") == req_id:
|
||||
return ((msg.get("result") or {}).get("result") or {}).get("value")
|
||||
return None
|
||||
|
||||
|
||||
CLICK_JS = r"""
|
||||
(() => {
|
||||
const END_RE = /^(end stream|stop streaming|结束直播|停止直播)$/i;
|
||||
const CANCEL_RE = /not yet|not now|cancel|keep|继续|取消|还没有/i;
|
||||
|
||||
function visible(el) {
|
||||
if (!el || !el.getBoundingClientRect) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.width < 2 || r.height < 2) return false;
|
||||
const st = window.getComputedStyle ? getComputedStyle(el) : null;
|
||||
if (st && (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0)) return false;
|
||||
return true;
|
||||
}
|
||||
function* deepNodes(root) {
|
||||
const stack = [root];
|
||||
while (stack.length) {
|
||||
const n = stack.pop();
|
||||
if (!n) continue;
|
||||
yield n;
|
||||
if (n.shadowRoot) stack.push(n.shadowRoot);
|
||||
if (n.children) {
|
||||
for (let i = n.children.length - 1; i >= 0; i--) stack.push(n.children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
function labelOf(el) {
|
||||
return String(
|
||||
el.getAttribute?.('aria-label') || el.innerText || el.textContent || el.value || ''
|
||||
).replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
function fireClick(el) {
|
||||
try { el.focus?.(); } catch (_) {}
|
||||
try {
|
||||
el.dispatchEvent(new MouseEvent('pointerdown', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('mousedown', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('pointerup', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('mouseup', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('click', {bubbles:true,cancelable:true,view:window}));
|
||||
} catch (_) {}
|
||||
try { el.click(); } catch (_) {}
|
||||
}
|
||||
for (const el of deepNodes(document)) {
|
||||
if (!el || !el.tagName) continue;
|
||||
const tag = String(el.tagName || '').toLowerCase();
|
||||
const role = String(el.getAttribute?.('role') || '').toLowerCase();
|
||||
const ok =
|
||||
tag === 'button' || tag === 'ytcp-button' || tag === 'tp-yt-paper-button' ||
|
||||
tag === 'yt-button-shape' || tag === 'yt-spec-button-shape-next' || role === 'button';
|
||||
if (!ok || !visible(el)) continue;
|
||||
const t = labelOf(el);
|
||||
if (!t || t.length > 48) continue;
|
||||
if (CANCEL_RE.test(t)) continue;
|
||||
if (!END_RE.test(t)) continue;
|
||||
fireClick(el);
|
||||
return {ok: true, text: t.slice(0, 40), needConfirm: true};
|
||||
}
|
||||
return {ok: false, error: 'not_found'};
|
||||
})()
|
||||
"""
|
||||
|
||||
CONFIRM_JS = r"""
|
||||
(() => {
|
||||
// Dialog only: [Not yet] [End] — NEVER match header "End Stream"
|
||||
const CONFIRM_EXACT = /^(end|结束)$/i;
|
||||
const CANCEL_RE = /not yet|not now|cancel|keep|go back|还没有|取消|继续|稍后再说|end stream|结束直播|stop streaming/i;
|
||||
|
||||
function visible(el) {
|
||||
if (!el || !el.getBoundingClientRect) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.width < 2 || r.height < 2) return false;
|
||||
const st = window.getComputedStyle ? getComputedStyle(el) : null;
|
||||
if (st && (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) === 0)) return false;
|
||||
return true;
|
||||
}
|
||||
function* deepNodes(root) {
|
||||
const stack = [root];
|
||||
while (stack.length) {
|
||||
const n = stack.pop();
|
||||
if (!n) continue;
|
||||
yield n;
|
||||
if (n.shadowRoot) stack.push(n.shadowRoot);
|
||||
if (n.children) {
|
||||
for (let i = n.children.length - 1; i >= 0; i--) stack.push(n.children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
function labelOf(el) {
|
||||
return String(
|
||||
el.getAttribute?.('aria-label') || el.innerText || el.textContent || ''
|
||||
).replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
function isClickable(el) {
|
||||
if (!el || !el.tagName) return false;
|
||||
const tag = String(el.tagName || '').toLowerCase();
|
||||
const role = String(el.getAttribute?.('role') || '').toLowerCase();
|
||||
return (
|
||||
tag === 'button' || tag === 'ytcp-button' || tag === 'tp-yt-paper-button' ||
|
||||
tag === 'yt-button-shape' || tag === 'yt-spec-button-shape-next' || role === 'button'
|
||||
);
|
||||
}
|
||||
function fireClick(el) {
|
||||
try { el.focus?.(); } catch (_) {}
|
||||
try {
|
||||
el.dispatchEvent(new MouseEvent('pointerdown', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('mousedown', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('pointerup', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('mouseup', {bubbles:true,cancelable:true,view:window}));
|
||||
el.dispatchEvent(new MouseEvent('click', {bubbles:true,cancelable:true,view:window}));
|
||||
} catch (_) {}
|
||||
try { el.click(); } catch (_) {}
|
||||
}
|
||||
|
||||
let roots = [document];
|
||||
for (const el of deepNodes(document)) {
|
||||
const role = String(el.getAttribute?.('role') || '').toLowerCase();
|
||||
const tag = String(el.tagName || '').toLowerCase();
|
||||
if (role === 'dialog' || tag.includes('dialog')) {
|
||||
roots.unshift(el);
|
||||
if (el.shadowRoot) roots.unshift(el.shadowRoot);
|
||||
}
|
||||
}
|
||||
|
||||
const exactHits = [];
|
||||
for (const root of roots) {
|
||||
for (const el of deepNodes(root)) {
|
||||
if (!isClickable(el) || !visible(el)) continue;
|
||||
const t = labelOf(el);
|
||||
if (!t || t.length > 64) continue;
|
||||
// Reject any control whose label contains End Stream / Not yet noise.
|
||||
if (/end stream|结束直播|stop streaming|not yet/i.test(t) && !CONFIRM_EXACT.test(t.trim())) continue;
|
||||
const compact = t.replace(/\s+/g, ' ').trim();
|
||||
if (CONFIRM_EXACT.test(compact)) exactHits.push([el, compact, 'label']);
|
||||
else {
|
||||
const leaf = String(el.innerText || '').replace(/\s+/g, ' ').trim();
|
||||
if (leaf && CONFIRM_EXACT.test(leaf) && leaf.length <= 8) exactHits.push([el, leaf, 'leaf']);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Prefer hits found under a dialog root.
|
||||
const pick = exactHits[0];
|
||||
if (!pick) return {ok: false, error: 'confirm_not_found', dialog_hint: roots.length > 1};
|
||||
fireClick(pick[0]);
|
||||
return {ok: true, text: pick[1].slice(0, 40), via: pick[2]};
|
||||
})()
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
tabs = json.loads(
|
||||
urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read().decode()
|
||||
)
|
||||
live = []
|
||||
for t in tabs:
|
||||
u = (t.get("url") or "").lower()
|
||||
if "studio.youtube.com" in u and "livestreaming" in u:
|
||||
live.append(t)
|
||||
if not live:
|
||||
print(json.dumps({"ok": False, "error": "no_live_tab"}))
|
||||
return
|
||||
tab = live[0]
|
||||
ws_url = tab.get("webSocketDebuggerUrl") or ""
|
||||
url = tab.get("url") or ""
|
||||
if not ws_url:
|
||||
print(json.dumps({"ok": False, "error": "no_ws", "url": url[:120]}))
|
||||
return
|
||||
|
||||
sock = ws_connect(ws_url)
|
||||
try:
|
||||
eval_js(sock, "true", req_id=1, timeout=3)
|
||||
|
||||
def _is_dialog_end(row: dict) -> bool:
|
||||
return bool(row.get("ok")) and str(row.get("text") or "").strip().lower() in {
|
||||
"end",
|
||||
"结束",
|
||||
}
|
||||
|
||||
# 1) Dialog already open → click exact "End" only (never header End Stream).
|
||||
pre = eval_js(sock, CONFIRM_JS, req_id=2, timeout=8) or {}
|
||||
if not isinstance(pre, dict):
|
||||
pre = {"ok": False, "error": "bad_pre_confirm"}
|
||||
first: dict = {"ok": False, "skipped": True}
|
||||
confirm: dict = {"ok": False, "skipped": True}
|
||||
if _is_dialog_end(pre):
|
||||
confirm = pre
|
||||
else:
|
||||
# 2) Click header End Stream, then dialog End (retries).
|
||||
first = eval_js(sock, CLICK_JS, req_id=3, timeout=8) or {}
|
||||
if not isinstance(first, dict):
|
||||
first = {"ok": False, "error": "bad_eval"}
|
||||
if first.get("ok"):
|
||||
confirm = {"ok": False, "error": "pending"}
|
||||
for attempt, req_id in enumerate((4, 5, 6, 7), start=1):
|
||||
time.sleep(1.6 if attempt == 1 else 1.0)
|
||||
confirm = eval_js(sock, CONFIRM_JS, req_id=req_id, timeout=8) or {}
|
||||
if not isinstance(confirm, dict):
|
||||
confirm = {"ok": False, "error": "bad_confirm_eval"}
|
||||
confirm["attempt"] = attempt
|
||||
if _is_dialog_end(confirm):
|
||||
break
|
||||
confirm["ok"] = False
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"ok": bool((first.get("ok") or _is_dialog_end(pre)) and _is_dialog_end(confirm)),
|
||||
"url": url[:200],
|
||||
"pre_confirm": pre,
|
||||
"end_click": first,
|
||||
"confirm_click": confirm,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -164,6 +164,12 @@ def main() -> None:
|
||||
nodata = bool(
|
||||
re.search(r"(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据", lower)
|
||||
)
|
||||
preparing = bool(
|
||||
re.search(
|
||||
r"preparing\s+stream|preparing\s+your\s+stream|准备(?:直播)?流|正在准备(?:直播|流)",
|
||||
lower,
|
||||
)
|
||||
)
|
||||
session_live = bool(
|
||||
re.search(r"\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?", lower)
|
||||
or re.search(r"(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}", text)
|
||||
@ -178,9 +184,20 @@ def main() -> None:
|
||||
lower,
|
||||
)
|
||||
)
|
||||
# Control-room chrome loaded (not blank SPA shell).
|
||||
control_ready = bool(
|
||||
re.search(
|
||||
r"end stream|stop streaming|结束直播|connect your encoder|stream health|stream settings|"
|
||||
r"stream key|streamkey|待开播|等待你开始|直播设置|推流码",
|
||||
lower,
|
||||
)
|
||||
)
|
||||
|
||||
status = ""
|
||||
if re.search(r"stream ended|直播已结束", lower) and not session_live:
|
||||
if preparing:
|
||||
# Preview spinner — NEVER treat as ready/on-air even if Excellent already shows.
|
||||
status = "preparing"
|
||||
elif re.search(r"stream ended|直播已结束", lower) and not session_live:
|
||||
status = "ended"
|
||||
elif session_live and (nodata or encoder_lost_hint):
|
||||
# 断播: LIVE session still open, encoder dropped — NOT 待开播
|
||||
@ -261,16 +278,19 @@ def main() -> None:
|
||||
|
||||
if live_duration and not session_live:
|
||||
session_live = True
|
||||
if status in {"", "waiting"} and (nodata or encoder_lost_hint):
|
||||
if preparing:
|
||||
status = "preparing"
|
||||
elif status in {"", "waiting"} and (nodata or encoder_lost_hint):
|
||||
status = "encoder_lost"
|
||||
elif status in {"", "waiting"}:
|
||||
status = "live"
|
||||
|
||||
# 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播.
|
||||
on_air = bool(status == "live" and not nodata and not encoder_lost_hint)
|
||||
# 开播 = session live + encoder has data. 断播 ≠ 开播 ≠ 待开播. Preparing ≠ 开播.
|
||||
on_air = bool(status == "live" and not nodata and not encoder_lost_hint and not preparing)
|
||||
encoder_lost = status == "encoder_lost" or (session_live and nodata)
|
||||
encoder_receiving = bool(
|
||||
not nodata
|
||||
not preparing
|
||||
and not nodata
|
||||
and not encoder_lost
|
||||
and (
|
||||
status == "live"
|
||||
@ -291,6 +311,8 @@ def main() -> None:
|
||||
"live_duration_sec": live_duration_sec,
|
||||
"on_air": on_air,
|
||||
"nodata": nodata,
|
||||
"preparing_stream": preparing,
|
||||
"control_ready": control_ready,
|
||||
"encoder_receiving": encoder_receiving,
|
||||
"encoder_lost": encoder_lost,
|
||||
"session_live": bool(session_live or status in {"live", "encoder_lost"}),
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
const LIVE_HUB_MIN_INTERVAL_MS = 1800;
|
||||
const LIVE_HUB_MIN_INTERVAL_MS = 4000;
|
||||
let lastSentAt = 0;
|
||||
let lastSignature = "";
|
||||
let observerQueued = false;
|
||||
|
||||
function cleanText(value, max = 260) {
|
||||
return String(value || "")
|
||||
@ -9,6 +10,43 @@ function cleanText(value, max = 260) {
|
||||
.slice(0, max);
|
||||
}
|
||||
|
||||
/** Pause Studio preview videos / mute — biggest RAM leak on livestreaming page. */
|
||||
function tameMedia() {
|
||||
try {
|
||||
document.querySelectorAll("video, audio").forEach((el) => {
|
||||
try {
|
||||
el.muted = true;
|
||||
el.pause();
|
||||
// Keep element for UI, but stop decoding frames.
|
||||
if (typeof el.disablePictureInPicture === "boolean") el.disablePictureInPicture = true;
|
||||
} catch (_) {}
|
||||
});
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
function injectMemCss() {
|
||||
if (document.getElementById("livehub-mem-css")) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = "livehub-mem-css";
|
||||
style.textContent = `
|
||||
/* Shrink heavy Live Control Room surfaces on low-RAM Neko hosts */
|
||||
ytls-live-dashboard-section-renderer video,
|
||||
ytls-stream-preview-section-renderer video,
|
||||
#preview-player video,
|
||||
.html5-video-player video {
|
||||
max-height: 180px !important;
|
||||
object-fit: contain !important;
|
||||
}
|
||||
ytls-live-dashboard-chart,
|
||||
ytcp-ve[class*="chart"],
|
||||
[class*="analytics-chart"] {
|
||||
max-height: 120px !important;
|
||||
overflow: hidden !important;
|
||||
}
|
||||
`;
|
||||
(document.head || document.documentElement).appendChild(style);
|
||||
}
|
||||
|
||||
function pageText() {
|
||||
return cleanText(document.body?.innerText || "", 6000);
|
||||
}
|
||||
@ -278,9 +316,23 @@ function sendTelemetry(force = false) {
|
||||
});
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(() => sendTelemetry(false));
|
||||
observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
|
||||
const observer = new MutationObserver(() => {
|
||||
if (observerQueued) return;
|
||||
observerQueued = true;
|
||||
setTimeout(() => {
|
||||
observerQueued = false;
|
||||
sendTelemetry(false);
|
||||
}, 2500);
|
||||
});
|
||||
// characterData on Studio Live fires constantly (viewer ticks) and burns RAM/CPU.
|
||||
observer.observe(document.documentElement, { subtree: true, childList: true });
|
||||
window.addEventListener("focus", () => sendTelemetry(true));
|
||||
document.addEventListener("visibilitychange", () => sendTelemetry(true));
|
||||
setInterval(() => sendTelemetry(false), 3000);
|
||||
injectMemCss();
|
||||
tameMedia();
|
||||
setInterval(() => {
|
||||
injectMemCss();
|
||||
tameMedia();
|
||||
sendTelemetry(false);
|
||||
}, 8000);
|
||||
sendTelemetry(true);
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Live Hub YouTube Studio Telemetry",
|
||||
"version": "1.3.0",
|
||||
"description": "Captures YouTube Studio live status, viewer signals, stream health, and popups for the LAN Live Hub.",
|
||||
"version": "1.4.0",
|
||||
"description": "Captures YouTube Studio live telemetry; pauses preview media to limit Neko Chrome RAM.",
|
||||
"permissions": ["storage", "tabs"],
|
||||
"host_permissions": [
|
||||
"https://studio.youtube.com/*",
|
||||
|
||||
@ -29,7 +29,9 @@
|
||||
},
|
||||
"default_locale": "en",
|
||||
"description": "__MSG_extDescription__",
|
||||
"host_permissions": [ "\u003Call_urls>" ],
|
||||
"host_permissions": [
|
||||
"<all_urls>"
|
||||
],
|
||||
"icons": {
|
||||
"128": "images/icon128.png",
|
||||
"32": "images/icon.png",
|
||||
@ -41,17 +43,36 @@
|
||||
"minimum_chrome_version": "120",
|
||||
"name": "__MSG_extName__",
|
||||
"offline_enabled": true,
|
||||
"optional_permissions": [ "downloads" ],
|
||||
"optional_permissions": [
|
||||
"downloads"
|
||||
],
|
||||
"options_page": "options.html",
|
||||
"options_ui": {
|
||||
"open_in_tab": true,
|
||||
"page": "options.html"
|
||||
},
|
||||
"permissions": [ "notifications", "unlimitedStorage", "tabs", "idle", "webNavigation", "webRequest", "webRequestBlocking", "storage", "contextMenus", "chrome://favicon/", "clipboardWrite", "cookies", "alarms", "declarativeNetRequestWithHostAccess", "scripting", "userScripts", "offscreen" ],
|
||||
"permissions": [
|
||||
"notifications",
|
||||
"unlimitedStorage",
|
||||
"tabs",
|
||||
"idle",
|
||||
"webNavigation",
|
||||
"webRequest",
|
||||
"webRequestBlocking",
|
||||
"storage",
|
||||
"contextMenus",
|
||||
"chrome://favicon/",
|
||||
"clipboardWrite",
|
||||
"cookies",
|
||||
"alarms",
|
||||
"declarativeNetRequestWithHostAccess",
|
||||
"scripting",
|
||||
"userScripts",
|
||||
"offscreen"
|
||||
],
|
||||
"short_name": "__MSG_extShortName__",
|
||||
"storage": {
|
||||
"managed_schema": "schema.json"
|
||||
},
|
||||
"update_url": "https://clients2.google.com/service/update2/crx",
|
||||
"version": "5.5.0"
|
||||
}
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
2026/05/19-04:29:50.026 4f Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001
|
||||
2026/05/19-04:29:50.026 4f Recovering log #3
|
||||
2026/05/19-04:29:50.027 4f Reusing old log /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log
|
||||
2026/09/11-10:09:37.478 96 Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001
|
||||
2026/09/11-10:09:37.479 96 Recovering log #3
|
||||
2026/09/11-10:09:37.479 96 Reusing old log /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log
|
||||
|
||||
@ -1,3 +1,2 @@
|
||||
2026/05/19-04:24:19.314 57 Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001
|
||||
2026/05/19-04:24:19.315 57 Recovering log #3
|
||||
2026/05/19-04:24:19.315 57 Reusing old log /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/000003.log
|
||||
2026/09/04-23:20:49.903 145 Creating DB /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo since it was missing.
|
||||
2026/09/04-23:20:49.934 145 Reusing MANIFEST /home/neko/.config/google-chrome/Default/Local Extension Settings/dhdgffkkebhmkfjojejmpbldmpobfkfo/MANIFEST-000001
|
||||
|
||||
@ -1 +1 @@
|
||||
{"extensions":{"settings":{"dhdgffkkebhmkfjojejmpbldmpobfkfo":{"account_extension_type":0,"ack_external":true,"active_permissions":{"api":["alarms","clipboardWrite","contextMenus","cookies","idle","notifications","storage","tabs","unlimitedStorage","webNavigation","webRequest","webRequestBlocking","scripting","declarativeNetRequestWithHostAccess","offscreen","userScripts"],"explicit_host":["<all_urls>"],"manifest_permissions":[],"scriptable_host":[]},"commands":{"open-dashboard":{"suggested_key":""},"open-dashboard-with-running-scripts":{"suggested_key":""},"open-new-script":{"suggested_key":""},"toggle-enable":{"suggested_key":""}},"content_settings":[],"creation_flags":9,"filtered_service_worker_events":{"webNavigation.onBeforeNavigate":[{"url":[{"schemes":["http","https"]}]}],"webNavigation.onCommitted":[{}]},"first_install_time":"13423454050276444","from_webstore":true,"incognito_content_settings":[],"incognito_preferences":{},"last_update_time":"13423454050276444","lastpingday":"13423388400889902","location":7,"manifest":{"action":{"default_icon":{"16":"images/icon_grey16.png","19":"images/icon_grey19.png","24":"images/icon_grey24.png","32":"images/icon_grey32.png","38":"images/icon_grey38.png"},"default_popup":"action.html","default_title":"Tampermonkey"},"background":{"service_worker":"background.js"},"commands":{"open-dashboard":{"description":"Open dashboard"},"open-dashboard-with-running-scripts":{"description":"Open dashboard with the current tab's URL used as filter"},"open-new-script":{"description":"Open new script tab"},"toggle-enable":{"description":"Toggle enable state"}},"current_locale":"en_US","default_locale":"en","description":"Change the web at will with userscripts","host_permissions":["<all_urls>"],"icons":{"128":"images/icon128.png","32":"images/icon.png","48":"images/icon48.png"},"incognito":"split","key":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjiyuc6OWY8gaVTe+b16fH2BBe0PQLMeUpEXSQvyv5a/6OiQ1D8bBLTfLvApD3zT2MZoXWu2KUILdkyg5OC/Tru8m+Js6e3RjHY9Rqbvnh8CJQgTJ+63L5w9aLsTvA2fqdDfhw8Mnl1GMcJd/RI/ZiBEm0stog0ZfyQjD1jpSEXQIDAQAB","manifest_version":3,"minimum_chrome_version":"120","name":"Tampermonkey","offline_enabled":true,"optional_permissions":["downloads"],"options_page":"options.html","options_ui":{"open_in_tab":true,"page":"options.html"},"permissions":["notifications","unlimitedStorage","tabs","idle","webNavigation","webRequest","webRequestBlocking","storage","contextMenus","chrome://favicon/","clipboardWrite","cookies","alarms","declarativeNetRequestWithHostAccess","scripting","userScripts","offscreen"],"short_name":"Tampermonkey","storage":{"managed_schema":"schema.json"},"update_url":"https://clients2.google.com/service/update2/crx","version":"5.5.0"},"path":"dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0","persistent_script_url_patterns":["<all_urls>"],"preferences":{},"regular_only_preferences":{},"service_worker_registration_info":{"version":"5.5.0"},"serviceworkerevents":["alarms.onAlarm","commands.onCommand","contextMenus.onClicked","notifications.onClicked","notifications.onClosed","notifications.onPermissionLevelChanged","permissions.onAdded","permissions.onRemoved","runtime.onConnectExternal","runtime.onInstalled","runtime.onUpdateAvailable","storage.onChanged","tabs.onActivated","tabs.onRemoved","tabs.onReplaced","tabs.onUpdated","webRequest.onBeforeRequest/s1","webRequest.onErrorOccurred/s4","webRequest.onHeadersReceived/s2","webRequest.onResponseStarted/s3"],"state":1,"uninstall_url":"https://www.tampermonkey.net/uninstall.php?ext=dhdg","user_scripts_worlds":{"configuration":{"_default":{"csp":"script-src 'self' 'unsafe-inline' *","messaging":true}}},"was_installed_by_default":false,"was_installed_by_oem":false}}}}
|
||||
{"extensions":{"settings":{"dhdgffkkebhmkfjojejmpbldmpobfkfo":{"account_extension_type":0,"active_permissions":{"api":["alarms","clipboardWrite","contextMenus","cookies","idle","notifications","storage","tabs","unlimitedStorage","webNavigation","webRequest","webRequestBlocking","scripting","declarativeNetRequestWithHostAccess","offscreen","userScripts"],"explicit_host":["<all_urls>"],"manifest_permissions":[],"scriptable_host":[]},"commands":{"open-dashboard":{"suggested_key":""},"open-dashboard-with-running-scripts":{"suggested_key":""},"open-new-script":{"suggested_key":""},"toggle-enable":{"suggested_key":""}},"content_settings":[],"creation_flags":9,"filtered_service_worker_events":{"webNavigation.onBeforeNavigate":[{"url":[{"schemes":["http","https"]}]}],"webNavigation.onCommitted":[{}]},"first_install_time":"13423454050276444","from_webstore":false,"incognito_content_settings":[],"incognito_preferences":{},"last_update_time":"13423454050276444","lastpingday":"13423388400889902","location":4,"manifest":{"action":{"default_icon":{"16":"images/icon_grey16.png","19":"images/icon_grey19.png","24":"images/icon_grey24.png","32":"images/icon_grey32.png","38":"images/icon_grey38.png"},"default_popup":"action.html","default_title":"Tampermonkey"},"background":{"service_worker":"background.js"},"commands":{"open-dashboard":{"description":"Open dashboard"},"open-dashboard-with-running-scripts":{"description":"Open dashboard with the current tab's URL used as filter"},"open-new-script":{"description":"Open new script tab"},"toggle-enable":{"description":"Toggle enable state"}},"current_locale":"en_US","default_locale":"en","description":"Change the web at will with userscripts","host_permissions":["<all_urls>"],"icons":{"128":"images/icon128.png","32":"images/icon.png","48":"images/icon48.png"},"incognito":"split","key":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjiyuc6OWY8gaVTe+b16fH2BBe0PQLMeUpEXSQvyv5a/6OiQ1D8bBLTfLvApD3zT2MZoXWu2KUILdkyg5OC/Tru8m+Js6e3RjHY9Rqbvnh8CJQgTJ+63L5w9aLsTvA2fqdDfhw8Mnl1GMcJd/RI/ZiBEm0stog0ZfyQjD1jpSEXQIDAQAB","manifest_version":3,"minimum_chrome_version":"120","name":"Tampermonkey","offline_enabled":true,"optional_permissions":["downloads"],"options_page":"options.html","options_ui":{"open_in_tab":true,"page":"options.html"},"permissions":["notifications","unlimitedStorage","tabs","idle","webNavigation","webRequest","webRequestBlocking","storage","contextMenus","chrome://favicon/","clipboardWrite","cookies","alarms","declarativeNetRequestWithHostAccess","scripting","userScripts","offscreen"],"short_name":"Tampermonkey","storage":{"managed_schema":"schema.json"},"version":"5.5.0"},"path":"dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0","persistent_script_url_patterns":["<all_urls>"],"preferences":{},"regular_only_preferences":{},"service_worker_registration_info":{"version":"5.5.0"},"serviceworkerevents":["alarms.onAlarm","commands.onCommand","contextMenus.onClicked","notifications.onClicked","notifications.onClosed","notifications.onPermissionLevelChanged","permissions.onAdded","permissions.onRemoved","runtime.onConnectExternal","runtime.onInstalled","runtime.onUpdateAvailable","storage.onChanged","tabs.onActivated","tabs.onRemoved","tabs.onReplaced","tabs.onUpdated","webRequest.onBeforeRequest/s1","webRequest.onErrorOccurred/s4","webRequest.onHeadersReceived/s2","webRequest.onResponseStarted/s3"],"state":1,"uninstall_url":"https://www.tampermonkey.net/uninstall.php?ext=dhdg","user_scripts_worlds":{"configuration":{"_default":{"csp":"script-src 'self' 'unsafe-inline' *","messaging":true}}},"was_installed_by_default":false,"was_installed_by_oem":false}}}}
|
||||
@ -1,5 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from app.yt_assign_db import group_is_time_slot, normalize_assign_category
|
||||
from app.yt_assign_db import (
|
||||
group_eligible_for_time_slot,
|
||||
group_is_time_slot,
|
||||
group_time_slot_armed,
|
||||
normalize_assign_category,
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_assign_category():
|
||||
@ -19,3 +24,25 @@ def test_group_is_time_slot():
|
||||
assert group_is_time_slot({"category": "普通"}) is False
|
||||
assert group_is_time_slot({}) is False
|
||||
assert group_is_time_slot(None) is False
|
||||
|
||||
|
||||
def test_group_time_slot_armed_default_true():
|
||||
assert group_time_slot_armed({}) is True
|
||||
assert group_time_slot_armed({"time_slot_armed": 1}) is True
|
||||
assert group_time_slot_armed({"time_slot_armed": 0}) is False
|
||||
assert group_time_slot_armed({"time_slot_armed": False}) is False
|
||||
assert group_time_slot_armed({"time_slot_armed": "false"}) is False
|
||||
|
||||
|
||||
def test_group_eligible_for_time_slot():
|
||||
base = {
|
||||
"enabled": True,
|
||||
"category": "time_slot",
|
||||
"has_stream_key": True,
|
||||
"time_slot_armed": True,
|
||||
}
|
||||
assert group_eligible_for_time_slot(base) is True
|
||||
assert group_eligible_for_time_slot({**base, "time_slot_armed": False}) is False
|
||||
assert group_eligible_for_time_slot({**base, "has_stream_key": False}) is False
|
||||
assert group_eligible_for_time_slot({**base, "category": "normal"}) is False
|
||||
assert group_eligible_for_time_slot({**base, "enabled": False}) is False
|
||||
|
||||
24
backend/tests/test_cdp_poll_running_disabled.py
Normal file
24
backend/tests/test_cdp_poll_running_disabled.py
Normal file
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit: CDP poll includes running-but-disabled Nekos."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app import youtube_neko as yn
|
||||
from app import yt_assign_db
|
||||
|
||||
|
||||
def test_cdp_poll_ids_include_running_disabled(monkeypatch):
|
||||
groups = [
|
||||
{"neko_enabled": True, "neko_instance_id": 1},
|
||||
{"neko_enabled": False, "neko_instance_id": 6},
|
||||
{"neko_enabled": False, "neko_instance_id": 9},
|
||||
]
|
||||
|
||||
def fake_state(nid, check_http=False):
|
||||
return {"running": nid == 6}
|
||||
|
||||
monkeypatch.setattr(yt_assign_db, "list_groups", lambda include_urls=False: groups)
|
||||
monkeypatch.setattr(yn, "_container_state", fake_state)
|
||||
ids = yn._neko_ids_for_cdp_poll()
|
||||
assert 1 in ids
|
||||
assert 6 in ids
|
||||
assert 9 not in ids
|
||||
42
backend/tests/test_complete_live_broadcast.py
Normal file
42
backend/tests/test_complete_live_broadcast.py
Normal file
@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Unit: complete_active_live_broadcast filters lifeCycleStatus."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from app import youtube_manage
|
||||
|
||||
|
||||
def test_complete_active_live_broadcast_completes_live(monkeypatch):
|
||||
async def fake_access(pk: str):
|
||||
return "tok", {"id": pk}
|
||||
|
||||
calls: list[dict[str, Any]] = []
|
||||
|
||||
async def fake_get(path: str, *, token: str, params: dict[str, Any]):
|
||||
assert path == "liveBroadcasts"
|
||||
return {
|
||||
"items": [
|
||||
{"id": "vid_live", "status": {"lifeCycleStatus": "live"}},
|
||||
{"id": "vid_complete", "status": {"lifeCycleStatus": "complete"}},
|
||||
{"id": "vid_ready", "status": {"lifeCycleStatus": "ready"}},
|
||||
]
|
||||
}
|
||||
|
||||
async def fake_post(path: str, *, token: str, params: dict[str, Any], json_body: dict[str, Any]):
|
||||
calls.append({"path": path, "params": params})
|
||||
return {"id": params.get("id"), "status": {"lifeCycleStatus": "complete"}}
|
||||
|
||||
monkeypatch.setattr(youtube_manage, "_access_for_channel", fake_access)
|
||||
monkeypatch.setattr(youtube_manage, "_get", fake_get)
|
||||
monkeypatch.setattr(youtube_manage, "_post", fake_post)
|
||||
|
||||
out = asyncio.run(youtube_manage.complete_active_live_broadcast("ch1"))
|
||||
assert out["completed"] == ["vid_live"]
|
||||
assert calls and calls[0]["params"]["broadcastStatus"] == "complete"
|
||||
|
||||
|
||||
def test_complete_empty_pk():
|
||||
out = asyncio.run(youtube_manage.complete_active_live_broadcast(""))
|
||||
assert out["ok"] is False
|
||||
46
backend/tests/test_prefer_non_uhd_stream.py
Normal file
46
backend/tests/test_prefer_non_uhd_stream.py
Normal file
@ -0,0 +1,46 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from app.douyin import pick_stream_candidates, _is_uhd_stream_url
|
||||
|
||||
|
||||
def test_prefer_non_uhd_over_origin():
|
||||
room = {
|
||||
"stream_url": {
|
||||
"flv_pull_url": {
|
||||
"ORIGIN": "http://cdn.example/stream_uhd.flv?unique_id=x_flv_uhd",
|
||||
"FULL_HD1": "http://cdn.example/stream_full.flv?unique_id=x_flv",
|
||||
"HD1": "http://cdn.example/stream_hd.flv?unique_id=x_hd_flv",
|
||||
"SD1": "http://cdn.example/stream_sd.flv",
|
||||
}
|
||||
}
|
||||
}
|
||||
cands = pick_stream_candidates(room)
|
||||
assert cands[0] == "http://cdn.example/stream_hd.flv?unique_id=x_hd_flv"
|
||||
assert cands[1] == "http://cdn.example/stream_full.flv?unique_id=x_flv"
|
||||
assert cands[-1].endswith("_uhd") or "_uhd" in cands[-1]
|
||||
|
||||
|
||||
def test_demote_uhd_even_if_only_labeled_hd():
|
||||
room = {
|
||||
"stream_url": {
|
||||
"flv_pull_url": {
|
||||
"HD1": "http://cdn.example/foo_uhd.flv",
|
||||
"SD1": "http://cdn.example/foo_sd.flv",
|
||||
}
|
||||
}
|
||||
}
|
||||
cands = pick_stream_candidates(room)
|
||||
assert cands[0] == "http://cdn.example/foo_sd.flv"
|
||||
assert _is_uhd_stream_url(cands[-1])
|
||||
|
||||
|
||||
def test_uhd_only_still_usable():
|
||||
room = {
|
||||
"stream_url": {
|
||||
"flv_pull_url": {
|
||||
"ORIGIN": "http://cdn.example/only_uhd.flv",
|
||||
}
|
||||
}
|
||||
}
|
||||
cands = pick_stream_candidates(room)
|
||||
assert len(cands) == 1
|
||||
assert "uhd" in cands[0]
|
||||
42
backend/tests/test_preparing_stream_gate.py
Normal file
42
backend/tests/test_preparing_stream_gate.py
Normal file
@ -0,0 +1,42 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Preparing stream must never count as on-air / ready for FFmpeg."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app import youtube_neko as yn
|
||||
|
||||
|
||||
def test_payload_stream_confirmed_rejects_preparing():
|
||||
assert not yn._payload_stream_confirmed(
|
||||
{
|
||||
"live_status": "preparing",
|
||||
"health": "excellent",
|
||||
"text": "Preparing stream Excellent connection",
|
||||
"signals": {"preparing_stream": True},
|
||||
}
|
||||
)
|
||||
assert not yn._payload_stream_confirmed(
|
||||
{
|
||||
"live_status": "live",
|
||||
"health": "excellent",
|
||||
"text": "Preparing stream Excellent connection Stream is healthy",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_payload_nodata_or_pending_includes_preparing():
|
||||
assert yn._payload_nodata_or_pending(
|
||||
{
|
||||
"live_status": "preparing",
|
||||
"text": "Preparing stream",
|
||||
"signals": {"preparing_stream": True},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_ffmpeg_pid_alive_helper():
|
||||
from app.youtube_relay_pipeline import _ffmpeg_pid_alive
|
||||
import os
|
||||
|
||||
assert _ffmpeg_pid_alive(0) is False
|
||||
assert _ffmpeg_pid_alive(-1) is False
|
||||
assert _ffmpeg_pid_alive(os.getpid()) is True
|
||||
78
backend/tests/test_relay_normal_auto.py
Normal file
78
backend/tests/test_relay_normal_auto.py
Normal file
@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests: normal auto candidates + first-live exclusive claim."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.youtube_relay_pipeline import (
|
||||
_claim_first_live_normal,
|
||||
_normal_auto_candidates,
|
||||
pick_source_for_group,
|
||||
)
|
||||
|
||||
|
||||
def test_normal_auto_candidates_skips_timeslot(monkeypatch):
|
||||
groups = [
|
||||
{"id": "n1", "enabled": 1, "category": "normal", "stream_key": "aaaa-bbbb-cccc-dddd-eeee"},
|
||||
{"id": "t1", "enabled": 1, "category": "time_slot", "stream_key": "aaaa-bbbb-cccc-dddd-eeee"},
|
||||
{"id": "n2", "enabled": 0, "category": "normal", "stream_key": "aaaa-bbbb-cccc-dddd-eeee"},
|
||||
{"id": "n3", "enabled": 1, "category": "normal", "stream_key": ""},
|
||||
]
|
||||
out = _normal_auto_candidates(groups)
|
||||
assert [g["id"] for g in out] == ["n1"]
|
||||
|
||||
|
||||
def test_claim_first_live_normal_by_sort_order(monkeypatch):
|
||||
live = {"r1", "r2"}
|
||||
|
||||
def _live_ids():
|
||||
return set(live)
|
||||
|
||||
monkeypatch.setattr("app.youtube_relay_pipeline._live_room_ids", _live_ids)
|
||||
|
||||
groups: list[dict[str, Any]] = [
|
||||
{
|
||||
"id": "b",
|
||||
"enabled": 1,
|
||||
"category": "normal",
|
||||
"sort_order": 20,
|
||||
"stream_key": "k",
|
||||
"featured": [{"url": "https://live.douyin.com/2", "room_id": "r2", "title": "B"}],
|
||||
},
|
||||
{
|
||||
"id": "a",
|
||||
"enabled": 1,
|
||||
"category": "normal",
|
||||
"sort_order": 10,
|
||||
"stream_key": "k",
|
||||
"featured": [{"url": "https://live.douyin.com/1", "room_id": "r1", "title": "A"}],
|
||||
},
|
||||
{
|
||||
"id": "c",
|
||||
"enabled": 1,
|
||||
"category": "normal",
|
||||
"sort_order": 5,
|
||||
"stream_key": "k",
|
||||
"featured": [{"url": "https://live.douyin.com/9", "room_id": "offline", "title": "C"}],
|
||||
},
|
||||
]
|
||||
claimed = _claim_first_live_normal(groups)
|
||||
assert claimed is not None
|
||||
gid, g, src = claimed
|
||||
assert gid == "a"
|
||||
assert src["room_id"] == "r1"
|
||||
|
||||
|
||||
def test_pick_source_normal_featured_prefer_live(monkeypatch):
|
||||
monkeypatch.setattr("app.youtube_relay_pipeline._live_room_ids", lambda: {"live1"})
|
||||
g = {
|
||||
"id": "g1",
|
||||
"enabled": 1,
|
||||
"category": "normal",
|
||||
"featured": [
|
||||
{"url": "https://live.douyin.com/off", "room_id": "off", "title": "off"},
|
||||
{"url": "https://live.douyin.com/live1", "room_id": "live1", "title": "on"},
|
||||
],
|
||||
}
|
||||
src = pick_source_for_group(g, respect_schedule=False)
|
||||
assert src and src["room_id"] == "live1"
|
||||
53
backend/tests/test_relay_paused_status.py
Normal file
53
backend/tests/test_relay_paused_status.py
Normal file
@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression: paused_* status must not show as「监听中」."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.youtube_relay_status import summarize_relay_group
|
||||
|
||||
|
||||
def test_summarize_paused_exclusive_not_monitoring():
|
||||
row = summarize_relay_group(
|
||||
group={
|
||||
"id": "g1",
|
||||
"enabled": True,
|
||||
"has_stream_key": True,
|
||||
"stream_key": "aaaa-bbbb-cccc-dddd-eeee",
|
||||
"category": "normal",
|
||||
"featured": [{"url": "https://live.douyin.com/1"}],
|
||||
},
|
||||
st={
|
||||
"status": "paused_exclusive",
|
||||
"error": "单路独占:当前仅允许 X 推流",
|
||||
"recent_log": [],
|
||||
},
|
||||
session_running=False,
|
||||
pipeline_enabled=True,
|
||||
time_slot_mode=False,
|
||||
lane_armed=True,
|
||||
)
|
||||
assert row["business_status"] == "paused_exclusive"
|
||||
assert "独占" in (row.get("business_note") or "")
|
||||
|
||||
|
||||
def test_summarize_paused_studio_not_monitoring():
|
||||
row = summarize_relay_group(
|
||||
group={
|
||||
"id": "g1",
|
||||
"enabled": True,
|
||||
"has_stream_key": True,
|
||||
"stream_key": "aaaa-bbbb-cccc-dddd-eeee",
|
||||
"category": "normal",
|
||||
"featured": [{"url": "https://live.douyin.com/1"}],
|
||||
},
|
||||
st={
|
||||
"status": "paused_studio",
|
||||
"error": "Studio 未 on_air 熔断中(约剩 5 分)",
|
||||
"recent_log": [],
|
||||
},
|
||||
session_running=False,
|
||||
pipeline_enabled=True,
|
||||
time_slot_mode=False,
|
||||
lane_armed=True,
|
||||
)
|
||||
assert row["business_status"] == "paused_studio"
|
||||
assert "熔断" in (row.get("business_note") or "")
|
||||
110
backend/tests/test_shorts_gap_rules.py
Normal file
110
backend/tests/test_shorts_gap_rules.py
Normal file
@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Unit tests for Shorts front-load pace (90% by BJ 20:00) + gap floors."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from unittest import mock
|
||||
|
||||
from app.shorts_schedule import (
|
||||
CHANNEL_GAP_FLOOR_SEC,
|
||||
QUOTA_DEADLINE_HOUR,
|
||||
QUOTA_FRONTLOAD_RATIO,
|
||||
_deadline_ts,
|
||||
_quota_pressure,
|
||||
fleet_pace_plan,
|
||||
pick_upload_at,
|
||||
)
|
||||
from app.timeutil import beijing_day_bounds, push_date_from_ts
|
||||
|
||||
|
||||
def test_channel_gap_floor_constant():
|
||||
assert CHANNEL_GAP_FLOOR_SEC == 600.0
|
||||
assert QUOTA_DEADLINE_HOUR == 20
|
||||
assert QUOTA_FRONTLOAD_RATIO == 0.9
|
||||
|
||||
|
||||
def test_deadline_is_beijing_20():
|
||||
day = push_date_from_ts(time.time())
|
||||
day_start, day_end = beijing_day_bounds(day)
|
||||
d = _deadline_ts(day)
|
||||
assert day_start < d < day_end
|
||||
assert abs(d - (day_start + 20 * 3600)) < 60
|
||||
|
||||
|
||||
def test_pick_upload_at_respects_10min_floor(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="Gap", daily_min=9, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
noon = beijing_day_bounds(day)[0] + 12 * 3600
|
||||
# Seed enough uploads so we are NOT behind front-load (avoid emergency <10min).
|
||||
for i in range(8):
|
||||
j = temp_db.create_shorts_job(session_id="", room_id=f"gap{i}", channel_pk=ch["id"], push_date=day)
|
||||
temp_db.update_shorts_job(
|
||||
j["id"], status="done", finished_at=noon - 3600 + i * 700, upload_at=noon - 3600 + i * 700
|
||||
)
|
||||
j = temp_db.create_shorts_job(session_id="", room_id="gapx", channel_pk=ch["id"], push_date=day)
|
||||
temp_db.update_shorts_job(j["id"], status="done", finished_at=noon - 30, upload_at=noon - 30)
|
||||
|
||||
cfg = {
|
||||
"shorts_upload_spread": True,
|
||||
"shorts_upload_min_gap_sec": 600,
|
||||
"shorts_channel_min_gap_sec": 600,
|
||||
}
|
||||
with mock.patch("app.shorts_schedule.time.time", return_value=noon):
|
||||
at = pick_upload_at(channel_pk=ch["id"], push_date=day, cfg=cfg)
|
||||
assert at >= noon - 30 + CHANNEL_GAP_FLOOR_SEC
|
||||
|
||||
|
||||
def test_pick_upload_at_stays_before_deadline_when_behind(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="Early", daily_min=9, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
day_start, _ = beijing_day_bounds(day)
|
||||
now = day_start + 6 * 3600 # 06:00 BJ — far behind 90% by 20:00
|
||||
deadline = _deadline_ts(day)
|
||||
cfg = {
|
||||
"shorts_upload_spread": True,
|
||||
"shorts_upload_min_gap_sec": 600,
|
||||
"shorts_channel_min_gap_sec": 600,
|
||||
}
|
||||
with mock.patch("app.shorts_schedule.time.time", return_value=now):
|
||||
at = pick_upload_at(channel_pk=ch["id"], push_date=day, cfg=cfg)
|
||||
assert at <= deadline + 60
|
||||
assert at < day_start + 22 * 3600 # not dumped near midnight
|
||||
|
||||
|
||||
def test_end_of_day_compresses_below_10min(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="Rush", daily_min=9, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
_, day_end = beijing_day_bounds(day)
|
||||
now = day_end - 12 * 60
|
||||
j = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"], push_date=day)
|
||||
temp_db.update_shorts_job(j["id"], status="uploaded", finished_at=now - 20, upload_at=now - 20)
|
||||
cfg = {
|
||||
"shorts_upload_spread": True,
|
||||
"shorts_upload_min_gap_sec": 600,
|
||||
"shorts_channel_min_gap_sec": 600,
|
||||
}
|
||||
with mock.patch("app.shorts_schedule.time.time", return_value=now):
|
||||
at = pick_upload_at(channel_pk=ch["id"], push_date=day, cfg=cfg)
|
||||
assert at < now + CHANNEL_GAP_FLOOR_SEC
|
||||
assert at <= day_end
|
||||
|
||||
|
||||
def test_quota_pressure_uses_channel_daily_min(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="P", daily_min=9, daily_max=12, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
g, c, behind, urgent = _quota_pressure(channel_pk=ch["id"], push_date=day, now=time.time())
|
||||
assert behind is True or urgent is True or g < 1.0
|
||||
assert c <= 1.0
|
||||
|
||||
|
||||
def test_fleet_pace_plan_behind_in_morning(temp_db):
|
||||
for i in range(3):
|
||||
temp_db.create_shorts_channel(name=f"C{i}", daily_min=9, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
day_start, _ = beijing_day_bounds(day)
|
||||
now = day_start + 6 * 3600
|
||||
with mock.patch("app.shorts_schedule.time.time", return_value=now):
|
||||
plan = fleet_pace_plan(day, now=now)
|
||||
assert plan["front_target"] == 25 or plan["front_target"] >= 24 # ceil(0.9*27)=25
|
||||
assert plan["behind"] is True
|
||||
assert plan["recommended_global_gap_sec"] <= 600
|
||||
@ -23,6 +23,7 @@ def test_shorts_quota_counts_scheduled(temp_db):
|
||||
)
|
||||
temp_db.update_shorts_job(job["id"], status="scheduled", upload_at=time.time() + 3600)
|
||||
assert temp_db.shorts_channel_upload_count(ch["id"], day) == 2
|
||||
assert temp_db.shorts_channel_uploaded_count(ch["id"], day) == 0
|
||||
|
||||
|
||||
def test_pick_shorts_channel_prefers_under_min(temp_db):
|
||||
@ -30,7 +31,8 @@ def test_pick_shorts_channel_prefers_under_min(temp_db):
|
||||
ch2 = temp_db.create_shorts_channel(name="B", daily_min=5, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
for i in range(5):
|
||||
temp_db.create_shorts_job(session_id="", room_id=f"a{i}", channel_pk=ch1["id"], push_date=day)
|
||||
job = temp_db.create_shorts_job(session_id="", room_id=f"a{i}", channel_pk=ch1["id"], push_date=day)
|
||||
temp_db.update_shorts_job(job["id"], status="uploaded", finished_at=time.time())
|
||||
picked = temp_db.pick_shorts_channel(day)
|
||||
assert picked is not None
|
||||
assert picked["id"] == ch2["id"]
|
||||
@ -40,15 +42,34 @@ def test_quota_gap_and_summary(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="G", daily_min=5, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
for i in range(3):
|
||||
temp_db.create_shorts_job(session_id="", room_id=f"g{i}", channel_pk=ch["id"], push_date=day)
|
||||
job = temp_db.create_shorts_job(session_id="", room_id=f"g{i}", channel_pk=ch["id"], push_date=day)
|
||||
temp_db.update_shorts_job(job["id"], status="uploaded", finished_at=time.time())
|
||||
summary = temp_db.shorts_channels_quota_summary(day)
|
||||
assert len(summary) == 1
|
||||
assert summary[0]["used"] == 3
|
||||
assert summary[0]["uploaded"] == 3
|
||||
assert summary[0]["gap"] == 6
|
||||
assert summary[0]["min_met"] is False
|
||||
assert temp_db.shorts_total_quota_gap(day) == 6
|
||||
|
||||
|
||||
def test_quota_progress_ignores_pending(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="P", daily_min=9, daily_max=9, enabled=True)
|
||||
day = push_date_from_ts(time.time())
|
||||
for i in range(2):
|
||||
job = temp_db.create_shorts_job(session_id="", room_id=f"up{i}", channel_pk=ch["id"], push_date=day)
|
||||
temp_db.update_shorts_job(job["id"], status="uploaded", finished_at=time.time())
|
||||
for i in range(7):
|
||||
temp_db.create_shorts_job(session_id="", room_id=f"pe{i}", channel_pk=ch["id"], push_date=day)
|
||||
summary = temp_db.shorts_channels_quota_summary(day)[0]
|
||||
assert summary["uploaded"] == 2
|
||||
assert summary["used"] == 2
|
||||
assert summary["pipeline"] == 9
|
||||
assert summary["gap"] == 7
|
||||
assert summary["max_met"] is False
|
||||
assert summary["pipeline_full"] is True
|
||||
|
||||
|
||||
def test_beijing_day_bounds():
|
||||
day = push_date_from_ts(time.time())
|
||||
start, end = beijing_day_bounds(day)
|
||||
|
||||
81
backend/tests/test_shorts_room_offsets.py
Normal file
81
backend/tests/test_shorts_room_offsets.py
Normal file
@ -0,0 +1,81 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Test multi-channel same-room with distinct clip offsets."""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app.timeutil import push_date_from_ts
|
||||
|
||||
|
||||
def test_same_room_multi_channel_offsets(temp_db):
|
||||
day = push_date_from_ts(time.time())
|
||||
ch_a = temp_db.create_shorts_channel(name="A", daily_min=9, daily_max=9, enabled=True)
|
||||
ch_b = temp_db.create_shorts_channel(name="B", daily_min=9, daily_max=9, enabled=True)
|
||||
ch_c = temp_db.create_shorts_channel(name="C", daily_min=9, daily_max=9, enabled=True)
|
||||
|
||||
off0 = temp_db.next_shorts_room_clip_offset("roomX", day, clip_sec=15)
|
||||
assert off0 == 0
|
||||
j1 = temp_db.create_shorts_job(
|
||||
session_id="",
|
||||
room_id="roomX",
|
||||
channel_pk=ch_a["id"],
|
||||
push_date=day,
|
||||
clip_offset_sec=off0,
|
||||
)
|
||||
assert j1 is not None
|
||||
assert float(j1.get("clip_offset_sec") or 0) == 0
|
||||
|
||||
off1 = temp_db.next_shorts_room_clip_offset("roomX", day, clip_sec=15)
|
||||
assert off1 == 15
|
||||
j2 = temp_db.create_shorts_job(
|
||||
session_id="",
|
||||
room_id="roomX",
|
||||
channel_pk=ch_b["id"],
|
||||
push_date=day,
|
||||
clip_offset_sec=off1,
|
||||
)
|
||||
assert j2 is not None
|
||||
assert float(j2.get("clip_offset_sec") or 0) == 15
|
||||
|
||||
off2 = temp_db.next_shorts_room_clip_offset("roomX", day, clip_sec=15)
|
||||
assert off2 == 30
|
||||
j3 = temp_db.create_shorts_job(
|
||||
session_id="",
|
||||
room_id="roomX",
|
||||
channel_pk=ch_c["id"],
|
||||
push_date=day,
|
||||
clip_offset_sec=off2,
|
||||
)
|
||||
assert j3 is not None
|
||||
|
||||
# Same channel cannot reuse same room
|
||||
j_dup = temp_db.create_shorts_job(
|
||||
session_id="",
|
||||
room_id="roomX",
|
||||
channel_pk=ch_a["id"],
|
||||
push_date=day,
|
||||
clip_offset_sec=45,
|
||||
)
|
||||
assert j_dup is None
|
||||
|
||||
|
||||
def test_legacy_global_dedupe_still_works(temp_db):
|
||||
day = push_date_from_ts(time.time())
|
||||
ch_a = temp_db.create_shorts_channel(name="A2", daily_min=9, daily_max=9, enabled=True)
|
||||
ch_b = temp_db.create_shorts_channel(name="B2", daily_min=9, daily_max=9, enabled=True)
|
||||
j1 = temp_db.create_shorts_job(
|
||||
session_id="",
|
||||
room_id="roomY",
|
||||
channel_pk=ch_a["id"],
|
||||
push_date=day,
|
||||
dedupe_room_global=True,
|
||||
)
|
||||
assert j1 is not None
|
||||
j2 = temp_db.create_shorts_job(
|
||||
session_id="",
|
||||
room_id="roomY",
|
||||
channel_pk=ch_b["id"],
|
||||
push_date=day,
|
||||
dedupe_room_global=True,
|
||||
)
|
||||
assert j2 is None
|
||||
@ -8,6 +8,8 @@ from app.shorts_yt_quota import (
|
||||
YT_DAILY_UPLOAD_LIMIT_DEFAULT,
|
||||
blocked_profile_ids,
|
||||
clear_all_upload_self_blocks,
|
||||
defer_profile_shorts_uploads,
|
||||
mark_api_quota_cooldown,
|
||||
pause_uploads_until_reset,
|
||||
profile_upload_blocked,
|
||||
project_uploads_available,
|
||||
@ -34,8 +36,8 @@ def test_yt_upload_budget_and_reserve(temp_db):
|
||||
assert remaining2 == remaining - 1
|
||||
|
||||
|
||||
def test_never_self_blocks_uploads(temp_db):
|
||||
"""Local counter / pause helpers must not gate uploads."""
|
||||
def test_local_counter_does_not_block(temp_db):
|
||||
"""Burning the local display counter must not gate uploads by itself."""
|
||||
cfg = temp_db.get_settings_map()
|
||||
for _ in range(YT_DAILY_UPLOAD_LIMIT_DEFAULT + 5):
|
||||
assert reserve_yt_upload_slot(cfg) is True
|
||||
@ -44,20 +46,43 @@ def test_never_self_blocks_uploads(temp_db):
|
||||
assert profile_upload_blocked(cfg, profile_id="A") == (False, 0.0)
|
||||
assert blocked_profile_ids(cfg) == set()
|
||||
|
||||
ch = temp_db.create_shorts_channel(name="Y", enabled=True)
|
||||
|
||||
def test_api_cooldown_blocks_and_ntfy_once(temp_db):
|
||||
"""Real API cool-down blocks auto path; second mark in-window should not re-notify."""
|
||||
cfg = temp_db.get_settings_map()
|
||||
until1, notify1 = mark_api_quota_cooldown(cfg, profile_id="B", reason="429 test")
|
||||
assert notify1 is True
|
||||
assert until1 > time.time()
|
||||
cfg = temp_db.get_settings_map()
|
||||
blocked, until = profile_upload_blocked(cfg, profile_id="B")
|
||||
assert blocked is True
|
||||
assert until > time.time()
|
||||
assert "B" in blocked_profile_ids(cfg)
|
||||
assert project_uploads_available(cfg, profile_id="B") is False
|
||||
# Other clients stay open
|
||||
assert project_uploads_available(cfg, profile_id="A") is True
|
||||
|
||||
until2, notify2 = mark_api_quota_cooldown(cfg, profile_id="B", reason="429 again")
|
||||
assert notify2 is False
|
||||
assert until2 >= until1 - 1
|
||||
|
||||
|
||||
def test_api_cooldown_defers_due_jobs(temp_db):
|
||||
ch = temp_db.create_shorts_channel(name="YB", enabled=True, oauth_profile_id="B")
|
||||
job = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"])
|
||||
temp_db.update_shorts_job(job["id"], status="scheduled", clip_path="/tmp/x.mp4", upload_at=time.time())
|
||||
until = pause_uploads_until_reset(temp_db.get_settings_map(), reason="test pause")
|
||||
now = time.time()
|
||||
temp_db.update_shorts_job(
|
||||
job["id"], status="scheduled", clip_path="/tmp/x.mp4", upload_at=now - 10
|
||||
)
|
||||
until = pause_uploads_until_reset(temp_db.get_settings_map(), profile_id="B", reason="test")
|
||||
moved = defer_profile_shorts_uploads("B", until, reason="cool")
|
||||
assert moved >= 1
|
||||
refreshed = temp_db.get_shorts_job(job["id"])
|
||||
assert refreshed is not None
|
||||
assert refreshed["status"] == "scheduled"
|
||||
# Must NOT defer the job into the future as a self-pause
|
||||
assert float(refreshed["upload_at"]) <= time.time() + 5
|
||||
cfg = temp_db.get_settings_map()
|
||||
assert float(cfg.get("shorts_yt_upload_blocked_until") or 0) == 0
|
||||
assert until > time.time() # reset timestamp still returned for UI hint
|
||||
clear_all_upload_self_blocks(cfg)
|
||||
assert profile_upload_blocked(temp_db.get_settings_map(), profile_id="A") == (False, 0.0)
|
||||
assert float(refreshed["upload_at"]) >= until
|
||||
# clear_all only drops expired cool-downs
|
||||
clear_all_upload_self_blocks(temp_db.get_settings_map())
|
||||
assert profile_upload_blocked(temp_db.get_settings_map(), profile_id="B")[0] is True
|
||||
|
||||
|
||||
def test_pacific_day_from_ts():
|
||||
|
||||
77
backend/tests/test_studio_snap_evidence_first.py
Normal file
77
backend/tests/test_studio_snap_evidence_first.py
Normal file
@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""studio_snapshot_for_group: evidence-first when one side has Live UI."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app import youtube_neko as yn
|
||||
|
||||
|
||||
def test_prefers_remote_live_over_fresh_local_closed(monkeypatch):
|
||||
local = {
|
||||
"live_page_open": False,
|
||||
"on_air": False,
|
||||
"age_sec": 5.0,
|
||||
"received_at": 1.0,
|
||||
"ui_source": "local",
|
||||
"neko_kind": "local",
|
||||
"viewer_count": None,
|
||||
}
|
||||
remote = {
|
||||
"live_page_open": True,
|
||||
"on_air": True,
|
||||
"age_sec": 8.0,
|
||||
"received_at": 1.0,
|
||||
"ui_source": "remote",
|
||||
"neko_kind": "remote",
|
||||
"viewer_count": 3,
|
||||
"url": "https://studio.youtube.com/video/x/livestreaming",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
yn,
|
||||
"studio_snapshot_for_ref",
|
||||
lambda *a, **k: dict(remote),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
yn,
|
||||
"studio_snapshot_for_instance",
|
||||
lambda *a, **k: dict(local),
|
||||
)
|
||||
g = {
|
||||
"neko_open_prefer": "local",
|
||||
"ops_neko_open_url": "https://example/neko/19/",
|
||||
"ops_neko_slot": 19,
|
||||
"neko_instance_id": 3,
|
||||
}
|
||||
snap = yn.studio_snapshot_for_group(g, max_age_sec=120.0, include_minute_reports=False)
|
||||
assert snap.get("live_page_open") is True
|
||||
assert snap.get("viewer_count") == 3
|
||||
assert str(snap.get("ui_source") or "").startswith("remote")
|
||||
|
||||
|
||||
def test_prefer_remote_still_used_when_both_live(monkeypatch):
|
||||
local = {
|
||||
"live_page_open": True,
|
||||
"on_air": True,
|
||||
"age_sec": 5.0,
|
||||
"received_at": 1.0,
|
||||
"ui_source": "local",
|
||||
"viewer_count": 1,
|
||||
}
|
||||
remote = {
|
||||
"live_page_open": True,
|
||||
"on_air": True,
|
||||
"age_sec": 5.0,
|
||||
"received_at": 1.0,
|
||||
"ui_source": "remote",
|
||||
"viewer_count": 9,
|
||||
}
|
||||
monkeypatch.setattr(yn, "studio_snapshot_for_ref", lambda *a, **k: dict(remote))
|
||||
monkeypatch.setattr(yn, "studio_snapshot_for_instance", lambda *a, **k: dict(local))
|
||||
g = {
|
||||
"neko_open_prefer": "remote",
|
||||
"ops_neko_open_url": "https://example/neko/19/",
|
||||
"ops_neko_slot": 19,
|
||||
"neko_instance_id": 3,
|
||||
}
|
||||
snap = yn.studio_snapshot_for_group(g, max_age_sec=120.0, include_minute_reports=False)
|
||||
assert snap.get("viewer_count") == 9
|
||||
34
backend/tests/test_timeslot_test_overlay.py
Normal file
34
backend/tests/test_timeslot_test_overlay.py
Normal file
@ -0,0 +1,34 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from app.yt_assign_db import overlay_timeslot_test_schedule
|
||||
|
||||
|
||||
def test_overlay_timeslot_test_marks_forced_active():
|
||||
sched = {
|
||||
"channels": [
|
||||
{"group_id": "a", "active": True, "alias_group_ids": []},
|
||||
{"group_id": "b", "active": False, "alias_group_ids": ["b2"]},
|
||||
]
|
||||
}
|
||||
out = overlay_timeslot_test_schedule(sched, test_on=True, test_group_id="b")
|
||||
assert out["test_mode"] is True
|
||||
assert out["test_group_id"] == "b"
|
||||
by = {c["group_id"]: c for c in out["channels"]}
|
||||
assert by["a"]["active"] is False
|
||||
assert by["a"]["schedule_active"] is True
|
||||
assert by["b"]["active"] is True
|
||||
assert by["b"]["test_force"] is True
|
||||
|
||||
|
||||
def test_overlay_timeslot_test_off_keeps_clock():
|
||||
sched = {
|
||||
"channels": [
|
||||
{"group_id": "a", "active": True, "alias_group_ids": []},
|
||||
{"group_id": "b", "active": False, "alias_group_ids": []},
|
||||
]
|
||||
}
|
||||
out = overlay_timeslot_test_schedule(sched, test_on=False, test_group_id="b")
|
||||
assert out["test_mode"] is False
|
||||
assert out["channels"][0]["active"] is True
|
||||
assert out["channels"][1]["active"] is False
|
||||
@ -1,7 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
from app.youtube_live import _live_entry, _parse_batch_result
|
||||
import time
|
||||
|
||||
from app.youtube_live import (
|
||||
_live_entry,
|
||||
_parse_batch_result,
|
||||
_studio_receiving_from_snap,
|
||||
_studio_snap_belongs_to_assign_group,
|
||||
)
|
||||
|
||||
|
||||
def test_parse_batch_live():
|
||||
@ -45,3 +52,84 @@ def test_parse_broadcast_shaped_as_search_not_required():
|
||||
assert entry["is_live"] is False
|
||||
assert entry["channel_id"] == "UCabc"
|
||||
assert entry["source"] == "oauth-broadcast"
|
||||
|
||||
|
||||
def test_studio_receiving_rejects_edge_mirror_and_preparing():
|
||||
assert not _studio_receiving_from_snap(
|
||||
{
|
||||
"on_air": True,
|
||||
"encoder_receiving": True,
|
||||
"live_status": "live",
|
||||
"detect_source": "edge_assign_live",
|
||||
"received_at": time.time(),
|
||||
}
|
||||
)
|
||||
assert not _studio_receiving_from_snap(
|
||||
{
|
||||
"on_air": True,
|
||||
"preparing_stream": True,
|
||||
"live_status": "preparing",
|
||||
"detect_source": "cdp_dom",
|
||||
"received_at": time.time(),
|
||||
}
|
||||
)
|
||||
assert not _studio_receiving_from_snap(
|
||||
{
|
||||
"on_air": True,
|
||||
"live_status": "live",
|
||||
"detect_source": "chrome_extension",
|
||||
"received_at": time.time() - 120,
|
||||
}
|
||||
)
|
||||
assert _studio_receiving_from_snap(
|
||||
{
|
||||
"on_air": True,
|
||||
"encoder_receiving": True,
|
||||
"live_status": "live",
|
||||
"detect_source": "chrome_extension",
|
||||
"received_at": time.time() - 10,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_studio_snap_shared_neko_requires_ownership():
|
||||
snap = {
|
||||
"on_air": True,
|
||||
"encoder_receiving": True,
|
||||
"live_status": "live",
|
||||
"url": "https://studio.youtube.com/video/pMQedt4HENo/livestreaming",
|
||||
"detect_source": "chrome_extension",
|
||||
"received_at": time.time() - 5,
|
||||
}
|
||||
# Sibling card on shared Neko, not pushing, wrong UC → must not claim receiving.
|
||||
assert not _studio_snap_belongs_to_assign_group(
|
||||
snap,
|
||||
youtube_channel_id="UCtVfMFdLTN4ap__8g7MFtVw",
|
||||
neko_shared=True,
|
||||
group_is_pushing=False,
|
||||
)
|
||||
# Owner pushing on that Neko may claim it.
|
||||
assert _studio_snap_belongs_to_assign_group(
|
||||
snap,
|
||||
youtube_channel_id="UCO9wMc9tj9mD221Gu0rLBeA",
|
||||
neko_shared=True,
|
||||
group_is_pushing=True,
|
||||
)
|
||||
# Channel path in Studio URL binds unambiguously.
|
||||
assert _studio_snap_belongs_to_assign_group(
|
||||
{
|
||||
**snap,
|
||||
"url": "https://studio.youtube.com/channel/UCtVfMFdLTN4ap__8g7MFtVw/livestreaming",
|
||||
},
|
||||
youtube_channel_id="UCtVfMFdLTN4ap__8g7MFtVw",
|
||||
neko_shared=True,
|
||||
group_is_pushing=False,
|
||||
)
|
||||
# Saved studio video hint matches snap URL.
|
||||
assert _studio_snap_belongs_to_assign_group(
|
||||
snap,
|
||||
youtube_channel_id="UCtVfMFdLTN4ap__8g7MFtVw",
|
||||
neko_shared=True,
|
||||
group_is_pushing=False,
|
||||
studio_url_hint="https://studio.youtube.com/video/pMQedt4HENo/livestreaming",
|
||||
)
|
||||
@ -1,4 +1,4 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { fetchJson } from "@/lib/api";
|
||||
import { useEventStream } from "@/lib/realtime";
|
||||
@ -30,12 +30,15 @@ const DouyinLiveContext = createContext<{
|
||||
refresh: async () => {},
|
||||
});
|
||||
|
||||
export function useDouyinLiveProviderValue(intervalMs = 10000) {
|
||||
export function useDouyinLiveProviderValue(intervalMs = 25000) {
|
||||
const [map, setMap] = useState<DouyinLiveMap | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { tick, last } = useEventStream(true);
|
||||
const inFlight = useRef(false);
|
||||
|
||||
const refresh = useCallback(async (silent = false) => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const data = (await fetchJson("/api/douyin/live-map")) as DouyinLiveMap;
|
||||
@ -43,13 +46,17 @@ export function useDouyinLiveProviderValue(intervalMs = 10000) {
|
||||
} catch {
|
||||
/* keep last map */
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh(true);
|
||||
const id = window.setInterval(() => void refresh(true), intervalMs);
|
||||
const id = window.setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
void refresh(true);
|
||||
}, intervalMs);
|
||||
const onVis = () => {
|
||||
if (document.visibilityState === "visible") void refresh(true);
|
||||
};
|
||||
@ -63,6 +70,7 @@ export function useDouyinLiveProviderValue(intervalMs = 10000) {
|
||||
useEffect(() => {
|
||||
if (!last?.kind) return;
|
||||
if (!["live", "offline", "risk"].includes(String(last.kind))) return;
|
||||
if (document.hidden) return;
|
||||
void refresh(true);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tick]);
|
||||
@ -83,18 +91,21 @@ export function useDouyinLiveMap() {
|
||||
return useContext(DouyinLiveContext);
|
||||
}
|
||||
|
||||
export function useDouyinLiveEntry(roomId?: string, fallback?: DouyinLiveEntry | null): DouyinLiveEntry | null {
|
||||
export function useDouyinLiveCount() {
|
||||
const { map } = useDouyinLiveMap();
|
||||
return Number(map?.live_count || 0);
|
||||
}
|
||||
|
||||
export function useDouyinLiveEntry(
|
||||
roomId?: string,
|
||||
fallback?: DouyinLiveEntry | null,
|
||||
): DouyinLiveEntry | null {
|
||||
const { map } = useDouyinLiveMap();
|
||||
const rid = String(roomId || "").trim();
|
||||
if (!rid) return fallback ?? null;
|
||||
return map?.entries?.[rid] ?? fallback ?? null;
|
||||
}
|
||||
|
||||
export function useDouyinLiveCount() {
|
||||
const { map } = useDouyinLiveMap();
|
||||
return Number(map?.live_count || 0);
|
||||
}
|
||||
|
||||
export function resolveDouyinLive(entry: DouyinLiveEntry | null | undefined, lastStatus?: string) {
|
||||
const status = String(entry?.last_status || lastStatus || "unknown").trim() || "unknown";
|
||||
const isLive = entry?.is_live ?? status === "live";
|
||||
|
||||
@ -46,6 +46,7 @@ export function useYouTubeLiveProviderValue(intervalMs = 30000) {
|
||||
const [map, setMap] = useState<YouTubeLiveMap | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [focused, setFocused] = useState(true);
|
||||
const inFlight = useMemo(() => ({ current: false }), []);
|
||||
|
||||
useEffect(() => {
|
||||
const unsub = window.desktop?.onWindowFocus?.((f) => setFocused(f));
|
||||
@ -58,6 +59,8 @@ export function useYouTubeLiveProviderValue(intervalMs = 30000) {
|
||||
}, []);
|
||||
|
||||
const refresh = useCallback(async (silent = false) => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const data = (await fetchJson("/api/youtube/live-map")) as YouTubeLiveMap;
|
||||
@ -65,9 +68,10 @@ export function useYouTubeLiveProviderValue(intervalMs = 30000) {
|
||||
} catch {
|
||||
/* keep last map */
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [inFlight]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh(true);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Loader2, RefreshCw, ArrowRight, ShieldOff } from "lucide-react";
|
||||
|
||||
@ -111,6 +111,7 @@ export default function HomePage() {
|
||||
const now = useNow(1000);
|
||||
const { connected, last, tick } = useEventStream(false); // desktop: poll only — SSE was wedging Windows API
|
||||
const ytLiveCount = useYouTubeLiveCount();
|
||||
const silentTick = useRef(0);
|
||||
|
||||
const load = useCallback(async (opts?: RefreshOpts) => {
|
||||
const silent = Boolean(opts?.silent);
|
||||
@ -121,6 +122,26 @@ export default function HomePage() {
|
||||
try {
|
||||
const iso = todayBeijingISO();
|
||||
const desktop = Boolean(window.desktop);
|
||||
// Silent polls: mostly light (monitor + active); fat payload every 3rd tick.
|
||||
const lightOnly = silent && silentTick.current++ % 3 !== 0;
|
||||
if (lightOnly) {
|
||||
const m = await fetchJson("/api/monitor/status?light=1").catch(() =>
|
||||
fetchJson("/api/monitor/status"),
|
||||
);
|
||||
const a = await fetchJson("/api/sessions/active");
|
||||
setStatus(m);
|
||||
const sessions = (a.sessions || []) as ActiveSession[];
|
||||
const seen = new Set<string>();
|
||||
setActive(
|
||||
sessions.filter((s) => {
|
||||
const key = s.room_id || s.id;
|
||||
if (!key || seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (desktop) {
|
||||
// Windows desktop: serialize SQLite-backed API calls (avoid 20s timeouts)
|
||||
const m = await fetchJson("/api/monitor/status");
|
||||
|
||||
@ -785,7 +785,7 @@ function OpsPanel() {
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const [h, pb] = await Promise.all([
|
||||
fetchJson("/api/health"),
|
||||
fetchJson("/api/health?detail=1"),
|
||||
fetchJson("/api/pb/health").catch(() => null),
|
||||
]);
|
||||
setHealth(h);
|
||||
|
||||
@ -59,6 +59,8 @@ type BoardChannel = {
|
||||
scheduled: number;
|
||||
uploaded: number;
|
||||
pending: number;
|
||||
recorded?: number;
|
||||
recording?: number;
|
||||
gap?: number;
|
||||
min_met?: boolean;
|
||||
max_met?: boolean;
|
||||
@ -241,11 +243,16 @@ export default function ShortsPage() {
|
||||
const totals = useMemo(() => {
|
||||
const uploaded = boardChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
|
||||
const scheduled = boardChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
|
||||
const used = boardChannels.reduce((s, c) => s + (c.used || 0), 0);
|
||||
const recorded = boardChannels.reduce((s, c) => s + (c.recorded || 0), 0);
|
||||
const pending = boardChannels.reduce((s, c) => s + (c.pending || 0), 0);
|
||||
const recording = boardChannels.reduce((s, c) => s + (c.recording || 0), 0);
|
||||
const used = uploaded;
|
||||
const cap = boardChannels.reduce((s, c) => s + (c.daily_max || 9), 0);
|
||||
const minTarget = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0);
|
||||
const gap = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.used || 0))), 0);
|
||||
return { uploaded, scheduled, used, cap, minTarget, gap };
|
||||
const gap = boardChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))), 0);
|
||||
const queuedUpload = scheduled + recorded;
|
||||
const pendingRecord = pending + recording;
|
||||
return { uploaded, scheduled, recorded, pending, recording, queuedUpload, pendingRecord, used, cap, minTarget, gap };
|
||||
}, [boardChannels]);
|
||||
|
||||
const hoursLeft = secondsLeft > 0 ? `${Math.floor(secondsLeft / 3600)}h${Math.floor((secondsLeft % 3600) / 60)}m` : "—";
|
||||
@ -258,7 +265,6 @@ export default function ShortsPage() {
|
||||
}>;
|
||||
|
||||
async function probeOauth() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/oauth/probe", { method: "POST" });
|
||||
const failed = Number(r.failed ?? 0);
|
||||
@ -269,13 +275,10 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle(enabled: boolean) {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
try {
|
||||
await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" });
|
||||
@ -283,8 +286,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -304,7 +305,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
|
||||
async function saveChannel(andAuth: boolean) {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
@ -329,8 +329,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -369,7 +367,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
|
||||
async function runReconcile() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/reconcile", { method: "POST" });
|
||||
toast.push(
|
||||
@ -379,8 +376,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -398,7 +393,6 @@ export default function ShortsPage() {
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/jobs/bulk", {
|
||||
method: "POST",
|
||||
@ -409,8 +403,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -663,9 +655,9 @@ export default function ShortsPage() {
|
||||
<>
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
||||
{[
|
||||
["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "每频道强制 9 条/日"],
|
||||
["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "每频道强制 9 条/日"],
|
||||
["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"],
|
||||
["已上传", String(totals.uploaded), `排队 ${totals.scheduled} · 剩余 ${hoursLeft}`],
|
||||
["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`],
|
||||
[
|
||||
"抖音在播源",
|
||||
String(status?.douyin_live_count ?? "—"),
|
||||
@ -714,7 +706,6 @@ export default function ShortsPage() {
|
||||
<span className="text-slate-400">开关</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void toggle(true)}
|
||||
className={`rounded-lg px-3 py-1.5 ${status?.enabled ? "bg-amber-500/25 text-amber-50" : "bg-white/5 text-slate-300"}`}
|
||||
>
|
||||
@ -722,7 +713,6 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void toggle(false)}
|
||||
className={`rounded-lg px-3 py-1.5 ${!status?.enabled ? "bg-rose-500/25 text-rose-50" : "bg-white/5 text-slate-300"}`}
|
||||
>
|
||||
@ -737,17 +727,14 @@ export default function ShortsPage() {
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/fill-quota", { method: "POST" });
|
||||
setMsg(`配额补量入队 ${r.just_quota_filled ?? 0}(北京日剩余 ${r.quota_gap ?? "—"} 槽)`);
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="ml-auto inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-1.5 text-xs text-teal-100"
|
||||
@ -757,10 +744,9 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/sample-now", { method: "POST" });
|
||||
const n = Number(r.just_enqueued ?? 0);
|
||||
const live = Number(r.live_count ?? 0);
|
||||
@ -772,8 +758,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="ml-auto inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-100"
|
||||
@ -783,7 +767,7 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={() => void runReconcile()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200"
|
||||
>
|
||||
@ -792,7 +776,6 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void probeOauth()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200"
|
||||
>
|
||||
@ -829,17 +812,14 @@ export default function ShortsPage() {
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/fill-quota", { method: "POST" });
|
||||
toast.push(`补量入队 ${r.just_quota_filled ?? 0}`, "ok");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="rounded-lg bg-amber-500/25 px-2.5 py-1 text-amber-50 hover:bg-amber-500/35"
|
||||
@ -858,7 +838,6 @@ export default function ShortsPage() {
|
||||
<div className="flex gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void probeOauth()}
|
||||
className="rounded-lg bg-rose-500/25 px-2.5 py-1 hover:bg-rose-500/35"
|
||||
>
|
||||
@ -915,16 +894,17 @@ export default function ShortsPage() {
|
||||
return String(a.id || "").localeCompare(String(b.id || ""));
|
||||
})
|
||||
.map((ch) => {
|
||||
const pct = Math.min(100, Math.round((ch.used / Math.max(1, ch.daily_max)) * 100));
|
||||
const progress = Number(ch.uploaded ?? ch.used ?? 0);
|
||||
const pct = Math.min(100, Math.round((progress / Math.max(1, ch.daily_max)) * 100));
|
||||
const minPct = Math.round((ch.daily_min / Math.max(1, ch.daily_max)) * 100);
|
||||
const full = channels.find((x) => x.id === ch.id);
|
||||
const gap = ch.gap ?? Math.max(0, ch.daily_max - ch.used);
|
||||
const gap = ch.gap ?? Math.max(0, ch.daily_max - progress);
|
||||
const warn = ch.enabled !== false && (ch.behind_pace || (!ch.min_met && gap > 0));
|
||||
return (
|
||||
<div
|
||||
key={ch.id}
|
||||
className={`rounded-xl border bg-gradient-to-br from-white/[0.04] to-transparent p-3 ${
|
||||
warn ? "border-amber-500/35" : ch.max_met ? "border-teal-500/30" : "border-white/10"
|
||||
warn ? "border-amber-500/35" : progress >= (ch.daily_max || 9) ? "border-teal-500/30" : "border-white/10"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
@ -970,8 +950,7 @@ export default function ShortsPage() {
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-slate-400">
|
||||
<span>
|
||||
{ch.used}/{ch.daily_max || 9}
|
||||
<span className="text-slate-600">(强制 9)</span>
|
||||
{progress}/{ch.daily_max || 9}
|
||||
</span>
|
||||
{gap > 0 ? <span className="text-amber-300">缺 {gap}</span> : <span className="text-teal-300">已满</span>}
|
||||
<span>上传 {ch.uploaded}</span>
|
||||
@ -1102,7 +1081,6 @@ export default function ShortsPage() {
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveChannel(true)}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
|
||||
>
|
||||
@ -1111,7 +1089,6 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveChannel(false)}
|
||||
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
||||
>
|
||||
@ -1196,7 +1173,6 @@ export default function ShortsPage() {
|
||||
<span className="text-teal-200">已选 {selectedCount}</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void bulkAction("retry")}
|
||||
className="rounded-lg bg-white/10 px-2.5 py-1 text-slate-100 hover:bg-white/15"
|
||||
>
|
||||
@ -1204,7 +1180,7 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || uploadBusy}
|
||||
disabled={uploadBusy}
|
||||
onClick={() => void bulkAction("upload_now")}
|
||||
className="rounded-lg bg-teal-500/20 px-2.5 py-1 text-teal-100 hover:bg-teal-500/30"
|
||||
>
|
||||
|
||||
@ -60,7 +60,6 @@ export default function YouTubePage() {
|
||||
const [videos, setVideos] = useState<YtVideo[]>([]);
|
||||
const [playlists, setPlaylists] = useState<any[]>([]);
|
||||
const [edit, setEdit] = useState<YtVideo | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [msg, setMsg] = useState("");
|
||||
|
||||
@ -84,7 +83,6 @@ export default function YouTubePage() {
|
||||
|
||||
const loadManage = useCallback(async () => {
|
||||
if (!channelPk) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const [d, v, p] = await Promise.all([
|
||||
@ -99,8 +97,6 @@ export default function YouTubePage() {
|
||||
setError((e as Error).message);
|
||||
setDash(null);
|
||||
setVideos([]);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [channelPk]);
|
||||
|
||||
@ -114,7 +110,6 @@ export default function YouTubePage() {
|
||||
|
||||
async function saveVideo() {
|
||||
if (!edit || !channelPk) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setMsg("");
|
||||
try {
|
||||
@ -133,14 +128,11 @@ export default function YouTubePage() {
|
||||
await loadManage();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function setPrivacy(videoId: string, privacy: string) {
|
||||
if (!channelPk) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, {
|
||||
method: "PATCH",
|
||||
@ -150,8 +142,6 @@ export default function YouTubePage() {
|
||||
await loadManage();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -164,7 +154,6 @@ export default function YouTubePage() {
|
||||
destructive: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "DELETE" });
|
||||
toast.push("视频已删除", "ok");
|
||||
@ -172,8 +161,6 @@ export default function YouTubePage() {
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -186,7 +173,6 @@ export default function YouTubePage() {
|
||||
}
|
||||
|
||||
async function runProbe() {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setMsg("");
|
||||
setResult(null);
|
||||
@ -201,8 +187,6 @@ export default function YouTubePage() {
|
||||
setResult(data);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -317,7 +301,7 @@ export default function YouTubePage() {
|
||||
onClick={() => void loadManage()}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
||||
>
|
||||
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
@ -514,7 +498,6 @@ export default function YouTubePage() {
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveVideo()}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
|
||||
>
|
||||
@ -595,11 +578,10 @@ export default function YouTubePage() {
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void runProbe()}
|
||||
className="inline-flex items-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white"
|
||||
>
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
|
||||
<Search className="h-4 w-4" />
|
||||
探测
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@ -33,7 +33,7 @@ export default function OpsMobilePage() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [h, m] = await Promise.all([
|
||||
fetchJson("/api/health"),
|
||||
fetchJson("/api/health?detail=1"),
|
||||
fetchJson("/api/ops/alerts/metrics"),
|
||||
]);
|
||||
setHealth(h as Health);
|
||||
|
||||
@ -111,9 +111,11 @@ export default function HomePage() {
|
||||
const [opsBusy, setOpsBusy] = useState("");
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const now = useNow(1000);
|
||||
const now = useNow(5000);
|
||||
const { connected, last, tick } = useEventStream(true);
|
||||
const silentTickRef = useRef(0);
|
||||
const connectedRef = useRef(connected);
|
||||
connectedRef.current = connected;
|
||||
const ytLiveCount = useYouTubeLiveCount();
|
||||
const { map: ytLiveMap } = useYouTubeLiveMap();
|
||||
const ytLiveNav = useMemo(() => primaryYouTubeLiveNav(ytLiveMap), [ytLiveMap]);
|
||||
@ -129,12 +131,13 @@ export default function HomePage() {
|
||||
if (silent) {
|
||||
silentTickRef.current += 1;
|
||||
const everyThird = silentTickRef.current % 3 === 0;
|
||||
const sseOk = connectedRef.current;
|
||||
// Silent poll: skip fat rooms/day-sessions/stats; SSE feeds events when connected.
|
||||
const reqs: Promise<unknown>[] = [
|
||||
fetchJson("/api/monitor/status?light=1"),
|
||||
fetchJson("/api/sessions/active?platform=douyin"),
|
||||
];
|
||||
if (!connected) {
|
||||
if (!sseOk) {
|
||||
reqs.push(fetchJson("/api/events?limit=20&platform=douyin"));
|
||||
}
|
||||
if (everyThird) {
|
||||
@ -145,7 +148,7 @@ export default function HomePage() {
|
||||
const m = results[i++] as MonitorStatus;
|
||||
setStatus((prev) => ({ ...(prev || {}), ...m } as MonitorStatus));
|
||||
const a = results[i++] as { sessions?: ActiveSession[] };
|
||||
if (!connected) {
|
||||
if (!sseOk) {
|
||||
const e = results[i++] as { events?: EventItem[] };
|
||||
setEvents(e.events || []);
|
||||
}
|
||||
@ -206,14 +209,14 @@ export default function HomePage() {
|
||||
} finally {
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, [connected]);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load({ silent: false });
|
||||
const t = setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
void load({ silent: true });
|
||||
}, 25000);
|
||||
}, 35000);
|
||||
const onVis = () => {
|
||||
if (!document.hidden) void load({ silent: true });
|
||||
};
|
||||
|
||||
@ -1349,7 +1349,7 @@ function OpsPanel() {
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const [h, pb] = await Promise.all([
|
||||
fetchJson("/api/health"),
|
||||
fetchJson("/api/health?detail=1"),
|
||||
fetchJson("/api/pb/health").catch(() => null),
|
||||
]);
|
||||
setHealth(h);
|
||||
|
||||
@ -86,6 +86,8 @@ type BoardChannel = {
|
||||
scheduled: number;
|
||||
uploaded: number;
|
||||
pending: number;
|
||||
recorded?: number;
|
||||
recording?: number;
|
||||
gap?: number;
|
||||
min_met?: boolean;
|
||||
max_met?: boolean;
|
||||
@ -154,7 +156,20 @@ export default function ShortsPage() {
|
||||
const [jobTotal, setJobTotal] = useState(0);
|
||||
const [form, setForm] = useState({ ...emptyForm });
|
||||
const [editId, setEditId] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [actionPending, setActionPending] = useState<Record<string, true>>({});
|
||||
const isPending = useCallback((key: string) => Boolean(actionPending[key]), [actionPending]);
|
||||
const withPending = useCallback(async (key: string, fn: () => Promise<void>) => {
|
||||
setActionPending((p) => (p[key] ? p : { ...p, [key]: true }));
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
setActionPending((p) => {
|
||||
const n = { ...p };
|
||||
delete n[key];
|
||||
return n;
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
const [togglingId, setTogglingId] = useState("");
|
||||
const [msg, setMsg] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
@ -179,10 +194,11 @@ export default function ShortsPage() {
|
||||
const { map: ytLiveMap } = useYouTubeLiveMap();
|
||||
|
||||
const load = useCallback(
|
||||
async (opts?: { appendJobs?: boolean; jobOffset?: number }) => {
|
||||
async (opts?: { appendJobs?: boolean; jobOffset?: number; soft?: boolean }) => {
|
||||
const appendJobs = Boolean(opts?.appendJobs);
|
||||
const soft = Boolean(opts?.soft);
|
||||
if (appendJobs) setLoadingMoreJobs(true);
|
||||
else setLoading(true);
|
||||
else if (!soft) setLoading(true);
|
||||
try {
|
||||
const off = appendJobs ? Number(opts?.jobOffset ?? 0) : 0;
|
||||
const jobQs = new URLSearchParams({ limit: String(JOB_PAGE), offset: String(off) });
|
||||
@ -452,13 +468,18 @@ export default function ShortsPage() {
|
||||
const totals = useMemo(() => {
|
||||
const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
|
||||
const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
|
||||
const used = displayChannels.reduce((s, c) => s + (c.used || 0), 0);
|
||||
const recorded = displayChannels.reduce((s, c) => s + (c.recorded || 0), 0);
|
||||
const pending = displayChannels.reduce((s, c) => s + (c.pending || 0), 0);
|
||||
const recording = displayChannels.reduce((s, c) => s + (c.recording || 0), 0);
|
||||
const used = uploaded;
|
||||
const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 9), 0);
|
||||
const minTarget = displayChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0);
|
||||
const gap = displayChannels
|
||||
.filter((c) => c.enabled !== false)
|
||||
.reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.used || 0))), 0);
|
||||
return { uploaded, scheduled, used, cap, minTarget, gap };
|
||||
.reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))), 0);
|
||||
const queuedUpload = scheduled + recorded;
|
||||
const pendingRecord = pending + recording;
|
||||
return { uploaded, scheduled, recorded, pending, recording, queuedUpload, pendingRecord, used, cap, minTarget, gap };
|
||||
}, [displayChannels]);
|
||||
|
||||
const hoursLeft = secondsLeft > 0 ? `${Math.floor(secondsLeft / 3600)}h${Math.floor((secondsLeft % 3600) / 60)}m` : "—";
|
||||
@ -476,7 +497,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
|
||||
async function probeOauth() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/oauth/probe", { method: "POST" });
|
||||
const failed = Number(r.failed ?? 0);
|
||||
@ -487,13 +507,10 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle(enabled: boolean) {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
try {
|
||||
await fetchJson(enabled ? "/api/shorts/start" : "/api/shorts/stop", { method: "POST" });
|
||||
@ -501,8 +518,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -529,7 +544,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
|
||||
async function saveChannel(andAuth: boolean) {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
@ -572,8 +586,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -638,7 +650,11 @@ export default function ShortsPage() {
|
||||
} else {
|
||||
toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok");
|
||||
}
|
||||
await load();
|
||||
// Soft refresh: keep cards mounted; only this switch shows busy.
|
||||
setChannels((prev) =>
|
||||
prev.map((c) => (c.id === ch.id ? { ...c, enabled: turningOn } : c)),
|
||||
);
|
||||
await load({ soft: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -653,7 +669,6 @@ export default function ShortsPage() {
|
||||
}
|
||||
|
||||
async function runReconcile() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/reconcile", { method: "POST" });
|
||||
toast.push(
|
||||
@ -663,8 +678,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -682,7 +695,6 @@ export default function ShortsPage() {
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/jobs/bulk", {
|
||||
method: "POST",
|
||||
@ -693,8 +705,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -965,9 +975,9 @@ export default function ShortsPage() {
|
||||
<>
|
||||
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
||||
{[
|
||||
["北京日配额", `${totals.used} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"],
|
||||
["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"],
|
||||
["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"],
|
||||
["已上传", String(totals.uploaded), `排队 ${totals.scheduled} · 剩余 ${hoursLeft}`],
|
||||
["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`],
|
||||
[
|
||||
"抖音在播源",
|
||||
String(status?.douyin_live_count ?? "—"),
|
||||
@ -976,7 +986,9 @@ export default function ShortsPage() {
|
||||
[
|
||||
"错峰间隔",
|
||||
`≥${Math.round((status?.upload_min_gap_sec || 720) / 60)}分`,
|
||||
`同频道 ≥${Math.round((status?.channel_min_gap_sec || 2400) / 60)}分 · 落后自动加速`,
|
||||
status?.pace?.behind
|
||||
? `同频道 ≥${Math.round((status?.channel_min_gap_sec || 600) / 60)}分 · 目标20:00前90% · 落后加速中`
|
||||
: `同频道 ≥${Math.round((status?.channel_min_gap_sec || 600) / 60)}分 · 目标20:00前90%`,
|
||||
],
|
||||
].map(([label, value, hint]) => (
|
||||
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">
|
||||
@ -1016,7 +1028,6 @@ export default function ShortsPage() {
|
||||
<span className="text-slate-400">开关</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void toggle(true)}
|
||||
className={`rounded-lg px-3 py-1.5 ${status?.enabled ? "bg-amber-500/25 text-amber-50" : "bg-white/5 text-slate-300"}`}
|
||||
>
|
||||
@ -1024,7 +1035,6 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void toggle(false)}
|
||||
className={`rounded-lg px-3 py-1.5 ${!status?.enabled ? "bg-rose-500/25 text-rose-50" : "bg-white/5 text-slate-300"}`}
|
||||
>
|
||||
@ -1039,17 +1049,14 @@ export default function ShortsPage() {
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/fill-quota", { method: "POST" });
|
||||
setMsg(`配额补量入队 ${r.just_quota_filled ?? 0}(北京日剩余 ${r.quota_gap ?? "—"} 槽)`);
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="ml-auto inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-1.5 text-xs text-teal-100"
|
||||
@ -1059,10 +1066,9 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/sample-now", { method: "POST" });
|
||||
const n = Number(r.just_enqueued ?? 0);
|
||||
const live = Number(r.live_count ?? 0);
|
||||
@ -1074,8 +1080,6 @@ export default function ShortsPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="ml-auto inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-100"
|
||||
@ -1085,7 +1089,7 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={() => void runReconcile()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200"
|
||||
>
|
||||
@ -1094,7 +1098,6 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void probeOauth()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200"
|
||||
>
|
||||
@ -1117,15 +1120,30 @@ export default function ShortsPage() {
|
||||
|
||||
{msg ? <div className="mb-3 text-sm text-teal-300">{msg}</div> : null}
|
||||
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
|
||||
{status?.upload_quota_blocked ? (
|
||||
<div className="mb-3 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2.5 text-xs text-rose-50">
|
||||
<p className="font-medium text-rose-100">
|
||||
Client {(status.upload_quota_blocked_profiles as string[] | undefined)?.join("、") || "?"}{" "}
|
||||
YouTube 接口配额冷静中(自动上传暂停,手动上传不拦)
|
||||
</p>
|
||||
<p className="mt-1 text-rose-100/90">
|
||||
{status.upload_quota_blocked_until ? (
|
||||
<>约至 {fmtTs(status.upload_quota_blocked_until)}(北京)后再自动尝试;冷静窗口内不再刷 ntfy。</>
|
||||
) : (
|
||||
<>冷静约 {Number(status.yt_quota_cooldown_sec) || 3600} 秒后自动重试。</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
{Array.isArray(status?.yt_quota_exhausted_hint) && (status.yt_quota_exhausted_hint as string[]).length ? (
|
||||
<div className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs text-amber-50">
|
||||
<p className="font-medium text-amber-100">部分 Client 本地计数已达参考上限(仅提示,不拦截上传)</p>
|
||||
<p className="font-medium text-amber-100">部分 Client 本地参考计数已达上限</p>
|
||||
<p className="mt-1 text-amber-100/90">
|
||||
提示:
|
||||
仅本地参考(非 Google 真限额):
|
||||
{(status.yt_quota_exhausted_hint as string[]).map((p) => `Client ${p}`).join("、")}
|
||||
。仍可点「立即上传」;以 YouTube 接口返回为准。
|
||||
。真限制以接口 429 / 上方「冷静中」为准;仍可「立即上传」。
|
||||
{status.yt_quota_reset_at ? (
|
||||
<> YouTube 侧预计重置:{fmtTs(status.yt_quota_reset_at)}(北京)</>
|
||||
<> 参考日切换:{fmtTs(status.yt_quota_reset_at)}(北京)</>
|
||||
) : null}
|
||||
</p>
|
||||
{Array.isArray(status.yt_quota_by_profile) ? (
|
||||
@ -1134,19 +1152,26 @@ export default function ShortsPage() {
|
||||
<span
|
||||
key={row.id}
|
||||
className={`rounded border px-2 py-0.5 text-[10px] ${
|
||||
row.exhausted_hint
|
||||
? "border-amber-400/40 bg-amber-500/20 text-amber-100"
|
||||
: "border-teal-400/30 bg-teal-500/10 text-teal-100"
|
||||
row.blocked
|
||||
? "border-rose-400/40 bg-rose-500/20 text-rose-100"
|
||||
: row.exhausted_hint
|
||||
? "border-amber-400/40 bg-amber-500/20 text-amber-100"
|
||||
: "border-teal-400/30 bg-teal-500/10 text-teal-100"
|
||||
}`}
|
||||
>
|
||||
Client {row.id} · {row.used}/{row.limit}
|
||||
{row.exhausted_hint ? " · 参考已满" : ` · 剩 ${row.remaining}`}
|
||||
{row.blocked
|
||||
? " · 冷静中"
|
||||
: row.exhausted_hint
|
||||
? " · 参考已满"
|
||||
: ` · 剩 ${row.remaining}`}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<p className="mt-1 text-[11px] text-amber-200/70">
|
||||
配额按 OAuth Client A/B/C/D(不同 Google 项目)分别计算,互不影响。本系统不自行暂停上传。
|
||||
配额按 OAuth Client A/B/C/D 分别计算。接口 429 后该 Client 自动上传冷静约{" "}
|
||||
{Number(status.yt_quota_cooldown_sec) || 3600} 秒;手动上传始终可用。
|
||||
</p>
|
||||
</div>
|
||||
) : Array.isArray(status?.yt_quota_by_profile) ? (
|
||||
@ -1155,12 +1180,15 @@ export default function ShortsPage() {
|
||||
<span
|
||||
key={row.id}
|
||||
className={`rounded border px-2 py-0.5 ${
|
||||
Number(row.remaining) <= 10
|
||||
? "border-amber-500/30 bg-amber-500/10 text-amber-100"
|
||||
: "border-white/10 bg-white/5"
|
||||
row.blocked
|
||||
? "border-rose-500/40 bg-rose-500/15 text-rose-100"
|
||||
: Number(row.remaining) <= 10
|
||||
? "border-amber-500/30 bg-amber-500/10 text-amber-100"
|
||||
: "border-white/10 bg-white/5"
|
||||
}`}
|
||||
>
|
||||
Client {row.id} · {row.used}/{row.limit}(剩 {row.remaining})
|
||||
Client {row.id} · {row.used}/{row.limit}
|
||||
{row.blocked ? " · 冷静中" : `(剩 ${row.remaining})`}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
@ -1183,17 +1211,14 @@ export default function ShortsPage() {
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
try {
|
||||
const r = await fetchJson("/api/shorts/fill-quota", { method: "POST" });
|
||||
toast.push(`补量入队 ${r.just_quota_filled ?? 0}`, "ok");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="rounded-lg bg-amber-500/25 px-2.5 py-1 text-amber-50 hover:bg-amber-500/35"
|
||||
@ -1212,7 +1237,6 @@ export default function ShortsPage() {
|
||||
<div className="flex gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void probeOauth()}
|
||||
className="rounded-lg bg-rose-500/25 px-2.5 py-1 hover:bg-rose-500/35"
|
||||
>
|
||||
@ -1250,7 +1274,7 @@ export default function ShortsPage() {
|
||||
dailyMin={Number(status?.quota_defaults?.daily_min ?? 9)}
|
||||
dailyMax={Number(status?.quota_defaults?.daily_max ?? 9)}
|
||||
channelCount={channels.length}
|
||||
busy={busy}
|
||||
busy={false}
|
||||
onSave={async ({ daily_min, daily_max }) => {
|
||||
await fetchJson("/api/shorts/quota-defaults", {
|
||||
method: "POST",
|
||||
@ -1340,10 +1364,11 @@ export default function ShortsPage() {
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{group.channels.map((ch) => {
|
||||
const pct = Math.min(100, Math.round((ch.used / Math.max(1, ch.daily_max)) * 100));
|
||||
const progress = Number(ch.uploaded ?? ch.used ?? 0);
|
||||
const pct = Math.min(100, Math.round((progress / Math.max(1, ch.daily_max)) * 100));
|
||||
const minPct = Math.round((ch.daily_min / Math.max(1, ch.daily_max)) * 100);
|
||||
const full = channels.find((x) => x.id === ch.id);
|
||||
const gap = ch.gap ?? Math.max(0, ch.daily_max - ch.used);
|
||||
const gap = ch.gap ?? Math.max(0, ch.daily_max - progress);
|
||||
const warn = ch.enabled !== false && (ch.behind_pace || (!ch.min_met && gap > 0));
|
||||
return (
|
||||
<div
|
||||
@ -1354,7 +1379,7 @@ export default function ShortsPage() {
|
||||
? "border-white/10 opacity-55"
|
||||
: warn
|
||||
? "border-amber-500/35"
|
||||
: ch.max_met
|
||||
: progress >= (ch.daily_max || 9)
|
||||
? "border-teal-500/30"
|
||||
: "border-white/10"
|
||||
}`}
|
||||
@ -1391,7 +1416,7 @@ export default function ShortsPage() {
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-slate-400">
|
||||
<span>
|
||||
{ch.used}/{ch.daily_max || 9}
|
||||
{progress}/{ch.daily_max || 9}
|
||||
</span>
|
||||
{gap > 0 ? <span className="text-amber-300">缺 {gap}</span> : <span className="text-teal-300">已满</span>}
|
||||
<span>上传 {ch.uploaded}</span>
|
||||
@ -1600,16 +1625,14 @@ export default function ShortsPage() {
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveChannel(true)}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
|
||||
>
|
||||
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <KeyRound className="h-3.5 w-3.5" />}
|
||||
{isPending("saveChannel") ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <KeyRound className="h-3.5 w-3.5" />}
|
||||
保存并授权
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveChannel(false)}
|
||||
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
||||
>
|
||||
@ -1696,7 +1719,6 @@ export default function ShortsPage() {
|
||||
<span className="text-teal-200">已选 {selectedCount}</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void bulkAction("retry")}
|
||||
className="rounded-lg bg-white/10 px-2.5 py-1 text-slate-100 hover:bg-white/15"
|
||||
>
|
||||
@ -1704,7 +1726,7 @@ export default function ShortsPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || uploadBusy}
|
||||
disabled={uploadBusy}
|
||||
onClick={() => void bulkAction("upload_now")}
|
||||
className="rounded-lg bg-teal-500/20 px-2.5 py-1 text-teal-100 hover:bg-teal-500/30"
|
||||
>
|
||||
|
||||
@ -487,6 +487,9 @@ export default function TikTokPage() {
|
||||
} else {
|
||||
toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok");
|
||||
}
|
||||
setChannels((prev) =>
|
||||
prev.map((c) => (c.id === ch.id ? { ...c, enabled: turningOn } : c)),
|
||||
);
|
||||
void load();
|
||||
} catch (e: any) {
|
||||
toast.push(e?.message || "切换失败", "err");
|
||||
|
||||
@ -70,7 +70,6 @@ export function ClipsPanel({
|
||||
}) {
|
||||
const [st, setSt] = useState<Status | null>(null);
|
||||
const [jobs, setJobs] = useState<XClipJob[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [clipSec, setClipSec] = useState(12);
|
||||
const [dailyMax, setDailyMax] = useState(20);
|
||||
const [captionTpl, setCaptionTpl] = useState("{anchor}");
|
||||
@ -128,15 +127,12 @@ export function ClipsPanel({
|
||||
}, [load]);
|
||||
|
||||
const run = async (fn: () => Promise<void>, okMsg: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast(okMsg, "ok");
|
||||
await load();
|
||||
} catch (e) {
|
||||
toast((e as Error).message || "操作失败", "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
@ -154,7 +150,7 @@ export function ClipsPanel({
|
||||
dailyMax={dailyMax}
|
||||
maxLo={1}
|
||||
maxHi={100}
|
||||
busy={busy}
|
||||
busy={false}
|
||||
saveLabel="保存每日上限"
|
||||
onSave={async ({ daily_max }) => {
|
||||
setDailyMax(daily_max);
|
||||
@ -184,7 +180,6 @@ export function ClipsPanel({
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className={enabled ? ghost : primary}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
@ -194,7 +189,7 @@ export function ClipsPanel({
|
||||
>
|
||||
{enabled ? "关闭自动" : "开启自动"}
|
||||
</button>
|
||||
<button type="button" disabled={busy} className={ghost} onClick={() => void load()}>
|
||||
<button type="button" className={ghost} onClick={() => void load()}>
|
||||
<RefreshCw className="h-3.5 w-3.5" /> 刷新
|
||||
</button>
|
||||
</div>
|
||||
@ -265,7 +260,6 @@ export function ClipsPanel({
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className={`${primary} mt-3`}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
@ -293,7 +287,7 @@ export function ClipsPanel({
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !enabled}
|
||||
disabled={!enabled}
|
||||
className={primary}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
@ -317,7 +311,7 @@ export function ClipsPanel({
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !enabled}
|
||||
disabled={!enabled}
|
||||
className={ghost}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
@ -366,7 +360,6 @@ export function ClipsPanel({
|
||||
{["scheduled", "recorded", "failed"].includes(j.status || "") ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className={ghost}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
@ -380,7 +373,6 @@ export function ClipsPanel({
|
||||
{["failed", "skipped"].includes(j.status || "") ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className={ghost}
|
||||
onClick={() =>
|
||||
void run(async () => {
|
||||
|
||||
@ -424,8 +424,10 @@ export default function YoutubeRelayLogPage() {
|
||||
<dd>{selected.end_reason || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-zinc-500">YouTube 推流密钥(后几位)</dt>
|
||||
<dd className="font-mono">{selected.youtube_key_suffix ? `…${selected.youtube_key_suffix}` : "—"}</dd>
|
||||
<dt className="text-zinc-500">YouTube 推流密钥(历史仅存后缀)</dt>
|
||||
<dd className="font-mono select-all">
|
||||
{selected.youtube_key_suffix ? `…${selected.youtube_key_suffix}` : "—"}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
479
frontend/src/app/youtube/analytics/[groupId]/page.tsx
Normal file
479
frontend/src/app/youtube/analytics/[groupId]/page.tsx
Normal file
@ -0,0 +1,479 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useParams, useSearchParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
ArrowLeft,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Clock3,
|
||||
ExternalLink,
|
||||
Flame,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
Sparkles,
|
||||
Star,
|
||||
Trophy,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { StudioViewerChart } from "@/components/StudioViewerChart";
|
||||
import { fetchJson, fmtDuration, fmtTs } from "@/lib/api";
|
||||
|
||||
type SourceRank = {
|
||||
rank?: number | null;
|
||||
room_id: string;
|
||||
anchor_name?: string;
|
||||
cover_url?: string;
|
||||
douyin_url?: string;
|
||||
session_count: number;
|
||||
live_hours: number;
|
||||
peak_viewers: number | null;
|
||||
avg_viewers: number | null;
|
||||
max_total_views: number | null;
|
||||
score: number;
|
||||
best_hours: Array<{ hour: number; label: string; peak_viewers: number | null; live_minutes: number }>;
|
||||
best_weekdays: Array<{ weekday: number; label: string; peak_viewers: number | null; live_hours: number }>;
|
||||
hour_heatmap?: Array<{ hour: number; live_minutes: number; peak_viewers: number | null }>;
|
||||
planning_tip?: string;
|
||||
in_pool?: boolean;
|
||||
in_featured?: boolean;
|
||||
measured?: boolean;
|
||||
stream_titles?: string[];
|
||||
last_started_at?: number | null;
|
||||
};
|
||||
|
||||
type AnalyticsPayload = {
|
||||
ok: boolean;
|
||||
group: Record<string, any>;
|
||||
window: Record<string, any>;
|
||||
overview: Record<string, any>;
|
||||
source_rankings: SourceRank[];
|
||||
planning_slots: Array<{
|
||||
hour: number;
|
||||
best_peak: number | null;
|
||||
sources: Array<{ room_id: string; anchor_name?: string; cover_url?: string; peak_viewers?: number | null; score?: number }>;
|
||||
}>;
|
||||
daily: any[];
|
||||
hours: any[];
|
||||
studio_sessions: any[];
|
||||
relay_sessions: any[];
|
||||
};
|
||||
|
||||
type Tab = "sources" | "slots" | "sessions" | "daily";
|
||||
|
||||
function fmtNum(n: number | null | undefined): string {
|
||||
if (n == null || !Number.isFinite(Number(n))) return "—";
|
||||
return Number(n).toLocaleString();
|
||||
}
|
||||
|
||||
function Cover({ src, name }: { src?: string; name?: string }) {
|
||||
const [broken, setBroken] = useState(false);
|
||||
const url = String(src || "").trim();
|
||||
if (!url || broken) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-rose-500/20 to-slate-900 text-lg font-semibold text-rose-100/80">
|
||||
{(name || "?").slice(0, 1)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={url} alt={name || ""} className="h-full w-full object-cover" onError={() => setBroken(true)} />
|
||||
);
|
||||
}
|
||||
|
||||
function Kpi({ label, value, hint, tone = "slate" }: { label: string; value: string; hint?: string; tone?: string }) {
|
||||
const tones: Record<string, string> = {
|
||||
slate: "border-white/10 from-white/[0.04]",
|
||||
rose: "border-rose-400/25 from-rose-500/15",
|
||||
teal: "border-teal-400/25 from-teal-500/15",
|
||||
amber: "border-amber-400/25 from-amber-500/15",
|
||||
};
|
||||
return (
|
||||
<div className={`rounded-2xl border bg-gradient-to-br to-transparent p-3 ${tones[tone] || tones.slate}`}>
|
||||
<p className="text-[10px] uppercase tracking-[0.14em] text-slate-500">{label}</p>
|
||||
<p className="mt-1 font-mono text-xl font-semibold text-slate-50">{value}</p>
|
||||
{hint ? <p className="mt-0.5 text-[10px] text-slate-500">{hint}</p> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ChannelAnalyticsPage() {
|
||||
const params = useParams<{ groupId: string }>();
|
||||
const search = useSearchParams();
|
||||
const groupId = String(params?.groupId || "");
|
||||
const [days, setDays] = useState(() => {
|
||||
const d = Number(search?.get("days") || 30);
|
||||
return [7, 14, 30, 60].includes(d) ? d : 30;
|
||||
});
|
||||
const [data, setData] = useState<AnalyticsPayload | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [tab, setTab] = useState<Tab>("sources");
|
||||
const [openRoom, setOpenRoom] = useState("");
|
||||
const [openSession, setOpenSession] = useState("");
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!groupId) return;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = (await fetchJson(
|
||||
`/api/youtube/assign/groups/${encodeURIComponent(groupId)}/analytics?days=${days}`
|
||||
)) as AnalyticsPayload;
|
||||
setData(res);
|
||||
const first = (res.source_rankings || []).find((r) => r.measured)?.room_id || "";
|
||||
setOpenRoom((prev) => prev || first);
|
||||
} catch (e: any) {
|
||||
setError(String(e?.message || e || "加载失败"));
|
||||
setData(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [groupId, days]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const measured = useMemo(() => (data?.source_rankings || []).filter((r) => r.measured), [data]);
|
||||
const unmeasured = useMemo(() => (data?.source_rankings || []).filter((r) => !r.measured), [data]);
|
||||
const top = measured[0];
|
||||
const g = data?.group;
|
||||
const ov = data?.overview;
|
||||
|
||||
const maxHour = useMemo(() => {
|
||||
const src = measured.find((r) => r.room_id === openRoom) || measured[0];
|
||||
return Math.max(1, ...((src?.hour_heatmap || []).map((h) => Number(h.live_minutes || 0))));
|
||||
}, [measured, openRoom]);
|
||||
|
||||
return (
|
||||
<Shell>
|
||||
<div className="relative mx-auto max-w-7xl px-3 pb-20 pt-4 md:px-6">
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 -z-10 h-[480px] overflow-hidden">
|
||||
<div className="absolute -left-16 top-8 h-72 w-72 rounded-full bg-rose-500/15 blur-3xl" />
|
||||
<div className="absolute right-0 top-0 h-80 w-80 rounded-full bg-amber-500/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-slate-400">
|
||||
<Link href="/youtube?mode=assign" className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-slate-300">
|
||||
<ArrowLeft className="h-3.5 w-3.5" /> 分配
|
||||
</Link>
|
||||
<Link href="/youtube/analytics" className="rounded-lg border border-amber-400/25 bg-amber-500/10 px-2.5 py-1.5 text-amber-100">
|
||||
全站源×频道矩阵
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="inline-flex rounded-xl border border-white/10 bg-black/30 p-0.5">
|
||||
{[7, 14, 30, 60].map((d) => (
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
onClick={() => setDays(d)}
|
||||
className={`rounded-lg px-2.5 py-1 text-[11px] ${days === d ? "bg-rose-500/25 text-rose-50" : "text-slate-400"}`}
|
||||
>
|
||||
{d}天
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="button" onClick={() => void load()} className="rounded-xl border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300">
|
||||
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="mb-5 overflow-hidden rounded-[28px] border border-white/10 bg-gradient-to-br from-[#151018] via-[#0c1218] to-[#081018] p-5 md:p-7">
|
||||
<div className="mb-2 inline-flex items-center gap-1.5 rounded-full border border-amber-400/25 bg-amber-500/10 px-2.5 py-1 text-[10px] uppercase tracking-[0.18em] text-amber-100">
|
||||
<Sparkles className="h-3 w-3" /> Source → Channel Planning
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight text-white md:text-3xl">{g?.name || "频道排源"}</h1>
|
||||
<p className="mt-2 max-w-3xl text-sm leading-relaxed text-slate-400">
|
||||
核心问题:哪个抖音直播间在这个 YouTube 频道表现最好?哪个北京时段该开?用 Studio 同时观看/总观看/峰值给每个抖音源打分,指导排班与选源。
|
||||
</p>
|
||||
{top ? (
|
||||
<div className="mt-5 flex flex-col gap-4 rounded-3xl border border-rose-400/25 bg-rose-500/[0.08] p-4 md:flex-row md:items-center">
|
||||
<div className="h-28 w-28 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-black/40 shadow-lg shadow-rose-900/30 md:h-32 md:w-32">
|
||||
<Cover src={top.cover_url} name={top.anchor_name} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Trophy className="h-4 w-4 text-amber-300" />
|
||||
<span className="text-[11px] uppercase tracking-wider text-amber-200">本频道最佳抖音源</span>
|
||||
<span className="rounded-md bg-black/40 px-1.5 py-0.5 font-mono text-[10px] text-slate-400">#{top.rank} · score {top.score}</span>
|
||||
</div>
|
||||
<p className="mt-1 truncate text-xl font-semibold text-white">{top.anchor_name || top.room_id}</p>
|
||||
<a href={top.douyin_url} target="_blank" rel="noreferrer" className="mt-1 inline-flex items-center gap-1 font-mono text-xs text-rose-200 hover:underline">
|
||||
{top.douyin_url?.replace(/^https?:\/\//, "")}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
<p className="mt-2 text-sm text-rose-50/90">{top.planning_tip}</p>
|
||||
<div className="mt-3 flex flex-wrap gap-3 font-mono text-[11px] text-slate-300">
|
||||
<span>均 {fmtNum(top.avg_viewers)}</span>
|
||||
<span>峰 {fmtNum(top.peak_viewers)}</span>
|
||||
<span>总观 {fmtNum(top.max_total_views)}</span>
|
||||
<span>{top.live_hours}h / {top.session_count}场</span>
|
||||
{(top.best_hours || []).slice(0, 2).map((h) => (
|
||||
<span key={h.hour} className="rounded-md border border-white/10 bg-black/30 px-1.5 py-0.5 text-amber-100">
|
||||
{h.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-4 text-sm text-slate-500">窗口内还没有可排名的抖音源 Studio 样本。开播并让 Neko 采样后会出现。</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{error ? <div className="mb-4 rounded-2xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-100">{error}</div> : null}
|
||||
{loading && !data ? (
|
||||
<div className="flex justify-center gap-2 py-20 text-slate-400">
|
||||
<Loader2 className="h-5 w-5 animate-spin" /> 汇总抖音源表现…
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{data ? (
|
||||
<>
|
||||
<div className="mb-4 grid grid-cols-2 gap-2 md:grid-cols-5">
|
||||
<Kpi label="已测抖音源" value={fmtNum(measured.length)} tone="rose" />
|
||||
<Kpi label="池内未测" value={fmtNum(unmeasured.length)} tone="slate" />
|
||||
<Kpi label="场次" value={fmtNum(ov?.session_count)} />
|
||||
<Kpi label="峰值同时" value={fmtNum(ov?.peak_viewers)} tone="amber" />
|
||||
<Kpi label="均值同时" value={fmtNum(ov?.avg_viewers)} tone="teal" />
|
||||
</div>
|
||||
|
||||
<div className="mb-4 flex flex-wrap gap-1 rounded-2xl border border-white/10 bg-black/30 p-1">
|
||||
{(
|
||||
[
|
||||
["sources", "抖音源排名", measured.length],
|
||||
["slots", "最佳时段", (data.planning_slots || []).length],
|
||||
["sessions", "场次", (data.studio_sessions || []).length],
|
||||
["daily", "每日", (data.daily || []).length],
|
||||
] as const
|
||||
).map(([id, label, count]) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
onClick={() => setTab(id)}
|
||||
className={`rounded-xl px-3 py-2 text-xs ${tab === id ? "bg-white/10 text-white" : "text-slate-400 hover:text-slate-200"}`}
|
||||
>
|
||||
{label}
|
||||
<span className="ml-1 font-mono text-[10px] text-slate-500">{count}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === "sources" ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-[11px] text-slate-500">按「排源分数」排序:均值同时 × 场次可信度 + 峰值 + 总观看 + 直播时长。展开看每源 24h 热力与建议开播点。</p>
|
||||
{measured.map((src) => {
|
||||
const open = openRoom === src.room_id;
|
||||
return (
|
||||
<div key={src.room_id} className={`overflow-hidden rounded-3xl border ${open ? "border-rose-400/35 bg-rose-500/[0.07]" : "border-white/10 bg-black/30"}`}>
|
||||
<button type="button" onClick={() => setOpenRoom(open ? "" : src.room_id)} className="flex w-full gap-3 p-3 text-left md:p-4">
|
||||
<div className="relative h-20 w-20 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-black/50 md:h-24 md:w-24">
|
||||
<Cover src={src.cover_url} name={src.anchor_name} />
|
||||
<span className="absolute left-1 top-1 rounded-md bg-black/70 px-1.5 py-0.5 font-mono text-[10px] text-amber-100">#{src.rank}</span>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="truncate text-base font-semibold text-white">{src.anchor_name || src.room_id}</p>
|
||||
{src.in_featured ? <span className="rounded border border-amber-400/30 bg-amber-500/15 px-1.5 text-[10px] text-amber-100">精选</span> : null}
|
||||
{src.in_pool ? <span className="rounded border border-white/10 bg-white/5 px-1.5 text-[10px] text-slate-400">池</span> : null}
|
||||
</div>
|
||||
<a
|
||||
href={src.douyin_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="mt-0.5 inline-flex max-w-full items-center gap-1 truncate font-mono text-[11px] text-rose-200/90 hover:underline"
|
||||
>
|
||||
{src.douyin_url?.replace(/^https?:\/\//, "")}
|
||||
<ExternalLink className="h-3 w-3 shrink-0" />
|
||||
</a>
|
||||
<p className="mt-1.5 line-clamp-2 text-[12px] text-slate-400">{src.planning_tip}</p>
|
||||
<div className="mt-2 flex flex-wrap gap-2 font-mono text-[11px]">
|
||||
<span className="rounded-md bg-black/40 px-1.5 py-0.5 text-rose-100">均 {fmtNum(src.avg_viewers)}</span>
|
||||
<span className="rounded-md bg-black/40 px-1.5 py-0.5 text-amber-100">峰 {fmtNum(src.peak_viewers)}</span>
|
||||
<span className="rounded-md bg-black/40 px-1.5 py-0.5 text-violet-100">总观 {fmtNum(src.max_total_views)}</span>
|
||||
<span className="rounded-md bg-black/40 px-1.5 py-0.5 text-slate-300">{src.live_hours}h · {src.session_count}场</span>
|
||||
<span className="rounded-md bg-black/40 px-1.5 py-0.5 text-teal-100">score {src.score}</span>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{(src.best_hours || []).slice(0, 3).map((h) => (
|
||||
<span key={h.hour} className="rounded-lg border border-amber-400/20 bg-amber-500/10 px-2 py-0.5 text-[10px] text-amber-50">
|
||||
{h.label} · 峰{fmtNum(h.peak_viewers)}
|
||||
</span>
|
||||
))}
|
||||
{(src.best_weekdays || []).slice(0, 2).map((w) => (
|
||||
<span key={w.weekday} className="rounded-lg border border-white/10 bg-white/5 px-2 py-0.5 text-[10px] text-slate-300">
|
||||
{w.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-1 text-slate-500">{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}</div>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="border-t border-white/5 px-3 py-4 md:px-4">
|
||||
<p className="mb-2 text-[10px] uppercase tracking-wider text-slate-500">该源在本频道 · 北京 24 小时热力(直播分钟 / 峰值)</p>
|
||||
<div className="grid grid-cols-6 gap-1 sm:grid-cols-8 md:grid-cols-12">
|
||||
{(src.hour_heatmap || []).map((h) => {
|
||||
const intensity = Number(h.live_minutes || 0) / maxHour;
|
||||
return (
|
||||
<div key={h.hour} className="relative overflow-hidden rounded-xl border border-white/5 bg-black/40 p-1.5" title={`${h.hour}:00 峰${fmtNum(h.peak_viewers)}`}>
|
||||
<div className="absolute inset-0 bg-rose-500/35" style={{ opacity: Math.max(0.03, intensity * 0.9) }} />
|
||||
<p className="relative font-mono text-[9px] text-slate-400">{String(h.hour).padStart(2, "0")}</p>
|
||||
<p className="relative font-mono text-[10px] text-slate-100">{Math.round(h.live_minutes)}′</p>
|
||||
<p className="relative text-[8px] text-slate-500">{fmtNum(h.peak_viewers)}</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{(src.stream_titles || []).length ? (
|
||||
<p className="mt-3 text-[11px] text-slate-500">标题采样:{(src.stream_titles || []).join(" · ")}</p>
|
||||
) : null}
|
||||
{src.last_started_at ? (
|
||||
<p className="mt-1 text-[11px] text-slate-600">最近关联 {fmtTs(src.last_started_at)}</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{unmeasured.length ? (
|
||||
<div className="pt-4">
|
||||
<p className="mb-2 text-xs text-slate-400">池/精选中尚未测到 Studio 数据的抖音源({unmeasured.length})</p>
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{unmeasured.map((src) => (
|
||||
<div key={src.room_id} className="flex gap-3 rounded-2xl border border-dashed border-white/10 bg-black/20 p-3">
|
||||
<div className="h-14 w-14 shrink-0 overflow-hidden rounded-xl border border-white/10">
|
||||
<Cover src={src.cover_url} name={src.anchor_name} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm text-slate-200">{src.anchor_name || src.room_id}</p>
|
||||
<a href={src.douyin_url} target="_blank" rel="noreferrer" className="truncate font-mono text-[10px] text-slate-500 hover:text-rose-200">
|
||||
{src.room_id}
|
||||
</a>
|
||||
<p className="mt-1 text-[10px] text-slate-600">未测 · 开播采样后进入排名</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{!measured.length && !unmeasured.length ? (
|
||||
<div className="rounded-3xl border border-dashed border-white/10 py-16 text-center text-sm text-slate-500">暂无抖音源关联数据</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "slots" ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-[11px] text-slate-500">按北京小时汇总:该时段历史上哪几个抖音源在本频道峰值最高 — 用来排时间段推流。</p>
|
||||
{(data.planning_slots || []).map((slot) => (
|
||||
<div key={slot.hour} className="rounded-3xl border border-white/10 bg-black/30 p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock3 className="h-4 w-4 text-amber-300" />
|
||||
<span className="font-mono text-lg text-white">
|
||||
{String(slot.hour).padStart(2, "0")}:00–{String((slot.hour + 1) % 24).padStart(2, "0")}:00
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-500">北京</span>
|
||||
</div>
|
||||
<span className="font-mono text-xs text-amber-100">时段峰 {fmtNum(slot.best_peak)}</span>
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{(slot.sources || []).map((s, i) => (
|
||||
<div key={`${s.room_id}-${i}`} className="flex items-center gap-3 rounded-2xl border border-white/5 bg-white/[0.03] p-2.5">
|
||||
<div className="h-12 w-12 overflow-hidden rounded-xl border border-white/10">
|
||||
<Cover src={s.cover_url} name={s.anchor_name} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm text-slate-100">{s.anchor_name || s.room_id}</p>
|
||||
<p className="font-mono text-[10px] text-slate-500">{s.room_id}</p>
|
||||
<p className="mt-0.5 font-mono text-[11px] text-amber-100">峰 {fmtNum(s.peak_viewers)} · score {fmtNum(s.score as any)}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!data.planning_slots?.length ? <p className="py-12 text-center text-sm text-slate-500">暂无时段建议</p> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "sessions" ? (
|
||||
<div className="space-y-2">
|
||||
{(data.studio_sessions || []).map((s: any) => {
|
||||
const open = openSession === s.id;
|
||||
return (
|
||||
<div key={s.id} className="rounded-2xl border border-white/10 bg-black/25">
|
||||
<button type="button" className="flex w-full items-start gap-2 px-3 py-3 text-left" onClick={() => setOpenSession(open ? "" : s.id)}>
|
||||
{open ? <ChevronDown className="mt-0.5 h-4 w-4 text-slate-500" /> : <ChevronRight className="mt-0.5 h-4 w-4 text-slate-500" />}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-slate-100">{(s.anchors || [])[0] || (s.source_rooms || [])[0] || "场次"}</p>
|
||||
<p className="text-[11px] text-slate-500">
|
||||
{fmtTs(s.started_at)} · {fmtDuration(s.duration_sec)} · 房 {(s.source_rooms || []).join(",") || "—"}
|
||||
</p>
|
||||
<p className="mt-1 font-mono text-[11px] text-slate-300">
|
||||
均 {fmtNum(s.avg_viewers)} · 峰 {fmtNum(s.peak_viewers)} · 总观 {fmtNum(s.max_total_views)}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="border-t border-white/5 px-3 py-3">
|
||||
<StudioViewerChart
|
||||
reports={s.minute_reports || []}
|
||||
currentViewers={s.end_viewers}
|
||||
currentTotalViews={s.max_total_views}
|
||||
currentDuration={s.live_duration}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "daily" ? (
|
||||
<div className="overflow-x-auto rounded-3xl border border-white/10 bg-black/25">
|
||||
<table className="min-w-full text-left text-xs">
|
||||
<thead className="text-[10px] uppercase text-slate-500">
|
||||
<tr>
|
||||
<th className="px-4 py-2">日期</th>
|
||||
<th className="px-3 py-2">场次</th>
|
||||
<th className="px-3 py-2">时长</th>
|
||||
<th className="px-3 py-2">峰</th>
|
||||
<th className="px-3 py-2">均</th>
|
||||
<th className="px-3 py-2">总观</th>
|
||||
<th className="px-3 py-2">源</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(data.daily || []).map((d: any) => (
|
||||
<tr key={d.date} className="border-t border-white/5">
|
||||
<td className="px-4 py-2 font-mono">{d.date}</td>
|
||||
<td className="px-3 py-2 font-mono">{d.session_count}</td>
|
||||
<td className="px-3 py-2 font-mono">{d.live_hours}h</td>
|
||||
<td className="px-3 py-2 font-mono">{fmtNum(d.peak_viewers)}</td>
|
||||
<td className="px-3 py-2 font-mono">{fmtNum(d.avg_viewers)}</td>
|
||||
<td className="px-3 py-2 font-mono">{fmtNum(d.max_total_views)}</td>
|
||||
<td className="max-w-[14rem] truncate px-3 py-2 text-slate-400">{(d.anchors || []).join("、") || (d.rooms || []).join(",")}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
240
frontend/src/app/youtube/analytics/page.tsx
Normal file
240
frontend/src/app/youtube/analytics/page.tsx
Normal file
@ -0,0 +1,240 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { ExternalLink, Loader2, RefreshCw, Sparkles, Trophy } from "lucide-react";
|
||||
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { fetchJson, fmtTs } from "@/lib/api";
|
||||
|
||||
type Rec = {
|
||||
rank: number;
|
||||
room_id: string;
|
||||
anchor_name?: string;
|
||||
cover_url?: string;
|
||||
douyin_url?: string;
|
||||
group_id?: string;
|
||||
channel_name?: string;
|
||||
youtube_channel_id?: string;
|
||||
score?: number;
|
||||
avg_viewers?: number | null;
|
||||
peak_viewers?: number | null;
|
||||
max_total_views?: number | null;
|
||||
live_hours?: number;
|
||||
best_hours?: Array<{ label: string; peak_viewers?: number | null }>;
|
||||
planning_tip?: string;
|
||||
};
|
||||
|
||||
type RoomRow = {
|
||||
room_id: string;
|
||||
anchor_name?: string;
|
||||
cover_url?: string;
|
||||
douyin_url?: string;
|
||||
best_channel?: Rec & { channel_name?: string; group_id?: string };
|
||||
channels: Array<{
|
||||
group_id?: string;
|
||||
channel_name?: string;
|
||||
score?: number;
|
||||
avg_viewers?: number | null;
|
||||
peak_viewers?: number | null;
|
||||
best_hours?: Array<{ label: string }>;
|
||||
}>;
|
||||
};
|
||||
|
||||
function fmtNum(n: number | null | undefined): string {
|
||||
if (n == null || !Number.isFinite(Number(n))) return "—";
|
||||
return Number(n).toLocaleString();
|
||||
}
|
||||
|
||||
function Cover({ src, name }: { src?: string; name?: string }) {
|
||||
const [broken, setBroken] = useState(false);
|
||||
if (!src || broken) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-amber-500/20 to-slate-900 text-base font-semibold text-amber-100/80">
|
||||
{(name || "?").slice(0, 1)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={src} alt={name || ""} className="h-full w-full object-cover" onError={() => setBroken(true)} />
|
||||
);
|
||||
}
|
||||
|
||||
export default function FleetSourceAnalyticsPage() {
|
||||
const [days, setDays] = useState(30);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [recs, setRecs] = useState<Rec[]>([]);
|
||||
const [rooms, setRooms] = useState<RoomRow[]>([]);
|
||||
const [windowMeta, setWindowMeta] = useState<Record<string, any> | null>(null);
|
||||
const [tab, setTab] = useState<"pairs" | "rooms">("pairs");
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const data = (await fetchJson(`/api/youtube/assign/analytics/sources?days=${days}`)) as any;
|
||||
setRecs(data.recommendations || []);
|
||||
setRooms(data.rooms || []);
|
||||
setWindowMeta(data.window || null);
|
||||
} catch (e: any) {
|
||||
setError(String(e?.message || e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [days]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
return (
|
||||
<Shell>
|
||||
<div className="relative mx-auto max-w-7xl px-3 pb-20 pt-4 md:px-6">
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 -z-10 h-[420px]">
|
||||
<div className="absolute left-10 top-10 h-64 w-64 rounded-full bg-amber-500/15 blur-3xl" />
|
||||
<div className="absolute right-0 top-0 h-72 w-72 rounded-full bg-rose-500/10 blur-3xl" />
|
||||
</div>
|
||||
|
||||
<div className="mb-5 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="mb-2 inline-flex items-center gap-1.5 rounded-full border border-amber-400/25 bg-amber-500/10 px-2.5 py-1 text-[10px] uppercase tracking-[0.16em] text-amber-100">
|
||||
<Sparkles className="h-3 w-3" /> Fleet Scheduling Matrix
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-white md:text-3xl">抖音源 × YouTube 频道</h1>
|
||||
<p className="mt-2 max-w-2xl text-sm text-slate-400">
|
||||
看清「哪个直播间」在「哪个频道」最好、该在什么北京时段开 — 用来安排 YouTube 直播选源与排班。
|
||||
</p>
|
||||
{windowMeta ? (
|
||||
<p className="mt-1 text-[11px] text-slate-600">
|
||||
近 {windowMeta.days} 天 · {windowMeta.room_count} 源 · {windowMeta.pair_count} 对关联 · {windowMeta.group_count} 频道 ·{" "}
|
||||
{windowMeta.generated_at ? fmtTs(windowMeta.generated_at) : ""}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="inline-flex rounded-xl border border-white/10 bg-black/30 p-0.5">
|
||||
{[14, 30, 60].map((d) => (
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
onClick={() => setDays(d)}
|
||||
className={`rounded-lg px-2.5 py-1 text-[11px] ${days === d ? "bg-amber-500/25 text-amber-50" : "text-slate-400"}`}
|
||||
>
|
||||
{d}天
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="button" onClick={() => void load()} className="rounded-xl border border-white/10 px-2.5 py-1.5 text-slate-300">
|
||||
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4 flex gap-1 rounded-2xl border border-white/10 bg-black/30 p-1">
|
||||
<button type="button" onClick={() => setTab("pairs")} className={`rounded-xl px-3 py-2 text-xs ${tab === "pairs" ? "bg-white/10 text-white" : "text-slate-400"}`}>
|
||||
最佳配对(源→频道)
|
||||
</button>
|
||||
<button type="button" onClick={() => setTab("rooms")} className={`rounded-xl px-3 py-2 text-xs ${tab === "rooms" ? "bg-white/10 text-white" : "text-slate-400"}`}>
|
||||
按抖音源看频道
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? <div className="mb-4 rounded-2xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-100">{error}</div> : null}
|
||||
{loading && !recs.length && !rooms.length ? (
|
||||
<div className="flex justify-center gap-2 py-20 text-slate-400">
|
||||
<Loader2 className="h-5 w-5 animate-spin" /> 计算全站矩阵…
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "pairs" ? (
|
||||
<div className="space-y-3">
|
||||
{recs.map((r) => (
|
||||
<div key={`${r.room_id}-${r.group_id}-${r.rank}`} className="flex flex-col gap-3 rounded-3xl border border-white/10 bg-black/30 p-3 md:flex-row md:items-center md:p-4">
|
||||
<div className="flex items-center gap-3 md:w-[22rem]">
|
||||
<div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-2xl border border-white/10">
|
||||
<Cover src={r.cover_url} name={r.anchor_name} />
|
||||
<span className="absolute left-1 top-1 rounded bg-black/70 px-1 font-mono text-[9px] text-amber-100">#{r.rank}</span>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium text-white">{r.anchor_name || r.room_id}</p>
|
||||
<a href={r.douyin_url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 truncate font-mono text-[10px] text-rose-200 hover:underline">
|
||||
live.douyin.com/{r.room_id}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden text-slate-600 md:block">→</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Trophy className="h-3.5 w-3.5 text-amber-300" />
|
||||
{r.group_id ? (
|
||||
<Link href={`/youtube/analytics/${encodeURIComponent(r.group_id)}`} className="text-sm font-medium text-amber-50 hover:underline">
|
||||
{r.channel_name || "频道"}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-sm text-amber-50">{r.channel_name}</span>
|
||||
)}
|
||||
<span className="font-mono text-[10px] text-slate-500">score {fmtNum(r.score)}</span>
|
||||
</div>
|
||||
<p className="mt-1 text-[12px] text-slate-400">{r.planning_tip}</p>
|
||||
<div className="mt-2 flex flex-wrap gap-2 font-mono text-[11px] text-slate-300">
|
||||
<span>均 {fmtNum(r.avg_viewers)}</span>
|
||||
<span>峰 {fmtNum(r.peak_viewers)}</span>
|
||||
<span>总观 {fmtNum(r.max_total_views)}</span>
|
||||
<span>{r.live_hours}h</span>
|
||||
{(r.best_hours || []).slice(0, 2).map((h, i) => (
|
||||
<span key={i} className="rounded border border-amber-400/20 bg-amber-500/10 px-1.5 text-amber-50">
|
||||
{h.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!recs.length && !loading ? <p className="py-16 text-center text-sm text-slate-500">暂无配对数据</p> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{tab === "rooms" ? (
|
||||
<div className="grid gap-3 lg:grid-cols-2">
|
||||
{rooms.map((room) => (
|
||||
<div key={room.room_id} className="rounded-3xl border border-white/10 bg-black/30 p-4">
|
||||
<div className="flex gap-3">
|
||||
<div className="h-16 w-16 shrink-0 overflow-hidden rounded-2xl border border-white/10">
|
||||
<Cover src={room.cover_url} name={room.anchor_name} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-base font-medium text-white">{room.anchor_name || room.room_id}</p>
|
||||
<a href={room.douyin_url} target="_blank" rel="noreferrer" className="font-mono text-[10px] text-rose-200 hover:underline">
|
||||
{room.room_id}
|
||||
</a>
|
||||
{room.best_channel ? (
|
||||
<p className="mt-1 text-[11px] text-amber-100/90">
|
||||
最佳频道:{room.best_channel.channel_name}(score {fmtNum(room.best_channel.score)})
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 space-y-1.5">
|
||||
{(room.channels || []).map((ch, i) => (
|
||||
<div key={`${ch.group_id}-${i}`} className="flex items-center justify-between gap-2 rounded-xl border border-white/5 bg-white/[0.03] px-2.5 py-2 text-[11px]">
|
||||
<Link href={ch.group_id ? `/youtube/analytics/${encodeURIComponent(ch.group_id)}` : "#"} className="truncate text-slate-200 hover:text-amber-100">
|
||||
{ch.channel_name || ch.group_id}
|
||||
</Link>
|
||||
<span className="shrink-0 font-mono text-slate-400">
|
||||
均{fmtNum(ch.avg_viewers)} · 峰{fmtNum(ch.peak_viewers)} · {fmtNum(ch.score)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!rooms.length && !loading ? <p className="col-span-full py-16 text-center text-sm text-slate-500">暂无源数据</p> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
364
frontend/src/app/youtube/keys/page.tsx
Normal file
364
frontend/src/app/youtube/keys/page.tsx
Normal file
@ -0,0 +1,364 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Copy,
|
||||
Download,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Save,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Shell } from "@/components/Shell";
|
||||
import { useConfirm } from "@/components/ConfirmDialog";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import { fetchJson } from "@/lib/api";
|
||||
|
||||
type KeyItem = {
|
||||
id: string;
|
||||
name?: string;
|
||||
youtube_channel_id?: string;
|
||||
channel_pk?: string;
|
||||
assign_group_id?: string;
|
||||
stream_key?: string;
|
||||
stream_key_masked?: string;
|
||||
has_stream_key?: boolean;
|
||||
note?: string;
|
||||
sort_order?: number;
|
||||
updated_at?: number;
|
||||
};
|
||||
|
||||
type Draft = {
|
||||
id: string;
|
||||
name: string;
|
||||
youtube_channel_id: string;
|
||||
channel_pk: string;
|
||||
assign_group_id: string;
|
||||
stream_key: string;
|
||||
note: string;
|
||||
};
|
||||
|
||||
const emptyDraft = (): Draft => ({
|
||||
id: "",
|
||||
name: "",
|
||||
youtube_channel_id: "",
|
||||
channel_pk: "",
|
||||
assign_group_id: "",
|
||||
stream_key: "",
|
||||
note: "",
|
||||
});
|
||||
|
||||
export default function YoutubeStreamKeysPage() {
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
const [items, setItems] = useState<KeyItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [draft, setDraft] = useState<Draft>(emptyDraft());
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = (await fetchJson("/api/youtube/stream-keys")) as {
|
||||
items?: KeyItem[];
|
||||
};
|
||||
setItems(data.items || []);
|
||||
} catch (e: any) {
|
||||
toast.push(String(e?.message || e), "err");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const startEdit = (it: KeyItem) => {
|
||||
setEditingId(it.id);
|
||||
setDraft({
|
||||
id: it.id,
|
||||
name: it.name || "",
|
||||
youtube_channel_id: it.youtube_channel_id || "",
|
||||
channel_pk: it.channel_pk || "",
|
||||
assign_group_id: it.assign_group_id || "",
|
||||
stream_key: it.stream_key || "",
|
||||
note: it.note || "",
|
||||
});
|
||||
};
|
||||
|
||||
const startNew = () => {
|
||||
setEditingId("__new__");
|
||||
setDraft(emptyDraft());
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingId(null);
|
||||
setDraft(emptyDraft());
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!draft.name.trim() && !draft.youtube_channel_id.trim()) {
|
||||
toast.push("请填写频道名称或 YouTube Channel ID", "err");
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await fetchJson("/api/youtube/stream-keys", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
id: draft.id || undefined,
|
||||
name: draft.name,
|
||||
youtube_channel_id: draft.youtube_channel_id,
|
||||
channel_pk: draft.channel_pk,
|
||||
assign_group_id: draft.assign_group_id,
|
||||
stream_key: draft.stream_key,
|
||||
note: draft.note,
|
||||
}),
|
||||
});
|
||||
toast.push("已保存到 Key 表(不影响推流/Neko)", "ok");
|
||||
cancelEdit();
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
toast.push(String(e?.message || e), "err");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: string, name: string) => {
|
||||
const ok = await confirm({
|
||||
title: "删除 Key 登记?",
|
||||
message: `仅删除 Key 表中的「${name}」,不会改分配频道、不会动 Neko。`,
|
||||
confirmLabel: "删除",
|
||||
destructive: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await fetchJson(`/api/youtube/stream-keys/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||
toast.push("已删除", "ok");
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
toast.push(String(e?.message || e), "err");
|
||||
}
|
||||
};
|
||||
|
||||
const importAssign = async () => {
|
||||
const ok = await confirm({
|
||||
title: "从分配频道导入?",
|
||||
message: "把当前 /youtube 分配频道里的名称、UC、直播 Key 快照进本表。只写 Key 表,不改 Neko、不改推流状态。",
|
||||
confirmLabel: "导入快照",
|
||||
});
|
||||
if (!ok) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const r = (await fetchJson("/api/youtube/stream-keys/import-assign", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ replace: false }),
|
||||
})) as { inserted?: number; updated?: number; total?: number };
|
||||
toast.push(`导入完成:新增 ${r.inserted ?? 0} · 更新 ${r.updated ?? 0} · 共 ${r.total ?? 0}`, "ok");
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
toast.push(String(e?.message || e), "err");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copyText = async (text: string, label: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
toast.push(`已复制${label}`, "ok");
|
||||
} catch {
|
||||
toast.push("复制失败", "err");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Shell>
|
||||
<div className="relative mx-auto max-w-5xl px-3 pb-20 pt-4 md:px-6">
|
||||
<div className="mb-5 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||
<Link href="/youtube" className="inline-flex items-center gap-1 hover:text-teal-200">
|
||||
<ArrowLeft className="h-3.5 w-3.5" />
|
||||
直播工作台
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<span>Key 表</span>
|
||||
</div>
|
||||
<h1 className="mt-1 flex items-center gap-2 text-xl font-semibold text-slate-50">
|
||||
<KeyRound className="h-5 w-5 text-amber-300" />
|
||||
频道 ↔ 直播 Key
|
||||
</h1>
|
||||
<p className="mt-1 text-xs text-slate-400">
|
||||
独立登记表,用于找回对应关系。编辑本页不会启动/停止 Neko,也不会改正在推流的分配配置。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void importAssign()}
|
||||
disabled={saving}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-teal-400/30 bg-teal-500/10 px-3 py-1.5 text-xs text-teal-50 hover:bg-teal-500/20 disabled:opacity-50"
|
||||
>
|
||||
<Download className="h-3.5 w-3.5" />
|
||||
从分配导入
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void load()}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-slate-600 bg-slate-900/60 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-800"
|
||||
>
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
刷新
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={startNew}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-amber-400/35 bg-amber-500/15 px-3 py-1.5 text-xs text-amber-50 hover:bg-amber-500/25"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
新建
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editingId ? (
|
||||
<section className="mb-5 rounded-2xl border border-amber-400/25 bg-amber-500/[0.07] p-4">
|
||||
<h2 className="mb-3 text-sm font-medium text-amber-50">
|
||||
{editingId === "__new__" ? "新建登记" : "编辑登记"}
|
||||
</h2>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="text-xs text-slate-300">
|
||||
频道名称
|
||||
<input
|
||||
className="mt-1 w-full rounded-lg border border-slate-700 bg-black/40 px-3 py-2 text-sm text-slate-100"
|
||||
value={draft.name}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-300">
|
||||
YouTube Channel ID (UC…)
|
||||
<input
|
||||
className="mt-1 w-full rounded-lg border border-slate-700 bg-black/40 px-3 py-2 font-mono text-sm text-slate-100"
|
||||
value={draft.youtube_channel_id}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, youtube_channel_id: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-300 md:col-span-2">
|
||||
直播 Stream Key
|
||||
<input
|
||||
className="mt-1 w-full rounded-lg border border-slate-700 bg-black/40 px-3 py-2 font-mono text-sm text-slate-100"
|
||||
value={draft.stream_key}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, stream_key: e.target.value }))}
|
||||
placeholder="xxxx-xxxx-xxxx-xxxx-xxxx"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-300">
|
||||
备注
|
||||
<input
|
||||
className="mt-1 w-full rounded-lg border border-slate-700 bg-black/40 px-3 py-2 text-sm text-slate-100"
|
||||
value={draft.note}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-slate-300">
|
||||
关联分配组 ID(可选)
|
||||
<input
|
||||
className="mt-1 w-full rounded-lg border border-slate-700 bg-black/40 px-3 py-2 font-mono text-xs text-slate-100"
|
||||
value={draft.assign_group_id}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, assign_group_id: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-4 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
onClick={() => void save()}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-emerald-400/35 bg-emerald-500/15 px-3 py-1.5 text-xs text-emerald-50 hover:bg-emerald-500/25 disabled:opacity-50"
|
||||
>
|
||||
{saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
|
||||
保存
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={cancelEdit}
|
||||
className="rounded-xl border border-slate-600 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-800"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-slate-400">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
加载中…
|
||||
</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="rounded-2xl border border-dashed border-slate-700 bg-slate-950/40 px-4 py-10 text-center text-sm text-slate-400">
|
||||
还没有登记。点「从分配导入」把当前直播 Key 快照进来,或点「新建」。
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{items.map((it) => {
|
||||
const keyText = it.stream_key || it.stream_key_masked || "";
|
||||
return (
|
||||
<div
|
||||
key={it.id}
|
||||
className="rounded-2xl border border-slate-700/80 bg-slate-950/50 px-4 py-3"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-slate-100">{it.name || "未命名"}</div>
|
||||
<div className="mt-0.5 font-mono text-[11px] text-slate-400">
|
||||
{it.youtube_channel_id || "—"}
|
||||
</div>
|
||||
{it.note ? <div className="mt-1 text-[11px] text-slate-500">{it.note}</div> : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={!it.stream_key}
|
||||
onClick={() => void copyText(it.stream_key || "", " Key")}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-teal-400/30 bg-teal-500/10 px-2 py-1 text-[11px] text-teal-50 hover:bg-teal-500/20 disabled:opacity-40"
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
复制 Key
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startEdit(it)}
|
||||
className="rounded-lg border border-amber-400/30 bg-amber-500/10 px-2 py-1 text-[11px] text-amber-50 hover:bg-amber-500/20"
|
||||
>
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void remove(it.id, it.name || it.id)}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-rose-400/30 bg-rose-500/10 px-2 py-1 text-[11px] text-rose-100 hover:bg-rose-500/20"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 break-all font-mono text-xs text-teal-100/90 select-all">{keyText || "—"}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@ -78,7 +78,6 @@ export default function YouTubePage() {
|
||||
const [videos, setVideos] = useState<YtVideo[]>([]);
|
||||
const [playlists, setPlaylists] = useState<any[]>([]);
|
||||
const [edit, setEdit] = useState<YtVideo | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [msg, setMsg] = useState("");
|
||||
|
||||
@ -102,7 +101,6 @@ export default function YouTubePage() {
|
||||
|
||||
const loadManage = useCallback(async () => {
|
||||
if (!channelPk) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const [d, v, p] = await Promise.all([
|
||||
@ -117,8 +115,6 @@ export default function YouTubePage() {
|
||||
setError((e as Error).message);
|
||||
setDash(null);
|
||||
setVideos([]);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [channelPk]);
|
||||
|
||||
@ -146,7 +142,6 @@ export default function YouTubePage() {
|
||||
|
||||
async function saveVideo() {
|
||||
if (!edit || !channelPk) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setMsg("");
|
||||
try {
|
||||
@ -165,14 +160,11 @@ export default function YouTubePage() {
|
||||
await loadManage();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function setPrivacy(videoId: string, privacy: string) {
|
||||
if (!channelPk) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, {
|
||||
method: "PATCH",
|
||||
@ -182,8 +174,6 @@ export default function YouTubePage() {
|
||||
await loadManage();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -196,7 +186,6 @@ export default function YouTubePage() {
|
||||
destructive: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/manage/${channelPk}/videos/${videoId}`, { method: "DELETE" });
|
||||
toast.push("视频已删除", "ok");
|
||||
@ -204,8 +193,6 @@ export default function YouTubePage() {
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -218,7 +205,6 @@ export default function YouTubePage() {
|
||||
}
|
||||
|
||||
async function runProbe() {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setMsg("");
|
||||
setResult(null);
|
||||
@ -233,8 +219,6 @@ export default function YouTubePage() {
|
||||
setResult(data);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -391,7 +375,7 @@ export default function YouTubePage() {
|
||||
onClick={() => void loadManage()}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
|
||||
>
|
||||
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
@ -588,7 +572,6 @@ export default function YouTubePage() {
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveVideo()}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
|
||||
>
|
||||
@ -669,11 +652,10 @@ export default function YouTubePage() {
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void runProbe()}
|
||||
className="inline-flex items-center gap-1 rounded-xl bg-[#ff2d55] px-4 py-2 text-sm text-white"
|
||||
>
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
|
||||
<Search className="h-4 w-4" />
|
||||
探测
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@ -191,7 +191,6 @@ export default function YtLongPage() {
|
||||
const [upcoming, setUpcoming] = useState<Job[]>([]);
|
||||
const [form, setForm] = useState({ ...emptyForm });
|
||||
const [editId, setEditId] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [togglingId, setTogglingId] = useState("");
|
||||
const [msg, setMsg] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
@ -203,10 +202,11 @@ export default function YtLongPage() {
|
||||
const [loadingMoreJobs, setLoadingMoreJobs] = useState(false);
|
||||
|
||||
const load = useCallback(
|
||||
async (opts?: { appendJobs?: boolean; jobOffset?: number }) => {
|
||||
async (opts?: { appendJobs?: boolean; jobOffset?: number; soft?: boolean }) => {
|
||||
const appendJobs = Boolean(opts?.appendJobs);
|
||||
const soft = Boolean(opts?.soft);
|
||||
if (appendJobs) setLoadingMoreJobs(true);
|
||||
else setLoading(true);
|
||||
else if (!soft) setLoading(true);
|
||||
try {
|
||||
const off = appendJobs ? Number(opts?.jobOffset ?? 0) : 0;
|
||||
const jobQs = new URLSearchParams({ limit: String(JOB_PAGE), offset: String(off) });
|
||||
@ -381,16 +381,16 @@ export default function YtLongPage() {
|
||||
const totals = useMemo(() => {
|
||||
const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
|
||||
const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
|
||||
const used = displayChannels.reduce((s, c) => s + (c.used || 0), 0);
|
||||
// Progress / 缺口按「已上传」计(与 Shorts 一致);used 含排队占坑,仅作内部参考。
|
||||
const used = uploaded;
|
||||
const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 0), 0);
|
||||
const gap = displayChannels
|
||||
.filter((c) => c.enabled !== false)
|
||||
.reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 0) - (c.used || 0))), 0);
|
||||
.reduce((s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), 0);
|
||||
return { uploaded, scheduled, used, cap, gap };
|
||||
}, [displayChannels]);
|
||||
|
||||
async function toggle(enabled: boolean) {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
@ -399,13 +399,10 @@ export default function YtLongPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function importFromShorts() {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
@ -416,13 +413,10 @@ export default function YtLongPage() {
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveChannel() {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
@ -449,8 +443,6 @@ export default function YtLongPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -505,7 +497,10 @@ export default function YtLongPage() {
|
||||
} else {
|
||||
toast.push(turningOn ? `已启用「${ch.name}」` : `已停用「${ch.name}」`, "ok");
|
||||
}
|
||||
await load();
|
||||
setChannels((prev) =>
|
||||
prev.map((c) => (c.id === ch.id ? { ...c, enabled: turningOn } : c)),
|
||||
);
|
||||
await load({ soft: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -551,8 +546,8 @@ export default function YtLongPage() {
|
||||
{[
|
||||
[
|
||||
"YouTube 上传",
|
||||
`${status?.upload_used ?? status?.quota_used ?? 0} / ${status?.daily_max ?? "—"}`,
|
||||
beijingWindow ? `${beijingWindow} · 长视频上传上限` : "长视频上传日上限(14×3)",
|
||||
`${totals.uploaded} / ${totals.cap || status?.daily_max || "—"}`,
|
||||
beijingWindow ? `${beijingWindow} · 已上传 / 各频道日上限合计` : "进度按已上传(不含排队占坑)",
|
||||
],
|
||||
[
|
||||
"母片录制",
|
||||
@ -568,16 +563,24 @@ export default function YtLongPage() {
|
||||
[
|
||||
"成片规格",
|
||||
`${Math.round(Number(settings.yt_long_min_sec || 180) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 480) / 60)}分`,
|
||||
"9:16 竖屏 · cascade 切短片",
|
||||
status?.api_quota_limited
|
||||
? `9:16 · API 限流中,每频道 cap ${status?.channel_daily_max_effective ?? 4}`
|
||||
: "9:16 竖屏 · cascade 切短片",
|
||||
],
|
||||
].map(([label, value, hint]) => (
|
||||
<div key={label as string} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">
|
||||
<div className="text-xs text-slate-500">{label}</div>
|
||||
<div className="mt-1 font-display text-2xl text-white">{value}</div>
|
||||
<div className="mt-1 text-[11px] text-slate-500">{hint}</div>
|
||||
].map(([title, value, sub]) => (
|
||||
<div key={String(title)} className="rounded-2xl border border-white/10 bg-black/30 px-4 py-3">
|
||||
<p className="text-[11px] uppercase tracking-wide text-slate-500">{title}</p>
|
||||
<p className="mt-1 text-xl font-semibold text-slate-100">{value}</p>
|
||||
<p className="mt-1 text-[11px] text-slate-500">{sub}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{status?.api_quota_limited ? (
|
||||
<div className="mb-4 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">
|
||||
YouTube 上传接口今日限流(429)。长视频每频道上限已软降为{" "}
|
||||
{status?.channel_daily_max_effective ?? 4};Shorts/长视频自动上传对冷静中的 Client 会跳过,手动上传不拦。
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<DailyQuotaGlobalCard
|
||||
accent="amber"
|
||||
@ -589,7 +592,7 @@ export default function YtLongPage() {
|
||||
maxLo={0}
|
||||
maxHi={50}
|
||||
channelCount={channels.length}
|
||||
busy={busy}
|
||||
busy={false}
|
||||
applyLabel="同步到全部频道"
|
||||
saveLabel="保存默认"
|
||||
onSave={async ({ daily_max }) => {
|
||||
@ -624,7 +627,6 @@ export default function YtLongPage() {
|
||||
<span className="text-slate-400">开关</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void toggle(true)}
|
||||
className={`rounded-lg px-3 py-1.5 ${status?.enabled ? "bg-amber-500/25 text-amber-50" : "bg-white/5 text-slate-300"}`}
|
||||
>
|
||||
@ -632,7 +634,6 @@ export default function YtLongPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void toggle(false)}
|
||||
className={`rounded-lg px-3 py-1.5 ${!status?.enabled ? "bg-rose-500/25 text-rose-50" : "bg-white/5 text-slate-300"}`}
|
||||
>
|
||||
@ -644,10 +645,9 @@ export default function YtLongPage() {
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
const r = await fetchJson("/api/yt-long/fill-quota", { method: "POST" });
|
||||
@ -655,8 +655,6 @@ export default function YtLongPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="ml-auto inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-3 py-1.5 text-xs text-teal-100"
|
||||
@ -666,10 +664,9 @@ export default function YtLongPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || !status?.enabled}
|
||||
disabled={!status?.enabled}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setMsg("");
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
const r = await fetchJson("/api/yt-long/sample-now", { method: "POST" });
|
||||
@ -680,8 +677,6 @@ export default function YtLongPage() {
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-100"
|
||||
@ -691,7 +686,6 @@ export default function YtLongPage() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void importFromShorts()}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-200"
|
||||
>
|
||||
@ -751,9 +745,11 @@ export default function YtLongPage() {
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{group.channels.map((ch) => {
|
||||
const pct = Math.min(100, Math.round((ch.used / Math.max(1, ch.daily_max)) * 100));
|
||||
// 进度条只按「已上传」,与 /shorts 一致;排队占坑不算进度。
|
||||
const progress = Number(ch.uploaded ?? 0);
|
||||
const pct = Math.min(100, Math.round((progress / Math.max(1, ch.daily_max)) * 100));
|
||||
const full = channels.find((x) => x.id === ch.id);
|
||||
const gap = ch.gap ?? Math.max(0, ch.daily_max - ch.used);
|
||||
const gap = Math.max(0, (ch.daily_max || 0) - progress);
|
||||
return (
|
||||
<div
|
||||
key={ch.id}
|
||||
@ -793,14 +789,13 @@ export default function YtLongPage() {
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-slate-400">
|
||||
<span>
|
||||
{ch.used}/{ch.daily_max || 0}
|
||||
上传 {progress}/{ch.daily_max || 0}
|
||||
</span>
|
||||
{gap > 0 ? (
|
||||
<span className="text-amber-300">缺 {gap}</span>
|
||||
) : (
|
||||
<span className="text-teal-300">已满</span>
|
||||
)}
|
||||
<span>上传 {ch.uploaded}</span>
|
||||
<span>排队 {ch.scheduled}</span>
|
||||
<span>待录 {ch.pending}</span>
|
||||
</div>
|
||||
@ -969,11 +964,10 @@ export default function YtLongPage() {
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void saveChannel()}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-[#ff2d55] px-3 py-2 text-sm text-white"
|
||||
>
|
||||
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
|
||||
{false ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
|
||||
保存
|
||||
</button>
|
||||
<button
|
||||
|
||||
@ -15,6 +15,8 @@ type Props = {
|
||||
disabled?: boolean;
|
||||
busy?: boolean;
|
||||
label?: string;
|
||||
/** Override default channel-pipeline tooltip (e.g. Neko power switch). */
|
||||
title?: string;
|
||||
accent?: Accent;
|
||||
size?: "sm" | "md";
|
||||
className?: string;
|
||||
@ -27,6 +29,7 @@ export function EnableSwitch({
|
||||
disabled = false,
|
||||
busy = false,
|
||||
label,
|
||||
title,
|
||||
accent = "teal",
|
||||
size = "sm",
|
||||
className = "",
|
||||
@ -35,6 +38,9 @@ export function EnableSwitch({
|
||||
const trackW = size === "md" ? "h-6 w-11" : "h-5 w-9";
|
||||
const knob = size === "md" ? "h-5 w-5" : "h-4 w-4";
|
||||
const travel = size === "md" ? "translate-x-5" : "translate-x-4";
|
||||
const tip =
|
||||
title ||
|
||||
(checked ? "关闭将清除任务并停止取样/上传" : "开启后恢复自动取样与上传");
|
||||
|
||||
return (
|
||||
<div
|
||||
@ -56,7 +62,7 @@ export function EnableSwitch({
|
||||
aria-checked={checked}
|
||||
aria-busy={busy || undefined}
|
||||
aria-label={checked ? "关闭" : "开启"}
|
||||
title={checked ? "关闭将清除任务并停止取样/上传" : "开启后恢复自动取样与上传"}
|
||||
title={tip}
|
||||
disabled={locked}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
|
||||
@ -66,7 +66,7 @@ export function HostResourceBar() {
|
||||
}
|
||||
};
|
||||
void load();
|
||||
const t = setInterval(() => void load(), 20000);
|
||||
const t = setInterval(() => void load(), 45000);
|
||||
const onVis = () => {
|
||||
if (!document.hidden) void load();
|
||||
};
|
||||
|
||||
@ -72,7 +72,7 @@ export function OpsNekoHubCredentialsCard() {
|
||||
return (
|
||||
<div className="rounded-2xl border border-teal-500/20 bg-teal-500/[0.06] px-3.5 py-3 text-xs text-slate-400">
|
||||
<Loader2 className="mr-1 inline h-3.5 w-3.5 animate-spin" />
|
||||
加载物理机配对凭证…
|
||||
加载远程配对凭证…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -7,7 +7,6 @@ import {
|
||||
Ban,
|
||||
Check,
|
||||
ChevronDown,
|
||||
Clock,
|
||||
Copy,
|
||||
Download,
|
||||
Eye,
|
||||
@ -503,6 +502,7 @@ export function YtAssignPanel({
|
||||
const [remoteCatalog, setRemoteCatalog] = useState<OpsNekoCatalogItem[]>([]);
|
||||
const [hostProfile, setHostProfile] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [avatarBusy, setAvatarBusy] = useState(false);
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
const [streamKeyDraft, setStreamKeyDraft] = useState("");
|
||||
const [noteDraft, setNoteDraft] = useState("");
|
||||
@ -557,10 +557,6 @@ export function YtAssignPanel({
|
||||
() => new Set((selected?.featured || []).map((f) => String(f.pool_url_id))),
|
||||
[selected]
|
||||
);
|
||||
const slotIds = useMemo(
|
||||
() => new Set((selected?.slots || []).map((s) => String(s.pool_url_id))),
|
||||
[selected]
|
||||
);
|
||||
const selectedSchedule = useMemo(
|
||||
() => scheduleForGroup(schedule, selected),
|
||||
[schedule, selected]
|
||||
@ -606,7 +602,12 @@ export function YtAssignPanel({
|
||||
if (t.kind === "assign" && t.id) ids.add(t.id);
|
||||
}
|
||||
for (const e of relayEntries) {
|
||||
if (e.group_id && isLivePushingRow(e)) ids.add(String(e.group_id));
|
||||
const gid = e.group_id ? String(e.group_id) : "";
|
||||
if (!gid) continue;
|
||||
if (isLivePushingRow(e)) ids.add(gid);
|
||||
// Align sidebar with Pro panel receiving: Studio on_air / encoder_receiving.
|
||||
const studio = (e.neko as { studio?: { on_air?: boolean; encoder_receiving?: boolean } } | undefined)?.studio;
|
||||
if (studio?.on_air || studio?.encoder_receiving) ids.add(gid);
|
||||
}
|
||||
for (const [k, v] of Object.entries(ytLiveMap?.entries || {})) {
|
||||
if (!v?.is_live) continue;
|
||||
@ -677,8 +678,9 @@ export function YtAssignPanel({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadGroups = useCallback(async () => {
|
||||
setBusy(true);
|
||||
const loadGroups = useCallback(async (opts?: { silent?: boolean }) => {
|
||||
const silent = Boolean(opts?.silent);
|
||||
if (!silent) setBusy(true);
|
||||
try {
|
||||
const [data] = await Promise.all([
|
||||
fetchJson("/api/youtube/assign/groups"),
|
||||
@ -692,13 +694,16 @@ export function YtAssignPanel({
|
||||
return list[0]?.id || "";
|
||||
});
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
if (!silent) toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
if (!silent) setBusy(false);
|
||||
}
|
||||
}, [toast, loadSchedule, focusGroupId]);
|
||||
|
||||
const remoteCatalogInFlight = useRef(false);
|
||||
const loadRemoteCatalog = useCallback(async () => {
|
||||
if (remoteCatalogInFlight.current) return;
|
||||
remoteCatalogInFlight.current = true;
|
||||
try {
|
||||
const [cat, hp] = await Promise.all([
|
||||
fetchJson("/api/ops/neko/remote-catalog").catch(() => ({ instances: [] })),
|
||||
@ -707,7 +712,9 @@ export function YtAssignPanel({
|
||||
setRemoteCatalog(((cat as { instances?: OpsNekoCatalogItem[] }).instances || []) as OpsNekoCatalogItem[]);
|
||||
setHostProfile(String((hp as { profile?: string }).profile || ""));
|
||||
} catch {
|
||||
/* ignore */
|
||||
/* keep last */
|
||||
} finally {
|
||||
remoteCatalogInFlight.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
@ -753,7 +760,7 @@ export function YtAssignPanel({
|
||||
}, []);
|
||||
|
||||
const refreshAllAvatars = useCallback(async () => {
|
||||
setBusy(true);
|
||||
setAvatarBusy(true);
|
||||
try {
|
||||
const r = await fetchJson("/api/youtube/manage/profiles/refresh?max_age_sec=0&limit=50", {
|
||||
method: "POST",
|
||||
@ -772,7 +779,7 @@ export function YtAssignPanel({
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setAvatarBusy(false);
|
||||
}
|
||||
}, [loadAllProfiles, toast]);
|
||||
|
||||
@ -795,8 +802,8 @@ export function YtAssignPanel({
|
||||
relayStatusRef.current?.entries ||
|
||||
[]) as RelayMonitorRow[];
|
||||
const pushing = rows.some((e) => isLivePushingRow(e));
|
||||
// Pushing: 5s; idle: 15s — backend status also caches ~1s.
|
||||
t = window.setTimeout(tick, pushing ? 5000 : 15000);
|
||||
// Pushing: 8s; idle: 20s — matches backend status cache ~5s.
|
||||
t = window.setTimeout(tick, pushing ? 8000 : 20000);
|
||||
});
|
||||
};
|
||||
t = window.setTimeout(tick, 4000);
|
||||
@ -806,7 +813,7 @@ export function YtAssignPanel({
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
const catTimer = window.setInterval(() => {
|
||||
if (!document.hidden) void loadRemoteCatalog();
|
||||
}, 5000);
|
||||
}, 30000);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (t) window.clearTimeout(t);
|
||||
@ -819,8 +826,8 @@ export function YtAssignPanel({
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => {
|
||||
if (document.hidden) return;
|
||||
void loadGroups();
|
||||
}, 45000);
|
||||
void loadGroups({ silent: true });
|
||||
}, 60000);
|
||||
return () => window.clearInterval(id);
|
||||
}, [loadGroups]);
|
||||
|
||||
@ -877,7 +884,7 @@ export function YtAssignPanel({
|
||||
toast.push(
|
||||
on
|
||||
? "时间段排班已开:请再开「自动推流」;排班与独占已解耦,物理机可关独占保 Neko 预热"
|
||||
: "时间段排班已关:恢复精选列表推流",
|
||||
: "时间段排班已关:普通频道将按直播地址列表自动监听开播推流",
|
||||
"ok",
|
||||
);
|
||||
await Promise.all([loadRelay(), loadSchedule()]);
|
||||
@ -994,7 +1001,7 @@ export function YtAssignPanel({
|
||||
setNewChannelPk("");
|
||||
setNewStreamKey("");
|
||||
setNewCategory("normal");
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
if (r?.group?.id) setGroupId(r.group.id);
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
@ -1015,7 +1022,7 @@ export function YtAssignPanel({
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.push("已保存直播 KEY / 备注", "ok");
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1031,8 +1038,8 @@ export function YtAssignPanel({
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ category }),
|
||||
});
|
||||
toast.push(category === "time_slot" ? "已切换为时间段推流" : "已切换为普通(手动推流)", "ok");
|
||||
await loadGroups();
|
||||
toast.push(category === "time_slot" ? "已切换为时间段推流" : "已切换为普通(关排班时自动推流)", "ok");
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1054,7 +1061,7 @@ export function YtAssignPanel({
|
||||
await fetchJson(`/api/youtube/assign/groups/${selected.id}`, { method: "DELETE" });
|
||||
toast.push("已删除", "ok");
|
||||
setGroupId("");
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1083,7 +1090,7 @@ export function YtAssignPanel({
|
||||
if (dup) parts.push(`去重 ${dup}`);
|
||||
if (bl) parts.push(`黑名单跳过 ${bl}`);
|
||||
toast.push(parts.join(" · "), n || dup || bl ? "ok" : "err");
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
void refreshLiveMap();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
@ -1110,7 +1117,7 @@ export function YtAssignPanel({
|
||||
`已拉黑(池删 ${r.pool_removed ?? 0} · 精选删 ${r.featured_removed ?? 0})`,
|
||||
"ok"
|
||||
);
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1129,7 +1136,7 @@ export function YtAssignPanel({
|
||||
`去重完成:池 ${r.pool_removed ?? 0} · 精选 ${r.featured_removed ?? 0}`,
|
||||
"ok"
|
||||
);
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1155,7 +1162,7 @@ export function YtAssignPanel({
|
||||
`已清理:池 ${r.pool_removed ?? 0} · 精选 ${r.featured_removed ?? 0}`,
|
||||
"ok"
|
||||
);
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1174,7 +1181,7 @@ export function YtAssignPanel({
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/assign/pool/${poolId}`, { method: "DELETE" });
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1193,7 +1200,7 @@ export function YtAssignPanel({
|
||||
const bl = Array.isArray(r?.skipped_blacklist) ? r.skipped_blacklist.length : 0;
|
||||
if (bl) toast.push("该房间在黑名单中,未加入精选", "err");
|
||||
else if (Number(r?.skipped_dup || 0) > 0 && !r?.added) toast.push("精选已存在(已去重)", "ok");
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1205,63 +1212,7 @@ export function YtAssignPanel({
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/assign/featured/${featuredId}`, { method: "DELETE" });
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function addSlot(poolUrlId: string) {
|
||||
if (!selected) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await fetchJson(`/api/youtube/assign/groups/${selected.id}/slots`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ pool_url_id: poolUrlId }),
|
||||
});
|
||||
const bl = Array.isArray(r?.skipped_blacklist) ? r.skipped_blacklist.length : 0;
|
||||
if (bl) toast.push("该房间在黑名单中,未加入时间段", "err");
|
||||
else if (Number(r?.skipped_dup || 0) > 0 && !r?.added) toast.push("时间段已存在(已去重)", "ok");
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeSlot(slotId: string) {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fetchJson(`/api/youtube/assign/slots/${slotId}`, { method: "DELETE" });
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function autoFillSlots(allGroups = false, force = false) {
|
||||
if (!selected && !allGroups) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = allGroups
|
||||
? await fetchJson("/api/youtube/assign/schedule/auto-fill", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ limit: 24, all_groups: true, force }),
|
||||
})
|
||||
: await fetchJson(`/api/youtube/assign/groups/${selected!.id}/slots/auto-fill`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ limit: 16, all_groups: false, force }),
|
||||
});
|
||||
const n = Number(r?.filled ?? 0);
|
||||
const skipped = String(r?.skipped || "");
|
||||
if (force && n > 0) toast.push(`已填充 ${n} 条直播源`, "ok");
|
||||
else if (force && skipped) toast.push(skipped === "no_live_data" ? "暂无抖音直播数据" : "列表已有数据", "warn");
|
||||
await loadGroups();
|
||||
await loadGroups({ silent: true });
|
||||
} catch (e) {
|
||||
toast.push((e as Error).message, "err");
|
||||
} finally {
|
||||
@ -1431,6 +1382,65 @@ export function YtAssignPanel({
|
||||
groups.find((g) => g.id === exclusiveWinnerId)?.name || (exclusiveWinnerId ? "未知频道" : "");
|
||||
const exclusiveLiveOn = relayStatus?.settings?.youtube_relay_exclusive_live !== false;
|
||||
const timeSlotModeOn = Boolean(relayStatus?.settings?.youtube_relay_time_slot_mode);
|
||||
useEffect(() => {
|
||||
if (!timeSlotModeOn) {
|
||||
setCategoryFilter((v) => (v === "time_slot" ? "normal" : v));
|
||||
}
|
||||
}, [timeSlotModeOn]);
|
||||
const normalGroups = useMemo(
|
||||
() => groups.filter((g) => (g.category || "normal") !== "time_slot"),
|
||||
[groups]
|
||||
);
|
||||
/** 普通频道「直播地址列表」里当前在播的抖音间(类似首页在播卡)。 */
|
||||
const normalLiveRooms = useMemo(() => {
|
||||
const entries = liveMap?.entries || {};
|
||||
const monitorByGid = new Map<string, RelayMonitorRow>();
|
||||
for (const e of relayEntries) {
|
||||
if (e.group_id) monitorByGid.set(String(e.group_id), e);
|
||||
}
|
||||
const out: Array<{
|
||||
key: string;
|
||||
groupId: string;
|
||||
groupName: string;
|
||||
roomId: string;
|
||||
url: string;
|
||||
title: string;
|
||||
cover?: string;
|
||||
pushing: boolean;
|
||||
}> = [];
|
||||
const seen = new Set<string>();
|
||||
for (const g of normalGroups) {
|
||||
const monitor = monitorByGid.get(g.id);
|
||||
const pushingGroup = isLivePushingRow(monitor);
|
||||
const pushRoom = String(monitor?.source_room_id || "").trim();
|
||||
for (const f of g.featured || []) {
|
||||
const roomId =
|
||||
String(f.room_id || "").trim() ||
|
||||
(String(f.url || "").match(/live\.douyin\.com\/(\d+)/i)?.[1] || "");
|
||||
if (!roomId) continue;
|
||||
const live = entries[roomId];
|
||||
const isLive =
|
||||
Boolean(live?.is_live) ||
|
||||
String(live?.last_status || "") === "live" ||
|
||||
(pushingGroup && pushRoom === roomId);
|
||||
if (!isLive) continue;
|
||||
const dedupe = `${g.id}:${roomId}`;
|
||||
if (seen.has(dedupe)) continue;
|
||||
seen.add(dedupe);
|
||||
out.push({
|
||||
key: dedupe,
|
||||
groupId: g.id,
|
||||
groupName: String(g.name || "频道"),
|
||||
roomId,
|
||||
url: String(f.url || live?.url || `https://live.douyin.com/${roomId}`),
|
||||
title: displayAnchor(f) || String(live?.anchor || "").trim() || roomId,
|
||||
cover: String(f.cover_url || live?.avatar_url || "").trim() || undefined,
|
||||
pushing: pushingGroup && (!pushRoom || pushRoom === roomId),
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}, [normalGroups, liveMap, relayEntries, displayAnchor]);
|
||||
const keyedChannelCountLocal = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const g of groups) {
|
||||
@ -1463,7 +1473,7 @@ export function YtAssignPanel({
|
||||
timeSlotModeOn={timeSlotModeOn}
|
||||
exclusiveLiveOn={exclusiveLiveOn}
|
||||
relayBusy={relayBusy}
|
||||
busy={busy}
|
||||
busy={avatarBusy}
|
||||
douyinLiveCount={relayStatus?.douyin_live_count ?? "—"}
|
||||
pushingCount={Number(relayStatus?.pushing_count ?? 0)}
|
||||
workerRunning={Boolean(relayStatus?.running)}
|
||||
@ -1520,7 +1530,7 @@ export function YtAssignPanel({
|
||||
value={newCategory}
|
||||
onChange={(e) => setNewCategory((e.target.value as AssignCategory) || "normal")}
|
||||
disabled={busy}
|
||||
title="分组分类:普通=手动推流;时间段=排班推流"
|
||||
title="分组分类:普通=关排班时自动听直播地址;时间段=24/N 排班"
|
||||
className="rounded-xl border border-white/10 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none ring-rose-400/0 transition focus:ring-2 focus:ring-rose-400/30"
|
||||
>
|
||||
<option value="normal">普通</option>
|
||||
@ -1536,7 +1546,7 @@ export function YtAssignPanel({
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-2 text-[10px] text-slate-500">
|
||||
普通 = 手动推流(精选源);时间段 = 24/N 排班 + 在播抖音源。其他分类待定。
|
||||
普通 = 关「时间段排班」且开「自动推流」时监听直播地址列表;时间段 = 24/N + 监控在播抖音。单路独占时只跑最先开播的那一路。
|
||||
</p>
|
||||
{channels.length === 0 ? (
|
||||
<p className="mt-3 text-xs text-amber-200">
|
||||
@ -1560,91 +1570,241 @@ export function YtAssignPanel({
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{slotConflicts.length > 0 ? (
|
||||
<div className="rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-100">
|
||||
<div className="font-medium">时段冲突:同一 Douyin URL 被分配到多个频道时段</div>
|
||||
<ul className="mt-2 list-inside list-disc space-y-1 text-amber-200/90">
|
||||
{slotConflicts.slice(0, 6).map((c) => (
|
||||
<li key={c.key}>
|
||||
{c.channels.join(" · ")} — {(c.url || c.key).slice(0, 48)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{timeSlotModeOn ? (
|
||||
<>
|
||||
{slotConflicts.length > 0 ? (
|
||||
<div className="rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-100">
|
||||
<div className="font-medium">时段冲突:同一 Douyin URL 被分配到多个频道时段</div>
|
||||
<ul className="mt-2 list-inside list-disc space-y-1 text-amber-200/90">
|
||||
{slotConflicts.slice(0, 6).map((c) => (
|
||||
<li key={c.key}>
|
||||
{c.channels.join(" · ")} — {(c.url || c.key).slice(0, 48)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
{schedule && (schedule.channels || []).length > 0 ? (
|
||||
<section className="overflow-hidden rounded-2xl border border-teal-500/20 bg-gradient-to-br from-teal-500/[0.07] via-black/20 to-violet-500/[0.04] p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-teal-50">
|
||||
时间段排班 ·「时间段」分类频道(北京时间)
|
||||
</h4>
|
||||
<p className="mt-0.5 text-[11px] text-teal-200/65">
|
||||
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "}
|
||||
{schedule.now_label} · 源=在播抖音
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void openTimeslotExclude()}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-amber-400/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] text-amber-50 transition hover:bg-amber-500/20"
|
||||
title="时段推流不会选用这些抖音间(避免与手动直播撞流)"
|
||||
>
|
||||
<ListFilter className="h-3 w-3" />
|
||||
排除手动直播名单
|
||||
{excludeMeta?.count ||
|
||||
relayStatus?.settings?.youtube_relay_timeslot_exclude_count ? (
|
||||
<span className="rounded bg-amber-500/25 px-1 text-[10px] tabular-nums">
|
||||
{excludeMeta?.count ??
|
||||
relayStatus?.settings?.youtube_relay_timeslot_exclude_count}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-1.5 overflow-x-auto pb-1">
|
||||
{(schedule.channels || []).map((ch) => {
|
||||
const active = Boolean(ch.active);
|
||||
const selectedNow = ch.group_id === groupId;
|
||||
return (
|
||||
<button
|
||||
key={ch.group_id}
|
||||
type="button"
|
||||
onClick={() => setGroupId(ch.group_id)}
|
||||
className={`min-w-[7.75rem] shrink-0 rounded-xl border px-2.5 py-2 text-left transition duration-200 ${
|
||||
active
|
||||
? "border-teal-400/45 bg-teal-500/20 shadow-[0_0_24px_-12px_rgba(45,212,191,0.8)]"
|
||||
: selectedNow
|
||||
? "border-violet-400/40 bg-violet-500/15"
|
||||
: "border-white/10 bg-black/35 hover:border-white/20 hover:bg-white/[0.04]"
|
||||
}`}
|
||||
>
|
||||
<div className="truncate text-[11px] font-medium text-slate-100">
|
||||
{ch.name || "频道"}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[10px] text-slate-400">
|
||||
{ch.start_label}–{ch.end_label}
|
||||
</div>
|
||||
{active ? (
|
||||
<div className="mt-1 text-[9px] font-medium uppercase tracking-wider text-teal-200/90">
|
||||
Now
|
||||
</div>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
) : (
|
||||
<section className="rounded-2xl border border-dashed border-teal-500/25 bg-teal-500/[0.04] px-4 py-6 text-center text-xs text-teal-100/70">
|
||||
时间段排班已开,但还没有带 KEY 的「时间段」分类频道
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<section className="overflow-hidden rounded-2xl border border-rose-500/20 bg-gradient-to-br from-rose-500/[0.08] via-black/25 to-fuchsia-500/[0.04] p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-rose-50">普通频道 · 在播抖音</h4>
|
||||
<p className="mt-0.5 text-[11px] text-rose-200/65">
|
||||
来自各普通频道「直播地址列表」· 与首页同款在播态势
|
||||
{Boolean(relayStatus?.enabled)
|
||||
? " · 开播即自动推流"
|
||||
: " · 自动推流关时可先观察"}
|
||||
</p>
|
||||
</div>
|
||||
<span className="rounded-lg border border-rose-400/25 bg-rose-500/15 px-2 py-1 text-[11px] tabular-nums text-rose-100">
|
||||
{normalLiveRooms.length} 路在播
|
||||
</span>
|
||||
</div>
|
||||
{normalLiveRooms.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-white/10 bg-black/20 px-3 py-8 text-center text-xs text-slate-500">
|
||||
当前没有普通频道直播地址在播
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{normalLiveRooms.map((row) => (
|
||||
<button
|
||||
key={row.key}
|
||||
type="button"
|
||||
onClick={() => setGroupId(row.groupId)}
|
||||
className={`flex items-center gap-3 rounded-xl border px-3 py-2 text-left transition ${
|
||||
row.pushing
|
||||
? "border-rose-400/40 bg-rose-500/15 shadow-[0_0_28px_-14px_rgba(251,113,133,0.85)]"
|
||||
: "border-rose-500/20 bg-rose-500/5 hover:bg-rose-500/10"
|
||||
}`}
|
||||
>
|
||||
<div className="relative h-14 w-10 shrink-0 overflow-hidden rounded bg-slate-900 ring-1 ring-white/10">
|
||||
{row.cover ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={row.cover} alt="" className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-[9px] text-slate-600">
|
||||
LIVE
|
||||
</div>
|
||||
)}
|
||||
<span className="absolute left-1 top-1 live-dot-douyin" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium text-white">
|
||||
{row.title}
|
||||
<span className="ml-1.5 inline-block align-middle">
|
||||
<DouyinLiveBadge roomId={row.roomId} compact />
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-0.5 truncate text-[11px] text-rose-200/80">
|
||||
→ {row.groupName}
|
||||
{row.pushing ? " · 推流中" : ""}
|
||||
</div>
|
||||
<a
|
||||
href={row.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="mt-0.5 block truncate text-[10px] text-slate-500 hover:text-slate-300"
|
||||
>
|
||||
{row.url.replace(/^https?:\/\//, "")}
|
||||
</a>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="overflow-hidden rounded-2xl border border-violet-500/20 bg-gradient-to-br from-violet-500/[0.07] via-black/20 to-rose-500/[0.04] p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-violet-50">普通频道</h4>
|
||||
<p className="mt-0.5 text-[11px] text-violet-200/65">
|
||||
{normalGroups.length} 个 · 动效标出当前在播 / 推流
|
||||
{exclusiveLiveOn && exclusiveWinnerName
|
||||
? ` · 独占中 ${exclusiveWinnerName}`
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{normalGroups.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-white/10 bg-black/20 px-3 py-6 text-center text-xs text-slate-500">
|
||||
还没有普通分类分组
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-1.5 overflow-x-auto pb-1">
|
||||
{normalGroups.map((g) => {
|
||||
const pk = String(g.channel_pk || "");
|
||||
const monitor = relayEntries.find((e) => e.group_id === g.id);
|
||||
const pushing = isLivePushingRow(monitor);
|
||||
const ytLive = liveAssignIds.has(g.id);
|
||||
const onAir = pushing || ytLive;
|
||||
const winner = exclusiveWinnerId === g.id;
|
||||
const selectedNow = g.id === groupId;
|
||||
const liveFeatCount = normalLiveRooms.filter((r) => r.groupId === g.id).length;
|
||||
return (
|
||||
<button
|
||||
key={g.id}
|
||||
type="button"
|
||||
onClick={() => setGroupId(g.id)}
|
||||
className={`relative min-w-[8.5rem] shrink-0 overflow-hidden rounded-xl border px-2.5 py-2.5 text-left transition duration-300 ${
|
||||
onAir
|
||||
? "border-rose-400/50 bg-rose-500/20 shadow-[0_0_28px_-10px_rgba(251,113,133,0.9)]"
|
||||
: selectedNow
|
||||
? "border-violet-400/40 bg-violet-500/15"
|
||||
: "border-white/10 bg-black/35 hover:border-white/20 hover:bg-white/[0.04]"
|
||||
}`}
|
||||
>
|
||||
{onAir ? (
|
||||
<span className="pointer-events-none absolute inset-0 animate-pulse bg-gradient-to-r from-rose-500/0 via-rose-400/10 to-rose-500/0" />
|
||||
) : null}
|
||||
<div className="relative">
|
||||
<YtChannelProfileSnippet
|
||||
profile={profileFor(pk)}
|
||||
fallbackName={g.name}
|
||||
fallbackChannelId={g.youtube_channel_id}
|
||||
liveChannelPk={pk || undefined}
|
||||
compact
|
||||
/>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1 text-[9px]">
|
||||
{onAir ? (
|
||||
<span className="inline-flex items-center gap-1 font-medium uppercase tracking-wider text-rose-200">
|
||||
<span className="live-dot-youtube" />
|
||||
{pushing ? businessStatusLabel(monitor) || "推流中" : "频道在播"}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-500">待命</span>
|
||||
)}
|
||||
{winner ? (
|
||||
<span className="rounded bg-amber-500/20 px-1 text-amber-100">独占</span>
|
||||
) : null}
|
||||
{liveFeatCount > 0 ? (
|
||||
<span className="rounded bg-fuchsia-500/20 px-1 text-fuchsia-100">
|
||||
抖音 {liveFeatCount}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
) : null}
|
||||
{schedule && (schedule.channels || []).length > 0 ? (
|
||||
<section className="overflow-hidden rounded-2xl border border-teal-500/20 bg-gradient-to-br from-teal-500/[0.07] via-black/20 to-violet-500/[0.04] p-4">
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-teal-50">
|
||||
{timeSlotModeOn || schedule.time_slot_mode
|
||||
? "时间段排班 ·「时间段」分类频道(北京时间)"
|
||||
: "24 小时频道轮播(北京时间)"}
|
||||
</h4>
|
||||
<p className="mt-0.5 text-[11px] text-teal-200/65">
|
||||
{schedule.channel_count} 个频道 · 每频道约 {schedule.slot_hours} 小时 · 当前{" "}
|
||||
{schedule.now_label}
|
||||
{timeSlotModeOn || schedule.time_slot_mode ? " · 源=在播抖音" : ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void openTimeslotExclude()}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-amber-400/25 bg-amber-500/10 px-2.5 py-1.5 text-[11px] text-amber-50 transition hover:bg-amber-500/20"
|
||||
title="时段推流不会选用这些抖音间(避免与手动直播撞流)"
|
||||
>
|
||||
<ListFilter className="h-3 w-3" />
|
||||
排除手动直播名单
|
||||
{excludeMeta?.count || relayStatus?.settings?.youtube_relay_timeslot_exclude_count ? (
|
||||
<span className="rounded bg-amber-500/25 px-1 text-[10px] tabular-nums">
|
||||
{excludeMeta?.count ??
|
||||
relayStatus?.settings?.youtube_relay_timeslot_exclude_count}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void autoFillSlots(true, true)}
|
||||
className="inline-flex items-center gap-1 rounded-xl border border-teal-400/20 bg-teal-500/15 px-2.5 py-1.5 text-[11px] text-teal-50 transition hover:bg-teal-500/25"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
全频道填充直播数据
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-1.5 overflow-x-auto pb-1">
|
||||
{(schedule.channels || []).map((ch) => {
|
||||
const active = Boolean(ch.active);
|
||||
const selectedNow = ch.group_id === groupId;
|
||||
return (
|
||||
<button
|
||||
key={ch.group_id}
|
||||
type="button"
|
||||
onClick={() => setGroupId(ch.group_id)}
|
||||
className={`min-w-[7.75rem] shrink-0 rounded-xl border px-2.5 py-2 text-left transition duration-200 ${
|
||||
active
|
||||
? "border-teal-400/45 bg-teal-500/20 shadow-[0_0_24px_-12px_rgba(45,212,191,0.8)]"
|
||||
: selectedNow
|
||||
? "border-violet-400/40 bg-violet-500/15"
|
||||
: "border-white/10 bg-black/35 hover:border-white/20 hover:bg-white/[0.04]"
|
||||
}`}
|
||||
>
|
||||
<div className="truncate text-[11px] font-medium text-slate-100">{ch.name || "频道"}</div>
|
||||
<div className="mt-0.5 text-[10px] text-slate-400">
|
||||
{ch.start_label}–{ch.end_label}
|
||||
</div>
|
||||
{active ? (
|
||||
<div className="mt-1 text-[9px] font-medium uppercase tracking-wider text-teal-200/90">Now</div>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-[minmax(280px,300px)_minmax(0,1fr)]">
|
||||
<aside className="space-y-2 xl:sticky xl:top-4 xl:self-start">
|
||||
@ -1772,15 +1932,14 @@ export function YtAssignPanel({
|
||||
? "border-teal-400/35 bg-teal-500/15 text-teal-100"
|
||||
: "border-white/15 bg-black/40 text-slate-200"
|
||||
}`}
|
||||
title="普通=手动推流;时间段=排班推流"
|
||||
title="普通=关排班时自动推流;时间段=24/N 排班"
|
||||
>
|
||||
<option value="normal">普通</option>
|
||||
<option value="time_slot">时间段</option>
|
||||
</select>
|
||||
</label>
|
||||
<span>池 {(g.pool || []).length}</span>
|
||||
<span>精选 {(g.featured || []).length}</span>
|
||||
<span>时段 {(g.slots || []).length}</span>
|
||||
<span>直播地址 {(g.featured || []).length}</span>
|
||||
{sch ? (
|
||||
<span className={sch.active ? "text-teal-300" : "text-violet-300/80"}>
|
||||
{sch.start_label}–{sch.end_label}
|
||||
@ -1844,8 +2003,10 @@ export function YtAssignPanel({
|
||||
onStop={(id) => void kickRelayGroup(id, "stop")}
|
||||
onRestart={(id) => void kickRelayGroup(id, "restart")}
|
||||
onNekoChange={() => {
|
||||
void loadGroups();
|
||||
// Silent: Neko toggle must not freeze the whole assign panel via setBusy(true).
|
||||
void loadGroups({ silent: true });
|
||||
void loadRemoteCatalog();
|
||||
void loadRelay();
|
||||
}}
|
||||
remoteCatalog={remoteCatalog}
|
||||
hostProfile={hostProfile}
|
||||
@ -1872,7 +2033,7 @@ export function YtAssignPanel({
|
||||
}}
|
||||
className="rounded-md border border-white/10 bg-slate-950 px-1.5 py-0.5 text-[11px] text-slate-100 outline-none"
|
||||
>
|
||||
<option value="normal">普通(手动推流)</option>
|
||||
<option value="normal">普通(关排班时自动推流)</option>
|
||||
<option value="time_slot">时间段(排班推流)</option>
|
||||
</select>
|
||||
</label>
|
||||
@ -1949,8 +2110,8 @@ export function YtAssignPanel({
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
|
||||
<section className="order-2 rounded-2xl border border-white/10 bg-black/25 p-4 lg:order-2 xl:order-2">
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<section className="order-2 rounded-2xl border border-white/10 bg-black/25 p-4 lg:order-2">
|
||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium text-slate-100">
|
||||
普通列表(URL 池)· {(selected.pool || []).length}
|
||||
@ -2001,7 +2162,6 @@ export function YtAssignPanel({
|
||||
) : (
|
||||
(selected.pool || []).map((u) => {
|
||||
const inFeat = featuredIds.has(u.id);
|
||||
const inSlot = slotIds.has(u.id);
|
||||
const banned = Boolean(u.blacklisted);
|
||||
return (
|
||||
<div
|
||||
@ -2043,23 +2203,10 @@ export function YtAssignPanel({
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || inSlot || banned}
|
||||
title={banned ? "已在黑名单" : inSlot ? "已在时间段" : "加入时间段轮播"}
|
||||
onClick={() => void addSlot(u.id)}
|
||||
className={`rounded-lg px-2 py-1 text-[11px] ${
|
||||
inSlot || banned
|
||||
? "bg-violet-500/20 text-violet-100 opacity-50"
|
||||
: "bg-white/5 text-slate-300 hover:bg-violet-500/15"
|
||||
}`}
|
||||
>
|
||||
<Clock className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || inFeat || banned}
|
||||
title={banned ? "已在黑名单" : inFeat ? "已在精选" : "加入精选"}
|
||||
title={banned ? "已在黑名单" : inFeat ? "已在直播地址" : "加入直播地址列表"}
|
||||
onClick={() => void addFeatured(u.id)}
|
||||
className={`rounded-lg px-2 py-1 text-[11px] ${
|
||||
inFeat || banned
|
||||
@ -2094,146 +2241,7 @@ export function YtAssignPanel({
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="order-3 rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4 xl:order-3 xl:col-span-1">
|
||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium text-violet-50">
|
||||
时间段列表(轮播)· {(selected.slots || []).length}
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void autoFillSlots(false, true)}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-violet-500/20 px-2 py-1 text-[11px] text-violet-100"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
填充直播
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyList("slots")}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-violet-50"
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
复制
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => exportList("slots")}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2 py-1 text-[11px] text-violet-50"
|
||||
>
|
||||
<Download className="h-3 w-3" />
|
||||
导出
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mb-3 text-[11px] text-violet-100/70">
|
||||
本频道 {selectedSchedule?.start_label || "—"}–{selectedSchedule?.end_label || "—"} 内按序轮播抖音源;多频道错开时段,避免同时推流。
|
||||
</p>
|
||||
<div className="max-h-[28rem] space-y-2 overflow-y-auto">
|
||||
{(selected.slots || []).length === 0 ? (
|
||||
<div className="py-10 text-center text-xs text-violet-100/50">
|
||||
从普通列表点时钟图标加入,或点「填充直播」
|
||||
</div>
|
||||
) : (
|
||||
(selected.slots || []).map((s, i) => {
|
||||
const banned = Boolean(s.blacklisted);
|
||||
const inFeat = s.pool_url_id ? featuredIds.has(s.pool_url_id) : false;
|
||||
const schSlot = (schedule?.channels || [])
|
||||
.find((c) => c.group_id === selected.id)
|
||||
?.slots?.[i] as SlotUrl | undefined;
|
||||
const timeLabel =
|
||||
schSlot?.window_start_label && schSlot?.window_end_label
|
||||
? `${schSlot.window_start_label}–${schSlot.window_end_label}`
|
||||
: null;
|
||||
return (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`flex items-center gap-2 rounded-xl border p-2 ${
|
||||
banned
|
||||
? "border-fuchsia-500/35 bg-fuchsia-500/10"
|
||||
: "border-violet-500/25 bg-black/40"
|
||||
}`}
|
||||
>
|
||||
<span className="shrink-0 rounded bg-violet-500/20 px-1.5 text-[10px] text-violet-100">
|
||||
#{i + 1}
|
||||
</span>
|
||||
<CoverThumb
|
||||
cover={s.cover_url}
|
||||
title={s.title}
|
||||
roomId={s.room_id}
|
||||
onOpen={(src) =>
|
||||
setLightbox({ src, title: s.title || "封面", subtitle: s.url })
|
||||
}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<div className="truncate text-sm text-violet-50">{displayAnchor(s)}</div>
|
||||
{s.room_id ? <DouyinLiveBadge roomId={s.room_id} compact showOffline /> : null}
|
||||
{timeLabel ? (
|
||||
<span className="rounded bg-violet-500/25 px-1.5 text-[10px] text-violet-100">
|
||||
{timeLabel}
|
||||
</span>
|
||||
) : null}
|
||||
{banned ? (
|
||||
<span className="rounded bg-fuchsia-500/25 px-1.5 text-[10px] text-fuchsia-100">
|
||||
黑名单
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<a
|
||||
href={s.url || "#"}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="block truncate text-[11px] text-sky-300 hover:underline"
|
||||
>
|
||||
{s.url || s.pool_url_id}
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-1">
|
||||
{s.pool_url_id ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy || inFeat || banned}
|
||||
title={banned ? "已在黑名单" : inFeat ? "已在精选" : "加入精选"}
|
||||
onClick={() => void addFeatured(s.pool_url_id)}
|
||||
className={`rounded-lg px-2 py-1 text-[11px] ${
|
||||
inFeat || banned
|
||||
? "bg-amber-500/20 text-amber-100 opacity-50"
|
||||
: "bg-white/5 text-slate-300 hover:bg-amber-500/15"
|
||||
}`}
|
||||
>
|
||||
<Star className="h-3 w-3" />
|
||||
</button>
|
||||
) : null}
|
||||
{s.pool_url_id ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
title="加入黑名单"
|
||||
onClick={() => void banPool(s.pool_url_id, s.title || s.url || "")}
|
||||
className="rounded-lg bg-fuchsia-500/15 px-2 py-1 text-fuchsia-100"
|
||||
>
|
||||
<Ban className="h-3 w-3" />
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void removeSlot(s.id)}
|
||||
className="rounded-lg bg-rose-500/10 px-2 py-1 text-rose-200"
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="order-1 rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4 lg:col-span-2 xl:order-1 xl:col-span-1">
|
||||
<section className="order-1 rounded-2xl border border-amber-500/20 bg-amber-500/5 p-4 lg:order-1">
|
||||
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
|
||||
<h4 className="text-sm font-medium text-amber-50">
|
||||
直播地址列表 · {(selected.featured || []).length}
|
||||
@ -2258,12 +2266,12 @@ export function YtAssignPanel({
|
||||
</div>
|
||||
</div>
|
||||
<p className="mb-3 text-[11px] text-amber-100/70">
|
||||
即分配页的精选列表;FFmpeg 推流只从此列表选源(优先在播)。从普通池点 ★ 加入。
|
||||
关「时间段排班」且开「自动推流」时:从此列表监听开播并推流(优先在播)。单路独占时只跑最先开播的频道。从普通池点 ★ 加入。
|
||||
</p>
|
||||
<div className="max-h-[28rem] space-y-2 overflow-y-auto">
|
||||
{(selected.featured || []).length === 0 ? (
|
||||
<div className="py-10 text-center text-xs text-amber-100/50">
|
||||
从左侧普通列表点星标加入精选
|
||||
从左侧普通列表点星标加入
|
||||
</div>
|
||||
) : (
|
||||
(selected.featured || []).map((f, i) => {
|
||||
@ -2357,7 +2365,7 @@ export function YtAssignPanel({
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-amber-50">排除手动直播名单</h3>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-slate-400">
|
||||
不是黑名单:这些抖音间仍可监控 / 手动推流。时间段自动选源与「全频道填充」不会选用它们,避免与已指定的手动直播撞同一路流。
|
||||
不是黑名单:这些抖音间仍可监控 / 手动推流。时间段自动选源不会选用它们,避免与已指定的手动直播撞同一路流。
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
|
||||
@ -164,11 +164,11 @@ export function YtRelayOpsHero({
|
||||
</h3>
|
||||
<p className="mt-1.5 text-sm leading-relaxed text-slate-400">
|
||||
{timeSlotModeOn
|
||||
? `排班中:${keyedChannelCount || "N"} 个有 KEY 频道平分 24h(北京时间),源取当前在播抖音。`
|
||||
: "精选列表推流:频道 + KEY → 抖音池 → 精选地址。打开自动推流后由 Worker 调度。"}
|
||||
? `排班中:${keyedChannelCount || "N"} 个「时间段」频道平分 24h(北京时间),源取监控里当前在播抖音。`
|
||||
: "普通模式:开「自动推流」后各普通频道监听直播地址列表,房间开播即推。"}
|
||||
{exclusiveLiveOn
|
||||
? " 资源策略为「独占」:开播时只保留一路 FFmpeg,并暂停其他 Neko(适合 VPS)。"
|
||||
: " 资源策略为「多开」:可同时保留多个 Neko 预热(适合物理机)。"}
|
||||
? " 「单路独占」:只保留最先开播的一路 FFmpeg + Neko,该路真正停播后再进下一轮。"
|
||||
: " 「多开」:可同时多路推流 / 多 Neko 预热(适合物理机)。"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { ExternalLink, Loader2, Monitor, RotateCw } from "lucide-react";
|
||||
import { Copy, ExternalLink, Loader2, Monitor, RotateCw } from "lucide-react";
|
||||
|
||||
import { DouyinLiveBadge } from "@/components/DouyinLiveBadge";
|
||||
import { EnableSwitch } from "@/components/EnableSwitch";
|
||||
@ -29,6 +29,7 @@ type GroupLike = {
|
||||
name?: string;
|
||||
enabled?: boolean;
|
||||
has_stream_key?: boolean;
|
||||
stream_key?: string;
|
||||
featured?: Array<{ url?: string }>;
|
||||
neko_instance_id?: number;
|
||||
neko_enabled?: boolean;
|
||||
@ -131,6 +132,8 @@ export function YtRelayProStatusPanel({
|
||||
const douyinSubtitle = row?.source_display || row?.source_title || "";
|
||||
const dUrl = row?.source_url || "";
|
||||
const suf = row?.stream_key_suffix || "—";
|
||||
const fullKey = String(group.stream_key || row?.stream_key || "").trim();
|
||||
const keyLabel = fullKey || (suf && suf !== "—" ? `…${suf}` : "");
|
||||
const urlCount = row?.url_count ?? (group.featured || []).length;
|
||||
const dyCount = row?.douyin_count ?? urlCount;
|
||||
const blocked = procStartBlocked(row);
|
||||
@ -150,6 +153,10 @@ export function YtRelayProStatusPanel({
|
||||
const [openPrefer, setOpenPrefer] = useState<"local" | "remote">(
|
||||
group.neko_open_prefer === "remote" ? "remote" : "local",
|
||||
);
|
||||
// Exclusive / time-slot may leave the container running while DB neko_enabled=0.
|
||||
// Power switch must follow container reality (except while a local toggle is in-flight).
|
||||
const containerOn = Boolean(nekoState?.running || nekoState?.ready);
|
||||
const nekoPowerOn = nekoBusy ? nekoEnabled : Boolean(nekoEnabled || containerOn);
|
||||
const localStudioUrl = String(
|
||||
group.neko_local_studio_url || group.neko_studio_url || nekoState?.studio_url || "",
|
||||
).trim();
|
||||
@ -161,20 +168,24 @@ export function YtRelayProStatusPanel({
|
||||
: localStudioUrl || String(nekoState?.studio_url || "").trim();
|
||||
|
||||
useEffect(() => {
|
||||
if (nekoBusy) return; // avoid overwriting optimistic power flip mid-flight
|
||||
setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled));
|
||||
}, [group.id, group.neko_enabled, row?.neko_enabled]);
|
||||
}, [group.id, group.neko_enabled, row?.neko_enabled, nekoBusy]);
|
||||
|
||||
useEffect(() => {
|
||||
if (nekoBusy) return;
|
||||
setOpenPrefer(group.neko_open_prefer === "remote" ? "remote" : "local");
|
||||
}, [group.id, group.neko_open_prefer]);
|
||||
}, [group.id, group.neko_open_prefer, nekoBusy]);
|
||||
|
||||
// Prefer Neko snapshot from relay/status (3.5s) — avoids a second docker poll loop.
|
||||
useEffect(() => {
|
||||
if (nekoBusy) return;
|
||||
if (row?.neko) {
|
||||
setNekoState(row.neko as NekoState);
|
||||
setNekoPollErr("");
|
||||
}
|
||||
}, [
|
||||
nekoBusy,
|
||||
row?.neko,
|
||||
row?.neko?.status,
|
||||
row?.neko?.ready,
|
||||
@ -215,6 +226,25 @@ export function YtRelayProStatusPanel({
|
||||
}, [instanceId, row?.neko, refreshNeko]);
|
||||
|
||||
async function postNeko(body: Record<string, unknown>) {
|
||||
const wantOn =
|
||||
typeof body.enabled === "boolean"
|
||||
? Boolean(body.enabled)
|
||||
: String(body.action || "") === "start";
|
||||
// Optimistic: flip switch immediately — never wait on docker + full panel reload.
|
||||
setNekoEnabled(wantOn);
|
||||
if (!wantOn) {
|
||||
setNekoState((prev) =>
|
||||
prev
|
||||
? { ...prev, running: false, ready: false, status: "exited" }
|
||||
: prev,
|
||||
);
|
||||
} else {
|
||||
setNekoState((prev) =>
|
||||
prev
|
||||
? { ...prev, running: true, ready: Boolean(prev.ready), status: prev.ready ? "healthy" : "starting" }
|
||||
: { running: true, ready: false, status: "starting" },
|
||||
);
|
||||
}
|
||||
setNekoBusy(true);
|
||||
try {
|
||||
const r = (await fetchJson(`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/neko`, {
|
||||
@ -222,11 +252,20 @@ export function YtRelayProStatusPanel({
|
||||
body: JSON.stringify(body),
|
||||
})) as { group?: GroupLike; neko?: NekoState };
|
||||
if (r.group) setNekoEnabled(Boolean(r.group.neko_enabled));
|
||||
if (r.neko) setNekoState(r.neko);
|
||||
if (r.neko) {
|
||||
setNekoState((prev) => ({
|
||||
...r.neko!,
|
||||
studio: (r.neko as NekoState)?.studio ?? prev?.studio ?? null,
|
||||
}));
|
||||
}
|
||||
// Parent must silent-refresh — never setBusy on whole assign panel.
|
||||
onNekoChange?.();
|
||||
await refreshNeko();
|
||||
} catch (e) {
|
||||
// Roll back optimistic power state from last known server bits.
|
||||
setNekoEnabled(Boolean(group.neko_enabled ?? row?.neko_enabled));
|
||||
if (row?.neko) setNekoState(row.neko as NekoState);
|
||||
toast.push((e as Error).message, "err");
|
||||
void refreshNeko();
|
||||
} finally {
|
||||
setNekoBusy(false);
|
||||
}
|
||||
@ -234,7 +273,7 @@ export function YtRelayProStatusPanel({
|
||||
|
||||
async function setPrefer(prefer: "local" | "remote") {
|
||||
if (prefer === "remote" && !remoteBound) {
|
||||
toast.push("请先在下方下拉框选择物理机 ops-neko 实例", "err");
|
||||
toast.push("请先在下方下拉框选择远程 ops-neko 实例", "err");
|
||||
return;
|
||||
}
|
||||
setNekoBusy(true);
|
||||
@ -274,7 +313,7 @@ export function YtRelayProStatusPanel({
|
||||
return;
|
||||
}
|
||||
const item = remoteCatalog.find((x) => String(x.id || `${x.edge_id}:${x.slot}`) === catalogId);
|
||||
if (!item?.open_url) throw new Error("未找到该物理机实例");
|
||||
if (!item?.open_url) throw new Error("未找到该远程实例");
|
||||
const r = (await fetchJson(
|
||||
`/api/youtube/assign/groups/${encodeURIComponent(group.id)}/ops-neko-bind`,
|
||||
{
|
||||
@ -355,7 +394,26 @@ export function YtRelayProStatusPanel({
|
||||
<span className="text-slate-600">·</span>
|
||||
</>
|
||||
) : null}
|
||||
<span>key …{suf}</span>
|
||||
<span className="inline-flex max-w-full items-center gap-1">
|
||||
<span className="truncate font-mono text-teal-200/90" title={fullKey || keyLabel}>
|
||||
key {keyLabel || "—"}
|
||||
</span>
|
||||
{fullKey ? (
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded border border-white/10 px-1 py-0.5 text-[9px] text-slate-300 hover:bg-white/10"
|
||||
title="复制直播 Key"
|
||||
onClick={() =>
|
||||
void navigator.clipboard.writeText(fullKey).then(
|
||||
() => toast.push("已复制 Key", "ok"),
|
||||
() => toast.push("复制失败", "err"),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Copy className="h-3 w-3" />
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
<span className="text-slate-600">·</span>
|
||||
<span>URL {urlCount}</span>
|
||||
<span className="text-slate-600">·</span>
|
||||
@ -385,6 +443,14 @@ export function YtRelayProStatusPanel({
|
||||
</div>
|
||||
|
||||
<div className="flex w-full shrink-0 flex-wrap items-center justify-end gap-1.5 sm:w-auto">
|
||||
<Link
|
||||
href={`/youtube/analytics/${encodeURIComponent(group.id)}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-rose-400/30 bg-rose-500/10 px-2.5 py-1.5 text-[11px] text-rose-100 hover:bg-rose-500/20"
|
||||
>
|
||||
数据
|
||||
</Link>
|
||||
<Link
|
||||
href={`/youtube-relay-log?group_id=${encodeURIComponent(group.id)}`}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 hover:bg-white/10"
|
||||
@ -460,20 +526,26 @@ export function YtRelayProStatusPanel({
|
||||
</span>
|
||||
</div>
|
||||
<EnableSwitch
|
||||
checked={nekoEnabled}
|
||||
disabled={nekoBusy}
|
||||
checked={nekoPowerOn}
|
||||
busy={nekoBusy}
|
||||
label="启用"
|
||||
title={nekoPowerOn ? "关闭并停止本机 Neko 容器" : "启用并启动本机 Neko 容器"}
|
||||
accent="amber"
|
||||
onChange={(v) => void postNeko({ enabled: v, action: v ? "start" : "stop" })}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-2 text-[10px] leading-relaxed text-slate-500">
|
||||
本机原生 Neko #{instanceId} 始终保留(默认停止)。密码{" "}
|
||||
本机 Neko #{instanceId}:启用=启动容器,关闭=停止(新建默认关)。密码{" "}
|
||||
<span className="font-mono text-slate-400">douyinweb</span>
|
||||
。地址须带尾斜杠。
|
||||
。开关跟随容器实态
|
||||
{containerOn && !nekoEnabled && !nekoBusy ? (
|
||||
<span className="text-amber-200/90">(容器在跑,DB 未启用 — 已按运行显示)</span>
|
||||
) : null}
|
||||
。
|
||||
{nekoPollErr ? <span className="ml-2 text-rose-300">({nekoPollErr})</span> : null}
|
||||
</p>
|
||||
|
||||
{/* Remote Neko — always visible UX (paired or empty CTA) */}
|
||||
{/* Remote Neko — prefer + bind */}
|
||||
<div className="mt-2 space-y-2 rounded-lg border border-teal-500/25 bg-teal-500/[0.07] px-2.5 py-2.5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
@ -483,18 +555,20 @@ export function YtRelayProStatusPanel({
|
||||
? `已配对${group.ops_neko_slot ? ` slot #${group.ops_neko_slot}` : ""}${
|
||||
group.ops_neko_edge_label ? ` · ${group.ops_neko_edge_label}` : ""
|
||||
}`
|
||||
: "选择物理机 ops-neko,或先完成 Neko 页配对同步目录"}
|
||||
: "未绑定:可选远程实例;双 VPS 通常只用本机 Neko"}
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/neko"
|
||||
className="shrink-0 rounded-lg border border-teal-400/30 bg-teal-500/10 px-2.5 py-1 text-[10px] text-teal-100 hover:bg-teal-500/20"
|
||||
>
|
||||
打开 Neko Tab
|
||||
</Link>
|
||||
{!remoteBound ? (
|
||||
<Link
|
||||
href="/neko"
|
||||
className="shrink-0 rounded-lg border border-teal-400/30 bg-teal-500/10 px-2.5 py-1 text-[10px] text-teal-100 hover:bg-teal-500/20"
|
||||
>
|
||||
去配对
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[10px] text-slate-400">默认打开</span>
|
||||
<span className="text-[10px] text-slate-400">打开偏好</span>
|
||||
<div className="inline-flex rounded-full border border-white/10 bg-black/30 p-0.5">
|
||||
<button
|
||||
type="button"
|
||||
@ -504,12 +578,12 @@ export function YtRelayProStatusPanel({
|
||||
openPrefer === "local" ? "bg-violet-400/90 text-slate-900" : "text-slate-400"
|
||||
}`}
|
||||
>
|
||||
本机原生
|
||||
本机
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={nekoBusy || !remoteBound}
|
||||
title={remoteBound ? "打开物理机配对实例" : "请先选择远程实例"}
|
||||
title={remoteBound ? "打开远程配对实例" : "请先选择远程实例"}
|
||||
onClick={() => void setPrefer("remote")}
|
||||
className={`rounded-full px-2.5 py-1 text-[10px] ${
|
||||
openPrefer === "remote" && remoteBound
|
||||
@ -524,14 +598,14 @@ export function YtRelayProStatusPanel({
|
||||
</div>
|
||||
{showRemotePicker ? (
|
||||
<label className="block text-[10px] text-slate-400">
|
||||
物理机实例
|
||||
远程实例
|
||||
<select
|
||||
disabled={nekoBusy}
|
||||
value={selectedCatalogId}
|
||||
onChange={(e) => void bindRemote(e.target.value)}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-2.5 py-2 text-[11px] text-slate-100 outline-none focus:ring-1 focus:ring-teal-400/40"
|
||||
>
|
||||
<option value="">— 不绑定(本机原生)—</option>
|
||||
<option value="">— 不绑定(用本机)—</option>
|
||||
{remoteCatalog.map((it) => {
|
||||
const id = String(it.id || `${it.edge_id}:${it.slot}`);
|
||||
const run = Boolean(it.running);
|
||||
@ -547,14 +621,14 @@ export function YtRelayProStatusPanel({
|
||||
</select>
|
||||
{remoteCatalog.length === 0 ? (
|
||||
<span className="mt-1 block text-[10px] text-slate-500">
|
||||
目录为空:请在物理机 Neko 页填入上方域名/Token 并点「配对」。
|
||||
目录为空:未配对对端。双 VPS 可只用本机,忽略此项。
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
{preferredUrl ? (
|
||||
<a
|
||||
href={preferredUrl}
|
||||
@ -563,70 +637,57 @@ export function YtRelayProStatusPanel({
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-violet-500/30 bg-violet-500/10 px-2.5 py-1.5 text-[11px] text-violet-100 hover:bg-violet-500/20"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
打开工作室
|
||||
{pushing && !(nekoState?.studio?.live_page_open)
|
||||
? "打开 Live 控制页"
|
||||
: "打开工作室"}
|
||||
{openPrefer === "remote" && remoteBound ? "(远程)" : "(本机)"}
|
||||
</a>
|
||||
) : null}
|
||||
{localStudioUrl ? (
|
||||
{openPrefer === "remote" && remoteBound && localStudioUrl ? (
|
||||
<a
|
||||
href={localStudioUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 hover:bg-white/10"
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-400 hover:bg-white/10"
|
||||
title="偏好为远程时,仍可另开本机工作室"
|
||||
>
|
||||
本机原生
|
||||
另开本机
|
||||
</a>
|
||||
) : null}
|
||||
{remoteStudioUrl ? (
|
||||
{openPrefer === "local" && remoteStudioUrl ? (
|
||||
<a
|
||||
href={remoteStudioUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-teal-500/30 bg-teal-500/10 px-2.5 py-1.5 text-[11px] text-teal-100 hover:bg-teal-500/20"
|
||||
title="偏好为本机时,仍可另开远程"
|
||||
>
|
||||
远程 Neko
|
||||
另开远程
|
||||
</a>
|
||||
) : (
|
||||
<Link
|
||||
href="/neko"
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-dashed border-teal-500/30 bg-teal-500/[0.06] px-2.5 py-1.5 text-[11px] text-teal-200/80 hover:bg-teal-500/15"
|
||||
) : null}
|
||||
{nekoEnabled ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={nekoBusy}
|
||||
onClick={() => void postNeko({ action: "restart" })}
|
||||
className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 disabled:opacity-40"
|
||||
title="重启本机 Docker Neko(不影响远程)"
|
||||
>
|
||||
去配对远程…
|
||||
</Link>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={nekoBusy || !nekoEnabled}
|
||||
onClick={() => void postNeko({ action: "start" })}
|
||||
className="rounded-lg bg-emerald-500/15 px-2.5 py-1.5 text-[11px] text-emerald-100 disabled:opacity-40"
|
||||
title="仅启停本机原生 Docker Neko,不影响物理机 Tab 实例"
|
||||
>
|
||||
启动本机 Neko
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={nekoBusy}
|
||||
onClick={() => void postNeko({ enabled: false, action: "stop" })}
|
||||
className="rounded-lg bg-rose-500/15 px-2.5 py-1.5 text-[11px] text-rose-100 disabled:opacity-40"
|
||||
>
|
||||
停止本机 Neko
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={nekoBusy || !nekoEnabled}
|
||||
onClick={() => void postNeko({ action: "restart" })}
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-white/5 px-2.5 py-1.5 text-[11px] text-slate-300 disabled:opacity-40"
|
||||
>
|
||||
<RotateCw className="h-3 w-3" />
|
||||
重启本机
|
||||
</button>
|
||||
<RotateCw className="h-3 w-3" />
|
||||
重启本机
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
{(() => {
|
||||
const st = nekoState?.studio;
|
||||
const preferRemote = openPrefer === "remote" && remoteBound;
|
||||
// Show studio analytics whenever we have telemetry OR local neko is up OR remote preferred.
|
||||
if (!st && !nekoState?.ready && !nekoState?.running && !preferRemote) return null;
|
||||
// Show studio analytics whenever we have telemetry OR local neko is up OR remote preferred
|
||||
// OR YouTube is already receiving (FFmpeg push) — receiving-first.
|
||||
const ytReceiving = isLivePushingRow(row);
|
||||
if (!st && !nekoState?.ready && !nekoState?.running && !preferRemote && !ytReceiving) return null;
|
||||
const reports = st?.minute_reports || [];
|
||||
const studioOnAir = Boolean(st?.on_air);
|
||||
const livePageOpen = Boolean(st?.live_page_open);
|
||||
const viewers =
|
||||
st?.viewer_count != null && Number.isFinite(Number(st.viewer_count))
|
||||
? Number(st.viewer_count).toLocaleString()
|
||||
@ -644,7 +705,16 @@ export function YtRelayProStatusPanel({
|
||||
? "本机 Neko 数据"
|
||||
: preferRemote
|
||||
? "远程(等待同步)"
|
||||
: "本机";
|
||||
: ytReceiving && !st
|
||||
? "接流优先"
|
||||
: "本机";
|
||||
// Receiving-first: never imply channel offline when YouTube ingest / FFmpeg is live.
|
||||
const airLabel = studioOnAir
|
||||
? "Studio 开播中"
|
||||
: ytReceiving
|
||||
? "YouTube 接流中"
|
||||
: "Studio 未开播";
|
||||
const airHot = studioOnAir || ytReceiving;
|
||||
return (
|
||||
<div className="mt-3 space-y-2 rounded-lg border border-white/10 bg-black/25 px-2.5 py-2">
|
||||
<div className="flex flex-wrap items-center gap-1.5 text-[10px]">
|
||||
@ -658,6 +728,14 @@ export function YtRelayProStatusPanel({
|
||||
>
|
||||
{srcLabel}
|
||||
</span>
|
||||
{ytReceiving ? (
|
||||
<span
|
||||
className="rounded-md bg-emerald-500/20 px-1.5 py-0.5 text-emerald-100 ring-1 ring-emerald-400/30"
|
||||
title="FFmpeg/业务推流已在向 YouTube 送流(优先于 Studio 页刮数)"
|
||||
>
|
||||
推流接流
|
||||
</span>
|
||||
) : null}
|
||||
{st?.live_status === "signed_out" ? (
|
||||
<span className="rounded-md bg-amber-500/20 px-1.5 py-0.5 text-amber-100 ring-1 ring-amber-400/30">
|
||||
Google 已登出 — 请打开工作室点选账号重新登录
|
||||
@ -665,28 +743,29 @@ export function YtRelayProStatusPanel({
|
||||
) : null}
|
||||
<span
|
||||
className={`rounded-md px-1.5 py-0.5 ring-1 ${
|
||||
st?.live_page_open
|
||||
livePageOpen
|
||||
? "bg-sky-500/15 text-sky-100 ring-sky-400/25"
|
||||
: "bg-white/5 text-slate-500 ring-white/10"
|
||||
}`}
|
||||
title="仅表示 Neko 里 Studio Live 控制页是否打开(刮观看数用)"
|
||||
>
|
||||
Live 页 {st?.live_page_open ? "已打开" : "未打开"}
|
||||
Live 页 {livePageOpen ? "已打开" : "未打开"}
|
||||
</span>
|
||||
<span
|
||||
className={`rounded-md px-1.5 py-0.5 ring-1 ${
|
||||
st?.on_air
|
||||
airHot
|
||||
? "bg-rose-500/20 text-rose-100 ring-rose-400/30"
|
||||
: "bg-white/5 text-slate-500 ring-white/10"
|
||||
}`}
|
||||
>
|
||||
{st?.on_air ? "开播中" : "未开播"}
|
||||
{airLabel}
|
||||
</span>
|
||||
{st?.on_air || liveDur !== "—" ? (
|
||||
{studioOnAir || liveDur !== "—" ? (
|
||||
<span className="rounded-md bg-rose-500/15 px-1.5 py-0.5 font-mono text-rose-100 ring-1 ring-rose-400/25">
|
||||
LIVE {liveDur}
|
||||
</span>
|
||||
) : null}
|
||||
{st?.live_status ? (
|
||||
{st?.live_status && st.live_status !== "signed_out" ? (
|
||||
<span className="rounded-md bg-white/5 px-1.5 py-0.5 text-slate-400 ring-1 ring-white/10">
|
||||
{st.live_status}
|
||||
</span>
|
||||
@ -706,6 +785,14 @@ export function YtRelayProStatusPanel({
|
||||
<span className="text-slate-600">{Math.round(Number(st.age_sec))}s 前</span>
|
||||
) : null}
|
||||
</div>
|
||||
{ytReceiving && !livePageOpen ? (
|
||||
<p className="text-[10px] leading-relaxed text-amber-200/90">
|
||||
YouTube 已在接流;当前刮数源未见 Studio Live 页(观看数为 —)。
|
||||
{remoteBound
|
||||
? "若 Live 开在远程 Neko,请把「打开偏好」切到远程,或点「另开远程」进 Live 控制页。"
|
||||
: "点「打开 Live 控制页」进入本机 Studio Live 即可刮数。"}
|
||||
</p>
|
||||
) : null}
|
||||
{st?.stream_title ? (
|
||||
<p className="truncate text-[10px] text-slate-400" title={st.stream_title}>
|
||||
{st.stream_title}
|
||||
@ -717,13 +804,15 @@ export function YtRelayProStatusPanel({
|
||||
currentViewers={st?.viewer_count}
|
||||
currentTotalViews={st?.total_views}
|
||||
currentDuration={st?.live_duration}
|
||||
onAir={Boolean(st?.on_air)}
|
||||
onAir={studioOnAir || ytReceiving}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-[10px] text-slate-600">
|
||||
{preferRemote
|
||||
? "远程分钟报告同步中(物理机开播约 1 分钟后出现;每 5 秒经目录同步到 VPS)"
|
||||
: "暂无分钟报告(开播后约 1 分钟开始汇总)"}
|
||||
{ytReceiving && !livePageOpen
|
||||
? "接流中但 Live 页未开,暂无分钟报告 — 打开工作室 Live 页约 1 分钟后开始汇总"
|
||||
: preferRemote
|
||||
? "远程分钟报告同步中(对端开播约 1 分钟后出现;每 5 秒经目录同步)"
|
||||
: "暂无分钟报告(Studio 开播后约 1 分钟开始汇总)"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -4,18 +4,55 @@ export function clearAuthRedirect() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON fetch with credentials + default timeout.
|
||||
* @param {string} url
|
||||
* @param {RequestInit & { timeoutMs?: number }} [init]
|
||||
*/
|
||||
export async function fetchJson(url, init) {
|
||||
const apiKey =
|
||||
typeof window !== "undefined" ? window.localStorage.getItem("dy_api_key") || "" : "";
|
||||
const res = await fetch(url, {
|
||||
...init,
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(apiKey ? { "X-API-Key": apiKey } : {}),
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
});
|
||||
const timeoutMs = Number(init?.timeoutMs);
|
||||
const ms =
|
||||
Number.isFinite(timeoutMs) && timeoutMs > 0
|
||||
? timeoutMs
|
||||
: /\/(upload|avatar|sync|import|export|backup)/i.test(String(url))
|
||||
? 60000
|
||||
: 15000;
|
||||
const { timeoutMs: _drop, ...fetchInit } = init || {};
|
||||
const ac = new AbortController();
|
||||
const userSignal = fetchInit.signal;
|
||||
let onUserAbort = null;
|
||||
if (userSignal) {
|
||||
if (userSignal.aborted) ac.abort();
|
||||
else {
|
||||
onUserAbort = () => ac.abort();
|
||||
userSignal.addEventListener("abort", onUserAbort, { once: true });
|
||||
}
|
||||
}
|
||||
const timer = setTimeout(() => ac.abort(), ms);
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
...fetchInit,
|
||||
signal: ac.signal,
|
||||
credentials: "include",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(apiKey ? { "X-API-Key": apiKey } : {}),
|
||||
...(fetchInit.headers || {}),
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
const name = e && e.name;
|
||||
if (name === "AbortError") {
|
||||
throw new Error(`请求超时(${Math.round(ms / 1000)}s),请稍后重试`);
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (userSignal && onUserAbort) userSignal.removeEventListener("abort", onUserAbort);
|
||||
}
|
||||
const text = await res.text();
|
||||
let data = null;
|
||||
try {
|
||||
@ -145,22 +182,30 @@ export function fmtClock(ts) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer channel avatar, then public S3 cover, then API proxy. */
|
||||
/** Prefer channel avatar (trusted public S3), then cover, then API proxy. */
|
||||
export function sessionCoverSrc(session, bust = true) {
|
||||
if (!session) return "";
|
||||
const avatarUrl = String(session.avatar_url || "").trim();
|
||||
const publicUrl = String(session.cover_url || "").trim();
|
||||
const proxyUrl = String(session.cover_proxy_url || "").trim();
|
||||
const fallback = session.id ? `/api/sessions/${session.id}/cover` : "";
|
||||
// Only trust avatar hosts that serve anonymous public objects. Broken dual-edge
|
||||
// hosts (dy.nomadro.com FRP) previously blanked the whole card.
|
||||
const avatarOk =
|
||||
/^https:\/\/s3\.nomadro\.com\//i.test(avatarUrl) ||
|
||||
/^https:\/\/dy\.nomadro\.live\/douyin-covers\//i.test(avatarUrl);
|
||||
const httpOk = (u) =>
|
||||
/^(https?:)\/\//i.test(u) &&
|
||||
!/^https?:\/\/dy\.nomadro\.com\/douyin-covers\//i.test(u);
|
||||
// Channel avatar (S3) first — stream-frame covers are not profile faces.
|
||||
const base =
|
||||
(avatarUrl.startsWith("http://") || avatarUrl.startsWith("https://") ? avatarUrl : "") ||
|
||||
(publicUrl.startsWith("http://") || publicUrl.startsWith("https://") ? publicUrl : "") ||
|
||||
(proxyUrl.startsWith("http://") || proxyUrl.startsWith("https://") ? proxyUrl : "") ||
|
||||
(avatarOk ? avatarUrl : "") ||
|
||||
(httpOk(publicUrl) ? publicUrl : "") ||
|
||||
(httpOk(proxyUrl) ? proxyUrl : "") ||
|
||||
proxyUrl ||
|
||||
fallback ||
|
||||
publicUrl ||
|
||||
avatarUrl ||
|
||||
(avatarOk ? avatarUrl : "") ||
|
||||
"";
|
||||
if (!base) return "";
|
||||
if (!bust) return base;
|
||||
|
||||
@ -33,12 +33,15 @@ const DouyinLiveContext = createContext<{
|
||||
refresh: async () => {},
|
||||
});
|
||||
|
||||
export function useDouyinLiveProviderValue(intervalMs = 25000) {
|
||||
export function useDouyinLiveProviderValue(intervalMs = 35000) {
|
||||
const [map, setMap] = useState<DouyinLiveMap | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { tick, last } = useEventStream(true);
|
||||
const inFlight = useMemo(() => ({ current: false }), []);
|
||||
|
||||
const refresh = useCallback(async (silent = false) => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const data = (await fetchJson("/api/douyin/live-map")) as DouyinLiveMap;
|
||||
@ -46,9 +49,10 @@ export function useDouyinLiveProviderValue(intervalMs = 25000) {
|
||||
} catch {
|
||||
/* keep last map */
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [inFlight]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh(true);
|
||||
|
||||
@ -49,8 +49,11 @@ export function channelLiveRef(channelId: string) {
|
||||
export function useYouTubeLiveProviderValue(intervalMs = 35000) {
|
||||
const [map, setMap] = useState<YouTubeLiveMap | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const inFlight = useMemo(() => ({ current: false }), []);
|
||||
|
||||
const refresh = useCallback(async (silent = false) => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
// 不 force:读服务端后台轮询写入的缓存(约 15–20s 更新)
|
||||
@ -59,9 +62,10 @@ export function useYouTubeLiveProviderValue(intervalMs = 35000) {
|
||||
} catch {
|
||||
/* keep last map */
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
}, [inFlight]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh(true);
|
||||
|
||||
@ -26,6 +26,7 @@ export type RelayMonitorRow = {
|
||||
url_count?: number;
|
||||
douyin_count?: number;
|
||||
has_stream_key?: boolean;
|
||||
stream_key?: string;
|
||||
stream_key_suffix?: string;
|
||||
neko_instance_id?: number;
|
||||
neko_enabled?: boolean;
|
||||
@ -84,6 +85,8 @@ export function businessStatusLabel(row?: RelayMonitorRow): string {
|
||||
if (business === "source_live") return "源已开播";
|
||||
if (business === "monitoring") return "监听中";
|
||||
if (business === "outside_slot") return "时段外";
|
||||
if (business === "paused_exclusive") return "独占暂停";
|
||||
if (business === "paused_studio") return "Studio熔断";
|
||||
if (business === "misconfigured") return "密钥异常";
|
||||
if (business === "youtube_key_rejected") return "密钥被拒";
|
||||
if (business === "stale") return "心跳过期";
|
||||
@ -103,6 +106,9 @@ export function businessStatusBadgeClass(row?: RelayMonitorRow): string {
|
||||
if (business === "waiting_source" || business === "monitoring" || business === "relay_starting" || business === "outside_slot") {
|
||||
return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||
}
|
||||
if (business === "paused_exclusive" || business === "paused_studio") {
|
||||
return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
|
||||
}
|
||||
if (business === "source_live") return "bg-sky-500/15 text-sky-100 ring-sky-500/25";
|
||||
if (business === "misconfigured" || business === "youtube_key_rejected" || business === "error" || business === "stale") {
|
||||
return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
|
||||
|
||||
171
scripts/_align_assign_neko_tm_both.py
Normal file
171
scripts/_align_assign_neko_tm_both.py
Normal file
@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Align assign-neko TM on PHYSICAL + VPS: offline load-extension, never touch Secure Preferences."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
FILES = {
|
||||
"browser-launch.sh": ROOT / "backend/neko/browser-launch.sh",
|
||||
"policies.json": ROOT / "backend/neko/policies/policies.json",
|
||||
"Preferences": ROOT / "backend/neko/tampermonkey-seed/Default/Preferences",
|
||||
"manifest.json": ROOT
|
||||
/ "backend/neko/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json",
|
||||
}
|
||||
|
||||
# Seed TM into profile only (Preferences + Extensions). NEVER Secure Preferences / Cookies.
|
||||
SEED_PROFILE = r'''
|
||||
import json, shutil
|
||||
from pathlib import Path
|
||||
EXT="dhdgffkkebhmkfjojejmpbldmpobfkfo"
|
||||
BASE=Path("/home/neko/.config/google-chrome/Default")
|
||||
SEED=Path("/etc/neko/tampermonkey-seed/Default")
|
||||
SEED_EXT=SEED/"Extensions"/EXT
|
||||
SEED_PREF=SEED/"Preferences"
|
||||
|
||||
def load(p):
|
||||
try: return json.loads(p.read_text(encoding="utf-8"))
|
||||
except Exception: return {}
|
||||
|
||||
if not SEED_EXT.exists():
|
||||
raise SystemExit("NO_SEED_EXT")
|
||||
# copy extension files if missing or empty
|
||||
dst=BASE/"Extensions"/EXT
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
(BASE/"Extensions").mkdir(parents=True, exist_ok=True)
|
||||
shutil.copytree(SEED_EXT, dst)
|
||||
# strip update_url
|
||||
mf=dst/"5.5.0_0"/"manifest.json"
|
||||
if mf.exists():
|
||||
md=load(mf); md.pop("update_url", None)
|
||||
mf.write_text(json.dumps(md, ensure_ascii=False, indent=3)+"\n", encoding="utf-8")
|
||||
# Preferences only — NEVER Secure Preferences
|
||||
seed_entry=((load(SEED_PREF).get("extensions") or {}).get("settings") or {}).get(EXT) or {}
|
||||
entry=dict(seed_entry) if isinstance(seed_entry, dict) else {}
|
||||
entry.update({"state":1,"path":f"{EXT}/5.5.0_0","location":4,"from_webstore":False})
|
||||
entry.pop("disable_reasons", None)
|
||||
mf2=entry.get("manifest")
|
||||
if isinstance(mf2, dict):
|
||||
mf2=dict(mf2); mf2.pop("update_url", None); entry["manifest"]=mf2
|
||||
pref=BASE/"Preferences"
|
||||
d=load(pref) if pref.exists() else {}
|
||||
d.setdefault("extensions",{}).setdefault("settings",{})[EXT]=dict(entry)
|
||||
d.setdefault("extensions",{}).setdefault("ui",{})["developer_mode"]=True
|
||||
pref.write_text(json.dumps(d, separators=(",",":")), encoding="utf-8")
|
||||
print("seeded_tm_ok")
|
||||
'''
|
||||
|
||||
REMOTE_SH = r'''
|
||||
set -e
|
||||
ROOT=/opt/douyinWEB/backend/neko
|
||||
# in-place overwrite (preserve bind-mount inodes)
|
||||
cat /tmp/browser-launch.sh.tmfix > "$ROOT/browser-launch.sh"
|
||||
chmod 755 "$ROOT/browser-launch.sh"
|
||||
cat /tmp/policies.json.tmfix > "$ROOT/policies/policies.json"
|
||||
chmod 644 "$ROOT/policies/policies.json"
|
||||
cat /tmp/Preferences.tmfix > "$ROOT/tampermonkey-seed/Default/Preferences"
|
||||
chmod 644 "$ROOT/tampermonkey-seed/Default/Preferences"
|
||||
MF="$ROOT/tampermonkey-seed/Default/Extensions/dhdgffkkebhmkfjojejmpbldmpobfkfo/5.5.0_0/manifest.json"
|
||||
if [ -f "$MF" ]; then cat /tmp/manifest.json.tmfix > "$MF"; chmod 644 "$MF"; fi
|
||||
|
||||
# ensure chromium policy dirs also get same file if separate mounts exist on host
|
||||
for d in /etc/opt/chrome/policies/managed /etc/chromium/policies/managed /etc/chromium-browser/policies/managed; do
|
||||
if [ -d "$d" ] || [ -L "$d" ]; then
|
||||
mkdir -p "$d" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
echo "=== remount check browser-launch ==="
|
||||
# force container remount of host files by stop/start running assign nekos
|
||||
NAMES=$(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' | sort || true)
|
||||
echo "running: $NAMES"
|
||||
for name in $NAMES; do
|
||||
echo "===== SEED $name ====="
|
||||
docker exec -i "$name" tee /tmp/_seed_tm.py < /tmp/_seed_tm_profile.py >/dev/null
|
||||
docker exec "$name" python3 /tmp/_seed_tm.py || echo SEED_FAIL
|
||||
# verify policy mount
|
||||
docker exec "$name" bash -lc 'ls -la /etc/opt/chrome/policies/managed/policies.json 2>/dev/null || echo NO_POLICY_MOUNT; grep -n Offline /etc/neko/browser-launch.sh | head -3 || echo NO_OFFLINE_IN_LAUNCH'
|
||||
docker exec "$name" supervisorctl restart google-chrome || docker exec "$name" supervisorctl start google-chrome || true
|
||||
done
|
||||
# if none running, still update host assets; operator starts manually
|
||||
sleep 12
|
||||
for name in $NAMES; do
|
||||
echo "===== VERIFY $name ====="
|
||||
docker exec -i "$name" python3 - <<'PY'
|
||||
import json, os, re, urllib.request
|
||||
from pathlib import Path
|
||||
ext="dhdgffkkebhmkfjojejmpbldmpobfkfo"
|
||||
e=((json.loads(Path("/home/neko/.config/google-chrome/Default/Preferences").read_text()).get("extensions") or {}).get("settings") or {}).get(ext) or {}
|
||||
print("tm", e.get("state"), e.get("location"), e.get("from_webstore"), "path", e.get("path"))
|
||||
print("ext", Path(f"/home/neko/.config/google-chrome/Default/Extensions/{ext}/5.5.0_0/manifest.json").exists())
|
||||
found=False
|
||||
for pid in os.listdir("/proc"):
|
||||
if not pid.isdigit(): continue
|
||||
try: cmd=open(f"/proc/{pid}/cmdline","rb").read().replace(b"\x00",b" ").decode()
|
||||
except Exception: continue
|
||||
if "google-chrome" in cmd and "--type=" not in cmd and "load-extension" in cmd:
|
||||
m=re.search(r"--load-extension=([^ ]+)", cmd)
|
||||
print("load_ext", m.group(1) if m else None); found=True; break
|
||||
if not found: print("load_ext NONE")
|
||||
try:
|
||||
tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=4).read())
|
||||
except Exception as ex:
|
||||
print("cdp", ex); tabs=[]
|
||||
print("tm_sw", sum(1 for t in tabs if t.get("type")=="service_worker" and "dhdgff" in (t.get("url") or "")))
|
||||
PY
|
||||
done
|
||||
'''
|
||||
|
||||
|
||||
def do_host(label: str, host: str, port: int, user: str, pw: str, use_sudo: bool) -> None:
|
||||
print(f"\n########## {label} ##########", flush=True)
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
for name, path in FILES.items():
|
||||
with sftp.file(f"/tmp/{name}.tmfix", "wb") as f:
|
||||
f.write(path.read_bytes())
|
||||
print("up", name, flush=True)
|
||||
with sftp.file("/tmp/_seed_tm_profile.py", "wb") as f:
|
||||
f.write(SEED_PROFILE.encode())
|
||||
with sftp.file("/tmp/_align_tm_remote.sh", "wb") as f:
|
||||
f.write(REMOTE_SH.encode())
|
||||
sftp.close()
|
||||
if use_sudo:
|
||||
cmd = f"echo {pw} | sudo -S -p '' bash /tmp/_align_tm_remote.sh"
|
||||
else:
|
||||
cmd = "bash /tmp/_align_tm_remote.sh"
|
||||
_i, o, e = c.exec_command(cmd, timeout=420)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
|
||||
c.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
# Ensure local seed prefs/manifest are offline
|
||||
pref = FILES["Preferences"]
|
||||
import json
|
||||
|
||||
d = json.loads(pref.read_text(encoding="utf-8"))
|
||||
e = d["extensions"]["settings"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]
|
||||
e["location"] = 4
|
||||
e["from_webstore"] = False
|
||||
if isinstance(e.get("manifest"), dict):
|
||||
e["manifest"].pop("update_url", None)
|
||||
pref.write_text(json.dumps(d, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
||||
mf = FILES["manifest.json"]
|
||||
md = json.loads(mf.read_text(encoding="utf-8"))
|
||||
md.pop("update_url", None)
|
||||
mf.write_text(json.dumps(md, ensure_ascii=False, indent=3) + "\n", encoding="utf-8")
|
||||
|
||||
do_host("PHYSICAL", "107.173.30.245", 4014, "eric", "4669805", True)
|
||||
do_host("VPS", "107.173.30.245", 22, "root", "Xiao4669805", False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
148
scripts/_apply_neko_oom_protect.py
Normal file
148
scripts/_apply_neko_oom_protect.py
Normal file
@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply host-level OOM protection to neko-7 processes + hard-restart Chrome with new flags."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def ssh():
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(
|
||||
"107.173.30.245",
|
||||
22,
|
||||
"root",
|
||||
"Xiao4669805",
|
||||
timeout=45,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
banner_timeout=120,
|
||||
)
|
||||
return c
|
||||
|
||||
|
||||
def run(c, cmd, t=180):
|
||||
print(f"\n$ {cmd[:220]}", flush=True)
|
||||
_i, o, e = c.exec_command(cmd, timeout=t)
|
||||
code = o.channel.recv_exit_status()
|
||||
out = (o.read() + e.read()).decode("utf-8", "replace")
|
||||
print(out[-16000:] if len(out) > 16000 else out, flush=True)
|
||||
return code, out
|
||||
|
||||
|
||||
c = ssh()
|
||||
run(
|
||||
c,
|
||||
r"""
|
||||
set -euo pipefail
|
||||
|
||||
# Persist helper: protect all PIDs in neko container cgroup (works without docker recreate).
|
||||
install -m 0755 /dev/stdin /usr/local/sbin/douyinweb-protect-neko-oom <<'EOF'
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
ADJ="${1:--800}"
|
||||
for name in $(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' || true); do
|
||||
cid=$(docker inspect -f '{{.Id}}' "$name")
|
||||
# cgroup v2 path used by docker on this host
|
||||
for base in \
|
||||
"/sys/fs/cgroup/system.slice/docker-${cid}.scope" \
|
||||
"/sys/fs/cgroup/docker/${cid}" \
|
||||
"/sys/fs/cgroup/system.slice/docker-${cid}.scope"
|
||||
do
|
||||
if [ -f "$base/cgroup.procs" ]; then
|
||||
while read -r p; do
|
||||
[ -n "$p" ] || continue
|
||||
echo "$ADJ" > "/proc/$p/oom_score_adj" 2>/dev/null || true
|
||||
done < "$base/cgroup.procs"
|
||||
echo "protected $name via $base adj=$ADJ"
|
||||
fi
|
||||
done
|
||||
# Also main pid
|
||||
main=$(docker inspect -f '{{.State.Pid}}' "$name")
|
||||
if [ -n "$main" ] && [ "$main" != "0" ]; then
|
||||
echo "$ADJ" > "/proc/$main/oom_score_adj" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
EOF
|
||||
|
||||
/usr/local/sbin/douyinweb-protect-neko-oom -800
|
||||
|
||||
# systemd timer every minute — re-apply after chrome spawn
|
||||
cat > /etc/systemd/system/douyinweb-neko-oom-protect.service <<'EOF'
|
||||
[Unit]
|
||||
Description=Protect douyinweb Neko/Chrome from host OOM killer
|
||||
After=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/douyinweb-protect-neko-oom -800
|
||||
EOF
|
||||
cat > /etc/systemd/system/douyinweb-neko-oom-protect.timer <<'EOF'
|
||||
[Unit]
|
||||
Description=Re-apply Neko OOM protection every minute
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=60s
|
||||
AccuracySec=15s
|
||||
Unit=douyinweb-neko-oom-protect.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now douyinweb-neko-oom-protect.timer
|
||||
systemctl start douyinweb-neko-oom-protect.service
|
||||
|
||||
echo ===HARD_RESTART_CHROME===
|
||||
# Kill entire chrome tree; browser-launch.sh loop relaunches with new memory flags.
|
||||
docker exec douyinweb-neko-7 sh -c 'pkill -9 -f /opt/google/chrome/chrome 2>/dev/null; pkill -9 chrome 2>/dev/null; true' || true
|
||||
sleep 8
|
||||
|
||||
cd /opt/douyinWEB/backend
|
||||
./.venv/bin/python - <<'PY'
|
||||
import json, time, subprocess
|
||||
from app import youtube_neko as yn
|
||||
nid=7
|
||||
for i in range(30):
|
||||
tabs=yn._cdp_fetch_tabs(nid)
|
||||
pages=[t for t in tabs if (t.get("type") or "page")=="page"]
|
||||
print("wait", i, len(pages))
|
||||
if pages:
|
||||
break
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise SystemExit("chrome_did_not_return")
|
||||
|
||||
# re-protect after spawn
|
||||
subprocess.check_call(["/usr/local/sbin/douyinweb-protect-neko-oom", "-800"])
|
||||
|
||||
studio="https://studio.youtube.com/video/xmwiN6n4d9Q/livestreaming"
|
||||
print(yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio))
|
||||
time.sleep(8)
|
||||
sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0)
|
||||
print("sig", json.dumps({k:sig.get(k) for k in ("ok","control_ready","live_status","on_air","url")}, ensure_ascii=False))
|
||||
print("text_head", str(sig.get("text") or "")[:200].replace("\n"," | "))
|
||||
|
||||
# verify cmdline has renderer-process-limit
|
||||
code,out=yn._run(["docker","exec",yn._container_name(nid),"sh","-c",
|
||||
"tr '\\0' '\\n' </proc/1/cmdline 2>/dev/null; for p in /proc/[0-9]*; do c=$(tr '\\0' ' ' <$p/cmdline 2>/dev/null); case \"$c\" in *chrome*--type=zygote*|*chrome*--user-data-dir*) echo OOM=$(cat $p/oom_score_adj 2>/dev/null) $c | head -c 220; echo;; esac; done | head -20"], timeout=20)
|
||||
print(out[:2500])
|
||||
# host view of container main oom
|
||||
import os
|
||||
main=int(subprocess.check_output(["docker","inspect","-f","{{.State.Pid}}","douyinweb-neko-7"], text=True).strip() or 0)
|
||||
print("main_pid", main, "oom", open(f"/proc/{main}/oom_score_adj").read().strip() if main else None)
|
||||
PY
|
||||
|
||||
free -h
|
||||
swapon --show
|
||||
systemctl is-active sing-box frpp 'wg-quick@wg-dy' douyinweb-neko-oom-protect.timer
|
||||
""",
|
||||
)
|
||||
c.close()
|
||||
print("DONE", time.strftime("%H:%M:%S"))
|
||||
72
scripts/_apply_shorts_gap_settings.py
Normal file
72
scripts/_apply_shorts_gap_settings.py
Normal file
@ -0,0 +1,72 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Set Shorts gap settings to 10min via API; report quota board. Do not toggle shorts_enabled."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import http.cookiejar
|
||||
import urllib.request
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def session(base: str):
|
||||
cj = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode()
|
||||
req = urllib.request.Request(
|
||||
base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"}
|
||||
)
|
||||
op.open(req, timeout=30)
|
||||
return op
|
||||
|
||||
|
||||
def call(op, base, path, method="GET", body=None, timeout=40):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(
|
||||
base + path,
|
||||
data=data,
|
||||
method=method,
|
||||
headers={"Content-Type": "application/json"} if body is not None else {},
|
||||
)
|
||||
with op.open(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode())
|
||||
|
||||
|
||||
for base in ("https://dy.nomadro.com", "https://dylive.nomadro.com"):
|
||||
print(f"\n===== {base} =====")
|
||||
op = session(base)
|
||||
before = call(op, base, "/api/shorts/status")
|
||||
print(
|
||||
"before enabled=", before.get("enabled"),
|
||||
"ch_gap=", before.get("channel_min_gap_sec"),
|
||||
"up_gap=", before.get("upload_min_gap_sec"),
|
||||
"board_gap=", (before.get("board") or {}).get("total_gap"),
|
||||
"min_unmet=", (before.get("board") or {}).get("min_unmet"),
|
||||
)
|
||||
# Only change gap rules — never flip shorts_enabled here.
|
||||
patched = call(
|
||||
op,
|
||||
base,
|
||||
"/api/settings",
|
||||
method="PATCH",
|
||||
body={
|
||||
"shorts_channel_min_gap_sec": 600,
|
||||
"shorts_upload_min_gap_sec": 600,
|
||||
"shorts_dedupe_room_day": True,
|
||||
},
|
||||
)
|
||||
print("patched keys ok=", bool(patched))
|
||||
after = call(op, base, "/api/shorts/status")
|
||||
print(
|
||||
"after enabled=", after.get("enabled"),
|
||||
"ch_gap=", after.get("channel_min_gap_sec"),
|
||||
"up_gap=", after.get("upload_min_gap_sec"),
|
||||
)
|
||||
board = after.get("board") or {}
|
||||
chans = board.get("channels") or []
|
||||
unmet = [c for c in chans if c.get("enabled") and not c.get("min_met")]
|
||||
print("min_unmet_count=", len(unmet), "total_gap=", board.get("total_gap"), "push_date=", board.get("push_date"))
|
||||
for c in unmet[:8]:
|
||||
print(" ", c.get("name"), "used=", c.get("used"), "min=", c.get("daily_min"), "max=", c.get("daily_max"))
|
||||
print("done")
|
||||
118
scripts/_audit_dual_fleet_health.py
Normal file
118
scripts/_audit_dual_fleet_health.py
Normal file
@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fleet self-check: dy + dylive neko chrome, mounts, API. Never recreate Neko."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOSTS = [
|
||||
("dylive", "107.173.30.245"),
|
||||
("dy", "108.174.50.68"),
|
||||
]
|
||||
|
||||
|
||||
def connect(host: str):
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(8):
|
||||
try:
|
||||
c.connect(
|
||||
host,
|
||||
22,
|
||||
"root",
|
||||
"Xiao4669805",
|
||||
timeout=40,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
banner_timeout=120,
|
||||
)
|
||||
return c
|
||||
except Exception as e:
|
||||
print(f"ssh_retry {host} {i}: {e}", flush=True)
|
||||
time.sleep(2 + i)
|
||||
raise SystemExit(f"ssh_fail {host}")
|
||||
|
||||
|
||||
SCRIPT = r"""
|
||||
set +e
|
||||
echo '=== host ==='
|
||||
hostname; free -m | head -2; uptime
|
||||
systemctl is-active douyinweb-api douyinweb-web 2>/dev/null
|
||||
curl -sS -m 8 -o /dev/null -w 'api_health:%{http_code}\n' http://127.0.0.1:8014/api/health
|
||||
curl -sS -m 8 -o /dev/null -w 'fe_youtube:%{http_code}\n' http://127.0.0.1:4015/youtube
|
||||
|
||||
echo '=== browser-launch host ==='
|
||||
file /opt/douyinWEB/backend/neko/browser-launch.sh 2>/dev/null || ls -la /opt/douyinWEB/backend/neko/browser-launch.sh
|
||||
head -1 /opt/douyinWEB/backend/neko/browser-launch.sh | od -c | head -2
|
||||
grep -n 'jitless\|no-turbofan\|PassageEmbeddings\|no-wasm-simd' /opt/douyinWEB/backend/neko/browser-launch.sh | head -10
|
||||
sh -n /opt/douyinWEB/backend/neko/browser-launch.sh && echo launch_syntax_ok || echo launch_syntax_BAD
|
||||
|
||||
echo '=== neko containers ==='
|
||||
docker ps -a --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V
|
||||
|
||||
echo '=== running neko chrome/supervisor ==='
|
||||
for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | sort -V); do
|
||||
echo "--- $n ---"
|
||||
# deleted mount?
|
||||
del=$(docker exec "$n" sh -c 'cat /proc/self/mountinfo 2>/dev/null | grep browser-launch' | grep -c '//deleted' || true)
|
||||
echo "browser_launch_deleted_mount=$del"
|
||||
docker exec "$n" sh -c 'grep -n jitless /etc/neko/browser-launch.sh 2>/dev/null | head -1; sh -n /etc/neko/browser-launch.sh 2>/dev/null && echo syntax_ok || echo syntax_BAD'
|
||||
st=$(docker exec "$n" supervisorctl status google-chrome 2>/dev/null | head -1)
|
||||
echo "chrome: $st"
|
||||
cdp=$(docker exec "$n" sh -c 'curl -sS -m 2 http://127.0.0.1:9222/json/version 2>/dev/null' | head -c 80)
|
||||
echo "cdp: ${cdp:-FAIL}"
|
||||
done
|
||||
|
||||
echo '=== assign neko_enabled vs running ==='
|
||||
cd /opt/douyinWEB/backend
|
||||
./.venv/bin/python - <<'PY'
|
||||
from app import yt_assign_db, db
|
||||
cfg = db.get_settings_map()
|
||||
print('auto', bool(cfg.get('youtube_relay_enabled') or cfg.get('youtube_relay_auto')))
|
||||
# try common keys
|
||||
for k in ('youtube_relay_enabled','youtube_relay_pipeline_enabled','youtube_relay_auto_push'):
|
||||
if k in cfg: print(k, cfg.get(k))
|
||||
print('time_slot', cfg.get('youtube_relay_time_slot_mode'))
|
||||
print('exclusive', cfg.get('youtube_relay_exclusive_live'))
|
||||
en=[]
|
||||
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
|
||||
nid=int(g.get('neko_instance_id') or 0)
|
||||
if g.get('neko_enabled'):
|
||||
en.append((g.get('name'), nid, g.get('category')))
|
||||
print('neko_enabled', en)
|
||||
PY
|
||||
|
||||
echo '=== relay status snippet ==='
|
||||
CS=$(mktemp)
|
||||
curl -sS -m 15 -c "$CS" -b "$CS" -X POST http://127.0.0.1:8014/api/auth/login \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"username":"hackrobot","password":"Xiao4669805@"}' >/dev/null
|
||||
curl -sS -m 15 -b "$CS" http://127.0.0.1:8014/api/youtube/relay/status | python3 - <<'PY'
|
||||
import sys,json
|
||||
d=json.load(sys.stdin)
|
||||
print('enabled', d.get('enabled'), 'running', d.get('running'), 'pushing', d.get('pushing_count'))
|
||||
print('douyin_live', d.get('douyin_live_count'), 'winner', d.get('exclusive_winner_group_id'))
|
||||
s=d.get('settings') or {}
|
||||
print('slot', s.get('youtube_relay_time_slot_mode'), 'excl', s.get('youtube_relay_exclusive_live'))
|
||||
print('err', (d.get('last_error') or '')[:200])
|
||||
PY
|
||||
|
||||
echo '=== FE marker ==='
|
||||
grep -Rnl '普通频道 · 在播抖音' /opt/douyinWEB/frontend/src/components/YtAssignPanel.tsx 2>/dev/null | head -1
|
||||
grep -Rnl '普通频道 · 在播抖音' /opt/douyinWEB/frontend/.next/static 2>/dev/null | head -2 || echo 'marker_not_in_static_or_missing_build'
|
||||
|
||||
echo HOST_CHECK_DONE
|
||||
"""
|
||||
|
||||
for label, host in HOSTS:
|
||||
print(f"\n######## {label} {host} ########", flush=True)
|
||||
c = connect(host)
|
||||
_i, o, e = c.exec_command(SCRIPT, timeout=240)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
|
||||
c.close()
|
||||
|
||||
print("ALL_HOSTS_DONE", flush=True)
|
||||
88
scripts/_audit_fix_neko6_remount_dy_api.py
Normal file
88
scripts/_audit_fix_neko6_remount_dy_api.py
Normal file
@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ops: remount browser-launch on dylive neko-6 + check dy API. Never recreate."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def connect(host: str):
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(10):
|
||||
try:
|
||||
c.connect(
|
||||
host,
|
||||
22,
|
||||
"root",
|
||||
"Xiao4669805",
|
||||
timeout=60,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
banner_timeout=300,
|
||||
)
|
||||
return c
|
||||
except Exception as e:
|
||||
print("retry", host, i, e, flush=True)
|
||||
time.sleep(2 + i)
|
||||
raise SystemExit(f"ssh_fail {host}")
|
||||
|
||||
|
||||
# --- dylive: remount browser-launch via container restart (volumes keep profile) ---
|
||||
print("=== dylive neko-6 remount ===", flush=True)
|
||||
dl = connect("107.173.30.245")
|
||||
_i, o, e = dl.exec_command(
|
||||
r"""
|
||||
set +e
|
||||
NAME=douyinweb-neko-6
|
||||
# ensure host launch script is LF + jitless
|
||||
sed -i 's/\r$//' /opt/douyinWEB/backend/neko/browser-launch.sh
|
||||
grep -n jitless /opt/douyinWEB/backend/neko/browser-launch.sh | head -1
|
||||
# restart remounts binds (NOT recreate)
|
||||
docker restart "$NAME"
|
||||
sleep 12
|
||||
docker exec "$NAME" sh -c 'cat /proc/self/mountinfo | grep browser-launch'
|
||||
del=$(docker exec "$NAME" sh -c 'cat /proc/self/mountinfo | grep browser-launch' | grep -c '//deleted' || true)
|
||||
echo deleted_mount=$del
|
||||
docker exec "$NAME" supervisorctl status
|
||||
docker exec "$NAME" sh -c 'curl -sS -m 5 http://127.0.0.1:9222/json/version | head -c 180; echo'
|
||||
# if chrome fatal, start again
|
||||
st=$(docker exec "$NAME" supervisorctl status google-chrome 2>/dev/null)
|
||||
echo "$st"
|
||||
case "$st" in
|
||||
*FATAL*|*STOPPED*)
|
||||
docker exec "$NAME" sh -c 'rm -f /home/neko/.config/google-chrome/Singleton*; supervisorctl start google-chrome; sleep 8; supervisorctl status google-chrome; curl -sS -m 5 http://127.0.0.1:9222/json/version | head -c 120; echo'
|
||||
;;
|
||||
esac
|
||||
free -m | head -2
|
||||
echo DYLIVE_OK
|
||||
""",
|
||||
timeout=180,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
|
||||
dl.close()
|
||||
|
||||
# --- dy: API hang diagnose ---
|
||||
print("=== dy API diagnose ===", flush=True)
|
||||
dy = connect("108.174.50.68")
|
||||
_i, o, e = dy.exec_command(
|
||||
r"""
|
||||
set +e
|
||||
systemctl is-active douyinweb-api douyinweb-web
|
||||
free -m | head -2
|
||||
ss -lntp | grep -E ':8014|:4015' || true
|
||||
timeout 5 curl -sS -m 4 -o /dev/null -w 'health:%{http_code} time:%{time_total}\n' http://127.0.0.1:8014/api/health || echo health_timeout
|
||||
journalctl -u douyinweb-api -n 40 --no-pager 2>/dev/null | tail -40
|
||||
# if hung workers, show top
|
||||
ps aux --sort=-%mem | head -15
|
||||
echo DY_OK
|
||||
""",
|
||||
timeout=90,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
|
||||
dy.close()
|
||||
print("DONE", flush=True)
|
||||
71
scripts/_audit_post_smoke.py
Normal file
71
scripts/_audit_post_smoke.py
Normal file
@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Post-audit smoke: dy + dylive health, neko chrome, relay flags."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from http.cookiejar import CookieJar
|
||||
import ssl
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
CTX = ssl.create_default_context()
|
||||
|
||||
|
||||
def ssh(host: str):
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(host, 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120)
|
||||
return c
|
||||
|
||||
|
||||
def run(c, cmd: str) -> str:
|
||||
_i, o, e = c.exec_command(cmd, timeout=90)
|
||||
return (o.read() + e.read()).decode("utf-8", "replace")
|
||||
|
||||
|
||||
for label, host in (("dylive", "107.173.30.245"), ("dy", "108.174.50.68")):
|
||||
print(f"\n## {label}", flush=True)
|
||||
c = ssh(host)
|
||||
print(run(c, r"""
|
||||
set +e
|
||||
free -m | head -2
|
||||
systemctl is-active douyinweb-api douyinweb-web
|
||||
curl -sS -m 10 -o /dev/null -w 'health:%{http_code}\n' http://127.0.0.1:8014/api/health
|
||||
curl -sS -m 10 -o /dev/null -w 'youtube:%{http_code}\n' http://127.0.0.1:4015/youtube
|
||||
docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort -V
|
||||
for n in $(docker ps --filter name=douyinweb-neko --format '{{.Names}}'); do
|
||||
st=$(docker exec "$n" supervisorctl status google-chrome 2>/dev/null | awk '{print $1,$2}')
|
||||
del=$(docker exec "$n" sh -c 'grep -c "//deleted" /proc/self/mountinfo' 2>/dev/null || echo 0)
|
||||
echo "$n chrome=[$st] deleted_mount_hits=$del"
|
||||
done
|
||||
cd /opt/douyinWEB/backend
|
||||
./.venv/bin/python - <<'PY'
|
||||
from app import db
|
||||
cfg=db.get_settings_map()
|
||||
print('relay_enabled', cfg.get('youtube_relay_enabled'))
|
||||
print('time_slot', cfg.get('youtube_relay_time_slot_mode'))
|
||||
print('exclusive', cfg.get('youtube_relay_exclusive_live'))
|
||||
PY
|
||||
grep -n 'paused_exclusive' /opt/douyinWEB/backend/app/youtube_relay_status.py | head -2
|
||||
grep -n 'time_slot_mode on but no time_slot' /opt/douyinWEB/backend/app/youtube_relay_pipeline.py | head -1
|
||||
"""), flush=True)
|
||||
c.close()
|
||||
|
||||
print("\n## public", flush=True)
|
||||
for base in ("https://dylive.nomadro.com", "https://dy.nomadro.live"):
|
||||
try:
|
||||
jar = CookieJar()
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar), urllib.request.HTTPSHandler(context=CTX))
|
||||
req = urllib.request.Request(f"{base}/api/auth/login", data=json.dumps({"username":"hackrobot","password":"Xiao4669805@"}).encode(), headers={"Content-Type":"application/json"}, method="POST")
|
||||
with opener.open(req, timeout=20) as r:
|
||||
print(base, "login", r.status, flush=True)
|
||||
with opener.open(urllib.request.Request(f"{base}/api/health"), timeout=15) as r:
|
||||
print(base, "health", r.status, flush=True)
|
||||
except Exception as e:
|
||||
print(base, "ERR", e, flush=True)
|
||||
|
||||
print("SMOKE_DONE", flush=True)
|
||||
121
scripts/_audit_project_health_dual.py
Normal file
121
scripts/_audit_project_health_dual.py
Normal file
@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Broad read-only health sweep: dy + dylive (live/neko/shorts/yt-long/disk/quota)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
PASS = "Xiao4669805"
|
||||
HOSTS = [("dy", "108.174.50.68"), ("dylive", "107.173.30.245")]
|
||||
|
||||
REMOTE = r'''
|
||||
set +e
|
||||
echo "=== host $(hostname) $(date -Is) ==="
|
||||
echo "-- mem --"
|
||||
free -h | head -3
|
||||
echo "-- disk --"
|
||||
df -h / /opt /var/lib/docker 2>/dev/null | head -10
|
||||
echo "-- units --"
|
||||
for u in douyinweb-api douyinweb-web douyinweb-yt douyinweb-pb; do
|
||||
printf '%s ' "$u"; systemctl is-active "$u" 2>/dev/null; done
|
||||
echo
|
||||
echo "-- neko containers --"
|
||||
docker ps -a --format '{{.Names}}\t{{.Status}}' 2>/dev/null | grep -i neko | sort
|
||||
echo "-- oom/kill recent (journal 6h) --"
|
||||
journalctl --since '6 hours ago' --no-pager 2>/dev/null | grep -iE 'Out of memory|oom-kill|Killed process|SIGILL|neko.*(exit|restart)|douyinweb-neko' | tail -25
|
||||
echo "-- api relay/shorts/ytlong via python --"
|
||||
cd /opt/douyinWEB/backend && .venv/bin/python <<'PY'
|
||||
import json, time
|
||||
from app import db
|
||||
from app.youtube_relay_pipeline import youtube_relay_pipeline
|
||||
from app import yt_long_db
|
||||
from app.shorts_yt_quota import quota_budgets_by_profile
|
||||
from app.timeutil import push_date_from_ts
|
||||
try:
|
||||
from app import youtube_neko
|
||||
except Exception as e:
|
||||
youtube_neko = None
|
||||
print("neko_import_err", e)
|
||||
|
||||
cfg = db.get_settings_map()
|
||||
day = push_date_from_ts(time.time())
|
||||
print("day", day)
|
||||
print("relay_enabled", cfg.get("youtube_relay_enabled"), "exclusive", cfg.get("youtube_relay_exclusive_live"))
|
||||
print("shorts_pipeline", cfg.get("shorts_enabled"), cfg.get("shorts_pipeline_enabled"))
|
||||
print("yt_long", cfg.get("yt_long_enabled"), "disk_min", cfg.get("clips_min_free_gb"))
|
||||
print("limited_day", cfg.get("yt_long_quota_limited_day"), str(cfg.get("yt_long_quota_limited_reason") or "")[:120])
|
||||
st = youtube_relay_pipeline.status()
|
||||
print("relay_running", st.get("running"), "pushing", st.get("pushing_count"), "winner", st.get("exclusive_winner_group_id"))
|
||||
# neko mismatch: running vs enabled
|
||||
try:
|
||||
from app import yt_assign_db
|
||||
groups = yt_assign_db.list_groups(include_urls=False)
|
||||
print("assign_groups", len(groups))
|
||||
mismatch = []
|
||||
for g in groups:
|
||||
nid = int(g.get("neko_instance_id") or 0)
|
||||
if nid < 1:
|
||||
continue
|
||||
en = bool(g.get("neko_enabled"))
|
||||
state = youtube_neko._container_state(nid, check_http=False) if youtube_neko else {}
|
||||
run = bool(state.get("running"))
|
||||
if en != run:
|
||||
mismatch.append((g.get("name"), nid, "enabled", en, "running", run, state.get("status")))
|
||||
print("neko_enabled_vs_running_mismatch", len(mismatch))
|
||||
for row in mismatch[:12]:
|
||||
print(" ", row)
|
||||
except Exception as e:
|
||||
print("neko_mismatch_err", e)
|
||||
print("yt_quota_budgets", json.dumps(quota_budgets_by_profile(cfg), ensure_ascii=False)[:900])
|
||||
print("yt_long_upload_used", yt_long_db.yt_long_upload_used(day), "daily_max", yt_long_db.yt_long_daily_max(cfg))
|
||||
try:
|
||||
s = db.shorts_channels_quota_summary(day)
|
||||
print("shorts_uploaded_sum", sum(int(r.get("uploaded") or 0) for r in s), "channels", len(s), "gap", sum(int(r.get("gap") or 0) for r in s))
|
||||
except Exception as e:
|
||||
print("shorts_err", e)
|
||||
# stuck jobs sample
|
||||
try:
|
||||
for stname in ("uploading", "recording", "pending"):
|
||||
d = db.list_shorts_jobs(push_date=day, status=stname, limit=5, offset=0)
|
||||
print(f"shorts_{stname}", d.get("total"), "sample", [ (j.get("id"), j.get("channel_name") or j.get("anchor_name"), j.get("error")) for j in (d.get("jobs") or [])[:3]])
|
||||
except Exception as e:
|
||||
print("jobs_err", e)
|
||||
try:
|
||||
for stname in ("uploading", "recording", "scheduled", "pending"):
|
||||
d = yt_long_db.list_yt_long_jobs_page(status=stname, push_date=day, limit=5, offset=0)
|
||||
print(f"ytlong_{stname}", d.get("total"))
|
||||
except Exception as e:
|
||||
print("ytlong_jobs_err", e)
|
||||
PY
|
||||
echo "-- ffmpeg count --"
|
||||
ps -eo pid,etime,cmd | grep -E '[f]fmpeg' | wc -l
|
||||
echo "-- last api errors 2h --"
|
||||
journalctl -u douyinweb-api --since '2 hours ago' --no-pager 2>/dev/null | grep -iE 'ERROR|Traceback|QUOTA|OOM|timeout|neko wait blocked|studio_not_on_air' | tail -30
|
||||
'''
|
||||
|
||||
|
||||
def run_host(label: str, host: str) -> None:
|
||||
print(f"\n########## {label} {host} ##########", flush=True)
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(8):
|
||||
try:
|
||||
c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90)
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"ssh_retry {i}: {e}", flush=True)
|
||||
time.sleep(2 + i)
|
||||
else:
|
||||
print("ssh_fail", flush=True)
|
||||
return
|
||||
_, o, e = c.exec_command(REMOTE, timeout=120)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
|
||||
c.close()
|
||||
|
||||
|
||||
for label, host in HOSTS:
|
||||
run_host(label, host)
|
||||
52
scripts/_check_cookie_keys_both.py
Normal file
52
scripts/_check_cookie_keys_both.py
Normal file
@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
PHYS = ("107.173.30.245", 4014, "eric", "4669805")
|
||||
VPS = ("107.173.30.245", 22, "root", "Xiao4669805")
|
||||
|
||||
SQL = r'''
|
||||
python3 - <<'PY'
|
||||
import sqlite3, json
|
||||
c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db")
|
||||
keys=c.execute("SELECT key FROM kv_settings ORDER BY 1").fetchall()
|
||||
interesting=[k[0] for k in keys if any(x in k[0].lower() for x in ("cookie","oauth","token","proxy"))]
|
||||
print("interesting_keys", interesting)
|
||||
for k in interesting:
|
||||
v=c.execute("SELECT value FROM kv_settings WHERE key=?",(k,)).fetchone()[0]
|
||||
try:
|
||||
parsed=json.loads(v)
|
||||
if isinstance(parsed,str):
|
||||
print(k, "str_len", len(parsed))
|
||||
elif isinstance(parsed,list):
|
||||
print(k, "list_len", len(parsed))
|
||||
elif isinstance(parsed,dict):
|
||||
print(k, "dict_keys", list(parsed.keys())[:12])
|
||||
else:
|
||||
print(k, type(parsed).__name__, str(parsed)[:80])
|
||||
except Exception:
|
||||
print(k, "raw_len", len(v or ""))
|
||||
# rooms / shorts sample
|
||||
print("rooms", c.execute("select count(*) from rooms").fetchone()[0])
|
||||
print("shorts", [(r[0], r[1], bool(r[2]), len(r[3] or "")) for r in c.execute("select id,name,oauth_ok,refresh_token from shorts_channels limit 5")])
|
||||
print("assign", [(r[0], r[1], len(r[2] or ""), r[3]) for r in c.execute("select id,name,stream_key,neko_enabled from yt_assign_groups")])
|
||||
c.close()
|
||||
PY
|
||||
'''
|
||||
|
||||
|
||||
def run(spec, cmd):
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(*spec, timeout=40, banner_timeout=80, allow_agent=False, look_for_keys=False)
|
||||
_i, o, e = c.exec_command(cmd, timeout=60)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
c.close()
|
||||
|
||||
|
||||
print("=== PHYSICAL ===")
|
||||
run(PHYS, f"echo '4669805' | sudo -S -p '' bash -lc {repr(SQL)}")
|
||||
print("=== DYLIVE ===")
|
||||
run(VPS, SQL)
|
||||
32
scripts/_check_dy_neko7_now.py
Normal file
32
scripts/_check_dy_neko7_now.py
Normal file
@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=180)
|
||||
_i, o, e = c.exec_command(
|
||||
r"""
|
||||
set +e
|
||||
docker exec douyinweb-neko-7 python3 -c '
|
||||
import json,urllib.request
|
||||
tabs=json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list",timeout=5).read())
|
||||
for t in tabs:
|
||||
if t.get("type")=="page":
|
||||
print((t.get("title") or "")[:80])
|
||||
print(" ", (t.get("url") or "")[:120])
|
||||
'
|
||||
echo '---'
|
||||
# stop unexpected neko-8 if we did not need it
|
||||
docker stop douyinweb-neko-8 2>/dev/null && echo stopped_neko8 || true
|
||||
docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}'
|
||||
dmesg -T 2>/dev/null | grep -i 'invalid opcode' | tail -2
|
||||
curl -sk -o /dev/null -w 'neko7:%{http_code}\n' https://dy.nomadro.live/neko/7/
|
||||
""",
|
||||
timeout=60,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
c.close()
|
||||
9
scripts/_check_dy_svc.py
Normal file
9
scripts/_check_dy_svc.py
Normal file
@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko, sys
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
|
||||
i, o, e = c.exec_command("systemctl is-active douyinweb-api; systemctl is-active douyinweb-web", timeout=30)
|
||||
print("dy_svc:", o.read().decode().strip().replace("\n", " / "))
|
||||
c.close()
|
||||
92
scripts/_check_dylive_after_neko_sync.py
Normal file
92
scripts/_check_dylive_after_neko_sync.py
Normal file
@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only health check on dylive after youtube_neko sync — no changes."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
HOST = "107.173.30.245"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
|
||||
def main():
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(6):
|
||||
try:
|
||||
c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||
break
|
||||
except Exception as e:
|
||||
print(e, flush=True)
|
||||
time.sleep(1 + i)
|
||||
else:
|
||||
raise SystemExit("ssh_fail")
|
||||
|
||||
cmd = r"""
|
||||
echo '=== units ==='
|
||||
for u in douyinweb-api douyinweb-web douyinweb-pb douyinweb-yt; do
|
||||
printf '%-18s %s\n' "$u" "$(systemctl is-active $u 2>/dev/null)"
|
||||
done
|
||||
echo '=== hash marker ==='
|
||||
grep -n 'relay may leave Chrome\|_neko_ids_for_cdp_poll\|Evidence-first' /opt/douyinWEB/backend/app/youtube_neko.py | head -10
|
||||
echo '=== api smoke ==='
|
||||
curl -sS -m 8 http://127.0.0.1:8014/api/health || true
|
||||
echo
|
||||
cd /opt/douyinWEB/backend
|
||||
./.venv/bin/python - <<'PY'
|
||||
import json
|
||||
from app import youtube_neko, yt_assign_db
|
||||
ids = youtube_neko._neko_ids_for_cdp_poll()
|
||||
print('cdp_poll_ids', ids)
|
||||
# enabled groups still included
|
||||
enabled=[]
|
||||
running_disabled=[]
|
||||
for g in yt_assign_db.list_groups(include_urls=False):
|
||||
nid=int(g.get('neko_instance_id') or 0)
|
||||
if nid<1: continue
|
||||
en=bool(g.get('neko_enabled'))
|
||||
try:
|
||||
run=bool(youtube_neko._container_state(nid, check_http=False).get('running'))
|
||||
except Exception:
|
||||
run=False
|
||||
if en: enabled.append(nid)
|
||||
if (not en) and run: running_disabled.append(nid)
|
||||
print('enabled_neko_ids', sorted(set(enabled)))
|
||||
print('running_disabled_ids', sorted(set(running_disabled)))
|
||||
# any active relay row studio snap
|
||||
try:
|
||||
from app.youtube_relay_pipeline import youtube_relay_pipeline
|
||||
st = youtube_relay_pipeline.status() if hasattr(youtube_relay_pipeline,'status') else None
|
||||
except Exception as e:
|
||||
st=None
|
||||
print('relay_status_err', type(e).__name__, str(e)[:120])
|
||||
# light: groups with running neko + snap
|
||||
for g in yt_assign_db.list_groups(include_urls=False):
|
||||
nid=int(g.get('neko_instance_id') or 0)
|
||||
if nid not in ids:
|
||||
continue
|
||||
snap=youtube_neko.studio_snapshot_for_group(g, max_age_sec=180)
|
||||
print('SNAP', g.get('name'), 'neko', nid, 'en', g.get('neko_enabled'),
|
||||
'page', snap.get('live_page_open'), 'air', snap.get('on_air'),
|
||||
'viewers', snap.get('viewer_count'), 'src', snap.get('detect_source') or snap.get('ui_source'))
|
||||
PY
|
||||
echo '=== ffmpeg ==='
|
||||
pgrep -c ffmpeg || echo 0
|
||||
echo '=== neko running ==='
|
||||
docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' 2>/dev/null
|
||||
"""
|
||||
_i, o, e = c.exec_command(cmd, timeout=90)
|
||||
print(o.read().decode("utf-8", "replace"), flush=True)
|
||||
err = e.read().decode("utf-8", "replace")
|
||||
if err.strip():
|
||||
print("[stderr]", err[:1500], flush=True)
|
||||
c.close()
|
||||
print("CHECK_DONE", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
42
scripts/_check_dylive_neko_after_stop.py
Normal file
42
scripts/_check_dylive_neko_after_stop.py
Normal file
@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check dylive neko fleet after WP stop."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(
|
||||
"107.173.30.245",
|
||||
22,
|
||||
"root",
|
||||
"Xiao4669805",
|
||||
timeout=50,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
banner_timeout=180,
|
||||
)
|
||||
_i, o, e = c.exec_command(
|
||||
r"""
|
||||
set +e
|
||||
docker ps -a --filter name=douyinweb-neko --format '{{.Names}}\t{{.Status}}'
|
||||
echo '---'
|
||||
free -m | head -2
|
||||
# which assign has neko 12 / 19
|
||||
cd /opt/douyinWEB/backend
|
||||
./.venv/bin/python - <<'PY'
|
||||
from app import yt_assign_db
|
||||
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
|
||||
nid = g.get('neko_instance_id')
|
||||
if nid in (12, 18, 19) or g.get('neko_enabled'):
|
||||
print(g.get('name'), 'neko', nid, 'en', g.get('neko_enabled'), 'cat', g.get('category'))
|
||||
PY
|
||||
""",
|
||||
timeout=60,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
c.close()
|
||||
20
scripts/_check_dylive_oauth_uri.py
Normal file
20
scripts/_check_dylive_oauth_uri.py
Normal file
@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
import json, sys, paramiko
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False)
|
||||
cmd = r'''python3 - <<'PY'
|
||||
import sqlite3, json
|
||||
c=sqlite3.connect("/opt/douyinWEB/backend/data/monitor.db")
|
||||
for k in ["shorts_oauth_redirect_uri","dy_cookie_updated_at"]:
|
||||
v=json.loads(c.execute("select value from kv_settings where key=?",(k,)).fetchone()[0])
|
||||
print(k, v)
|
||||
print("rooms", c.execute("select count(*) from rooms").fetchone()[0])
|
||||
print("shorts", c.execute("select count(*) from shorts_channels").fetchone()[0])
|
||||
print("assign", c.execute("select count(*) from yt_assign_groups").fetchone()[0])
|
||||
c.close()
|
||||
PY'''
|
||||
_i,o,e=c.exec_command(cmd, timeout=30)
|
||||
print((o.read()+e.read()).decode("utf-8","replace"))
|
||||
c.close()
|
||||
32
scripts/_check_keep_edge_svcs.py
Normal file
32
scripts/_check_keep_edge_svcs.py
Normal file
@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Confirm sing-box / frpp / wg stay active on VPS. Live flush."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
|
||||
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=25, banner_timeout=40, allow_agent=False, look_for_keys=False)
|
||||
print("connected", flush=True)
|
||||
cmd = (
|
||||
"systemctl is-active sing-box frpp 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' 2>/dev/null; "
|
||||
"systemctl is-enabled sing-box frpp 'wg-quick@wg-dy' 'wg-quick@wg-dy-cn' 2>/dev/null; "
|
||||
"ss -lntp | grep -E ':(4014|7000|8999)\\b' || true; "
|
||||
"wg show interfaces 2>/dev/null; "
|
||||
"systemctl show -p ActiveState --value sing-box frpp"
|
||||
)
|
||||
_i, o, e = c.exec_command(cmd, timeout=40)
|
||||
while not o.channel.exit_status_ready():
|
||||
if o.channel.recv_ready():
|
||||
sys.stdout.write(o.channel.recv(4096).decode("utf-8", "replace"))
|
||||
sys.stdout.flush()
|
||||
time.sleep(0.1)
|
||||
sys.stdout.write((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
sys.stdout.flush()
|
||||
c.close()
|
||||
print("DONE", flush=True)
|
||||
79
scripts/_check_opsneko_login_left.py
Normal file
79
scripts/_check_opsneko_login_left.py
Normal file
@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
SH = r"""
|
||||
echo "===== regular neko cookie auth check ====="
|
||||
for i in 1 2 3; do
|
||||
python3 - <<PY
|
||||
import sqlite3, json
|
||||
from pathlib import Path
|
||||
i="$i"
|
||||
fp=Path(f"/opt/douyinWEB/backend/data/neko/profiles/{i}/Default/Cookies")
|
||||
pref=Path(f"/opt/douyinWEB/backend/data/neko/profiles/{i}/Default/Preferences")
|
||||
ai=[]
|
||||
if pref.exists():
|
||||
d=json.loads(pref.read_text(encoding='utf-8', errors='replace'))
|
||||
ai=[a.get('email') for a in (d.get('account_info') or []) if isinstance(a, dict)]
|
||||
print(f"neko-{i} emails={ai} cookies_size={fp.stat().st_size if fp.exists() else None}")
|
||||
if fp.exists():
|
||||
con=sqlite3.connect(f"file:{fp}?mode=ro", uri=True)
|
||||
cur=con.cursor()
|
||||
cur.execute("select count(*) from cookies")
|
||||
print(" total", cur.fetchone()[0])
|
||||
cur.execute("select host_key, name from cookies where name like '%SID%' or name like '%SAPISID%' or name like '%LSID%' or name='SID' limit 20")
|
||||
print(" auth", cur.fetchall())
|
||||
con.close()
|
||||
PY
|
||||
done
|
||||
|
||||
echo "===== Local State / first-install times ====="
|
||||
ls -la /opt/douyinWEB/backend/data/ops_neko/profiles/1/Local\ State /opt/douyinWEB/backend/data/ops_neko/profiles/2/Local\ State 2>/dev/null
|
||||
stat /opt/douyinWEB/backend/data/ops_neko/profiles/*/Default/Cookies | grep -E 'File:|Modify|Size'
|
||||
|
||||
echo "===== ops hub / assign pairing still in DB? ====="
|
||||
python3 - <<'PY'
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
for db in [
|
||||
Path('/opt/douyinWEB/backend/data/monitor.db'),
|
||||
Path('/opt/douyinWEB/backend/data/ops_neko.db'),
|
||||
]:
|
||||
if not db.exists():
|
||||
print('missing', db); continue
|
||||
print('DB', db, db.stat().st_size)
|
||||
con=sqlite3.connect(f'file:{db}?mode=ro', uri=True)
|
||||
cur=con.cursor()
|
||||
cur.execute("select name from sqlite_master where type='table' order by 1")
|
||||
tables=[r[0] for r in cur.fetchall()]
|
||||
print(' tables', tables[:40])
|
||||
for t in tables:
|
||||
if any(x in t.lower() for x in ('ops','neko','hub','cred','pair','assign','studio')):
|
||||
try:
|
||||
cur.execute(f'select count(*) from {t}')
|
||||
print(f' {t}:', cur.fetchone()[0])
|
||||
except Exception as e:
|
||||
print(' err', t, e)
|
||||
con.close()
|
||||
PY
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/_check_login_left.sh", "wb") as f:
|
||||
f.write(SH.encode())
|
||||
sftp.close()
|
||||
_i, o, e = c.exec_command("echo 4669805 | sudo -S -p '' bash /tmp/_check_login_left.sh", timeout=90)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
23
scripts/_check_opsneko_open_url.py
Normal file
23
scripts/_check_opsneko_open_url.py
Normal file
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
import paramiko
|
||||
import sys
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False)
|
||||
_i, o, e = c.exec_command(
|
||||
"echo '4669805' | sudo -S -p '' bash -lc '"
|
||||
"curl -sS -m 8 -b /tmp/cj -c /tmp/cj -X POST http://127.0.0.1:8014/api/auth/login "
|
||||
" -H \"Content-Type: application/json\" "
|
||||
" -d \"{\\\"username\\\":\\\"hackrobot\\\",\\\"password\\\":\\\"Xiao4669805@\\\"}\" >/dev/null; "
|
||||
"curl -sS -m 8 -b /tmp/cj http://127.0.0.1:8014/api/ops/neko | "
|
||||
" python3 -c \"import sys,json; d=json.load(sys.stdin); "
|
||||
"print(\\\"peer\\\", d.get(\\\"peer\\\",{}).get(\\\"effective_public_base\\\"), d.get(\\\"peer\\\",{}).get(\\\"cn_edge_usable\\\")); "
|
||||
"inst=(d.get(\\\"instances\\\") or [{}])[0]; print(\\\"open_url\\\", inst.get(\\\"open_url\\\")); "
|
||||
"print(\\\"running\\\", inst.get(\\\"running\\\"))\""
|
||||
"'",
|
||||
timeout=40,
|
||||
)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
c.close()
|
||||
125
scripts/_cleanup_dylive_p0p1.py
Normal file
125
scripts/_cleanup_dylive_p0p1.py
Normal file
@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""P0+P1 cleanup on dylive (authorized). Seaweed inspect only in this pass."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
HOST = "107.173.30.245"
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
|
||||
def run(c, cmd, timeout=300):
|
||||
print(f"\n===== {cmd[:120]} =====", flush=True)
|
||||
_i, o, e = c.exec_command(cmd, timeout=timeout, get_pty=True)
|
||||
chan = o.channel
|
||||
start = time.time()
|
||||
while True:
|
||||
if chan.recv_ready():
|
||||
sys.stdout.write(chan.recv(8192).decode("utf-8", "replace"))
|
||||
sys.stdout.flush()
|
||||
if chan.recv_stderr_ready():
|
||||
sys.stdout.write(chan.recv_stderr(8192).decode("utf-8", "replace"))
|
||||
sys.stdout.flush()
|
||||
if chan.exit_status_ready():
|
||||
while chan.recv_ready():
|
||||
sys.stdout.write(chan.recv(8192).decode("utf-8", "replace"))
|
||||
sys.stdout.flush()
|
||||
break
|
||||
if time.time() - start > timeout:
|
||||
print("TIMEOUT", flush=True)
|
||||
break
|
||||
time.sleep(0.15)
|
||||
code = chan.recv_exit_status()
|
||||
print(f"\n[exit {code}]", flush=True)
|
||||
return code
|
||||
|
||||
|
||||
def main():
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(8):
|
||||
try:
|
||||
print(f"ssh try {i}", flush=True)
|
||||
c.connect(HOST, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||
break
|
||||
except Exception as ex:
|
||||
print(ex, flush=True)
|
||||
time.sleep(1 + i)
|
||||
else:
|
||||
raise SystemExit("ssh_fail")
|
||||
|
||||
# --- P0 ---
|
||||
print("\n######## P0 ########", flush=True)
|
||||
run(
|
||||
c,
|
||||
r"""
|
||||
set -e
|
||||
echo BEFORE=$(df -h / | awk 'NR==2{print $3,$4,$5}')
|
||||
# docker build cache
|
||||
docker builder prune -af
|
||||
# journal
|
||||
journalctl --vacuum-size=300M
|
||||
# .next.bak* keep .next
|
||||
cd /opt/douyinWEB/frontend
|
||||
ls -d .next.bak* 2>/dev/null || true
|
||||
rm -rf .next.bak*
|
||||
# /tmp deploy tgz
|
||||
rm -f /tmp/next-*.tgz /tmp/dy_next_*.tgz /tmp/dy-next-*.tgz /tmp/next-fe-*.tgz /tmp/src-*.tgz /tmp/pb.zip 2>/dev/null || true
|
||||
ls -lh /tmp/*.tgz /tmp/*.zip 2>/dev/null | head -20 || echo tmp_tgz_cleared
|
||||
# apt
|
||||
apt-get clean || true
|
||||
echo AFTER_P0=$(df -h / | awk 'NR==2{print $3,$4,$5}')
|
||||
""",
|
||||
timeout=400,
|
||||
)
|
||||
|
||||
# --- P1 ---
|
||||
print("\n######## P1 ########", flush=True)
|
||||
run(
|
||||
c,
|
||||
r"""
|
||||
set -e
|
||||
BK=/opt/douyinWEB/backend/data/backups
|
||||
# keep newest 3 monitor backups
|
||||
cd "$BK"
|
||||
ls -1t monitor_*.db 2>/dev/null | tail -n +4 | while read f; do rm -f -- "$f"; echo del_bak "$f"; done
|
||||
echo bak_left=$(ls -1 monitor_*.db 2>/dev/null | wc -l) bak_size=$(du -sh "$BK" | awk '{print $1}')
|
||||
# npm / cache
|
||||
rm -rf /root/.npm /root/.cache
|
||||
# .local: only clear obvious caches if present
|
||||
du -sh /root/.local/* 2>/dev/null | sort -h | tail -20 || true
|
||||
rm -rf /root/.local/share/Trash /root/.local/share/pip /root/.local/lib 2>/dev/null || true
|
||||
# docker exited containers + dangling images
|
||||
docker container prune -f
|
||||
docker image prune -f
|
||||
echo AFTER_P1=$(df -h / | awk 'NR==2{print $3,$4,$5}')
|
||||
docker system df
|
||||
""",
|
||||
timeout=300,
|
||||
)
|
||||
|
||||
# seaweed layout inspect for 2-day retention
|
||||
print("\n######## SEAWEED INSPECT ########", flush=True)
|
||||
run(
|
||||
c,
|
||||
r"""
|
||||
df -h / /data
|
||||
du -sh /data/seaweed /data/seaweed/* 2>/dev/null
|
||||
find /data/seaweed -maxdepth 3 -type d 2>/dev/null | head -40
|
||||
# sample object keys via weed / s3 if possible
|
||||
ls -la /data/seaweed/volume 2>/dev/null | head -20
|
||||
# env for s3
|
||||
grep -E 'S3|SEAWEED|AWS|covers' /opt/douyinWEB/backend/.env /etc/systemd/system/douyinweb-*.service 2>/dev/null | head -40
|
||||
""",
|
||||
timeout=60,
|
||||
)
|
||||
c.close()
|
||||
print("CLEANUP_DONE", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
71
scripts/_clone_tm_les_to_ops.py
Normal file
71
scripts/_clone_tm_les_to_ops.py
Normal file
@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
CMD = r"""
|
||||
echo 4669805 | sudo -S -p '' bash -lc '
|
||||
EXT=dhdgffkkebhmkfjojejmpbldmpobfkfo
|
||||
echo --- profile8 ---
|
||||
P8=/opt/douyinWEB/backend/data/neko/profiles/8/Default/Local\ Extension\ Settings/$EXT
|
||||
ls -la "$P8" | head
|
||||
grep -aR "YouTube Studio Auto Dismiss" "$P8" | wc -l
|
||||
grep -ao "YouTube Studio Auto Dismiss" "$P8"/* 2>/dev/null | head
|
||||
echo --- seed ---
|
||||
SEED=/opt/douyinWEB/backend/neko/tampermonkey-seed/Default/Local\ Extension\ Settings/$EXT
|
||||
ls -la "$SEED" | head
|
||||
grep -aR "YouTube Studio Auto Dismiss" "$SEED" | wc -l
|
||||
# Try installAsSystemScripts true and reimport
|
||||
python3 - <<'"'"'PY'"'"'
|
||||
import json
|
||||
from pathlib import Path
|
||||
p=Path("/opt/douyinWEB/backend/neko/policies/policies.json")
|
||||
d=json.loads(p.read_text())
|
||||
ji=d["3rdparty"]["extensions"]["dhdgffkkebhmkfjojejmpbldmpobfkfo"]["jsonImport"][0]
|
||||
ji["installAsSystemScripts"]=True
|
||||
p.write_text(json.dumps(d,ensure_ascii=False,indent=2)+"\n")
|
||||
print("set installAsSystemScripts", ji)
|
||||
PY
|
||||
for i in 1 2; do
|
||||
name=douyinweb-ops-neko-$i
|
||||
docker exec "$name" supervisorctl stop google-chrome || true
|
||||
sleep 1
|
||||
# clone profile8 LES if it has script
|
||||
if grep -aq "YouTube Studio Auto Dismiss" $P8/* 2>/dev/null; then
|
||||
echo cloning_from_profile8_to_ops$i
|
||||
docker exec "$name" bash -lc "rm -rf /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT /home/neko/.config/google-chrome/Default/Managed\ Extension\ Settings/$EXT"
|
||||
docker cp "$P8" "$name:/home/neko/.config/google-chrome/Default/Local Extension Settings/$EXT"
|
||||
docker exec "$name" bash -lc "rm -f /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT/LOCK; chown -R neko:neko /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT"
|
||||
else
|
||||
echo profile8_empty_try_system_import
|
||||
docker exec "$name" bash -lc "rm -rf /home/neko/.config/google-chrome/Default/Local\ Extension\ Settings/$EXT /home/neko/.config/google-chrome/Default/Managed\ Extension\ Settings/$EXT"
|
||||
fi
|
||||
docker exec "$name" supervisorctl start google-chrome
|
||||
done
|
||||
sleep 20
|
||||
for i in 1 2; do
|
||||
echo ===== OPS$i =====
|
||||
docker exec douyinweb-ops-neko-$i bash -lc "
|
||||
P=/home/neko/.config/google-chrome/Default
|
||||
du -sh \"\$P/Local Extension Settings/$EXT\" 2>/dev/null
|
||||
echo HITS=\$(grep -aR \"YouTube Studio Auto Dismiss\" \"\$P/Local Extension Settings/$EXT\" 2>/dev/null | wc -l)
|
||||
strings \"\$P/Local Extension Settings/$EXT\"/* 2>/dev/null | grep -E \"2\\.2\\.|Auto Dismiss\" | head -8
|
||||
"
|
||||
done
|
||||
'
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False)
|
||||
_i, o, e = c.exec_command(CMD, timeout=180)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"))
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
46
scripts/_cmp_api_bind_docker.py
Normal file
46
scripts/_cmp_api_bind_docker.py
Normal file
@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare API bind + docker networking: dylive (good) vs dy."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
PASS = "Xiao4669805"
|
||||
CMD = r"""
|
||||
echo '=== uvicorn / unit ==='
|
||||
systemctl cat douyinweb-api 2>/dev/null | grep -E 'ExecStart|Environment|Host|8014' | head -30
|
||||
ps aux | grep -E 'uvicorn app.main' | grep -v grep | head -3
|
||||
echo '=== listen ==='
|
||||
ss -lntp | grep 8014 || true
|
||||
echo '=== docker network ==='
|
||||
docker network ls
|
||||
NAME=$(docker ps --filter name=douyinweb-neko --format '{{.Names}}' | head -1)
|
||||
docker inspect "$NAME" --format 'NetworkMode={{.HostConfig.NetworkMode}} ExtraHosts={{json .HostConfig.ExtraHosts}}'
|
||||
docker inspect "$NAME" --format '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} IP={{$v.IPAddress}} GW={{$v.Gateway}}{{end}}'
|
||||
echo '=== curl from container to health ==='
|
||||
for u in \
|
||||
'http://172.17.0.1:8014/api/health' \
|
||||
'http://host.docker.internal:8014/api/health' \
|
||||
'https://dy.nomadro.live/api/health' \
|
||||
'https://dylive.nomadro.com/api/health'; do
|
||||
code=$(docker exec "$NAME" curl -sS -m 5 -o /dev/null -w '%{http_code}' "$u" 2>/dev/null || echo fail)
|
||||
echo "$code $u"
|
||||
done
|
||||
"""
|
||||
|
||||
def run(host, name):
|
||||
print(f"\n===== {name} {host} =====", flush=True)
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(host, 22, "root", PASS, timeout=30, allow_agent=False, look_for_keys=False)
|
||||
_i, o, e = c.exec_command(CMD, timeout=60)
|
||||
print(o.read().decode("utf-8", "replace"), flush=True)
|
||||
err = e.read().decode("utf-8", "replace")
|
||||
if err.strip():
|
||||
print("[stderr]", err[:600], flush=True)
|
||||
c.close()
|
||||
|
||||
run("107.173.30.245", "dylive")
|
||||
run("108.174.50.68", "dy")
|
||||
print("DONE", flush=True)
|
||||
97
scripts/_cmp_assign_cards_youtubei.py
Normal file
97
scripts/_cmp_assign_cards_youtubei.py
Normal file
@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Compare assign channel cards + youtubei probe on physical vs VPS."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
REMOTE = r'''
|
||||
import asyncio, json, os, sys
|
||||
os.chdir("/opt/douyinWEB/backend")
|
||||
sys.path.insert(0, ".")
|
||||
from app import yt_assign_db, db
|
||||
from app import youtube_client
|
||||
from app import youtube_live
|
||||
|
||||
async def main():
|
||||
groups = yt_assign_db.list_groups(include_urls=False)
|
||||
print("ASSIGN_N", len(groups))
|
||||
cards = []
|
||||
for g in groups:
|
||||
if not g.get("enabled"):
|
||||
continue
|
||||
cid = str(g.get("youtube_channel_id") or "").strip()
|
||||
pk = str(g.get("channel_pk") or "").strip()
|
||||
name = str(g.get("name") or "")
|
||||
if cid or pk:
|
||||
cards.append((name, cid, pk, str(g.get("id") or "")[:8]))
|
||||
print("ENABLED_WITH_CH", len(cards))
|
||||
for row in cards[:20]:
|
||||
print(" ", row)
|
||||
|
||||
# what live-map currently probes (channel_groups + shorts only?)
|
||||
cg = (db.list_channel_groups(platform="youtube", limit=500, offset=0).get("groups") or [])
|
||||
shorts = db.list_shorts_channels()
|
||||
print("channel_groups", len(cg), "shorts", len(shorts))
|
||||
|
||||
urls = []
|
||||
for name, cid, pk, gid in cards:
|
||||
if cid:
|
||||
urls.append(f"https://www.youtube.com/channel/{cid}")
|
||||
urls = list(dict.fromkeys(urls))
|
||||
print("PROBE_URLS", len(urls))
|
||||
if urls:
|
||||
try:
|
||||
h = await youtube_client.health()
|
||||
print("yt_svc_health", h)
|
||||
except Exception as ex:
|
||||
print("yt_svc_health_err", ex)
|
||||
try:
|
||||
data = await youtube_client.batch_live(urls[:15])
|
||||
live_n = 0
|
||||
for r in (data.get("results") or []):
|
||||
if r.get("is_live"):
|
||||
live_n += 1
|
||||
print(" LIVE", r.get("input"), (r.get("live") or {}).get("title") or r.get("title"))
|
||||
else:
|
||||
print(" off ", str(r.get("input") or "")[-30:], "err", (r.get("error") or "")[:60])
|
||||
print("batch_live_count", live_n, "/", len(data.get("results") or []))
|
||||
except Exception as ex:
|
||||
print("batch_live_err", type(ex).__name__, ex)
|
||||
|
||||
m = await youtube_live.build_live_map(force=True)
|
||||
print("live_map_count", m.get("live_count"), "source", m.get("source"), "svc_error", (m.get("svc_error") or "")[:100])
|
||||
|
||||
asyncio.run(main())
|
||||
'''
|
||||
|
||||
|
||||
def run(label, host, port, user, pwd, sudo=False):
|
||||
print(f"\n######## {label} ########")
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(host, port, user, pwd, timeout=30, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
with sftp.file("/tmp/_cmp_cards_yt.py", "w") as f:
|
||||
f.write(REMOTE)
|
||||
sftp.close()
|
||||
py = "/opt/douyinWEB/backend/.venv/bin/python"
|
||||
cmd = f"{py} /tmp/_cmp_cards_yt.py"
|
||||
if sudo:
|
||||
cmd = f"echo '{pwd}' | sudo -S -p '' {cmd}"
|
||||
_, o, e = c.exec_command(cmd, timeout=180)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace")[:4000])
|
||||
c.close()
|
||||
|
||||
|
||||
def main():
|
||||
run("dylive/VPS", "107.173.30.245", 22, "root", "Xiao4669805", False)
|
||||
run("dy/physical", "107.173.30.245", 4014, "eric", "4669805", True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
58
scripts/_cmp_browser_launch_phys.py
Normal file
58
scripts/_cmp_browser_launch_phys.py
Normal file
@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Compare host browser-launch.sh with local; show if mangled."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOCAL = ROOT / "backend/neko/browser-launch.sh"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(
|
||||
"107.173.30.245",
|
||||
4014,
|
||||
"eric",
|
||||
"4669805",
|
||||
timeout=45,
|
||||
allow_agent=False,
|
||||
look_for_keys=False,
|
||||
banner_timeout=120,
|
||||
)
|
||||
sftp = c.open_sftp()
|
||||
remote = sftp.file("/opt/douyinWEB/backend/neko/browser-launch.sh", "r").read()
|
||||
sftp.close()
|
||||
local = LOCAL.read_bytes()
|
||||
print("local_sha", hashlib.sha256(local).hexdigest()[:16], "len", len(local))
|
||||
print("remote_sha", hashlib.sha256(remote).hexdigest()[:16], "len", len(remote))
|
||||
print("same", local == remote)
|
||||
text = remote.decode("utf-8", "replace")
|
||||
print("--- remote first 40 lines ---")
|
||||
print("\n".join(text.splitlines()[:40]))
|
||||
print("--- remote grep profile_dir / extension_flags / set - ---")
|
||||
for i, line in enumerate(text.splitlines(), 1):
|
||||
if any(
|
||||
x in line
|
||||
for x in (
|
||||
"profile_dir=",
|
||||
"extension_flags",
|
||||
"set -",
|
||||
"tm_load_dir",
|
||||
"launch_browser",
|
||||
"browser_pid",
|
||||
)
|
||||
):
|
||||
print(f"{i}:{line}")
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
140
scripts/_cmp_dual_ffmpeg_sources.py
Normal file
140
scripts/_cmp_dual_ffmpeg_sources.py
Normal file
@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare live FFmpeg inputs on both VPS — same source claim."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOSTS = [("dylive", "107.173.30.245"), ("dy", "108.174.50.68")]
|
||||
PASS = "Xiao4669805"
|
||||
|
||||
SCRIPT = r"""
|
||||
set +e
|
||||
echo '=== ffmpeg procs ==='
|
||||
ps -eo pid,pcpu,pmem,etime,cmd | grep '[f]fmpeg' | head -5
|
||||
echo
|
||||
echo '=== parse input url ==='
|
||||
python3 - <<'PY'
|
||||
import subprocess, re, urllib.parse
|
||||
out=subprocess.check_output(['ps','-eo','args'], text=True, errors='replace')
|
||||
for line in out.splitlines():
|
||||
if 'ffmpeg' not in line or 'rtmps://' not in line: continue
|
||||
if line.strip().startswith('grep'): continue
|
||||
# input after -i
|
||||
m=re.search(r'-i\s+(\S+)', line)
|
||||
vin=m.group(1).strip('"') if m else ''
|
||||
# output rtmps
|
||||
mo=re.search(r'(rtmps://\S+)', line)
|
||||
vout=mo.group(1) if mo else ''
|
||||
# scale
|
||||
ms=re.search(r'scale=([^:\\s]+)', line)
|
||||
scale=ms.group(1) if ms else ''
|
||||
mb=re.search(r'-b:v\s+(\S+)', line)
|
||||
br=mb.group(1) if mb else ''
|
||||
mt=re.search(r'-threads\s+(\S+)', line)
|
||||
th=mt.group(1) if mt else ''
|
||||
print('INPUT', vin[:220])
|
||||
# classify
|
||||
low=vin.lower()
|
||||
kind='unknown'
|
||||
for k in ('uhd','origin','hd','sd','ld','md','_or4','_hd','_sd','_ld'):
|
||||
if k in low: kind=k; break
|
||||
# unique_id / stream id
|
||||
qs=urllib.parse.urlparse(vin)
|
||||
q=urllib.parse.parse_qs(qs.query)
|
||||
print('host', qs.hostname)
|
||||
print('path', qs.path[-80:])
|
||||
print('unique_id', (q.get('unique_id') or [''])[0][:120])
|
||||
print('kind_hint', kind)
|
||||
print('scale', scale, 'b:v', br, 'threads', th)
|
||||
print('OUT', vout[:100])
|
||||
print('CPU_LINE_has_uhd', '_uhd' in vin or 'uhd' in vin.lower())
|
||||
PY
|
||||
echo
|
||||
echo '=== relay status brief ==='
|
||||
cd /opt/douyinWEB/backend
|
||||
./.venv/bin/python - <<'PY'
|
||||
from app.db import _connect, _lock
|
||||
import json
|
||||
with _lock:
|
||||
conn=_connect()
|
||||
try:
|
||||
rows=conn.execute("SELECT group_id, status, substr(source_url,1,120), substr(coalesce(last_error,''),1,60) FROM yt_relay_states WHERE status LIKE '%push%' OR status LIKE '%live%' OR is_pushing=1 LIMIT 10").fetchall()
|
||||
except Exception:
|
||||
try:
|
||||
cols=[r[1] for r in conn.execute('PRAGMA table_info(yt_relay_states)').fetchall()]
|
||||
print('relay_cols', cols)
|
||||
rows=conn.execute('SELECT * FROM yt_relay_states LIMIT 5').fetchall()
|
||||
for r in rows: print(dict(r))
|
||||
rows=[]
|
||||
except Exception as e:
|
||||
print('err', e); rows=[]
|
||||
for r in rows:
|
||||
print('relay', r)
|
||||
# groups currently pushing via names
|
||||
try:
|
||||
for r in conn.execute("SELECT name, neko_instance_id, neko_enabled FROM yt_assign_groups").fetchall():
|
||||
pass
|
||||
except Exception: pass
|
||||
PY
|
||||
# from API local
|
||||
curl -sS -m 8 http://127.0.0.1:8014/api/youtube/relay/status 2>/dev/null | python3 - <<'PY'
|
||||
import sys,json
|
||||
raw=sys.stdin.read()
|
||||
try:
|
||||
d=json.loads(raw)
|
||||
except Exception as e:
|
||||
print('json_fail', e, raw[:200]); raise SystemExit
|
||||
entries=d.get('entries') or d.get('groups') or d.get('items') or []
|
||||
if isinstance(d, dict) and not entries:
|
||||
# maybe {group_id: {...}}
|
||||
if all(isinstance(v, dict) for v in d.values()):
|
||||
entries=[{'group_id':k, **v} for k,v in d.items() if isinstance(v, dict)]
|
||||
print('keys', list(d.keys())[:20])
|
||||
if isinstance(entries, list):
|
||||
for e in entries[:12]:
|
||||
if not isinstance(e, dict):
|
||||
continue
|
||||
pushing=e.get('is_pushing') or e.get('pushing') or (str(e.get('status') or '').lower() in ('pushing','live','on_air'))
|
||||
src=str(e.get('source_url') or e.get('douyin_url') or e.get('input_url') or '')[:100]
|
||||
name=e.get('name') or e.get('group_name') or e.get('title') or ''
|
||||
if pushing or src:
|
||||
print({
|
||||
'name': str(name)[:40],
|
||||
'pushing': pushing,
|
||||
'status': e.get('status') or e.get('phase'),
|
||||
'src': src,
|
||||
'fps': e.get('fps') or e.get('ffmpeg_fps'),
|
||||
'bitrate': e.get('bitrate') or e.get('speed'),
|
||||
})
|
||||
PY
|
||||
echo HOST_DONE
|
||||
"""
|
||||
|
||||
|
||||
def connect(host):
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(8):
|
||||
try:
|
||||
c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120)
|
||||
return c
|
||||
except Exception as e:
|
||||
print("retry", host, e, flush=True)
|
||||
time.sleep(2)
|
||||
raise SystemExit("ssh fail")
|
||||
|
||||
|
||||
for label, host in HOSTS:
|
||||
print(f"\n######## {label} {host} ########", flush=True)
|
||||
c = connect(host)
|
||||
_i, o, e = c.exec_command(SCRIPT, timeout=60)
|
||||
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
|
||||
c.close()
|
||||
print("ALL_DONE", flush=True)
|
||||
72
scripts/_cmp_dy_dylive_cpu.py
Normal file
72
scripts/_cmp_dy_dylive_cpu.py
Normal file
@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare dy vs dylive CPU/ffmpeg/neko — read only."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
PASS = "Xiao4669805"
|
||||
HOSTS = [
|
||||
("dy", "108.174.50.68"),
|
||||
("dylive", "107.173.30.245"),
|
||||
]
|
||||
|
||||
CMD = r"""
|
||||
echo HOST=$(hostname)
|
||||
echo UPTIME=$(uptime)
|
||||
echo CORES=$(nproc)
|
||||
free -h | head -2
|
||||
echo '---TOP---'
|
||||
ps -eo pcpu,pmem,rss,comm,args --sort=-pcpu | head -18
|
||||
echo '---FFMPEG---'
|
||||
pgrep -a ffmpeg 2>/dev/null | while read -r line; do
|
||||
pid=$(echo "$line" | awk '{print $1}')
|
||||
cpu=$(ps -p "$pid" -o pcpu=,rss= 2>/dev/null)
|
||||
# extract input url quality hint
|
||||
echo "PID $pid CPU/RSS $cpu"
|
||||
echo "$line" | tr ' ' '\n' | grep -E '_uhd|_hd|_sd|ORIGIN|rtmps|yt_long|clips/' | head -8
|
||||
echo '---'
|
||||
done
|
||||
echo ffmpeg_n=$(pgrep -c ffmpeg 2>/dev/null || echo 0)
|
||||
echo '---NEKO---'
|
||||
docker ps --filter name=neko --format '{{.Names}} {{.Status}}' 2>/dev/null
|
||||
docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}' 2>/dev/null | grep neko || true
|
||||
echo '---API---'
|
||||
ps -eo pcpu,pmem,rss,args | grep -E 'uvicorn app.main|next-server' | grep -v grep
|
||||
echo '---LOADSRC---'
|
||||
# soft decode clue: threads / preset in ffmpeg
|
||||
pgrep -a ffmpeg 2>/dev/null | grep -oE '\-threads [0-9]+|\-preset [a-z0-9]+|\-b:v [^ ]+|\-vf [^ ]+' | head -40
|
||||
"""
|
||||
|
||||
|
||||
def connect(host):
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
for i in range(6):
|
||||
try:
|
||||
c.connect(host, 22, "root", PASS, timeout=25, allow_agent=False, look_for_keys=False)
|
||||
return c
|
||||
except Exception as e:
|
||||
print(f"ssh {host} fail {e}", flush=True)
|
||||
time.sleep(1 + i)
|
||||
raise SystemExit(f"ssh_fail {host}")
|
||||
|
||||
|
||||
def main():
|
||||
for name, host in HOSTS:
|
||||
print(f"\n########## {name} {host} ##########", flush=True)
|
||||
c = connect(host)
|
||||
_i, o, e = c.exec_command(CMD, timeout=45)
|
||||
print(o.read().decode("utf-8", "replace"), flush=True)
|
||||
err = e.read().decode("utf-8", "replace")
|
||||
if err.strip():
|
||||
print("[stderr]", err[:500], flush=True)
|
||||
c.close()
|
||||
print("DONE", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user