diff --git a/README.md b/README.md index fde33d7..bc5f53f 100644 --- a/README.md +++ b/README.md @@ -435,13 +435,36 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,** 关闭软愈合(仅排障):`DY_DISABLE_NEKO_SOFT_HEAL=1` 或 `DY_DISABLE_STUDIO_CDP_LOOP=1`。日志关键字:`neko_runtime_heal`。 +#### API 防挂死 / 直播优先 CPU(双 VPS) + +现网根因(尤其 **VPS-B dy.nomadro.live**):直播推流 ffmpeg 与 yt_long/shorts 转码叠在一起 → load 飙高 → uvicorn 事件循环饿死 → `/api/health` 超时 → 整站「宕机」。**dylive 同代码**不叠加重转码时即可稳住。对策: + +| 层 | 机制 | 行为 | +|----|------|------| +| 瞬时 health | `GET /api/health`(默认) | **禁止** await S3/YT/PB;仅进程态 + 可选缓存 deps。依赖探测用 `?detail=1` | +| ffmpeg 隔离 | `backend/app/procutil.py` + `douyinweb-ffmpeg.slice` | 推流/成片子进程迁出 API cgroup,避免 `MemoryHigh` 回收把 API 打成 D-state | +| 剪辑让路 | `host_metrics.clip_encode_defer_reason()` | 有 YouTube **直播推流** 或 load/CPU 过高时,yt_long / shorts / tiktok / x_clips **不新开** 录制 ffmpeg | +| API 内存 | systemd drop-in(对齐 dylive 紧预算,按机内存微调) | 例:dylive ≈ High **700M** / Max **900M**;dy.live ≈ High **1100M** / Max **1500M**(ffmpeg 已外置) | +| ffmpeg CPU | `douyinweb-ffmpeg.slice` `CPUQuota` | dy.live 现网 **200%**(4 核机留给 API/Neko 余量) | +| 看门狗 | `scripts/linux/api_health_watch.sh` → `douyinweb-api-watch.service` | health 连续失败或 `:8014` Recv-Q 过高 → SIGKILL 重启 API | + +对齐部署(代码 + systemd):`python scripts/_align_dy_to_dylive_harden.py`(经 VPS-A 跳到 VPS-B);仅 cgroup/watch 骨架也可用 `scripts/_deploy_api_hang_harden.py`。 + #### 时段排除名单(timeslot exclude) 分配页「排除手动直播名单」:已用于手动开播的抖音房不再被时段自动挑选 / 日程自动填充。API:`/api/youtube/assign/timeslot-exclude*`。 -#### YouTube YPP 频道创收 API(调研) +#### YouTube YPP 频道创收 + +官方可通过 [YouTube Analytics API](https://developers.google.com/youtube/analytics/reference/reports/query) 拉取频道 **预估创收**(`estimatedRevenue` 等),需 OAuth scope `yt-analytics-monetary.readonly`。 + +| 项 | 说明 | +|----|------| +| 控制台 | `/yt-revenue`(侧栏「收益」) | +| API | `GET /api/yt-revenue/summary` · `GET /api/yt-revenue/channels/{channel_pk}` | +| 后端 | `backend/app/yt_revenue.py`;频道需重新授权含 monetary scope,否则 `need_reauth` | +| 调研 | [docs/YPP_REVENUE_API.md](docs/YPP_REVENUE_API.md);站点 AdSense 另见 [docs/ADSENSE_API.md](docs/ADSENSE_API.md) | -官方 **可以**通过 [YouTube Analytics API](https://developers.google.com/youtube/analytics/reference/reports/query) 拉取频道 **预估创收**(`estimatedRevenue` 等),需 OAuth scope `yt-analytics-monetary.readonly`。本仓库当前 Shorts OAuth **未包含**该 scope,也**尚未接入**收益拉取。分析结论见 [docs/YPP_REVENUE_API.md](docs/YPP_REVENUE_API.md)。(站点 AdSense 是另一套 API,见 [docs/ADSENSE_API.md](docs/ADSENSE_API.md)。) - **不复用** sh2 RTMP 转播通道 ### 封面(S3) @@ -482,6 +505,8 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,** | `/youtube` | 频道管理(默认)+ InnerTube 探测 | | `/youtube` → **分配** | Pro 转播:KEY / 精选源 / 时间段 / Neko / FFmpeg 实况 | | `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 | +| `/yt-long` | 长视频成片 / 上传 | +| `/yt-revenue` | YPP 预估创收(需 monetary OAuth) | | `/settings` | 防风控、通知、静默、YT/Shorts、**全局 SOCKS5**、改密、PB/S3 运维 | | `/ops` | 运维:Umami / ntfy / DNS / systemd;顶栏另有 CPU·内存条 | | `/web` | Umami 多站点访问分析 | diff --git a/backend/app/clip_cascade.py b/backend/app/clip_cascade.py index 43b3de2..cdfc792 100644 --- a/backend/app/clip_cascade.py +++ b/backend/app/clip_cascade.py @@ -94,7 +94,9 @@ def cut_segment( str(out), ] try: - proc = subprocess.run(copy_cmd, capture_output=True, text=True, timeout=dur + 60) + from .procutil import run_outside_api_cgroup + + proc = run_outside_api_cgroup(copy_cmd, capture_output=True, text=True, timeout=dur + 60) except Exception as exc: return {"ok": False, "error": str(exc)[:300]} if proc.returncode == 0 and out.is_file() and out.stat().st_size >= 20_000: @@ -130,7 +132,9 @@ def cut_segment( str(out), ] try: - proc = subprocess.run(cmd, capture_output=True, text=True, timeout=dur + 120) + from .procutil import run_outside_api_cgroup + + proc = run_outside_api_cgroup(cmd, capture_output=True, text=True, timeout=dur + 120) except Exception as exc: return {"ok": False, "error": str(exc)[:300]} if proc.returncode != 0: diff --git a/backend/app/db.py b/backend/app/db.py index b7e09fc..db57c0e 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -3393,6 +3393,8 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: "oauth_ok", "oauth_checked_at", "oauth_error", + "ypp_ok", + "ypp_checked_at", "yt_profile_json", "yt_profile_at", } @@ -3411,6 +3413,13 @@ def update_shorts_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: v = _normalize_daily_quota(v, default=SHORTS_DAILY_FORCE) if k == "enabled": v = 1 if v else 0 + if k == "ypp_ok": + try: + v = int(v) + except Exception: + continue + if v not in (-1, 0, 1): + continue if k == "oauth_profile_id": v = str(v or "").strip().upper() sets.append(f"{k} = ?") @@ -3473,7 +3482,11 @@ def delete_shorts_jobs_for_channel(channel_pk: str) -> dict[str, int]: def delete_shorts_channel(channel_pk: str) -> dict[str, int]: - """Delete channel and cascade: jobs + local clip materials.""" + """Delete Shorts channel + its jobs/clips only. + + Never touches Live 分配 (yt_assign_*), stream keys, Neko binds, or yt_long + channels — those are independent products linked by youtube_channel_id. + """ pk = str(channel_pk or "").strip() stats = delete_shorts_jobs_for_channel(pk) with _lock: diff --git a/backend/app/host_metrics.py b/backend/app/host_metrics.py index fc8f4b7..3ea983c 100644 --- a/backend/app/host_metrics.py +++ b/backend/app/host_metrics.py @@ -98,3 +98,34 @@ def snapshot(*, sample_cpu: bool = False) -> dict[str, Any]: _snapshot_cache = out _snapshot_cache_at = now return dict(out) + + +def live_youtube_push_active() -> bool: + """True when at least one YouTube live relay ffmpeg is pushing.""" + try: + from .youtube_relay_pipeline import youtube_relay_pipeline as rp + + flags = rp.pushing_flags() or {} + return any(bool((v or {}).get("is_pushing")) for v in flags.values()) + except Exception: + return False + + +def clip_encode_defer_reason(*, respect_live_push: bool = True) -> str: + """Why clip ffmpeg should wait. Empty string = OK to start encode. + + Live relay must keep CPU headroom; concurrent yt_long/shorts encode is what + wedged dy.nomadro.live (load~47) while identical code on dylive stayed up. + """ + if respect_live_push and live_youtube_push_active(): + return "live_relay_pushing" + snap = snapshot(sample_cpu=False) + cores = max(1, int(snap.get("cpu_cores") or 1)) + load1 = float(snap.get("load1") or 0.0) + cpu = float(snap.get("cpu_percent") or 0.0) + # Leave ~1 core free for API accept loop + Neko CDP. + if load1 >= max(1.5, cores * 1.15): + return f"load1={load1}" + if cpu >= 80.0: + return f"cpu={cpu}" + return "" diff --git a/backend/app/main.py b/backend/app/main.py index e1d7953..270ced4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -177,7 +177,7 @@ async def lifespan(_: FastAPI): try: from . import ops_neko_sync - asyncio.create_task(ops_neko_sync.edge_sync_loop(interval_sec=5.0)) + asyncio.create_task(ops_neko_sync.edge_sync_loop(interval_sec=30.0)) except Exception: pass @@ -325,7 +325,11 @@ _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 — default path must not touch thread pools or SQLite.""" + """Fast health — default path must not await network / thread pools / SQLite. + + Under CPU storm (live relay + clip encode) any await here times out the + watchdog and looks like a full site outage. Use ?detail=1 for deps. + """ if _DESKTOP_LIGHT: return {"ok": True, "time": time.time(), "desktop_light": True} out: dict[str, Any] = { @@ -368,8 +372,7 @@ 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 "异常/已停". + # Instant liveness for watchdog / Caddy / operators. Never block on S3/YT/PB. if not detail: try: out["monitor"] = { @@ -395,54 +398,23 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]: } 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 - ): + if isinstance(cached_deps, dict): 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, + else: + # Stubs so ops UI does not flash "异常" before first detail refresh. + out["youtube"] = {"ok": True, "service": "youtube-svc", "deferred": True} + out["pocketbase"] = {"ok": True, "deferred": True} + out["s3"] = { + "enabled": bool(getattr(settings, "s3_endpoint", None)), + "ok": True, + "deferred": True, + "endpoint": getattr(settings, "s3_endpoint", "") or "", + "bucket": getattr(settings, "s3_bucket", "") or "", + "public_base": getattr(settings, "s3_public_base", "") or "", } - 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 + out["deps_cached"] = False return out try: @@ -501,6 +473,11 @@ async def health(detail: int = Query(0, ge=0, le=1)) -> dict[str, Any]: out["s3"] = await asyncio.wait_for(asyncio.to_thread(_s3), timeout=1.0) except Exception as exc: out["s3"] = {"enabled": False, "ok": False, "error": str(exc)[:120]} + # Feed default /api/health stubs so UI can show last-known without blocking. + _HEALTH_DEPS_CACHE["at"] = time.time() + _HEALTH_DEPS_CACHE["payload"] = { + k: out[k] for k in ("youtube", "pocketbase", "s3") if k in out + } return out @@ -886,14 +863,23 @@ async def shorts_live_analytics( @app.get("/api/shorts/oauth/start") -async def shorts_oauth_start(channel_pk: str, request: Request, return_to: str = "") -> RedirectResponse: +async def shorts_oauth_start( + channel_pk: str, + request: Request, + return_to: str = "", + monetary: int = 0, +) -> RedirectResponse: try: await shorts_oauth.prepare_reauthorize(channel_pk) ret = str(return_to or request.query_params.get("return_to") or "").strip() + want_monetary = bool(int(monetary or 0)) or str( + request.query_params.get("monetary") or "" + ).strip().lower() in {"1", "true", "yes"} url = shorts_oauth.build_authorize_url( channel_pk=channel_pk, request_base=_request_public_base(request), return_to=ret, + include_monetary=want_monetary, ) except ValueError as exc: raise HTTPException(400, str(exc)) from exc @@ -1049,8 +1035,9 @@ async def shorts_channels_update(channel_pk: str, body: ShortsChannelUpdate) -> @app.delete("/api/shorts/channels/{channel_pk}") async def shorts_channels_delete(channel_pk: str) -> dict[str, Any]: + """Delete Shorts card only — Live 分配 / stream key / Neko 配置保留。""" stats = db.delete_shorts_channel(channel_pk) - return {"ok": True, **stats} + return {"ok": True, "live_assign_preserved": True, "yt_long_preserved": True, **stats} @app.get("/api/shorts/jobs") @@ -1612,6 +1599,28 @@ async def x_clips_job_retry(job_id: str) -> dict[str, Any]: # ── YouTube long-form 9:16 (isolated; default disabled) ────────────────────── +@app.get("/api/yt-revenue/summary") +async def yt_revenue_summary( + days: int = Query(28, ge=1, le=90), + force: int = Query(0, ge=0, le=1), +) -> dict[str, Any]: + """Fleet AdSense / YouTube Analytics estimated revenue (Live / Shorts / 长视频).""" + from . import yt_revenue + + return await yt_revenue.fleet_revenue(days=days, force=bool(force)) + + +@app.get("/api/yt-revenue/channels/{channel_pk}") +async def yt_revenue_channel( + channel_pk: str, + days: int = Query(28, ge=1, le=90), + force: int = Query(0, ge=0, le=1), +) -> dict[str, Any]: + from . import yt_revenue + + return await yt_revenue.fetch_channel_revenue(channel_pk, days=days, force=bool(force)) + + @app.get("/api/yt-long/status") async def yt_long_status(light: int = Query(0, ge=0, le=1)) -> dict[str, Any]: fn = yt_long_pipeline.status_light if light else yt_long_pipeline.status diff --git a/backend/app/ops_neko.py b/backend/app/ops_neko.py index 8c62ff8..8c5f4ee 100644 --- a/backend/app/ops_neko.py +++ b/backend/app/ops_neko.py @@ -501,13 +501,45 @@ def push_catalog_to_hub() -> dict[str, Any]: return {"ok": False, "error": str(exc)[:300], "payload": payload} -def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[str, Any]: +def ensure_slot_live_studio( + slot: int, + *, + youtube_channel_id: str = "", + skip_scrape_if_fresh_sec: float = 0.0, +) -> dict[str, Any]: """Physical edge: ensure ops-neko Chrome has YouTube Live Control Room open (待开播).""" from . import youtube_neko as yn slot_i = int(slot or 0) if slot_i < 1: return {"ok": False, "error": "bad_slot"} + fresh_sec = float(skip_scrape_if_fresh_sec or 0) + if fresh_sec > 0: + try: + snap = yn.studio_snapshot_for_ref( + f"ops:{slot_i}", max_age_sec=fresh_sec, include_minute_reports=False + ) + age = snap.get("age_sec") + if ( + snap.get("live_page_open") + or snap.get("received_at") + or snap.get("on_air") + or snap.get("url") + ) and (age is None or float(age) <= fresh_sec): + name = _container_name(slot_i) + yt = str(youtube_channel_id or "").strip() + studio_url = yn.studio_live_control_url(yt) if yt else str(snap.get("url") or "") + if studio_url and _container_running(slot_i): + yn._cdp_ensure_live_studio_in_container(name, studio_url=studio_url) + return { + "ok": True, + "slot": slot_i, + "skipped_scrape": True, + "age_sec": age, + "studio_url": studio_url, + } + except Exception: + pass name = _container_name(slot_i) if not _container_running(slot_i): try: @@ -638,7 +670,7 @@ def ensure_slot_live_studio(slot: int, *, youtube_channel_id: str = "") -> dict[ return {"ok": bool(opened.get("ok")), "slot": slot_i, "studio_url": studio_url, "cdp": opened} -def ensure_bound_slots_live_studio() -> dict[str, Any]: +def ensure_bound_slots_live_studio(*, skip_scrape_if_fresh_sec: float = 0.0) -> dict[str, Any]: """Edge heartbeat: bound/running ops slots keep Live Control Room open.""" cards_by_id: dict[str, dict[str, Any]] = {} try: @@ -671,7 +703,13 @@ def ensure_bound_slots_live_studio() -> dict[str, Any]: break if not should: continue - results.append(ensure_slot_live_studio(slot, youtube_channel_id=yt)) + results.append( + ensure_slot_live_studio( + slot, + youtube_channel_id=yt, + skip_scrape_if_fresh_sec=skip_scrape_if_fresh_sec, + ) + ) return { "ok": True, "ensured": sum(1 for r in results if r.get("ok")), diff --git a/backend/app/ops_neko_sync.py b/backend/app/ops_neko_sync.py index e9d14b8..b4e5768 100644 --- a/backend/app/ops_neko_sync.py +++ b/backend/app/ops_neko_sync.py @@ -56,8 +56,15 @@ def sync_once() -> dict[str, Any]: _state["enabled"] = True # Keep YouTube Live Control Room open on bound ops-neko Chrome before catalog push. + # Skip heavy CDP scrape when extension/host ingest is already fresh (physical dy + # used to docker-exec scrape every 5s → RSS thrash + accept backlog). try: - live = ops_neko.ensure_bound_slots_live_studio() + live = ops_neko.ensure_bound_slots_live_studio(skip_scrape_if_fresh_sec=45.0) + except TypeError: + try: + live = ops_neko.ensure_bound_slots_live_studio() + except Exception as exc: + live = {"ok": False, "error": str(exc)[:200]} except Exception as exc: live = {"ok": False, "error": str(exc)[:200]} catalog = ops_neko.push_catalog_to_hub() @@ -89,8 +96,13 @@ def sync_once() -> dict[str, Any]: return {"ok": ok, "catalog": catalog, "binds": binds} -async def edge_sync_loop(*, interval_sec: float = 5.0) -> None: - """Background loop — only does work when peer role is edge.""" +async def edge_sync_loop(*, interval_sec: float = 30.0) -> None: + """Background loop — only does work when peer role is edge. + + Default 30s (was 5s): physical dy was CDP-scraping + catalog-pushing every 5s + while VPS hub skips this path entirely — that asymmetry is why same code + hung on dy but not dylive. + """ global _kick _kick = asyncio.Event() _state["interval_sec"] = float(interval_sec) diff --git a/backend/app/procutil.py b/backend/app/procutil.py new file mode 100644 index 0000000..42f0d0e --- /dev/null +++ b/backend/app/procutil.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +"""Spawn helpers: keep heavy ffmpeg out of douyinweb-api MemoryAccounting. + +Children inherit the service cgroup; under MemoryHigh reclaim the API accept +loop freezes (D-state). Move ffmpeg PIDs into douyinweb-ffmpeg.slice so encode +/ relay push RAM is charged separately. +""" +from __future__ import annotations + +import logging +import os +import subprocess +import time +from pathlib import Path +from typing import Any, Sequence + +log = logging.getLogger("douyinweb.procutil") + +FFMPEG_SLICE = "douyinweb-ffmpeg.slice" +_CGROUP_ROOT = Path("/sys/fs/cgroup") +_procs_path: Path | None = None +_ensured = False + + +def _resolve_cgroup_procs() -> Path | None: + """Locate cgroup.procs for the ffmpeg slice (path varies by systemd layout).""" + global _procs_path + if _procs_path and _procs_path.is_file(): + return _procs_path + candidates: list[Path] = [ + _CGROUP_ROOT / "douyinweb.slice" / FFMPEG_SLICE / "cgroup.procs", + _CGROUP_ROOT / "system.slice" / FFMPEG_SLICE / "cgroup.procs", + _CGROUP_ROOT / FFMPEG_SLICE / "cgroup.procs", + ] + try: + r = subprocess.run( + ["systemctl", "show", "-p", "ControlGroup", "--value", FFMPEG_SLICE], + capture_output=True, + text=True, + timeout=5, + check=False, + ) + cg = (r.stdout or "").strip().lstrip("/") + if cg: + candidates.insert(0, _CGROUP_ROOT / cg / "cgroup.procs") + except Exception: + pass + for p in candidates: + if p.is_file(): + _procs_path = p + return p + return None + + +def ensure_ffmpeg_slice() -> bool: + """Best-effort: create/start the slice so cgroup.procs is writable.""" + global _ensured + if _resolve_cgroup_procs() is not None: + _ensured = True + return True + try: + subprocess.run( + ["systemctl", "start", FFMPEG_SLICE], + capture_output=True, + timeout=8, + check=False, + ) + except Exception: + pass + ok = _resolve_cgroup_procs() is not None + _ensured = ok + return ok + + +def detach_pid_from_service_cgroup(pid: int) -> bool: + """Move *pid* into douyinweb-ffmpeg.slice (no-op on non-Linux / missing cgroup).""" + try: + pid_i = int(pid or 0) + except Exception: + return False + if pid_i <= 1: + return False + if os.name != "posix": + return False + if not ensure_ffmpeg_slice(): + return False + procs = _resolve_cgroup_procs() + if procs is None: + return False + try: + # Writing the leader migrates the whole thread-group. + procs.write_text(f"{pid_i}\n", encoding="utf-8") + return True + except Exception as exc: + log.debug("cgroup detach pid=%s failed: %s", pid_i, exc) + return False + + +def popen_outside_api_cgroup(cmd: Sequence[str], **kwargs: Any) -> subprocess.Popen: + """subprocess.Popen then migrate into ffmpeg slice.""" + proc = subprocess.Popen(cmd, **kwargs) # noqa: S603 + try: + if proc.pid: + # Brief yield so kernel registers the task before migrate. + time.sleep(0.02) + if detach_pid_from_service_cgroup(int(proc.pid)): + log.debug("detached pid=%s to %s", proc.pid, FFMPEG_SLICE) + except Exception: + pass + return proc + + +def run_outside_api_cgroup( + cmd: Sequence[str], + *, + timeout: float | None = None, + capture_output: bool = False, + text: bool = False, + **kwargs: Any, +) -> subprocess.CompletedProcess: + """Like subprocess.run, but child is moved out of the API cgroup.""" + stdout = subprocess.PIPE if capture_output else kwargs.pop("stdout", None) + stderr = subprocess.PIPE if capture_output else kwargs.pop("stderr", None) + proc = popen_outside_api_cgroup( + cmd, + stdout=stdout, + stderr=stderr, + text=text, + **kwargs, + ) + try: + out, err = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + proc.kill() + out, err = proc.communicate() + raise subprocess.TimeoutExpired(cmd, timeout, output=out, stderr=err) from None + return subprocess.CompletedProcess(cmd, proc.returncode, out, err) diff --git a/backend/app/shorts_clip.py b/backend/app/shorts_clip.py index 05e6262..9f1d47c 100644 --- a/backend/app/shorts_clip.py +++ b/backend/app/shorts_clip.py @@ -247,7 +247,11 @@ async def record_clip( def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]: try: - proc = subprocess.run(cmd_local, capture_output=True, text=True, timeout=sec + 90) + from .procutil import run_outside_api_cgroup + + proc = run_outside_api_cgroup( + cmd_local, capture_output=True, text=True, timeout=sec + 90 + ) except subprocess.TimeoutExpired: return {"ok": False, "error": "ffmpeg 录制超时"} except Exception as exc: diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index 4b3dec1..716be3a 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -28,6 +28,13 @@ YOUTUBE_SCOPES = " ".join( "https://www.googleapis.com/auth/youtube.force-ssl", ] ) +# Opt-in only (收益 tab / reauth). Not required for oauth_ok. +YT_MONETARY_SCOPES = " ".join( + [ + "https://www.googleapis.com/auth/yt-analytics.readonly", + "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", + ] +) # Requested on authorize so we can show Gmail on A/B/C/D; not required for oauth_ok. IDENTITY_SCOPES = "openid email profile" @@ -368,7 +375,13 @@ def channel_can_authorize(channel: dict[str, Any] | None, cfg: dict[str, Any] | return resolve_oauth_client(channel, cfg).get("source") != "none" -def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: str = "") -> str: +def build_authorize_url( + *, + channel_pk: str, + request_base: str = "", + return_to: str = "", + include_monetary: bool = False, +) -> str: _hydrate_oauth_states() cfg = _cfg() channel = db.get_shorts_channel(channel_pk) @@ -395,11 +408,12 @@ def build_authorize_url(*, channel_pk: str, request_base: str = "", return_to: s else: _oauth_states[state] = (channel_pk, now + 600, client_id, client_secret) _persist_oauth_states() + scope = authorize_scopes(include_monetary=bool(include_monetary)) params = { "client_id": client_id, "redirect_uri": resolve_redirect_uri(request_base), "response_type": "code", - "scope": authorize_scopes(), + "scope": scope, "access_type": "offline", # Must force consent to obtain refresh_token. Do NOT set include_granted_scopes — # Google often omits refresh_token when the app "already has some access". @@ -414,9 +428,18 @@ def requested_scopes() -> list[str]: return [s for s in YOUTUBE_SCOPES.split() if s] -def authorize_scopes() -> str: +def monetary_scopes() -> list[str]: + return [s for s in YT_MONETARY_SCOPES.split() if s] + + +def authorize_scopes(*, include_monetary: bool = False) -> str: """Scopes for Google consent. YouTube only — brand accounts break with openid/email.""" - return " ".join(s for s in YOUTUBE_SCOPES.split() if s) + scopes = [s for s in YOUTUBE_SCOPES.split() if s] + if include_monetary: + for s in monetary_scopes(): + if s not in scopes: + scopes.append(s) + return " ".join(scopes) FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl" @@ -565,15 +588,28 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic _stamp_oauth_error(channel_pk, err) raise ValueError(err) items = ch_data.get("items") or [] + # Prefer the brand that already matches this card's UC (multi-brand Google logins). + expected_uc = str(channel.get("youtube_channel_id") or "").strip() + expected_name = str(channel.get("name") or "").strip() + chosen: dict[str, Any] | None = None + if expected_uc and isinstance(items, list): + for it in items: + if not isinstance(it, dict): + continue + if str(it.get("id") or "").strip() == expected_uc: + chosen = it + break + if chosen is None and items and isinstance(items[0], dict): + chosen = items[0] yt_id = "" yt_title = "" yt_handle = "" - if items: - sn = items[0].get("snippet") or {} - yt_id = str(items[0].get("id") or "") + if chosen: + sn = chosen.get("snippet") or {} + yt_id = str(chosen.get("id") or "") yt_title = str(sn.get("title") or "") yt_handle = str(sn.get("customUrl") or "").strip() - if not items: + if not items or not yt_id: err = ( "Google 账号下没有可用的 YouTube 频道(mine=true 为空)。" "请确认授权时选的是有频道的品牌账号,不是空的 Google 登录号。" @@ -581,9 +617,35 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic _stamp_oauth_error(channel_pk, err) raise ValueError(err) + # Hard lock: re-auth must not rewrite this card into another brand. + # (Previously we overwrote youtube_channel_id + name → duplicate 「nomad Street Food」.) + if expected_uc and yt_id != expected_uc: + err = ( + f"授权选中的 YouTube 频道是「{yt_title or yt_id}」({yt_id})," + f"但本卡绑定的是「{expected_name or expected_uc}」({expected_uc})。" + "凭证未写入。请重新点授权,在 Google 账号/品牌列表里选对本卡的频道。" + ) + _stamp_oauth_error(channel_pk, err) + # Best-effort revoke the wrong-brand grant so it does not linger. + try: + async with httpx.AsyncClient(**_google_client_kwargs(timeout=15.0)) as client: + await client.post( + "https://oauth2.googleapis.com/revoke", + data={"token": access}, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + if refresh: + await client.post( + "https://oauth2.googleapis.com/revoke", + data={"token": refresh}, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + except Exception: + pass + raise ValueError(err) + google_email = await fetch_google_account_email(access) - # Clicked card wins: accept whatever brand Google returned; never rewrite siblings. # Soft-warn if the same YouTube channel is already bound to another Shorts card. dup_warn = "" if yt_id: @@ -637,12 +699,13 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic "client_secret": client_secret, "refresh_token": refresh, } - if yt_id: + # Only set UC when card had none; never swap to a different UC (guarded above). + if yt_id and not expected_uc: patch["youtube_channel_id"] = yt_id if google_email: patch["oauth_email"] = google_email - # Refresh display name/handle from Google — brand label may differ from old card title. - if yt_title: + # Keep operator card title on reauth — never auto-rename into another brand's title. + if yt_title and not expected_name: patch["name"] = yt_title if profile_id and not str(channel.get("oauth_profile_id") or "").strip(): patch["oauth_profile_id"] = profile_id diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index bcd776b..9d9aa8a 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -1097,9 +1097,16 @@ class ShortsPipeline: if job: runner = "upload" if not job and self._active_records < record_max: - job = db.claim_pending_shorts_record() - if job: - runner = "record" + try: + from .host_metrics import clip_encode_defer_reason + + defer_rec = clip_encode_defer_reason() + except Exception: + defer_rec = "" + if not defer_rec: + job = db.claim_pending_shorts_record() + if job: + runner = "record" if not job: await asyncio.sleep(2) continue diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index f2fcafc..0361e36 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -427,7 +427,13 @@ class TikTokPipeline: self._active_uploads += 1 asyncio.create_task(self._run_upload(job)) max_rec = max(1, int(cfg.get("tiktok_max_concurrent") or 1)) - while self._active_records < max_rec: + try: + from .host_metrics import clip_encode_defer_reason + + defer_rec = clip_encode_defer_reason() + except Exception: + defer_rec = "" + while not defer_rec and self._active_records < max_rec: job = tiktok_db.claim_pending_tiktok_record() if not job: break diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py index 72ef712..0cac5bd 100644 --- a/backend/app/x_clips_pipeline.py +++ b/backend/app/x_clips_pipeline.py @@ -392,7 +392,13 @@ class XClipsPipeline: self.last_error = str(exc)[:240] max_rec = max(1, int(cfg.get("x_clips_max_concurrent") or 1)) - while self._active_records < max_rec: + try: + from .host_metrics import clip_encode_defer_reason + + defer_rec = clip_encode_defer_reason() + except Exception: + defer_rec = "" + while not defer_rec and self._active_records < max_rec: pending = x_clips_db.list_pending_x_clip_jobs(limit=1) if not pending: break diff --git a/backend/app/youtube_live.py b/backend/app/youtube_live.py index 9d34009..1e1de28 100644 --- a/backend/app/youtube_live.py +++ b/backend/app/youtube_live.py @@ -756,10 +756,9 @@ async def _build_live_map_unlocked(*, now: float) -> dict[str, Any]: assign_groups = await asyncio.to_thread( lambda: yt_assign_db.list_groups(include_urls=False) ) - relay_payload = await asyncio.to_thread(youtube_relay_pipeline.status) - relay_rows = { - str(r.get("group_id") or ""): r for r in (relay_payload.get("groups") or []) - } + # Do NOT call full relay.status() here — it rebuilds heavy studio/neko payloads and + # used to recurse into douyin live-map (RSS blow-up on physical dy). + relay_rows = await asyncio.to_thread(youtube_relay_pipeline.pushing_flags) pk_to_gid: dict[str, str] = {} gid_to_name: dict[str, str] = {} for g in assign_groups: diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py index 297a279..3e9545b 100644 --- a/backend/app/youtube_manage.py +++ b/backend/app/youtube_manage.py @@ -221,33 +221,29 @@ async def _mirror_avatar_to_s3(channel_pk: str, cdn_url: str) -> str: async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]: token, ch = await _access_for_channel(channel_pk) - yt_id = str(ch.get("youtube_channel_id") or "").strip() + expected_uc = str(ch.get("youtube_channel_id") or "").strip() # Include status → isChannelMonetizationEnabled so YPP is written with the same call. params: dict[str, Any] = {"part": "snippet,contentDetails,statistics,brandingSettings,status"} - if yt_id: - params["id"] = yt_id + if expected_uc: + params["id"] = expected_uc else: params["mine"] = "true" data = await _get("channels", token=token, params=params) items = data.get("items") or [] - if not items and yt_id: - # Stored id may be stale — fall back to mine=true (brand picker during OAuth). - data = await _get( - "channels", - token=token, - params={"part": "snippet,contentDetails,statistics,brandingSettings,status", "mine": "true"}, + if not items and expected_uc: + # Token may belong to another brand — refuse mine=true rewrite of this card. + raise ValueError( + f"授权凭证读不到本卡绑定的频道 {expected_uc}。" + "请对本卡重新授权,并在 Google 品牌列表中选对频道(禁止选成其它品牌)。" ) - items = data.get("items") or [] if not items: raise ValueError("未拿到频道资料(请确认授权账号下有频道,且 Google 项目已启用 YouTube Data API v3)") item = items[0] - # If stored youtube_channel_id differs, still return mine (Brand account caveat) yt_id = str(item.get("id") or "") - if yt_id and yt_id != str(ch.get("youtube_channel_id") or ""): - try: - db.update_shorts_channel(channel_pk, youtube_channel_id=yt_id, name=str((item.get("snippet") or {}).get("title") or ch.get("name"))) - except Exception: - pass + if expected_uc and yt_id and yt_id != expected_uc: + raise ValueError( + f"返回频道 {yt_id} 与本卡绑定 {expected_uc} 不一致,已拒绝写入资料缓存。" + ) uploads = ((item.get("contentDetails") or {}).get("relatedPlaylists") or {}).get("uploads") or "" sn = item.get("snippet") or {} st = item.get("statistics") or {} @@ -264,13 +260,13 @@ async def fetch_channel_profile(channel_pk: str) -> dict[str, Any]: try: from .yt_long_monetize import _persist_ypp_for_shorts - _persist_ypp_for_shorts(shorts_pk=channel_pk, ypp=ypp, youtube_channel_id=yt_id) + _persist_ypp_for_shorts(shorts_pk=channel_pk, ypp=ypp, youtube_channel_id=yt_id or expected_uc) except Exception: log.exception("persist ypp_ok failed for %s", channel_pk) profile = { "ok": True, "channel_pk": channel_pk, - "youtube_channel_id": yt_id, + "youtube_channel_id": yt_id or expected_uc, "title": sn.get("title"), "description": sn.get("description"), "custom_url": sn.get("customUrl"), @@ -331,6 +327,16 @@ def save_yt_profile_cache(channel_pk: str, profile: dict[str, Any]) -> None: import time snippet = profile_snippet(profile) or {} + # Refuse caching a profile for a different UC than this Shorts card + # (bad OAuth brand pick used to poison the UI as another channel). + try: + ch = db.get_shorts_channel(channel_pk) or {} + expect = str(ch.get("youtube_channel_id") or "").strip() + got = str(snippet.get("youtube_channel_id") or profile.get("youtube_channel_id") or profile.get("id") or "").strip() + if expect and got and expect != got: + return + except Exception: + pass snippet["fetched_at"] = time.time() # Drop heavy raw if present payload = { diff --git a/backend/app/youtube_neko.py b/backend/app/youtube_neko.py index 1fe8412..8e4270f 100644 --- a/backend/app/youtube_neko.py +++ b/backend/app/youtube_neko.py @@ -1048,10 +1048,14 @@ def sync_caddy_neko_snippet(count: int) -> dict[str, Any]: def _host_http_ok(instance_id: int) -> bool: """True when published host port answers (detects stale containers with empty PortBindings).""" port = _http_port(int(instance_id)) + # Always bypass env HTTP(S)_PROXY — otherwise curl to 127.0.0.1:920x goes via proxy + # and falsely reports dead, triggering endless force-recreate → public /neko/N 502. code, text = _run( [ "curl", "-sS", + "--noproxy", + "*", "-o", "/dev/null", "-w", @@ -1437,20 +1441,88 @@ def stop_instances_except(keep_instance_id: int) -> list[int]: return stopped +def _host_http_published(instance_id: int) -> bool: + """True when docker-proxy has the instance HTTP port (even if app still booting).""" + port = _http_port(int(instance_id)) + code, text = _run( + ["ss", "-lnt"], + timeout=6, + ) + needle = f":{port}" + return code == 0 and needle in (text or "") + + def ensure_instance_running(instance_id: int) -> dict[str, Any]: """Ensure one Neko container exists and is running (for exclusive-live winner).""" + import time as _time + _ensure_browser_launch_exec() idx = int(instance_id or 0) if idx < 1: return {"ok": False, "skipped": "no_instance"} desired = max(_desired_from_db(), idx) ensure_capacity(desired, start_instances={idx}, reconcile_running=False) + name = _container_name(idx) + svc = f"neko{idx}" st = _container_state(idx) - if st.get("running"): + if st.get("running") and _host_http_ok(idx): return {"ok": True, "id": idx, "already": True} - code, out = _run(["docker", "start", _container_name(idx)], timeout=60) + + # Booting: port published but / not answering yet — wait, do not recreate (avoids 502 races). + if st.get("running") and _host_http_published(idx) and not _host_http_ok(idx): + for _ in range(20): + _time.sleep(2.0) + if _host_http_ok(idx): + return {"ok": True, "id": idx, "waited_boot": True} + # fall through to recreate only if still dead after ~40s + + # Stale exists with no published HTTP — force remove then compose up once. + if st.get("exists") and (not st.get("running") or not _host_http_ok(idx)): + _run(["docker", "rm", "-f", name], timeout=45) + ensure_capacity(desired, start_instances=set()) + code, out = _run( + _compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc), + timeout=300, + ) + if code != 0: + return {"ok": False, "id": idx, "error": (out or "force-recreate failed")[:300]} + _run(["docker", "start", name], timeout=60) + for _ in range(20): + if _host_http_ok(idx): + return {"ok": True, "id": idx, "recreated": True} + _time.sleep(2.0) + return { + "ok": False, + "id": idx, + "error": f"recreated but host port {_http_port(idx)} unreachable", + } + + code, out = _run(["docker", "start", name], timeout=60) if code != 0: return {"ok": False, "id": idx, "error": (out or "start failed")[:300]} + for _ in range(15): + if _host_http_ok(idx): + return {"ok": True, "id": idx, "started": True} + _time.sleep(2.0) + if not _host_http_ok(idx): + _run(["docker", "rm", "-f", name], timeout=45) + ensure_capacity(desired, start_instances=set()) + code, out = _run( + _compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc), + timeout=300, + ) + if code != 0: + return {"ok": False, "id": idx, "error": (out or "force-recreate failed")[:300]} + _run(["docker", "start", name], timeout=60) + for _ in range(20): + if _host_http_ok(idx): + return {"ok": True, "id": idx, "recreated": True} + _time.sleep(2.0) + return { + "ok": False, + "id": idx, + "error": f"started but host port {_http_port(idx)} unreachable", + } return {"ok": True, "id": idx, "started": True} @@ -2403,15 +2475,38 @@ def wait_instance_ready_for_live( if isinstance(sig, dict) and sig.get("ok"): preparing = bool(sig.get("preparing_stream")) control_ready = bool(sig.get("control_ready")) + chrome_offline = bool(sig.get("chrome_offline")) or ( + "err_internet" in str(sig.get("text") or "").lower() + or "no internet" in str(sig.get("text") or "").lower() + ) + encoder_receiving = bool( + (sig.get("encoder_receiving") or sig.get("on_air")) + and not chrome_offline + ) if sig.get("live_status"): live_status = str(sig.get("live_status") or live_status) if sig.get("health"): health = str(sig.get("health") or health) + if chrome_offline: + # Chrome interstitial ≠ Studio receiving — keep waiting. + _time.sleep(2.0) + continue if preparing: # Keep waiting — never hand off to FFmpeg while preview spins. _time.sleep(2.0) continue - if not control_ready and live_status not in {"live", "waiting", "encoder_lost"}: + # Receiving-first: Studio already accepting encoder → do not block on + # SPA chrome flags (control_ready can lag while ingest is healthy). + if encoder_receiving: + control_ready = True + if not live_status: + live_status = "live" if sig.get("on_air") else "receiving" + if not control_ready and live_status not in { + "live", + "waiting", + "encoder_lost", + "receiving", + }: _time.sleep(2.0) continue return { @@ -2633,16 +2728,23 @@ def recreate_all_instances(*, start_enabled: bool = True) -> dict[str, Any]: # --- Studio telemetry ingest (sh2 live-ops extension) --- _studio_events: list[dict[str, Any]] = [] -_STUDIO_EVENTS_MAX = 200 +# Keep ring buffer small — dozens of Nekos POSTing every few seconds otherwise +# retain hundreds of full Studio payloads and push RSS over MemoryHigh. +_STUDIO_EVENTS_MAX = 80 _studio_latest_by_neko: dict[int, dict[str, Any]] = {} _studio_latest_by_ref: dict[str, dict[str, Any]] = {} _studio_minute_reports: dict[int, list[dict[str, Any]]] = {} _studio_minute_reports_by_ref: dict[str, list[dict[str, Any]]] = {} _studio_minute_last_at: dict[int, float] = {} _studio_minute_last_at_by_ref: dict[str, float] = {} -_STUDIO_MINUTE_MAX = 120 +_STUDIO_MINUTE_MAX = 60 _studio_bootstrapped = False _CDP_POLL_INTERVAL_SEC = 55.0 +# Per-ref coalesce: drop duplicate ingest storms that only update timestamps. +_studio_ingest_last_fp: dict[str, tuple[float, str]] = {} +_STUDIO_INGEST_COALESCE_SEC = 12.0 +_STUDIO_DISK_WRITE_MIN_INTERVAL = 30.0 +_studio_disk_write_at = 0.0 def parse_neko_ref(raw: Any) -> tuple[str, str, int]: @@ -2966,12 +3068,34 @@ def _maybe_append_minute_report(neko_id: int, event: dict[str, Any], *, ref_key: pass -_studio_disk_write_at: float = 0.0 -_STUDIO_DISK_WRITE_MIN_INTERVAL = 2.0 +def _studio_ingest_fingerprint(body: dict[str, Any]) -> str: + """Cheap fingerprint so unchanged Studio chrome doesn't allocate new events. + + Intentionally ignores tick-level viewer_count / duration — those change every few + seconds during a live and would defeat coalesce (dy RSS climb). + """ + signals = body.get("signals") if isinstance(body.get("signals"), dict) else {} + return "|".join( + [ + str(body.get("live_status") or ""), + str(body.get("health") or ""), + "1" if body.get("on_air") else "0", + "1" if signals.get("encoder_receiving") else "0", + "1" if signals.get("nodata") else "0", + "1" if signals.get("encoder_lost") else "0", + "1" if signals.get("chrome_offline") else "0", + str(body.get("url") or "")[-48:], + ] + ) def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: - """Accept Studio telemetry from in-container Chrome extension (local or ops-neko).""" + """Accept Studio telemetry from in-container Chrome extension (local or ops-neko). + + Hot path must stay allocation-light: Neko tabs POST every few seconds. Duplicate + fingerprints are coalesced in-place so RSS cannot climb into MemoryHigh thrash + (dy historically hung in D-state with /api/health timing out while PID stayed "active"). + """ import time as _time import uuid @@ -2986,6 +3110,60 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: body["neko_ref"] = ref_key body["neko_kind"] = kind now = float(body.get("received_at") or _time.time()) + coalesce_key = ref_key or (f"local:{neko_id}" if neko_id > 0 else "") + fp = _studio_ingest_fingerprint(body) + if coalesce_key: + prev = _studio_ingest_last_fp.get(coalesce_key) + if prev and (now - float(prev[0])) < _STUDIO_INGEST_COALESCE_SEC and prev[1] == fp: + # Refresh latest timestamp + volatile counters in-place — no new event alloc. + existing = _studio_latest_by_ref.get(coalesce_key) or ( + _studio_latest_by_neko.get(neko_id) if neko_id > 0 else None + ) + if isinstance(existing, dict): + existing["received_at"] = now + payload_ex = existing.get("payload") + if isinstance(payload_ex, dict): + payload_ex["received_at"] = now + for k in ( + "viewer_count", + "total_views", + "like_count", + "live_duration", + "live_duration_sec", + "stream_title", + ): + if k in body and body.get(k) is not None: + payload_ex[k] = body.get(k) + # Still stamp minute buckets while coalescing (55s gate inside). + try: + _maybe_append_minute_report( + neko_id, + existing, + ref_key=ref_key or coalesce_key, + kind=kind, + ) + except Exception: + pass + # Slide coalesce window so stable live doesn't allocate every 12s forever. + _studio_ingest_last_fp[coalesce_key] = (now, fp) + return { + "ok": True, + "coalesced": True, + "event": { + "id": existing.get("id"), + "received_at": now, + "neko_instance_id": neko_id, + "neko_ref": ref_key, + "neko_kind": kind, + }, + } + _studio_ingest_last_fp[coalesce_key] = (now, fp) + # Bound coalesce map (ops refs can churn over weeks). + if len(_studio_ingest_last_fp) > 256: + oldest = sorted(_studio_ingest_last_fp.items(), key=lambda kv: float(kv[1][0]))[:64] + for k, _ in oldest: + _studio_ingest_last_fp.pop(k, None) + event = { "id": str(uuid.uuid4()), "received_at": now, @@ -3004,8 +3182,7 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: _maybe_append_minute_report(neko_id, event, ref_key=f"local:{neko_id}", kind="local") if neko_id > 0: _studio_latest_by_neko[neko_id] = event - # Dozens of Neko tabs POST every ~1–2s; indent+rewrite of one file saturates the - # default thread pool and wedges /api/health (to_thread). Debounce disk persist. + # Debounce disk persist — under MemoryHigh reclaim, sync writes → D-state hangs. if now - _studio_disk_write_at >= _STUDIO_DISK_WRITE_MIN_INTERVAL: _studio_disk_write_at = now try: @@ -3018,7 +3195,7 @@ def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]: "event": { "id": event["id"], "received_at": event["received_at"], - "neko_instance_id": neko_id, + "neko_instance_id": event["neko_instance_id"], "neko_ref": ref_key, "neko_kind": kind, }, diff --git a/backend/app/youtube_relay.py b/backend/app/youtube_relay.py index a5eef2e..ae62ab7 100644 --- a/backend/app/youtube_relay.py +++ b/backend/app/youtube_relay.py @@ -219,6 +219,95 @@ def _terminate_proc(proc: subprocess.Popen | None) -> None: pass +def kill_ffmpeg_sharing_rtmp(youtube_rtmp: str, *, keep_pid: int = 0) -> list[int]: + """Kill other host ffmpeg processes already pushing the same YouTube stream key. + + YouTube returns "More than one ingestion is using the primary URL" when two + encoders share one key — Studio health goes Poor and public live flaps. + """ + import os + + key = (youtube_rtmp or "").rstrip("/").split("/")[-1].strip() + if len(key) < 8: + return [] + try: + out = subprocess.check_output(["ps", "-eo", "pid,cmd"], text=True, timeout=8) + except Exception: + return [] + killed: list[int] = [] + keep = int(keep_pid or 0) + keep_set = {keep} if keep > 0 else set() + # Also protect children of keep (proxychains → ffmpeg). + if keep > 0: + try: + for line in out.splitlines(): + parts = line.split(None, 1) + if len(parts) < 2: + continue + try: + pid = int(parts[0]) + except Exception: + continue + # /proc ppid check below + except Exception: + pass + try: + import pathlib + + for proc_dir in pathlib.Path("/proc").iterdir(): + if not proc_dir.name.isdigit(): + continue + pid = int(proc_dir.name) + try: + status = (proc_dir / "status").read_text(encoding="utf-8", errors="ignore") + except Exception: + continue + for ln in status.splitlines(): + if ln.startswith("PPid:"): + try: + ppid = int(ln.split()[1]) + except Exception: + break + if ppid in keep_set or pid == keep: + keep_set.add(pid) + break + except Exception: + pass + for line in out.splitlines(): + low = line.lower() + if "ffmpeg" not in low or key not in line: + continue + # Only YouTube ingest destinations — never match unrelated ffmpeg with same token. + if "rtmps.youtube.com" not in low and "rtmp.youtube.com" not in low and "/live2/" not in low: + continue + try: + pid = int(line.split(None, 1)[0]) + except Exception: + continue + if pid in keep_set: + continue + try: + os.kill(pid, 9) + killed.append(pid) + except Exception: + pass + return killed + + +_RTMP_SPAWN_LOCKS: dict[str, threading.Lock] = {} +_RTMP_SPAWN_LOCKS_MU = threading.Lock() + + +def _rtmp_spawn_lock(youtube_rtmp: str) -> threading.Lock: + key = (youtube_rtmp or "").rstrip("/").split("/")[-1].strip() or "_" + with _RTMP_SPAWN_LOCKS_MU: + lock = _RTMP_SPAWN_LOCKS.get(key) + if lock is None: + lock = threading.Lock() + _RTMP_SPAWN_LOCKS[key] = lock + return lock + + class RelayPushSession: """One FFmpeg push subprocess with stderr monitoring. @@ -325,6 +414,51 @@ class RelayPushSession: self.stats.recent_log.append( f"[ffmpeg] source {self._source_index + 1}/{len(self.input_urls)} -i {self.input_url[:160]}" ) + # Serialize spawn per stream key so two sessions cannot Popen then + # mutually kill each other via post-spawn rival cleanup. + with _rtmp_spawn_lock(self.youtube_rtmp): + # Do NOT pre-kill without keep_pid: a concurrent session may already + # hold the only healthy encoder for this key. + try: + try: + from . import egress_hub + + wrapped = egress_hub.wrap_ffmpeg_cmd(cmd) + if wrapped != cmd: + self.stats.recent_log.append( + f"[ffmpeg] egress proxychains mode={egress_hub.get_mode()}" + ) + cmd = wrapped + except Exception as exc: + self.stats.recent_log.append(f"[ffmpeg] egress wrap skipped: {exc}") + # Keep encode RAM out of douyinweb-api MemoryHigh (D-state hang). + from .procutil import popen_outside_api_cgroup + + self._proc = popen_outside_api_cgroup( + cmd, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + bufsize=1, + ) + except FileNotFoundError: + self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found") + self.stats.running = False + return + except Exception as exc: + self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}") + self.stats.running = False + return + + self.stats.pid = int(self._proc.pid or 0) + self.stats.running = True + try: + rivals = kill_ffmpeg_sharing_rtmp(self.youtube_rtmp, keep_pid=self.stats.pid) + if rivals: + self.stats.recent_log.append(f"[ffmpeg] post-spawn killed rivals {rivals}") + except Exception: + pass def _reader() -> None: proc = self._proc @@ -345,37 +479,6 @@ class RelayPushSession: finally: q.put(None) - try: - try: - from . import egress_hub - - wrapped = egress_hub.wrap_ffmpeg_cmd(cmd) - if wrapped != cmd: - self.stats.recent_log.append( - f"[ffmpeg] egress proxychains mode={egress_hub.get_mode()}" - ) - cmd = wrapped - except Exception as exc: - self.stats.recent_log.append(f"[ffmpeg] egress wrap skipped: {exc}") - self._proc = subprocess.Popen( - cmd, - stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, - stderr=subprocess.PIPE, - text=True, - bufsize=1, - ) - except FileNotFoundError: - self.stats.recent_log.append("[ffmpeg] ERROR: ffmpeg binary not found") - self.stats.running = False - return - except Exception as exc: - self.stats.recent_log.append(f"[ffmpeg] ERROR spawn failed: {exc}") - self.stats.running = False - return - - self.stats.pid = int(self._proc.pid or 0) - self.stats.running = True self.stats.recent_log.append(f"[ffmpeg] pid={self.stats.pid} started") if self.on_stats: try: diff --git a/backend/app/youtube_relay_pipeline.py b/backend/app/youtube_relay_pipeline.py index 0c4ddd8..7183e0a 100644 --- a/backend/app/youtube_relay_pipeline.py +++ b/backend/app/youtube_relay_pipeline.py @@ -37,10 +37,19 @@ def _live_room_ids() -> set[str]: def _douyin_live_count_cached() -> int: + """Cheap live room count — never rebuild the full douyin live-map (that allocates huge dicts).""" try: from . import douyin_live - return int(douyin_live.build_live_map().get("live_count") or 0) + cached = douyin_live._CACHE.get("payload") # noqa: SLF001 + if isinstance(cached, dict) and (time.time() - float(douyin_live._CACHE.get("at") or 0)) < float( + getattr(douyin_live, "_CACHE_TTL_SEC", 12.0) + ): + return int(cached.get("live_count") or 0) + except Exception: + pass + try: + return int(db.monitor_status_data(light=True).get("counts", {}).get("live_rooms") or 0) except Exception: try: return len(_live_room_ids()) @@ -305,6 +314,29 @@ class YoutubeRelayPipeline: ) return True, msg + def pushing_flags(self) -> dict[str, dict[str, bool]]: + """Lightweight {group_id: {is_pushing}} for live-map — avoids full status rebuild.""" + out: dict[str, dict[str, bool]] = {} + try: + states = {str(s.get("group_id") or ""): s for s in youtube_relay_db.list_relay_states()} + except Exception: + states = {} + for gid, st in states.items(): + if not gid: + continue + sess = self._sessions.get(gid) + running = bool(sess and sess.stats.running) + orphan_pid = int(st.get("ffmpeg_pid") or 0) + orphan_alive = (not running) and _ffmpeg_pid_alive(orphan_pid) + raw = str(st.get("status") or "").lower() + pushing = running or orphan_alive or raw in {"pushing", "streaming"} + out[gid] = {"is_pushing": pushing} + for gid, sess in list(self._sessions.items()): + if gid in out: + continue + out[gid] = {"is_pushing": bool(sess and sess.stats.running)} + return out + def status(self) -> dict[str, Any]: now = time.time() cached = self._status_cache @@ -429,7 +461,30 @@ class YoutubeRelayPipeline: "ops_neko_slot": int(g.get("ops_neko_slot") or 0), } try: - snap = youtube_neko.studio_snapshot_for_group(g, max_age_sec=120.0) + # Keep lean minute_reports for the status panel chart (LIVE 时长≠空报告). + # Cap fields so poll JSON stays small — no text/html blobs. + snap = youtube_neko.studio_snapshot_for_group( + g, max_age_sec=120.0, include_minute_reports=True + ) + raw_reports = snap.get("minute_reports") if isinstance(snap.get("minute_reports"), list) else [] + lean_reports: list[dict[str, Any]] = [] + for mr in raw_reports[:45]: + if not isinstance(mr, dict): + continue + lean_reports.append( + { + "ts": mr.get("ts"), + "viewer_count": mr.get("viewer_count"), + "total_views": mr.get("total_views"), + "like_count": mr.get("like_count"), + "live_duration": str(mr.get("live_duration") or "")[:16], + "live_duration_sec": mr.get("live_duration_sec"), + "on_air": bool(mr.get("on_air")), + "live_status": str(mr.get("live_status") or "")[:24], + "health": str(mr.get("health") or "")[:24], + "neko_ref": str(mr.get("neko_ref") or "")[:32], + } + ) neko_state["studio"] = { "live_page_open": bool(snap.get("live_page_open")), "on_air": bool(snap.get("on_air")), @@ -445,7 +500,7 @@ class YoutubeRelayPipeline: "received_at": snap.get("received_at") or 0, "age_sec": snap.get("age_sec"), "detect_source": snap.get("detect_source") or "", - "minute_reports": snap.get("minute_reports") or [], + "minute_reports": lean_reports, "neko_ref": snap.get("neko_ref") or "", "neko_kind": snap.get("neko_kind") or "", "ui_source": snap.get("ui_source") or "", diff --git a/backend/app/yt_long_clip.py b/backend/app/yt_long_clip.py index debafa1..05fad05 100644 --- a/backend/app/yt_long_clip.py +++ b/backend/app/yt_long_clip.py @@ -135,7 +135,9 @@ async def record_long_clip( def _run(cmd_local: list[str] = cmd, used_url: str = url) -> dict[str, Any]: try: - proc = subprocess.run( + from .procutil import run_outside_api_cgroup + + proc = run_outside_api_cgroup( cmd_local, capture_output=True, text=True, diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index c383318..d410f32 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -535,6 +535,13 @@ class YtLongPipeline: cfg = db.get_settings_map() max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) # Never reclaim active long recordings here (3–8 min + encode); loop handles orphans safely + try: + from .host_metrics import clip_encode_defer_reason + + if clip_encode_defer_reason(): + return 0 + except Exception: + pass db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") slots = max(0, max_rec - max(self._active_records, db_recording)) if slots <= 0: @@ -642,7 +649,18 @@ class YtLongPipeline: pass except Exception: pass - while self._active_records < max_rec and db_recording < max_rec: + # Never steal CPU from live YouTube push (site hang root cause on dy VPS). + try: + from .host_metrics import clip_encode_defer_reason + + defer = clip_encode_defer_reason() + except Exception: + defer = "" + while ( + not defer + and self._active_records < max_rec + and db_recording < max_rec + ): pending = yt_long_db.list_pending_yt_long_jobs(limit=1) if not pending: break diff --git a/backend/app/yt_revenue.py b/backend/app/yt_revenue.py new file mode 100644 index 0000000..81a7aff --- /dev/null +++ b/backend/app/yt_revenue.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +"""YouTube AdSense / Analytics monetary revenue — linked to Live / Shorts / 长视频. + +Uses YouTube Analytics API v2 estimatedRevenue metrics. Requires opt-in OAuth +scopes (yt-analytics-monetary.readonly) — not part of default upload oauth_ok. +""" +from __future__ import annotations + +import time +from datetime import date, datetime, timedelta, timezone +from typing import Any + +import httpx + +from . import db +from . import yt_assign_db +from .shorts_oauth import channel_oauth_creds, monetary_scopes, token_scopes +from .shorts_upload import refresh_access_token + +_ANALYTICS = "https://youtubeanalytics.googleapis.com/v2/reports" +_CACHE: dict[str, tuple[float, dict[str, Any]]] = {} +_CACHE_TTL_SEC = 900.0 # 15 min + +_CONTENT_MAP = { + "LIVE_STREAM": "live", + "SHORTS": "shorts", + "VIDEO_ON_DEMAND": "long", + # legacy / alternate labels + "LIVE": "live", + "ON_DEMAND": "long", +} + + +def _beijing_today() -> date: + return datetime.now(timezone(timedelta(hours=8))).date() + + +def _httpx_kwargs(*, timeout: float = 45.0) -> dict[str, Any]: + try: + from . import egress_hub + + return egress_hub.google_httpx_kwargs(timeout=timeout) + except Exception: + return {"timeout": timeout, "trust_env": False} + + +def _parse_float(v: Any) -> float | None: + try: + if v is None or v == "": + return None + return float(v) + except (TypeError, ValueError): + return None + + +def _empty_bucket() -> dict[str, Any]: + return { + "estimated_revenue": 0.0, + "estimated_ad_revenue": 0.0, + "gross_revenue": 0.0, + "monetized_playbacks": 0.0, + "ad_impressions": 0.0, + "playback_based_cpm": None, + } + + +def _add_row(bucket: dict[str, Any], cols: dict[str, Any]) -> None: + for k in ( + "estimated_revenue", + "estimated_ad_revenue", + "gross_revenue", + "monetized_playbacks", + "ad_impressions", + ): + bucket[k] = float(bucket.get(k) or 0) + float(cols.get(k) or 0) + cpm = cols.get("playback_based_cpm") + if cpm is not None: + bucket["playback_based_cpm"] = cpm + + +async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]: + ch = db.get_shorts_channel(channel_pk) + if not ch: + raise ValueError("频道不存在") + creds = channel_oauth_creds(ch) + if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]): + raise ValueError("频道未授权 Google OAuth") + token = await refresh_access_token( + client_id=creds["client_id"], + client_secret=creds["client_secret"], + refresh_token=creds["refresh_token"], + ) + return token, ch + + +async def channel_monetary_ready(channel_pk: str) -> dict[str, Any]: + """Check whether this Shorts OAuth token has Analytics monetary scopes.""" + try: + token, ch = await _access_for_channel(channel_pk) + except Exception as exc: + return { + "ok": False, + "authorized": False, + "monetary_ok": False, + "error": str(exc)[:200], + "missing_scopes": monetary_scopes(), + } + granted = await token_scopes(token) + need = set(monetary_scopes()) + missing = sorted(s for s in need if s not in granted) + return { + "ok": True, + "authorized": True, + "monetary_ok": not missing, + "missing_scopes": missing, + "channel_pk": channel_pk, + "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), + "name": str(ch.get("name") or ch.get("title") or ""), + } + + +async def _query_reports( + access: str, + *, + start: str, + end: str, + metrics: str, + dimensions: str = "", + filters: str = "", +) -> dict[str, Any]: + params: dict[str, str] = { + "ids": "channel==MINE", + "startDate": start, + "endDate": end, + "metrics": metrics, + } + if dimensions: + params["dimensions"] = dimensions + if filters: + params["filters"] = filters + async with httpx.AsyncClient(**_httpx_kwargs()) as client: + resp = await client.get( + _ANALYTICS, + params=params, + headers={"Authorization": f"Bearer {access}"}, + ) + data = resp.json() if resp.content else {} + if resp.status_code >= 400: + err = data.get("error") if isinstance(data, dict) else None + msg = "" + if isinstance(err, dict): + msg = str(err.get("message") or err) + raise RuntimeError(msg or f"analytics HTTP {resp.status_code}: {str(data)[:240]}") + return data if isinstance(data, dict) else {} + + +def _rows_as_dicts(report: dict[str, Any]) -> list[dict[str, Any]]: + headers = [str(h.get("name") or "") for h in (report.get("columnHeaders") or []) if isinstance(h, dict)] + out: list[dict[str, Any]] = [] + for row in report.get("rows") or []: + if not isinstance(row, (list, tuple)): + continue + item: dict[str, Any] = {} + for i, name in enumerate(headers): + if i >= len(row): + break + item[name] = row[i] + out.append(item) + return out + + +def _metric_cols(row: dict[str, Any]) -> dict[str, Any]: + return { + "estimated_revenue": _parse_float(row.get("estimatedRevenue")) or 0.0, + "estimated_ad_revenue": _parse_float(row.get("estimatedAdRevenue")) or 0.0, + "gross_revenue": _parse_float(row.get("grossRevenue")) or 0.0, + "monetized_playbacks": _parse_float(row.get("monetizedPlaybacks")) or 0.0, + "ad_impressions": _parse_float(row.get("adImpressions")) or 0.0, + "playback_based_cpm": _parse_float(row.get("playbackBasedCpm")), + } + + +_METRICS = ( + "estimatedRevenue,estimatedAdRevenue,grossRevenue," + "monetizedPlaybacks,adImpressions,playbackBasedCpm" +) + + +async def fetch_channel_revenue( + channel_pk: str, + *, + days: int = 28, + force: bool = False, +) -> dict[str, Any]: + """Pull AdSense-linked YouTube Analytics revenue for one OAuth channel.""" + days_i = max(1, min(90, int(days or 28))) + cache_key = f"{channel_pk}:{days_i}" + now = time.time() + if not force: + hit = _CACHE.get(cache_key) + if hit and (now - float(hit[0])) < _CACHE_TTL_SEC: + return dict(hit[1]) + + ready = await channel_monetary_ready(channel_pk) + if not ready.get("authorized"): + out = { + "ok": False, + "channel_pk": channel_pk, + "error": ready.get("error") or "未授权", + "monetary_ok": False, + "need_reauth": True, + } + return out + if not ready.get("monetary_ok"): + out = { + "ok": False, + "channel_pk": channel_pk, + "name": ready.get("name"), + "youtube_channel_id": ready.get("youtube_channel_id"), + "error": "缺少 YouTube Analytics 收益权限,请在本页点击「授权收益」", + "monetary_ok": False, + "need_reauth": True, + "missing_scopes": ready.get("missing_scopes") or [], + } + return out + + token, ch = await _access_for_channel(channel_pk) + end = _beijing_today() + start = end - timedelta(days=days_i - 1) + start_s, end_s = start.isoformat(), end.isoformat() + + by_type = { + "live": _empty_bucket(), + "shorts": _empty_bucket(), + "long": _empty_bucket(), + "other": _empty_bucket(), + } + daily: list[dict[str, Any]] = [] + totals = _empty_bucket() + type_error = "" + + try: + total_report = await _query_reports( + token, start=start_s, end=end_s, metrics=_METRICS, dimensions="day" + ) + for row in _rows_as_dicts(total_report): + cols = _metric_cols(row) + _add_row(totals, cols) + daily.append({"day": str(row.get("day") or ""), **cols}) + except Exception as exc: + return { + "ok": False, + "channel_pk": channel_pk, + "name": str(ch.get("name") or ""), + "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), + "error": str(exc)[:300], + "monetary_ok": True, + "need_reauth": "insufficient" in str(exc).lower() or "scope" in str(exc).lower(), + } + + try: + type_report = await _query_reports( + token, + start=start_s, + end=end_s, + metrics=_METRICS, + dimensions="creatorContentType", + ) + for row in _rows_as_dicts(type_report): + raw = str(row.get("creatorContentType") or "").strip().upper() + key = _CONTENT_MAP.get(raw, "other") + _add_row(by_type[key], _metric_cols(row)) + except Exception as exc: + # Some channels/API versions lack creatorContentType — keep totals, note gap. + type_error = str(exc)[:240] + # Fallback: liveOrOnDemand if available + try: + lod = await _query_reports( + token, + start=start_s, + end=end_s, + metrics=_METRICS, + dimensions="liveOrOnDemand", + ) + for row in _rows_as_dicts(lod): + raw = str(row.get("liveOrOnDemand") or "").strip().upper() + key = "live" if raw == "LIVE" else "long" + _add_row(by_type[key], _metric_cols(row)) + type_error = "" + except Exception as exc2: + type_error = f"{type_error}; fallback: {exc2}"[:300] + + links = _product_links( + youtube_channel_id=str(ch.get("youtube_channel_id") or ""), + shorts_pk=channel_pk, + ) + out: dict[str, Any] = { + "ok": True, + "channel_pk": channel_pk, + "name": str(ch.get("name") or ch.get("title") or ""), + "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), + "oauth_profile_id": str(ch.get("oauth_profile_id") or ""), + "currency": "USD", + "window": {"start": start_s, "end": end_s, "days": days_i}, + "totals": totals, + "by_type": by_type, + "daily": daily, + "links": links, + "type_error": type_error, + "monetary_ok": True, + "need_reauth": False, + "fetched_at": now, + } + _CACHE[cache_key] = (now, out) + return out + + +def _product_links(*, youtube_channel_id: str, shorts_pk: str) -> dict[str, Any]: + """Map UC… / Shorts pk → Live 分配 / Shorts / 长视频 cards.""" + ucid = str(youtube_channel_id or "").strip() + live_groups: list[dict[str, Any]] = [] + long_channels: list[dict[str, Any]] = [] + try: + for g in yt_assign_db.list_groups(include_urls=False): + gid = str(g.get("id") or "") + g_uc = str(g.get("youtube_channel_id") or "").strip() + g_pk = str(g.get("channel_pk") or "").strip() + if (ucid and g_uc == ucid) or (shorts_pk and g_pk == shorts_pk): + live_groups.append( + { + "group_id": gid, + "name": str(g.get("name") or ""), + "youtube_channel_id": g_uc, + "href": f"/youtube?live=1&focus={gid}" if gid else "/youtube", + } + ) + except Exception: + pass + try: + from . import yt_long_db + + for c in yt_long_db.list_yt_long_channels(): + c_uc = str(c.get("youtube_channel_id") or "").strip() + src = str(c.get("source_shorts_channel_pk") or "").strip() + if (ucid and c_uc == ucid) or (shorts_pk and src == shorts_pk): + long_channels.append( + { + "id": str(c.get("id") or ""), + "name": str(c.get("name") or ""), + "youtube_channel_id": c_uc, + "href": "/yt-long", + } + ) + except Exception: + pass + return { + "live": live_groups, + "shorts": { + "channel_pk": shorts_pk, + "href": f"/shorts?focus={shorts_pk}" if shorts_pk else "/shorts", + }, + "long": long_channels, + } + + +async def fleet_revenue(*, days: int = 28, force: bool = False) -> dict[str, Any]: + """Aggregate revenue across all authorized Shorts channels.""" + days_i = max(1, min(90, int(days or 28))) + channels = db.list_shorts_channels() + rows: list[dict[str, Any]] = [] + fleet_totals = _empty_bucket() + fleet_by_type = { + "live": _empty_bucket(), + "shorts": _empty_bucket(), + "long": _empty_bucket(), + "other": _empty_bucket(), + } + need_reauth = 0 + ok_n = 0 + for ch in channels: + pk = str(ch.get("id") or "").strip() + if not pk: + continue + if not str(ch.get("refresh_token") or "").strip(): + continue + try: + one = await fetch_channel_revenue(pk, days=days_i, force=force) + except Exception as exc: + one = {"ok": False, "channel_pk": pk, "error": str(exc)[:200], "need_reauth": True} + rows.append(one) + if one.get("need_reauth"): + need_reauth += 1 + if not one.get("ok"): + continue + ok_n += 1 + _add_row(fleet_totals, one.get("totals") or {}) + bt = one.get("by_type") or {} + for k in ("live", "shorts", "long", "other"): + _add_row(fleet_by_type[k], bt.get(k) or {}) + + end = _beijing_today() + start = end - timedelta(days=days_i - 1) + return { + "ok": True, + "window": {"start": start.isoformat(), "end": end.isoformat(), "days": days_i}, + "currency": "USD", + "totals": fleet_totals, + "by_type": fleet_by_type, + "channels": rows, + "ok_count": ok_n, + "need_reauth_count": need_reauth, + "fetched_at": time.time(), + } diff --git a/backend/neko/cdp_studio_scrape.py b/backend/neko/cdp_studio_scrape.py index d17e38a..62f6bd5 100644 --- a/backend/neko/cdp_studio_scrape.py +++ b/backend/neko/cdp_studio_scrape.py @@ -161,6 +161,14 @@ def main() -> None: pass lower = text.lower() + # Chrome error / offline interstitial — never treat as Studio receiving. + chrome_offline = bool( + re.search( + r"err_internet_disconnected|err_name_not_resolved|err_connection|" + r"no internet|没有网络|无法访问此网站|aw,\s*snap", + lower, + ) + ) nodata = bool( re.search(r"(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据", lower) ) @@ -286,18 +294,36 @@ def main() -> None: status = "live" # 开播 = 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 preparing + on_air = bool( + status == "live" and not nodata - and not encoder_lost - and ( - status == "live" - or health - or re.search(r"starting|receiving|connecting|正在接收|连接中", lower) + and not encoder_lost_hint + and not preparing + and not chrome_offline + ) + encoder_lost = status == "encoder_lost" or (session_live and nodata) + # Do NOT match bare "connecting" — Chrome offline page says "Reconnecting to Wi-Fi". + ingest_hint = bool( + re.search( + r"(?:^|[^a-z])(?:starting|receiving)(?:[^a-z]|$)|正在接收|编码器正在接收|" + r"stream health|excellent connection|good connection", + lower, ) ) + encoder_receiving = bool( + not chrome_offline + and not preparing + and not nodata + and not encoder_lost + and (status == "live" or health or ingest_hint) + ) + if chrome_offline: + status = "offline" + control_ready = False + on_air = False + encoder_receiving = False + encoder_lost = False + session_live = False print( json.dumps( { @@ -316,6 +342,7 @@ def main() -> None: "encoder_receiving": encoder_receiving, "encoder_lost": encoder_lost, "session_live": bool(session_live or status in {"live", "encoder_lost"}), + "chrome_offline": chrome_offline, "text": text[:500], }, ensure_ascii=False, diff --git a/backend/neko/live-ops-extension/content.js b/backend/neko/live-ops-extension/content.js index a344369..87cc767 100644 --- a/backend/neko/live-ops-extension/content.js +++ b/backend/neko/live-ops-extension/content.js @@ -334,5 +334,5 @@ setInterval(() => { injectMemCss(); tameMedia(); sendTelemetry(false); -}, 8000); +}, 12000); sendTelemetry(true); diff --git a/frontend/src/app/yt-revenue/page.tsx b/frontend/src/app/yt-revenue/page.tsx new file mode 100644 index 0000000..21ba5db --- /dev/null +++ b/frontend/src/app/yt-revenue/page.tsx @@ -0,0 +1,383 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; +import { + Clapperboard, + DollarSign, + Link2, + Loader2, + Radio, + RefreshCw, + Smartphone, +} from "lucide-react"; + +import { Shell } from "@/components/Shell"; +import { OauthClientBadge, normalizeOauthProfileId } from "@/components/OauthClientBadge"; +import { fetchJson, fmtTs } from "@/lib/api"; + +type MoneyBucket = { + estimated_revenue?: number; + estimated_ad_revenue?: number; + gross_revenue?: number; + monetized_playbacks?: number; + ad_impressions?: number; + playback_based_cpm?: number | null; +}; + +type ChannelRow = { + ok?: boolean; + channel_pk?: string; + name?: string; + youtube_channel_id?: string; + oauth_profile_id?: string; + error?: string; + monetary_ok?: boolean; + need_reauth?: boolean; + totals?: MoneyBucket; + by_type?: { + live?: MoneyBucket; + shorts?: MoneyBucket; + long?: MoneyBucket; + other?: MoneyBucket; + }; + links?: { + live?: Array<{ group_id?: string; name?: string; href?: string }>; + shorts?: { channel_pk?: string; href?: string }; + long?: Array<{ id?: string; name?: string; href?: string }>; + }; + window?: { start?: string; end?: string; days?: number }; +}; + +type Summary = { + ok?: boolean; + currency?: string; + window?: { start?: string; end?: string; days?: number }; + totals?: MoneyBucket; + by_type?: { + live?: MoneyBucket; + shorts?: MoneyBucket; + long?: MoneyBucket; + other?: MoneyBucket; + }; + channels?: ChannelRow[]; + ok_count?: number; + need_reauth_count?: number; + fetched_at?: number; +}; + +function fmtUsd(n: number | null | undefined): string { + if (n == null || !Number.isFinite(Number(n))) return "—"; + const v = Number(n); + return v.toLocaleString(undefined, { + style: "currency", + currency: "USD", + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }); +} + +function TypeCard({ + title, + emoji, + href, + bucket, + links, +}: { + title: string; + emoji: string; + href: string; + bucket?: MoneyBucket; + links?: ReactNode; +}) { + return ( +
+ YouTube Analytics 预估 AdSense 收益,按直播 / Shorts / 长视频拆分,并关联本机分配频道与任务台。 + 需频道补授权「Analytics 收益」权限(不影响上传)。 +
+