169 lines
6.2 KiB
Python
169 lines
6.2 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Deploy Shorts YouTube API cool-down (1h after 429, ntfy once) to phys+VPS."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sys
|
|
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/shorts_yt_quota.py",
|
|
"backend/app/shorts_pipeline.py",
|
|
"backend/app/db.py",
|
|
"backend/tests/test_shorts_yt_quota.py",
|
|
]
|
|
|
|
REMOTE = r'''#!/bin/bash
|
|
set -euo pipefail
|
|
ROOT=/opt/douyinWEB
|
|
i=0
|
|
while [ -f "/tmp/_dy_cool_${i}.path" ]; do
|
|
rel=$(cat "/tmp/_dy_cool_${i}.path")
|
|
dst="$ROOT/$rel"
|
|
mkdir -p "$(dirname "$dst")"
|
|
python3 -c "from pathlib import Path; p=Path('/tmp/_dy_cool_${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
|
|
|
|
python3 <<'PY' || true
|
|
import sqlite3, json, time
|
|
from pathlib import Path
|
|
dbp = Path("/opt/douyinWEB/backend/data/monitor.db")
|
|
if not dbp.is_file():
|
|
print("no_db")
|
|
else:
|
|
conn = sqlite3.connect(str(dbp))
|
|
row = conn.execute("SELECT value FROM kv_settings WHERE key=?", ("shorts_yt_quota_cooldown_sec",)).fetchone()
|
|
if not row:
|
|
conn.execute(
|
|
"INSERT INTO kv_settings(key,value) VALUES(?,?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
("shorts_yt_quota_cooldown_sec", "3600"),
|
|
)
|
|
conn.commit()
|
|
print("inserted shorts_yt_quota_cooldown_sec=3600")
|
|
else:
|
|
print("shorts_yt_quota_cooldown_sec=", row[0])
|
|
try:
|
|
now = time.time()
|
|
recent = conn.execute(
|
|
"SELECT COUNT(*) FROM shorts_jobs j "
|
|
"JOIN shorts_channels c ON c.id = j.channel_pk "
|
|
"WHERE UPPER(TRIM(COALESCE(c.oauth_profile_id,''))) = 'B' "
|
|
"AND j.error LIKE '%429%' AND j.updated_at > ?",
|
|
(now - 3600,),
|
|
).fetchone()[0]
|
|
print("recent_B_429_jobs", recent)
|
|
if recent >= 1:
|
|
raw = conn.execute("SELECT value FROM kv_settings WHERE key=?", ("shorts_yt_quota_by_profile",)).fetchone()
|
|
qmap = {}
|
|
if raw and raw[0]:
|
|
try:
|
|
qmap = json.loads(raw[0])
|
|
if not isinstance(qmap, dict):
|
|
qmap = {}
|
|
except Exception:
|
|
qmap = {}
|
|
entry = dict(qmap.get("B") or {})
|
|
until = max(float(entry.get("blocked_until") or 0), now + 3600)
|
|
# Must set Pacific date or _sync_profile_entry clears blocked_until
|
|
from datetime import datetime, timezone, timedelta
|
|
pt = datetime.fromtimestamp(now, tz=timezone(timedelta(hours=-7))).strftime("%Y-%m-%d")
|
|
entry.update({
|
|
"blocked_until": until,
|
|
"quota_ntfy_at": float(entry.get("quota_ntfy_at") or now),
|
|
"date": pt,
|
|
"count": int(entry.get("count") or 90),
|
|
})
|
|
qmap["B"] = entry
|
|
payload = json.dumps(qmap, ensure_ascii=False)
|
|
conn.execute(
|
|
"INSERT INTO kv_settings(key,value) VALUES(?,?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
("shorts_yt_quota_by_profile", payload),
|
|
)
|
|
conn.commit()
|
|
print("armed_B_cooldown_until", until)
|
|
except Exception as e:
|
|
print("arm_err", e)
|
|
conn.close()
|
|
PY
|
|
|
|
systemctl restart douyinweb-api.service
|
|
sleep 6
|
|
systemctl is-active douyinweb-api.service
|
|
|
|
grep -nE 'mark_api_quota_cooldown|DEFAULT_API_COOLDOWN|blocked_profile_ids|冷静约' \
|
|
"$ROOT/backend/app/shorts_yt_quota.py" "$ROOT/backend/app/shorts_pipeline.py" | head -25
|
|
|
|
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_cool_{i}.bin", "wb") as f:
|
|
f.write(data)
|
|
with sftp.file(f"/tmp/_dy_cool_{i}.path", "w") as f:
|
|
f.write(rel.replace("\\", "/"))
|
|
with sftp.file("/tmp/_dy_cool_remote.sh", "w") as f:
|
|
f.write(REMOTE.replace("\r\n", "\n"))
|
|
sftp.close()
|
|
cmd = f"echo '{pw}' | sudo -S -p '' bash /tmp/_dy_cool_remote.sh" if sudo else "bash /tmp/_dy_cool_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,
|
|
"blocked=", st.get("upload_quota_blocked"),
|
|
"until=", st.get("upload_quota_blocked_until"),
|
|
"profiles=", st.get("upload_quota_blocked_profiles"),
|
|
"cooldown_sec=", st.get("yt_quota_cooldown_sec"),
|
|
"by_profile=", [
|
|
{
|
|
"id": p.get("id"),
|
|
"blocked": p.get("blocked"),
|
|
"until": p.get("blocked_until"),
|
|
"used": p.get("used"),
|
|
}
|
|
for p in (st.get("yt_quota_by_profile") or [])
|
|
if p.get("blocked") or p.get("id") in ("A", "B")
|
|
],
|
|
)
|
|
except Exception as exc:
|
|
print(base, "ERR", exc)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
deploy("VPS dylive", "107.173.30.245", 22, "root", "Xiao4669805", sudo=False)
|
|
deploy("phys dy", "107.173.30.245", 4014, "eric", "4669805", sudo=True)
|
|
print("\n===== public =====")
|
|
pub("https://dylive.nomadro.com")
|
|
pub("https://dy.nomadro.com")
|
|
print("done")
|