fix(yt-long): always enable ads on YPP uploads and show Chinese monetize result
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
052c49714f
commit
b08b66724d
@ -19,11 +19,12 @@ from . import db
|
||||
|
||||
YOUTUBE_SCOPES = " ".join(
|
||||
[
|
||||
# Minimal set for Shorts upload + channel identity.
|
||||
# Avoid youtubepartner / yt-analytics here — they often break
|
||||
# Upload + identity + Studio monetize (force-ssl).
|
||||
# Avoid youtubepartner / yt-analytics — they often break
|
||||
# unverified OAuth consent (Google 500 / access_denied).
|
||||
"https://www.googleapis.com/auth/youtube.upload",
|
||||
"https://www.googleapis.com/auth/youtube.readonly",
|
||||
"https://www.googleapis.com/auth/youtube.force-ssl",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@ -1,14 +1,17 @@
|
||||
# -*- 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).
|
||||
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
|
||||
|
||||
@ -16,32 +19,30 @@ 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"
|
||||
_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_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",
|
||||
]
|
||||
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_SKIPPED",
|
||||
}
|
||||
for q in qs
|
||||
{"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",
|
||||
@ -49,6 +50,27 @@ def _self_cert_payload() -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
@ -80,42 +102,8 @@ async def fetch_channel_ypp_status(
|
||||
}
|
||||
|
||||
|
||||
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 = {
|
||||
def _studio_headers(access_token: str) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Content-Type": "application/json",
|
||||
"x-origin": _STUDIO_ORIGIN,
|
||||
@ -126,9 +114,17 @@ async def enable_video_monetize_with_ads(
|
||||
"(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(url, headers=headers, json=body)
|
||||
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 = (
|
||||
@ -137,12 +133,58 @@ async def enable_video_monetize_with_ads(
|
||||
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 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,
|
||||
@ -153,11 +195,7 @@ async def ensure_ypp_and_monetize(
|
||||
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.
|
||||
"""
|
||||
"""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": ""}
|
||||
@ -173,45 +211,62 @@ async def ensure_ypp_and_monetize(
|
||||
return out
|
||||
|
||||
ypp_info = await fetch_channel_ypp_status(access_token=access, proxy_url=proxy_url)
|
||||
ypp = bool(ypp_info.get("ypp"))
|
||||
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 = str(ypp_info.get("channel_id") or (channel_row or {}).get("youtube_channel_id") or "")
|
||||
yt_ch = row_yt or probe_yt
|
||||
|
||||
cid = str((channel_row or {}).get("id") or "")
|
||||
if cid:
|
||||
if cid and ypp_info.get("ok") and not mismatch:
|
||||
try:
|
||||
yt_long_db.update_yt_long_channel(
|
||||
cid,
|
||||
ypp_ok=1 if ypp else 0,
|
||||
ypp_ok=1 if live_ypp else 0,
|
||||
ypp_checked_at=time.time(),
|
||||
youtube_channel_id=yt_ch or str((channel_row or {}).get("youtube_channel_id") or ""),
|
||||
youtube_channel_id=yt_ch or row_yt,
|
||||
)
|
||||
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
|
||||
|
||||
want = ypp if force_monetize is None else bool(force_monetize)
|
||||
if not want:
|
||||
out["skipped"] = "not_ypp" if not ypp else "monetize_default_off"
|
||||
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]
|
||||
|
||||
@ -853,13 +853,17 @@ class YtLongPipeline:
|
||||
proxy_url=proxy,
|
||||
)
|
||||
if mon.get("monetized"):
|
||||
monetize_note = "ypp_monetize_on"
|
||||
elif mon.get("skipped"):
|
||||
monetize_note = f"ypp_skip:{mon.get('skipped')}"
|
||||
monetize_note = "已开启广告获利"
|
||||
elif mon.get("skipped") == "not_ypp":
|
||||
monetize_note = "非YPP频道,未开广告"
|
||||
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]}"
|
||||
raw = str(mon.get("monetize_error") or mon.get("error") or "")[:160]
|
||||
if "授权范围" in raw or "insufficient" in raw.lower():
|
||||
monetize_note = "获利未开:授权范围不够,请到 Shorts 重新授权该频道"
|
||||
else:
|
||||
monetize_note = f"获利未开:{raw}"
|
||||
except Exception as exc:
|
||||
monetize_note = f"ypp_monetize_err:{str(exc)[:120]}"
|
||||
monetize_note = f"获利未开:{str(exc)[:120]}"
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="uploaded",
|
||||
|
||||
@ -127,7 +127,15 @@ function jobResultZh(job: {
|
||||
clip_path?: string;
|
||||
status?: string;
|
||||
}): { text: string; tone: "ok" | "warn" | "err" | "muted" } {
|
||||
if (job.youtube_url) return { text: "已上传 YouTube", tone: "ok" };
|
||||
if (job.youtube_url) {
|
||||
const note = String(job.error || "").trim();
|
||||
if (note.includes("已开启广告获利")) return { text: "已上传 · 已开广告获利", tone: "ok" };
|
||||
if (note.includes("非YPP")) return { text: "已上传 · 非YPP未开广告", tone: "muted" };
|
||||
if (note.includes("获利未开") || note.includes("ypp_monetize")) {
|
||||
return { text: note.replace(/^ypp_monetize_fail:/, "获利未开:").slice(0, 80), tone: "warn" };
|
||||
}
|
||||
return { text: "已上传 YouTube", tone: "ok" };
|
||||
}
|
||||
const err = String(job.error || "").trim();
|
||||
if (!err) {
|
||||
if (job.clip_ready || job.clip_path) return { text: "成片已好,等待上传", tone: "muted" };
|
||||
|
||||
Loading…
Reference in New Issue
Block a user