douyinWEB/backend/app/yt_long_monetize.py
eric 1febe0869e 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 <cursoragent@cursor.com>
2026-08-20 12:55:25 -05:00

219 lines
7.8 KiB
Python

# -*- 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