cards.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """Google Chat outbound text formatting and Cards v2 rendering.
  2. Extracted from ``adapter.py``; the card dict shapes and key order here are the
  3. wire format and must stay byte-identical.
  4. """
  5. from __future__ import annotations
  6. import re
  7. from typing import Any, Callable, Dict
  8. # Invisible Unicode codepoints that render as tofu (□) in Google Chat's
  9. # restricted font stack: ZWS/ZWNJ/ZWJ, bidi marks, word joiner, BOM and
  10. # Variation Selectors (Chat ignores them and often shows a blank box).
  11. # Pattern lifted from PR #14965.
  12. _INVISIBLE_RE = re.compile(
  13. "["
  14. "\u200b" # Zero-Width Space
  15. "\u200c" # Zero-Width Non-Joiner
  16. "\u200d" # Zero-Width Joiner (ZWJ)
  17. "\u200e\u200f" # LTR / RTL marks
  18. "\u2060" # Word Joiner
  19. "\ufeff" # BOM / Zero-Width No-Break Space
  20. "\ufe00-\ufe0f" # Variation Selectors 1-16 (VS1–VS16)
  21. "\U000e0100-\U000e01ef" # Variation Selectors 17-256
  22. "]"
  23. )
  24. def format_message(content: str) -> str:
  25. """Convert standard Markdown to Google Chat's dialect.
  26. Chat renders only ``*bold*``, ``_italic_``, ``~strike~`` and code; ``**bold**``,
  27. ``# headers`` and ``[text](url)`` must be converted. Fenced and inline code
  28. are protected via placeholders so literal asterisks/brackets inside them
  29. survive; invisible tofu codepoints are stripped at the end.
  30. """
  31. if not content:
  32. return content
  33. placeholders: dict[str, str] = {}
  34. def _ph(value: str) -> str:
  35. key = f"\x00GC{len(placeholders)}\x00"
  36. placeholders[key] = value
  37. return key
  38. text = content
  39. # Protect fenced blocks first, then inline code.
  40. text = re.sub(r"(```(?:[^\n]*\n)?[\s\S]*?```)", lambda m: _ph(m.group(0)), text)
  41. text = re.sub(r"(`[^`]+`)", lambda m: _ph(m.group(0)), text)
  42. # Headers (## Title) → *Title* (Chat has no header support).
  43. text = re.sub(r"^#{1,6}\s+(.+)$", lambda m: _ph(f"*{m.group(1).strip()}*"), text, flags=re.MULTILINE)
  44. # ***text*** → *_text_*, then **text** → *text*.
  45. text = re.sub(r"\*\*\*(.+?)\*\*\*", lambda m: _ph(f"*_{m.group(1)}_*"), text)
  46. text = re.sub(r"\*\*(.+?)\*\*", lambda m: _ph(f"*{m.group(1)}*"), text)
  47. # [text](url) → <url|text> (Slack-style angle-bracket).
  48. text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", lambda m: _ph(f"<{m.group(2)}|{m.group(1)}>"), text)
  49. text = _INVISIBLE_RE.sub("", text)
  50. # Collapse double spaces left over from stripped chars.
  51. text = re.sub(r" +", " ", text)
  52. for key, value in placeholders.items():
  53. text = text.replace(key, value)
  54. return text
  55. def _required_str(mapping: dict[str, Any], key: str, context: str) -> str:
  56. value = mapping.get(key)
  57. value = str(value).strip() if value is not None else ""
  58. if not value:
  59. raise ValueError(f"{context}.{key} is required")
  60. return value
  61. def _copy_opt(dst: dict[str, Any], src: dict[str, Any], *keys: tuple[str, str]) -> dict[str, Any]:
  62. """Copy truthy ``src[src_key]`` into ``dst[dst_key]`` as str, in the given order."""
  63. for src_key, dst_key in keys:
  64. if src.get(src_key):
  65. dst[dst_key] = str(src[src_key])
  66. return dst
  67. def _required_list(mapping: dict[str, Any], key: str, error: str) -> list:
  68. items = mapping.get(key) or []
  69. if not isinstance(items, list) or not items:
  70. raise ValueError(error)
  71. return items
  72. def _button_to_chat(button: dict[str, Any]) -> dict[str, Any]:
  73. text = _required_str(button, "text", "button")
  74. action = _required_str(button, "action", "button")
  75. raw_params = button.get("parameters") or {}
  76. if not isinstance(raw_params, dict):
  77. raise ValueError("button.parameters must be an object")
  78. parameters = [{"key": str(key), "value": str(value)} for key, value in sorted(raw_params.items())]
  79. return {"text": text, "onClick": {"action": {"function": action, "parameters": parameters}}}
  80. def _text_widget(widget: dict[str, Any]) -> dict[str, Any]:
  81. return {"textParagraph": {"text": format_message(_required_str(widget, "text", "widget"))}}
  82. def _decorated_text_widget(widget: dict[str, Any]) -> dict[str, Any]:
  83. decorated: dict[str, Any] = {
  84. "text": format_message(_required_str(widget, "text", "widget")),
  85. "wrapText": bool(widget.get("wrap_text", True))}
  86. return {"decoratedText": _copy_opt(decorated, widget, ("top_label", "topLabel"), ("bottom_label", "bottomLabel"))}
  87. def _image_widget(widget: dict[str, Any]) -> dict[str, Any]:
  88. image = {"imageUrl": _required_str(widget, "image_url", "widget")}
  89. return {"image": _copy_opt(image, widget, ("alt_text", "altText"))}
  90. def _buttons_widget(widget: dict[str, Any]) -> dict[str, Any]:
  91. raw_buttons = _required_list(widget, "buttons", "button widgets require at least one button")
  92. return {"buttonList": {"buttons": [_button_to_chat(btn) for btn in raw_buttons]}}
  93. def _selection_item(item: Any) -> dict[str, Any]:
  94. if not isinstance(item, dict):
  95. raise ValueError("selection items must be objects")
  96. return {
  97. "text": _required_str(item, "text", "selection item"),
  98. "value": _required_str(item, "value", "selection item"),
  99. "selected": bool(item.get("selected", False))}
  100. def _selection_widget(widget: dict[str, Any]) -> dict[str, Any]:
  101. name = _required_str(widget, "name", "widget")
  102. raw_items = _required_list(widget, "items", "selection widgets require at least one item")
  103. return {
  104. "selectionInput": {
  105. "name": name,
  106. "label": str(widget.get("label") or name),
  107. "type": str(widget.get("selection_type") or "CHECK_BOX"),
  108. "items": [_selection_item(item) for item in raw_items]}}
  109. _WIDGET_RENDERERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
  110. "text": _text_widget,
  111. "text_paragraph": _text_widget,
  112. "decorated_text": _decorated_text_widget,
  113. "buttons": _buttons_widget,
  114. "button_list": _buttons_widget,
  115. "selection": _selection_widget,
  116. "selection_input": _selection_widget,
  117. "image": _image_widget,
  118. "divider": lambda widget: {"divider": {}},
  119. }
  120. def _widget_to_chat(widget: dict[str, Any]) -> dict[str, Any]:
  121. if not isinstance(widget, dict):
  122. raise ValueError("card widgets must be objects")
  123. widget_type = str(widget.get("type") or "").strip()
  124. renderer = _WIDGET_RENDERERS.get(widget_type)
  125. if renderer is None:
  126. raise ValueError(f"unsupported widget type: {widget_type or '<missing>'}")
  127. return renderer(widget)
  128. def _section_to_chat(section: Any) -> dict[str, Any]:
  129. if not isinstance(section, dict):
  130. raise ValueError("card sections must be objects")
  131. widgets = _required_list(section, "widgets", "card section widgets must contain at least one widget")
  132. rendered: dict[str, Any] = {"widgets": [_widget_to_chat(w) for w in widgets]}
  133. return _copy_opt(rendered, section, ("header", "header"))
  134. def _header_to_chat(header: Any) -> dict[str, Any]:
  135. if not isinstance(header, dict):
  136. raise ValueError("card.header must be an object")
  137. rendered: dict[str, Any] = {"title": _required_str(header, "title", "card.header")}
  138. _copy_opt(rendered, header, ("subtitle", "subtitle"))
  139. if header.get("image_url"):
  140. rendered["imageUrl"] = str(header["image_url"])
  141. rendered["imageType"] = str(header.get("image_type") or "SQUARE")
  142. return _copy_opt(rendered, header, ("image_alt_text", "imageAltText"))
  143. def card_spec_to_cards_v2(card_spec: dict[str, Any]) -> dict[str, Any]:
  144. if not isinstance(card_spec, dict):
  145. raise ValueError("card must be an object")
  146. raw_sections = _required_list(card_spec, "sections", "card.sections must contain at least one section")
  147. card: dict[str, Any] = {"sections": [_section_to_chat(s) for s in raw_sections]}
  148. header = card_spec.get("header")
  149. if header:
  150. card["header"] = _header_to_chat(header)
  151. return {"cardId": str(card_spec.get("card_id") or "hermes-card"), "card": card}