# -*- coding: utf-8 -*- """Sync cookie, deploy time-slot fix, restart API, kick current winner via HTTP.""" from __future__ import annotations import sys from pathlib import Path import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") ROOT = Path(__file__).resolve().parents[1] FILES = [ "backend/app/youtube_neko.py", "backend/app/youtube_relay_pipeline.py", ] 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=60, allow_agent=False, look_for_keys=False) return c def run(c: paramiko.SSHClient, cmd: str, timeout: int = 300) -> tuple[int, 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() text = out + (("\n" + err) if err.strip() else "") return code, text def main() -> int: print("1) cookie from ypp") ypp = ssh("192.227.152.110", "Leaf448772566") code, raw = run( ypp, "cd /opt/douyinWEB/backend && PYTHONPATH=. .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, ) ypp.close() lines = raw.strip().splitlines() cookie = "" if lines and lines[0].strip().isdigit() and int(lines[0].strip()) > 20: cookie = "\n".join(lines[1:]).strip() print("ypp_cookie_len", len(cookie)) print("2) upload + apply on dy") dy = ssh("108.174.50.68", "Xiao4669805") sftp = dy.open_sftp() for rel in FILES: sftp.put(str(ROOT / rel), f"/opt/douyinWEB/{rel}") print("uploaded", rel) with sftp.file("/tmp/dy_cookie_payload.txt", "w") as f: f.write(cookie) sftp.close() remote = r""" set -e cd /opt/douyinWEB/backend PYTHONPATH=. .venv/bin/python <<'PY' from pathlib import Path import time from app import db, youtube_relay_db, yt_assign_db from app.youtube_relay_pipeline import _group_in_active_slot db.init_db() cookie = Path('/tmp/dy_cookie_payload.txt').read_text(encoding='utf-8', errors='replace').strip() if len(cookie) > 20: db.update_settings_map({'dy_cookie': cookie, 'dy_cookie_updated_at': time.time()}) print('cookie_set', len(cookie)) else: print('cookie_missing_payload', len(cookie)) db.update_settings_map({ 'youtube_relay_time_slot_mode': True, 'youtube_relay_enabled': True, 'youtube_relay_exclusive_live': True, 'youtube_relay_respect_schedule': True, }) 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', recent_log=['[relay] reset outside_slot'], ffmpeg_pid=0, ) print('IDLE', g.get('name')) from app import youtube_neko assert hasattr(youtube_neko, 'stop_instance') print('code_ok') PY rm -f /tmp/dy_cookie_payload.txt systemctl restart douyinweb-api sleep 5 systemctl is-active douyinweb-api # Kick via authenticated local API (into the running worker process) PYTHONPATH=. .venv/bin/python <<'PY' import json, time, urllib.request from app.session_auth import create_session_token, get_admin_credentials, SESSION_COOKIE from app import db, yt_assign_db from app.youtube_relay_pipeline import _group_in_active_slot, pick_source_for_group db.init_db() user, _ = get_admin_credentials() token = create_session_token(user) def call(method, path, body=None, timeout=180): req = urllib.request.Request( f'http://127.0.0.1:8014{path}', data=(json.dumps(body).encode() if body is not None else None), method=method, headers={'Cookie': f'{SESSION_COOKIE}={token}', 'Content-Type': 'application/json'}, ) with urllib.request.urlopen(req, timeout=timeout) as resp: return json.loads(resp.read().decode()) st = call('POST', '/api/youtube/relay/start') print('relay_start_enabled', st.get('enabled'), 'running', st.get('running')) winner = None for g in yt_assign_db.list_groups(include_urls=True, include_secret=True): gid = str(g.get('id') or '') if g.get('enabled') and (g.get('has_stream_key') or str(g.get('stream_key') or '').strip()): if _group_in_active_slot(gid, keyed_only=True): winner = g break if not winner: print('NO_WINNER') else: print('kick_group', winner.get('name'), winner.get('id')) # force start current slot group r = call('POST', f"/api/youtube/relay/groups/{winner['id']}/start") print('group_start', {k: r.get(k) for k in ('ok','waiting','error','note','ffmpeg_pid','status') if k in r or True}) # slim print print('group_start_keys', list(r.keys())[:20]) print('group_start_status', r.get('status') or (r.get('state') or {}).get('status'), 'err', str(r.get('error') or r.get('note') or '')[:200]) time.sleep(12) st2 = call('GET', '/api/youtube/relay/status') print('after_enabled', st2.get('enabled'), 'running', st2.get('running')) rows = st2.get('groups') or st2.get('lanes') or [] if isinstance(rows, list): for row in rows: name = row.get('name') or row.get('group_name') print('ROW', name, 'biz', row.get('business_status') or row.get('status'), 'neko', (row.get('neko') or {}).get('running'), 'err', str(row.get('error') or '')[:120]) else: print('status_keys', list(st2.keys())[:30]) PY """ code, out = run(dy, remote, 420) print(out[-8000:] if len(out) > 8000 else out) print("exit", code) dy.close() return code if __name__ == "__main__": raise SystemExit(main())