Parser de Stanzas

El módulo parser.py proporciona herramientas para parsear las stanzas XML entrantes desde el socket XMPP, manejando fragmentación TCP.

Funciones de Parseo

parse_todus_message(stanza: str) -> dict

Parsea una stanza <m> de ToDus y devuelve un diccionario con todos los campos extraídos.

Ejemplo de salida:

{
    "from": "5312345678@im.todus.cu",
    "to": "5387654321@im.todus.cu",
    "id": "a1b2c3d4",
    "type": "c",
    "body": "Hola mundo",
    "is_group": False,
    "buttons": [],
    "reply_to": "",
    "raw": "<m ...>...</m>"
}

Campos principales:

  • from, to, id, type, original_id
  • body – Texto del mensaje.
  • is_groupTrue si es mensaje de grupo.
  • group_id, sender_phone – Si es grupo.
  • reply_to – ID del mensaje al que se responde.
  • url, file_name, file_size, file_id – Archivos.
  • image_width, image_height, image_thumbnail – Imágenes.
  • video_url, video_name, video_duration, video_width, video_height, video_thumbnail – Videos.
  • sticker_id, sticker_name, sticker_pack, sticker_hash – Stickers.
  • contact_id, contact_name, contact_phone – Contactos.
  • location_lat, location_lon, location_zoom, location_text – Ubicación.
  • event_title, event_start, event_end, event_all_day, event_ics – Eventos.
  • buttons – Lista de diccionarios con text, command, data, size.
  • edited – ID de edición.
  • deleted – ID de eliminación.
  • receipt, receipt_type – Confirmaciones (delivered / read).
  • chat_statecomposing o paused.
  • offline_ts – Timestamp de mensaje offline.
  • raw – Stanza original.

parse_presence(stanza: str) -> dict

Parsea presencia XMPP.

{
    "from": "...",
    "to": "...",
    "id": "...",
    "status": "Online",
    "show": "chat",
    "priority": 5,
    "raw": "..."
}

parse_iq(stanza: str) -> dict

Parsea stanzas IQ.

{
    "from": "...",
    "to": "...",
    "id": "...",
    "type": "result" | "set" | "get",
    "error": "...",           # si existe
    "query": "...",           # contenido interno
    "upload_url": "...",      # si es respuesta de upload
    "download_url": "...",    # si es respuesta de upload
    "real_url": "...",        # si es respuesta de download
    "raw": "..."
}

parse_tdack(stanza: str) -> dict

Parsea acknowledgment (<tdack>).

{
    "type": "tdack",
    "message_id": "...",
    "raw": "..."
}

IncrementalParser

Parser que maneja stanzas fragmentadas en múltiples paquetes TCP.

Métodos

  • feed(chunk: str) -> list[dict] – Alimenta con nuevo chunk y retorna stanzas completas parseadas.
  • reset() – Limpia el buffer interno.

Uso Interno: El cliente ToDusClientBase utiliza este parser en _listen_loop para procesar el flujo continuo de datos.

parser = IncrementalParser()
stanzas = parser.feed(recv_data)
for stanza in stanzas:
    # Procesar cada stanza

Ejemplo de Uso Directo

from todus.parser import parse_todus_message

raw = '<m to="..." t="c" i="123" xmlns="jc"><k xmlns="x8"/><b>Hola</b></m>'
parsed = parse_todus_message(raw)
print(parsed["body"])  # "Hola"