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.xevent;
019
020import java.lang.reflect.Method;
021import java.util.List;
022import java.util.Map;
023import java.util.WeakHashMap;
024import java.util.concurrent.CopyOnWriteArrayList;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028import org.jivesoftware.smack.Manager;
029import org.jivesoftware.smack.SmackException.NotConnectedException;
030import org.jivesoftware.smack.StanzaListener;
031import org.jivesoftware.smack.XMPPConnection;
032import org.jivesoftware.smack.filter.AndFilter;
033import org.jivesoftware.smack.filter.MessageTypeFilter;
034import org.jivesoftware.smack.filter.NotFilter;
035import org.jivesoftware.smack.filter.StanzaExtensionFilter;
036import org.jivesoftware.smack.filter.StanzaFilter;
037import org.jivesoftware.smack.packet.Message;
038import org.jivesoftware.smack.packet.Stanza;
039
040import org.jivesoftware.smackx.xevent.packet.MessageEvent;
041
042import org.jxmpp.jid.Jid;
043
044/**
045 * 
046 * Manages message events requests and notifications. A MessageEventManager provides a high
047 * level access to request for notifications and send event notifications. It also provides 
048 * an easy way to hook up custom logic when requests or notifications are received. 
049 *
050 * @author Gaston Dombiak
051 * @see <a href="http://xmpp.org/extensions/xep-0022.html">XEP-22: Message Events</a>
052 */
053public final class MessageEventManager extends Manager {
054    private static final Logger LOGGER = Logger.getLogger(MessageEventManager.class.getName());
055
056    private static final Map<XMPPConnection, MessageEventManager> INSTANCES = new WeakHashMap<>();
057
058    private static final StanzaFilter PACKET_FILTER = new AndFilter(new StanzaExtensionFilter(
059                    new MessageEvent()), new NotFilter(MessageTypeFilter.ERROR));
060
061    private final List<MessageEventNotificationListener> messageEventNotificationListeners = new CopyOnWriteArrayList<>();
062    private final List<MessageEventRequestListener> messageEventRequestListeners = new CopyOnWriteArrayList<>();
063
064    public synchronized static MessageEventManager getInstanceFor(XMPPConnection connection) {
065        MessageEventManager messageEventManager = INSTANCES.get(connection);
066        if (messageEventManager == null) {
067            messageEventManager = new MessageEventManager(connection);
068            INSTANCES.put(connection, messageEventManager);
069        }
070        return messageEventManager;
071    }
072
073    /**
074     * Creates a new message event manager.
075     *
076     * @param connection an XMPPConnection to a XMPP server.
077     */
078    private MessageEventManager(XMPPConnection connection) {
079        super(connection);
080        // Listens for all message event packets and fire the proper message event listeners.
081        connection.addAsyncStanzaListener(new StanzaListener() {
082            @Override
083            public void processStanza(Stanza packet) {
084                Message message = (Message) packet;
085                MessageEvent messageEvent = message.getExtension("x", "jabber:x:event");
086                if (messageEvent.isMessageEventRequest()) {
087                    // Fire event for requests of message events
088                    for (String eventType : messageEvent.getEventTypes())
089                        fireMessageEventRequestListeners(
090                            message.getFrom(),
091                            message.getStanzaId(),
092                            eventType.concat("NotificationRequested"));
093                } else
094                    // Fire event for notifications of message events
095                    for (String eventType : messageEvent.getEventTypes())
096                        fireMessageEventNotificationListeners(
097                            message.getFrom(),
098                            messageEvent.getStanzaId(),
099                            eventType.concat("Notification"));
100            }
101        }, PACKET_FILTER);
102    }
103
104    /**
105     * Adds event notification requests to a message. For each event type that
106     * the user wishes event notifications from the message recipient for, <tt>true</tt>
107     * should be passed in to this method.
108     * 
109     * @param message the message to add the requested notifications.
110     * @param offline specifies if the offline event is requested.
111     * @param delivered specifies if the delivered event is requested.
112     * @param displayed specifies if the displayed event is requested.
113     * @param composing specifies if the composing event is requested.
114     */
115    public static void addNotificationsRequests(Message message, boolean offline,
116            boolean delivered, boolean displayed, boolean composing)
117    {
118        // Create a MessageEvent Package and add it to the message
119        MessageEvent messageEvent = new MessageEvent();
120        messageEvent.setOffline(offline);
121        messageEvent.setDelivered(delivered);
122        messageEvent.setDisplayed(displayed);
123        messageEvent.setComposing(composing);
124        message.addExtension(messageEvent);
125    }
126
127    /**
128     * Adds a message event request listener. The listener will be fired anytime a request for
129     * event notification is received.
130     *
131     * @param messageEventRequestListener a message event request listener.
132     */
133    public void addMessageEventRequestListener(MessageEventRequestListener messageEventRequestListener) {
134        messageEventRequestListeners.add(messageEventRequestListener);
135
136    }
137
138    /**
139     * Removes a message event request listener. The listener will be fired anytime a request for
140     * event notification is received.
141     *
142     * @param messageEventRequestListener a message event request listener.
143     */
144    public void removeMessageEventRequestListener(MessageEventRequestListener messageEventRequestListener) {
145        messageEventRequestListeners.remove(messageEventRequestListener);
146    }
147
148    /**
149     * Adds a message event notification listener. The listener will be fired anytime a notification
150     * event is received.
151     *
152     * @param messageEventNotificationListener a message event notification listener.
153     */
154    public void addMessageEventNotificationListener(MessageEventNotificationListener messageEventNotificationListener) {
155        messageEventNotificationListeners.add(messageEventNotificationListener);
156    }
157
158    /**
159     * Removes a message event notification listener. The listener will be fired anytime a notification
160     * event is received.
161     *
162     * @param messageEventNotificationListener a message event notification listener.
163     */
164    public void removeMessageEventNotificationListener(MessageEventNotificationListener messageEventNotificationListener) {
165        messageEventNotificationListeners.remove(messageEventNotificationListener);
166    }
167
168    /**
169     * Fires message event request listeners.
170     */
171    private void fireMessageEventRequestListeners(
172        Jid from,
173        String packetID,
174        String methodName) {
175        try {
176            Method method =
177                MessageEventRequestListener.class.getDeclaredMethod(
178                    methodName,
179                    new Class<?>[] { Jid.class, String.class, MessageEventManager.class });
180            for (MessageEventRequestListener listener : messageEventRequestListeners) {
181                method.invoke(listener, new Object[] { from, packetID, this });
182            }
183        } catch (Exception e) {
184            LOGGER.log(Level.SEVERE, "Error while invoking MessageEventRequestListener's  " + methodName, e);
185        }
186    }
187
188    /**
189     * Fires message event notification listeners.
190     */
191    private void fireMessageEventNotificationListeners(
192        Jid from,
193        String packetID,
194        String methodName) {
195        try {
196            Method method =
197                MessageEventNotificationListener.class.getDeclaredMethod(
198                    methodName,
199                    new Class<?>[] { Jid.class, String.class });
200            for (MessageEventNotificationListener listener : messageEventNotificationListeners) {
201                method.invoke(listener, new Object[] { from, packetID });
202            }
203        } catch (Exception e) {
204            LOGGER.log(Level.SEVERE, "Error while invoking MessageEventNotificationListener's " + methodName, e);
205        }
206    }
207
208    /**
209     * Sends the notification that the message was delivered to the sender of the original message.
210     * 
211     * @param to the recipient of the notification.
212     * @param packetID the id of the message to send.
213     * @throws NotConnectedException 
214     * @throws InterruptedException 
215     */
216    public void sendDeliveredNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
217        // Create the message to send
218        Message msg = new Message(to);
219        // Create a MessageEvent Package and add it to the message
220        MessageEvent messageEvent = new MessageEvent();
221        messageEvent.setDelivered(true);
222        messageEvent.setStanzaId(packetID);
223        msg.addExtension(messageEvent);
224        // Send the packet
225        connection().sendStanza(msg);
226    }
227
228    /**
229     * Sends the notification that the message was displayed to the sender of the original message.
230     * 
231     * @param to the recipient of the notification.
232     * @param packetID the id of the message to send.
233     * @throws NotConnectedException 
234     * @throws InterruptedException 
235     */
236    public void sendDisplayedNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
237        // Create the message to send
238        Message msg = new Message(to);
239        // Create a MessageEvent Package and add it to the message
240        MessageEvent messageEvent = new MessageEvent();
241        messageEvent.setDisplayed(true);
242        messageEvent.setStanzaId(packetID);
243        msg.addExtension(messageEvent);
244        // Send the packet
245        connection().sendStanza(msg);
246    }
247
248    /**
249     * Sends the notification that the receiver of the message is composing a reply.
250     * 
251     * @param to the recipient of the notification.
252     * @param packetID the id of the message to send.
253     * @throws NotConnectedException 
254     * @throws InterruptedException 
255     */
256    public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
257        // Create the message to send
258        Message msg = new Message(to);
259        // Create a MessageEvent Package and add it to the message
260        MessageEvent messageEvent = new MessageEvent();
261        messageEvent.setComposing(true);
262        messageEvent.setStanzaId(packetID);
263        msg.addExtension(messageEvent);
264        // Send the packet
265        connection().sendStanza(msg);
266    }
267
268    /**
269     * Sends the notification that the receiver of the message has cancelled composing a reply.
270     * 
271     * @param to the recipient of the notification.
272     * @param packetID the id of the message to send.
273     * @throws NotConnectedException 
274     * @throws InterruptedException 
275     */
276    public void sendCancelledNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
277        // Create the message to send
278        Message msg = new Message(to);
279        // Create a MessageEvent Package and add it to the message
280        MessageEvent messageEvent = new MessageEvent();
281        messageEvent.setCancelled(true);
282        messageEvent.setStanzaId(packetID);
283        msg.addExtension(messageEvent);
284        // Send the packet
285        connection().sendStanza(msg);
286    }
287}