feat: add dashboard, oauth health, ops alerts, readonly role, and S3 archive replay

New pages and APIs for cross-platform jobs, YouTube OAuth health, mobile ops,
settings audit, optional DB backup, quota/disk alerts, and clip archive replay.
All new behavior defaults off to avoid changing production pipelines.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-23 08:02:58 -05:00
parent fd22339bff
commit b4e07d792e
22 changed files with 2134 additions and 75 deletions

94
backend/app/authz.py Normal file
View File

@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
"""Role-based access: admin (read/write) vs readonly (read-only)."""
from __future__ import annotations
import secrets
from typing import Any, Optional
from starlette.requests import Request
from .session_auth import hash_password, verify_session_payload
def get_readonly_credentials() -> tuple[str, str]:
from . import db
m = db.get_settings_map()
user = str(m.get("readonly_username") or "").strip()
pw_hash = str(m.get("readonly_password_hash") or "").strip()
return user, pw_hash
def readonly_enabled() -> bool:
user, pw_hash = get_readonly_credentials()
return bool(user and pw_hash)
def verify_readonly(username: str, password: str) -> bool:
user, pw_hash = get_readonly_credentials()
if not user or not pw_hash:
return False
if not secrets.compare_digest(str(username or ""), user):
return False
return secrets.compare_digest(hash_password(str(password or "")), pw_hash)
def set_readonly_password(username: str, password: str) -> None:
from . import db
user = str(username or "").strip()
if not user:
db.update_settings_map({"readonly_username": "", "readonly_password_hash": ""})
return
pw = str(password or "")
if len(pw) < 8:
raise ValueError("只读账号密码至少 8 位")
db.update_settings_map(
{
"readonly_username": user,
"readonly_password_hash": hash_password(pw),
}
)
def session_payload_from_request(request: Request) -> Optional[dict[str, Any]]:
from .config import settings
from .session_auth import SESSION_COOKIE, verify_session_token
if not settings.auth_enabled:
return {"u": str(settings.admin_username or "admin"), "role": "admin"}
token = (request.cookies.get(SESSION_COOKIE) or "").strip()
if not token:
auth = request.headers.get("Authorization") or ""
if auth.lower().startswith("bearer "):
token = auth[7:].strip()
if not token:
return None
payload = verify_session_payload(token)
if not payload:
# Legacy token without role — treat as admin if username verifies
user = verify_session_token(token)
if user:
return {"u": user, "role": "admin"}
return None
return payload
def session_role_from_request(request: Request) -> str:
payload = session_payload_from_request(request)
if not payload:
return ""
role = str(payload.get("role") or "admin").strip().lower()
return role if role in {"admin", "readonly"} else "admin"
def assert_write_access(request: Request) -> None:
from fastapi import HTTPException
role = session_role_from_request(request)
if role == "readonly":
raise HTTPException(403, "只读账号无写入权限")
def is_write_method(method: str) -> bool:
return method.upper() in {"POST", "PUT", "PATCH", "DELETE"}

149
backend/app/clip_archive.py Normal file
View File

@ -0,0 +1,149 @@
# -*- coding: utf-8 -*-
"""Archive clips to S3 before deletion; replay upload from archive."""
from __future__ import annotations
import time
from pathlib import Path
from typing import Any
from .config import settings
def _archive_enabled(cfg: dict[str, Any] | None = None) -> bool:
from . import db
m = cfg if cfg is not None else db.get_settings_map()
if not m.get("clip_archive_to_s3_enabled", False):
return False
from . import s3_storage
return s3_storage.s3_enabled()
def archive_key(platform: str, job_id: str, ext: str = "mp4") -> str:
pid = str(platform or "unknown").strip().lower()
jid = str(job_id or "unknown").strip()
return f"clips/archive/{pid}/{jid}.{ext.lstrip('.')}"
def maybe_archive_clip(
path: str,
*,
platform: str,
job_id: str,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
if not _archive_enabled(cfg):
return {"skipped": True}
p = Path(str(path or "").strip())
if not p.is_file():
return {"skipped": True, "reason": "no_file"}
key = archive_key(platform, job_id)
try:
from . import s3_storage
url = s3_storage.upload_file(p, key, content_type="video/mp4")
if not url:
return {"ok": False, "error": "upload_empty"}
meta = s3_storage.head_object(key) or {}
return {"ok": True, "key": key, "url": url, "size": meta.get("size")}
except Exception as exc:
return {"ok": False, "error": str(exc)[:200]}
def get_archive_meta(platform: str, job_id: str) -> dict[str, Any] | None:
from . import s3_storage
if not s3_storage.s3_enabled():
return None
key = archive_key(platform, job_id)
return s3_storage.head_object(key)
def archive_clip_for_path(path: str) -> dict[str, Any]:
"""Find job by clip_path and archive if enabled."""
from . import db
from . import tiktok_db
from . import yt_long_db
p = str(path or "").strip()
if not p:
return {"skipped": True}
cfg = db.get_settings_map()
for plat, table, mod in (
("shorts", "shorts_jobs", db),
("tiktok", "tiktok_jobs", tiktok_db),
("yt_long", "yt_long_jobs", yt_long_db),
):
try:
lock = getattr(mod, "_lock", db._lock)
connect = getattr(mod, "_connect", db._connect)
with lock:
conn = connect()
try:
row = conn.execute(
f"SELECT id FROM {table} WHERE clip_path = ? ORDER BY updated_at DESC LIMIT 1",
(p,),
).fetchone()
if row:
jid = str(row["id"])
return maybe_archive_clip(p, platform=plat, job_id=jid, cfg=cfg)
finally:
conn.close()
except Exception:
continue
return {"skipped": True, "reason": "job_not_found"}
async def replay_from_archive(platform: str, job_id: str) -> dict[str, Any]:
"""Download archived clip to local temp and re-queue upload for the job."""
import asyncio
import tempfile
from . import db
from . import s3_storage
from . import tiktok_db
from . import yt_long_db
plat = str(platform or "").strip().lower()
jid = str(job_id or "").strip()
if not jid:
return {"ok": False, "error": "no_job_id"}
meta = get_archive_meta(plat, jid)
if not meta or not meta.get("key"):
return {"ok": False, "error": "archive_not_found"}
key = str(meta["key"])
try:
client = s3_storage._client()
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
dest = tmp.name
await asyncio.to_thread(
client.download_file,
settings.s3_bucket,
key,
dest,
)
except Exception as exc:
return {"ok": False, "error": f"download:{exc}"[:200]}
now = time.time()
if plat == "shorts":
job = db.get_shorts_job(jid)
if not job:
return {"ok": False, "error": "job_not_found"}
db.update_shorts_job(jid, status="scheduled", clip_path=dest, upload_at=now + 30, error="archive_replay")
return {"ok": True, "platform": plat, "job_id": jid, "clip_path": dest}
if plat == "tiktok":
job = tiktok_db.get_tiktok_job(jid)
if not job:
return {"ok": False, "error": "job_not_found"}
tiktok_db.update_tiktok_job(jid, status="scheduled", clip_path=dest, upload_at=now + 30, error="archive_replay")
return {"ok": True, "platform": plat, "job_id": jid, "clip_path": dest}
if plat == "yt_long":
job = yt_long_db.get_yt_long_job(jid)
if not job:
return {"ok": False, "error": "job_not_found"}
yt_long_db.update_yt_long_job(jid, status="scheduled", clip_path=dest, upload_at=now + 30, error="archive_replay")
return {"ok": True, "platform": plat, "job_id": jid, "clip_path": dest}
return {"ok": False, "error": "unsupported_platform"}

View File

@ -163,6 +163,12 @@ def unlink_clip(path: str, *, clear_refs: bool = True) -> bool:
return False
try:
if p.is_file():
try:
from .clip_archive import archive_clip_for_path
archive_clip_for_path(str(p))
except Exception:
pass
p.unlink()
if clear_refs:
_clear_path_refs(str(p), time.time())

View File

@ -399,6 +399,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"notify_webhook_url": "",
"notify_on_live": True,
"notify_on_offline": False,
"notify_ntfy_on_douyin_live": False,
"notify_on_risk": True,
"notify_on_shorts_fail": True,
"notify_on_shorts_ok": False,
@ -446,6 +447,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
{"id": "C", "label": "谷歌账号 C", "client_id": "", "client_secret": ""},
{"id": "D", "label": "谷歌账号 D", "client_id": "", "client_secret": ""},
],
# Studio browser cookies per OAuth profile — required for yt-long ad monetize
"yt_studio_cookies_by_profile": {},
"shorts_gcp_project_id": "live-473104",
"shorts_yt_daily_upload_limit": 90,
"shorts_yt_upload_blocked_until": 0,
@ -537,6 +540,22 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"tiktok_oauth_client_key": "",
"tiktok_oauth_client_secret": "",
"tiktok_oauth_redirect_uri": "https://dylive.nomadro.com/api/tiktok/oauth/callback/",
# Ops / audit / archive (all off by default — no behavior change on existing installs)
"settings_audit_enabled": True,
"db_backup_enabled": False,
"db_backup_interval_hours": 24,
"db_backup_keep_days": 7,
"ops_alerts_enabled": False,
"ops_alert_disk_enabled": False,
"ops_alert_quota_enabled": False,
"ops_alert_interval_sec": 900,
"ops_alert_cooldown_sec": 3600,
"ops_alert_failed_jobs_threshold": 50,
"notify_on_tiktok_unaudited": True,
"notify_webhook_standard_json": False,
"clip_archive_to_s3_enabled": False,
"readonly_username": "",
"readonly_password_hash": "",
}
for key, value in defaults.items():
row = conn.execute("SELECT 1 FROM kv_settings WHERE key = ?", (key,)).fetchone()
@ -688,7 +707,7 @@ def youtube_monitor_status_data() -> dict[str, Any]:
conn.close()
def update_settings_map(patch: dict[str, Any]) -> dict[str, Any]:
def update_settings_map(patch: dict[str, Any], *, audit_actor: str = "") -> dict[str, Any]:
with _lock:
conn = _connect()
try:
@ -709,6 +728,12 @@ def update_settings_map(patch: dict[str, Any]) -> dict[str, Any]:
conn.commit()
finally:
conn.close()
try:
from .settings_audit import log_settings_patch
log_settings_patch(patch, actor=audit_actor)
except Exception:
pass
return get_settings_map()

107
backend/app/db_backup.py Normal file
View File

