Files

104 lines
4.1 KiB
Python
Executable File

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""sync_tokvi.py — банк токви с фермы -> прод iishko: новые каналы, status, abilities, model_limits.
Запуск на ферме (отдельный VPS с root-SSH). Идемпотентно, печатает 'new keys: 0' когда нечего делать.
"""
import json
import os
import subprocess
import sys
BANK = "/root/tokvi/bank.jsonl"
PROD_KEYS = "/root/tokvi_keys.json"
SSHPROD = "/root/sshprod.sh"
MODELS = ("claude-opus-5,claude-opus-4-8,claude-fable-5,claude-fable-5-1,claude-sonnet-5,"
"gpt-6-astra,gpt-6.1-terra,gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna,grok-4.6,gpt-5.5")
GROUPS = ["default", "premium", "t1", "t2", "t3", "t4"]
PRIO = 650
def prod(cmd, timeout=900):
p = subprocess.run(["bash", SSHPROD, cmd], capture_output=True, text=True, timeout=timeout)
return p.returncode, (p.stdout or "") + (p.stderr or "")
def main():
apply = "--apply" in sys.argv
bank = []
if os.path.exists(BANK):
for l in open(BANK, encoding="utf-8", errors="replace"):
l = l.strip()
if not l.startswith("{"):
continue
try:
r = json.loads(l)
except Exception:
continue
if r.get("key"):
bank.append(r)
if not bank:
print("new keys: 0 (bank empty)")
return
rc, out = prod("cat %s 2>/dev/null" % PROD_KEYS)
try:
cur = json.loads(out)
except Exception:
cur = []
have = {x["key"] for x in cur if x.get("key")}
new = [b for b in bank if b["key"] not in have]
if not new:
print("new keys: 0")
return
print("new keys: %d (bank %d, prod %d)" % (len(new), len(bank), len(have)))
if not apply:
return
nxt = 1
for x in cur:
try:
nxt = max(nxt, int(x["name"].split("-")[1]) + 1)
except Exception:
pass
for b in new:
cur.append({"name": "tokvi-%02d" % nxt, "key": b["key"], "mail": b.get("mail", "")})
nxt += 1
payload = json.dumps(cur, ensure_ascii=False)
rc, out = prod("cat > %s <<'EOFJSON'\n%s\nEOFJSON\necho WROTE; wc -c %s" % (PROD_KEYS, payload, PROD_KEYS))
print("write:", out.strip().splitlines()[-1:])
py = r'''
import sqlite3
DB="/opt/grok-gateway/new-api/one-api.db"
MODELS="%s".split(",")
GROUPS=%s
PRIO=%d
con=sqlite3.connect(DB,timeout=300); con.execute("pragma busy_timeout=300000"); cur=con.cursor()
cur.execute("update channels set status=1, auto_ban=0, priority=? where name like 'tokvi-%%'", (PRIO,))
cids=[r[0] for r in cur.execute("select id from channels where name like 'tokvi-%%'").fetchall()]
for cid in cids:
for m in MODELS:
for g in GROUPS:
cur.execute("""insert into abilities ("group",model,channel_id,enabled,priority,weight,tag)
values (?,?,?,1,?,1,'tokvi') on conflict("group",model,channel_id) do update set enabled=1,priority=?,weight=1""",(g,m,cid,PRIO,PRIO))
patched=0
for tid,ml in cur.execute("select id,coalesce(model_limits,'') from tokens where status=1").fetchall():
have=[x for x in ml.split(",") if x]; need=[m for m in MODELS if m not in have]
if need:
cur.execute("update tokens set model_limits=? where id=?",(",".join(have+need),tid)); patched+=1
cur.execute("update users set quota = used_quota + 20000000000 where quota - used_quota < 2000000000")
con.commit()
print("tokvi channels:", cur.execute("select status,count(*) from channels where name like 'tokvi-%%' group by 1").fetchall())
print("abilities:", cur.execute("select a.model,a.enabled,count(*) from abilities a join channels c on c.id=a.channel_id where c.tag='tokvi' group by 1,2").fetchall())
print("tokens patched:", patched)
con.close()
''' % (MODELS, GROUPS, PRIO)
rc, out = prod("python3 - <<'PYEOF'\n%s\nPYEOF" % py)
print("heal:", out.strip().replace("\n", " ")[:400])
rc, out = prod("systemctl restart new-api; sleep 8; systemctl is-active new-api")
print("restart:", out.strip())
if __name__ == "__main__":
main()