""" Reply-Quote-Stripper: Entfernt zitierte Parent-Nachrichten aus Reply-Texten. P0: Verhindert Fehl-Routing durch Keyword-Matches in zitierten Texten. Zweistufig defensiv: 1. Attachments-basiert: Rocket.Chat sendet bei Replies die Parent-Nachricht als attachment mit. Entferne den zitierten Text aus dem Nachrichtentext. 2. Text-basiert (Fallback): Regex-Heuristik für Markdown-Blockquotes (> quote) und [quote]-Blöcke. Konfliktfrei mit Butler-Prinzip — der Strip verschärft die 100%-Heuristik, ohne sie zu unterlaufen. """ from __future__ import annotations import re from typing import List, Optional, Tuple # ═══════════════════════════════════════════════════════════════════════════ # Rocket.Chat Reply-Quote Patterns # ═══════════════════════════════════════════════════════════════════════════ # Rocket.Chat reply link pattern: [ ](https://...?msg=MSGID) # This is the inline reply marker that Rocket.Chat inserts when replying. _RC_REPLY_LINK_RE = re.compile( r'\[\s*\]\s*\(\s*https?://[^)]*\?msg=[^)]+\)\s*', re.IGNORECASE, ) # Markdown blockquote: lines starting with > # Matches one or more consecutive lines starting with '> ' _BLOCKQUOTE_RE = re.compile( r'(?:^|\n)(?:> .*(?:\n|$))+', re.MULTILINE, ) # [quote]...[/quote] blocks (BBCode-style, used by some RC clients) _QUOTE_BLOCK_RE = re.compile( r'\[quote[^\]]*\].*?\[/quote\]', re.DOTALL | re.IGNORECASE, ) # [quote="author"]...[/quote] blocks _QUOTE_AUTHOR_BLOCK_RE = re.compile( r'\[quote=["\']?[^\]"\']*["\']?\].*?\[/quote\]', re.DOTALL | re.IGNORECASE, ) # Rocket.Chat attachment types that indicate a reply quote _REPLY_ATTACHMENT_TYPES = frozenset({ 'reply', 'quote', 'message', }) def _extract_quoted_text_from_attachments(attachments: list) -> Optional[str]: """Extrahiere den zitierten Text aus Reply-Attachments. Rocket.Chat sendet bei Replies die Parent-Nachricht als attachment mit. Typische Felder: - attachment_type: 'reply' oder 'quote' - text: der zitierte Nachrichtentext - description: Beschreibung (z.B. Autor der Parent-Nachricht) - author_name: Name des Autors der Parent-Nachricht - message_link: Link zur Parent-Nachricht Returns: Der zitierte Text wenn gefunden, sonst None. """ if not attachments or not isinstance(attachments, list): return None for attachment in attachments: if not isinstance(attachment, dict): continue # Check for reply/quote attachment types att_type = attachment.get('type', '') att_attachment_type = attachment.get('attachment_type', '') if att_type in _REPLY_ATTACHMENT_TYPES or att_attachment_type in _REPLY_ATTACHMENT_TYPES: # Try to get the quoted text quoted = attachment.get('text', '') or attachment.get('description', '') if quoted: return quoted.strip() # Also check for message_link (Rocket.Chat reply indicator) if attachment.get('message_link'): quoted = attachment.get('text', '') or attachment.get('description', '') if quoted: return quoted.strip() return None def _strip_rc_reply_link(text: str) -> str: """Entferne den Rocket.Chat Reply-Link [ ](url?msg=ID) aus dem Text.""" return _RC_REPLY_LINK_RE.sub('', text).strip() def _strip_blockquotes(text: str) -> str: """Entferne Markdown-Blockquotes (> quote) aus dem Text.""" return _BLOCKQUOTE_RE.sub('', text).strip() def _strip_quote_blocks(text: str) -> str: """Entferne [quote]...[/quote] Blöcke aus dem Text.""" text = _QUOTE_AUTHOR_BLOCK_RE.sub('', text) text = _QUOTE_BLOCK_RE.sub('', text) return text.strip() def strip_reply_quote( text: str, attachments: Optional[list] = None, ) -> Tuple[str, bool]: """Entferne Reply-Quote aus einer Nachricht (P0). Zweistufig defensiv: 1. Attachments-basiert: Wenn die Nachricht Reply-Attachments enthält, wird der zitierte Text aus dem Nachrichtentext entfernt. 2. Text-basiert (Fallback): Regex-Heuristik für Blockquote-Pattern. Args: text: Der Nachrichtentext. attachments: Optionale Liste von Attachments aus dem msg_obj. Returns: Tuple aus (bereinigtem Text, ob ein Quote gestrippt wurde). """ if not text: return text, False stripped = False result = text # ── Stufe 1: Attachments-basiert ────────────────────────────────── if attachments: quoted_text = _extract_quoted_text_from_attachments(attachments) if quoted_text and quoted_text in result: result = result.replace(quoted_text, '', 1).strip() stripped = True # ── Stufe 1b: RC Reply-Link entfernen ────────────────────────────── # [ ](https://chat.example.com/group/room?msg=MSGID) before_link = result result = _strip_rc_reply_link(result) if result != before_link: stripped = True # ── Stufe 2: Text-basiert (Fallback) ─────────────────────────────── # Nur wenn Stufe 1 nichts gefunden hat if not stripped: # [quote]...[/quote] Blöcke before_quote = result result = _strip_quote_blocks(result) if result != before_quote: stripped = True if not stripped: # Markdown-Blockquotes (> quote) before_bq = result result = _strip_blockquotes(before_bq) if result != before_bq: stripped = True # Clean up: collapse multiple blank lines, strip result = re.sub(r'\n{3,}', '\n\n', result) result = result.strip() return result, stripped def strip_reply_quote_for_routing( text: str, attachments: Optional[list] = None, ) -> Tuple[str, str, bool]: """P1: Trenne routing_text und display_text. - routing_text: Ohne Quote — für Archivar/Keyword-Matcher/classify_and_route - display_text: Mit Quote — für Agent und Conversation-History Args: text: Der originale Nachrichtentext. attachments: Optionale Attachments aus dem msg_obj. Returns: Tuple aus (routing_text, display_text, was_stripped). Wenn kein Quote gefunden: routing_text == display_text == text. """ routing_text, was_stripped = strip_reply_quote(text, attachments) display_text = text # Originaltext mit Quote für Agent/History return routing_text, display_text, was_stripped