diff --git a/backend/app/main.py b/backend/app/main.py index 624e943..91dea34 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -535,6 +535,26 @@ async def shorts_live_analytics( top_anchors=top_anchors, ) channels = db.shorts_live_channel_stats(date_from=date_from, date_to=date_to) + ypp_by_shorts: dict[str, int] = {} + try: + from . import yt_long_db, youtube_manage + + ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk() + enriched = [] + for c in channels: + row = dict(c) + pk = str(row.get("id") or "") + if pk: + ch = db.get_shorts_channel(pk) or {} + row["yt_profile"] = youtube_manage._snippet_from_channel_row(ch) + row["authorized"] = bool(str(ch.get("refresh_token") or "").strip()) + row["oauth_ok"] = ch.get("oauth_ok") + row["oauth_profile_id"] = str(ch.get("oauth_profile_id") or "").strip().upper() + row["ypp_ok"] = ypp_by_shorts.get(pk, -1) + enriched.append(row) + channels = enriched + except Exception: + pass recent = db.list_sessions(platform="shorts", limit=20, offset=0) live_now = sum(1 for c in channels if int(c.get("active") or 0) > 0 or str(c.get("last_status") or "") == "live") return { @@ -1352,6 +1372,14 @@ async def yt_long_channels_import_shorts() -> dict[str, Any]: return {"ok": True, **result} +@app.post("/api/yt-long/channels/probe-ypp") +async def yt_long_channels_probe_ypp(limit: int = Query(50, ge=1, le=200)) -> dict[str, Any]: + """Refresh YPP flags for yt_long channels linked to Shorts OAuth.""" + from .yt_long_monetize import refresh_all_ypp_from_shorts + + return await refresh_all_ypp_from_shorts(limit=limit) + + @app.post("/api/yt-long/channels") async def yt_long_channels_create(body: dict[str, Any] | None = None) -> dict[str, Any]: from . import yt_long_db diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index f4e15e8..7ecba96 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -340,6 +340,14 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic if yt_title and (not name or name.startswith("Shorts") or name == "未命名频道"): patch["name"] = yt_title updated = db.update_shorts_channel(channel_pk, **patch) + try: + from . import youtube_manage as ytm + from .yt_long_monetize import refresh_ypp_for_shorts_channel + + await ytm.fetch_channel_profile(channel_pk) + await refresh_ypp_for_shorts_channel(channel_pk) + except Exception: + pass return { "ok": True, "channel": updated, diff --git a/backend/app/shorts_schedule.py b/backend/app/shorts_schedule.py index 9912604..94fb191 100644 --- a/backend/app/shorts_schedule.py +++ b/backend/app/shorts_schedule.py @@ -213,6 +213,14 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: from .db import SHORTS_DAILY_FORCE, _normalize_daily_quota from .upload_timeline import build_timeline + ypp_by_shorts = {} + try: + from . import yt_long_db + + ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk() + except Exception: + ypp_by_shorts = {} + for c in channels: cid = str(c["id"]) daily_min = _normalize_daily_quota(c.get("daily_min"), default=SHORTS_DAILY_FORCE) @@ -243,6 +251,12 @@ def schedule_board(limit: int = 24) -> dict[str, Any]: "max_met": used >= daily_max, "behind_pace": bool(c.get("enabled") and used < expected_min and used < daily_min), "yt_profile": youtube_manage._snippet_from_channel_row(c), + "last_status": str(c.get("last_status") or "offline"), + "last_title": str(c.get("last_title") or ""), + "last_live_url": str(c.get("last_live_url") or ""), + "oauth_ok": c.get("oauth_ok"), + "oauth_error": str(c.get("oauth_error") or ""), + "ypp_ok": ypp_by_shorts.get(cid, -1), **stats, } ) diff --git a/backend/app/youtube_manage.py b/backend/app/youtube_manage.py index 5302031..e6b0d4c 100644 --- a/backend/app/youtube_manage.py +++ b/backend/app/youtube_manage.py @@ -104,9 +104,17 @@ async def _delete(path: str, *, token: str, params: dict[str, Any]) -> None: def list_managed_channels() -> list[dict[str, Any]]: rows = db.list_shorts_channels() + ypp_by_shorts: dict[str, int] = {} + try: + from . import yt_long_db + + ypp_by_shorts = yt_long_db.ypp_ok_by_shorts_pk() + except Exception: + ypp_by_shorts = {} out = [] for ch in rows: sn = _snippet_from_channel_row(ch) or {} + cid = str(ch.get("id") or "") out.append( { "id": ch.get("id"), @@ -114,6 +122,13 @@ def list_managed_channels() -> list[dict[str, Any]]: "youtube_channel_id": ch.get("youtube_channel_id") or sn.get("youtube_channel_id") or "", "enabled": bool(ch.get("enabled")), "authorized": bool(str(ch.get("refresh_token") or "").strip()), + "oauth_profile_id": str(ch.get("oauth_profile_id") or "").strip().upper(), + "oauth_ok": ch.get("oauth_ok"), + "oauth_error": str(ch.get("oauth_error") or ""), + "last_status": str(ch.get("last_status") or "offline"), + "last_title": str(ch.get("last_title") or ""), + "last_live_url": str(ch.get("last_live_url") or ""), + "ypp_ok": ypp_by_shorts.get(cid, -1), "daily_min": ch.get("daily_min"), "daily_max": ch.get("daily_max"), "privacy": ch.get("privacy"), diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index 1f80c40..5c80115 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -1099,6 +1099,45 @@ def import_channels_from_shorts() -> dict[str, Any]: return sync_channels_from_shorts() +def ypp_ok_by_shorts_pk() -> dict[str, int]: + """Map shorts channel pk -> yt_long ypp_ok (-1/0/1).""" + out: dict[str, int] = {} + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + for row in conn.execute( + "SELECT source_shorts_channel_pk, ypp_ok FROM yt_long_channels WHERE source_shorts_channel_pk != ''" + ).fetchall(): + pk = str(row["source_shorts_channel_pk"] or "").strip() + if not pk: + continue + try: + out[pk] = int(row["ypp_ok"] if row["ypp_ok"] is not None else -1) + except Exception: + out[pk] = -1 + finally: + conn.close() + return out + + +def get_yt_long_by_shorts_pk(shorts_pk: str) -> dict[str, Any] | None: + pk = str(shorts_pk or "").strip() + if not pk: + return None + with _lock: + conn = _connect() + try: + ensure_yt_long_tables(conn) + row = conn.execute( + "SELECT * FROM yt_long_channels WHERE source_shorts_channel_pk = ? LIMIT 1", + (pk,), + ).fetchone() + return dict(row) if row else None + finally: + conn.close() + + def public_yt_long_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: if not ch: diff --git a/backend/app/yt_long_monetize.py b/backend/app/yt_long_monetize.py index 0a08a37..63d278a 100644 --- a/backend/app/yt_long_monetize.py +++ b/backend/app/yt_long_monetize.py @@ -247,6 +247,12 @@ async def ensure_ypp_and_monetize( pass want = ypp if force_monetize is None else bool(force_monetize) + if not want and int((channel_row or {}).get("monetize_default") or 1) == 1: + try: + if int((channel_row or {}).get("ypp_ok") or -1) == 1: + want = True + except Exception: + pass if not want: out["skipped"] = "not_ypp" return out @@ -271,3 +277,66 @@ async def ensure_ypp_and_monetize( if not mon.get("ok"): out["monetize_error"] = str(mon.get("error") or "")[:300] return out + + +async def refresh_ypp_for_shorts_channel(shorts_pk: str) -> dict[str, Any]: + """Probe YPP via OAuth and update linked yt_long_channels row.""" + from . import db as appdb + from . import yt_long_db as yldb + from .shorts_oauth import channel_oauth_creds + + pk = str(shorts_pk or "").strip() + if not pk: + return {"ok": False, "error": "no_pk"} + row = yldb.get_yt_long_by_shorts_pk(pk) + ch = appdb.get_shorts_channel(pk) or {} + creds = channel_oauth_creds(ch if ch else (row or {})) + if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")): + return {"ok": False, "error": "no_oauth", "shorts_pk": pk} + try: + access = await refresh_access_token( + client_id=str(creds["client_id"]), + client_secret=str(creds["client_secret"]), + refresh_token=str(creds["refresh_token"]), + ) + except Exception as exc: + return {"ok": False, "error": f"token:{exc}"[:200], "shorts_pk": pk} + info = await fetch_channel_ypp_status(access_token=access) + ypp = bool(info.get("ypp")) + yt_id = str(info.get("channel_id") or ch.get("youtube_channel_id") or "").strip() + long_id = str((row or {}).get("id") or "").strip() + if long_id and info.get("ok"): + patch: dict[str, Any] = { + "ypp_ok": 1 if ypp else 0, + "ypp_checked_at": time.time(), + } + if yt_id: + patch["youtube_channel_id"] = yt_id + yldb.update_yt_long_channel(long_id, **patch) + return { + "ok": bool(info.get("ok")), + "ypp": ypp, + "shorts_pk": pk, + "yt_long_pk": long_id, + "youtube_channel_id": yt_id, + "error": info.get("error"), + } + + +async def refresh_all_ypp_from_shorts(*, limit: int = 50) -> dict[str, Any]: + from . import db as appdb + from . import yt_long_db as yldb + + rows = appdb.list_shorts_channels(enabled=None) + results: list[dict[str, Any]] = [] + ypp_count = 0 + for ch in rows[: max(1, min(limit, 200))]: + if not str(ch.get("refresh_token") or "").strip(): + continue + if not yldb.get_yt_long_by_shorts_pk(str(ch.get("id") or "")): + continue + r = await refresh_ypp_for_shorts_channel(str(ch.get("id") or "")) + results.append(r) + if r.get("ypp"): + ypp_count += 1 + return {"probed": len(results), "ypp_channels": ypp_count, "results": results} diff --git a/frontend/src/app/shorts/page.tsx b/frontend/src/app/shorts/page.tsx index 108901c..1e5c301 100644 --- a/frontend/src/app/shorts/page.tsx +++ b/frontend/src/app/shorts/page.tsx @@ -31,6 +31,7 @@ import { import { UploadTimeline } from "@/components/UploadTimeline"; import { YouTubeLiveBadge } from "@/components/YouTubeLiveBadge"; import { YtChannelProfileSnippet, type YtProfileSnippet } from "@/components/YtChannelProfileSnippet"; +import type { YtChannelMeta } from "@/components/YtChannelMetaBadges"; import { SessionCharts, type RelayStats } from "@/components/SessionCharts"; import { PageLoader, TableSkeleton } from "@/components/ui"; import { fetchJson, fmtDuration, fmtTs, todayBeijingISO, shiftBeijingISO } from "@/lib/api"; @@ -84,6 +85,12 @@ type BoardChannel = { max_met?: boolean; behind_pace?: boolean; yt_profile?: YtProfileSnippet | null; + ypp_ok?: number; + oauth_ok?: number; + oauth_error?: string; + last_status?: string; + last_title?: string; + last_live_url?: string; }; type Job = { @@ -394,6 +401,18 @@ export default function ShortsPage() { oauth_error?: string; }>; + function channelMeta(ch: BoardChannel): YtChannelMeta { + const oauthBad = oauthIssues.some((x) => x.id === ch.id); + return { + enabled: ch.enabled, + authorized: ch.authorized, + oauthOk: oauthBad ? 0 : ch.oauth_ok, + oauthError: oauthBad ? oauthIssues.find((x) => x.id === ch.id)?.oauth_error : ch.oauth_error, + yppOk: ch.ypp_ok, + oauthProfileId: ch.oauth_profile_id, + }; + } + async function probeOauth() { setBusy(true); try { @@ -755,12 +774,22 @@ export default function ShortsPage() { {liveChannels.map((ch) => (