MiguelHincapieC
MiguelHincapieC

Reputation: 5531

Chat Markers (XEP-0333) in Smack

There is an old question about this but at that time Smack didn't have support for this XMPP extension (XEP-0333). Also there is a question in discourse.igniterealtime.org but it has no answer and it was focused to ask when they are going to give support for xep-0333 extension.

At this moment it's supported by Smack in Experimental Smack Extensions and you can find the code here.

I have been looking for examples, guide or how to use this extension with no luck so far. I tried digging in the code too hoping find some javadoc about how to use but no success either.

The goal of this question is obtain a snippet of code of how can I use it in smack 4.x.x

Upvotes: 2

Views: 1112

Answers (1)

MiguelHincapieC
MiguelHincapieC

Reputation: 5531

update: waiting for a PR code review in order to update the following code.

Answering my own question:
As I said Smack library has Experimental support to XEP-0333, after try using it with version 4.2 and 4.3.0-rc1 I found the XEP-0333 needed be improved in order to make it works like IncomingChatMessageListener or ChatStateListener.

Moreover I couldn't make it works only using OutgoingChatMessageListener and IncomingChatMessageListener interfaces because inside they check that the <message> has a <body> tag (because xmpp protocol rules), but that rule doesn't apply to XEP-0333:

When the recipient sends a Chat Marker, it SHOULD ensure that the message stanza contains only the Chat Marker child element and optionally (when appropriate) a thread child element. Naturally, intermediate entities might add other extension elements to the message when routing or delivering the receipt message, e.g., a element as specified in Delayed Delivery (XEP-0203).

So what I did was improve ChatMarkersManager class following architecture and behavior from ChatManager (version 2) and ChatStateManager.

The following code is the improved one (I still need a feedback from Smack library guys) but it's working:

public final class ChatMarkersManager extends Manager {

private static final Map<XMPPConnection, ChatMarkersManager> INSTANCES = new WeakHashMap<>();

// @FORMATTER:OFF
private static final StanzaFilter FILTER = new NotFilter(new StanzaExtensionFilter(ChatMarkersElements.NAMESPACE));
private static final StanzaFilter CHAT_STATE_FILTER = new NotFilter(new StanzaExtensionFilter(ChatStateManager.NAMESPACE));

private static final StanzaFilter MESSAGE_FILTER = new OrFilter(
        MessageTypeFilter.NORMAL_OR_CHAT,
        MessageTypeFilter.GROUPCHAT
);

private static final StanzaFilter INCOMING_MESSAGE_FILTER = new AndFilter(
        MESSAGE_FILTER,
        new StanzaExtensionFilter(ChatMarkersElements.NAMESPACE)
);
// @FORMATTER:ON

private final Set<IncomingChatMarkerMessageListener> incomingListeners = new CopyOnWriteArraySet<>();

private final AsyncButOrdered<Chat> asyncButOrdered = new AsyncButOrdered<>();

private ChatMarkersManager(XMPPConnection connection) {
    super(connection);
    connection.addStanzaInterceptor(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet)
                throws
                SmackException.NotConnectedException,
                InterruptedException,
                SmackException.NotLoggedInException {
            Message message = (Message) packet;
            if (shouldDiscardMessage(message)) {
                return;
            }

            if (message.getBodies().isEmpty()) {
                return;
            }

            // if message already has a chatMarkerExtension, then do nothing,
            if (!FILTER.accept(message)) {
                return;
            }

            // otherwise add a markable extension,
            message.addExtension(new ChatMarkersElements.MarkableExtension());
        }
    }, MESSAGE_FILTER);

    connection.addSyncStanzaListener(new StanzaListener() {
        @Override
        public void processStanza(Stanza packet)
                throws
                SmackException.NotConnectedException,
                InterruptedException,
                SmackException.NotLoggedInException {
            final Message message = (Message) packet;
            if (shouldDiscardMessage(message)) {
                return;
            }

            EntityFullJid fullFrom = message.getFrom().asEntityFullJidIfPossible();
            EntityBareJid bareFrom = fullFrom.asEntityBareJid();
            final Chat chat = ChatManager.getInstanceFor(connection()).chatWith(bareFrom);

            List<IncomingChatMarkerMessageListener> listeners;
            synchronized (incomingListeners) {
                listeners = new ArrayList<>(incomingListeners.size());
                listeners.addAll(incomingListeners);
            }

            final List<IncomingChatMarkerMessageListener> finalListeners = listeners;
            asyncButOrdered.performAsyncButOrdered(chat, new Runnable() {
                @Override
                public void run() {
                    for (IncomingChatMarkerMessageListener listener : finalListeners) {
                        if (ChatMarkersElements.MarkableExtension.from(message) != null) {
                            listener.newMarkableMessage(message);
                        } else if (ChatMarkersElements.ReceivedExtension.from(message) != null) {
                            listener.newReceivedMessage(message);
                        } else if (ChatMarkersElements.DisplayedExtension.from(message) != null) {
                            listener.newDisplayedMessage(message);
                        } else if (ChatMarkersElements.AcknowledgedExtension.from(message) != null) {
                            listener.newAcknowledgedMessage(message);
                        }
                    }
                }
            });

        }
    }, INCOMING_MESSAGE_FILTER);

    ServiceDiscoveryManager.getInstanceFor(connection).addFeature(ChatMarkersElements.NAMESPACE);
}

