aboutsummaryrefslogtreecommitdiff
path: root/xmpp-cli-bridge/xmpp_cli_bridge/__init__.py
blob: f5ff805c53f720fb4e24be2a44d8f62582307410 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Connect an XMPP account to a Python handler: serve(jid, password, handler)."""
from __future__ import annotations

import asyncio
import logging
import re
import sys
from typing import Callable, Optional
from xml.etree import ElementTree as ET

_MARK = "{xmpp-cli-bridge}mark"  # tags our replies so bounces back to us are dropped

from slixmpp import ClientXMPP

Handler = Callable[[str, str], Optional[str]]

# control chars are illegal in XML 1.0; sending them kills the stream
_XML_BAD = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff]")

logger = logging.getLogger(__name__)


class _Bridge(ClientXMPP):
    def __init__(self, jid: str, password: str, handler: Handler) -> None:
        super().__init__(jid, password)
        self._handler = handler
        self.add_event_handler("session_start", self._on_start)
        self.add_event_handler("message", self._on_message)

    async def _on_start(self, _event) -> None:
        logger.info("connected as %s", self.boundjid.bare)
        self.send_presence()

    async def _on_message(self, msg) -> None:
        if msg["type"] in ("groupchat", "error") or not msg["body"]:
            logger.debug("ignoring %s message from %s", msg["type"], msg["from"])
            return
        if msg.xml.find(_MARK) is not None:  # our own reply, bounced back
            return
        logger.info("message from %s: %.200r", msg["from"], str(msg["body"]))
        try:
            loop = asyncio.get_running_loop()
            reply = await loop.run_in_executor(
                None, self._handler, str(msg["body"]), str(msg["from"])
           )
        except Exception as exc:
            reply = f"error: {exc}"
        if reply is not None:
            # ESC (0x1b) etc. are illegal XML; sending them kills the stream
            # (seen live: pass ls output -> server <not-well-formed>)
            out = msg.reply(_XML_BAD.sub("", str(reply)))
            ET.SubElement(out.xml, _MARK)
            out.send()
            logger.info("reply sent to %s (%d chars)", msg["from"], len(out["body"]))


def serve(jid: str, password: str, handler: Handler) -> None:
    """Log in and dispatch messages to handler(body, sender_jid) -> reply or None.

    Blocks until Ctrl-C; handler runs in a worker thread so it may block.
    """
    # one line per event on stdout; the child's stderr still goes to the
    # terminal, so the two don't interleave
    logging.basicConfig(
        stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(message)s"
    )

    async def _run() -> None:
        bot = _Bridge(jid, password, handler)
        bot.connect()
        try:
            await bot.disconnected
        finally:
            bot.disconnect()

    try:
        asyncio.run(_run())
    except KeyboardInterrupt:
        pass