#!/usr/bin/env python3
# Libervia plugin
# Copyright (C) 2009-2026 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
from typing import List
from twisted.words.protocols.jabber.xmlstream import XMPPHandler
from twisted.words.xish import domish
from tx_xmpp import disco, itx_xmpp
from zope.interface import implementer
from libervia.backend.core.constants import Const as C
from libervia.backend.core.i18n import _
from libervia.backend.core.log import getLogger
from libervia.backend.core.core_types import SatXMPPEntity
log = getLogger(__name__)
NS_JINGLE_GROUPING = "urn:xmpp:jingle:apps:grouping:0"
NS_RFC_5888 = "urn:ietf:rfc:5888"
PLUGIN_INFO = {
C.PI_NAME: "Jingle Grouping Framework",
C.PI_IMPORT_NAME: "XEP-0338",
C.PI_TYPE: "XEP",
C.PI_MODES: C.PLUG_MODE_BOTH,
C.PI_PROTOCOLS: ["XEP-0338"],
C.PI_DEPENDENCIES: ["XEP-0166", "XEP-0167"],
C.PI_RECOMMENDATIONS: [],
C.PI_MAIN: "XEP_0338",
C.PI_HANDLER: "yes",
C.PI_DESCRIPTION: _("""Jingle mapping of RFC 5888 SDP Grouping Framework"""),
}
class XEP_0338:
def __init__(self, host):
log.info(f"plugin {PLUGIN_INFO[C.PI_NAME]!r} initialization")
self._j = host.plugins["XEP-0166"]
host.trigger.add("XEP-0167_parse_sdp_a", self._parse_sdp_a_trigger)
host.trigger.add(
"XEP-0167_generate_sdp_session", self._generate_sdp_session_trigger
)
host.trigger.add(
"XEP-0167_jingle_session_init", self._jingle_session_init_trigger
)
host.trigger.add(
"XEP-0167_content_add_elt_built", self._content_add_elt_built_trigger
)
host.trigger.add("XEP-0167_jingle_handler", self._jingle_handler_trigger)
def get_handler(self, client):
return XEP_0338_handler()
def _parse_sdp_a_trigger(
self,
attribute: str,
parts: List[str],
call_data: dict,
metadata: dict,
media_type: str,
application_data: dict,
transport_data: dict,
) -> None:
"""Parse "group" attributes"""
if attribute == "group":
semantics = parts[0]
content_names = parts[1:]
metadata.setdefault("group", {})[semantics] = content_names
def _generate_sdp_session_trigger(
self,
session: dict,
local: bool,
sdp_lines: List[str],
content_names: List[str] | None = None,
) -> None:
"""Generate "group" attributes"""
if content_names is not None:
# the session groups describe the full session: only the generated m-lines
# sharing a single transport are bundled
ice_key = "local_ice_data" if local else "peer_ice_data"
for names in self._group_by_transport(
session, content_names, ice_key
).values():
if len(names) > 1:
sdp_lines.append(f"a=group:BUNDLE {' '.join(names)}")
return
key = "metadata" if local else "peer_metadata"
group_data = session[key].get("group", {})
for semantics, names in group_data.items():
sdp_lines.append(f"a=group:{semantics} {' '.join(names)}")
def _group_by_transport(
self, session: dict, content_names: List[str], ice_key: str
) -> dict[tuple[str, str], List[str]]:
"""Group content names sharing a single transport
@param session: session data
@param content_names: names of the contents to group
@param ice_key: transport data key holding the credentials ("local_ice_data" or
"peer_ice_data")
@return: dict mapping (ufrag, pwd) to the names sharing the transport
"""
groups: dict[tuple[str, str], List[str]] = {}
for name in content_names:
ice_data = session["contents"][name]["transport_data"][ice_key]
groups.setdefault((ice_data["ufrag"], ice_data["pwd"]), []).append(name)
return groups
def parse_group_element(self, jingle_elt: domish.Element, session: dict) -> None:
"""Parse the and elements"""
for group_elt in jingle_elt.elements(NS_JINGLE_GROUPING, "group"):
try:
metadata = session["peer_metadata"]
semantics = group_elt["semantics"]
group_content = metadata.setdefault("group", {})[semantics] = []
for content_elt in group_elt.elements(NS_JINGLE_GROUPING, "content"):
group_content.append(content_elt["name"])
except KeyError as e:
log.warning(f"Error while parsing : {e}\n{group_elt.toXml()}")
def _add_group_elt(
self,
jingle_elt: domish.Element,
semantics: str,
content_names: List[str],
) -> None:
"""Add a element with the given contents
@param jingle_elt: element the group is added to
@param semantics: grouping semantics (e.g. "BUNDLE")
@param content_names: names of the grouped contents
"""
group_elt = domish.Element((NS_JINGLE_GROUPING, "group"))
jingle_elt.addChild(group_elt)
group_elt["semantics"] = semantics
for content_name in content_names:
content_elt = group_elt.addElement((NS_JINGLE_GROUPING, "content"))
content_elt["name"] = content_name
def add_group_element(
self, jingle_elt: domish.Element, session: dict, source: str = "metadata"
) -> None:
"""Build the and elements if possible
@param jingle_elt: element the groups are added to
@param session: session data
@param source: session key holding the group data ("metadata" for the local
groups, "peer_metadata" to echo the peer's groups)
"""
for semantics, content_names in session.get(source, {}).get("group", {}).items():
self._add_group_elt(jingle_elt, semantics, content_names)
def _content_add_elt_built_trigger(
self,
client: SatXMPPEntity,
session: dict,
jingle_elt: domish.Element,
added: List[str],
) -> None:
"""Add the BUNDLE groups of a sent content-add
The added contents are bundled with the other contents sharing their transport.
@param client: the client entity
@param session: session data
@param jingle_elt: element of the content-add to be sent
@param added: names of the contents added to the session
"""
for names in self._group_by_transport(
session, list(session["contents"]), "local_ice_data"
).values():
# the element lists the full bundle, not only the added contents
if len(names) > 1 and any(name in names for name in added):
self._add_group_elt(jingle_elt, "BUNDLE", names)
def _jingle_session_init_trigger(
self,
client: SatXMPPEntity,
session: dict,
content_name: str,
media: str,
media_data: dict,
desc_elt: domish.Element,
) -> None:
if content_name == next(iter(session["contents"])):
# the element must be added only once, so we do it only for the first
# content
jingle_elt = session["jingle_elt"]
self.add_group_element(jingle_elt, session)
async def _jingle_handler_trigger(
self,
client: SatXMPPEntity,
action: str,
session: dict,
content_name: str,
desc_elt: domish.Element,
) -> None:
# this is a session metadata, so we only generate it on the first content
if content_name == next(iter(session["contents"])) and action in (
self._j.A_PREPARE_CONFIRMATION,
self._j.A_SESSION_INITIATE,
self._j.A_PREPARE_INITIATOR,
):
jingle_elt = session["jingle_elt"]
self.parse_group_element(jingle_elt, session)
if action == self._j.A_SESSION_INITIATE:
self.add_group_element(jingle_elt, session, source="peer_metadata")
@implementer(itx_xmpp.IDisco)
class XEP_0338_handler(XMPPHandler):
def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
return [disco.DiscoFeature(NS_RFC_5888)]
def getDiscoItems(self, requestor, target, nodeIdentifier=""):
return []