From 1febe0869eacb4291e45aed2aabf8a98ea8c2091 Mon Sep 17 00:00:00 2001 From: eric Date: Thu, 20 Aug 2026 12:55:25 -0500 Subject: [PATCH] feat(yt-long): auto-enable ad monetization for YPP channels Detect isChannelMonetizationEnabled and best-effort turn on Monetize with ads after long-form upload. Co-authored-by: Cursor --- backend/app/db.py | 1 + backend/app/main.py | 1 + backend/app/yt_long_db.py | 40 +++++- backend/app/yt_long_monetize.py | 218 ++++++++++++++++++++++++++++++ backend/app/yt_long_pipeline.py | 28 +++- frontend/src/app/yt-long/page.tsx | 7 + 6 files changed, 290 insertions(+), 5 deletions(-) create mode 100644 backend/app/yt_long_monetize.py diff --git a/backend/app/db.py b/backend/app/db.py index 80e4dd2..8587a91 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -525,6 +525,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "clip_cascade_enabled": True, "clips_max_age_hours": 24, "clips_min_free_gb": 12, + "yt_long_monetize_when_ypp": True, "tiktok_auto_retry_failed": False, "tiktok_auto_retry_max_attempts": 3, "tiktok_auto_retry_interval_sec": 300, diff --git a/backend/app/main.py b/backend/app/main.py index 966dc31..48e00bc 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1218,6 +1218,7 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st "yt_long_landscape_16x9", "clip_cascade_enabled", "yt_long_auto_match_source", + "yt_long_monetize_when_ypp", ): if k in raw: patch[k] = bool(raw[k]) diff --git a/backend/app/yt_long_db.py b/backend/app/yt_long_db.py index 2b8b9f3..2cfcdf8 100644 --- a/backend/app/yt_long_db.py +++ b/backend/app/yt_long_db.py @@ -109,6 +109,26 @@ def ensure_yt_long_tables(conn: sqlite3.Connection) -> None: conn.execute( "CREATE INDEX IF NOT EXISTS idx_yt_long_channels_enabled ON yt_long_channels(enabled, last_assigned_at)" ) + # YPP / monetization cache (additive; safe on existing DBs) + try: + cols = {str(r[1]) for r in conn.execute("PRAGMA table_info(yt_long_channels)").fetchall()} + except Exception: + cols = set() + if "ypp_ok" not in cols: + try: + conn.execute("ALTER TABLE yt_long_channels ADD COLUMN ypp_ok INTEGER NOT NULL DEFAULT -1") + except Exception: + pass + if "ypp_checked_at" not in cols: + try: + conn.execute("ALTER TABLE yt_long_channels ADD COLUMN ypp_checked_at REAL NOT NULL DEFAULT 0") + except Exception: + pass + if "monetize_default" not in cols: + try: + conn.execute("ALTER TABLE yt_long_channels ADD COLUMN monetize_default INTEGER NOT NULL DEFAULT 1") + except Exception: + pass def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int: @@ -717,6 +737,9 @@ def update_yt_long_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: "oauth_ok", "oauth_checked_at", "oauth_error", + "ypp_ok", + "ypp_checked_at", + "monetize_default", } sets: list[str] = [] params: list[Any] = [] @@ -725,6 +748,13 @@ def update_yt_long_channel(channel_pk: str, **fields: Any) -> dict[str, Any]: continue if k == "enabled": v = 1 if v else 0 + if k == "monetize_default": + v = 1 if v else 0 + if k == "ypp_ok": + try: + v = int(v) + except Exception: + continue if k == "daily_max": try: v = max(0, min(50, int(v))) @@ -871,7 +901,7 @@ def public_yt_long_channel(ch: dict[str, Any] | None) -> dict[str, Any] | None: def channel_board(push_date: str = "") -> dict[str, Any]: day = push_date or push_date_from_ts(time.time()) - placeholders = ",".join("?" for _ in _QUOTA_STATUSES) + placeholders = ",".join("?" for _ in _UPLOAD_STATUSES) channels = list_yt_long_channels(enabled=None) board: list[dict[str, Any]] = [] total_gap = 0 @@ -887,7 +917,7 @@ def channel_board(push_date: str = "") -> dict[str, Any]: SELECT COUNT(*) AS c FROM yt_long_jobs WHERE push_date = ? AND channel_pk = ? AND status IN ({placeholders}) """, - (day, cid, *_QUOTA_STATUSES), + (day, cid, *_UPLOAD_STATUSES), ).fetchone() used = int(used_row["c"]) if used_row else 0 by = { @@ -903,6 +933,10 @@ def channel_board(push_date: str = "") -> dict[str, Any]: } gap = max(0, dmax - used) if ch.get("enabled") else 0 total_gap += gap + try: + ypp_ok = int(ch.get("ypp_ok") if ch.get("ypp_ok") is not None else -1) + except Exception: + ypp_ok = -1 board.append( { "id": cid, @@ -920,6 +954,8 @@ def channel_board(push_date: str = "") -> dict[str, Any]: "failed": int(by.get("failed") or 0), "oauth_ok": ch.get("oauth_ok"), "oauth_error": ch.get("oauth_error") or "", + "ypp_ok": ypp_ok, + "monetize_default": bool(int(ch.get("monetize_default") if ch.get("monetize_default") is not None else 1)), } ) finally: diff --git a/backend/app/yt_long_monetize.py b/backend/app/yt_long_monetize.py new file mode 100644 index 0000000..39d3763 --- /dev/null +++ b/backend/app/yt_long_monetize.py @@ -0,0 +1,218 @@ +# -*- coding: utf-8 -*- +"""Enable YouTube long-form ad monetization for YPP-eligible channels. + +Detects YPP via Data API channels.status.isChannelMonetizationEnabled. +After upload, best-effort enables "Monetize with ads" via YouTube Studio +innertube metadata_update (Data API cannot set this for normal creators). + +Never raises into the upload caller — monetize failure must not fail the upload. +""" +from __future__ import annotations + +import time +from typing import Any + +import httpx + +from .shorts_upload import _client_kwargs, refresh_access_token + +# Studio innertube (public web client key; used by YouTube Studio web) +_STUDIO_KEY = "AIzaSyBUPetSUmoZL-OhlxA7ZlfWJRJKBa7VFkE" +_STUDIO_ORIGIN = "https://studio.youtube.com" + + +def _self_cert_payload() -> dict[str, Any]: + """Skip altered-content questionnaire answers (same pattern Studio uses for defaults).""" + qs = [ + "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", + ] + return { + "newSelfCertificationData": { + "questionnaireAnswers": [ + { + "question": q, + "answer": "VIDEO_SELF_CERTIFICATION_ANSWER_SKIPPED", + } + for q in qs + ], + "certificationMethod": "VIDEO_SELF_CERTIFICATION_METHOD_DEFAULT_NONE", + "questionnaireVersion": "VIDEO_SELF_CERTIFICATION_QUESTIONNAIRE_VERSION_8", + } + } + + +async def fetch_channel_ypp_status( + *, + access_token: str, + proxy_url: str = "", +) -> dict[str, Any]: + """Return {ypp: bool, channel_id, raw_status} for the authorized account.""" + async with httpx.AsyncClient(**_client_kwargs(timeout=45.0, proxy_url=proxy_url)) as client: + resp = await client.get( + "https://www.googleapis.com/youtube/v3/channels", + params={"part": "id,status,snippet", "mine": "true"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + 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[:200] + return {"ok": False, "ypp": False, "error": str(err)[:300]} + items = data.get("items") or [] + if not items: + return {"ok": False, "ypp": False, "error": "no_channel"} + item = items[0] + st = item.get("status") or {} + ypp = bool(st.get("isChannelMonetizationEnabled")) + return { + "ok": True, + "ypp": ypp, + "channel_id": str(item.get("id") or ""), + "title": str(((item.get("snippet") or {}).get("title") or "")), + "status": st, + } + + +async def enable_video_monetize_with_ads( + *, + access_token: str, + video_id: str, + youtube_channel_id: str = "", + proxy_url: str = "", +) -> dict[str, Any]: + """Best-effort: turn on 'Monetize with ads' like Studio's default checkbox.""" + vid = str(video_id or "").strip() + if not vid: + return {"ok": False, "error": "no_video_id"} + ch = str(youtube_channel_id or "").strip() + body: dict[str, Any] = { + "encryptedVideoId": vid, + "videoReadMask": {}, + "monetizationSettings": {"newMonetizeWithAds": True}, + "selfCertification": _self_cert_payload(), + "context": { + "client": { + "clientName": 62, + "clientVersion": "1.20240304.01.00", + "hl": "en", + "gl": "US", + "utcOffsetMinutes": 0, + }, + "request": {"returnLogEntry": True, "internalExperimentFlags": []}, + "user": { + "delegationContext": { + "externalChannelId": ch, + "roleType": {"channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"}, + } + }, + }, + } + url = f"{_STUDIO_ORIGIN}/youtubei/v1/video_manager/metadata_update?alt=json&key={_STUDIO_KEY}" + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + "x-origin": _STUDIO_ORIGIN, + "origin": _STUDIO_ORIGIN, + "referer": f"{_STUDIO_ORIGIN}/", + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" + ), + } + try: + async with httpx.AsyncClient(**_client_kwargs(timeout=60.0, proxy_url=proxy_url)) as client: + resp = await client.post(url, headers=headers, 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} + # Studio often returns 200 even when partial; treat HTTP OK as soft success + return {"ok": True, "raw_keys": list(data.keys())[:12] if isinstance(data, dict) else []} + except Exception as exc: + return {"ok": False, "error": str(exc)[:400]} + + +async def ensure_ypp_and_monetize( + *, + client_id: str, + client_secret: str, + refresh_token: str, + video_id: str, + channel_row: dict[str, Any] | None = None, + proxy_url: str = "", + force_monetize: bool | None = None, +) -> dict[str, Any]: + """ + If channel is YPP-eligible (or force_monetize), enable ads monetization on video. + + Updates yt_long_channels.ypp_ok cache when channel_row has an id. + """ + from . import yt_long_db + + out: dict[str, Any] = {"ypp": False, "monetized": False, "skipped": ""} + try: + access = await refresh_access_token( + client_id=client_id, + client_secret=client_secret, + refresh_token=refresh_token, + proxy_url=proxy_url, + ) + except Exception as exc: + out["error"] = f"token:{exc}"[:200] + return out + + ypp_info = await fetch_channel_ypp_status(access_token=access, proxy_url=proxy_url) + ypp = bool(ypp_info.get("ypp")) + out["ypp"] = ypp + out["ypp_probe"] = {k: ypp_info.get(k) for k in ("ok", "channel_id", "error")} + yt_ch = str(ypp_info.get("channel_id") or (channel_row or {}).get("youtube_channel_id") or "") + + cid = str((channel_row or {}).get("id") or "") + if cid: + try: + yt_long_db.update_yt_long_channel( + cid, + ypp_ok=1 if ypp else 0, + ypp_checked_at=time.time(), + youtube_channel_id=yt_ch or str((channel_row or {}).get("youtube_channel_id") or ""), + ) + except Exception: + pass + + want = force_monetize + if want is None: + # Channel override: monetize_default=0 disables; default on when YPP + try: + md = (channel_row or {}).get("monetize_default") + if md is not None and int(md) == 0: + want = False + else: + want = ypp + except Exception: + want = ypp + + if not want: + out["skipped"] = "not_ypp" if not ypp else "monetize_default_off" + return out + + mon = await enable_video_monetize_with_ads( + access_token=access, + video_id=video_id, + youtube_channel_id=yt_ch, + proxy_url=proxy_url, + ) + out["monetized"] = bool(mon.get("ok")) + if not mon.get("ok"): + out["monetize_error"] = str(mon.get("error") or "")[:300] + return out diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index 6e40b06..250c6f7 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -19,6 +19,7 @@ from .shorts_clip import resolve_stream_candidates from .timeutil import push_date_from_ts from .yt_long_clip import record_long_clip from .yt_long_db import YT_LONG_MAX_SEC, YT_LONG_MIN_SEC +from .yt_long_monetize import ensure_ypp_and_monetize from .yt_long_upload import upload_youtube_long_mp4 @@ -412,6 +413,7 @@ class YtLongPipeline: "yt_long_upload_min_gap_sec": int(cfg.get("yt_long_upload_min_gap_sec") or 900), "yt_long_landscape_16x9": bool(cfg.get("yt_long_landscape_16x9", False)), "clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)), + "yt_long_monetize_when_ypp": bool(cfg.get("yt_long_monetize_when_ypp", True)), "clips_max_age_hours": float(cfg.get("clips_max_age_hours") or 24), "clips_min_free_gb": float(cfg.get("clips_min_free_gb") or 12), }, @@ -780,6 +782,25 @@ class YtLongPipeline: ) vid = str(result.get("video_id") or "") url = str(result.get("url") or "") + monetize_note = "" + if cfg.get("yt_long_monetize_when_ypp", True) and vid: + try: + mon = await ensure_ypp_and_monetize( + client_id=str(creds["client_id"]), + client_secret=str(creds["client_secret"]), + refresh_token=str(creds["refresh_token"]), + video_id=vid, + channel_row=channel, + proxy_url=proxy, + ) + if mon.get("monetized"): + monetize_note = "ypp_monetize_on" + elif mon.get("skipped"): + monetize_note = f"ypp_skip:{mon.get('skipped')}" + elif mon.get("monetize_error") or mon.get("error"): + monetize_note = f"ypp_monetize_fail:{(mon.get('monetize_error') or mon.get('error') or '')[:120]}" + except Exception as exc: + monetize_note = f"ypp_monetize_err:{str(exc)[:120]}" yt_long_db.update_yt_long_job( jid, status="uploaded", @@ -787,16 +808,17 @@ class YtLongPipeline: youtube_url=url, title=title, description=description, - error="", + error=monetize_note, finished_at=time.time(), clip_path="" if cfg.get("yt_long_delete_clip_after_upload", True) else clip, ) _emit( "yt_long_ok", "info", - f"长视频已上传:{fresh.get('anchor_name') or jid} → {url}", + f"长视频已上传:{fresh.get('anchor_name') or jid} → {url}" + + (f"({monetize_note})" if monetize_note else ""), fresh, - {"youtube_url": url, "video_id": vid}, + {"youtube_url": url, "video_id": vid, "monetize": monetize_note}, ) if cfg.get("yt_long_delete_clip_after_upload", True): try: diff --git a/frontend/src/app/yt-long/page.tsx b/frontend/src/app/yt-long/page.tsx index f5abd62..d23c45d 100644 --- a/frontend/src/app/yt-long/page.tsx +++ b/frontend/src/app/yt-long/page.tsx @@ -51,6 +51,8 @@ type BoardChannel = { pending: number; failed?: number; gap?: number; + ypp_ok?: number; + monetize_default?: boolean; }; type Job = { @@ -596,6 +598,11 @@ export default function YtLongPage() { {ch.authorized ? "已授权" : "未授权"} + {Number(ch.ypp_ok) === 1 ? ( + YPP·默认获利 + ) : Number(ch.ypp_ok) === 0 ? ( + 非YPP + ) : null}