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

131 lines
5.4 KiB
Python

# -*- coding: utf-8 -*-
"""
Step 1: Fix admin password back to Xiao4669805@
Step 2: Restore shorts_channels from git stash (best available)
Step 3: Report rooms/sessions/events count on server
"""
import hashlib
import json
import paramiko
import sqlite3
import time
from pathlib import Path
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
DB_PATH = "/opt/douyinWEB/backend/data/monitor.db"
TARGET_PW = "Xiao4669805@"
SESSION_SECRET = "douyinweb-session-2026"
def pw_hash(pw: str) -> str:
return hashlib.sha256(f"{SESSION_SECRET}:{pw}".encode()).hexdigest()
def ssh_run(client: paramiko.SSHClient, cmd: str, timeout: int = 60) -> tuple[str, str]:
_stdin, stdout, stderr = client.exec_command(cmd, timeout=timeout)
return (
stdout.read().decode("utf-8", "replace").strip(),
stderr.read().decode("utf-8", "replace").strip(),
)
def main() -> None:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
# ── 1. Fix admin password ─────────────────────────────────────────
h = pw_hash(TARGET_PW)
val = json.dumps(h)
cmd = (
"python3 -c \""
"import sqlite3, json; "
f"conn=sqlite3.connect('{DB_PATH}'); "
f"conn.execute(\\\"UPDATE kv_settings SET value=? WHERE key='admin_password_hash'\\\",({val!r},)); "
"conn.commit(); "
"row=conn.execute(\\\"SELECT value FROM kv_settings WHERE key='admin_password_hash'\\\").fetchone(); "
"print('hash_set', bool(row))\""
)
out, err = ssh_run(c, cmd, timeout=60)
print("=== FIX PASSWORD ===")
print(out)
if err:
print("err:", err[:300])
# ── 2. Dump current DB state ──────────────────────────────────────
print("\n=== SERVER DB COUNTS ===")
for tbl in ["rooms", "sessions", "events", "channel_groups", "shorts_channels", "shorts_jobs", "kv_settings"]:
out, err = ssh_run(
c,
f"python3 -c \"import sqlite3; conn=sqlite3.connect('{DB_PATH}'); print(conn.execute('select count(*) from {tbl}').fetchone()[0])\"",
)
print(f" {tbl}: {out} {('ERR:'+err[:60]) if err else ''}")
# ── 3. Check stash list ───────────────────────────────────────────
print("\n=== STASH LIST ===")
out, err = ssh_run(c, "cd /opt/douyinWEB && git stash list", timeout=30)
print(out or "(empty)")
# ── 4. Check each stash for shorts_channels ────────────────────────
stash_count = sum(1 for l in out.splitlines() if l.strip())
best_stash = None
best_count = 0
print("\n=== STASH shorts_channels counts ===")
for i in range(min(stash_count, 5)):
tmp = f"/tmp/monitor_stash{i}.db"
out2, _ = ssh_run(
c,
f"cd /opt/douyinWEB && git show stash@{{{i}}}:backend/data/monitor.db > {tmp} 2>/dev/null; "
f"python3 -c \"import sqlite3; conn=sqlite3.connect('{tmp}'); "
"r=conn.execute('select count(*) from shorts_channels').fetchone(); print(r[0] if r else 0)\" 2>/dev/null || echo 0",
timeout=120,
)
cnt = int(out2.strip()) if out2.strip().isdigit() else 0
print(f" stash@{{{i}}}: {cnt} shorts_channels")
if cnt > best_count:
best_count = cnt
best_stash = i
# ── 5. Restore if found ────────────────────────────────────────────
if best_stash is not None and best_count > 0:
print(f"\n=== RESTORING from stash@{{{best_stash}}} ({best_count} shorts_channels) ===")
tmp = f"/tmp/monitor_stash{best_stash}.db"
# Copy only shorts_channels + shorts_jobs rows into live DB
restore_cmd = (
f"python3 -c \""
f"import sqlite3; "
f"src=sqlite3.connect('{tmp}'); "
f"dst=sqlite3.connect('{DB_PATH}'); "
f"ch_rows=src.execute('SELECT * FROM shorts_channels').fetchall(); "
f"dst.execute('DELETE FROM shorts_channels'); "
f"if ch_rows: dst.executemany('INSERT OR REPLACE INTO shorts_channels VALUES ({','.join(['?']*len(src.execute('PRAGMA table_info(shorts_channels)').fetchall()))})', ch_rows); "
f"dst.commit(); "
f"print('restored', len(ch_rows), 'channels')\""
)
out, err = ssh_run(c, restore_cmd, timeout=120)
print(out)
if err:
print("err:", err[:300])
else:
print("\n=== NO shorts_channels found in any stash ===")
# Still try: check ALL git stash entries for shorts data
print("best available stash count was 0. Will use git log to check committed DBs.")
# ── 6. Restart API ─────────────────────────────────────────────────
print("\n=== RESTART API ===")
out, err = ssh_run(
c,
"systemctl restart douyinweb-api --no-block; sleep 5; systemctl is-active douyinweb-api douyinweb-web",
timeout=30,
)
print(out)
c.close()
print("\nDONE")
if __name__ == "__main__":
main()