001/**
002 *
003 * Copyright 2003-2007 Jive Software.
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 */
017
018package org.jivesoftware.smackx.chatstates;
019
020import java.util.Map;
021import java.util.WeakHashMap;
022
023import org.jivesoftware.smack.Manager;
024import org.jivesoftware.smack.MessageListener;
025import org.jivesoftware.smack.SmackException.NotConnectedException;
026import org.jivesoftware.smack.XMPPConnection;
027import org.jivesoftware.smack.chat.ChatManagerListener;
028import org.jivesoftware.smack.chat.ChatMessageListener;
029import org.jivesoftware.smack.filter.NotFilter;
030import org.jivesoftware.smack.filter.StanzaExtensionFilter;
031import org.jivesoftware.smack.filter.StanzaFilter;
032import org.jivesoftware.smack.packet.ExtensionElement;
033import org.jivesoftware.smack.packet.Message;
034
035import org.jivesoftware.smackx.chatstates.packet.ChatStateExtension;
036import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
037
038/**
039 * Handles chat state for all chats on a particular XMPPConnection. This class manages both the
040 * stanza(/packet) extensions and the disco response necessary for compliance with
041 * <a href="http://www.xmpp.org/extensions/xep-0085.html">XEP-0085</a>.
042 *
043 * NOTE: {@link org.jivesoftware.smackx.chatstates.ChatStateManager#getInstance(org.jivesoftware.smack.XMPPConnection)}
044 * needs to be called in order for the listeners to be registered appropriately with the connection.
045 * If this does not occur you will not receive the update notifications.
046 *
047 * @author Alexander Wenckus
048 * @see org.jivesoftware.smackx.chatstates.ChatState
049 * @see org.jivesoftware.smackx.chatstates.packet.ChatStateExtension
050 */
051// TODO Migrate to new chat2 API on Smack 4.3.
052@SuppressWarnings("deprecation")
053public final class ChatStateManager extends Manager {
054    public static final String NAMESPACE = "http://jabber.org/protocol/chatstates";
055
056    private static final Map<XMPPConnection, ChatStateManager> INSTANCES = new WeakHashMap<>();
057
058    private static final StanzaFilter filter = new NotFilter(new StanzaExtensionFilter(NAMESPACE));
059
060    /**
061     * Returns the ChatStateManager related to the XMPPConnection and it will create one if it does
062     * not yet exist.
063     *
064     * @param connection the connection to return the ChatStateManager
065     * @return the ChatStateManager related the the connection.
066     */
067    public static synchronized ChatStateManager getInstance(final XMPPConnection connection) {
068            ChatStateManager manager = INSTANCES.get(connection);
069            if (manager == null) {
070                manager = new ChatStateManager(connection);
071            }
072            return manager;
073    }
074
075    private final OutgoingMessageInterceptor outgoingInterceptor = new OutgoingMessageInterceptor();
076
077    private final IncomingMessageInterceptor incomingInterceptor = new IncomingMessageInterceptor();
078
079    /**
080     * Maps chat to last chat state.
081     */
082    private final Map<org.jivesoftware.smack.chat.Chat, ChatState> chatStates = new WeakHashMap<>();
083
084    private final org.jivesoftware.smack.chat.ChatManager chatManager;
085
086    private ChatStateManager(XMPPConnection connection) {
087        super(connection);
088        chatManager = org.jivesoftware.smack.chat.ChatManager.getInstanceFor(connection);
089        chatManager.addOutgoingMessageInterceptor(outgoingInterceptor, filter);
090        chatManager.addChatListener(incomingInterceptor);
091
092        ServiceDiscoveryManager.getInstanceFor(connection).addFeature(NAMESPACE);
093        INSTANCES.put(connection, this);
094    }
095
096
097    /**
098     * Sets the current state of the provided chat. This method will send an empty bodied Message
099     * stanza(/packet) with the state attached as a {@link org.jivesoftware.smack.packet.ExtensionElement}, if
100     * and only if the new chat state is different than the last state.
101     *
102     * @param newState the new state of the chat
103     * @param chat the chat.
104     * @throws NotConnectedException 
105     * @throws InterruptedException 
106     */
107    public void setCurrentState(ChatState newState, org.jivesoftware.smack.chat.Chat chat) throws NotConnectedException, InterruptedException {
108        if (chat == null || newState == null) {
109            throw new IllegalArgumentException("Arguments cannot be null.");
110        }
111        if (!updateChatState(chat, newState)) {
112            return;
113        }
114        Message message = new Message();
115        ChatStateExtension extension = new ChatStateExtension(newState);
116        message.addExtension(extension);
117
118        chat.sendMessage(message);
119    }
120
121
122    @Override
123    public boolean equals(Object o) {
124        if (this == o) return true;
125        if (o == null || getClass() != o.getClass()) return false;
126
127        ChatStateManager that = (ChatStateManager) o;
128
129        return connection().equals(that.connection());
130
131    }
132
133    @Override
134    public int hashCode() {
135        return connection().hashCode();
136    }
137
138    private synchronized boolean updateChatState(org.jivesoftware.smack.chat.Chat chat, ChatState newState) {
139        ChatState lastChatState = chatStates.get(chat);
140        if (lastChatState != newState) {
141            chatStates.put(chat, newState);
142            return true;
143        }
144        return false;
145    }
146
147    private static void fireNewChatState(org.jivesoftware.smack.chat.Chat chat, ChatState state, Message message) {
148        for (ChatMessageListener listener : chat.getListeners()) {
149            if (listener instanceof ChatStateListener) {
150                ((ChatStateListener) listener).stateChanged(chat, state, message);
151            }
152        }
153    }
154
155    private class OutgoingMessageInterceptor implements MessageListener {
156
157        @Override
158        public void processMessage(Message message) {
159            org.jivesoftware.smack.chat.Chat chat = chatManager.getThreadChat(message.getThread());
160            if (chat == null) {
161                return;
162            }
163            if (updateChatState(chat, ChatState.active)) {
164                message.addExtension(new ChatStateExtension(ChatState.active));
165            }
166        }
167    }
168
169    private static class IncomingMessageInterceptor implements ChatManagerListener, ChatMessageListener {
170
171        @Override
172        public void chatCreated(final org.jivesoftware.smack.chat.Chat chat, boolean createdLocally) {
173            chat.addMessageListener(this);
174        }
175
176        @Override
177        public void processMessage(org.jivesoftware.smack.chat.Chat chat, Message message) {
178            ExtensionElement extension = message.getExtension(NAMESPACE);
179            if (extension == null) {
180                return;
181            }
182
183            ChatState state;
184            try {
185                state = ChatState.valueOf(extension.getElementName());
186            }
187            catch (Exception ex) {
188                return;
189            }
190
191            fireNewChatState(chat, state, message);
192        }
193    }
194}