douyinWEB/scripts/_fix_featured_kick_relay.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

152 lines
5.8 KiB
Python

# -*- coding: utf-8 -*-
"""Promote pool→featured for keyed groups, deploy pipeline fix, kick EvanVlogs."""
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]
CMD = r"""
set -e
while IFS= read -r line; do
[ -n "$line" ] || continue
export "$line"
done < <(systemctl show douyinweb-api -p Environment --value | tr ' ' '\n')
cd /opt/douyinWEB/backend
.venv/bin/python <<'PY'
from app import db, yt_assign_db
db.init_db()
# Promote each group's pool URLs into featured when featured empty (needed for non-slot mode / diagnostics).
for g in yt_assign_db.list_groups(include_urls=True, include_secret=False):
feat = g.get('featured') or []
pool = g.get('pool') or []
if feat or not pool:
continue
if not g.get('has_stream_key'):
continue
pids = [str(x.get('id') or x.get('pool_url_id') or '') for x in pool]
pids = [p for p in pids if p]
if not pids:
continue
try:
r = yt_assign_db.add_featured(str(g['id']), pids)
print('featured_ok', g.get('name'), len(pids), 'now', len((r.get('group') or {}).get('featured') or []))
except Exception as e:
print('featured_fail', g.get('name'), e)
print('done_promote')
PY
systemctl restart douyinweb-api
sleep 8
systemctl is-active douyinweb-api
.venv/bin/python <<'PY'
import json, time, urllib.request, urllib.error, subprocess
from app import db, yt_assign_db, youtube_relay_db, youtube_neko
from app.youtube_relay_pipeline import _group_in_active_slot, pick_source_for_group, _time_slot_mode
from app.session_auth import create_session_token, get_admin_credentials, SESSION_COOKIE, ensure_default_admin_credentials, hash_password
from app.config import settings
db.init_db()
ensure_default_admin_credentials()
db.update_settings_map({
'admin_username': str(settings.admin_username or 'hackrobot'),
'admin_password_hash': hash_password(str(settings.admin_password or '')),
'youtube_relay_time_slot_mode': True,
'youtube_relay_enabled': True,
'youtube_relay_exclusive_live': True,
})
print('cookie', len(str(db.get_settings_map().get('dy_cookie') or '')), 'slot', _time_slot_mode())
live = db.list_live_douyin_rooms_for_shorts(limit=40)
print('live', len(live))
for r in live[:8]:
print('L', r.get('room_id'), (r.get('last_anchor') or r.get('anchor_name') or '')[:24], (r.get('url') or '')[:50])
user, _ = get_admin_credentials()
token = create_session_token(user)
port = 8014
def call(method, path, body=None, timeout=300):
data = None if body is None else json.dumps(body).encode()
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 json.loads(resp.read().decode())
except urllib.error.HTTPError as e:
print('HTTP', e.code, path, e.read().decode('utf-8', 'replace')[:500])
raise
st = call('POST', '/api/youtube/relay/start')
print('relay', st.get('enabled'), st.get('running'))
winner = None
for g in yt_assign_db.list_groups(include_urls=True, 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'), 'feat', len((winner or {}).get('featured') or []), 'neko', (winner or {}).get('neko_instance_id'))
if winner:
src = pick_source_for_group(winner, respect_schedule=True)
print('pick', src)
keep = int(winner.get('neko_instance_id') or 0)
for g in yt_assign_db.list_groups(include_urls=False, include_secret=False):
if str(g.get('id')) == str(winner.get('id')):
continue
if not g.get('has_stream_key'):
continue
nid = int(g.get('neko_instance_id') or 0)
if nid > 0:
print('stop', nid, g.get('name'), youtube_neko.stop_instance(nid))
if keep:
print('start_neko', youtube_neko.ensure_instance_running(keep))
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', 'fatal', 'source_url')})
stt = youtube_relay_db.get_relay_state(str(winner['id'])) or {}
print('db', stt.get('status'), str(stt.get('error') or '')[:240])
for line in (stt.get('recent_log') or [])[-15:]:
print('LOG', line)
time.sleep(30)
st2 = call('GET', '/api/youtube/relay/status')
print('after', st2.get('running'))
for row in st2.get('groups') or []:
print('G', row.get('name'), 'biz', row.get('business_status'), 'st', row.get('status'),
'neko', ((row.get('neko') or {}).get('running')), 'err', str(row.get('error') or '')[:140])
print(subprocess.getoutput("ps aux | grep '[f]fmpeg' | grep -iE 'rtmp|a\\.rtmp|youtube' | head -8"))
print(subprocess.getoutput("docker ps --format '{{.Names}} {{.Status}}' | grep -i neko | head -15"))
PY
"""
def main() -> int:
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()
for rel in ("backend/app/youtube_relay_pipeline.py",):
sftp.put(str(ROOT / rel), f"/opt/douyinWEB/{rel}")
print("uploaded", rel)
sftp.close()
_, o, e = c.exec_command(CMD, timeout=480)
out = o.read().decode("utf-8", "replace")
err = e.read().decode("utf-8", "replace")
code = o.channel.recv_exit_status()
print(out[-14000:] if len(out) > 14000 else out)
if err.strip():
print("STDERR", err[-2500:])
print("exit", code)
c.close()
return code
if __name__ == "__main__":
raise SystemExit(main())