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 = (MessageEvent) message.getExtensionElement("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, <code>true</code>
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 if the XMPP connection is not connected.
213     * @throws InterruptedException if the calling thread was interrupted.
214     */
215    public void sendDeliveredNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
216        // Create a MessageEvent Package and add it to the message
217        MessageEvent messageEvent = new MessageEvent();
218        messageEvent.setDelivered(true);
219        messageEvent.setStanzaId(packetID);
220
221        XMPPConnection connection = connection();
222        Message msg = connection.getStanzaFactory().buildMessageStanza()
223                .to(to)
224                .addExtension(messageEvent)
225                .build();
226        // Send the packet
227        connection.sendStanza(msg);
228    }
229
230    /**
231     * Sends the notification that the message was displayed to the sender of the original message.
232     *
233     * @param to the recipient of the notification.
234     * @param packetID the id of the message to send.
235     * @throws NotConnectedException if the XMPP connection is not connected.
236     * @throws InterruptedException if the calling thread was interrupted.
237     */
238    public void sendDisplayedNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
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
244        XMPPConnection connection = connection();
245        Message msg = connection.getStanzaFactory().buildMessageStanza()
246                .to(to)
247                .addExtension(messageEvent)
248                .build();
249        // Send the packet
250        connection.sendStanza(msg);
251    }
252
253    /**
254     * Sends the notification that the receiver of the message is composing a reply.
255     *
256     * @param to the recipient of the notification.
257     * @param packetID the id of the message to send.
258     * @throws NotConnectedException if the XMPP connection is not connected.
259     * @throws InterruptedException if the calling thread was interrupted.
260     */
261    public void sendComposingNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
262        // Create a MessageEvent Package and add it to the message
263        MessageEvent messageEvent = new MessageEvent();
264        messageEvent.setComposing(true);
265        messageEvent.setStanzaId(packetID);
266
267        XMPPConnection connection = connection();
268        Message msg = connection.getStanzaFactory().buildMessageStanza()
269                .to(to)
270                .addExtension(messageEvent)
271                .build();
272        // Send the packet
273        connection.sendStanza(msg);
274    }
275
276    /**
277     * Sends the notification that the receiver of the message has cancelled composing a reply.
278     *
279     * @param to the recipient of the notification.
280     * @param packetID the id of the message to send.
281     * @throws NotConnectedException if the XMPP connection is not connected.
282     * @throws InterruptedException if the calling thread was interrupted.
283     */
284    public void sendCancelledNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
285        // Create a MessageEvent Package and add it to the message
286        MessageEvent messageEvent = new MessageEvent();
287        messageEvent.setCancelled(true);
288        messageEvent.setStanzaId(packetID);
289
290        XMPPConnection connection = connection();
291
292        Message msg = connection.getStanzaFactory().buildMessageStanza()
293                .to(to)
294                .addExtension(messageEvent)
295                .build();
296        // Send the packet
297        connection().sendStanza(msg);
298    }
299}