platform_config.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. """
  2. Chatto Platform Config
  3. """
  4. import os
  5. import re
  6. # Put the vendored dependencies for THIS platform on sys.path before importing
  7. # anything from chattolib. Imported relatively as part of the plugin package and
  8. # absolutely when this module is loaded standalone (e.g. by the tests).
  9. try:
  10. from .vendor_path import setup_vendor_path
  11. except ImportError: # pragma: no cover - depends on how the module is loaded
  12. from vendor_path import setup_vendor_path
  13. setup_vendor_path()
  14. import logging
  15. from typing import Any, Dict, Generic, Optional, TypeVar
  16. from gateway.config import PlatformConfig
  17. import utils
  18. # Absolute import — the vendor dir is on sys.path (see above) and chattolib's
  19. # own modules import each other absolutely ("from chattolib.x import y").
  20. # Importing it relatively as well would load a *second* copy of every module
  21. # under a different name, so isinstance() checks across the two would fail.
  22. from chattolib import ChattoClient
  23. logger = logging.getLogger(__name__)
  24. # --------------------------------------------------------------------------- #
  25. # Constants
  26. # --------------------------------------------------------------------------- #
  27. class ChattoConstants:
  28. """
  29. Chatto Platform Constants
  30. """
  31. def __init__(self):
  32. pass
  33. PLATFORM_NAME: str = "chatto-platform"
  34. PLATFORM_LABEL: str = "Chatto"
  35. INSTALL_HINT = "Requires a Chatto server. See https://docs.chatto.run"
  36. # NOTE: env var names live on the ConfigFields below (ConfigField.env_name),
  37. # so there is exactly one source of truth for them.
  38. MAX_MESSAGE_LENGTH = 10000
  39. SEEN_CAP = 500
  40. # WebSocket / realtime protocol
  41. WS_PATH = "/api/realtime"
  42. WS_AUTH_TIMEOUT = 20.0
  43. WS_MAX_MESSAGE_BYTES = 4_000_000
  44. WS_PING_INTERVAL = 30.0
  45. WS_PING_FAILURE_THRESHOLD = 3
  46. WS_RECONNECT_INITIAL_BACKOFF = 1.0
  47. WS_RECONNECT_MAX_BACKOFF = 30.0
  48. # A candidate @-handle, not a confirmed one — every match is resolved
  49. # against the member directory before it counts. Must start alphanumeric,
  50. # so prose like "per @-mention" yields nothing to look up.
  51. # The lookbehind keeps the domain half of an e-mail address from becoming a
  52. # candidate and costing a directory lookup.
  53. MENTION_RE = re.compile(r"(?<![\w.])@([A-Za-z0-9_][A-Za-z0-9_.\-]*)")
  54. # Handles that address the room rather than a person — the bot is one of
  55. # the addressees, so these do not mean "this is for someone else".
  56. BROADCAST_MENTIONS = frozenset({"here", "channel", "everyone", "all", "room"})
  57. # Presence is a TTL the server lets lapse — chattolib refuses to set OFFLINE
  58. # at all ("stop refreshing to go offline"), so staying online means
  59. # re-announcing ONLINE on this interval for as long as we are connected.
  60. PRESENCE_REFRESH_INTERVAL = 60.0
  61. # HTTP timeout used for outbound URL fetches
  62. HTTP_TIMEOUT = 30
  63. # Emoji shortcode mapping (Chatto uses shortcode names, not unicode emoji)
  64. # Emoji shortcode mapping (Chatto uses shortcode names, not unicode emoji)
  65. EMOJI_TO_SHORTCODE: Dict[str, str] = {
  66. "👍": "thumbsup",
  67. "👎": "thumbsdown",
  68. "❤️": "heart",
  69. "❤": "heart",
  70. "✅": "white_check_mark",
  71. "❌": "x",
  72. "👀": "eyes",
  73. "🫥": "dotted_line_face",
  74. "🎉": "tada",
  75. "😂": "joy",
  76. "🚀": "rocket",
  77. "🔥": "fire",
  78. "💯": "100",
  79. "🤔": "thinking",
  80. "👏": "clap",
  81. "🙏": "pray",
  82. "😅": "sweat_smile",
  83. "😴": "sleeping",
  84. "⏳": "hourglass",
  85. }
  86. # Chunk size for asset uploads (256 KB)
  87. UPLOAD_CHUNK_SIZE = 256 * 1024
  88. def _get_env_or_extra_str_opt(env_var: str, extra_val: Optional[str | bool], default: Optional[str] = None) -> Optional[str]:
  89. """Get a value from environment variable or extra config."""
  90. env_value = os.getenv(env_var)
  91. if env_value is not None:
  92. return env_value.strip()
  93. if extra_val is not None:
  94. if isinstance(extra_val, str):
  95. return extra_val.strip()
  96. elif isinstance(extra_val, bool):
  97. return str(extra_val)
  98. else:
  99. logger.error("extra_val: %s is supposed to be str, but %s was found.", extra_val, str(type(extra_val)))
  100. if default is not None:
  101. logger.debug("Chatto: Defaulting to '%s'", default)
  102. return default.strip()
  103. return None
  104. def _get_env_or_extra_str(env_var: str, extra_val: Optional[str | bool], default: Optional[str] = None) -> str:
  105. """Get a value from environment variable or extra config."""
  106. my_string = _get_env_or_extra_str_opt(env_var, extra_val, default)
  107. if my_string:
  108. return my_string
  109. return ""
  110. def _get_env_or_extra_truthy(env_var: str, extra_val: Optional[str | bool], default: bool = False) -> bool:
  111. """Get a boolean value from environment variable or extra config."""
  112. return utils.is_truthy_value(_get_env_or_extra_str(env_var, extra_val, str(default)), default)
  113. def _split_str_to_list(mystring: str) -> list[str]:
  114. """Split a comma-separated string, trimming whitespace and dropping empties."""
  115. return [part.strip() for part in mystring.split(",") if part.strip()]
  116. def _get_env_or_extra_list(env_var: str, extra_val: Optional[list[str]]) -> list[str]:
  117. """Get a list of values from environment variable or extra config."""
  118. env_value = os.getenv(env_var)
  119. if env_value is not None:
  120. return _split_str_to_list(env_value)
  121. if extra_val is not None:
  122. if isinstance(extra_val, list):
  123. return [str(c).strip() for c in extra_val if str(c).strip()]
  124. if isinstance(extra_val, str):
  125. return _split_str_to_list(extra_val)
  126. return []
  127. T = TypeVar("T")
  128. class ConfigValue(Generic[T]):
  129. """The resolved value of a single config field, bound to one configuration
  130. instance.
  131. Access the payload via ``.value``. ``__bool__``/``__eq__`` delegate to it,
  132. so a forgotten ``.value`` (``if config.allow_all_users:``) still evaluates
  133. the actual setting instead of the always-truthy wrapper object.
  134. """
  135. __slots__ = ("value", "field_name", "env_name")
  136. def __init__(self, value: T, field_name: str, env_name: str) -> None:
  137. self.value = value
  138. self.field_name = field_name
  139. self.env_name = env_name
  140. def __bool__(self) -> bool:
  141. return bool(self.value)
  142. def __eq__(self, other: Any) -> bool:
  143. if isinstance(other, ConfigValue):
  144. return self.value == other.value
  145. return self.value == other
  146. def __hash__(self) -> int:
  147. return hash(self.value)
  148. def __contains__(self, item: Any) -> bool:
  149. return item in self.value # type: ignore[operator]
  150. def __iter__(self):
  151. return iter(self.value) # type: ignore[call-overload]
  152. def __str__(self) -> str:
  153. return str(self.value)
  154. def __repr__(self) -> str:
  155. return f"{self.field_name}={self.value!r}"
  156. class ConfigField(Generic[T]):
  157. """Declarative descriptor for one config field.
  158. Declares *how* a field is read (kind, env var name, default); the resolved
  159. payload lives per configuration instance in ``instance._values``, never on
  160. the descriptor itself. Reading a field on the class (rather than on an
  161. instance) yields the descriptor, so ``ChattoConfiguration.token.env_name``
  162. keeps working for the registration hooks.
  163. """
  164. field_name: str = ""
  165. env_name: str = ""
  166. def __init__(
  167. self,
  168. kind: str,
  169. *,
  170. default: Any = None,
  171. config_key: Optional[str] = None,
  172. doc: str = "",
  173. ) -> None:
  174. # kind: "str" | "str_opt" | "bool" | "list"
  175. self.kind = kind
  176. self.default = default
  177. # config_key: the name used in config.yaml's "extra" block and (upper-cased,
  178. # CHATTO_-prefixed) as the env var, where it differs from the attribute name.
  179. self._config_key = config_key
  180. self.__doc__ = doc
  181. def __set_name__(self, owner: Any, name: str) -> None:
  182. self.field_name = str(name).lower().replace("chatto_", "", 1)
  183. self.config_key = self._config_key or self.field_name
  184. self.env_name = f"CHATTO_{self.config_key.upper()}"
  185. def __get__(self, instance: Any, owner: Any = None) -> "ConfigValue[T]":
  186. if instance is None:
  187. return self # type: ignore[return-value]
  188. return instance._values[self.field_name]
  189. def __set__(self, instance: Any, value: Any) -> None:
  190. raise AttributeError(
  191. f"Chatto: config field '{self.field_name}' is read-only; "
  192. f"set '{self.field_name}.value' if you really need to override it."
  193. )
  194. def resolve(self, extra: Dict[str, Any]) -> ConfigValue:
  195. """Read this field from the environment, then from ``extra``, then the default."""
  196. raw = extra.get(self.config_key)
  197. if self.kind == "list":
  198. value: Any = _get_env_or_extra_list(self.env_name, raw)
  199. elif self.kind == "bool":
  200. value = _get_env_or_extra_truthy(self.env_name, raw, bool(self.default))
  201. elif self.kind == "str_opt":
  202. value = _get_env_or_extra_str_opt(self.env_name, raw, self.default)
  203. else:
  204. value = _get_env_or_extra_str(self.env_name, raw, self.default)
  205. return ConfigValue(value, self.field_name, self.env_name)
  206. class ChattoConfiguration:
  207. """Chatto platform configuration.
  208. Every field is resolved once per instance, in this order:
  209. environment variable → ``PlatformConfig.extra`` → declared default.
  210. """
  211. base_url = ConfigField("str", default=ChattoClient.DEFAULT_BASE_URL)
  212. token = ConfigField("str_opt")
  213. login = ConfigField("str")
  214. password = ConfigField("str")
  215. channels_list = ConfigField("list", config_key="channels")
  216. home_channel = ConfigField("str")
  217. allowed_users = ConfigField("list")
  218. require_mention = ConfigField("bool", default=False)
  219. # free_response_channels: room IDs where the bot responds without being
  220. # mentioned via "@botname" even when require_mention is true.
  221. free_response_channels_list = ConfigField("list", config_key="free_response_channels")
  222. # Auto-thread: by default, Chatto creates a thread for replies to room
  223. # messages (not DMs, not already in a thread). This keeps conversations
  224. # organized in the room. Can be disabled via extra.auto_thread=false.
  225. auto_thread = ConfigField("bool", default=True)
  226. allow_all_users = ConfigField("bool", default=False)
  227. reactions = ConfigField("bool", default=True)
  228. def __init__(self, pconfig: PlatformConfig):
  229. """Resolve every declared ConfigField against env vars and
  230. ``PlatformConfig.extra`` (which Hermes pre-populates from config.yaml).
  231. """
  232. extra: Dict[str, Any] = getattr(pconfig, "extra", None) or {}
  233. self._values: Dict[str, ConfigValue] = {
  234. field.field_name: field.resolve(extra) for field in self.fields()
  235. }
  236. logger.debug("ChattoConfiguration: %s", self)
  237. @classmethod
  238. def fields(cls) -> list[ConfigField]:
  239. """All declared config fields, in declaration order."""
  240. return [v for v in vars(cls).values() if isinstance(v, ConfigField)]
  241. def __str__(self) -> str:
  242. redacted = {"token", "password"}
  243. parts = [
  244. f"{name}={'***' if name in redacted and cv.value else cv.value!r}"
  245. for name, cv in self._values.items()
  246. ]
  247. return "ChattoConfiguration(" + ", ".join(parts) + ")"