Files

155 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""th_sync_vps.py — sync new TokenHarbor keys from tokenharbor_keys.txt to VPS new-api.
For each key not yet deployed (tracked in th_vps_deployed.json):
- create channel th-pool-NN (one key per channel) with all free+paid models
- insert abilities rows
- restart new-api once at the end
Run from the project dir with Python 3.11 (needs paramiko? no - uses scp/ssh CLI).
"""
# __portable_paths__ (auto-injected: portable, env-overridable paths)
import os as _pos, sys as _psys
from pathlib import Path as _PPath
_ROOT = _PPath(__file__).resolve().parent
_REPO = _ROOT
for _ in range(4):
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
break
if _REPO.parent == _REPO:
break
_REPO = _REPO.parent
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
try:
_DATA.mkdir(parents=True, exist_ok=True)
_WORK.mkdir(parents=True, exist_ok=True)
except Exception:
pass
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
def _d(name, env=None):
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
if env and _pos.environ.get(env):
return _PPath(_pos.environ[env])
return _DATA / name
def _w(name=""):
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
return (_WORK / name) if name else _WORK
# --- end portable prelude ---
import json, sqlite3, subprocess, time, os, sys
from pathlib import Path
PROJ = Path(str(_d("Desktop/_PROJECTS/авторег проект")))
KEYS_FILE = PROJ / "tokenharbor_keys.txt"
DEPLOYED = PROJ / "th_vps_deployed.json"
SSH = ["ssh", "-i", os.path.expanduser("~/.ssh/id_ed25519"), "root@YOUR_VPS_IP"]
MODELS = ("mimo-v2.6-flash:free,mimo-v2.5:free,deepseek-v4.1-flash:free,deepseek-v4-flash:free,"
"claude-haiku-5.5:free,th-rudder:free,grok-4.7,claude-opus-5.5,glm-5.3,kimi-k3,"
"gemini-3.8-flash,claude-fable-5.1,deepseek-v4-pro,qwen3.8-max,gpt-6-luna,gpt-6-astra,"
"gpt-6.1-sol,apex,th-orchestra,th-rudder,mimo-v2.6-pro,claude-sonnet-5.5,mistral-large-4,"
"qwen3.8-27b,qwen3.8-flash,glm-5.3-flash,gpt-6.1-sol,muse-spark-1-3,mimo-v2.5-pro")
def load_deployed():
if DEPLOYED.exists():
return json.loads(DEPLOYED.read_text())
return {"keys": []}
def main():
lines = KEYS_FILE.read_text(encoding="utf-8").strip().splitlines()
keys = []
for l in lines:
parts = [p.strip() for p in l.split("|")]
if len(parts) >= 2 and parts[1].startswith("thk_live_"):
keys.append((parts[0], parts[1]))
dep = load_deployed()
done = set(dep["keys"])
fresh = [(e, k) for e, k in keys if k not in done]
if not fresh:
print("nothing new to deploy; total deployed:", len(done))
return
print(f"deploying {len(fresh)} new keys (total in file: {len(keys)})")
payload = json.dumps({"fresh": [{"email": e, "key": k} for e, k in fresh], "models": MODELS})
tmp = Path(os.environ.get("TMPDIR", ".")) / "th_sync_payload.json"
tmp.write_text(payload, encoding="utf-8")
r = subprocess.run(["scp", "-i", os.path.expanduser("~/.ssh/id_ed25519"), str(tmp), "root@YOUR_VPS_IP:/tmp/th_sync_payload.json"], capture_output=True, text=True)
if r.returncode != 0:
print("SCP FAIL:", r.stderr[:200]); return
remote = r'''
import json, sqlite3, time, urllib.request
from concurrent.futures import ThreadPoolExecutor
d = json.load(open("/tmp/th_sync_payload.json"))
models = "claude-haiku-5.5,mimo-v2.6-flash,mimo-v2.5,deepseek-v4.1-flash-th,deepseek-v4-flash-th"
mapping = json.dumps({
"claude-haiku-5.5": "claude-haiku-5.5:free",
"mimo-v2.6-flash": "mimo-v2.6-flash:free",
"mimo-v2.5": "mimo-v2.5:free",
"deepseek-v4.1-flash-th": "deepseek-v4.1-flash:free",
"deepseek-v4-flash-th": "deepseek-v4-flash:free",
})
fresh = d["fresh"]
def alive(item):
k = item["key"].strip()
try:
req = urllib.request.Request("https://tokenharbor.ai/v1/models",
headers={"Authorization": ("B"+"earer ") + k})
urllib.request.urlopen(req, timeout=20).read()
return True
except Exception:
return False
with ThreadPoolExecutor(max_workers=12) as ex:
keep = [it for it, ok in zip(fresh, ex.map(alive, fresh)) if ok]
print("valid keys:", len(keep), "of", len(fresh))
db = sqlite3.connect("/opt/grok-gateway/new-api/one-api.db", timeout=60)
db.execute("PRAGMA busy_timeout=60000")
now = int(time.time())
row = db.execute("SELECT COUNT(*) FROM channels WHERE tag='tokenharbor'").fetchone()[0]
created = []
for i, item in enumerate(keep):
k = item["key"].strip()
exists = db.execute("SELECT id FROM channels WHERE instr(key, ?) > 0", (k,)).fetchone()
if exists:
continue
idx = row + i + 1
db.execute('INSERT INTO channels (type,key,status,name,weight,created_time,base_url,models,"group",model_mapping,priority,auto_ban,tag,other,setting,status_code_mapping) VALUES (1,?,1,?,10,?,?,?,"default",?,0,0,"tokenharbor","[{}]","{}","")',
(k, "th-pool-%03d" % idx, now, "https://tokenharbor.ai", models, mapping))
cid = db.execute("SELECT last_insert_rowid()").fetchone()[0]
for m in models.split(","):
db.execute('INSERT OR IGNORE INTO abilities ("group", model, channel_id, enabled, priority, weight, tag) VALUES ("default", ?, ?, 1, 0, 10, "tokenharbor")', (m, cid))
created.append((cid, k))
db.commit()
print("created", len(created), "channels:", [c[0] for c in created][:5], "..." if len(created) > 5 else "")
json.dump([k for _, k in created], open("/tmp/th_sync_created.json", "w"))
total = db.execute("SELECT COUNT(*) FROM channels WHERE tag='tokenharbor' AND status=1").fetchone()[0]
print("TH pool active:", total)
'''
r2 = subprocess.run(SSH + ["bash", "-c", "systemctl stop new-api; python3 -; systemctl start new-api"], input=remote, capture_output=True, text=True)
out = (r2.stdout or "") + (r2.stderr or "")
print("REMOTE:", out.strip()[:300])
if "created" not in out:
print("remote deploy failed, not marking deployed"); return
# fetch created keys list
r3 = subprocess.run(SSH + ["cat", "/tmp/th_sync_created.json"], capture_output=True, text=True)
try:
created_keys = json.loads(r3.stdout)
except Exception:
created_keys = [k for _, k in fresh]
dep["keys"] = sorted(set(dep["keys"]) | set(created_keys))
DEPLOYED.write_text(json.dumps(dep, indent=1))
print("deployed total now:", len(dep["keys"]))
r4 = subprocess.run(SSH + ["systemctl", "restart", "new-api"], capture_output=True, text=True)
time.sleep(6)
r5 = subprocess.run(SSH + ["systemctl", "is-active", "new-api"], capture_output=True, text=True)
print("new-api:", r5.stdout.strip())
if __name__ == "__main__":
main()