@ -0,0 +1,107 @@
# -*- coding: utf-8 -*-
"""SQLite backup — copy-only, never modifies source DB."""
from __future__ import annotations
import shutil
import time
from pathlib import Path
from typing import Any
from .config import settings
def _backup_dir() -> Path:
p = Path(settings.data_dir) / "backups"
p.mkdir(parents=True, exist_ok=True)
return p
def _db_path() -> Path:
return Path(settings.data_dir) / "monitor.db"
def run_backup(*, label: str = "") -> dict[str, Any]:
src = _db_path()
if not src.is_file():
return {"ok": False, "error": "db_not_found"}
stamp = time.strftime("%Y%m%d_%H%M%S")
name = f"monitor_{stamp}{('_' + label) if label else ''}.db"
dest = _backup_dir() / name
try:
shutil.copy2(src, dest)
size = dest.stat().st_size
return {"ok": True, "path": str(dest), "name": name, "size": size, "ts": time.time()}
except Exception as exc:
return {"ok": False, "error": str(exc)[:200]}
def list_backups(*, limit: int = 20) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
for p in sorted(_backup_dir().glob("monitor_*.db"), key=lambda x: x.stat().st_mtime, reverse=True):
try:
st = p.stat()
rows.append(
{
"name": p.name,
"size": st.st_size,
"ts": st.st_mtime,
}
)
except OSError:
continue
if len(rows) >= max(1, limit):
break
return rows
def prune_backups(*, keep_days: float = 7.0) -> dict[str, Any]:
cutoff = time.time() - max(1.0, keep_days) * 86400.0
removed = 0
for p in _backup_dir().glob("monitor_*.db"):
try:
if p.stat().st_mtime < cutoff:
p.unlink(missing_ok=True)
removed += 1
except OSError:
continue
return {"ok": True, "removed": removed}
async def backup_loop() -> None:
import asyncio
from . import db
await asyncio.sleep(60)
while True:
try:
cfg = db.get_settings_map()
if not cfg.get("db_backup_enabled", False):
await asyncio.sleep(300)
continue
try:
interval_h = float(cfg.get("db_backup_interval_hours") or 24)
except Exception:
interval_h = 24.0
interval_h = max(1.0, min(168.0, interval_h))
try:
keep_days = float(cfg.get("db_backup_keep_days") or 7)
except Exception:
keep_days = 7.0
result = run_backup(label="auto")
if result.get("ok"):
prune_backups(keep_days=keep_days)
try:
db.add_event(
kind="db_backup",
level="info",
message=f"数据库已备份:{result.get('name')}",
meta={"size": result.get("size"), "name": result.get("name")},
)
except Exception:
pass
await asyncio.sleep(interval_h * 3600.0)
except asyncio.CancelledError:
raise
except Exception:
await asyncio.sleep(600)

View File

