#!/usr/bin/env python3 import json import os import sqlite3 import sys import time from pathlib import Path from contextlib import closing from account_limits import account_uid BOT_DB = '/opt/grok-bot/bot.db' NA_DB = '/opt/grok-gateway/new-api/one-api.db' STATE = '/opt/grok-bot/econ_cap_state.json' # Keep this literal compatible with the Mini App's read-only policy parser. DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000} QUOTA_PER_USD = 500000 OWNER_UID = os.environ.get("IISHKO_OWNER_UID", "0").strip() or "0" # owner identity from config; "0" = no owner privilege ST_ENABLED, ST_PAUSED, ST_EXPIRED, ST_EXHAUSTED = 1, 2, 3, 4 def load_state(archive=True): if not os.path.exists(STATE): return {}, 0 try: with open(STATE, encoding='utf-8') as fh: raw = json.load(fh) except Exception: return {}, 0 if not isinstance(raw, dict): return {}, 0 if 'paused' in raw: p = raw.get('paused') or {} return ({k: v for k, v in p.items() if isinstance(v, dict)}, 0) if raw: if archive: try: with open(STATE + '.v1.bak-%d' % int(time.time()), 'w', encoding='utf-8') as fh: json.dump(raw, fh) except Exception: pass return {}, len(raw) return {}, 0 def _levels(now): """Read ranks and all deny flags; a broken/incomplete policy must raise.""" lvl, nogo = {}, set() uri = Path(BOT_DB).resolve().as_uri() + '?mode=ro' with closing(sqlite3.connect(uri, uri=True, timeout=30)) as bot: rows = bot.execute( 'SELECT tg_id,badge_lock,badge_until,rank_cache,' 'COALESCE(banned,0),COALESCE(key_locked,0),COALESCE(api_blocked,0) FROM users' ).fetchall() for uid, lock, until, rank, banned, key_locked, api_blocked in rows: effective = int(lock or 0) if not until or int(until) > now else 0 lvl[str(uid)] = min(4, max(0, effective, int(rank or 0))) if banned or api_blocked or key_locked: nogo.add(str(uid)) return lvl, nogo def _sync_cap_flag(paused, dry): """Only the daily access flag is mutable; never infer a token unlock.""" want = {uid for name in paused if (uid := account_uid(name)) is not None} set_on = set_off = 0 uri = Path(BOT_DB).resolve().as_uri() + ('?mode=ro' if dry else '?mode=rw') with closing(sqlite3.connect(uri, uri=True, timeout=30)) as bot: bot.execute('PRAGMA busy_timeout=30000') if not dry: bot.execute('BEGIN IMMEDIATE') try: cols = {r[1] for r in bot.execute('PRAGMA table_info(users)')} if 'cap_paused' not in cols: if dry: return len(want), 0 bot.execute('ALTER TABLE users ADD COLUMN cap_paused INTEGER DEFAULT 0') have = {int(t): int(c or 0) for t, c in bot.execute('SELECT tg_id,COALESCE(cap_paused,0) FROM users')} for uid, current in have.items(): desired = int(uid in want) if current == desired: continue if desired: set_on += 1 elif current: set_off += 1 if not dry: bot.execute('UPDATE users SET cap_paused=? WHERE tg_id=?', (desired, uid)) if not dry: bot.commit() except BaseException: if not dry: bot.rollback() raise return set_on, set_off def main(argv=None): argv = sys.argv[1:] if argv is None else argv dry = '--dry-run' in argv now = int(time.time()) msk0 = now - ((now + 3 * 3600) % 86400) previous, migrated_v1 = load_state(archive=not dry) lvl, nogo = _levels(now) uri = Path(NA_DB).resolve().as_uri() + '?mode=ro' with closing(sqlite3.connect(uri, uri=True, timeout=60)) as na: na.execute('BEGIN') spent_uid = {} for name, quota in na.execute( 'SELECT token_name,COALESCE(SUM(quota),0) FROM logs ' 'WHERE type=2 AND created_at>=? AND created_at