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

300 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Fix YT profile thumbs + rewrite Neko UI copy; deploy dual VPS."""
from __future__ import annotations
import hashlib
import sys
import time
import tarfile
import io
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
DYLIVE, DY, PASS = "107.173.30.245", "108.174.50.68", "Xiao4669805"
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
def connect(host):
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(10):
try:
c.connect(host, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=120)
return c
except Exception as e:
print("retry", host, e, flush=True)
time.sleep(2 + i)
raise SystemExit("ssh fail")
def run(c, script, timeout=600):
_i, o, e = c.exec_command(script, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def put(c, data: bytes, remote: str):
sftp = c.open_sftp()
with sftp.file(remote, "wb") as f:
f.write(data)
sftp.close()
# --- 1) Fix UI copy locally ---
panel = ROOT / "frontend/src/components/YtRelayProStatusPanel.tsx"
text = panel.read_text(encoding="utf-8")
repls = [
("打开物理机配对实例", "打开远程配对实例"),
("请先选择远程实例", "请先选择远程实例"),
("未绑定:在下方选物理机实例,或去 Neko 页完成配对", "未绑定:在下方选远程实例,或去 Neko 页完成对端配对(双 VPS 可选)"),
("物理机实例", "远程实例"),
("目录为空:请到 Neko 页完成物理机配对。", "目录为空:未配对对端;双 VPS 可只用本机 Neko,无需远程。"),
(
"本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{",
"本机 Neko #{instanceId}:开关=启停容器(新建默认关)。密码{",
),
]
# The last one uses template - fix the actual source string
repls[-1] = (
"本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{",
"本机 Neko #{instanceId}:开关控制容器启停(新建默认关)。密码{",
)
# In TSX it's JSX with {instanceId}
old_help = '本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{" "}'
# read exact lines
for a, b in [
("打开物理机配对实例", "打开远程配对实例"),
("未绑定:在下方选物理机实例,或去 Neko 页完成配对", "未绑定:可选远程实例;双 VPS 通常只用本机 Neko"),
("物理机实例", "远程实例"),
("目录为空:请到 Neko 页完成物理机配对。", "目录为空:未配对对端。双 VPS 可只用本机,忽略此项。"),
]:
if a not in text:
print("MISSING_STR", a, flush=True)
else:
text = text.replace(a, b)
print("replaced", a[:30], flush=True)
# help text
old = "本机 Neko #{instanceId} 默认停止;启用即启停容器。密码{"
# actual file content:
import re
text2, n = re.subn(
r"本机 Neko #\{instanceId\} 默认停止;启用即启停容器。",
"本机 Neko #{instanceId}:启用=启动容器,关闭=停止(新建默认关)。",
text,
count=1,
)
print("help_n", n, flush=True)
text = text2
panel.write_text(text, encoding="utf-8")
# OpsNekoHubCredentialsCard
ops = ROOT / "frontend/src/components/OpsNekoHubCredentialsCard.tsx"
if ops.exists():
ot = ops.read_text(encoding="utf-8")
ot2 = ot.replace("加载物理机配对凭证", "加载远程配对凭证")
if ot2 != ot:
ops.write_text(ot2, encoding="utf-8")
print("ops card text updated", flush=True)
FIX_THUMBS = r'''
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json, re, urllib.request
from app.db import _connect, _lock
def exists(url: str) -> bool:
try:
urllib.request.urlopen(url, timeout=4).read(8)
return True
except Exception:
return False
def rewrite_url(u: str) -> str:
u = str(u or "")
u2 = u.replace("https://dy.nomadro.com/douyin-covers", "https://s3.nomadro.com/douyin-covers")
u2 = u2.replace("http://dy.nomadro.com/douyin-covers", "https://s3.nomadro.com/douyin-covers")
return u2
with _lock:
conn = _connect()
cols = [r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()]
print("cols_has_yt_profile", "yt_profile_json" in cols)
rows = conn.execute(
"SELECT id, name, yt_profile_json FROM shorts_channels WHERE yt_profile_json IS NOT NULL AND yt_profile_json != ''"
).fetchall()
fixed = 0
cleared = 0
ok = 0
for rid, name, raw in rows:
try:
data = json.loads(raw)
except Exception:
continue
changed = False
thumb = str(data.get("thumb_url") or "").strip()
thumbs = data.get("thumbnails") if isinstance(data.get("thumbnails"), dict) else {}
# rewrite hosts
new_thumb = rewrite_url(thumb)
if new_thumb != thumb:
data["thumb_url"] = new_thumb
thumb = new_thumb
changed = True
for k in ("default", "medium", "high"):
node = thumbs.get(k) if isinstance(thumbs.get(k), dict) else None
if not node:
continue
ou = str(node.get("url") or "")
nu = rewrite_url(ou)
if nu != ou:
node["url"] = nu
changed = True
# if still broken, prefer thumb_cdn youtube googleusercontent
cdn = str(data.get("thumb_cdn") or "").strip()
check = str(data.get("thumb_url") or "").strip()
if check.startswith("http") and not exists(check):
if cdn.startswith("http") and exists(cdn):
data["thumb_url"] = cdn
data["thumbnails"] = {
"default": {"url": cdn},
"medium": {"url": cdn},
}
changed = True
print("fallback_cdn", name, cdn[:60])
else:
# blank so UI can refresh later rather than letter-from-broken
data["thumb_url"] = cdn if cdn.startswith("http") else ""
if data.get("thumbnails"):
for k, node in list(data["thumbnails"].items()):
if isinstance(node, dict):
node["url"] = data["thumb_url"]
changed = True
cleared += 1
print("broken", name, check[-50:])
check = data["thumb_url"]
if check.startswith("http") and exists(check):
ok += 1
if changed:
conn.execute(
"UPDATE shorts_channels SET yt_profile_json=? WHERE id=?",
(json.dumps(data, ensure_ascii=False), rid),
)
fixed += 1
conn.commit()
print("fixed", fixed, "ok_now", ok, "cleared_or_cdn", cleared)
PY
'''
for label, host in [("dylive", DYLIVE), ("dy", DY)]:
print(f"\n######## fix thumbs {label} ########", flush=True)
c = connect(host)
print(run(c, FIX_THUMBS, timeout=300), flush=True)
c.close()
# --- deploy FE files + rebuild on dy, sync to dylive ---
files = [
"frontend/src/components/YtRelayProStatusPanel.tsx",
"frontend/src/components/OpsNekoHubCredentialsCard.tsx",
"frontend/src/lib/api.js",
"backend/app/session_auth.py",
"backend/app/youtube_neko.py",
]
print("\n######## deploy sources to dy + build ########", flush=True)
c = connect(DY)
for rel in files:
p = ROOT / rel.replace("/", "\\")
if p.exists():
put(c, p.read_bytes(), f"/opt/douyinWEB/{rel}")
print("put", rel, flush=True)
print(
run(
c,
r"""
set -e
systemctl restart douyinweb-api
cd /opt/douyinWEB/frontend
export NODE_OPTIONS=--max-old-space-size=3072
npm run build 2>&1 | tail -25
systemctl restart douyinweb-web
sleep 2
systemctl is-active douyinweb-api douyinweb-web
tar -C /opt/douyinWEB/frontend -czf /tmp/next-fe-neko-ui.tgz .next
# also pack changed src for dylive
tar -C /opt/douyinWEB -czf /tmp/src-neko-ui.tgz \
frontend/src/components/YtRelayProStatusPanel.tsx \
frontend/src/components/OpsNekoHubCredentialsCard.tsx \
frontend/src/lib/api.js \
backend/app/session_auth.py \
backend/app/youtube_neko.py
ls -lh /tmp/next-fe-neko-ui.tgz /tmp/src-neko-ui.tgz
""",
timeout=700,
),
flush=True,
)
sftp = c.open_sftp()
sftp.get("/tmp/next-fe-neko-ui.tgz", str(ROOT / "scripts/_next-fe-neko-ui.tgz"))
sftp.get("/tmp/src-neko-ui.tgz", str(ROOT / "scripts/_src-neko-ui.tgz"))
sftp.close()
c.close()
print("\n######## deploy to dylive ########", flush=True)
c = connect(DYLIVE)
put(c, (ROOT / "scripts/_src-neko-ui.tgz").read_bytes(), "/tmp/src-neko-ui.tgz")
put(c, (ROOT / "scripts/_next-fe-neko-ui.tgz").read_bytes(), "/tmp/next-fe-neko-ui.tgz")
print(
run(
c,
r"""
set -e
tar -C /opt/douyinWEB -xzf /tmp/src-neko-ui.tgz
systemctl stop douyinweb-web || true
rm -rf /opt/douyinWEB/frontend/.next.bak_neko_ui
mv /opt/douyinWEB/frontend/.next /opt/douyinWEB/frontend/.next.bak_neko_ui 2>/dev/null || true
tar -C /opt/douyinWEB/frontend -xzf /tmp/next-fe-neko-ui.tgz
systemctl restart douyinweb-api
systemctl start douyinweb-web
sleep 2
systemctl is-active douyinweb-api douyinweb-web
# hash check
python3 - <<'PY'
import hashlib, pathlib
for rel in [
'backend/app/youtube_neko.py',
'frontend/src/components/YtRelayProStatusPanel.tsx',
'frontend/src/lib/api.js',
]:
p=pathlib.Path('/opt/douyinWEB')/rel
print(hashlib.sha256(p.read_bytes()).hexdigest()[:12], rel)
PY
grep -n '远程实例\|双 VPS\|打开远程' /opt/douyinWEB/frontend/src/components/YtRelayProStatusPanel.tsx | head -10
""",
timeout=120,
),
flush=True,
)
c.close()
# trigger profile refresh on both so CDN fills missing
REFRESH = r'''
cd /opt/douyinWEB/backend
# call local API with cookie is hard; invoke python directly
./.venv/bin/python - <<'PY'
import asyncio
from app import youtube_manage
async def main():
r = await youtube_manage.refresh_stale_yt_profiles(max_age_sec=0, limit=50)
print(r)
asyncio.run(main())
PY
'''
for label, host in [("dylive", DYLIVE), ("dy", DY)]:
print(f"\n######## refresh profiles {label} ########", flush=True)
c = connect(host)
print(run(c, REFRESH, timeout=300), flush=True)
c.close()
print("ALL_DONE", flush=True)