douyinWEB/scripts/_lookup_profile_emails.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

146 lines
5.9 KiB
Python

# -*- coding: utf-8 -*-
"""Resolve Gmail for OAuth profiles A/B/C via token userinfo / channel meta."""
from __future__ import annotations
import sys
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
SCRIPT = r"""
import json, sqlite3, urllib.request, urllib.parse, urllib.error
from app import db
db.init_db()
cfg = db.get_settings_map()
raw_p = cfg.get('shorts_oauth_profiles') or []
profiles = raw_p if isinstance(raw_p, list) else json.loads(raw_p or '[]')
conn = sqlite3.connect('/opt/douyinWEB/backend/data/monitor.db')
conn.row_factory = sqlite3.Row
def refresh_access(client_id, client_secret, refresh_token):
data = urllib.parse.urlencode({
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
}).encode()
req = urllib.request.Request('https://oauth2.googleapis.com/token', data=data, method='POST')
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
def userinfo(access_token):
req = urllib.request.Request(
'https://www.googleapis.com/oauth2/v2/userinfo',
headers={'Authorization': f'Bearer {access_token}'},
)
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
def tokeninfo(access_token):
url = 'https://oauth2.googleapis.com/tokeninfo?' + urllib.parse.urlencode({'access_token': access_token})
with urllib.request.urlopen(url, timeout=30) as resp:
return json.loads(resp.read().decode())
# YouTube Data API channels.list mine=true → not email but channel
def yt_mine(access_token):
url = 'https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails&mine=true'
req = urllib.request.Request(url, headers={'Authorization': f'Bearer {access_token}'})
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode())
hints = cfg.get('shorts_oauth_brand_hints')
print('BRAND_HINTS', json.dumps(hints, ensure_ascii=False)[:500] if not isinstance(hints, str) else hints[:500])
for p in profiles:
pid = str(p.get('id') or '').upper()
cid = str(p.get('client_id') or '')
sec = str(p.get('client_secret') or '')
print('='*50)
print('PROFILE', pid, 'label', p.get('label'), 'client', cid[:32]+'...')
rows = conn.execute(
"SELECT id,name,youtube_channel_id,client_id,client_secret,refresh_token,oauth_ok,yt_profile_json "
"FROM shorts_channels WHERE upper(coalesce(oauth_profile_id,''))=? AND length(coalesce(refresh_token,''))>10 "
"ORDER BY oauth_ok DESC, updated_at DESC",
(pid,),
).fetchall()
print('channels_with_token', len(rows))
email_found = None
err_last = ''
for r in rows[:6]:
try:
meta = json.loads(r['yt_profile_json'] or '{}') if r['yt_profile_json'] else {}
except Exception:
meta = {}
if isinstance(meta, dict):
for k in ('email','account_email','google_email'):
if meta.get(k):
print('CACHED_META', r['name'], k, meta.get(k))
email_found = meta.get(k)
for use_cid, use_sec, src in [
(cid, sec, 'profile'),
(str(r['client_id'] or cid), str(r['client_secret'] or sec), 'channel'),
]:
try:
tok = refresh_access(use_cid, use_sec, r['refresh_token'])
at = tok.get('access_token') or ''
if not at:
err_last = f'no access_token via {src}: {tok}'
continue
try:
ti = tokeninfo(at)
print('TOKENINFO', r['name'], 'via', src, 'email=', ti.get('email'), 'sub=', ti.get('sub'), 'scope=', (ti.get('scope') or '')[:100])
if ti.get('email'):
email_found = ti.get('email')
except Exception as exc:
print('tokeninfo_fail', r['name'], str(exc)[:120])
try:
ui = userinfo(at)
print('USERINFO', r['name'], 'via', src, ui)
if ui.get('email'):
email_found = ui.get('email')
except Exception as exc:
body=''
if isinstance(exc, urllib.error.HTTPError):
body = exc.read().decode('utf-8','replace')[:160]
print('userinfo_fail', r['name'], str(exc)[:80], body)
try:
yt = yt_mine(at)
items = yt.get('items') or []
titles = [(it.get('id'), (it.get('snippet') or {}).get('title'), (it.get('snippet') or {}).get('customUrl')) for it in items]
print('YT_MINE', r['name'], titles[:3])
except Exception as exc:
print('yt_mine_fail', r['name'], str(exc)[:100])
if email_found:
break
except Exception as exc:
err_last = f'{src}/{r["name"]}: {exc}'
if isinstance(exc, urllib.error.HTTPError):
err_last += ' ' + exc.read().decode('utf-8','replace')[:200]
if email_found:
break
print('RESULT', pid, email_found or f'(not found) last_err={err_last[:220]}')
print('='*50)
print('DONE')
conn.close()
"""
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=60, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
with sftp.file("/tmp/_profile_emails.py", "w") as f:
f.write(SCRIPT)
sftp.close()
_, o, e = c.exec_command(
"cd /opt/douyinWEB/backend && PYTHONPATH=. .venv/bin/python /tmp/_profile_emails.py 2>&1",
timeout=180,
)
print(o.read().decode("utf-8", "replace"))
err = e.read().decode("utf-8", "replace")
if err.strip():
print(err[-800:])
c.close()