douyinWEB/scripts/_migrate_dylive_settings_to_dy.py
2026-09-13 22:10:49 -05:00

189 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Copy safe settings from dylive (107) → dy.nomadro.live (108).
Copies: OAuth client profiles (id/secret), redirect URI template, relay quality defaults.
Does NOT copy: rooms/monitor.db, refresh_tokens, assign groups, channel cards.
"""
from __future__ import annotations
import json
import sys
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
SRC = ("107.173.30.245", "root", "Xiao4669805") # dylive
DST = ("108.174.50.68", "root", "Xiao4669805") # dy.nomadro.live
DST_REDIRECT = "https://dy.nomadro.live/api/shorts/oauth/callback"
def connect(host, user, password):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
host,
22,
user,
password,
timeout=45,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
return c
def run(c, cmd, t=120):
_i, o, e = c.exec_command(cmd, timeout=t)
out = (o.read() + e.read()).decode("utf-8", "replace")
code = o.channel.recv_exit_status()
return code, out
# --- pull from dylive ---
src = connect(*SRC)
code, out = run(
src,
r"""
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json
from app import db
sm = db.get_settings_map()
keys = [
'shorts_oauth_profiles',
'shorts_oauth_client_id',
'shorts_oauth_client_secret',
'shorts_oauth_redirect_uri',
'shorts_gcp_project_id',
'youtube_relay_quality_preset',
'youtube_relay_bitrate',
'youtube_relay_use_rtmps',
'youtube_relay_exclusive_live',
'youtube_relay_time_slot_mode',
'neko_mem_limit',
'dy_cookie',
]
payload = {}
for k in keys:
if k in sm and sm.get(k) not in (None, ''):
payload[k] = sm.get(k)
# redact print
safe = json.loads(json.dumps(payload))
if isinstance(safe.get('shorts_oauth_profiles'), list):
for p in safe['shorts_oauth_profiles']:
if p.get('client_secret'):
p['client_secret'] = (p['client_secret'][:4] + '…' + p['client_secret'][-4:]) if len(str(p['client_secret']))>8 else '***'
if p.get('client_id'):
p['client_id'] = str(p['client_id'])[:28] + '…'
if safe.get('shorts_oauth_client_secret'):
s=str(safe['shorts_oauth_client_secret']); safe['shorts_oauth_client_secret']=s[:4]+'…'+s[-4:]
if safe.get('dy_cookie'):
safe['dy_cookie'] = f"len={len(str(payload.get('dy_cookie') or ''))}"
print('SUMMARY', json.dumps(safe, ensure_ascii=False))
print('PAYLOAD_JSON_START')
print(json.dumps(payload, ensure_ascii=False))
print('PAYLOAD_JSON_END')
# also dump client_secret files if any
from pathlib import Path
for p in Path('/opt/douyinWEB').glob('client_secret_*.json'):
print('FILE', p.name)
PY
""",
)
src.close()
print(out[-4000:])
assert code == 0, out
start = out.find("PAYLOAD_JSON_START")
end = out.find("PAYLOAD_JSON_END")
assert start >= 0 and end > start, "no payload"
payload = json.loads(out[start + len("PAYLOAD_JSON_START") : end].strip())
# Rewrite redirect to dy domain; keep profile credentials
payload["shorts_oauth_redirect_uri"] = DST_REDIRECT
# Do not enable relay automatically on empty box
payload.pop("youtube_relay_enabled", None)
# Merge into dst
dst = connect(*DST)
sftp = dst.open_sftp()
with sftp.file("/tmp/migrate_settings.json", "w") as f:
f.write(json.dumps(payload, ensure_ascii=False))
sftp.close()
code2, out2 = run(
dst,
r"""
set -euo pipefail
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json
from app import db
from app import shorts_oauth
payload = json.loads(open('/tmp/migrate_settings.json', encoding='utf-8').read())
sm = db.get_settings_map()
# Merge OAuth profiles: fill empty slots from source; never wipe existing filled secrets unless source has them
src_profiles = {p['id']: p for p in shorts_oauth.normalize_oauth_profiles(payload.get('shorts_oauth_profiles'))}
cur_profiles = shorts_oauth.normalize_oauth_profiles(sm.get('shorts_oauth_profiles'))
merged = []
for p in cur_profiles:
row = dict(p)
sp = src_profiles.get(row['id']) or {}
if sp.get('client_id') and (not row.get('client_id') or sp.get('client_id')):
# prefer source if present
if sp.get('client_id'):
row['client_id'] = sp['client_id']
if sp.get('client_secret'):
row['client_secret'] = sp['client_secret']
if sp.get('label'):
row['label'] = sp['label']
merged.append(row)
# add any missing ids from source
have = {p['id'] for p in merged}
for pid, sp in src_profiles.items():
if pid not in have:
merged.append(sp)
patch = {
'shorts_oauth_profiles': merged,
'shorts_oauth_redirect_uri': payload.get('shorts_oauth_redirect_uri') or 'https://dy.nomadro.live/api/shorts/oauth/callback',
}
for k in (
'shorts_oauth_client_id', 'shorts_oauth_client_secret', 'shorts_gcp_project_id',
'youtube_relay_quality_preset', 'youtube_relay_bitrate', 'youtube_relay_use_rtmps',
'youtube_relay_exclusive_live', 'youtube_relay_time_slot_mode', 'neko_mem_limit',
'dy_cookie',
):
if payload.get(k) not in (None, ''):
patch[k] = payload[k]
db.update_settings_map(patch)
sm2 = db.get_settings_map()
print('redirect', sm2.get('shorts_oauth_redirect_uri'))
print('neko_mem_limit', sm2.get('neko_mem_limit'))
print('dy_cookie_len', len(str(sm2.get('dy_cookie') or '')))
print('relay_preset', sm2.get('youtube_relay_quality_preset'), 'bitrate', sm2.get('youtube_relay_bitrate'))
for p in shorts_oauth.normalize_oauth_profiles(sm2.get('shorts_oauth_profiles')):
cid = str(p.get('client_id') or '')
print(p['id'], 'cid', (cid[:28]+'…') if cid else '-', 'sec', bool(p.get('client_secret')))
# ensure nginx neko include synced for 4 instances
from app import youtube_neko as yn
print('sync_nginx', yn.sync_nginx_proxy(4))
PY
nginx -t && systemctl reload nginx
curl -sS -o /dev/null -w 'login:%{http_code}\n' --max-time 15 https://dy.nomadro.live/login
# copy any client_secret json files from dylive upload if present on /tmp
ls -la /opt/douyinWEB/client_secret_*.json 2>/dev/null || true
""",
)
dst.close()
print(out2[-5000:])
print("exit", code2)
raise SystemExit(code2)