102 行
4.7 KiB
Python
102 行
4.7 KiB
Python
|
|
"""Persistent chat command quota checks and audit records."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import json
|
||
|
|
from datetime import datetime, timezone
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
from adapters.astrbot_command_adapter import ChatCommandContext
|
||
|
|
from core.audit_service import AuditService
|
||
|
|
from core.identity import RequestContext
|
||
|
|
from database.db_helper import Database, load_database_settings
|
||
|
|
|
||
|
|
|
||
|
|
class ChatCommandGuardService:
|
||
|
|
def __init__(self, database: Database | None = None):
|
||
|
|
self.database = database or Database(load_database_settings())
|
||
|
|
self.audit = AuditService(self.database)
|
||
|
|
|
||
|
|
def check_generation(self, config: dict[str, Any], chat: ChatCommandContext, *, size: str, active_jobs: list[dict[str, Any]]) -> None:
|
||
|
|
access = config.get("chat_access") if isinstance(config.get("chat_access"), dict) else {}
|
||
|
|
user_limit = _positive_int(access.get("user_concurrency_limit"), 2)
|
||
|
|
group_limit = _positive_int(access.get("group_concurrency_limit"), 5)
|
||
|
|
daily_limit = _positive_int(access.get("daily_user_generation_limit"), 30)
|
||
|
|
daily_group_limit = _positive_int(access.get("daily_group_generation_limit"), 100)
|
||
|
|
if size == "3840x2160" and access.get("allow_4k") is not True:
|
||
|
|
raise ValueError("聊天命令尚未授权 4K 生成")
|
||
|
|
if size == "2560x1440" and access.get("allow_2k", True) is not True:
|
||
|
|
raise ValueError("聊天命令尚未授权 2K 生成")
|
||
|
|
user_active = sum(1 for item in active_jobs if _request_metadata(item).get("user_id") == chat.user_id)
|
||
|
|
group_active = sum(1 for item in active_jobs if chat.group_id and _request_metadata(item).get("group_id") == chat.group_id)
|
||
|
|
if user_active >= user_limit:
|
||
|
|
raise ValueError(f"用户并发任务已达到上限 {user_limit}")
|
||
|
|
if chat.group_id and group_active >= group_limit:
|
||
|
|
raise ValueError(f"群聊并发任务已达到上限 {group_limit}")
|
||
|
|
if self._daily_count(chat.user_id) >= daily_limit:
|
||
|
|
raise ValueError(f"用户今日生成次数已达到上限 {daily_limit}")
|
||
|
|
if chat.group_id and self._daily_group_count(chat.group_id) >= daily_group_limit:
|
||
|
|
raise ValueError(f"群聊今日生成次数已达到上限 {daily_group_limit}")
|
||
|
|
|
||
|
|
def record(self, chat: ChatCommandContext, action: str, *, target_id: str | None = None, allowed: bool = True, details: dict[str, Any] | None = None) -> None:
|
||
|
|
ctx = RequestContext.from_astrbot(username=chat.user_id, user_id=chat.user_id, source=f"astrbot_chat:{chat.platform}", permissions=set())
|
||
|
|
self.audit.record(
|
||
|
|
ctx=ctx,
|
||
|
|
action="chat_command_allowed" if allowed else "chat_command_denied",
|
||
|
|
target_type="chat_command",
|
||
|
|
target_id=target_id,
|
||
|
|
metadata={
|
||
|
|
"command": action,
|
||
|
|
"platform": chat.platform,
|
||
|
|
"message_origin": chat.message_origin,
|
||
|
|
"group_id": chat.group_id,
|
||
|
|
**(details or {}),
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
def _daily_count(self, user_id: str) -> int:
|
||
|
|
placeholder = self.database._placeholder
|
||
|
|
start = datetime.now(timezone.utc).date().isoformat()
|
||
|
|
conn = self.database.connect()
|
||
|
|
try:
|
||
|
|
row = conn.execute(
|
||
|
|
f"SELECT COUNT(*) AS count FROM audit_logs WHERE actor_id = {placeholder} AND action = {placeholder} AND created_at >= {placeholder}",
|
||
|
|
(user_id, "chat_command_allowed", start),
|
||
|
|
).fetchone()
|
||
|
|
return int(row["count"] if row else 0)
|
||
|
|
finally:
|
||
|
|
conn.close()
|
||
|
|
|
||
|
|
def _daily_group_count(self, group_id: str) -> int:
|
||
|
|
placeholder = self.database._placeholder
|
||
|
|
start = datetime.now(timezone.utc).date().isoformat()
|
||
|
|
conn = self.database.connect()
|
||
|
|
try:
|
||
|
|
rows = conn.execute(
|
||
|
|
f"SELECT metadata_json FROM audit_logs WHERE action = {placeholder} AND created_at >= {placeholder}",
|
||
|
|
("chat_command_allowed", start),
|
||
|
|
).fetchall()
|
||
|
|
count = 0
|
||
|
|
for row in rows:
|
||
|
|
try:
|
||
|
|
metadata = json.loads(row["metadata_json"] or "{}")
|
||
|
|
except (TypeError, ValueError):
|
||
|
|
continue
|
||
|
|
if str(metadata.get("group_id") or "") == group_id:
|
||
|
|
count += 1
|
||
|
|
return count
|
||
|
|
finally:
|
||
|
|
conn.close()
|
||
|
|
|
||
|
|
|
||
|
|
def _request_metadata(job: dict[str, Any]) -> dict[str, Any]:
|
||
|
|
request = job.get("request") if isinstance(job.get("request"), dict) else {}
|
||
|
|
return request.get("metadata") if isinstance(request.get("metadata"), dict) else {}
|
||
|
|
|
||
|
|
|
||
|
|
def _positive_int(value: Any, default: int) -> int:
|
||
|
|
try:
|
||
|
|
return max(int(value), 1)
|
||
|
|
except (TypeError, ValueError):
|
||
|
|
return default
|