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

141 lines
4.4 KiB
Python

# -*- coding: utf-8 -*-
"""Inspect Shorts dups + yt_long orphans on physical; safe-clean unused ones."""
from __future__ import annotations
import json
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
PASS = "4669805"
REMOTE = r'''
import sqlite3, json, time
p="/opt/douyinWEB/backend/data/monitor.db"
con=sqlite3.connect(p)
con.row_factory=sqlite3.Row
def dump(sql, args=()):
return [dict(r) for r in con.execute(sql, args)]
dup_yt = "UCjQ8jnBm2N4FGRowNXcXThw"
print("=== asian streetfood cards ===")
cards = dump("""
SELECT id, name, youtube_channel_id, enabled,
CASE WHEN refresh_token IS NOT NULL AND length(trim(refresh_token))>0 THEN 1 ELSE 0 END AS has_rt,
oauth_email, updated_at, created_at
FROM shorts_channels WHERE youtube_channel_id=?
""", (dup_yt,))
print(json.dumps(cards, ensure_ascii=False, indent=2))
ids = [c["id"] for c in cards]
print("=== assign groups for these pks ===")
if ids:
q=",".join("?"*len(ids))
print(json.dumps(dump(
f"SELECT id,name,channel_pk,youtube_channel_id,neko_instance_id,enabled FROM yt_assign_groups WHERE channel_pk IN ({q})",
ids), ensure_ascii=False, indent=2))
print("=== shorts jobs by channel (pending/running) ===")
if ids:
q=",".join("?"*len(ids))
print(json.dumps(dump(
f"""SELECT channel_pk, status, COUNT(*) n FROM shorts_jobs
WHERE channel_pk IN ({q}) GROUP BY channel_pk, status""",
ids), ensure_ascii=False, indent=2))
orphans = [
"08a7a072-8c98-43ea-8488-b1db971c5d27",
"cf0c1355-7586-418c-927a-df4762de5774",
]
print("=== yt_long orphan detail + jobs ===")
for oid in orphans:
row = dump("SELECT id,name,youtube_channel_id,source_shorts_channel_pk,enabled FROM yt_long_channels WHERE id=?", (oid,))
jobs = dump("""SELECT status, COUNT(*) n FROM yt_long_jobs WHERE channel_pk=? GROUP BY status""", (oid,))
print(json.dumps({"channel": row, "jobs": jobs}, ensure_ascii=False))
# Decide cleanup:
# Keep asian streetfood card with refresh_token; if both have, keep newer updated_at.
# Delete the other only if not referenced by yt_assign_groups.
keep = None
drop = None
with_rt = [c for c in cards if c.get("has_rt")]
if len(with_rt) == 1:
keep = with_rt[0]["id"]
elif cards:
keep = sorted(cards, key=lambda c: float(c.get("updated_at") or 0), reverse=True)[0]["id"]
if keep:
drop = [c["id"] for c in cards if c["id"] != keep]
assigned = set()
if drop:
q=",".join("?"*len(drop))
assigned = {r["channel_pk"] for r in dump(
f"SELECT channel_pk FROM yt_assign_groups WHERE channel_pk IN ({q})", drop)}
print("=== cleanup plan ===")
print(json.dumps({"keep": keep, "drop": drop, "assigned_block": list(assigned)}, ensure_ascii=False))
deleted = {"shorts": [], "yt_long": []}
for pk in drop or []:
if pk in assigned:
print("skip shorts", pk, "still in assign group")
continue
con.execute("DELETE FROM shorts_channels WHERE id=?", (pk,))
deleted["shorts"].append(pk)
for oid in orphans:
jobs = dump("""SELECT COUNT(*) n FROM yt_long_jobs WHERE channel_pk=? AND status IN ('pending','running','uploading','recording')""", (oid,))
active = int(jobs[0]["n"] if jobs else 0)
if active:
print("skip yt_long", oid, "active jobs", active)
continue
con.execute("DELETE FROM yt_long_channels WHERE id=?", (oid,))
deleted["yt_long"].append(oid)
con.commit()
print("=== deleted ===")
print(json.dumps(deleted, ensure_ascii=False))
print("DONE")
'''
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for i in range(8):
try:
c.connect(
"107.173.30.245",
4014,
"eric",
PASS,
timeout=60,
banner_timeout=120,
allow_agent=False,
look_for_keys=False,
)
break
except Exception as ex:
print("ssh", i, type(ex).__name__, flush=True)
time.sleep(2 + i)
else:
raise SystemExit("ssh failed")
sftp = c.open_sftp()
with sftp.file("/tmp/_clean_dups_physical.py", "w") as f:
f.write(REMOTE)
sftp.close()
_, o, e = c.exec_command(
f"echo '{PASS}' | sudo -S -p '' python3 /tmp/_clean_dups_physical.py",
timeout=60,
)
print((o.read() + e.read()).decode("utf-8", "replace"), flush=True)
c.close()
if __name__ == "__main__":
main()