# -*- coding: utf-8 -*- """Copy dy_cookie from old VPS + local sh2; kick time-slot winner on dy.""" from __future__ import annotations import configparser import sys from pathlib import Path import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") LOCAL_INI = Path(r"C:\project\sh2\d2ypp2\config\config.ini") def read_local_cookie() -> str: if not LOCAL_INI.is_file(): return "" p = configparser.RawConfigParser() p.read(LOCAL_INI, encoding="utf-8") for sec in ("Cookie", "cookie"): if p.has_section(sec): for key in ("抖音cookie", "douyin_cookie", "dy_cookie"): try: v = (p.get(sec, key) or "").strip() if len(v) > 50: return v except Exception: continue return "" def ssh(host: str, password: str) -> paramiko.SSHClient: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(host, 22, "root", password, timeout=45, allow_agent=False, look_for_keys=False) return c def run(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> str: _, o, e = c.exec_command(cmd, timeout=timeout) out = o.read().decode("utf-8", "replace") err = e.read().decode("utf-8", "replace") code = o.channel.recv_exit_status() if code != 0: raise RuntimeError(f"exit={code}\n{out}\n{err}") return out def main() -> int: cookie = read_local_cookie() print("local_cookie", len(cookie)) if len(cookie) < 50: print("pull from old VPS…") old = ssh("107.173.30.245", "Xiao4669805") raw = run( old, "cd /opt/douyinWEB/backend && .venv/bin/python -c \"from app import db; db.init_db(); " "c=str(db.get_settings_map().get('dy_cookie') or ''); print(len(c)); print(c)\"", 60, ) old.close() lines = raw.strip().splitlines() if lines and lines[0].strip().isdigit() and int(lines[0]) > 50: cookie = "\n".join(lines[1:]).strip() print("old_cookie", len(cookie)) if len(cookie) < 50: print("FATAL no cookie") return 2 dy = ssh("108.174.50.68", "Xiao4669805") sftp = dy.open_sftp() with sftp.file("/tmp/dy_cookie_payload.txt", "w") as f: f.write(cookie) sftp.close() out = run( dy, r""" set -e cd /opt/douyinWEB/backend .venv/bin/python <<'PY' from pathlib import Path import time, json, urllib.request from app import db, youtube_relay_db, yt_assign_db, youtube_neko from app.youtube_relay_pipeline import _group_in_active_slot from app.session_auth import create_session_token, get_admin_credentials, SESSION_COOKIE, ensure_default_admin_credentials db.init_db() ensure_default_admin_credentials() cookie = Path('/tmp/dy_cookie_payload.txt').read_text(encoding='utf-8', errors='replace').strip() db.update_settings_map({ 'dy_cookie': cookie, 'dy_cookie_updated_at': time.time(), 'youtube_relay_time_slot_mode': True, 'youtube_relay_enabled': True, 'youtube_relay_exclusive_live': True, 'youtube_relay_respect_schedule': True, }) print('cookie_set', len(cookie)) for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): if not g.get('has_stream_key'): continue gid=str(g.get('id') or '') if _group_in_active_slot(gid, keyed_only=True): print('WINNER', g.get('name'), gid, 'neko', g.get('neko_instance_id')) else: youtube_relay_db.upsert_relay_state(gid, status='idle', error='非当前时段:已停推流并关闭 Neko', ffmpeg_pid=0, recent_log=['[relay] outside_slot']) neko=int(g.get('neko_instance_id') or 0) if neko>0: print('stop_neko', neko, youtube_neko.stop_instance(neko)) user print('IDLE', g.get('name')) PY rm -f /tmp/dy_cookie_payload.txt systemctl restart douyinweb-api sleep 6 systemctl is-active douyinweb-api ss -lntp | grep -E '8014|8000' || true cd /opt/douyinWEB/backend .venv/bin/python <<'PY' import json, time, urllib.request, urllib.error from app import db, yt_assign_db from app.youtube_relay_pipeline import _group_in_active_slot from app.session_auth import create_session_token, get_admin_credentials, SESSION_COOKIE, ensure_default_admin_credentials db.init_db() ensure_default_admin_credentials() user,_=get_admin_credentials() token=create_session_token(user) print('auth_user', user) # discover API port ports=[] for p in (8014,8000,8010,8080): try: urllib.request.urlopen(f'http://127.0.0.1:{p}/api/health', timeout=3) ports.append(p) except Exception: pass print('ports', ports) port = ports[0] if ports else 8014 def call(method, path, body=None, timeout=180): data=json.dumps(body).encode() if body is not None else None req=urllib.request.Request( f'http://127.0.0.1:{port}{path}', data=data, method=method, headers={'Cookie': f'{SESSION_COOKIE}={token}', 'Content-Type':'application/json'}, ) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.status, json.loads(resp.read().decode()) except urllib.error.HTTPError as e: body=e.read().decode('utf-8','replace')[:500] print('HTTP', e.code, path, body) raise code, st = call('POST', '/api/youtube/relay/start') print('start', code, 'enabled', st.get('enabled'), 'running', st.get('running')) winner=None for g in yt_assign_db.list_groups(include_urls=False, include_secret=False): if g.get('has_stream_key') and g.get('enabled') and _group_in_active_slot(str(g.get('id')), keyed_only=True): winner=g break print('winner', (winner or {}).get('name'), (winner or {}).get('id')) if winner: code, r = call('POST', f"/api/youtube/relay/groups/{winner['id']}/start") print('group_start', code, 'ok', r.get('ok'), 'waiting', r.get('waiting'), 'err', str(r.get('error') or r.get('note') or '')[:200], 'pid', r.get('ffmpeg_pid')) time.sleep(15) code, st2 = call('GET', '/api/youtube/relay/status') print('running', st2.get('running'), 'enabled', st2.get('enabled')) for row in st2.get('groups') or []: print('G', row.get('name'), 'biz', row.get('business_status'), 'status', row.get('status'), 'neko_run', ((row.get('neko') or {}).get('running')), 'err', str(row.get('error') or '')[:140]) PY """, 420, ) print(out[-7000:] if len(out) > 7000 else out) dy.close() return 0 if __name__ == "__main__": raise SystemExit(main())