# -*- coding: utf-8 -*- """YouTube Studio innertube auth via Google cookies (SAPISIDHASH). OAuth bearer tokens work for Data API upload but Studio metadata_update (set monetize / self-cert) requires browser session cookies + sessionInfo.token. """ from __future__ import annotations import hashlib import json import re import time from typing import Any import httpx from .shorts_upload import _client_kwargs _STUDIO_ORIGIN = "https://studio.youtube.com" _DEFAULT_KEY = "AIzaSyBUPetSUmoZL-OhlxA7ZlfWJRJKBa7VFkE" _UA = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" ) def sapisid_hash(sapisid: str, *, origin: str = _STUDIO_ORIGIN, ts: int | None = None) -> str: stamp = ts if ts is not None else int(time.time()) digest = hashlib.sha1(f"{stamp} {sapisid} {origin}".encode()).hexdigest() return f"{stamp}_{digest}" def _cookie_val(cookies: dict[str, Any], *keys: str) -> str: for k in keys: v = str(cookies.get(k) or cookies.get(k.lower()) or cookies.get(k.upper()) or "").strip() if v: return v return "" def cookie_header(cookies: dict[str, Any]) -> str: parts: list[str] = [] for key in ("SID", "HSID", "SSID", "APISID", "SAPISID", "LOGIN_INFO", "VISITOR_INFO1_LIVE"): val = _cookie_val(cookies, key) if val: parts.append(f"{key}={val}") return "; ".join(parts) def studio_headers(cookies: dict[str, Any]) -> dict[str, str]: sapisid = _cookie_val(cookies, "SAPISID", "sapisid") auth = f"SAPISIDHASH {sapisid_hash(sapisid)}" if sapisid else "" hdr = { "content-type": "application/json", "cookie": cookie_header(cookies), "x-origin": _STUDIO_ORIGIN, "origin": _STUDIO_ORIGIN, "referer": f"{_STUDIO_ORIGIN}/", "User-Agent": _UA, } if auth: hdr["authorization"] = auth visitor = _cookie_val(cookies, "VISITOR_INFO1_LIVE", "visitor_info1_live") if visitor: hdr["x-goog-visitor-id"] = visitor return hdr def parse_ytcfg_from_html(html: str) -> dict[str, Any]: out: dict[str, Any] = {} for pat in ( r"ytcfg\.set\s*\(\s*(\{.*?\})\s*\)\s*;", r"var\s+ytcfg\s*=\s*(\{.*?\});", ): m = re.search(pat, html, re.DOTALL) if not m: continue try: blob = json.loads(m.group(1)) if isinstance(blob, dict): out.update(blob) except Exception: pass for key in ("INNERTUBE_API_KEY", "DELEGATED_SESSION_ID", "CHANNEL_ID", "VISITOR_DATA", "XSRF_TOKEN"): if key in out: continue m = re.search(rf'"{key}"\s*:\s*"([^"]+)"', html) if m: out[key] = m.group(1) return out def studio_cookies_configured(cookies: dict[str, Any] | None) -> bool: if not cookies: return False need = ("SID", "HSID", "SSID", "APISID", "SAPISID") return all(_cookie_val(cookies, k) for k in need) def session_token_from_cookies(cookies: dict[str, Any]) -> str: return _cookie_val(cookies, "SESSION_TOKEN", "session_token", "sessionToken") async def fetch_studio_config( cookies: dict[str, Any], *, proxy_url: str = "", channel_url: str = "", ) -> dict[str, Any]: """Load studio.youtube.com and parse ytcfg (DELEGATED_SESSION_ID, etc.).""" if not studio_cookies_configured(cookies): return {"ok": False, "error": "studio_cookies_incomplete"} url = channel_url or f"{_STUDIO_ORIGIN}/channel/" try: async with httpx.AsyncClient(**_client_kwargs(timeout=45.0, proxy_url=proxy_url)) as client: resp = await client.get(url, headers=studio_headers(cookies), follow_redirects=True) html = resp.text or "" if resp.status_code >= 400: return {"ok": False, "error": f"studio_page_{resp.status_code}", "snippet": html[:200]} if "oops" in html.lower() and "something went wrong" in html.lower(): return {"ok": False, "error": "studio_page_error", "hint": "check LOGIN_INFO cookie"} cfg = parse_ytcfg_from_html(html) delegated = str(cfg.get("DELEGATED_SESSION_ID") or "").strip() channel_id = str(cfg.get("CHANNEL_ID") or "").strip() api_key = str(cfg.get("INNERTUBE_API_KEY") or _DEFAULT_KEY).strip() if not delegated: return {"ok": False, "error": "no_delegated_session_id", "keys": list(cfg.keys())[:12]} return { "ok": True, "delegated_session_id": delegated, "channel_id": channel_id, "innertube_api_key": api_key, "visitor_data": str(cfg.get("VISITOR_DATA") or "").strip(), } except Exception as exc: return {"ok": False, "error": str(exc)[:240]} def studio_cookies_for_profile(cfg: dict[str, Any], profile_id: str) -> dict[str, Any]: pid = str(profile_id or "").strip().upper() if not pid: return {} raw = cfg.get("yt_studio_cookies_by_profile") if not isinstance(raw, dict): return {} row = raw.get(pid) return dict(row) if isinstance(row, dict) else {} def merge_studio_cookies_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> dict[str, dict[str, str]]: from . import db as appdb settings = existing_cfg or appdb.get_settings_map() prev_raw = settings.get("yt_studio_cookies_by_profile") prev: dict[str, dict[str, str]] = dict(prev_raw) if isinstance(prev_raw, dict) else {} if not isinstance(incoming, dict): return prev keys = ("SID", "HSID", "SSID", "APISID", "SAPISID", "LOGIN_INFO", "SESSION_TOKEN", "VISITOR_INFO1_LIVE") out: dict[str, dict[str, str]] = dict(prev) for pid_raw, row in incoming.items(): pid = str(pid_raw or "").strip().upper() if not pid or not isinstance(row, dict): continue old = dict(out.get(pid) or {}) merged: dict[str, str] = {} for k in keys: v = str(row.get(k) or row.get(k.lower()) or "").strip() if (not v) or v.startswith("***"): v = str(old.get(k) or old.get(k.lower()) or "").strip() if v: merged[k] = v if merged: out[pid] = merged elif pid in out: del out[pid] return out def public_studio_cookies_by_profile(cfg: dict[str, Any]) -> dict[str, Any]: raw = cfg.get("yt_studio_cookies_by_profile") if not isinstance(raw, dict): return {} pub: dict[str, Any] = {} for pid_raw, row in raw.items(): pid = str(pid_raw or "").strip().upper() if not pid or not isinstance(row, dict): continue pub[pid] = { "configured": studio_cookies_configured(row), "has_session_token": bool(session_token_from_cookies(row)), "SID": ("***" + str(row.get("SID") or "")[-4:]) if str(row.get("SID") or "") else "", "SAPISID": ("***" + str(row.get("SAPISID") or "")[-4:]) if str(row.get("SAPISID") or "") else "", "SESSION_TOKEN": ("***" + str(row.get("SESSION_TOKEN") or "")[-6:]) if str(row.get("SESSION_TOKEN") or "") else "", } return pub def resolve_studio_profile_id(channel_row: dict[str, Any] | None) -> str: ch = channel_row or {} pid = str(ch.get("oauth_profile_id") or "").strip().upper() if pid: return pid src = str(ch.get("source_shorts_channel_pk") or "").strip() if src: try: from . import db as appdb sch = appdb.get_shorts_channel(src) or {} pid = str(sch.get("oauth_profile_id") or "").strip().upper() if pid: return pid except Exception: pass return "A" async def post_studio_monetize( *, cookies: dict[str, Any], video_id: str, youtube_channel_id: str, studio_cfg: dict[str, Any] | None = None, proxy_url: str = "", ) -> dict[str, Any]: """Enable monetize with ads using cookie session (adasq-compatible payload).""" vid = str(video_id or "").strip() ch = str(youtube_channel_id or "").strip() if not vid: return {"ok": False, "error": "no_video_id"} if not studio_cookies_configured(cookies): return {"ok": False, "error": "studio_cookies_incomplete"} cfg = studio_cfg or await fetch_studio_config( cookies, proxy_url=proxy_url, channel_url=f"{_STUDIO_ORIGIN}/channel/{ch}/videos" if ch else "", ) if not cfg.get("ok"): return {"ok": False, "error": str(cfg.get("error") or "studio_config_fail")[:240]} session_token = session_token_from_cookies(cookies) if not session_token: return {"ok": False, "error": "missing_session_token", "hint": "Studio 网络面板 metadata_update 里复制 sessionInfo.token"} delegated = str(cfg.get("delegated_session_id") or "").strip() api_key = str(cfg.get("innertube_api_key") or _DEFAULT_KEY).strip() url = f"{_STUDIO_ORIGIN}/youtubei/v1/video_manager/metadata_update?alt=json&key={api_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", ] body: dict[str, Any] = { "encryptedVideoId": vid, "videoReadMask": {}, "monetizationSettings": {"newMonetizeWithAds": True}, "adFormats": { "newHasOverlayAds": "ENABLED", "newHasProductListingAds": "ENABLED", "newHasSkippableVideoAds": "ENABLED", "newHasNonSkippableVideoAds": "ENABLED", }, "adBreaks": { "newHasPrerolls": "DISABLED", "newHasMidrollAds": "DISABLED", "newHasManualMidrolls": "DISABLED", "newHasPostrolls": "ENABLED", }, "selfCertification": { "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", } }, "context": { "client": { "clientName": 62, "clientVersion": "1.20210104.03.01", "hl": "en-GB", "gl": "US", "experimentsToken": "", "utcOffsetMinutes": 0, "osName": "Android", "androidSdkVersion": 33, "deviceMake": "Google", "deviceModel": "Pixel 6 Pro", }, "request": { "returnLogEntry": True, "internalExperimentFlags": [], "sessionInfo": {"token": session_token}, }, "user": { "onBehalfOfUser": delegated, "delegationContext": { "externalChannelId": ch, "roleType": {"channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"}, }, "serializedDelegationContext": "", }, "clientScreenNonce": "", }, } try: async with httpx.AsyncClient(**_client_kwargs(timeout=60.0, proxy_url=proxy_url)) as client: resp = await client.post(url, headers=studio_headers(cookies), 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, "auth": "studio_cookie"} except Exception as exc: return {"ok": False, "error": str(exc)[:400]}