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>
458 lines
18 KiB
Python
458 lines
18 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Migrate rooms + OAuth/channels from ypp.smallzhiyuns.com → dy.nomadro.live.
|
|
|
|
Same codebase; ypp is older deploy. We merge (do not wipe) into dy:
|
|
- Douyin rooms from CSV (and any missing from ypp)
|
|
- shorts_oauth_profiles / client settings from ypp (keep dy redirect URIs)
|
|
- shorts_channels + yt_long_channels (match by youtube_channel_id; insert if missing)
|
|
- yt_assign stream_key when ypp has a key and dy group matches by channel id/name
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import json
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import paramiko
|
|
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CSV_PATH = Path(r"C:\Users\admin\Desktop\rooms_20260901_195041.csv")
|
|
|
|
YPP_HOST = "192.227.152.110"
|
|
YPP_PASS = "Leaf448772566"
|
|
DY_HOST = "108.174.50.68"
|
|
DY_PASS = "Xiao4669805"
|
|
|
|
EXPORT_PY = r"""
|
|
import json, sqlite3, time
|
|
DB='/opt/douyinWEB/backend/data/monitor.db'
|
|
conn=sqlite3.connect(DB)
|
|
conn.row_factory=sqlite3.Row
|
|
|
|
def rows(sql, args=()):
|
|
return [dict(r) for r in conn.execute(sql, args).fetchall()]
|
|
|
|
kv_keys = [
|
|
'shorts_oauth_client_id','shorts_oauth_client_secret','shorts_oauth_profiles',
|
|
'shorts_oauth_brand_hints','tiktok_oauth_client_key','tiktok_oauth_client_secret',
|
|
]
|
|
settings = {}
|
|
for k in kv_keys:
|
|
r = conn.execute('SELECT value FROM kv_settings WHERE key=?',(k,)).fetchone()
|
|
if r: settings[k]=r[0]
|
|
|
|
out = {
|
|
'exported_at': time.time(),
|
|
'settings': settings,
|
|
'rooms': rows('SELECT room_id,url,note,tags,enabled,last_status,last_anchor FROM rooms'),
|
|
'shorts_channels': rows('SELECT * FROM shorts_channels'),
|
|
'yt_long_channels': rows('SELECT * FROM yt_long_channels'),
|
|
'yt_assign_groups': rows('SELECT * FROM yt_assign_groups'),
|
|
}
|
|
print(json.dumps(out, ensure_ascii=False))
|
|
"""
|
|
|
|
APPLY_PY = r"""
|
|
import json, sqlite3, time, uuid, os
|
|
from pathlib import Path
|
|
|
|
payload = json.loads(Path('/tmp/ypp_migrate_payload.json').read_text(encoding='utf-8'))
|
|
csv_rooms = json.loads(Path('/tmp/rooms_csv.json').read_text(encoding='utf-8'))
|
|
|
|
DB='/opt/douyinWEB/backend/data/monitor.db'
|
|
conn=sqlite3.connect(DB)
|
|
conn.row_factory=sqlite3.Row
|
|
now=time.time()
|
|
stats={'rooms_created':0,'rooms_updated':0,'shorts_upserted':0,'shorts_inserted':0,
|
|
'yl_upserted':0,'yl_inserted':0,'assign_key_updated':0,'settings_merged':0}
|
|
|
|
def get_setting(key):
|
|
r=conn.execute('SELECT value FROM kv_settings WHERE key=?',(key,)).fetchone()
|
|
return r[0] if r else None
|
|
|
|
def set_setting(key, value):
|
|
conn.execute(
|
|
"INSERT INTO kv_settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
(key, value if isinstance(value,str) else json.dumps(value, ensure_ascii=False))
|
|
)
|
|
|
|
# --- settings: merge oauth profiles; keep dy redirect ---
|
|
src_settings = payload.get('settings') or {}
|
|
# merge profiles
|
|
try:
|
|
dy_profiles = json.loads(get_setting('shorts_oauth_profiles') or '[]')
|
|
except Exception:
|
|
dy_profiles = []
|
|
if not isinstance(dy_profiles, list):
|
|
dy_profiles = []
|
|
try:
|
|
ypp_profiles = json.loads(src_settings.get('shorts_oauth_profiles') or '[]')
|
|
except Exception:
|
|
ypp_profiles = []
|
|
if not isinstance(ypp_profiles, list):
|
|
ypp_profiles = []
|
|
|
|
by_cid = {}
|
|
for p in dy_profiles:
|
|
cid = str((p or {}).get('client_id') or '').strip()
|
|
if cid: by_cid[cid]=p
|
|
for p in ypp_profiles:
|
|
cid = str((p or {}).get('client_id') or '').strip()
|
|
if not cid:
|
|
continue
|
|
if cid in by_cid:
|
|
# refresh secret from ypp
|
|
by_cid[cid] = {**by_cid[cid], **{k:v for k,v in (p or {}).items() if v}}
|
|
else:
|
|
# assign next free id letter
|
|
used = {str(x.get('id') or '').upper() for x in by_cid.values()}
|
|
letter = str((p or {}).get('id') or 'Y').upper()
|
|
if letter in used:
|
|
for cand in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
|
|
if cand not in used:
|
|
letter = cand
|
|
break
|
|
np = dict(p)
|
|
np['id'] = letter
|
|
if not np.get('label'):
|
|
np['label'] = f'谷歌账号 {letter} (from ypp)'
|
|
by_cid[cid] = np
|
|
merged_profiles = list(by_cid.values())
|
|
# stable order by id
|
|
merged_profiles.sort(key=lambda x: str(x.get('id') or ''))
|
|
set_setting('shorts_oauth_profiles', json.dumps(merged_profiles, ensure_ascii=False))
|
|
stats['settings_merged'] += 1
|
|
stats['profiles_count'] = len(merged_profiles)
|
|
|
|
# copy brand hints if dy empty-ish
|
|
bh = src_settings.get('shorts_oauth_brand_hints')
|
|
if bh and (not get_setting('shorts_oauth_brand_hints') or get_setting('shorts_oauth_brand_hints') in ('','{}','null')):
|
|
set_setting('shorts_oauth_brand_hints', bh)
|
|
stats['settings_merged'] += 1
|
|
|
|
# default client = first profile A or first
|
|
default = next((p for p in merged_profiles if str(p.get('id')).upper()=='A'), merged_profiles[0] if merged_profiles else None)
|
|
if default:
|
|
set_setting('shorts_oauth_client_id', str(default.get('client_id') or ''))
|
|
set_setting('shorts_oauth_client_secret', str(default.get('client_secret') or ''))
|
|
|
|
# force dy redirect
|
|
set_setting('shorts_oauth_redirect_uri', 'https://dy.nomadro.live/api/shorts/oauth/callback')
|
|
set_setting('tiktok_oauth_redirect_uri', 'https://dy.nomadro.live/api/tiktok/oauth/callback/')
|
|
|
|
# tiktok keys if ypp has real ones
|
|
tk = str(src_settings.get('tiktok_oauth_client_key') or '').strip()
|
|
ts = str(src_settings.get('tiktok_oauth_client_secret') or '').strip()
|
|
if len(tk) > 5:
|
|
set_setting('tiktok_oauth_client_key', tk)
|
|
if len(ts) > 5:
|
|
set_setting('tiktok_oauth_client_secret', ts)
|
|
|
|
# --- rooms from CSV + ypp ---
|
|
def upsert_room(room_id, url, note='', tags='', enabled=1, last_anchor=''):
|
|
room_id = str(room_id or '').strip()
|
|
url = str(url or '').strip()
|
|
if not room_id and url:
|
|
# extract digits
|
|
import re
|
|
m = re.search(r'(\d{6,})', url)
|
|
room_id = m.group(1) if m else ''
|
|
if not url and room_id:
|
|
url = f'https://live.douyin.com/{room_id}'
|
|
if not room_id or not url:
|
|
return
|
|
tags_s = tags if isinstance(tags, str) else ','.join(tags or [])
|
|
row = conn.execute('SELECT id FROM rooms WHERE room_id=?', (room_id,)).fetchone()
|
|
if row:
|
|
conn.execute(
|
|
"UPDATE rooms SET url=?, note=CASE WHEN note IS NULL OR note='' THEN ? ELSE note END, "
|
|
"tags=CASE WHEN tags IS NULL OR tags='' THEN ? ELSE tags END, enabled=?, updated_at=? WHERE room_id=?",
|
|
(url, note or '', tags_s, 1 if enabled else 0, now, room_id)
|
|
)
|
|
# also refresh last_anchor if provided and empty
|
|
if last_anchor:
|
|
conn.execute(
|
|
"UPDATE rooms SET last_anchor=CASE WHEN last_anchor IS NULL OR last_anchor='' THEN ? ELSE last_anchor END WHERE room_id=?",
|
|
(last_anchor, room_id)
|
|
)
|
|
stats['rooms_updated'] += 1
|
|
else:
|
|
pk = str(uuid.uuid4())
|
|
conn.execute(
|
|
'INSERT INTO rooms(id, room_id, url, note, tags, enabled, last_status, last_anchor, last_checked_at, created_at, updated_at) '
|
|
'VALUES(?,?,?,?,?,?,?,?,?,?,?)',
|
|
(pk, room_id, url, note or '', tags_s, 1 if enabled else 0, 'unknown', last_anchor or '', 0, now, now)
|
|
)
|
|
stats['rooms_created'] += 1
|
|
|
|
for r in csv_rooms:
|
|
upsert_room(r.get('room_id'), r.get('url'), r.get('note') or '', r.get('tags') or '',
|
|
int(r.get('enabled') or 1), r.get('last_anchor') or '')
|
|
for r in payload.get('rooms') or []:
|
|
upsert_room(r.get('room_id'), r.get('url'), r.get('note') or '', r.get('tags') or '',
|
|
int(r.get('enabled') or 1), r.get('last_anchor') or '')
|
|
|
|
# map ypp oauth profile client_id → dy profile id letter
|
|
cid_to_pid = {str(p.get('client_id') or ''): str(p.get('id') or '') for p in merged_profiles}
|
|
|
|
# --- shorts channels ---
|
|
sc_cols = {r[1] for r in conn.execute('PRAGMA table_info(shorts_channels)').fetchall()}
|
|
for src in payload.get('shorts_channels') or []:
|
|
ycid = str(src.get('youtube_channel_id') or '').strip()
|
|
if not ycid:
|
|
continue
|
|
# map profile
|
|
src_cid = str(src.get('client_id') or '').strip()
|
|
pid = cid_to_pid.get(src_cid) or str(src.get('oauth_profile_id') or 'B')
|
|
existing = conn.execute(
|
|
'SELECT id FROM shorts_channels WHERE youtube_channel_id=? LIMIT 1', (ycid,)
|
|
).fetchone()
|
|
fields = {
|
|
'name': src.get('name') or '',
|
|
'youtube_channel_id': ycid,
|
|
'client_id': src.get('client_id') or '',
|
|
'client_secret': src.get('client_secret') or '',
|
|
'refresh_token': src.get('refresh_token') or '',
|
|
'enabled': int(src.get('enabled') or 1),
|
|
'daily_min': int(src.get('daily_min') or 5),
|
|
'daily_max': int(src.get('daily_max') or 9),
|
|
'title_template': src.get('title_template') or '{anchor} 直播瞬间 #Shorts',
|
|
'description_template': src.get('description_template') or '',
|
|
'privacy': src.get('privacy') or 'public',
|
|
'note': (src.get('note') or '') + ' | from ypp',
|
|
'oauth_ok': int(src.get('oauth_ok') or 0),
|
|
'oauth_error': src.get('oauth_error') or '',
|
|
'oauth_profile_id': pid,
|
|
'updated_at': now,
|
|
}
|
|
if 'upload_priority' in sc_cols:
|
|
fields['upload_priority'] = int(src.get('upload_priority') or 0)
|
|
if 'yt_profile_json' in sc_cols and src.get('yt_profile_json'):
|
|
fields['yt_profile_json'] = src.get('yt_profile_json')
|
|
if existing:
|
|
sets = ', '.join(f'{k}=?' for k in fields)
|
|
conn.execute(f'UPDATE shorts_channels SET {sets} WHERE id=?', (*fields.values(), existing['id']))
|
|
stats['shorts_upserted'] += 1
|
|
src['_dy_pk'] = existing['id']
|
|
else:
|
|
pk = str(src.get('id') or uuid.uuid4())
|
|
# avoid pk collision
|
|
if conn.execute('SELECT 1 FROM shorts_channels WHERE id=?', (pk,)).fetchone():
|
|
pk = str(uuid.uuid4())
|
|
fields['id'] = pk
|
|
fields['created_at'] = float(src.get('created_at') or now)
|
|
cols = list(fields.keys())
|
|
conn.execute(
|
|
f"INSERT INTO shorts_channels({', '.join(cols)}) VALUES({', '.join('?'*len(cols))})",
|
|
tuple(fields.values())
|
|
)
|
|
stats['shorts_inserted'] += 1
|
|
src['_dy_pk'] = pk
|
|
|
|
# rebuild ypp shorts id -> dy pk map by youtube_channel_id
|
|
ycid_to_sc = {}
|
|
for r in conn.execute('SELECT id, youtube_channel_id FROM shorts_channels').fetchall():
|
|
if r['youtube_channel_id']:
|
|
ycid_to_sc[r['youtube_channel_id']] = r['id']
|
|
|
|
# --- yt long channels ---
|
|
yl_cols = {r[1] for r in conn.execute('PRAGMA table_info(yt_long_channels)').fetchall()}
|
|
for src in payload.get('yt_long_channels') or []:
|
|
ycid = str(src.get('youtube_channel_id') or '').strip()
|
|
if not ycid:
|
|
continue
|
|
src_cid = str(src.get('client_id') or '').strip()
|
|
pid = cid_to_pid.get(src_cid) or str(src.get('oauth_profile_id') or 'B')
|
|
src_sc = str(src.get('source_shorts_channel_pk') or '')
|
|
# remap source shorts pk via youtube id of that shorts channel in payload
|
|
sc_ycid = ''
|
|
for sc in payload.get('shorts_channels') or []:
|
|
if str(sc.get('id')) == src_sc:
|
|
sc_ycid = str(sc.get('youtube_channel_id') or '')
|
|
break
|
|
dy_sc_pk = ycid_to_sc.get(sc_ycid or ycid, '')
|
|
existing = conn.execute(
|
|
'SELECT id FROM yt_long_channels WHERE youtube_channel_id=? LIMIT 1', (ycid,)
|
|
).fetchone()
|
|
fields = {
|
|
'name': src.get('name') or '',
|
|
'youtube_channel_id': ycid,
|
|
'oauth_profile_id': pid,
|
|
'client_id': src.get('client_id') or '',
|
|
'client_secret': src.get('client_secret') or '',
|
|
'refresh_token': src.get('refresh_token') or '',
|
|
'enabled': int(src.get('enabled') or 1),
|
|
'daily_max': int(src.get('daily_max') or 4),
|
|
'title_template': src.get('title_template') or '{anchor} street food live',
|
|
'description_template': src.get('description_template') or '',
|
|
'privacy': src.get('privacy') or 'public',
|
|
'note': (src.get('note') or '') + ' | from ypp',
|
|
'source_shorts_channel_pk': dy_sc_pk,
|
|
'oauth_ok': int(src.get('oauth_ok') or 0),
|
|
'oauth_error': src.get('oauth_error') or '',
|
|
'updated_at': now,
|
|
}
|
|
if 'ypp_ok' in yl_cols:
|
|
fields['ypp_ok'] = int(src.get('ypp_ok') or 0)
|
|
if 'monetize_default' in yl_cols:
|
|
fields['monetize_default'] = int(src.get('monetize_default') or 1)
|
|
if 'upload_priority' in yl_cols:
|
|
fields['upload_priority'] = int(src.get('upload_priority') or 10)
|
|
if existing:
|
|
sets = ', '.join(f'{k}=?' for k in fields)
|
|
conn.execute(f'UPDATE yt_long_channels SET {sets} WHERE id=?', (*fields.values(), existing['id']))
|
|
stats['yl_upserted'] += 1
|
|
else:
|
|
pk = str(src.get('id') or uuid.uuid4())
|
|
if conn.execute('SELECT 1 FROM yt_long_channels WHERE id=?', (pk,)).fetchone():
|
|
pk = str(uuid.uuid4())
|
|
fields['id'] = pk
|
|
fields['created_at'] = float(src.get('created_at') or now)
|
|
cols = list(fields.keys())
|
|
conn.execute(
|
|
f"INSERT INTO yt_long_channels({', '.join(cols)}) VALUES({', '.join('?'*len(cols))})",
|
|
tuple(fields.values())
|
|
)
|
|
stats['yl_inserted'] += 1
|
|
|
|
# --- assign stream keys ---
|
|
for src in payload.get('yt_assign_groups') or []:
|
|
sk = str(src.get('stream_key') or '').strip()
|
|
if not sk:
|
|
continue
|
|
ycid = str(src.get('youtube_channel_id') or '').strip()
|
|
name = str(src.get('name') or '').strip()
|
|
row = None
|
|
if ycid:
|
|
row = conn.execute('SELECT id, stream_key FROM yt_assign_groups WHERE youtube_channel_id=?', (ycid,)).fetchone()
|
|
if not row and name:
|
|
row = conn.execute('SELECT id, stream_key FROM yt_assign_groups WHERE name=?', (name,)).fetchone()
|
|
if row:
|
|
# only fill if empty or overwrite from ypp when ypp has key
|
|
conn.execute('UPDATE yt_assign_groups SET stream_key=?, updated_at=? WHERE id=?', (sk, now, row['id']))
|
|
# also link channel_pk if possible
|
|
sc_pk = ycid_to_sc.get(ycid, '')
|
|
if sc_pk:
|
|
conn.execute('UPDATE yt_assign_groups SET channel_pk=? WHERE id=?', (sc_pk, row['id']))
|
|
stats['assign_key_updated'] += 1
|
|
else:
|
|
# create assign group if missing
|
|
pk = str(src.get('id') or uuid.uuid4())
|
|
if conn.execute('SELECT 1 FROM yt_assign_groups WHERE id=?', (pk,)).fetchone():
|
|
pk = str(uuid.uuid4())
|
|
sc_pk = ycid_to_sc.get(ycid, '')
|
|
neko = int(src.get('neko_instance_id') or 0)
|
|
# pick free neko id
|
|
if neko <= 0:
|
|
used = {int(r[0] or 0) for r in conn.execute('SELECT neko_instance_id FROM yt_assign_groups').fetchall()}
|
|
for i in range(1, 20):
|
|
if i not in used:
|
|
neko = i
|
|
break
|
|
so = conn.execute('SELECT coalesce(max(sort_order),0)+1 FROM yt_assign_groups').fetchone()[0]
|
|
conn.execute(
|
|
'INSERT INTO yt_assign_groups(id,name,channel_pk,youtube_channel_id,stream_key,note,enabled,sort_order,created_at,updated_at,neko_instance_id,neko_enabled) '
|
|
'VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',
|
|
(pk, name or ycid, sc_pk, ycid, sk, 'from ypp', 1, so, now, now, neko, 0)
|
|
)
|
|
stats['assign_key_updated'] += 1
|
|
|
|
conn.commit()
|
|
|
|
# summary without secrets
|
|
sc_n = conn.execute('SELECT count(*) FROM shorts_channels').fetchone()[0]
|
|
yl_n = conn.execute('SELECT count(*) FROM yt_long_channels').fetchone()[0]
|
|
rm_n = conn.execute('SELECT count(*) FROM rooms').fetchone()[0]
|
|
ag = [dict(r) for r in conn.execute('SELECT name, youtube_channel_id, length(stream_key) sk_len, channel_pk FROM yt_assign_groups').fetchall()]
|
|
sc = [dict(r) for r in conn.execute('SELECT name, youtube_channel_id, oauth_profile_id, oauth_ok, length(refresh_token) rt FROM shorts_channels ORDER BY name').fetchall()]
|
|
print(json.dumps({
|
|
'ok': True,
|
|
'stats': stats,
|
|
'totals': {'rooms': rm_n, 'shorts': sc_n, 'yt_long': yl_n},
|
|
'assign': ag,
|
|
'shorts': sc,
|
|
}, ensure_ascii=False, indent=2))
|
|
conn.close()
|
|
"""
|
|
|
|
|
|
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 exec_out(c: paramiko.SSHClient, cmd: str, timeout: int = 180) -> 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:
|
|
# parse CSV
|
|
rooms = []
|
|
with CSV_PATH.open("r", encoding="utf-8-sig", newline="") as f:
|
|
for row in csv.DictReader(f):
|
|
rooms.append(
|
|
{
|
|
"room_id": (row.get("room_id") or "").strip(),
|
|
"url": (row.get("url") or "").strip(),
|
|
"note": (row.get("note") or "").strip(),
|
|
"tags": (row.get("tags") or "").strip(),
|
|
"enabled": int(row.get("enabled") or 1),
|
|
"last_anchor": (row.get("last_anchor") or "").strip(),
|
|
}
|
|
)
|
|
print(f"CSV rooms: {len(rooms)}")
|
|
|
|
# export from ypp
|
|
print("export from ypp…")
|
|
ypp = ssh(YPP_HOST, YPP_PASS)
|
|
sftp = ypp.open_sftp()
|
|
with sftp.file("/tmp/_ypp_export.py", "w") as f:
|
|
f.write(EXPORT_PY)
|
|
sftp.close()
|
|
raw = exec_out(ypp, "cd /opt/douyinWEB/backend && .venv/bin/python /tmp/_ypp_export.py", 120)
|
|
payload = json.loads(raw)
|
|
ypp.close()
|
|
print(
|
|
"ypp export:",
|
|
f"rooms={len(payload.get('rooms') or [])}",
|
|
f"shorts={len(payload.get('shorts_channels') or [])}",
|
|
f"yt_long={len(payload.get('yt_long_channels') or [])}",
|
|
f"assign={len(payload.get('yt_assign_groups') or [])}",
|
|
f"settings={list((payload.get('settings') or {}).keys())}",
|
|
)
|
|
|
|
# apply on dy
|
|
print("apply on dy…")
|
|
dy = ssh(DY_HOST, DY_PASS)
|
|
sftp = dy.open_sftp()
|
|
with sftp.file("/tmp/ypp_migrate_payload.json", "w") as f:
|
|
f.write(json.dumps(payload, ensure_ascii=False))
|
|
with sftp.file("/tmp/rooms_csv.json", "w") as f:
|
|
f.write(json.dumps(rooms, ensure_ascii=False))
|
|
with sftp.file("/tmp/_ypp_apply.py", "w") as f:
|
|
f.write(APPLY_PY)
|
|
sftp.close()
|
|
out = exec_out(dy, "cd /opt/douyinWEB/backend && .venv/bin/python /tmp/_ypp_apply.py", 180)
|
|
print(out)
|
|
# cleanup secrets on remote
|
|
exec_out(dy, "rm -f /tmp/ypp_migrate_payload.json /tmp/_ypp_apply.py /tmp/rooms_csv.json", 30)
|
|
dy.close()
|
|
print("done")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|