@ -91,6 +91,12 @@ from .timeutil import stamp_beijing
@asynccontextmanager
async def lifespan(_: FastAPI):
await asyncio.to_thread(db.init_db)
try:
from .session_auth import ensure_default_admin_credentials
await asyncio.to_thread(ensure_default_admin_credentials)
except Exception:
pass
try:
from .yt_channel_meta import ensure_default_brand_hints
@ -134,6 +140,17 @@ async def lifespan(_: FastAPI):
if not _desktop_light:
asyncio.create_task(_live_map_refresh_loop())
async def _ops_background_loops() -> None:
if _desktop_light:
return
from .db_backup import backup_loop
from .ops_alerts import alert_loop
asyncio.create_task(backup_loop())
asyncio.create_task(alert_loop())
asyncio.create_task(_ops_background_loops())
async def _start_workers() -> None:
if _desktop_light:
return
@ -277,31 +294,49 @@ async def health() -> dict[str, Any]:
@app.get("/api/auth/status")
async def auth_status(request: Request) -> dict[str, Any]:
from .authz import session_payload_from_request, session_role_from_request, readonly_enabled
user = session_user_from_request(request)
role = session_role_from_request(request) if user else ""
return {
"api_key_required": bool(str(settings.api_key or "").strip()),
"auth_enabled": bool(settings.auth_enabled),
"authenticated": bool(user),
"username": user or "",
"role": role or ("admin" if user else ""),
"readonly_enabled": readonly_enabled(),
}
@app.get("/api/auth/me")
async def auth_me(request: Request) -> dict[str, Any]:
from .authz import session_role_from_request
user = session_user_from_request(request)
if not user and settings.auth_enabled:
raise HTTPException(401, "未登录")
return {"ok": True, "username": user or settings.admin_username}
return {
"ok": True,
"username": user or settings.admin_username,
"role": session_role_from_request(request) or "admin",
}
@app.post("/api/auth/login")
async def auth_login(request: Request, body: dict[str, Any]) -> JSONResponse:
from .authz import verify_readonly
username = str(body.get("username") or body.get("user") or "").strip()
password = str(body.get("password") or "")
if not verify_admin(username, password):
role = "admin"
if verify_admin(username, password):
role = "admin"
elif verify_readonly(username, password):
role = "readonly"
else:
raise HTTPException(401, "用户名或密码错误")
resp = JSONResponse({"ok": True, "username": username})
set_session_cookie(resp, username, secure=_request_secure(request))
resp = JSONResponse({"ok": True, "username": username, "role": role})
set_session_cookie(resp, username, secure=_request_secure(request), role=role)
return resp
@ -437,6 +472,9 @@ def _public_settings(cfg: dict[str, Any]) -> dict[str, Any]:
out["shorts_upload_socks_profiles"] = shorts_socks.list_socks_profiles(cfg, public=True)
out["shorts_upload_socks_enabled"] = bool(cfg.get("shorts_upload_socks_enabled"))
out["shorts_upload_socks_profile_id"] = str(cfg.get("shorts_upload_socks_profile_id") or "")
from . import yt_studio_auth
out["yt_studio_cookies_by_profile"] = yt_studio_auth.public_studio_cookies_by_profile(cfg)
tt_secret = str(out.get("tiktok_oauth_client_secret") or "")
if tt_secret and not tt_secret.startswith("***"):
out["tiktok_oauth_client_secret"] = ("***" + tt_secret[-4:]) if len(tt_secret) > 4 else "***"
@ -578,12 +616,14 @@ async def shorts_live_analytics(
@app.get("/api/shorts/oauth/start")
async def shorts_oauth_start(channel_pk: str, request: Request) -> RedirectResponse:
async def shorts_oauth_start(channel_pk: str, request: Request, return_to: str = "") -> RedirectResponse:
try:
await shorts_oauth.prepare_reauthorize(channel_pk)
ret = str(return_to or request.query_params.get("return_to") or "").strip()
url = shorts_oauth.build_authorize_url(
channel_pk=channel_pk,
request_base=_request_public_base(request),
return_to=ret,
)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
@ -610,12 +650,23 @@ async def shorts_oauth_callback(
)
title = quote(str(result.get("youtube_title") or "ok"))
handle = quote(str(result.get("youtube_handle") or ""))
ret = str(result.get("return_to") or "").strip()
if ret:
sep = "&" if "?" in ret else "?"
return RedirectResponse(
f"{base}{ret}{sep}oauth=ok&title={title}" + (f"&handle={handle}" if handle else ""),
status_code=302,
)
return RedirectResponse(
f"{base}/shorts?oauth=ok&title={title}" + (f"&handle={handle}" if handle else ""),
status_code=302,
)
except Exception as exc:
# Keep enough room for mismatch hints (got vs need channel names).
ret = str(request.query_params.get("return_to") or "").strip()
msg = quote(str(exc)[:320])
if ret and ret.startswith("/") and not ret.startswith("//"):
sep = "&" if "?" in ret else "?"
return RedirectResponse(f"{base}{ret}{sep}oauth=error&msg={msg}", status_code=302)
return RedirectResponse(f"{base}/shorts?oauth=error&msg={quote(str(exc)[:320])}", status_code=302)
@ -2013,8 +2064,89 @@ async def get_settings() -> dict[str, Any]:
return _public_settings(cfg)
@app.get("/api/dashboard/jobs")
async def dashboard_jobs(
limit: int = Query(60, ge=1, le=200),
status: str = "",
) -> dict[str, Any]:
from .platform_dashboard import list_recent_jobs
return await asyncio.to_thread(list_recent_jobs, limit=limit, status=status)
@app.get("/api/youtube/oauth-health")
async def youtube_oauth_health() -> dict[str, Any]:
from .platform_dashboard import oauth_health_board
return await asyncio.to_thread(oauth_health_board)
@app.post("/api/youtube/oauth-health/probe")
async def youtube_oauth_health_probe(request: Request) -> dict[str, Any]:
from .authz import assert_write_access
from .platform_dashboard import oauth_health_probe_all
assert_write_access(request)
return await oauth_health_probe_all()
@app.get("/api/ops/backups")
async def ops_list_backups(limit: int = Query(20, ge=1, le=100)) -> dict[str, Any]:
from .db_backup import list_backups
return {"backups": list_backups(limit=limit)}
@app.post("/api/ops/backups/run")
async def ops_run_backup(request: Request) -> dict[str, Any]:
from .authz import assert_write_access
from .db_backup import run_backup
assert_write_access(request)
return await asyncio.to_thread(run_backup, label="manual")
@app.get("/api/ops/alerts/metrics")
async def ops_alert_metrics() -> dict[str, Any]:
from .ops_alerts import collect_metrics
return await asyncio.to_thread(collect_metrics)
@app.post("/api/ops/alerts/check")
async def ops_alert_check(request: Request) -> dict[str, Any]:
from .authz import assert_write_access
from .ops_alerts import check_and_alert
assert_write_access(request)
return await check_and_alert()
@app.get("/api/archive/{platform}/{job_id}")
async def archive_meta(platform: str, job_id: str) -> dict[str, Any]:
from .clip_archive import get_archive_meta
meta = get_archive_meta(platform, job_id)
return {"ok": bool(meta), "archive": meta}
@app.post("/api/archive/{platform}/{job_id}/replay")
async def archive_replay(platform: str, job_id: str, request: Request) -> dict[str, Any]:
from .authz import assert_write_access
from .clip_archive import replay_from_archive
assert_write_access(request)
return await replay_from_archive(platform, job_id)
@app.get("/api/events/audit")
async def settings_audit_events(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]:
rows = db.list_events(kind="settings_audit", limit=limit)
return {"events": rows.get("events") or [], "total": int(rows.get("total") or 0)}
@app.patch("/api/settings")
async def patch_settings(body: SettingsUpdate) -> dict[str, Any]:
async def patch_settings(body: SettingsUpdate, request: Request) -> dict[str, Any]:
patch = body.model_dump(exclude_none=True)
if "shorts_oauth_client_secret" in patch:
sec = str(patch.get("shorts_oauth_client_secret") or "").strip()
@ -2032,7 +2164,27 @@ async def patch_settings(body: SettingsUpdate) -> dict[str, Any]:
patch["shorts_upload_socks_profiles"] = shorts_socks.merge_socks_profiles_patch(
patch.get("shorts_upload_socks_profiles"), existing
)
cfg = await asyncio.to_thread(db.update_settings_map, patch)
if "yt_studio_cookies_by_profile" in patch:
from . import yt_studio_auth
existing = await asyncio.to_thread(db.get_settings_map)
patch["yt_studio_cookies_by_profile"] = yt_studio_auth.merge_studio_cookies_patch(
patch.get("yt_studio_cookies_by_profile"), existing
)
if "readonly_password" in patch:
from .session_auth import hash_password
existing = await asyncio.to_thread(db.get_settings_map)
user = str(patch.pop("readonly_username", None) or existing.get("readonly_username") or "").strip()
pw = str(patch.pop("readonly_password", None) or "").strip()
if pw and not pw.startswith("***"):
patch["readonly_username"] = user
patch["readonly_password_hash"] = hash_password(pw)
elif user and "readonly_username" in body.model_dump(exclude_none=True):
patch["readonly_username"] = user
cfg = await asyncio.to_thread(
db.update_settings_map, patch, audit_actor=str(session_user_from_request(request) or "")
)
return _public_settings(cfg)
@ -2960,21 +3112,23 @@ async def anchors_detail(key: str) -> dict[str, Any]:
@app.post("/api/notify/test")
async def notify_test() -> dict[str, Any]:
from .notify import send_webhook
from . import ops_panel
from .notify import NTFY_TOPIC, send_webhook
cfg = db.get_settings_map()
url = str(cfg.get("notify_webhook_url") or "").strip()
if not url:
raise HTTPException(400, "未配置 Webhook URL")
ntfy_ok = bool(ops_panel.ntfy_config().get("configured"))
if not url and not ntfy_ok:
raise HTTPException(400, "未配置 Webhook URL 或 ntfy")
await send_webhook(
"ops",
{
"message": "【测试】DouyinWEB Webhook 连通性检查",
"message": "【测试】DouyinWEB 通知连通性检查",
"test": True,
"time": time.time(),
},
)
return {"ok": True, "webhook": url}
return {"ok": True, "webhook": url or None, "ntfy_topic": NTFY_TOPIC if ntfy_ok else None}
@app.get("/api/ops")

View File

@ -193,6 +193,7 @@ class SettingsUpdate(BaseModel):
notify_webhook_url: Optional[str] = None
notify_on_live: Optional[bool] = None
notify_on_offline: Optional[bool] = None
notify_ntfy_on_douyin_live: Optional[bool] = None
notify_on_risk: Optional[bool] = None
notify_on_shorts_fail: Optional[bool] = None
notify_on_shorts_ok: Optional[bool] = None
@ -232,10 +233,26 @@ class SettingsUpdate(BaseModel):
shorts_oauth_client_secret: Optional[str] = None
shorts_oauth_redirect_uri: Optional[str] = None
shorts_oauth_profiles: Optional[list[dict[str, Any]]] = None
yt_studio_cookies_by_profile: Optional[dict[str, Any]] = None
shorts_gcp_project_id: Optional[str] = None
shorts_upload_socks_enabled: Optional[bool] = None
shorts_upload_socks_profile_id: Optional[str] = None
shorts_upload_socks_profiles: Optional[list[dict[str, Any]]] = None
settings_audit_enabled: Optional[bool] = None
db_backup_enabled: Optional[bool] = None
db_backup_interval_hours: Optional[float] = None
db_backup_keep_days: Optional[float] = None
ops_alerts_enabled: Optional[bool] = None
ops_alert_disk_enabled: Optional[bool] = None
ops_alert_quota_enabled: Optional[bool] = None
ops_alert_interval_sec: Optional[float] = None
ops_alert_cooldown_sec: Optional[float] = None
ops_alert_failed_jobs_threshold: Optional[int] = None
notify_on_tiktok_unaudited: Optional[bool] = None
notify_webhook_standard_json: Optional[bool] = None
clip_archive_to_s3_enabled: Optional[bool] = None
readonly_username: Optional[str] = None
readonly_password: Optional[str] = None
class ShortsChannelCreate(BaseModel):

View File

@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import threading
import time
from typing import Any
import httpx
@ -9,6 +10,86 @@ import httpx
from . import db
from .timeutil import beijing_now
NTFY_TOPIC = "dylive"
_EVENT_NTFY: dict[str, tuple[str, str, str]] = {
"live": ("抖音开播", "high", "red_circle,live"),
"offline": ("抖音停播", "default", "white_circle,offline"),
"risk": ("抖音风控", "high", "warning"),
"shorts_fail": ("Shorts 失败", "high", "x"),
"shorts_ok": ("Shorts 成功", "default", "white_check_mark"),
"shorts_quota": ("Shorts 配额", "default", "chart_with_upwards_trend"),
"tiktok_fail": ("TikTok 失败", "high", "x"),
"tiktok_ok": ("TikTok 成功", "default", "white_check_mark"),
"tiktok_limit": ("TikTok 限流", "high", "warning"),
"tiktok_unaudited": ("TikTok 仅自己可见", "default", "lock"),
"watch_remind": ("盯梢提醒", "default", "eyes"),
"ops": ("系统测试", "default", "bell"),
"ops_disk": ("磁盘预警", "high", "floppy_disk"),
"ops_quota": ("配额预警", "default", "chart_with_upwards_trend"),
"ops_backlog": ("任务积压", "default", "warning"),
}
def _notify_allowed(event: str, cfg: dict[str, Any]) -> bool:
if event == "live" and not cfg.get("notify_on_live", True):
return False
if event == "offline" and not cfg.get("notify_on_offline", False):
return False
if event == "risk" and not cfg.get("notify_on_risk", True):
return False
if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True):
return False
if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False):
return False
if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True):
return False
if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True):
return False
if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False):
return False
if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True):
return False
if event == "tiktok_unaudited" and not cfg.get("notify_on_tiktok_unaudited", True):
return False
if event in {"ops_disk", "ops_quota", "ops_backlog"} and not cfg.get("ops_alerts_enabled", False):
return False
if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True):
return False
return True
def _skip_generic_ntfy(event: str, payload: dict[str, Any]) -> bool:
"""YouTube live/offline uses dedicated detailed ntfy builder."""
if event not in {"live", "offline"}:
return False
if str(payload.get("platform") or "").lower() == "youtube":
return True
if payload.get("group_id") and not payload.get("room_pk"):
return True
return False
def build_event_ntfy(event: str, payload: dict[str, Any]) -> tuple[str, str, str, str]:
title, priority, tags = _EVENT_NTFY.get(event, (event, "default", "bell"))
msg = str(payload.get("message") or event).strip()
lines = [msg]
for key, label in (
("anchor_name", "主播"),
("room_id", "房间"),
("url", "链接"),
("session_id", "Session"),
("job_id", "任务"),
):
val = payload.get(key)
if val:
lines.append(f"{label}:{val}")
duration = payload.get("duration_seconds")
if duration is not None:
lines.append(f"时长:{_fmt_duration(duration)}")
lines.append(f"时间:{beijing_now().strftime('%Y-%m-%d %H:%M:%S')} 北京时间")
return title, "\n".join(lines), priority, tags
def _fmt_duration(seconds: Any) -> str:
total = max(0, int(float(seconds or 0)))
@ -83,7 +164,7 @@ async def send_ntfy_youtube(event: str, fields: dict[str, Any]) -> None:
async def _send() -> None:
try:
await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags)
await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, NTFY_TOPIC)
except Exception:
pass
@ -112,49 +193,97 @@ def fire_ntfy_youtube(event: str, fields: dict[str, Any]) -> None:
threading.Thread(target=_run, daemon=True).start()
async def send_webhook(event: str, payload: dict[str, Any]) -> None:
"""Existing webhook notifier — unchanged behavior (ops/ntfy is a separate module)."""
def _skip_douyin_ntfy(event: str, payload: dict[str, Any], cfg: dict[str, Any]) -> bool:
"""Douyin live/offline ntfy can be toggled independently from webhook."""
if event not in {"live", "offline"}:
return False
if _skip_generic_ntfy(event, payload):
return False
return not cfg.get("notify_ntfy_on_douyin_live", False)
async def send_ntfy_event(event: str, payload: dict[str, Any]) -> None:
"""Push project events to ntfy topic dylive (if server ntfy is configured)."""
if _skip_generic_ntfy(event, payload):
return
cfg = db.get_settings_map()
url = str(cfg.get("notify_webhook_url") or "").strip()
if not url:
if _skip_douyin_ntfy(event, payload, cfg):
return
if event == "live" and not cfg.get("notify_on_live", True):
return
if event == "offline" and not cfg.get("notify_on_offline", False):
return
if event == "risk" and not cfg.get("notify_on_risk", True):
return
if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True):
return
if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False):
return
if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True):
return
if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True):
return
if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False):
return
if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True):
return
if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True):
return
# allow ops/test always when URL configured
body = {
"event": event,
"text": payload.get("message") or event,
"payload": payload,
}
async def _post() -> None:
try:
async with httpx.AsyncClient(timeout=8.0, trust_env=False) as client:
await client.post(url, json=body)
except Exception:
pass
try:
asyncio.get_running_loop()
asyncio.create_task(_post())
except RuntimeError:
await _post()
from . import ops_panel
if not ops_panel.ntfy_config().get("configured"):
return
title, message, priority, tags = build_event_ntfy(event, payload)
async def _send() -> None:
try:
await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, NTFY_TOPIC)
except Exception:
pass
try:
asyncio.get_running_loop()
asyncio.create_task(_send())
except RuntimeError:
await _send()
except Exception:
pass
def _event_platform(event: str) -> str:
if event.startswith("shorts"):
return "shorts"
if event.startswith("tiktok"):
return "tiktok"
if event.startswith("yt_long") or event.startswith("yt-long"):
return "yt_long"
if event.startswith("x"):
return "x"
if event in {"live", "offline", "risk"}:
return "douyin"
if event.startswith("ops"):
return "ops"
return ""
async def send_webhook(event: str, payload: dict[str, Any]) -> None:
"""Notify via optional webhook URL and always via ntfy topic dylive when configured."""
cfg = db.get_settings_map()
if not _notify_allowed(event, cfg):
return
url = str(cfg.get("notify_webhook_url") or "").strip()
if url:
standard = bool(cfg.get("notify_webhook_standard_json", False))
if standard:
body = {
"schema": "dylive.webhook.v1",
"event": event,
"ts": time.time(),
"platform": str(payload.get("platform") or _event_platform(event)),
"level": str(payload.get("level") or "info"),
"message": str(payload.get("message") or event),
"data": {k: v for k, v in payload.items() if k not in {"message", "level", "platform"}},
}
else:
body = {
"event": event,
"text": payload.get("message") or event,
"payload": payload,
}
async def _post() -> None:
try:
async with httpx.AsyncClient(timeout=8.0, trust_env=False) as client:
await client.post(url, json=body)
except Exception:
pass
try:
asyncio.get_running_loop()
asyncio.create_task(_post())
except RuntimeError:
await _post()
await send_ntfy_event(event, payload)

140
backend/app/ops_alerts.py Normal file
View File

