from __future__ import annotations from typing import Any from yuxi.utils.logging_config import logger class ConfigWritesManager: """配置写入管理 — 允许通过命令动态修改 Mattermost 渠道配置。 支持的写操作: - dm_policy、group_policy 安全策略切换 - allow_from / group_allow_from 白名单管理 - chatmode / require_mention 行为配置 - reply_to_mode 回复模式 - auto_register_commands 命令注册开关 """ ALLOWED_WRITE_KEYS = frozenset( { "dm_policy", "group_policy", "allow_from", "group_allow_from", "chatmode", "require_mention", "onchar_prefixes", "reply_to_mode", "auto_register_commands", "dangerously_allow_name_matching", } ) def __init__(self, config: dict[str, Any] | None = None): self._config = config or {} def is_config_writes_enabled(self) -> bool: return bool(self._config.get("config_writes", False)) def write_config(self, key: str, value: Any) -> bool: if not self.is_config_writes_enabled(): logger.warning("[Mattermost] Config writes are disabled") return False if key not in self.ALLOWED_WRITE_KEYS: logger.warning(f"[Mattermost] Config write denied for key '{key}'") return False self._config[key] = value logger.info(f"[Mattermost] Config updated: {key} = {value}") return True def add_to_allowlist(self, target: str, list_type: str = "dm") -> bool: key = "allow_from" if list_type == "dm" else "group_allow_from" if not self.is_config_writes_enabled(): return False current = self._config.get(key, []) if not isinstance(current, list): current = [] from .security import normalize_allow_entry normalized = normalize_allow_entry(target) if not normalized: return False if normalized not in current: current.append(normalized) self._config[key] = current logger.info(f"[Mattermost] Added '{target}' to {key}") return True def remove_from_allowlist(self, target: str, list_type: str = "dm") -> bool: key = "allow_from" if list_type == "dm" else "group_allow_from" if not self.is_config_writes_enabled(): return False current = self._config.get(key, []) if not isinstance(current, list): return False from .security import normalize_allow_entry normalized = normalize_allow_entry(target) if normalized in current: current.remove(normalized) self._config[key] = current logger.info(f"[Mattermost] Removed '{target}' from {key}") return True def get_config(self) -> dict[str, Any]: return {k: v for k, v in self._config.items() if k in self.ALLOWED_WRITE_KEYS}