aboutsummaryrefslogtreecommitdiff
path: root/src/org/jivesoftware/smackx/MessageEventManager.java
blob: 3502509d4394394c354061a7885ed8136c6c626d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright 2003-2007 Jive Software.
 *
 * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jivesoftware.smackx;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.packet.MessageEvent;

/**
 * Manages message events requests and notifications. A MessageEventManager provides a high
 * level access to request for notifications and send event notifications. It also provides 
 * an easy way to hook up custom logic when requests or notifications are received. 
 *
 * @author Gaston Dombiak
 */
public class MessageEventManager {

    private List<MessageEventNotificationListener> messageEventNotificationListeners = new ArrayList<MessageEventNotificationListener>();
    private List<MessageEventRequestListener> messageEventRequestListeners = new ArrayList<MessageEventRequestListener>();

    private Connection con;

    private PacketFilter packetFilter = new PacketExtensionFilter("x", "jabber:x:event");
    private PacketListener packetListener;

    /**
     * Creates a new message event manager.
     *
     * @param con a Connection to a XMPP server.
     */
    public MessageEventManager(Connection con) {
        this.con = con;
        init();
    }

    /**
     * Adds event notification requests to a message. For each event type that
     * the user wishes event notifications from the message recepient for, <tt>true</tt>
     * should be passed in to this method.
     * 
     * @param message the message to add the requested notifications.
     * @param offline specifies if the offline event is requested.
     * @param delivered specifies if the delivered event is requested.
     * @param displayed specifies if the displayed event is requested.
     * @param composing specifies if the composing event is requested.
     */
    public static void addNotificationsRequests(Message message, boolean offline,
            boolean delivered, boolean displayed, boolean composing)
    {
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setOffline(offline);
        messageEvent.setDelivered(delivered);
        messageEvent.setDisplayed(displayed);
        messageEvent.setComposing(composing);
        message.addExtension(messageEvent);
    }

    /**
     * Adds a message event request listener. The listener will be fired anytime a request for
     * event notification is received.
     *
     * @param messageEventRequestListener a message event request listener.
     */
    public void addMessageEventRequestListener(MessageEventRequestListener messageEventRequestListener) {
        synchronized (messageEventRequestListeners) {
            if (!messageEventRequestListeners.contains(messageEventRequestListener)) {
                messageEventRequestListeners.add(messageEventRequestListener);
            }
        }
    }

    /**
     * Removes a message event request listener. The listener will be fired anytime a request for
     * event notification is received.
     *
     * @param messageEventRequestListener a message event request listener.
     */
    public void removeMessageEventRequestListener(MessageEventRequestListener messageEventRequestListener) {
        synchronized (messageEventRequestListeners) {
            messageEventRequestListeners.remove(messageEventRequestListener);
        }
    }

    /**
     * Adds a message event notification listener. The listener will be fired anytime a notification
     * event is received.
     *
     * @param messageEventNotificationListener a message event notification listener.
     */
    public void addMessageEventNotificationListener(MessageEventNotificationListener messageEventNotificationListener) {
        synchronized (messageEventNotificationListeners) {
            if (!messageEventNotificationListeners.contains(messageEventNotificationListener)) {
                messageEventNotificationListeners.add(messageEventNotificationListener);
            }
        }
    }

    /**
     * Removes a message event notification listener. The listener will be fired anytime a notification
     * event is received.
     *
     * @param messageEventNotificationListener a message event notification listener.
     */
    public void removeMessageEventNotificationListener(MessageEventNotificationListener messageEventNotificationListener) {
        synchronized (messageEventNotificationListeners) {
            messageEventNotificationListeners.remove(messageEventNotificationListener);
        }
    }

    /**
     * Fires message event request listeners.
     */
    private void fireMessageEventRequestListeners(
        String from,
        String packetID,
        String methodName) {
        MessageEventRequestListener[] listeners = null;
        Method method;
        synchronized (messageEventRequestListeners) {
            listeners = new MessageEventRequestListener[messageEventRequestListeners.size()];
            messageEventRequestListeners.toArray(listeners);
        }
        try {
            method =
                MessageEventRequestListener.class.getDeclaredMethod(
                    methodName,
                    new Class[] { String.class, String.class, MessageEventManager.class });
            for (int i = 0; i < listeners.length; i++) {
                method.invoke(listeners[i], new Object[] { from, packetID, this });
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * Fires message event notification listeners.
     */
    private void fireMessageEventNotificationListeners(
        String from,
        String packetID,
        String methodName) {
        MessageEventNotificationListener[] listeners = null;
        Method method;
        synchronized (messageEventNotificationListeners) {
            listeners =
                new MessageEventNotificationListener[messageEventNotificationListeners.size()];
            messageEventNotificationListeners.toArray(listeners);
        }
        try {
            method =
                MessageEventNotificationListener.class.getDeclaredMethod(
                    methodName,
                    new Class[] { String.class, String.class });
            for (int i = 0; i < listeners.length; i++) {
                method.invoke(listeners[i], new Object[] { from, packetID });
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        // Listens for all message event packets and fire the proper message event listeners.
        packetListener = new PacketListener() {
            public void processPacket(Packet packet) {
                Message message = (Message) packet;
                MessageEvent messageEvent =
                    (MessageEvent) message.getExtension("x", "jabber:x:event");
                if (messageEvent.isMessageEventRequest()) {
                    // Fire event for requests of message events
                    for (Iterator<String> it = messageEvent.getEventTypes(); it.hasNext();)
                        fireMessageEventRequestListeners(
                            message.getFrom(),
                            message.getPacketID(),
                            it.next().concat("NotificationRequested"));
                } else
                    // Fire event for notifications of message events
                    for (Iterator<String> it = messageEvent.getEventTypes(); it.hasNext();)
                        fireMessageEventNotificationListeners(
                            message.getFrom(),
                            messageEvent.getPacketID(),
                            it.next().concat("Notification"));

            };

        };
        con.addPacketListener(packetListener, packetFilter);
    }

    /**
     * Sends the notification that the message was delivered to the sender of the original message
     * 
     * @param to the recipient of the notification.
     * @param packetID the id of the message to send.
     */
    public void sendDeliveredNotification(String to, String packetID) {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setDelivered(true);
        messageEvent.setPacketID(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        con.sendPacket(msg);
    }

    /**
     * Sends the notification that the message was displayed to the sender of the original message
     * 
     * @param to the recipient of the notification.
     * @param packetID the id of the message to send.
     */
    public void sendDisplayedNotification(String to, String packetID) {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setDisplayed(true);
        messageEvent.setPacketID(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        con.sendPacket(msg);
    }

    /**
     * Sends the notification that the receiver of the message is composing a reply
     * 
     * @param to the recipient of the notification.
     * @param packetID the id of the message to send.
     */
    public void sendComposingNotification(String to, String packetID) {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setComposing(true);
        messageEvent.setPacketID(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        con.sendPacket(msg);
    }

    /**
     * Sends the notification that the receiver of the message has cancelled composing a reply.
     * 
     * @param to the recipient of the notification.
     * @param packetID the id of the message to send.
     */
    public void sendCancelledNotification(String to, String packetID) {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setCancelled(true);
        messageEvent.setPacketID(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        con.sendPacket(msg);
    }

    public void destroy() {
        if (con != null) {
            con.removePacketListener(packetListener);
        }
    }

    protected void finalize() throws Throwable {
        destroy();
        super.finalize();
    }
}