platform_config.py 11 KB

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