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

129 lines
4.7 KiB
Python

# -*- coding: utf-8 -*-
"""Deploy Shorts quota rules (1 room→1 ch, ≥10min gap, Beijing min fill) to phys+VPS."""
from __future__ import annotations
import json
import sys
import time
import http.cookiejar
import urllib.request
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
FILES = [
"backend/app/db.py",
"backend/app/shorts_schedule.py",
"backend/app/shorts_pipeline.py",
"backend/tests/test_shorts_gap_rules.py",
]
REMOTE = r"""#!/bin/bash
set -euo pipefail
ROOT=/opt/douyinWEB
i=0
while [ -f "/tmp/_dy_sq_${i}.path" ]; do
rel=$(cat "/tmp/_dy_sq_${i}.path")
dst="$ROOT/$rel"
mkdir -p "$(dirname "$dst")"
python3 -c "from pathlib import Path; p=Path('/tmp/_dy_sq_${i}.bin'); d=Path('$dst'); d.write_bytes(p.read_bytes().replace(b'\r\n',b'\n').replace(b'\r',b'\n')); print('ok', d)"
i=$((i+1))
done
systemctl restart douyinweb-api.service
sleep 6
systemctl is-active douyinweb-api.service
# Apply gap settings (operator rule) without touching room/channel business rows.
python3 <<'PY'
import json, urllib.request
# Update via local settings API if possible — else direct sqlite
try:
import sqlite3
from pathlib import Path
dbp = Path('/opt/douyinWEB/backend/data/monitor.db')
if dbp.is_file():
conn = sqlite3.connect(str(dbp))
conn.row_factory = sqlite3.Row
for k,v in [('shorts_channel_min_gap_sec','600'),('shorts_upload_min_gap_sec','600')]:
row = conn.execute('SELECT value FROM settings WHERE key=?', (k,)).fetchone()
if row:
conn.execute('UPDATE settings SET value=? WHERE key=?', (v,k))
else:
try:
conn.execute('INSERT INTO settings(key,value) VALUES(?,?)', (k,v))
except Exception:
pass
conn.commit()
# show shorts enabled + gaps
keys=('shorts_enabled','shorts_channel_min_gap_sec','shorts_upload_min_gap_sec','shorts_dedupe_room_day')
for k in keys:
r=conn.execute('SELECT value FROM settings WHERE key=?',(k,)).fetchone()
print('setting', k, r['value'] if r else None)
# today quota summary via python import if path works
conn.close()
except Exception as e:
print('settings_err', e)
PY
grep -nE 'CHANNEL_GAP_FLOOR|daily_min first|shorts_channel_last_slot|CHANNEL_GAP_FLOOR_SEC' \
"$ROOT/backend/app/shorts_schedule.py" "$ROOT/backend/app/shorts_pipeline.py" "$ROOT/backend/app/db.py" | head -20
curl -sS -m 5 http://127.0.0.1:8014/api/ping; echo
"""
def deploy(label, host, port, user, pw, *, sudo):
print(f"\n===== {label} =====")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(host, port, user, pw, timeout=45, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for i, rel in enumerate(FILES):
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n")
with sftp.file(f"/tmp/_dy_sq_{i}.bin", "wb") as f:
f.write(data)
with sftp.file(f"/tmp/_dy_sq_{i}.path", "w") as f:
f.write(rel.replace("\\", "/"))
with sftp.file("/tmp/_dy_sq_remote.sh", "w") as f:
f.write(REMOTE.replace("\r\n", "\n"))
sftp.close()
cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_sq_remote.sh" if sudo else "bash /tmp/_dy_sq_remote.sh"
_, o, e = c.exec_command(cmd, timeout=180)
print((o.read() + e.read()).decode("utf-8", "replace"))
c.close()
def pub(base):
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
data = json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode()
req = urllib.request.Request(
base + "/api/auth/login", data=data, method="POST", headers={"Content-Type": "application/json"}
)
try:
op.open(req, timeout=30)
with op.open(urllib.request.Request(base + "/api/shorts/status"), timeout=40) as r:
st = json.loads(r.read().decode())
print(
base,
"enabled=", st.get("enabled"),
"channel_gap=", st.get("channel_min_gap_sec"),
"upload_gap=", st.get("upload_min_gap_sec"),
"min_unmet=", (st.get("board") or {}).get("min_unmet"),
"gap=", (st.get("board") or {}).get("total_gap"),
)
except Exception as exc:
print(base, "ERR", exc)
deploy("phys", "107.173.30.245", 4014, "eric", "4669805", sudo=True)
deploy("vps", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False)
time.sleep(3)
print("\n===== public =====")
for b in ("https://dy.nomadro.com", "https://dylive.nomadro.com"):
pub(b)
print("done")