# -*- coding: utf-8 -*- """YouTube AdSense / Analytics monetary revenue — linked to Live / Shorts / 长视频. Uses YouTube Analytics API v2 estimatedRevenue metrics. Requires opt-in OAuth scopes (yt-analytics-monetary.readonly) — not part of default upload oauth_ok. """ from __future__ import annotations import time from datetime import date, datetime, timedelta, timezone from typing import Any import httpx from . import db from . import yt_assign_db from .shorts_oauth import channel_oauth_creds, monetary_scopes, token_scopes from .shorts_upload import refresh_access_token _ANALYTICS = "https://youtubeanalytics.googleapis.com/v2/reports" _CACHE: dict[str, tuple[float, dict[str, Any]]] = {} _CACHE_TTL_SEC = 900.0 # 15 min _CONTENT_MAP = { "LIVE_STREAM": "live", "SHORTS": "shorts", "VIDEO_ON_DEMAND": "long", # legacy / alternate labels "LIVE": "live", "ON_DEMAND": "long", } def _beijing_today() -> date: return datetime.now(timezone(timedelta(hours=8))).date() def _httpx_kwargs(*, timeout: float = 45.0) -> dict[str, Any]: try: from . import egress_hub return egress_hub.google_httpx_kwargs(timeout=timeout) except Exception: return {"timeout": timeout, "trust_env": False} def _parse_float(v: Any) -> float | None: try: if v is None or v == "": return None return float(v) except (TypeError, ValueError): return None def _empty_bucket() -> dict[str, Any]: return { "estimated_revenue": 0.0, "estimated_ad_revenue": 0.0, "gross_revenue": 0.0, "monetized_playbacks": 0.0, "ad_impressions": 0.0, "playback_based_cpm": None, } def _add_row(bucket: dict[str, Any], cols: dict[str, Any]) -> None: for k in ( "estimated_revenue", "estimated_ad_revenue", "gross_revenue", "monetized_playbacks", "ad_impressions", ): bucket[k] = float(bucket.get(k) or 0) + float(cols.get(k) or 0) cpm = cols.get("playback_based_cpm") if cpm is not None: bucket["playback_based_cpm"] = cpm async def _access_for_channel(channel_pk: str) -> tuple[str, dict[str, Any]]: ch = db.get_shorts_channel(channel_pk) if not ch: raise ValueError("频道不存在") creds = channel_oauth_creds(ch) if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]): raise ValueError("频道未授权 Google OAuth") token = await refresh_access_token( client_id=creds["client_id"], client_secret=creds["client_secret"], refresh_token=creds["refresh_token"], ) return token, ch async def channel_monetary_ready(channel_pk: str) -> dict[str, Any]: """Check whether this Shorts OAuth token has Analytics monetary scopes.""" try: token, ch = await _access_for_channel(channel_pk) except Exception as exc: return { "ok": False, "authorized": False, "monetary_ok": False, "error": str(exc)[:200], "missing_scopes": monetary_scopes(), } granted = await token_scopes(token) need = set(monetary_scopes()) missing = sorted(s for s in need if s not in granted) return { "ok": True, "authorized": True, "monetary_ok": not missing, "missing_scopes": missing, "channel_pk": channel_pk, "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), "name": str(ch.get("name") or ch.get("title") or ""), } async def _query_reports( access: str, *, start: str, end: str, metrics: str, dimensions: str = "", filters: str = "", ) -> dict[str, Any]: params: dict[str, str] = { "ids": "channel==MINE", "startDate": start, "endDate": end, "metrics": metrics, } if dimensions: params["dimensions"] = dimensions if filters: params["filters"] = filters async with httpx.AsyncClient(**_httpx_kwargs()) as client: resp = await client.get( _ANALYTICS, params=params, headers={"Authorization": f"Bearer {access}"}, ) data = resp.json() if resp.content else {} if resp.status_code >= 400: err = data.get("error") if isinstance(data, dict) else None msg = "" if isinstance(err, dict): msg = str(err.get("message") or err) raise RuntimeError(msg or f"analytics HTTP {resp.status_code}: {str(data)[:240]}") return data if isinstance(data, dict) else {} def _rows_as_dicts(report: dict[str, Any]) -> list[dict[str, Any]]: headers = [str(h.get("name") or "") for h in (report.get("columnHeaders") or []) if isinstance(h, dict)] out: list[dict[str, Any]] = [] for row in report.get("rows") or []: if not isinstance(row, (list, tuple)): continue item: dict[str, Any] = {} for i, name in enumerate(headers): if i >= len(row): break item[name] = row[i] out.append(item) return out def _metric_cols(row: dict[str, Any]) -> dict[str, Any]: return { "estimated_revenue": _parse_float(row.get("estimatedRevenue")) or 0.0, "estimated_ad_revenue": _parse_float(row.get("estimatedAdRevenue")) or 0.0, "gross_revenue": _parse_float(row.get("grossRevenue")) or 0.0, "monetized_playbacks": _parse_float(row.get("monetizedPlaybacks")) or 0.0, "ad_impressions": _parse_float(row.get("adImpressions")) or 0.0, "playback_based_cpm": _parse_float(row.get("playbackBasedCpm")), } _METRICS = ( "estimatedRevenue,estimatedAdRevenue,grossRevenue," "monetizedPlaybacks,adImpressions,playbackBasedCpm" ) async def fetch_channel_revenue( channel_pk: str, *, days: int = 28, force: bool = False, ) -> dict[str, Any]: """Pull AdSense-linked YouTube Analytics revenue for one OAuth channel.""" days_i = max(1, min(90, int(days or 28))) cache_key = f"{channel_pk}:{days_i}" now = time.time() if not force: hit = _CACHE.get(cache_key) if hit and (now - float(hit[0])) < _CACHE_TTL_SEC: return dict(hit[1]) ready = await channel_monetary_ready(channel_pk) if not ready.get("authorized"): out = { "ok": False, "channel_pk": channel_pk, "error": ready.get("error") or "未授权", "monetary_ok": False, "need_reauth": True, } return out if not ready.get("monetary_ok"): out = { "ok": False, "channel_pk": channel_pk, "name": ready.get("name"), "youtube_channel_id": ready.get("youtube_channel_id"), "error": "缺少 YouTube Analytics 收益权限,请在本页点击「授权收益」", "monetary_ok": False, "need_reauth": True, "missing_scopes": ready.get("missing_scopes") or [], } return out token, ch = await _access_for_channel(channel_pk) end = _beijing_today() start = end - timedelta(days=days_i - 1) start_s, end_s = start.isoformat(), end.isoformat() by_type = { "live": _empty_bucket(), "shorts": _empty_bucket(), "long": _empty_bucket(), "other": _empty_bucket(), } daily: list[dict[str, Any]] = [] totals = _empty_bucket() type_error = "" try: total_report = await _query_reports( token, start=start_s, end=end_s, metrics=_METRICS, dimensions="day" ) for row in _rows_as_dicts(total_report): cols = _metric_cols(row) _add_row(totals, cols) daily.append({"day": str(row.get("day") or ""), **cols}) except Exception as exc: return { "ok": False, "channel_pk": channel_pk, "name": str(ch.get("name") or ""), "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), "error": str(exc)[:300], "monetary_ok": True, "need_reauth": "insufficient" in str(exc).lower() or "scope" in str(exc).lower(), } try: type_report = await _query_reports( token, start=start_s, end=end_s, metrics=_METRICS, dimensions="creatorContentType", ) for row in _rows_as_dicts(type_report): raw = str(row.get("creatorContentType") or "").strip().upper() key = _CONTENT_MAP.get(raw, "other") _add_row(by_type[key], _metric_cols(row)) except Exception as exc: # Some channels/API versions lack creatorContentType — keep totals, note gap. type_error = str(exc)[:240] # Fallback: liveOrOnDemand if available try: lod = await _query_reports( token, start=start_s, end=end_s, metrics=_METRICS, dimensions="liveOrOnDemand", ) for row in _rows_as_dicts(lod): raw = str(row.get("liveOrOnDemand") or "").strip().upper() key = "live" if raw == "LIVE" else "long" _add_row(by_type[key], _metric_cols(row)) type_error = "" except Exception as exc2: type_error = f"{type_error}; fallback: {exc2}"[:300] links = _product_links( youtube_channel_id=str(ch.get("youtube_channel_id") or ""), shorts_pk=channel_pk, ) out: dict[str, Any] = { "ok": True, "channel_pk": channel_pk, "name": str(ch.get("name") or ch.get("title") or ""), "youtube_channel_id": str(ch.get("youtube_channel_id") or ""), "oauth_profile_id": str(ch.get("oauth_profile_id") or ""), "currency": "USD", "window": {"start": start_s, "end": end_s, "days": days_i}, "totals": totals, "by_type": by_type, "daily": daily, "links": links, "type_error": type_error, "monetary_ok": True, "need_reauth": False, "fetched_at": now, } _CACHE[cache_key] = (now, out) return out def _product_links(*, youtube_channel_id: str, shorts_pk: str) -> dict[str, Any]: """Map UC… / Shorts pk → Live 分配 / Shorts / 长视频 cards.""" ucid = str(youtube_channel_id or "").strip() live_groups: list[dict[str, Any]] = [] long_channels: list[dict[str, Any]] = [] try: for g in yt_assign_db.list_groups(include_urls=False): gid = str(g.get("id") or "") g_uc = str(g.get("youtube_channel_id") or "").strip() g_pk = str(g.get("channel_pk") or "").strip() if (ucid and g_uc == ucid) or (shorts_pk and g_pk == shorts_pk): live_groups.append( { "group_id": gid, "name": str(g.get("name") or ""), "youtube_channel_id": g_uc, "href": f"/youtube?live=1&focus={gid}" if gid else "/youtube", } ) except Exception: pass try: from . import yt_long_db for c in yt_long_db.list_yt_long_channels(): c_uc = str(c.get("youtube_channel_id") or "").strip() src = str(c.get("source_shorts_channel_pk") or "").strip() if (ucid and c_uc == ucid) or (shorts_pk and src == shorts_pk): long_channels.append( { "id": str(c.get("id") or ""), "name": str(c.get("name") or ""), "youtube_channel_id": c_uc, "href": "/yt-long", } ) except Exception: pass return { "live": live_groups, "shorts": { "channel_pk": shorts_pk, "href": f"/shorts?focus={shorts_pk}" if shorts_pk else "/shorts", }, "long": long_channels, } async def fleet_revenue(*, days: int = 28, force: bool = False) -> dict[str, Any]: """Aggregate revenue across all authorized Shorts channels.""" days_i = max(1, min(90, int(days or 28))) channels = db.list_shorts_channels() rows: list[dict[str, Any]] = [] fleet_totals = _empty_bucket() fleet_by_type = { "live": _empty_bucket(), "shorts": _empty_bucket(), "long": _empty_bucket(), "other": _empty_bucket(), } need_reauth = 0 ok_n = 0 for ch in channels: pk = str(ch.get("id") or "").strip() if not pk: continue if not str(ch.get("refresh_token") or "").strip(): continue try: one = await fetch_channel_revenue(pk, days=days_i, force=force) except Exception as exc: one = {"ok": False, "channel_pk": pk, "error": str(exc)[:200], "need_reauth": True} rows.append(one) if one.get("need_reauth"): need_reauth += 1 if not one.get("ok"): continue ok_n += 1 _add_row(fleet_totals, one.get("totals") or {}) bt = one.get("by_type") or {} for k in ("live", "shorts", "long", "other"): _add_row(fleet_by_type[k], bt.get(k) or {}) end = _beijing_today() start = end - timedelta(days=days_i - 1) return { "ok": True, "window": {"start": start.isoformat(), "end": end.isoformat(), "days": days_i}, "currency": "USD", "totals": fleet_totals, "by_type": fleet_by_type, "channels": rows, "ok_count": ok_n, "need_reauth_count": need_reauth, "fetched_at": time.time(), }