IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
"""Read-only account-wide daily request metadata shared by both API protocols."""
|
||||
from contextlib import closing
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
_OWNER = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z")
|
||||
DEFAULT_REQUEST_LIMITS = {0: 5000, 1: 5000, 2: 10000, 3: 20000, 4: 30000}
|
||||
MSK = timezone(timedelta(hours=3))
|
||||
|
||||
|
||||
def _read(path):
|
||||
con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=3)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
return con
|
||||
|
||||
|
||||
def daily_snapshot(newapi_db, bot_db, raw_key, *, now=None, limits=None, entitlement_reader=None):
|
||||
now = int(time.time()) if now is None else int(now)
|
||||
moment = datetime.fromtimestamp(now, MSK)
|
||||
day = moment.date().isoformat()
|
||||
reset = int(datetime.combine(moment.date() + timedelta(days=1), datetime.min.time(), MSK).timestamp())
|
||||
with closing(_read(newapi_db)) as con:
|
||||
tokens = con.execute("SELECT name FROM tokens WHERE key=? AND deleted_at IS NULL", (raw_key,)).fetchall()
|
||||
if len(tokens) != 1:
|
||||
return None
|
||||
match = _OWNER.fullmatch(tokens[0]["name"] or "")
|
||||
if not match:
|
||||
return None
|
||||
uid = int(match[1])
|
||||
if uid > 9223372036854775807:
|
||||
return None
|
||||
with closing(_read(bot_db)) as con:
|
||||
user = con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone()
|
||||
if user is None:
|
||||
return None
|
||||
columns = set(user.keys())
|
||||
if not {"quota_date", "chat_count", "rank_cache"}.issubset(columns):
|
||||
raise sqlite3.DatabaseError("daily request counters are unavailable")
|
||||
def value(key, default=0):
|
||||
return user[key] if key in columns and user[key] is not None else default
|
||||
unlimited = bool(value("vip") or value("admin") or int(value("unlim_until")) > now)
|
||||
locked = int(value("badge_lock")) if not value("badge_until") or int(value("badge_until")) > now else 0
|
||||
rank = min(4, max(0, locked, int(value("rank_cache", 1))))
|
||||
configured = DEFAULT_REQUEST_LIMITS if limits is None else limits
|
||||
base = configured.get(rank, configured.get(1, 5000))
|
||||
if type(base) is not int or base < 0:
|
||||
raise ValueError("invalid daily request limit")
|
||||
used = max(0, int(value("chat_count"))) if value("quota_date") == day else 0
|
||||
extra = 0
|
||||
if entitlement_reader is not None:
|
||||
extra = entitlement_reader(bot_db, uid, now=now).get("extra_requests", 0)
|
||||
if type(extra) is not int or extra < 0:
|
||||
raise ValueError("invalid extra request entitlement")
|
||||
limit = base + extra
|
||||
return {"scope": "account", "period": "day", "timezone": "Europe/Moscow", "date": day,
|
||||
"limit": None if unlimited else limit, "used": used,
|
||||
"remaining": None if unlimited else max(0, limit - used), "reset_at": reset,
|
||||
"unlimited": unlimited, "extra_requests": extra,
|
||||
"note": "Admission attempts count once before forwarding. Provider retries do not consume a second daily request. Model-specific and monetary budgets may also apply."}
|
||||
|
||||
|
||||
def quota_headers(snapshot):
|
||||
if snapshot is None:
|
||||
return {}
|
||||
return {"X-Iishko-Daily-Limit": "unlimited" if snapshot["unlimited"] else str(snapshot["limit"]),
|
||||
"X-Iishko-Daily-Remaining": "unlimited" if snapshot["unlimited"] else str(snapshot["remaining"]),
|
||||
"X-Iishko-Daily-Used": str(snapshot["used"]),
|
||||
"X-Iishko-Daily-Reset": str(snapshot["reset_at"]),
|
||||
"X-Iishko-Daily-Scope": "account", "X-Iishko-Daily-Timezone": "Europe/Moscow"}
|
||||
Reference in New Issue
Block a user