/**
 * Get the singleton instance of ChatMarkersManager.
 *
 * @param connection
 * @return the instance of ChatMarkersManager
 */
public static synchronized ChatMarkersManager getInstanceFor(XMPPConnection connection) {
    ChatMarkersManager chatMarkersManager = INSTANCES.get(connection);

    if (chatMarkersManager == null) {
        chatMarkersManager = new ChatMarkersManager(connection);
        INSTANCES.put(connection, chatMarkersManager);
    }

    return chatMarkersManager;
}

/**
 * Register a IncomingChatMarkerMessageListener. That listener will be informed about new
 * incoming markable messages.
 *
 * @param listener IncomingChatMarkerMessageListener
 * @return true, if the listener was not registered before
 */
public boolean addIncomingChatMarkerMessageListener(IncomingChatMarkerMessageListener listener) {
    synchronized (incomingListeners) {
        return incomingListeners.add(listener);
    }
}

/**
 * Unregister a IncomingChatMarkerMessageListener.
 *
 * @param listener IncomingChatMarkerMessageListener
 * @return true, if the listener was registered before
 */
public boolean removeIncomingChatMarkerMessageListener(IncomingChatMarkerMessageListener listener) {
    synchronized (incomingListeners) {
        return incomingListeners.remove(listener);
    }
}

public void markMessageAsReceived(String id, Jid to, Jid from, String thread)
        throws
        SmackException.NotConnectedException,
        InterruptedException {
    Message message = createMessage(id, to, from, thread);
    message.addExtension(new ChatMarkersElements.ReceivedExtension(id));
    sendChatMarkerMessage(message);
}

public void markMessageAsDisplayed(String id, Jid to, Jid from, String thread)
        throws
        SmackException.NotConnectedException,
        InterruptedException {
    Message message = createMessage(id, to, from, thread);
    message.addExtension(new ChatMarkersElements.DisplayedExtension(id));
    sendChatMarkerMessage(message);
}

public void markMessageAsAcknowledged(String id, Jid to, Jid from, String thread)
        throws
        SmackException.NotConnectedException,
        InterruptedException {
    Message message = createMessage(id, to, from, thread);
    message.addExtension(new ChatMarkersElements.AcknowledgedExtension(id));
    sendChatMarkerMessage(message);
}

private Message createMessage(String id, Jid to, Jid from, String thread) {
    Message message = new Message();
    message.setStanzaId(id);
    message.setTo(to);
    message.setFrom(from);
    message.setThread(thread);
    return message;
}

private void sendChatMarkerMessage(Message message) throws SmackException.NotConnectedException, InterruptedException {
    connection().sendStanza(message);
}

/**
 * From XEP-0333, Protocol Format: The Chat Marker MUST have an 'id' which is the 'id' of the
 * message being marked.
 *
 * @param message to be analyzed.
 * @return true if the message contains a stanza Id.
 * @see <a href="http://xmpp.org/extensions/xep-0333.html">XEP-0333: Chat Markers</a>
 */
private boolean shouldDiscardMessage(Message message) {
    if (StringUtils.isNullOrEmpty(message.getStanzaId())) {
        return true;
    }

    if (!CHAT_STATE_FILTER.accept(message)) {
        ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE);
        String chatStateElementName = extension.getElementName();

        ChatState state;
        try {
            state = ChatState.valueOf(chatStateElementName);
            return !(state == ChatState.active);
        } catch (Exception ex) {
            return true;
        }
    }

    return false;
}

/**
 * Returns true if Chat Markers is supported by the server.
 *
 * @return true if Chat Markers is supported by the server.
 * @throws SmackException.NotConnectedException
 * @throws XMPPException.XMPPErrorException
 * @throws SmackException.NoResponseException
 * @throws InterruptedException
 */
public boolean isSupportedByServer()
        throws SmackException.NoResponseException, XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException {
    return ServiceDiscoveryManager.getInstanceFor(connection())
            .serverSupportsFeature(ChatMarkersElements.NAMESPACE);
}

}

The interface is simple:

public interface IncomingChatMarkerMessageListener {

void newMarkableMessage(Message message);
void newReceivedMessage(Message message);
void newDisplayedMessage(Message message);
void newAcknowledgedMessage(Message message);

}

At this moment I'm not using the Chat object so I'm not passing it through the interface but it can be added easily. Actually I want to be enable to deal with Chat and MultiChat.

This can be used alongside with XEP-0085 as the document suggest in 8.5 Interaction with Chat States.

Like I said before it's working, following protocol rules but I have some questions that I can't answer and I'm hopping get some feedback from Smack library guys :D

Upvotes: 4

Related Questions