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

145 lines
4.4 KiB
Python

# -*- coding: utf-8 -*-
import json
import time
import sqlite3
import datetime
import sys
DB = "/opt/douyinWEB/backend/data/monitor.db"
BJ = datetime.timezone(datetime.timedelta(hours=8))
conn = sqlite3.connect(DB)
conn.row_factory = sqlite3.Row
def bj(ts):
try:
return datetime.datetime.fromtimestamp(float(ts or 0), BJ).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return str(ts)
def cols(table):
return [r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()]
rows = conn.execute(
"SELECT id,name,category,enabled,neko_instance_id,youtube_channel_id FROM yt_assign_groups WHERE lower(name) LIKE '%nomadvlog%'"
).fetchall()
print("GROUPS", [dict(r) for r in rows])
gids = [r["id"] for r in rows]
gid = gids[0]
print("events cols", cols("events"))
print("yt_relay_states cols", cols("yt_relay_states"))
print("yt_relay_sessions cols", cols("yt_relay_sessions"))
print("sessions cols", cols("sessions")[:30])
st = conn.execute("SELECT * FROM yt_relay_states WHERE group_id=?", (gid,)).fetchone()
print("\n==== STATE ====")
if st:
d = dict(st)
for k in sorted(d.keys()):
if k == "recent_log":
continue
print(f" {k}={d.get(k)}")
log = d.get("recent_log") or ""
if isinstance(log, str) and log.strip().startswith("["):
try:
log = json.loads(log)
except Exception:
pass
if isinstance(log, list):
print("recent_log:")
for line in log[-60:]:
print(" ", line)
else:
print("recent_log_raw", str(log)[-2500:])
else:
print("NO STATE ROW")
# relay sessions history
print("\n==== yt_relay_sessions ====")
try:
rs = conn.execute(
"SELECT * FROM yt_relay_sessions WHERE group_id=? ORDER BY rowid DESC LIMIT 40",
(gid,),
).fetchall()
print("count", len(rs))
for r in rs:
d = dict(r)
print({k: d.get(k) for k in d if k != "recent_log"})
except Exception as e:
print("err", e)
# events schema adaptive
ecols = set(cols("events"))
ts_col = "created_at" if "created_at" in ecols else ("ts" if "ts" in ecols else None)
print("\n==== EVENTS ts_col", ts_col, "====")
if ts_col:
ev = conn.execute(
f"""
SELECT * FROM events
WHERE {ts_col} > ?
AND (
message LIKE '%nomadvlog%'
OR message LIKE '%YouTube 开播%'
OR message LIKE '%YouTube 停播%'
OR IFNULL(room_pk,'') = ?
OR IFNULL(meta,'') LIKE ?
)
ORDER BY {ts_col} DESC LIMIT 150
""",
(time.time() - 36 * 3600, gid, f"%{gid}%"),
).fetchall()
print("events", len(ev))
open_n = close_n = 0
for e in ev:
d = dict(e)
msg = d.get("message") or ""
tsv = d.get(ts_col)
print(bj(tsv), d.get("kind"), msg[:150])
if "开播" in msg and ("nomadvlog" in msg.lower() or d.get("room_pk") == gid):
open_n += 1
if "停播" in msg and ("nomadvlog" in msg.lower() or d.get("room_pk") == gid):
close_n += 1
print("FLAP open", open_n, "close", close_n)
# youtube channel groups table? for monitor
print("\n==== channel_groups / yt status ====")
for t in ("channel_groups", "youtube_channels", "yt_channels"):
if t in {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}:
print("table", t, cols(t)[:25])
# settings
print("\n==== SETTINGS ====")
for k in [
"youtube_relay_enabled",
"youtube_relay_time_slot_mode",
"youtube_relay_exclusive_live",
"youtube_relay_respect_schedule",
"youtube_relay_on_air_deadline_sec",
]:
row = conn.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone()
print(k, row["value"] if row else None)
# schedule
print("\n==== SCHEDULE ====")
sys.path.insert(0, "/opt/douyinWEB/backend")
from app import yt_assign_db
sched = yt_assign_db.build_rotation_schedule(include_urls=False, keyed_only=True)
print("keys", list(sched.keys()))
for c in sched.get("channels") or []:
if "nomadvlog" in str(c.get("name") or "").lower() or c.get("active"):
print(json.dumps(dict(c), ensure_ascii=False, default=str)[:1000])
# shorts channel same YT id?
print("\n==== shorts same UC ====")
uc = rows[0]["youtube_channel_id"]
sc = conn.execute(
"SELECT id,name,enabled,last_status,last_title,last_live_url FROM shorts_channels WHERE youtube_channel_id=?",
(uc,),
).fetchall()
print([dict(x) for x in sc])
conn.close()