Next.js + FastAPI + PocketBase stack for room/session monitoring, cookie sync from sh2, and anti-risk polling defaults. Co-authored-by: Cursor <cursoragent@cursor.com>
183 lines
5.7 KiB
Python
183 lines
5.7 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Parse Desktop/11.txt and import real Douyin rooms (direct SQLite, no PB wait)."""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
import sys
|
||
import time
|
||
from collections import Counter
|
||
from pathlib import Path
|
||
|
||
SRC = Path(r"C:\Users\admin\Desktop\11.txt")
|
||
OUT = Path(r"C:\Users\admin\Desktop\douyinWEB\backend\data\import_rooms.json")
|
||
BACKEND = Path(r"C:\Users\admin\Desktop\douyinWEB\backend")
|
||
|
||
HOST_RE = re.compile(r"(10\.\d+\.\d+\.\d+)\s*(?:\(([A-Za-z])\))?", re.I)
|
||
URL_RE = re.compile(
|
||
r"https://live\.douyin\.com/(\d+)\s*(?:,\s*主播:\s*([^h]*?))?(?=https://live\.douyin\.com/|$)"
|
||
)
|
||
DEMO_ROOM_IDS = {
|
||
"123456789012",
|
||
"234567890123",
|
||
"345678901234",
|
||
"111111111111",
|
||
"222222222222",
|
||
}
|
||
|
||
|
||
def _host_label(m: re.Match[str]) -> str:
|
||
ip = m.group(1)
|
||
lane = (m.group(2) or "").upper()
|
||
return f"{ip}-{lane}" if lane else ip
|
||
|
||
|
||
def parse_rooms(text: str) -> list[dict]:
|
||
host = "unknown"
|
||
bag: dict[str, dict] = {}
|
||
|
||
for raw in text.splitlines():
|
||
line = raw.strip().lstrip("\ufeff")
|
||
if not line:
|
||
continue
|
||
has_url = "live.douyin.com" in line
|
||
hm = HOST_RE.search(line)
|
||
|
||
# host-only lines (skip incomplete fragments like "10.88.")
|
||
if not has_url:
|
||
if hm:
|
||
host = _host_label(hm)
|
||
continue
|
||
|
||
# dense line may start with "10.88.0.5 (B) https://..."
|
||
if hm:
|
||
prefix = line[: hm.start()].strip()
|
||
# only treat as host marker when it appears before the first URL
|
||
if hm.start() < line.find("https://"):
|
||
host = _host_label(hm)
|
||
|
||
for m in URL_RE.finditer(line):
|
||
rid = m.group(1)
|
||
name = (m.group(2) or "").strip()
|
||
name = re.sub(r"\s+", " ", name).strip(" ,,")
|
||
if rid not in bag:
|
||
bag[rid] = {
|
||
"url": f"https://live.douyin.com/{rid}",
|
||
"room_id": rid,
|
||
"name": name,
|
||
"hosts": {host},
|
||
}
|
||
else:
|
||
if name and not bag[rid]["name"]:
|
||
bag[rid]["name"] = name
|
||
bag[rid]["hosts"].add(host)
|
||
|
||
rooms: list[dict] = []
|
||
for item in bag.values():
|
||
hosts = sorted(h for h in item["hosts"] if h and h != "unknown")
|
||
primary = hosts[0] if hosts else "unknown"
|
||
tags = ["真实"]
|
||
for h in hosts:
|
||
tags.append(h)
|
||
rooms.append(
|
||
{
|
||
"url": item["url"],
|
||
"room_id": item["room_id"],
|
||
"name": item["name"],
|
||
"host": primary,
|
||
"hosts": hosts,
|
||
"tags": ",".join(tags),
|
||
}
|
||
)
|
||
rooms.sort(key=lambda r: (r["host"], r["room_id"]))
|
||
return rooms
|
||
|
||
|
||
def main() -> None:
|
||
sys.path.insert(0, str(BACKEND))
|
||
from app import db
|
||
|
||
print("init db...", flush=True)
|
||
db.init_db()
|
||
|
||
text = SRC.read_text(encoding="utf-8-sig")
|
||
rooms = parse_rooms(text)
|
||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||
OUT.write_text(json.dumps(rooms, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
named = sum(1 for r in rooms if r["name"])
|
||
print(f"parsed unique={len(rooms)} named={named}", flush=True)
|
||
print("hosts=", dict(Counter(r["host"] for r in rooms)), flush=True)
|
||
|
||
# Pause monitor traffic while we rewrite the list
|
||
db.update_settings_map(
|
||
{
|
||
"monitor_enabled": False,
|
||
"max_concurrency": 1,
|
||
"min_request_gap_sec": 4.0,
|
||
"request_jitter_sec": 2.5,
|
||
"offline_interval_sec": 300.0,
|
||
"live_interval_sec": 90.0,
|
||
"global_pause_on_risk_sec": 600.0,
|
||
}
|
||
)
|
||
print("monitor paused", flush=True)
|
||
|
||
existing = db.list_rooms(limit=2000).get("rooms") or []
|
||
demo_ids = [
|
||
r["id"]
|
||
for r in existing
|
||
if str(r.get("room_id") or "") in DEMO_ROOM_IDS
|
||
or str(r.get("note") or "").startswith("示例")
|
||
or "demo" in ",".join(r.get("tags") or []).lower()
|
||
]
|
||
if demo_ids:
|
||
db.bulk_rooms("delete", demo_ids)
|
||
print(f"removed_demo={len(demo_ids)}", flush=True)
|
||
|
||
existing = db.list_rooms(limit=2000).get("rooms") or []
|
||
by_rid = {str(r.get("room_id")): r for r in existing}
|
||
|
||
created = 0
|
||
updated = 0
|
||
pks: list[str] = []
|
||
now = time.time()
|
||
|
||
for r in rooms:
|
||
note = r["name"] or r["room_id"]
|
||
tags = r["tags"]
|
||
if r["room_id"] in by_rid:
|
||
pk = by_rid[r["room_id"]]["id"]
|
||
db.update_room(pk, note=note, enabled=True, tags=tags)
|
||
updated += 1
|
||
pks.append(pk)
|
||
else:
|
||
room = db.create_room(r["url"], note=note, enabled=True, tags=tags)
|
||
created += 1
|
||
pks.append(room["id"])
|
||
|
||
# Stagger first checks: ~8s apart after 60s quiet
|
||
with db._lock: # noqa: SLF001
|
||
conn = db._connect() # noqa: SLF001
|
||
try:
|
||
for i, pk in enumerate(pks):
|
||
conn.execute(
|
||
"UPDATE rooms SET next_check_at = ?, updated_at = ?, last_error = '', error_count = 0 WHERE id = ?",
|
||
(now + 60.0 + i * 8.0, now, pk),
|
||
)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
db.update_settings_map({"monitor_enabled": True})
|
||
counts = db.counts()
|
||
print(f"created={created} updated={updated}", flush=True)
|
||
print(f"counts={counts}", flush=True)
|
||
print(f"stagger_minutes≈{(len(pks) * 8) / 60:.1f}", flush=True)
|
||
sample = (db.list_rooms(limit=3).get("rooms") or [])
|
||
for s in sample:
|
||
print("sample", s.get("room_id"), s.get("note"), s.get("tags"), flush=True)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|