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 static synchronized 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        // Create a MessageEvent Package and add it to the message
118        MessageEvent messageEvent = new MessageEvent();
119        messageEvent.setOffline(offline);
120        messageEvent.setDelivered(delivered);
121        messageEvent.setDisplayed(displayed);
122        messageEvent.setComposing(composing);
123        message.addExtension(messageEvent);
124    }
125
126    /**
127     * Adds a message event request listener. The listener will be fired anytime a request for
128     * event notification is received.
129     *
130     * @param messageEventRequestListener a message event request listener.
131     */
132    public void addMessageEventRequestListener(MessageEventRequestListener messageEventRequestListener) {
133        messageEventRequestListeners.add(messageEventRequestListener);
134
135    }
136
137    /**
138     * Removes a message event request listener. The listener will be fired anytime a request for
139     * event notification is received.
140     *
141     * @param messageEventRequestListener a message event request listener.
142     */
143    public void removeMessageEventRequestListener(MessageEventRequestListener messageEventRequestListener) {
144        messageEventRequestListeners.remove(messageEventRequestListener);
145    }
146
147    /**
148     * Adds a message event notification listener. The listener will be fired anytime a notification
149     * event is received.
150     *
151     * @param messageEventNotificationListener a message event notification listener.
152     */
153    public void addMessageEventNotificationListener(MessageEventNotificationListener messageEventNotificationListener) {
154        messageEventNotificationListeners.add(messageEventNotificationListener);
155    }
156
157    /**
158     * Removes a message event notification listener. The listener will be fired anytime a notification
159     * event is received.
160     *
161     * @param messageEventNotificationListener a message event notification listener.
162     */
163    public void removeMessageEventNotificationListener(MessageEventNotificationListener messageEventNotificationListener) {
164        messageEventNotificationListeners.remove(messageEventNotificationListener);
165    }
166
167    /**
168     * Fires message event request listeners.
169     */
170    private void fireMessageEventRequestListeners(
171        Jid from,
172        String packetID,
173        String methodName) {
174        try {
175            Method method =
176                MessageEventRequestListener.class.getDeclaredMethod(
177                    methodName,
178                    new Class<?>[] { Jid.class, String.class, MessageEventManager.class });
179            for (MessageEventRequestListener listener : messageEventRequestListeners) {
180                method.invoke(listener, new Object[] { from, packetID, this });
181            }
182        } catch (Exception e) {
183            LOGGER.log(Level.SEVERE, "Error while invoking MessageEventRequestListener's  " + methodName, e);
184        }
185    }
186
187    /**
188     * Fires message event notification listeners.
189     */
190    private void fireMessageEventNotificationListeners(
191        Jid from,
192        String packetID,
193        String methodName) {
194        try {
195            Method method =
196                MessageEventNotificationListener.class.getDeclaredMethod(
197                    methodName,
198                    new Class<?>[] { Jid.class, String.class });
199            for (MessageEventNotificationListener listener : messageEventNotificationListeners) {
200                method.invoke(listener, new Object[] { from, packetID });
201            }
202        } catch (Exception e) {
203            LOGGER.log(Level.SEVERE, "Error while invoking MessageEventNotificationListener's " + methodName, e);
204        }
205    }
206
207    /**
208     * Sends the notification that the message was delivered to the sender of the original message.
209     *
210     * @param to the recipient of the notification.
211     * @param packetID the id of the message to send.
212     * @throws NotConnectedException
213     * @throws InterruptedException
214     */
215    public void sendDeliveredNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
216        // Create the message to send
217        Message msg = new Message(to);
218        // Create a MessageEvent Package and add it to the message
219        MessageEvent messageEvent = new MessageEvent();
220        messageEvent.setDelivered(true);
221        messageEvent.setStanzaId(packetID);
222        msg.addExtension(messageEvent);
223        // Send the packet
224        connection().sendStanza(msg);
225    }
226
227    /**
228     * Sends the notification that the message was displayed to the sender of the original message.
229     *
230     * @param to the recipient of the notification.
231     * @param packetID the id of the message to send.
232     * @throws NotConnectedException
233     * @throws InterruptedException
234     */
235    public void sendDisplayedNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
236        // Create the message to send
237        Message msg = new Message(to);
238        // Create a MessageEvent Package and add it to the message
239        MessageEvent messageEvent = new MessageEvent();
240        messageEvent.setDisplayed(true);
241        messageEvent.setStanzaId(packetID);
242        msg.addExtension(messageEvent);
243        // Send the packet
244        connection().sendStanza(msg);
245    }
246
247    /**
248     * Sends the notification that the receiver of the message is composing a reply.
249     *
250     * @param to the recipient of the notification.
251     * @param packetID the id of the message to send.
252     * @throws NotConnectedException
253     * @throws InterruptedException
254     */
255    public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
256        // Create the message to send
257        Message msg = new Message(to);
258        // Create a MessageEvent Package and add it to the message
259        MessageEvent messageEvent = new MessageEvent();
260        messageEvent.setComposing(true);
261        messageEvent.setStanzaId(packetID);
262        msg.addExtension(messageEvent);
263        // Send the packet
264        connection().sendStanza(msg);
265    }
266
267    /**
268     * Sends the notification that the receiver of the message has cancelled composing a reply.
269     *
270     * @param to the recipient of the notification.
271     * @param packetID the id of the message to send.
272     * @throws NotConnectedException
273     * @throws InterruptedException
274     */
275    public void sendCancelledNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
276        // Create the message to send
277        Message msg = new Message(to);
278        // Create a MessageEvent Package and add it to the message
279        MessageEvent messageEvent = new MessageEvent();
280        messageEvent.setCancelled(true);
281        messageEvent.setStanzaId(packetID);
282        msg.addExtension(messageEvent);
283        // Send the packet
284        connection().sendStanza(msg);
285    }
286}