@ -0,0 +1,140 @@
# -*- coding: utf-8 -*-
"""Disk / quota / backlog alerts — off by default, cooldown dedupe."""
from __future__ import annotations
import time
from typing import Any
_last_fired: dict[str, float] = {}
def _cooldown_ok(key: str, cooldown_sec: float) -> bool:
now = time.time()
last = _last_fired.get(key, 0.0)
if now - last < max(300.0, cooldown_sec):
return False
_last_fired[key] = now
return True
async def _fire(event: str, message: str, extra: dict[str, Any] | None = None) -> None:
from .notify import send_webhook
payload = {"message": message, **(extra or {})}
await send_webhook(event, payload)
def collect_metrics() -> dict[str, Any]:
from . import db
from .clip_retention import disk_free_gb
from . import shorts_yt_quota
from . import yt_long_db
from . import tiktok_db
cfg = db.get_settings_map()
out: dict[str, Any] = {"ts": time.time()}
out["disk_free_gb"] = round(disk_free_gb(), 2)
try:
out["shorts_quota_gap"] = shorts_yt_quota.upload_gap(cfg=cfg)
except Exception:
out["shorts_quota_gap"] = -1
try:
out["yt_long_upload_gap"] = yt_long_db.yt_long_upload_gap(cfg=cfg)
except Exception:
out["yt_long_upload_gap"] = -1
try:
out["tiktok_daily_gap"] = tiktok_db.tiktok_total_quota_gap()
except Exception:
out["tiktok_daily_gap"] = -1
backlog = 0
for fn, st in (
(db.list_shorts_jobs, "failed"),
(tiktok_db.list_tiktok_jobs, "failed"),
):
try:
data = fn(status=st, limit=200, offset=0)
backlog += len(data.get("items") or [])
except Exception:
pass
out["failed_jobs"] = backlog
return out
async def check_and_alert() -> dict[str, Any]:
from . import db
cfg = db.get_settings_map()
if not cfg.get("ops_alerts_enabled", False):
return {"skipped": True}
try:
cooldown = float(cfg.get("ops_alert_cooldown_sec") or 3600)
except Exception:
cooldown = 3600.0
metrics = collect_metrics()
fired: list[str] = []
if cfg.get("ops_alert_disk_enabled", False):
try:
min_free = float(cfg.get("clips_min_free_gb") or 12)
except Exception:
min_free = 12.0
free = float(metrics.get("disk_free_gb") or 0)
if free < min_free and _cooldown_ok("ops_disk", cooldown):
await _fire(
"ops_disk",
f"磁盘空间不足:剩余 {free:.1f} GB(阈值 {min_free:.0f} GB)",
{"disk_free_gb": free, "threshold_gb": min_free},
)
fired.append("ops_disk")
if cfg.get("ops_alert_quota_enabled", False):
gaps = [
("shorts", metrics.get("shorts_quota_gap"), 0),
("yt_long", metrics.get("yt_long_upload_gap"), 0),
("tiktok", metrics.get("tiktok_daily_gap"), 0),
]
low = [f"{p}={g}" for p, g, th in gaps if isinstance(g, int) and g <= th]
if low and _cooldown_ok("ops_quota", cooldown):
await _fire(
"ops_quota",
f"上传配额已满或不足:{', '.join(low)}",
{"gaps": dict(gaps)},
)
fired.append("ops_quota")
try:
max_fail = int(cfg.get("ops_alert_failed_jobs_threshold") or 50)
except Exception:
max_fail = 50
failed = int(metrics.get("failed_jobs") or 0)
if failed >= max_fail and _cooldown_ok("ops_backlog", cooldown):
await _fire(
"ops_backlog",
f"失败任务积压:{failed} 条(阈值 {max_fail})",
{"failed_jobs": failed},
)
fired.append("ops_backlog")
return {"ok": True, "fired": fired, "metrics": metrics}
async def alert_loop() -> None:
import asyncio
from . import db
await asyncio.sleep(120)
while True:
try:
cfg = db.get_settings_map()
if cfg.get("ops_alerts_enabled", False):
await check_and_alert()
try:
interval = float(cfg.get("ops_alert_interval_sec") or 900)
except Exception:
interval = 900.0
await asyncio.sleep(max(300.0, interval))
except asyncio.CancelledError:
raise
except Exception:
await asyncio.sleep(600)

View File

@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""Cross-platform recent jobs + OAuth health board (read-mostly)."""
from __future__ import annotations
import time
from typing import Any
def list_recent_jobs(*, limit: int = 60, status: str = "") -> dict[str, Any]:
from . import db
from . import tiktok_db
from . import x_clips_db
from . import yt_long_db
lim = max(1, min(limit, 200))
items: list[dict[str, Any]] = []
def _push(platform: str, row: dict[str, Any], *, url_key: str, id_key: str) -> None:
items.append(
{
"platform": platform,
"id": str(row.get("id") or ""),
"status": str(row.get("status") or ""),
"anchor_name": str(row.get("anchor_name") or ""),
"room_id": str(row.get("room_id") or ""),
"channel_pk": str(row.get("channel_pk") or ""),
"error": str(row.get("error") or "")[:240],
"external_url": str(row.get(url_key) or ""),
"external_id": str(row.get(id_key) or ""),
"finished_at": float(row.get("finished_at") or row.get("updated_at") or 0),
"updated_at": float(row.get("updated_at") or 0),
}
)
st = str(status or "").strip()
shorts = db.list_shorts_jobs(status=st or None, limit=lim, offset=0)
for row in shorts.get("jobs") or []:
_push("shorts", row, url_key="youtube_url", id_key="youtube_video_id")
tt = tiktok_db.list_tiktok_jobs(status=st or None, limit=lim, offset=0)
for row in tt.get("jobs") or []:
vid = str(row.get("tiktok_video_id") or row.get("tiktok_publish_id") or "")
_push("tiktok", row, url_key="tiktok_video_id", id_key="tiktok_video_id")
if items:
items[-1]["external_url"] = vid
xc = x_clips_db.list_x_clip_jobs(status=st or None, limit=lim, offset=0)
for row in xc.get("jobs") or []:
_push("x_clips", row, url_key="media_url", id_key="x2_job_id")
yl = yt_long_db.list_yt_long_jobs_page(status=st or None, limit=lim, offset=0)
for row in yl.get("jobs") or []:
_push("yt_long", row, url_key="youtube_url", id_key="youtube_video_id")
items.sort(key=lambda x: float(x.get("finished_at") or x.get("updated_at") or 0), reverse=True)
return {"items": items[:lim], "count": len(items[:lim])}
def oauth_health_board(*, probe: bool = False) -> dict[str, Any]:
from . import db
from . import youtube_manage
from . import yt_long_db
from .yt_channel_meta import oauth_meta_from_channel, brand_hint_for_handle
rows = db.list_shorts_channels(enabled=None)
ypp_map = yt_long_db.ypp_ok_by_shorts_pk()
profiles = youtube_manage.list_yt_profile_caches()
out: list[dict[str, Any]] = []
probed = 0
for ch in rows:
pk = str(ch.get("id") or "")
meta = oauth_meta_from_channel(ch)
prof = profiles.get(pk) or {}
handle = prof.get("custom_url") or prof.get("handle") or ""
brand = brand_hint_for_handle(handle, str(ch.get("name") or ""), str(ch.get("note") or ""))
row = {
"id": pk,
"name": ch.get("name"),
"youtube_channel_id": ch.get("youtube_channel_id"),
"handle": handle,
"thumb_url": (prof.get("thumbnails") or {}).get("default", {}).get("url") if isinstance(prof.get("thumbnails"), dict) else "",
"oauth_ok": int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1),
"oauth_error": str(ch.get("oauth_error") or "")[:160],
"oauth_profile_id": meta.get("oauth_profile_id") or str(ch.get("oauth_profile_id") or ""),
"brand_hint": brand,
"authorized": bool(meta.get("authorized")),
"enabled": bool(ch.get("enabled")),
"ypp_ok": ypp_map.get(pk, -1),
}
out.append(row)
return {"channels": out, "total": len(out)}
async def oauth_health_probe_all() -> dict[str, Any]:
from .shorts_oauth import probe_all_enabled_channels
result = await probe_all_enabled_channels()
board = oauth_health_board(probe=False)
board["probe"] = result
return board

View File

@ -48,6 +48,27 @@ def hash_password(password: str) -> str:
return hashlib.sha256(f"{_secret()}:{password}".encode()).hexdigest()
def ensure_default_admin_credentials() -> None:
"""Ensure standard admin account uses config defaults (hackrobot / DY_ADMIN_PASSWORD)."""
from . import db
user = str(settings.admin_username or "hackrobot").strip()
expected_hash = hash_password(str(settings.admin_password or ""))
m = db.get_settings_map()
cur_user = str(m.get("admin_username") or "").strip()
cur_hash = str(m.get("admin_password_hash") or "").strip()
updates: dict[str, str] = {}
if not cur_user:
updates["admin_username"] = user
if not cur_hash or cur_user == user:
if cur_hash != expected_hash:
updates["admin_password_hash"] = expected_hash
if not cur_user and "admin_username" not in updates:
updates["admin_username"] = user
if updates:
db.update_settings_map(updates)
def get_admin_credentials() -> tuple[str, str]:
"""Return (username, password_hash) from DB; seed from config on first use."""
from . import db
@ -84,9 +105,10 @@ def change_admin_password(*, username: str, current_password: str, new_password:
db.update_settings_map({"admin_password_hash": hash_password(new_p)})
def create_session_token(username: str) -> str:
def create_session_token(username: str, *, role: str = "admin") -> str:
payload = {
"u": username,
"role": role if role in {"admin", "readonly"} else "admin",
"exp": int(time.time()) + SESSION_TTL_SEC,
}
body = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode().rstrip("=")
@ -95,6 +117,14 @@ def create_session_token(username: str) -> str:
def verify_session_token(token: str) -> Optional[str]:
payload = verify_session_payload(token)
if not payload:
return None
user = str(payload.get("u") or "").strip()
return user or None
def verify_session_payload(token: str) -> Optional[dict[str, Any]]:
if not token or "." not in token:
return None
body, sig = token.rsplit(".", 1)
@ -109,7 +139,9 @@ def verify_session_token(token: str) -> Optional[str]:
if int(payload.get("exp") or 0) < int(time.time()):
return None
user = str(payload.get("u") or "").strip()
return user or None
if not user:
return None
return payload
def session_user_from_request(request: Request) -> Optional[str]:
@ -123,8 +155,8 @@ def session_user_from_request(request: Request) -> Optional[str]:
return verify_session_token(token) if token else None
def set_session_cookie(response: Response, username: str, *, secure: bool) -> None:
token = create_session_token(username)
def set_session_cookie(response: Response, username: str, *, secure: bool, role: str = "admin") -> None:
token = create_session_token(username, role=role)
response.set_cookie(
key=SESSION_COOKIE,
value=token,
@ -178,7 +210,18 @@ class SessionAuthMiddleware:
await self.app(scope, receive, send)
return
if session_user_from_request(request):
user = session_user_from_request(request)
if user:
method = str(scope.get("method") or "GET").upper()
if method in {"POST", "PUT", "PATCH", "DELETE"}:
from .authz import session_role_from_request
if session_role_from_request(request) == "readonly":
allowed = {"/api/auth/logout"}
if path not in allowed:
resp = JSONResponse({"detail": "只读账号无写入权限"}, status_code=403)
await resp(scope, receive, send)
return
await self.app(scope, receive, send)
return

View File

@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
"""Audit trail for settings changes — append-only events, no data mutation."""
from __future__ import annotations
from typing import Any
_SENSITIVE_KEYS = frozenset(
{
"admin_password_hash",
"readonly_password_hash",
"shorts_oauth_client_secret",
"tiktok_oauth_client_secret",
"dy_cookie",
"yt_studio_cookies_by_profile",
"shorts_upload_socks_profiles",
"tiktok_upload_socks_profiles",
}
)
def _mask_value(key: str, value: Any) -> Any:
if key in _SENSITIVE_KEYS:
return "***"
if key == "shorts_oauth_profiles" and isinstance(value, list):
out = []
for row in value:
if not isinstance(row, dict):
continue
r = dict(row)
if r.get("client_secret"):
r["client_secret"] = "***"
out.append(r)
return out
if isinstance(value, str) and len(value) > 120:
return value[:80] + "…"
return value
def log_settings_patch(patch: dict[str, Any], *, actor: str = "") -> None:
if not patch:
return
try:
from . import db
if not db.get_settings_map().get("settings_audit_enabled", True):
return
except Exception:
pass
safe = {k: _mask_value(k, v) for k, v in patch.items() if v is not None}
if not safe:
return
keys = ", ".join(sorted(safe.keys())[:12])
more = len(safe) - 12
msg = f"设置变更:{keys}" + (f" 等 {more} 项" if more > 0 else "")
try:
from . import db
db.add_event(
kind="settings_audit",
level="info",
message=msg,
meta={"actor": actor or "system", "patch": safe},
)
except Exception:
pass

View File

@ -711,6 +711,25 @@ class TikTokPipeline:
oauth_checked_at=time.time(),
oauth_error="",
)
privacy = str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE").strip().upper()
if privacy in {"SELF_ONLY", "PRIVATE"} and cfg.get("notify_on_tiktok_unaudited", True):
try:
from .notify import send_webhook
asyncio.create_task(
send_webhook(
"tiktok_unaudited",
{
"message": f"TikTok 已上传但仅自己可见({privacy}):{fresh.get('anchor_name') or jid}",
"job_id": jid,
"channel_pk": ch_pk,
"privacy_level": privacy,
"platform": "tiktok",
},
)
)
except Exception:
pass
if cfg.get("tiktok_delete_clip_after_upload", True):
try:
Path(clip).unlink(missing_ok=True)

View File

@ -221,23 +221,71 @@ async def enable_video_monetize_with_ads(
video_id: str,
youtube_channel_id: str = "",
proxy_url: str = "",
channel_row: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Turn on 'Monetize with ads'. Retries a few Studio payload shapes."""
"""Turn on 'Monetize with ads'. Prefers Studio cookie session; falls back to OAuth bearer."""
from . import db as appdb
from . import yt_studio_auth as ysa
vid = str(video_id or "").strip()
if not vid:
return {"ok": False, "error": "no_video_id"}
ch = str(youtube_channel_id or "").strip()
cfg = appdb.get_settings_map()
pid = ysa.resolve_studio_profile_id(channel_row)
cookies = ysa.studio_cookies_for_profile(cfg, pid)
if ysa.studio_cookies_configured(cookies):
cookie_mon = await ysa.post_studio_monetize(
cookies=cookies,
video_id=vid,
youtube_channel_id=ch,
proxy_url=proxy_url,
)
if cookie_mon.get("ok"):
return cookie_mon
err = str(cookie_mon.get("error") or "")
if err == "missing_session_token":
return {
"ok": False,
"error": "缺少 Studio session token:请在设置 → OAuth 配置档填写(见说明)",
"monetize_error": cookie_mon.get("hint") or err,
}
if err == "studio_cookies_incomplete":
pass
else:
cookie_mon.setdefault("auth", "studio_cookie")
return cookie_mon
base = {"encryptedVideoId": vid, "videoReadMask": {"title": True}}
cert_top = _self_cert_no().get("newSelfCertificationData")
cert_skipped = _self_cert_skipped()
cert_top = cert_skipped.get("newSelfCertificationData")
ad_formats = {
"newHasOverlayAds": "ENABLED",
"newHasProductListingAds": "ENABLED",
"newHasSkippableVideoAds": "ENABLED",
"newHasNonSkippableVideoAds": "ENABLED",
}
payloads: list[dict[str, Any]] = [
{**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id=ch, client_name="WEB_CREATOR")},
{
**base,
"monetizationSettings": {"newMonetizeWithAds": True},
"adFormats": ad_formats,
"selfCertification": cert_skipped,
"context": _context(channel_id=ch, client_name=62),
},
{
**base,
"monetizationSettings": {"newMonetizeWithAds": True},
"selfCertification": cert_skipped,
"context": _context(channel_id=ch, client_name=62),
},
{**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id=ch, client_name=62)},
{**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id="", client_name="WEB_CREATOR")},
{**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id=ch, client_name="WEB_CREATOR")},
{
**base,
"monetizationSettings": {"newMonetizeWithAds": True},
"newSelfCertificationData": cert_top,
"context": _context(channel_id=ch, client_name="WEB_CREATOR"),
"context": _context(channel_id=ch, client_name=62),
},
{
**base,
@ -251,12 +299,6 @@ async def enable_video_monetize_with_ads(
"selfCertification": _self_cert_no(),
"context": _context(channel_id=ch, client_name="WEB_CREATOR"),
},
{
**base,
"monetizationSettings": {"newMonetizeWithAds": True},
"selfCertification": _self_cert_no_legacy(),
"context": _context(channel_id=ch, client_name=62),
},
]
last: dict[str, Any] = {"ok": False, "error": "no_attempt"}
for body in payloads:
@ -351,6 +393,7 @@ async def ensure_ypp_and_monetize(
video_id=video_id,
youtube_channel_id=yt_ch,
proxy_url=proxy_url,
channel_row=channel_row,
)
if not mon.get("ok"):
await asyncio.sleep(8)
@ -359,6 +402,7 @@ async def ensure_ypp_and_monetize(
video_id=video_id,
youtube_channel_id=yt_ch,
proxy_url=proxy_url,
channel_row=channel_row,
)
out["monetized"] = bool(mon.get("ok"))
if mon.get("ok"):

