douyinWEB/backend/app/yt_long_monetize.py
2026-08-21 22:29:17 -05:00

274 lines
9.5 KiB
Python

# -*- 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_no() -> dict[str, Any]:
"""Answer the altered-content quiz as all-No (street-food live is not that content)."""
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 _context(*, channel_id: str = "", client_name: Any = "WEB_CREATOR") -> dict[str, Any]:
ctx: dict[str, Any] = {
"client": {
"clientName": client_name,
"clientVersion": "1.20240724.01.00",
"hl": "en",
"gl": "US",
"utcOffsetMinutes": 0,
}
}
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 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()
payloads: list[dict[str, Any]] = [
{
"encryptedVideoId": vid,
"videoReadMask": {"title": True},
"monetizationSettings": {"newMonetizeWithAds": True},
"context": _context(channel_id="", client_name="WEB_CREATOR"),
},
{
"encryptedVideoId": vid,
"videoReadMask": {"title": True},
"monetizationSettings": {"newMonetizeWithAds": True},
"selfCertification": _self_cert_no(),
"context": _context(channel_id=ch, client_name="WEB_CREATOR"),
},
{
"encryptedVideoId": vid,
"videoReadMask": {},
"monetizationSettings": {"newMonetizeWithAds": True},
"selfCertification": _self_cert_no(),
"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()
# Scope problem will not be fixed by another payload.
if "insufficient" in err and "scope" in err:
last["error"] = "授权范围不够,请到 Shorts 页重新授权该频道后再传"
return last
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:
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 not mon.get("ok"):
out["monetize_error"] = str(mon.get("error") or "")[:300]
return out