Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
147 lines
6.3 KiB
Python
147 lines
6.3 KiB
Python
import ast
|
|
from contextlib import closing
|
|
import os
|
|
from pathlib import Path
|
|
import sqlite3
|
|
from threading import Lock
|
|
import time
|
|
|
|
import gateway_commerce
|
|
|
|
_CACHE = {}
|
|
_LOCK = Lock()
|
|
_CONSTANTS = {'TIER_MODELS', 'IMG_MODELS', 'IMG_ALWAYS', 'VID_MODELS', 'MUS_MODELS',
|
|
'MODEL_ALIASES', 'T4_ALIASES', 'MODEL_DESCS', 'BADGES', 'RANK_REFS',
|
|
'BG_IMG_MODELS', 'REF_NEW_ID_MIN', 'PROMO_ACTIVE_UNTIL'}
|
|
|
|
|
|
def _source():
|
|
explicit = os.environ.get('IISHKO_BOT_SOURCE')
|
|
if explicit:
|
|
return Path(explicit)
|
|
root = Path(os.environ.get('IISHKO_APP_ROOT', Path(__file__).resolve().parent))
|
|
return root / 'grok_bot.py'
|
|
|
|
|
|
def _literal(node, constants):
|
|
if isinstance(node, ast.Name):
|
|
if node.id not in constants:
|
|
raise ValueError('unknown catalogue constant')
|
|
return constants[node.id]
|
|
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
left, right = _literal(node.left, constants), _literal(node.right, constants)
|
|
if type(left) not in (list, tuple) or type(right) is not type(left):
|
|
raise ValueError('invalid catalogue concatenation')
|
|
return left + right
|
|
return ast.literal_eval(node)
|
|
|
|
|
|
def _catalogue():
|
|
source = _source()
|
|
stat = source.stat()
|
|
key = (str(source.resolve()), stat.st_mtime_ns, stat.st_size)
|
|
with _LOCK:
|
|
if _CACHE.get('key') == key:
|
|
return _CACHE['data']
|
|
tree = ast.parse(source.read_text(encoding='utf-8'))
|
|
result = {}
|
|
for node in tree.body:
|
|
if isinstance(node, ast.Assign):
|
|
names = [target.id for target in node.targets
|
|
if isinstance(target, ast.Name) and target.id in _CONSTANTS]
|
|
if names:
|
|
try:
|
|
value = _literal(node.value, result)
|
|
except (ValueError, TypeError):
|
|
if any(name in {'TIER_MODELS', 'BADGES', 'RANK_REFS'} for name in names):
|
|
raise
|
|
continue
|
|
for name in names:
|
|
result[name] = value
|
|
if not {'TIER_MODELS', 'BADGES', 'RANK_REFS'} <= result.keys():
|
|
raise ValueError('trusted rank catalogue is unavailable')
|
|
tiers = result['TIER_MODELS']
|
|
if not isinstance(tiers, dict) or set(tiers) != {1, 2, 3, 4}:
|
|
raise ValueError('invalid trusted rank catalogue')
|
|
if any(not isinstance(models, (list, tuple)) or any(not isinstance(model, str) for model in models)
|
|
for models in tiers.values()):
|
|
raise ValueError('invalid trusted model catalogue')
|
|
_CACHE.update(key=key, data=result)
|
|
return result
|
|
|
|
|
|
def _rank(con, uid, user, constants, now):
|
|
env_admins = {int(value) for value in os.environ.get('IISHKO_ADMIN_IDS', '').split(',') if value.strip().isdigit()}
|
|
if uid in env_admins or user.get('admin'):
|
|
return 4
|
|
days = max(0, (now - int(user.get('created') or 0)) // 86400) if user.get('created') else 0
|
|
refs = con.execute('SELECT COALESCE(SUM(CASE WHEN tg_id>=? THEN 0.5 ELSE 1.0 END),0) '
|
|
'FROM users WHERE referred_by=? AND ref_awarded=1',
|
|
(constants.get('REF_NEW_ID_MIN', 9_000_000_000), uid)).fetchone()[0]
|
|
rank = 1
|
|
for level in (2, 3, 4):
|
|
_, _, rep, age = constants['BADGES'][level]
|
|
if days >= age and (refs >= constants['RANK_REFS'][level] or rep and (user.get('rep') or 0) >= rep):
|
|
rank = level
|
|
if rank < 2 and now < constants.get('PROMO_ACTIVE_UNTIL', 0):
|
|
rank = 2
|
|
floor, until = int(user.get('badge_lock') or 0), int(user.get('badge_until') or 0)
|
|
if floor and (until == 0 or now < until):
|
|
rank = max(rank, min(4, max(1, floor)))
|
|
return rank
|
|
|
|
|
|
def base_models(bot_db, uid):
|
|
if type(uid) is not int or not 0 < uid <= 9223372036854775807:
|
|
return []
|
|
constants = _catalogue()
|
|
uri = Path(bot_db).resolve().as_uri() + '?mode=ro'
|
|
with closing(sqlite3.connect(uri, uri=True, timeout=8)) as con:
|
|
con.row_factory = sqlite3.Row
|
|
con.execute('PRAGMA query_only=ON')
|
|
row = con.execute('SELECT * FROM users WHERE tg_id=?', (uid,)).fetchone()
|
|
if row is None:
|
|
return []
|
|
user = dict(row)
|
|
if user.get('banned') or user.get('api_blocked'):
|
|
return []
|
|
tier = _rank(con, uid, user, constants, int(time.time()))
|
|
tiers = constants['TIER_MODELS']
|
|
models = [model for level in range(1, tier + 1) for model in tiers[level]]
|
|
images = list(constants.get('IMG_MODELS', ())) + list(constants.get('IMG_ALWAYS', ()))
|
|
media = set(images + list(constants.get('VID_MODELS', ())) + list(constants.get('MUS_MODELS', ())))
|
|
models += images
|
|
for alias in constants.get('MODEL_ALIASES', ()):
|
|
ranks = [level for level, names in tiers.items() if alias in names]
|
|
if alias in media or ranks and min(ranks) <= tier:
|
|
models.append(alias)
|
|
if tier >= 4:
|
|
models += list(constants.get('T4_ALIASES', ()))
|
|
descriptions = constants.get('MODEL_DESCS', {})
|
|
models += sorted({model.replace('.', '-') for model in models if '.' in model} & set(descriptions))
|
|
return list(dict.fromkeys(models))
|
|
|
|
|
|
def public_models():
|
|
"""Current operator catalogue, independent of a user's rank or stale token."""
|
|
constants = _catalogue()
|
|
names = {name for models in constants['TIER_MODELS'].values() for name in models}
|
|
for key in ('T4_ALIASES', 'IMG_MODELS', 'IMG_ALWAYS'):
|
|
names.update(constants.get(key, ()))
|
|
names.update(name.replace('.', '-') for name in tuple(names)
|
|
if name.replace('.', '-') in constants.get('MODEL_DESCS', {}))
|
|
return frozenset(names)
|
|
|
|
|
|
def allowed(bot_db, uid, model, token_models, default_allowed):
|
|
try:
|
|
if model not in public_models():
|
|
# Non-managed name: retain the existing token gate.
|
|
return bool(default_allowed)
|
|
# Managed catalogue model: re-derive from the authoritative rank catalogue
|
|
# plus *active* passes. base_models/model_access read fresh state and raise
|
|
# on any inconsistency, which the handler below turns into a rejection.
|
|
return gateway_commerce.model_access(bot_db, uid, model, base_models(bot_db, uid))
|
|
except (OSError, ValueError, TypeError, KeyError, sqlite3.Error, SyntaxError):
|
|
return False
|