001/**
002 *
003 * Copyright 2018 Miguel Hincapie.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.chat_markers.filter;
018
019import org.jivesoftware.smack.filter.StanzaExtensionFilter;
020import org.jivesoftware.smack.packet.ExtensionElement;
021import org.jivesoftware.smack.packet.Stanza;
022
023import org.jivesoftware.smackx.chatstates.ChatState;
024import org.jivesoftware.smackx.chatstates.ChatStateManager;
025
026/**
027 * Chat Markers Manager class (XEP-0333).
028 *
029 * @author Miguel Hincapie
030 * @see <a href="http://xmpp.org/extensions/xep-0333.html">XEP-0333: Chat
031 * Markers</a>
032 */
033public final class EligibleForChatMarkerFilter extends StanzaExtensionFilter {
034
035    public static final EligibleForChatMarkerFilter INSTANCE = new EligibleForChatMarkerFilter(ChatStateManager.NAMESPACE);
036
037    private EligibleForChatMarkerFilter(String namespace) {
038        super(namespace);
039    }
040
041    /**
042     * From XEP-0333, Protocol Format: The Chat Marker MUST have an 'id' which is the 'id' of the
043     * message being marked.<br>
044     * In order to make Chat Markers works together with XEP-0085 as it said in
045     * 8.5 Interaction with Chat States, only messages with <code>active</code> chat
046     * state are accepted.
047     *
048     * @param message to be analyzed.
049     * @return true if the message contains a stanza Id.
050     * @see <a href="http://xmpp.org/extensions/xep-0333.html">XEP-0333: Chat Markers</a>
051     */
052    @Override
053    public boolean accept(Stanza message) {
054        if (!message.hasStanzaIdSet()) {
055            return false;
056        }
057
058        if (super.accept(message)) {
059            ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE);
060            String chatStateElementName = extension.getElementName();
061
062            ChatState state;
063            try {
064                state = ChatState.valueOf(chatStateElementName);
065                return state == ChatState.active;
066            }
067            catch (Exception ex) {
068                return false;
069            }
070        }
071
072        return true;
073    }
074}