astrbot_plugin_imagestudio/core/chat_access_policy.py

48 行
1.7 KiB
Python

"""Chat command allowlist policy shared by AstrBot adapters."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
STRICT_ACTIONS = frozenset({"quick_profile", "character_workflow"})
ANY_ALLOWLIST_ACTIONS = frozenset({"single_image"})
def chat_action_allowed(
config: Mapping[str, Any] | None,
action: str,
*,
group_id: str | None,
user_id: str | None,
) -> bool:
"""Return whether a chat action passes the configured allowlists.
Quick profile and character workflow require both group and user matches.
Single-image generation accepts either match. Private chats have no group
match, so strict actions are intentionally unavailable there unless the
caller supplies a platform conversation/group identifier.
"""
access = config.get("chat_access") if isinstance(config, Mapping) else None
access = access if isinstance(access, Mapping) else {}
groups = _normalized_ids(access.get("group_allowlist"))
users = _normalized_ids(access.get("user_allowlist"))
group_match = bool(group_id and str(group_id).strip() in groups)
user_match = bool(user_id and str(user_id).strip() in users)
normalized_action = str(action or "").strip().lower()
if normalized_action in STRICT_ACTIONS:
return group_match and user_match
if normalized_action in ANY_ALLOWLIST_ACTIONS:
return group_match or user_match
return False
def _normalized_ids(value: Any) -> set[str]:
if isinstance(value, str):
value = value.replace(",", "\n").splitlines()
if not isinstance(value, (list, tuple, set, frozenset)):
return set()
return {str(item).strip() for item in value if str(item).strip()}