aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetTypingNotificationsJabberImpl.java
blob: 87702b24ee3e35907c328cbdb6c8ce63573ba2ad (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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.protocol.jabber;

import java.util.*;

import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.util.*;
import org.jivesoftware.smackx.*;

/**
 * Maps SIP Communicator typing notifications to those going and coming from
 * smack lib.
 *
 * @author Damian Minkov
 * @author Emil Ivov
 */
public class OperationSetTypingNotificationsJabberImpl
    extends AbstractOperationSetTypingNotifications<ProtocolProviderServiceJabberImpl>
{
    private static final Logger logger =
        Logger.getLogger(OperationSetTypingNotificationsJabberImpl.class);

    /**
     * An active instance of the opSetPersPresence operation set. We're using
     * it to map incoming events to contacts in our contact list.
     */
    private OperationSetPersistentPresenceJabberImpl opSetPersPresence = null;

    /**
     * We use this listener to ceise the moment when the protocol provider
     * has been successfully registered.
     */
    private ProviderRegListener providerRegListener = new ProviderRegListener();

    /**
     * The manger which send us the typing info and through which we send inf
     */
    private MessageEventManager messageEventManager = null;

    private Hashtable packetIDsTable = new Hashtable();

    /**
     * The listener instance that we use to track chat states according to
     * XEP-0085;
     */
    private SmackChatStateListener smackChatStateListener = null;

    /**
     * The listener instance that we use in order to track for new chats so that
     * we could stick a SmackChatStateListener to them.
     */
    private SmackChatManagerListener smackChatManagerListener = null;

    /**
     * @param provider a ref to the <tt>ProtocolProviderServiceImpl</tt>
     * that created us and that we'll use for retrieving the underlying aim
     * connection.
     */
    OperationSetTypingNotificationsJabberImpl(
        ProtocolProviderServiceJabberImpl provider)
    {
        super(provider);

        provider.addRegistrationStateChangeListener(providerRegListener);
    }

    /**
     * Sends a notification to <tt>notifiedContatct</tt> that we have entered
     * <tt>typingState</tt>.
     *
     * @param notifiedContact the <tt>Contact</tt> to notify
     * @param typingState the typing state that we have entered.
     *
     * @throws java.lang.IllegalStateException if the underlying stack is
     * not registered and initialized.
     * @throws java.lang.IllegalArgumentException if <tt>notifiedContact</tt> is
     * not an instance belonging to the underlying implementation.
     */
    public void sendTypingNotification(Contact notifiedContact, int typingState)
        throws IllegalStateException, IllegalArgumentException
    {
        assertConnected();

        if( !(notifiedContact instanceof ContactJabberImpl) )
           throw new IllegalArgumentException(
               "The specified contact is not a Jabber contact."
               + notifiedContact);

        /**
         * Emil Ivov: We used to use this in while we were still using XEP-0022
         * to send typing notifications. I am commenting it out today on
         * 2008-08-20 as we now also support XEP-0085 (see below) and using both
         * mechanisms sends double notifications which, apart from simply being
         * redundant, is also causing the jabber slick to fail.
         *
        String packetID =
            (String)packetIDsTable.get(notifiedContact.getAddress());

        //First do XEP-0022 notifications
        if(packetID != null)
        {
            if(typingState == STATE_TYPING)
            {
                messageEventManager.
                    sendComposingNotification(notifiedContact.getAddress(),
                                              packetID);
            }
            else if(typingState == STATE_STOPPED)
            {
                messageEventManager.
                    sendCancelledNotification(notifiedContact.getAddress(),
                                              packetID);
                packetIDsTable.remove(notifiedContact.getAddress());
            }
        }
        */

        //now handle XEP-0085
        sendXep85ChatState(notifiedContact, typingState);
    }

    /**
     * Converts <tt>state</tt> into the corresponding smack <tt>ChatState</tt>
     * and sends it to contact.
     *
     * @param contact the contact that we'd like to send our state to.
     * @param state the state we'd like to sent.
     */
    private void sendXep85ChatState(Contact contact, int state)
    {
        logger.trace("Sending XEP-0085 chat state=" + state
            + " to " + contact.getAddress());

        Chat chat = parentProvider.getConnection()
            .getChatManager().createChat(contact.getAddress(), null);

        ChatState chatState = null;


        if(state == STATE_TYPING)
        {
            chatState = ChatState.composing;
        }
        else if(state == STATE_STOPPED)
        {
            chatState = ChatState.inactive;
        }
        else if(state == STATE_PAUSED)
        {
            chatState = ChatState.paused;
        }
        else
        {
            chatState = ChatState.gone;
        }

        try
        {
            ChatStateManager.getInstance(parentProvider.getConnection())
                .setCurrentState(chatState, chat);
        }
        catch(XMPPException exc)
        {
            //we don't want to bother the user with network exceptions
            //so let's simply log it.
            logger.warn("Failed to send state [" + state + "] to ["
                + contact.getAddress() + "].", exc);
        }
    }

    /**
     * Our listener that will tell us when we're registered and
     * ready to accept us as a listener.
     */
    private class ProviderRegListener
        implements RegistrationStateChangeListener
    {
        /**
         * The method is called by a ProtocolProvider implementation whenver
         * a change in the registration state of the corresponding provider had
         * occurred.
         * @param evt ProviderStatusChangeEvent the event describing the status
         * change.
         */
        public void registrationStateChanged(RegistrationStateChangeEvent evt)
        {
            logger.debug("The provider changed state from: "
                         + evt.getOldState()
                         + " to: " + evt.getNewState());
            if (evt.getNewState() == RegistrationState.REGISTERED)
            {
                opSetPersPresence =
                    (OperationSetPersistentPresenceJabberImpl) parentProvider
                        .getOperationSet(OperationSetPersistentPresence.class);

                messageEventManager =
                    new MessageEventManager(parentProvider.getConnection());

                messageEventManager.addMessageEventRequestListener(
                    new JabberMessageEventRequestListener());
                messageEventManager.addMessageEventNotificationListener(
                    new IncomingMessageEventsListener());

                //according to the smack api documentation we need to do this
                //every time we connect in order to reinitialize the chat state
                //manager (@see http://tinyurl.com/6j9uqs )

                ChatStateManager.getInstance(parentProvider.getConnection());

                if(smackChatManagerListener == null)
                    smackChatManagerListener = new SmackChatManagerListener();

                parentProvider.getConnection().getChatManager()
                    .addChatListener(smackChatManagerListener);
            }
        }
    }

    /**
     * The class that we use when listening for new chats so that we could start
     * tracking them for chat events.
     */
    private class SmackChatManagerListener implements ChatManagerListener
    {
        /**
         * Simply adds a chat state listener to every newly created chat
         * so that we could track it for chat state events.
         *
         * @param chat the chat that we need to add a state listener to.
         * @param isLocal indicates whether the chat has been initiated by us
         */
        public void chatCreated(Chat chat, boolean isLocal)
        {
            logger.trace("Created a chat with "
                + chat.getParticipant() + " local="+isLocal);

            if(smackChatStateListener == null)
                smackChatStateListener = new SmackChatStateListener();

            chat.addMessageListener(smackChatStateListener);
        };
    }

    /**
     * Listens for incoming request for typing info
     */
    private class JabberMessageEventRequestListener
        implements MessageEventRequestListener
    {
        public void deliveredNotificationRequested(String from, String packetID,
            MessageEventManager messageEventManager)
        {
            messageEventManager.sendDeliveredNotification(from, packetID);
        }

        public void displayedNotificationRequested(String from, String packetID,
            MessageEventManager messageEventManager)
        {
            messageEventManager.sendDisplayedNotification(from, packetID);
        }

        public void composingNotificationRequested(String from, String packetID,
            MessageEventManager messageEventManager)
        {
            if(packetID != null)
            {
                String fromID = StringUtils.parseBareAddress(from);
                packetIDsTable.put(fromID, packetID);
            }
        }

        public void offlineNotificationRequested(String from, String packetID,
                                                 MessageEventManager
                                                 messageEventManager)
        {}
    }

    /**
     * Receives incoming typing info
     */
    private class IncomingMessageEventsListener
        implements MessageEventNotificationListener
    {
        public void deliveredNotification(String from, String packetID)
        {
        }

        public void displayedNotification(String from, String packetID)
        {
        }

        public void composingNotification(String from, String packetID)
        {
            String fromID = StringUtils.parseBareAddress(from);

            Contact sourceContact = opSetPersPresence.findContactByID(fromID);

            if(sourceContact == null)
            {
                //create the volatile contact
                sourceContact = opSetPersPresence.createVolatileContact(fromID);
            }

            fireTypingNotificationsEvent(sourceContact, STATE_TYPING);
        }

        public void offlineNotification(String from, String packetID)
        {
        }

        public void cancelledNotification(String from, String packetID)
        {
            String fromID = StringUtils.parseBareAddress(from);
            Contact sourceContact = opSetPersPresence.findContactByID(fromID);

            if(sourceContact == null)
            {
                //create the volatile contact
                sourceContact = opSetPersPresence.createVolatileContact(fromID);
            }

            fireTypingNotificationsEvent(sourceContact, STATE_STOPPED);
        }
    }


    /**
     * The listener that we use to track chat state notifications according
     * to XEP-0085.
     */
    private class SmackChatStateListener implements ChatStateListener
    {
        /**
         * Called by smack when the state of a chat changes.
         *
         * @param chat the chat that is concerned by this event.
         * @param state the new state of the chat.
         */
        public void stateChanged(Chat chat, ChatState state)
        {
            logger.trace(chat.getParticipant() + " entered the "
                + state.name()+ " state.");

            String fromID = StringUtils.parseBareAddress(chat.getParticipant());
            Contact sourceContact = opSetPersPresence.findContactByID(fromID);

            if(sourceContact == null)
            {
                //create the volatile contact
                sourceContact = opSetPersPresence.createVolatileContact(fromID);
            }

            if (ChatState.composing.equals(state))
            {
                fireTypingNotificationsEvent(sourceContact, STATE_TYPING);
            }
            else if (ChatState.paused.equals(state)
                || ChatState.active.equals(state) )
            {
                fireTypingNotificationsEvent(sourceContact, STATE_PAUSED);
            }
            else if (ChatState.inactive.equals(state)
                || ChatState.gone.equals(state) )
            {
                fireTypingNotificationsEvent(sourceContact, STATE_STOPPED);
            }
        }

        /**
         * Called when a new message is received. We ignore this one since
         * we handle message reception on a lower level.
         *
         * @param chat the chat that the message belongs to
         * @param msg the message that we need to process.
         */
        public void processMessage(Chat chat,
                                    org.jivesoftware.smack.packet.Message msg)
        {
            logger.trace("ignoring a process message");

        }
    }
}