View File

@ -860,6 +860,13 @@ class YtLongPipeline:
raw = str(mon.get("monetize_error") or mon.get("error") or "")[:160]
if "授权范围" in raw or "insufficient" in raw.lower():
monetize_note = "获利未开:授权范围不够,请到 Shorts 重新授权该频道"
elif "session token" in raw.lower() or "studio cookie" in raw.lower():
monetize_note = f"获利未开:{raw}"
elif "invalid argument" in raw.lower() or "self_certification" in raw.lower():
monetize_note = (
"获利未开:需在设置 → OAuth 配置档填写 Studio Cookie + session token"
f"({raw[:80]})"
)
else:
monetize_note = f"获利未开:{raw}"
except Exception as exc:

View File

@ -0,0 +1,328 @@
# -*- coding: utf-8 -*-
"""YouTube Studio innertube auth via Google cookies (SAPISIDHASH).
OAuth bearer tokens work for Data API upload but Studio metadata_update
(set monetize / self-cert) requires browser session cookies + sessionInfo.token.
"""
from __future__ import annotations
import hashlib
import json
import re
import time
from typing import Any
import httpx
from .shorts_upload import _client_kwargs
_STUDIO_ORIGIN = "https://studio.youtube.com"
_DEFAULT_KEY = "AIzaSyBUPetSUmoZL-OhlxA7ZlfWJRJKBa7VFkE"
_UA = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
)
def sapisid_hash(sapisid: str, *, origin: str = _STUDIO_ORIGIN, ts: int | None = None) -> str:
stamp = ts if ts is not None else int(time.time())
digest = hashlib.sha1(f"{stamp} {sapisid} {origin}".encode()).hexdigest()
return f"{stamp}_{digest}"
def _cookie_val(cookies: dict[str, Any], *keys: str) -> str:
for k in keys:
v = str(cookies.get(k) or cookies.get(k.lower()) or cookies.get(k.upper()) or "").strip()
if v:
return v
return ""
def cookie_header(cookies: dict[str, Any]) -> str:
parts: list[str] = []
for key in ("SID", "HSID", "SSID", "APISID", "SAPISID", "LOGIN_INFO", "VISITOR_INFO1_LIVE"):
val = _cookie_val(cookies, key)
if val:
parts.append(f"{key}={val}")
return "; ".join(parts)
def studio_headers(cookies: dict[str, Any]) -> dict[str, str]:
sapisid = _cookie_val(cookies, "SAPISID", "sapisid")
auth = f"SAPISIDHASH {sapisid_hash(sapisid)}" if sapisid else ""
hdr = {
"content-type": "application/json",
"cookie": cookie_header(cookies),
"x-origin": _STUDIO_ORIGIN,
"origin": _STUDIO_ORIGIN,
"referer": f"{_STUDIO_ORIGIN}/",
"User-Agent": _UA,
}
if auth:
hdr["authorization"] = auth
visitor = _cookie_val(cookies, "VISITOR_INFO1_LIVE", "visitor_info1_live")
if visitor:
hdr["x-goog-visitor-id"] = visitor
return hdr
def parse_ytcfg_from_html(html: str) -> dict[str, Any]:
out: dict[str, Any] = {}
for pat in (
r"ytcfg\.set\s*\(\s*(\{.*?\})\s*\)\s*;",
r"var\s+ytcfg\s*=\s*(\{.*?\});",
):
m = re.search(pat, html, re.DOTALL)
if not m:
continue
try:
blob = json.loads(m.group(1))
if isinstance(blob, dict):
out.update(blob)
except Exception:
pass
for key in ("INNERTUBE_API_KEY", "DELEGATED_SESSION_ID", "CHANNEL_ID", "VISITOR_DATA", "XSRF_TOKEN"):
if key in out:
continue
m = re.search(rf'"{key}"\s*:\s*"([^"]+)"', html)
if m:
out[key] = m.group(1)
return out
def studio_cookies_configured(cookies: dict[str, Any] | None) -> bool:
if not cookies:
return False
need = ("SID", "HSID", "SSID", "APISID", "SAPISID")
return all(_cookie_val(cookies, k) for k in need)
def session_token_from_cookies(cookies: dict[str, Any]) -> str:
return _cookie_val(cookies, "SESSION_TOKEN", "session_token", "sessionToken")
async def fetch_studio_config(
cookies: dict[str, Any],
*,
proxy_url: str = "",
channel_url: str = "",
) -> dict[str, Any]:
"""Load studio.youtube.com and parse ytcfg (DELEGATED_SESSION_ID, etc.)."""
if not studio_cookies_configured(cookies):
return {"ok": False, "error": "studio_cookies_incomplete"}
url = channel_url or f"{_STUDIO_ORIGIN}/channel/"
try:
async with httpx.AsyncClient(**_client_kwargs(timeout=45.0, proxy_url=proxy_url)) as client:
resp = await client.get(url, headers=studio_headers(cookies), follow_redirects=True)
html = resp.text or ""
if resp.status_code >= 400:
return {"ok": False, "error": f"studio_page_{resp.status_code}", "snippet": html[:200]}
if "oops" in html.lower() and "something went wrong" in html.lower():
return {"ok": False, "error": "studio_page_error", "hint": "check LOGIN_INFO cookie"}
cfg = parse_ytcfg_from_html(html)
delegated = str(cfg.get("DELEGATED_SESSION_ID") or "").strip()
channel_id = str(cfg.get("CHANNEL_ID") or "").strip()
api_key = str(cfg.get("INNERTUBE_API_KEY") or _DEFAULT_KEY).strip()
if not delegated:
return {"ok": False, "error": "no_delegated_session_id", "keys": list(cfg.keys())[:12]}
return {
"ok": True,
"delegated_session_id": delegated,
"channel_id": channel_id,
"innertube_api_key": api_key,
"visitor_data": str(cfg.get("VISITOR_DATA") or "").strip(),
}
except Exception as exc:
return {"ok": False, "error": str(exc)[:240]}
def studio_cookies_for_profile(cfg: dict[str, Any], profile_id: str) -> dict[str, Any]:
pid = str(profile_id or "").strip().upper()
if not pid:
return {}
raw = cfg.get("yt_studio_cookies_by_profile")
if not isinstance(raw, dict):
return {}
row = raw.get(pid)
return dict(row) if isinstance(row, dict) else {}
def merge_studio_cookies_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> dict[str, dict[str, str]]:
from . import db as appdb
settings = existing_cfg or appdb.get_settings_map()
prev_raw = settings.get("yt_studio_cookies_by_profile")
prev: dict[str, dict[str, str]] = dict(prev_raw) if isinstance(prev_raw, dict) else {}
if not isinstance(incoming, dict):
return prev
keys = ("SID", "HSID", "SSID", "APISID", "SAPISID", "LOGIN_INFO", "SESSION_TOKEN", "VISITOR_INFO1_LIVE")
out: dict[str, dict[str, str]] = dict(prev)
for pid_raw, row in incoming.items():
pid = str(pid_raw or "").strip().upper()
if not pid or not isinstance(row, dict):
continue
old = dict(out.get(pid) or {})
merged: dict[str, str] = {}
for k in keys:
v = str(row.get(k) or row.get(k.lower()) or "").strip()
if (not v) or v.startswith("***"):
v = str(old.get(k) or old.get(k.lower()) or "").strip()
if v:
merged[k] = v
if merged:
out[pid] = merged
elif pid in out:
del out[pid]
return out
def public_studio_cookies_by_profile(cfg: dict[str, Any]) -> dict[str, Any]:
raw = cfg.get("yt_studio_cookies_by_profile")
if not isinstance(raw, dict):
return {}
pub: dict[str, Any] = {}
for pid_raw, row in raw.items():
pid = str(pid_raw or "").strip().upper()
if not pid or not isinstance(row, dict):
continue
pub[pid] = {
"configured": studio_cookies_configured(row),
"has_session_token": bool(session_token_from_cookies(row)),
"SID": ("***" + str(row.get("SID") or "")[-4:]) if str(row.get("SID") or "") else "",
"SAPISID": ("***" + str(row.get("SAPISID") or "")[-4:]) if str(row.get("SAPISID") or "") else "",
"SESSION_TOKEN": ("***" + str(row.get("SESSION_TOKEN") or "")[-6:]) if str(row.get("SESSION_TOKEN") or "") else "",
}
return pub
def resolve_studio_profile_id(channel_row: dict[str, Any] | None) -> str:
ch = channel_row or {}
pid = str(ch.get("oauth_profile_id") or "").strip().upper()
if pid:
return pid
src = str(ch.get("source_shorts_channel_pk") or "").strip()
if src:
try:
from . import db as appdb
sch = appdb.get_shorts_channel(src) or {}
pid = str(sch.get("oauth_profile_id") or "").strip().upper()
if pid:
return pid
except Exception:
pass
return "A"
async def post_studio_monetize(
*,
cookies: dict[str, Any],
video_id: str,
youtube_channel_id: str,
studio_cfg: dict[str, Any] | None = None,
proxy_url: str = "",
) -> dict[str, Any]:
"""Enable monetize with ads using cookie session (adasq-compatible payload)."""
vid = str(video_id or "").strip()
ch = str(youtube_channel_id or "").strip()
if not vid:
return {"ok": False, "error": "no_video_id"}
if not studio_cookies_configured(cookies):
return {"ok": False, "error": "studio_cookies_incomplete"}
cfg = studio_cfg or await fetch_studio_config(
cookies,
proxy_url=proxy_url,
channel_url=f"{_STUDIO_ORIGIN}/channel/{ch}/videos" if ch else "",
)
if not cfg.get("ok"):
return {"ok": False, "error": str(cfg.get("error") or "studio_config_fail")[:240]}
session_token = session_token_from_cookies(cookies)
if not session_token:
return {"ok": False, "error": "missing_session_token", "hint": "Studio 网络面板 metadata_update 里复制 sessionInfo.token"}
delegated = str(cfg.get("delegated_session_id") or "").strip()
api_key = str(cfg.get("innertube_api_key") or _DEFAULT_KEY).strip()
url = f"{_STUDIO_ORIGIN}/youtubei/v1/video_manager/metadata_update?alt=json&key={api_key}"
cert_questions = [
"VIDEO_SELF_CERTIFICATION_QUESTION_PY",
"VIDEO_SELF_CERTIFICATION_QUESTION_SC",
"VIDEO_SELF_CERTIFICATION_QUESTION_VG",
"VIDEO_SELF_CERTIFICATION_QUESTION_HD",
"VIDEO_SELF_CERTIFICATION_QUESTION_DG",
"VIDEO_SELF_CERTIFICATION_QUESTION_HH",
"VIDEO_SELF_CERTIFICATION_QUESTION_FM",
"VIDEO_SELF_CERTIFICATION_QUESTION_SE",
"VIDEO_SELF_CERTIFICATION_QUESTION_SK",
]
body: dict[str, Any] = {
"encryptedVideoId": vid,
"videoReadMask": {},
"monetizationSettings": {"newMonetizeWithAds": True},
"adFormats": {
"newHasOverlayAds": "ENABLED",
"newHasProductListingAds": "ENABLED",
"newHasSkippableVideoAds": "ENABLED",
"newHasNonSkippableVideoAds": "ENABLED",
},
"adBreaks": {
"newHasPrerolls": "DISABLED",
"newHasMidrollAds": "DISABLED",
"newHasManualMidrolls": "DISABLED",
"newHasPostrolls": "ENABLED",
},
"selfCertification": {
"newSelfCertificationData": {
"questionnaireAnswers": [
{"question": q, "answer": "VIDEO_SELF_CERTIFICATION_ANSWER_SKIPPED"}
for q in cert_questions
],
"certificationMethod": "VIDEO_SELF_CERTIFICATION_METHOD_DEFAULT_NONE",
"questionnaireVersion": "VIDEO_SELF_CERTIFICATION_QUESTIONNAIRE_VERSION_8",
}
},
"context": {
"client": {
"clientName": 62,
"clientVersion": "1.20210104.03.01",
"hl": "en-GB",
"gl": "US",
"experimentsToken": "",
"utcOffsetMinutes": 0,
"osName": "Android",
"androidSdkVersion": 33,
"deviceMake": "Google",
"deviceModel": "Pixel 6 Pro",
},
"request": {
"returnLogEntry": True,
"internalExperimentFlags": [],
"sessionInfo": {"token": session_token},
},
"user": {
"onBehalfOfUser": delegated,
"delegationContext": {
"externalChannelId": ch,
"roleType": {"channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"},
},
"serializedDelegationContext": "",
},
"clientScreenNonce": "",
},
}
try:
async with httpx.AsyncClient(**_client_kwargs(timeout=60.0, proxy_url=proxy_url)) as client:
resp = await client.post(url, headers=studio_headers(cookies), json=body)
data = resp.json() if resp.content else {}
if resp.status_code >= 400:
err = (
(data.get("error") or {}).get("message")
if isinstance(data, dict)
else None
) or resp.text[:300]
return {"ok": False, "error": str(err)[:400], "status_code": resp.status_code}
return {"ok": True, "auth": "studio_cookie"}
except Exception as exc:
return {"ok": False, "error": str(exc)[:400]}

