# -*- coding: utf-8 -*- """Enable YouTube long-form ad monetization for YPP-eligible channels. Detects YPP via Data API channels.status.isChannelMonetizationEnabled, falling back to the cached yt_long_channels.ypp_ok flag. After upload, turns on "Monetize with ads" via YouTube Studio innertube (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 asyncio import time from typing import Any import httpx from .shorts_upload import _client_kwargs, refresh_access_token _STUDIO_KEY = "AIzaSyBUPetSUmoZL-OhlxA7ZlfWJRJKBa7VFkE" _STUDIO_ORIGIN = "https://studio.youtube.com" _STUDIO_URL = f"{_STUDIO_ORIGIN}/youtubei/v1/video_manager/metadata_update?alt=json&key={_STUDIO_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", ] def _self_cert_skipped() -> dict[str, Any]: """Match youtube-studio library — skip altered-content questionnaire.""" return { "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", } } def _self_cert_no() -> dict[str, Any]: """Answer altered-content quiz as all-No.""" return { "newSelfCertificationData": { "questionnaireAnswers": [ {"question": q, "answer": 2} for q in _CERT_QUESTIONS ], "certificationMethod": 1, "questionnaireVersion": 8, } } def _self_cert_no_legacy() -> dict[str, Any]: return { "newSelfCertificationData": { "questionnaireAnswers": [ {"question": q, "answer": "VIDEO_SELF_CERTIFICATION_ANSWER_NO"} for q in _CERT_QUESTIONS ], "certificationMethod": "VIDEO_SELF_CERTIFICATION_METHOD_DEFAULT_NONE", "questionnaireVersion": "VIDEO_SELF_CERTIFICATION_QUESTIONNAIRE_VERSION_8", } } def _self_cert_none_above() -> dict[str, Any]: return { "newSelfCertificationData": { "questionnaireAnswers": [], "noneOfTheAboveSelected": True, "certificationMethod": 1, "questionnaireVersion": 8, } } def _context(*, channel_id: str = "", client_name: Any = "WEB_CREATOR") -> dict[str, Any]: ctx: dict[str, Any] = { "client": { "clientName": client_name, "clientVersion": "1.20250218.01.00", "hl": "en", "gl": "US", "utcOffsetMinutes": 0, } } if client_name == 62 or client_name == "62": ctx["client"].update( { "osName": "Android", "androidSdkVersion": 33, "deviceMake": "Google", "deviceModel": "Pixel 6 Pro", } ) ch = str(channel_id or "").strip() if ch: ctx["user"] = { "delegationContext": { "externalChannelId": ch, "roleType": {"channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"}, } } return ctx 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, } def _studio_headers(access_token: str) -> dict[str, str]: return { "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" ), } async def _post_studio( *, access_token: str, body: dict[str, Any], proxy_url: str = "", ) -> dict[str, Any]: try: async with httpx.AsyncClient(**_client_kwargs(timeout=60.0, proxy_url=proxy_url)) as client: resp = await client.post(_STUDIO_URL, headers=_studio_headers(access_token), 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, "raw_keys": list(data.keys())[:12] if isinstance(data, dict) else []} except Exception as exc: return {"ok": False, "error": str(exc)[:400]} async def verify_video_monetized( *, access_token: str, video_id: str, proxy_url: str = "", ) -> dict[str, Any]: """Best-effort check via Data API monetizationDetails.""" vid = str(video_id or "").strip() if not vid: return {"ok": False, "monetized": False} try: 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/videos", params={"part": "monetizationDetails,status", "id": vid}, headers={"Authorization": f"Bearer {access_token}"}, ) data = resp.json() if resp.content else {} if resp.status_code >= 400: return {"ok": False, "monetized": False, "error": str(resp.text[:200])} items = data.get("items") or [] if not items: return {"ok": False, "monetized": False, "error": "no_video"} md = items[0].get("monetizationDetails") or {} enabled = bool(md.get("access") and str(md.get("access")).lower() != "blocked") return {"ok": True, "monetized": enabled, "details": md} except Exception as exc: return {"ok": False, "monetized": False, "error": str(exc)[:200]} async def enable_video_monetize_with_ads( *, access_token: str, video_id: str, youtube_channel_id: str = "", proxy_url: str = "", ) -> dict[str, Any]: """Turn on 'Monetize with ads'. Retries a few Studio payload shapes.""" vid = str(video_id or "").strip() if not vid: return {"ok": False, "error": "no_video_id"} ch = str(youtube_channel_id or "").strip() base = {"encryptedVideoId": vid, "videoReadMask": {"title": True}} cert_top = _self_cert_no().get("newSelfCertificationData") payloads: list[dict[str, Any]] = [ {**base, "monetizationSettings": {"newMonetizeWithAds": True}, "context": _context(channel_id=ch, client_name="WEB_CREATOR")}, {**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}, "newSelfCertificationData": cert_top, "context": _context(channel_id=ch, client_name="WEB_CREATOR"), }, { **base, "monetizationSettings": {"newMonetizeWithAds": True}, "selfCertification": _self_cert_none_above(), "context": _context(channel_id=ch, client_name="WEB_CREATOR"), }, { **base, "monetizationSettings": {"newMonetizeWithAds": True}, "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: last = await _post_studio(access_token=access_token, body=body, proxy_url=proxy_url) if last.get("ok"): return last err = str(last.get("error") or "").lower() if "insufficient" in err and "scope" in err: last["error"] = "授权范围不够,请到 Shorts 页重新授权该频道后再传" return last if "self_certification" in err or "selfcertification" in err: continue return last 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]: """YPP channels always get ads enabled. Cached ypp_ok=1 counts even if live probe is flaky.""" 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) live_ypp = bool(ypp_info.get("ypp")) cached = 0 try: cached = int((channel_row or {}).get("ypp_ok") if (channel_row or {}).get("ypp_ok") is not None else -1) except Exception: cached = -1 row_yt = str((channel_row or {}).get("youtube_channel_id") or "").strip() probe_yt = str(ypp_info.get("channel_id") or "").strip() mismatch = bool(ypp_info.get("ok") and row_yt and probe_yt and row_yt != probe_yt) ypp = live_ypp if mismatch: # mine=true hit a different brand channel — trust local YPP cache ypp = cached == 1 or live_ypp elif not ypp_info.get("ok") and cached == 1: ypp = True elif cached == 1: ypp = True out["ypp"] = ypp out["ypp_probe"] = {k: ypp_info.get(k) for k in ("ok", "channel_id", "error")} yt_ch = row_yt or probe_yt cid = str((channel_row or {}).get("id") or "") if cid and ypp_info.get("ok") and not mismatch: try: yt_long_db.update_yt_long_channel( cid, ypp_ok=1 if live_ypp else 0, ypp_checked_at=time.time(), youtube_channel_id=yt_ch or row_yt, ) except Exception: 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 # Video id is registered before processing finishes; a short wait avoids invalid argument. await asyncio.sleep(4) mon = await enable_video_monetize_with_ads( access_token=access, video_id=video_id, youtube_channel_id=yt_ch, proxy_url=proxy_url, ) if not mon.get("ok"): await asyncio.sleep(8) 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 mon.get("ok"): verify = await verify_video_monetized(access_token=access, video_id=video_id, proxy_url=proxy_url) out["monetize_verified"] = bool(verify.get("monetized")) if verify.get("monetized"): out["monetized"] = True 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}