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>
195 lines
6.9 KiB
Python
195 lines
6.9 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Push sh2 Douyin cookie to dy VPS and kick current time-slot winner."""
|
|
from __future__ import annotations
|
|
|
|
import configparser
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
INI = Path(r"C:\project\sh2\d2ypp2\config\config.ini")
|
|
FILES = [
|
|
"backend/app/youtube_neko.py",
|
|
"backend/app/youtube_relay_pipeline.py",
|
|
"backend/app/cookie_loader.py",
|
|
]
|
|
|
|
|
|
def load_cookie() -> str:
|
|
p = configparser.RawConfigParser()
|
|
p.read(INI, encoding="utf-8")
|
|
return (p.get("Cookie", "抖音cookie") or "").strip()
|
|
|
|
|
|
def main() -> int:
|
|
cookie = load_cookie()
|
|
print("sh2_cookie_len", len(cookie))
|
|
if len(cookie) < 50:
|
|
print("FATAL: local sh2 cookie empty")
|
|
return 2
|
|
|
|
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 FILES:
|
|
local = ROOT / rel
|
|
if local.exists():
|
|
sftp.put(str(local), f"/opt/douyinWEB/{rel}")
|
|
print("uploaded", rel)
|
|
# persist cookie file on VPS for bootstrap_cookie_into_db
|
|
try:
|
|
sftp.mkdir("/opt/douyinWEB/config")
|
|
except Exception:
|
|
pass
|
|
ini_body = "[Cookie]\n抖音cookie = " + cookie.replace("%", "%%") + "\n"
|
|
# RawConfigParser uses % interpolation - for file read by our loader we use RawConfigParser so %% wrong
|
|
# cookie_loader uses RawConfigParser — write literal cookie without doubling
|
|
ini_body = "[Cookie]\n抖音cookie = " + cookie + "\n"
|
|
with sftp.file("/opt/douyinWEB/config/douyin_cookie.ini", "w") as f:
|
|
f.write(ini_body)
|
|
with sftp.file("/tmp/dy_cookie_payload.txt", "w") as f:
|
|
f.write(cookie)
|
|
sftp.close()
|
|
print("cookie file uploaded")
|
|
|
|
cmd = r"""
|
|
set -e
|
|
cd /opt/douyinWEB/backend
|
|
.venv/bin/python <<'PY'
|
|
from pathlib import Path
|
|
import time
|
|
from app import db, youtube_relay_db, yt_assign_db, youtube_neko, cookie_loader
|
|
from app.youtube_relay_pipeline import _group_in_active_slot
|
|
from app.session_auth import 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('db_cookie', len(str(db.get_settings_map().get('dy_cookie') or '')))
|
|
# also verify loader path
|
|
print('bootstrap', cookie_loader.bootstrap_cookie_into_db())
|
|
|
|
winner=None
|
|
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):
|
|
winner=g
|
|
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 and hasattr(youtube_neko, 'stop_instance'):
|
|
print('stop', neko, youtube_neko.stop_instance(neko))
|
|
print('IDLE', g.get('name'))
|
|
print('winner_ok', bool(winner))
|
|
PY
|
|
rm -f /tmp/dy_cookie_payload.txt
|
|
systemctl restart douyinweb-api
|
|
sleep 6
|
|
systemctl is-active douyinweb-api
|
|
|
|
cd /opt/douyinWEB/backend
|
|
.venv/bin/python <<'PY'
|
|
import json, time, urllib.request, urllib.error
|
|
from app import db, yt_assign_db, youtube_relay_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()
|
|
user,_=get_admin_credentials()
|
|
token=create_session_token(user)
|
|
print('cookie_now', len(str(db.get_settings_map().get('dy_cookie') or '')))
|
|
|
|
# find API port
|
|
port=None
|
|
for p in (8014,8000,8010):
|
|
try:
|
|
urllib.request.urlopen(f'http://127.0.0.1:{p}/api/health', timeout=3).read()
|
|
port=p
|
|
break
|
|
except Exception as e:
|
|
print('port_fail', p, type(e).__name__)
|
|
print('api_port', port)
|
|
if not port:
|
|
raise SystemExit('no api port')
|
|
|
|
def call(method, path, body=None, timeout=240):
|
|
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 resp.status, json.loads(resp.read().decode())
|
|
except urllib.error.HTTPError as e:
|
|
print('HTTP', e.code, path, e.read().decode('utf-8','replace')[:400])
|
|
raise
|
|
|
|
_, st = call('POST', '/api/youtube/relay/start')
|
|
print('relay', '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('kick', (winner or {}).get('name'), (winner or {}).get('id'), 'neko', (winner or {}).get('neko_instance_id'))
|
|
if winner:
|
|
keep=int(winner.get('neko_instance_id') or 0)
|
|
if keep:
|
|
print('neko_except', youtube_neko.stop_instances_except(keep))
|
|
print('neko_start', 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')})
|
|
stt = youtube_relay_db.get_relay_state(str(winner['id'])) or {}
|
|
print('state', stt.get('status'), str(stt.get('error') or '')[:200])
|
|
for line in (stt.get('recent_log') or [])[-10:]:
|
|
print('LOG', line)
|
|
|
|
time.sleep(20)
|
|
_, st2 = call('GET', '/api/youtube/relay/status')
|
|
print('after_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', ((row.get('neko') or {}).get('running')),
|
|
'err', str(row.get('error') or '')[:120])
|
|
PY
|
|
"""
|
|
print("remote…")
|
|
_, o, e = c.exec_command(cmd, timeout=420)
|
|
out = o.read().decode("utf-8", "replace")
|
|
err = e.read().decode("utf-8", "replace")
|
|
code = o.channel.recv_exit_status()
|
|
print(out[-8000:] if len(out) > 8000 else out)
|
|
if err.strip():
|
|
print("STDERR", err[-1500:])
|
|
print("exit", code)
|
|
c.close()
|
|
return code
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|