View File

@ -0,0 +1,163 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Loader2, RefreshCw, RotateCcw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
type JobRow = {
platform: string;
id: string;
status: string;
anchor_name?: string;
error?: string;
external_url?: string;
finished_at?: number;
};
const PLAT: Record<string, { label: string; href: string; retry?: string }> = {
shorts: { label: "Shorts", href: "/shorts", retry: "/api/shorts/jobs" },
tiktok: { label: "TikTok", href: "/tiktok", retry: "/api/tiktok/jobs" },
yt_long: { label: "长视频", href: "/yt-long", retry: "/api/yt-long/jobs" },
x_clips: { label: "X", href: "/x", retry: "/api/x-clips/jobs" },
};
export default function DashboardPage() {
const toast = useToast();
const [items, setItems] = useState<JobRow[]>([]);
const [loading, setLoading] = useState(true);
const [status, setStatus] = useState("");
const load = useCallback(async () => {
setLoading(true);
try {
const q = status ? `?status=${encodeURIComponent(status)}&limit=80` : "?limit=80";
const data = await fetchJson<{ items?: JobRow[] }>(`/api/dashboard/jobs${q}`);
setItems(data.items || []);
} catch (e) {
toast.push((e as Error).message, "error");
} finally {
setLoading(false);
}
}, [status, toast]);
useEffect(() => {
void load();
}, [load]);
async function retryJob(row: JobRow) {
const base = PLAT[row.platform]?.retry;
if (!base) return;
try {
await fetchJson(`${base}/${row.id}/retry`, { method: "POST" });
toast.push("已加入重试", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "error");
}
}
async function replayArchive(row: JobRow) {
try {
await fetchJson(`/api/archive/${row.platform}/${row.id}/replay`, { method: "POST" });
toast.push("已从归档重传", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "error");
}
}
return (
<Shell>
<div className="mx-auto max-w-6xl space-y-4 p-4 md:p-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-lg font-semibold text-slate-100">跨平台任务看板</h1>
<p className="mt-1 text-xs text-slate-500">Shorts / TikTok / 长视频 / X 最近任务汇总</p>
</div>
<div className="flex flex-wrap gap-2">
<select
value={status}
onChange={(e) => setStatus(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-xs"
>
<option value="">全部状态</option>
<option value="failed">failed</option>
<option value="uploaded">uploaded</option>
<option value="scheduled">scheduled</option>
</select>
<button
type="button"
onClick={() => void load()}
className="inline-flex items-center gap-1 rounded-lg border border-white/10 px-3 py-1.5 text-xs"
>
<RefreshCw className="h-3.5 w-3.5" /> 刷新
</button>
</div>
</div>
{loading ? (
<div className="flex justify-center py-16">
<Loader2 className="h-6 w-6 animate-spin text-slate-500" />
</div>
) : (
<div className="overflow-x-auto rounded-xl border border-white/10">
<table className="min-w-full text-left text-xs">
<thead className="bg-black/40 text-slate-500">
<tr>
<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>
{items.map((row) => (
<tr key={`${row.platform}-${row.id}`} className="border-t border-white/5">
<td className="px-3 py-2">
<Link href={PLAT[row.platform]?.href || "/"} className="text-sky-300 hover:underline">
{PLAT[row.platform]?.label || row.platform}
</Link>
</td>
<td className="px-3 py-2">{row.anchor_name || "—"}</td>
<td className="px-3 py-2">{row.status}</td>
<td className="max-w-xs truncate px-3 py-2 text-slate-400" title={row.error}>
{row.error || "—"}
</td>
<td className="px-3 py-2 text-slate-500">{fmtTs(row.finished_at || 0)}</td>
<td className="px-3 py-2">
<div className="flex flex-wrap gap-1">
{row.status === "failed" ? (
<button
type="button"
onClick={() => void retryJob(row)}
className="rounded border border-white/10 px-2 py-0.5 text-[10px]"
>
重试
</button>
) : null}
<button
type="button"
onClick={() => void replayArchive(row)}
className="inline-flex items-center gap-0.5 rounded border border-white/10 px-2 py-0.5 text-[10px]"
>
<RotateCcw className="h-3 w-3" /> 归档重传
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
{!items.length ? <p className="p-6 text-center text-slate-500">暂无任务</p> : null}
</div>
)}
</div>
</Shell>
);
}

View File

@ -0,0 +1,127 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Activity, HardDrive, Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
type Health = {
monitor?: { running?: boolean; live_count?: number };
shorts?: { enabled?: boolean; last_error?: string };
tiktok?: { enabled?: boolean };
yt_long?: { enabled?: boolean };
};
type Metrics = {
disk_free_gb?: number;
shorts_quota_gap?: number;
yt_long_upload_gap?: number;
tiktok_daily_gap?: number;
failed_jobs?: number;
};
export default function OpsMobilePage() {
const toast = useToast();
const [health, setHealth] = useState<Health>({});
const [metrics, setMetrics] = useState<Metrics>({});
const [loading, setLoading] = useState(true);
const load = useCallback(async () => {
setLoading(true);
try {
const [h, m] = await Promise.all([
fetchJson<Health>("/api/health"),
fetchJson<Metrics>("/api/ops/alerts/metrics"),
]);
setHealth(h);
setMetrics(m);
} catch (e) {
toast.push((e as Error).message, "error");
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
const t = setInterval(() => void load(), 30000);
return () => clearInterval(t);
}, [load]);
return (
<Shell>
<div className="mx-auto max-w-lg space-y-4 p-4 pb-24">
<div className="flex items-center justify-between">
<h1 className="text-base font-semibold text-slate-100">运维速览</h1>
<button type="button" onClick={() => void load()} className="rounded-lg border border-white/10 p-2">
<RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
</button>
</div>
<div className="grid grid-cols-2 gap-3">
<Card icon={<Activity className="h-4 w-4 text-teal-400" />} label="抖音在播" value={String(health.monitor?.live_count ?? "—")} />
<Card icon={<HardDrive className="h-4 w-4 text-sky-400" />} label="磁盘 GB" value={metrics.disk_free_gb?.toFixed(1) ?? "—"} />
<Card label="Shorts 配额" value={String(metrics.shorts_quota_gap ?? "—")} />
<Card label="失败任务" value={String(metrics.failed_jobs ?? "—")} />
</div>
<div className="rounded-xl border border-white/10 bg-black/25 p-4 text-xs text-slate-400 space-y-2">
<div>监控:{health.monitor?.running ? "运行中" : "已停"}</div>
<div>Shorts:{health.shorts?.enabled ? "开" : "关"}</div>
<div>TikTok:{health.tiktok?.enabled ? "开" : "关"}</div>
<div>长视频:{health.yt_long?.enabled ? "开" : "关"}</div>
</div>
<div className="grid gap-2">
<Link href="/dashboard" className="rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-center">
任务看板
</Link>
<Link href="/youtube/health" className="rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-center">
YouTube 健康
</Link>
<Link href="/ops" className="rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-center">
完整运维页
</Link>
</div>
<button
type="button"
onClick={async () => {
try {
await fetchJson("/api/notify/test", { method: "POST" });
toast.push("ntfy 测试已发送", "ok");
} catch (e) {
toast.push((e as Error).message, "error");
}
}}
className="w-full rounded-xl border border-sky-500/30 bg-sky-500/10 py-3 text-sm text-sky-100"
>
测试通知
</button>
</div>
</Shell>
);
}
function Card({
icon,
label,
value,
}: {
icon?: React.ReactNode;
label: string;
value: string;
}) {
return (
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
<div className="mb-1 flex items-center gap-1 text-[10px] text-slate-500">
{icon}
{label}
</div>
<div className="text-xl font-semibold text-slate-100">{value}</div>
</div>
);
}

View File

@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Loader2, Save, ShieldOff } from "lucide-react";
import { Shell } from "@/components/Shell";
@ -71,6 +72,7 @@ export default function SettingsPage() {
body.notify_webhook_url = String(settings.notify_webhook_url || "");
body.notify_on_live = Boolean(settings.notify_on_live);
body.notify_on_offline = Boolean(settings.notify_on_offline);
body.notify_ntfy_on_douyin_live = Boolean(settings.notify_ntfy_on_douyin_live);
body.notify_on_risk = Boolean(settings.notify_on_risk);
body.notify_on_shorts_fail = settings.notify_on_shorts_fail !== false;
body.notify_on_shorts_ok = Boolean(settings.notify_on_shorts_ok);
@ -123,6 +125,42 @@ export default function SettingsPage() {
client_secret: String(p.client_secret || ""),
}));
body.shorts_oauth_profiles = oauthProfiles;
const studioCookiesRaw =
settings.yt_studio_cookies_by_profile && typeof settings.yt_studio_cookies_by_profile === "object"
? (settings.yt_studio_cookies_by_profile as Record<string, any>)
: {};
const studioPatch: Record<string, any> = {};
for (const pid of ["A", "B", "C", "D"]) {
const row = studioCookiesRaw[pid];
if (row && typeof row === "object") {
studioPatch[pid] = {
SID: String(row.SID || ""),
HSID: String(row.HSID || ""),
SSID: String(row.SSID || ""),
APISID: String(row.APISID || ""),
SAPISID: String(row.SAPISID || ""),
LOGIN_INFO: String(row.LOGIN_INFO || ""),
SESSION_TOKEN: String(row.SESSION_TOKEN || ""),
};
}
}
if (Object.keys(studioPatch).length) body.yt_studio_cookies_by_profile = studioPatch;
body.settings_audit_enabled = settings.settings_audit_enabled !== false;
body.db_backup_enabled = Boolean(settings.db_backup_enabled);
body.db_backup_interval_hours = Number(settings.db_backup_interval_hours ?? 24);
body.db_backup_keep_days = Number(settings.db_backup_keep_days ?? 7);
body.ops_alerts_enabled = Boolean(settings.ops_alerts_enabled);
body.ops_alert_disk_enabled = Boolean(settings.ops_alert_disk_enabled);
body.ops_alert_quota_enabled = Boolean(settings.ops_alert_quota_enabled);
body.ops_alert_interval_sec = Number(settings.ops_alert_interval_sec ?? 900);
body.ops_alert_cooldown_sec = Number(settings.ops_alert_cooldown_sec ?? 3600);
body.ops_alert_failed_jobs_threshold = Number(settings.ops_alert_failed_jobs_threshold ?? 50);
body.notify_on_tiktok_unaudited = settings.notify_on_tiktok_unaudited !== false;
body.notify_webhook_standard_json = Boolean(settings.notify_webhook_standard_json);
body.clip_archive_to_s3_enabled = Boolean(settings.clip_archive_to_s3_enabled);
body.readonly_username = String(settings.readonly_username || "");
const roPw = String(settings.readonly_password || "");
if (roPw && !roPw.startsWith("***")) body.readonly_password = roPw;
// Keep legacy global client in sync with profile A when A is filled
const profA = oauthProfiles.find((p) => p.id === "A");
if (profA?.client_id) body.shorts_oauth_client_id = profA.client_id;
@ -613,6 +651,9 @@ export default function SettingsPage() {
<p className="mt-1 text-[11px] leading-relaxed text-slate-500">
每个谷歌 Cloud 项目填一套 Client,保存一次即可。Shorts 频道只需选择 A/B/C/D,不必再手填密钥。
各项目均须登记同一回调 URI。密钥留空或显示 *** 表示不修改已有值。
<span className="block mt-1 text-amber-200/90">
长视频 YPP 自动开广告还需填写下方 Studio Cookie(与 OAuth 不同,从 studio.youtube.com 浏览器复制)。
</span>
</p>
</div>
{(["A", "B", "C", "D"] as const).map((pid) => {
@ -662,6 +703,28 @@ export default function SettingsPage() {
});
};
const ready = Boolean(String(row.client_id || "").trim() && String(row.client_secret || "").trim());
const studioAll =
settings.yt_studio_cookies_by_profile && typeof settings.yt_studio_cookies_by_profile === "object"
? (settings.yt_studio_cookies_by_profile as Record<string, any>)
: {};
const studioRow = (studioAll[pid] as Record<string, string>) || {};
const setStudioCookie = (key: string, val: string) => {
setSettings((prev) => {
const prevMap =
prev.yt_studio_cookies_by_profile && typeof prev.yt_studio_cookies_by_profile === "object"
? { ...(prev.yt_studio_cookies_by_profile as Record<string, any>) }
: {};
const prevRow = { ...(prevMap[pid] || {}) };
prevRow[key] = val;
prevMap[pid] = prevRow;
return { ...prev, yt_studio_cookies_by_profile: prevMap };
});
};
const studioReady = Boolean(
String(studioRow.SID || "").trim() &&
String(studioRow.SAPISID || "").trim() &&
String(studioRow.SESSION_TOKEN || "").trim()
);
return (
<div
key={pid}
@ -704,6 +767,51 @@ export default function SettingsPage() {
/>
</label>
</div>
<details className="mt-3 rounded-lg border border-white/10 bg-black/30 p-2">
<summary className="cursor-pointer text-[11px] text-slate-300">
Studio Cookie(长视频开广告)
<span className={`ml-2 ${studioReady ? "text-teal-300" : "text-amber-300"}`}>
{studioReady ? "已填" : "未填"}
</span>
</summary>
<p className="mt-2 text-[10px] leading-relaxed text-slate-500">
登录 studio.youtube.com(选对应品牌频道)→ F12 → Application → Cookies → 复制 SID/HSID/SSID/APISID/SAPISID/LOGIN_INFO。
再改任意视频标题 → Network → metadata_update → Payload → context.request.sessionInfo.token 复制到 SESSION_TOKEN。
Nomadro Hub 用账号 A + 品牌 nomad Immigration。
</p>
<div className="mt-2 grid gap-2 md:grid-cols-2">
{(["SID", "HSID", "SSID", "APISID", "SAPISID"] as const).map((k) => (
<label key={k} className="block text-[10px] text-slate-400">
{k}
<input
value={String(studioRow[k] || "")}
onChange={(e) => setStudioCookie(k, e.target.value)}
className="mt-0.5 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 font-mono text-[10px]"
autoComplete="off"
/>
</label>
))}
<label className="block text-[10px] text-slate-400 md:col-span-2">
LOGIN_INFO(品牌账号建议填写)
<input
value={String(studioRow.LOGIN_INFO || "")}
onChange={(e) => setStudioCookie("LOGIN_INFO", e.target.value)}
className="mt-0.5 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 font-mono text-[10px]"
autoComplete="off"
/>
</label>
<label className="block text-[10px] text-slate-400 md:col-span-2">
SESSION_TOKEN
<input
value={String(studioRow.SESSION_TOKEN || "")}
onChange={(e) => setStudioCookie("SESSION_TOKEN", e.target.value)}
className="mt-0.5 w-full rounded border border-white/10 bg-slate-900 px-2 py-1 font-mono text-[10px]"
placeholder="metadata_update 请求里的 sessionInfo.token"
autoComplete="off"
/>
</label>
</div>
</details>
</div>
);
})}
@ -830,10 +938,13 @@ export default function SettingsPage() {
{[
["notify_on_live", "开播通知"],
["notify_on_offline", "停播通知"],
["notify_ntfy_on_douyin_live", "抖音直播 ntfy"],
["notify_on_risk", "风控通知"],
["notify_on_shorts_fail", "Shorts 失败"],
["notify_on_shorts_ok", "Shorts 成功"],
["notify_on_shorts_quota", "Shorts 配额落后"],
["notify_on_tiktok_unaudited", "TikTok 仅自己可见"],
["notify_webhook_standard_json", "Webhook 标准 JSON v1"],
["capture_cover_on_start", "开播截图"],
].map(([key, label]) => (
<label key={key} className="inline-flex items-center gap-2">
@ -890,6 +1001,57 @@ export default function SettingsPage() {
</div>
</div>
<div className="mb-6 space-y-3 rounded-xl border border-white/10 bg-black/25 p-4">
<h3 className="text-sm font-medium text-slate-200">运维增强(默认关闭,不影响现有业务)</h3>
<div className="grid gap-3 md:grid-cols-2">
{[
["db_backup_enabled", "自动备份 monitor.db"],
["ops_alerts_enabled", "配额/磁盘/积压预警"],
["ops_alert_disk_enabled", "磁盘预警"],
["ops_alert_quota_enabled", "配额预警"],
["clip_archive_to_s3_enabled", "删除前归档 clip 到 S3"],
["settings_audit_enabled", "设置变更审计"],
].map(([key, label]) => (
<label key={key} className="inline-flex items-center gap-2 text-xs text-slate-300">
<input
type="checkbox"
checked={Boolean(settings[key])}
onChange={(e) => setSettings((prev) => ({ ...prev, [key]: e.target.checked }))}
/>
{label}
</label>
))}
</div>
<div className="grid gap-2 md:grid-cols-2">
<label className="block text-xs text-slate-400">
只读账号用户名
<input
value={String(settings.readonly_username || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, readonly_username: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
placeholder="留空=禁用只读登录"
/>
</label>
<label className="block text-xs text-slate-400">
只读账号密码
<input
type="password"
value={String(settings.readonly_password || "")}
onChange={(e) => setSettings((prev) => ({ ...prev, readonly_password: e.target.value }))}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-2 py-1.5 text-sm"
placeholder="至少 8 位"
/>
</label>
</div>
<p className="text-[11px] text-slate-500">
只读账号可查看全部页面,不能 POST/保存/启停 worker。备份文件见{" "}
<Link href="/ops/mobile" className="text-sky-300 underline">
运维速览
</Link>
或 API <code className="text-slate-400">/api/ops/backups</code>。
</p>
</div>
<OpsPanel />
<ApiKeyPanel />

View File

@ -0,0 +1,150 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Loader2, RefreshCw, ShieldCheck } from "lucide-react";
import { Shell } from "@/components/Shell";
import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet";
import { useToast } from "@/components/Toast";
import { fetchJson } from "@/lib/api";
type ChannelRow = {
id: string;
name?: string;
youtube_channel_id?: string;
handle?: string;
thumb_url?: string;
oauth_ok?: number;
oauth_error?: string;
oauth_profile_id?: string;
brand_hint?: string;
authorized?: boolean;
enabled?: boolean;
ypp_ok?: number;
yt_profile?: YtProfileSnippet | null;
};
export default function YoutubeOAuthHealthPage() {
const toast = useToast();
const [rows, setRows] = useState<ChannelRow[]>([]);
const [loading, setLoading] = useState(true);
const [probing, setProbing] = useState(false);
const load = useCallback(async () => {
setLoading(true);
try {
const data = await fetchJson<{ channels?: ChannelRow[] }>("/api/youtube/oauth-health");
setRows(data.channels || []);
} catch (e) {
toast.push((e as Error).message, "error");
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
}, [load]);
async function probeAll() {
setProbing(true);
try {
await fetchJson("/api/youtube/oauth-health/probe", { method: "POST" });
toast.push("OAuth 探测完成", "ok");
await load();
} catch (e) {
toast.push((e as Error).message, "error");
} finally {
setProbing(false);
}
}
const okCount = rows.filter((r) => r.oauth_ok === 1).length;
return (
<Shell>
<div className="mx-auto max-w-6xl space-y-4 p-4 md:p-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-lg font-semibold text-slate-100">YouTube 频道健康</h1>
<p className="mt-1 text-xs text-slate-500">
OAuth / YPP / Google 品牌名对照 · 重授权请选品牌名而非 YouTube 标题
</p>
</div>
<div className="flex gap-2">
<button
type="button"
onClick={() => void load()}
className="inline-flex items-center gap-1 rounded-lg border border-white/10 px-3 py-1.5 text-xs"
>
<RefreshCw className="h-3.5 w-3.5" /> 刷新
</button>
<button
type="button"
disabled={probing}
onClick={() => void probeAll()}
className="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"
>
{probing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <ShieldCheck className="h-3.5 w-3.5" />}
探测 OAuth
</button>
<Link href="/shorts/reauth-batch" className="rounded-lg border border-white/10 px-3 py-1.5 text-xs">
批量重授权
</Link>
</div>
</div>
<div className="rounded-xl border border-white/10 bg-black/25 px-4 py-3 text-sm text-slate-300">
已授权 <span className="text-teal-300">{okCount}</span> / {rows.length} ·
失败 {rows.filter((r) => r.oauth_ok === 0).length} · 未探测{" "}
{rows.filter((r) => r.oauth_ok === -1).length}
</div>
{loading ? (
<div className="flex justify-center py-16 text-slate-500">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : (
<div className="grid gap-3 md:grid-cols-2">
{rows.map((ch) => (
<div
key={ch.id}
className={`rounded-xl border p-4 ${
ch.oauth_ok === 1
? "border-teal-500/25 bg-teal-500/5"
: ch.oauth_ok === 0
? "border-rose-500/30 bg-rose-500/5"
: "border-white/10 bg-black/20"
}`}
>
<YtChannelProfileSnippet
profile={
ch.yt_profile || {
title: ch.name,
custom_url: ch.handle,
thumbnails: ch.thumb_url ? { default: { url: ch.thumb_url } } : undefined,
}
}
fallbackName={ch.name}
fallbackChannelId={ch.youtube_channel_id}
/>
<div className="mt-2 space-y-1 text-[11px] text-slate-400">
<div>
账号 {ch.oauth_profile_id || "—"} ·{" "}
{ch.oauth_ok === 1 ? "OAuth OK" : ch.oauth_ok === 0 ? "OAuth 失败" : "未探测"}
</div>
{ch.brand_hint ? (
<div className="text-amber-200/90">Google 品牌:{ch.brand_hint}</div>
) : null}
{ch.ypp_ok === 1 ? <div className="text-teal-300">YPP · 获利</div> : null}
{ch.oauth_error ? <div className="text-rose-300">{ch.oauth_error}</div> : null}
</div>
</div>
))}
</div>
)}
</div>
</Shell>
);
}

View File

@ -22,6 +22,7 @@ import {
} from "@/lib/youtubeLive";
const NAV = [
{ href: "/dashboard", label: "看板", emoji: "📋" },
{ href: "/", label: "概览", emoji: "📡" },
{ href: "/slots", label: "时段", emoji: "🕐" },
{ href: "/sessions", label: "场次", emoji: "🎬" },
@ -37,13 +38,14 @@ const NAV = [
{ href: "/x", label: "X", emoji: "𝕏" },
{ href: "/clash", label: "Clash", emoji: "🧿" },
{ href: "/ops", label: "运维", emoji: "🛰️" },
{ href: "/ops/mobile", label: "运维·简", emoji: "📱" },
{ href: "/downloads", label: "下载", emoji: "⬇️" },
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
{ href: "/settings", label: "设置", emoji: "⚙️" },
];
/** Bottom bar: 概览 / TikTok / X / Shorts + 更多(YouTube 仅在「更多」) */
const MOBILE_PRIMARY = ["/", "/tiktok", "/x", "/shorts"];
const MOBILE_PRIMARY = ["/", "/dashboard", "/tiktok", "/shorts"];
function navActive(pathname: string, href: string) {
return pathname === href || (href !== "/" && pathname.startsWith(href));

View File

@ -254,6 +254,22 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
() => (schedule?.channels || []).find((c) => c.group_id === groupId) || null,
[schedule, groupId]
);
const slotConflicts = useMemo(() => {
const byKey = new Map<string, { url?: string; channels: string[] }>();
for (const ch of schedule?.channels || []) {
const label = String(ch.name || ch.group_id || "");
for (const slot of ch.slots || []) {
const key = String(slot.pool_url_id || slot.url || "").trim();
if (!key) continue;
const prev = byKey.get(key) || { url: slot.url, channels: [] };
if (!prev.channels.includes(label)) prev.channels.push(label);
byKey.set(key, prev);
}
}
return [...byKey.entries()]
.filter(([, v]) => v.channels.length > 1)
.map(([key, v]) => ({ key, url: v.url, channels: v.channels }));
}, [schedule]);
const channelById = useMemo(() => {
const m: Record<string, ManagedChannel> = {};
for (const c of channels) m[c.id] = c;
@ -749,6 +765,18 @@ export function YtAssignPanel({ channels }: { channels: ManagedChannel[] }) {
</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>
</div>
) : null}
{schedule && (schedule.channels || []).length > 0 ? (
<section className="rounded-2xl border border-violet-500/25 bg-violet-500/5 p-4">
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">