QXmpp

Introduction

QXmpp is a cross-platform C++ XMPP client and server library built on top of the Qt framework (Qt 6.4+). It implements a large number of XMPP Extension Protocols (XEPs) and exposes a modern, reactive API based on C++20 and Qt's property system.

Getting Started

The central class is QXmppClient. Create one, register the managers you need, then connect:

auto *client = new QXmppClient(this);

// Register managers
auto *pubsub  = client->addNewExtension<QXmppPubSubManager>();
auto *disco   = client->addNewExtension<QXmppDiscoveryManager>();
auto *muc     = client->addNewExtension<QXmppMucManagerV2>();

// Connect
QXmppConfiguration config;
config.setJid("user@example.org");
config.setPassword("secret");
client->connectToServer(config);

Async API

All network operations return a QXmppTask<T>, which represents a pending result. QXmppTask supports co_await, making sequential async code straightforward:

QXmppTask<void> MyManager::doSomething()
{
    auto result = co_await muc->joinRoom("room@conference.example.org", "MyNick").withContext(this);
    if (auto *err = std::get_if<QXmppError>(&result)) {
        qWarning() << "Join failed:" << err->description;
        co_return;
    }
    // continue ...
}

Alternatively, use .then() to attach a callback:

muc->joinRoom("room@conference.example.org", "MyNick").then(this, [](auto result) {
    if (auto *err = std::get_if<QXmppError>(&result)) {
        qWarning() << "Join failed:" << err->description;
    }
});

Results are typically QXmpp::Result<T>, a std::variant<T, QXmppError>. Always pass a context object (this) to .then() or .withContext() to ensure the callback is not invoked after the object has been destroyed.

Reactive Properties

Selected APIs expose observable state via QBindable<T>, backed by Qt's QProperty system. QXmppMucRoomV2 is the primary example — room info, config, and participant state are all exposed as bindable properties that update automatically when the server reports changes:

auto room = *muc->findRoom("room@conference.example.org");
room.setWatchAvatar(true);

// m_avatarNotifier is a QPropertyNotifier member: discarding the handle
// returned by addNotifier() unsubscribes the callback immediately.
m_avatarNotifier = room.avatar().addNotifier([room]() {
    // called whenever the room avatar changes
    auto val = room.avatar().value();
});

Observer lifetime, addNotifier() versus subscribe(), and how to bridge bindable state into classic signals are covered in Reactive Properties.

IQ Requests

IQ stanzas are represented by QXmpp::Iq::Stanza, usually via the aliases QXmpp::Iq::Get, QXmpp::Iq::Set, QXmpp::Iq::Result and QXmpp::Iq::Error. They are aggregates with a typed payload, so only the needed fields are set via designated initializers.

QXmppClient::sendIq() sends a get or set request and returns only the payload of the response: for a get request the same payload type as the request, for a set request QXmpp::Success. Errors from the other entity are returned as QXmppError.

auto result = co_await client->sendIq(QXmpp::Iq::Get<QXmppDiscoInfo> { .to = u"example.org"_s }).withContext(this);
if (auto *info = std::get_if<QXmppDiscoInfo>(&result)) {
    qDebug() << "Features:" << info->features();
}

A payload is any type with a static XmlTag, a static fromDom() and a toXml() function:

struct StatusQuery {
    static constexpr std::tuple XmlTag = { u"status", u"urn:example:status" };
    static std::optional<StatusQuery> fromDom(const QDomElement &el);
    void toXml(QXmlStreamWriter *writer) const;

    QString text;
};

Incoming requests are answered by adding a handler to the hook QXmpp::Iq::Received for the type of the request. The handler returns the payload of the result, QXmpp::Success, a QXmppStanza::Error or a QXmppTask of them to reply asynchronously:

hooks().add<QXmpp::Iq::Received<QXmpp::Iq::Get<StatusQuery>>>([this](QXmpp::Iq::Get<StatusQuery> &&iq) {
    return StatusQuery { .text = m_status };
});

End-to-end encryption of IQs is opt-in via QXmpp::Iq::SendOptions and selected via the QXmpp::Iq::SelectEncryption hook. Replies to encrypted requests are encrypted the same way.

Hooks

Extensions are connected via hooks instead of virtual functions or signals. A hook is a type with a name and a handler signature; any extension (or the application) can add handlers to the hooks of the client. Handlers can run asynchronously, stop further handlers, be keyed (e.g. per PubSub node) or be the single responder of a hook. See QXmpp::Hooks for the details.

Extensions add their handlers in their constructor via QXmppClientExtension::hooks(), the application via QXmppClient::hooks(). Handlers are removed when their owner is destroyed:

// announce a feature via service discovery
client->hooks(this).add<QXmpp::Disco::CollectInfo>([](QList<QString> &features, QList<QXmppDiscoIdentity> &) {
    features.append(u"urn:example:status"_s);
});

Important hooks of QXmpp:

Messages and End-to-End Encryption

Incoming messages from the stream, message carbons and archive queries run through the message pipeline (see QXmpp::Messages): the real sender is resolved (e.g. in MUC rooms), the message is decrypted and the QXmpp::Messages::Received hook is run with its QXmpp::Messages::Context. Messages not consumed by a handler are delivered via QXmppClient::messageReceived(), also those of rooms joined via QXmppMucManagerV2. Messages of archive queries are returned by QXmppMamManager::retrieve().

Messages sent via QXmppClient::sendMessage() or QXmppClient::send() run through the outgoing pipeline. The application selects the end-to-end encryption via the QXmpp::Messages::SelectEncryption hook:

client->hooks(this).add<QXmpp::Messages::SelectEncryption>([this](QXmpp::Messages::EncryptionSelection &selection) {
    if (isEncryptionEnabled(selection.to())) {
        selection.setEncryption(QXmpp::E2ee::Omemo2);
    }
});

QXmppClient::sendMessage() reports in QXmpp::Messages::Sent how the message has been processed: the encryption actually used, the recipients, whether the delivery has been confirmed and, for MUC rooms and MIX channels, the ID of the message in their archive. Messages to rooms and channels finish after their reflection.

QXmppMessage message;
message.setTo(u"room@conference.example.org"_s);
message.setType(QXmppMessage::GroupChat);
message.setBody(u"Hello!"_s);

auto result = co_await client->sendMessage(std::move(message)).withContext(this);
if (auto *sent = std::get_if<QXmpp::Messages::Sent>(&result)) {
    // sent->deliveryState(), sent->archiveId(), ...
}

Encryptions are implemented as providers registered via QXmpp::E2ee::Providers, which decrypt incoming and encrypt outgoing messages and IQs. QXmppOmemoManager is the provider for OMEMO.

Managers

Managers are the primary way to use XMPP features. Register them with QXmppClient and extend QXmppClient by subclassing QXmppClientExtension. See the Managers module for the full list.

Messaging

Contacts and Roster

Groupchat

File Sharing

End-to-End Encryption

Calls

Bookmarks and PubSub

Service Discovery and Utilities

Legacy (deprecated)

Low-Level Stanza API

For direct access to XMPP stanzas: