aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/muc/ChatRoomQuery.java
blob: 9cd1c21f5b8a36f73cdf3e1c90eece066ee19d23 (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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * 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 net.java.sip.communicator.impl.muc;

import java.util.*;
import java.util.regex.*;

import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.muc.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;

import org.osgi.framework.*;

/**
 * The <tt>ChatRoomQuery</tt> is a query over the
 * <tt>ChatRoomContactSourceService</tt>.
 * 
 * @author Hristo Terezov
 */
public class ChatRoomQuery
    extends AsyncContactQuery<ContactSourceService>
    implements LocalUserChatRoomPresenceListener,
               ChatRoomListChangeListener,
               ChatRoomProviderWrapperListener
{
    /**
     * The query string.
     */
    private String queryString;

    /**
     * List with the current results for the query.
     */
    private Set<ChatRoomSourceContact> contactResults
        = new TreeSet<ChatRoomSourceContact>();

    /**
     * MUC service.
     */
    private MUCServiceImpl mucService;

    /**
     * The number of contact query listeners.
     */
    private int contactQueryListenersCount = 0;

    /**
     * The protocol provider registration listener.
     */
    private ServiceListener protolProviderRegistrationListener = null;

    /**
     * Creates an instance of <tt>ChatRoomQuery</tt> by specifying
     * the parent contact source, the query string to match and the maximum
     * result contacts to return.
     *
     * @param queryString the query string to match
     * @param contactSource the parent contact source
     */
    public ChatRoomQuery(String queryString, 
        ChatRoomContactSourceService contactSource)
    {
        super(contactSource,
            Pattern.compile(queryString, Pattern.CASE_INSENSITIVE
                            | Pattern.LITERAL), true);
        this.queryString = queryString;
        
        mucService = MUCActivator.getMUCService();
        
    }

    /**
     * Adds listeners for the query
     */
    private void initListeners()
    {
        for(ProtocolProviderService pps : MUCActivator.getChatRoomProviders())
        {
            addQueryToProviderPresenceListeners(pps);
        }
        
        mucService.addChatRoomListChangeListener(this);
        mucService.addChatRoomProviderWrapperListener(this);
        protolProviderRegistrationListener = new ProtocolProviderRegListener();
        MUCActivator.bundleContext.addServiceListener(
            protolProviderRegistrationListener);
    }

    /**
     * Adds the query as presence listener to protocol provider service.
     * @param pps the protocol provider service.
     */
    public void addQueryToProviderPresenceListeners(ProtocolProviderService pps)
    {
        OperationSetMultiUserChat opSetMUC 
            = pps.getOperationSet(OperationSetMultiUserChat.class);
        if(opSetMUC != null)
        {
            opSetMUC.addPresenceListener(this);
        }
    }

    /**
     * Removes the query from protocol provider service presence listeners.
     * @param pps the protocol provider service.
     */
    public void removeQueryFromProviderPresenceListeners(
        ProtocolProviderService pps)
    {
        OperationSetMultiUserChat opSetMUC 
            = pps.getOperationSet(OperationSetMultiUserChat.class);
        if(opSetMUC != null)
        {
            opSetMUC.removePresenceListener(this);
        }
    }

    @Override
    protected void run()
    {
        Iterator<ChatRoomProviderWrapper> chatRoomProviders
            = mucService.getChatRoomProviders();
        
        while (chatRoomProviders.hasNext())
        {
            ChatRoomProviderWrapper provider = chatRoomProviders.next();
            providerAdded(provider, true);
        }
        
        if (getStatus() != QUERY_CANCELED)
            setStatus(QUERY_COMPLETED);
    }

    /**
     * Handles adding a chat room provider.
     * @param provider the provider.
     * @param addQueryResult indicates whether we should add the chat room to 
     * the query results or fire an event without adding it to the results. 
     */
    private void providerAdded(ChatRoomProviderWrapper provider, 
        boolean addQueryResult)
    {
       
        for(int i = 0; i < provider.countChatRooms(); i++)
        {
            ChatRoomWrapper chatRoom = provider.getChatRoom(i);
            addChatRoom( provider.getProtocolProvider(), 
                chatRoom.getChatRoomName(), chatRoom.getChatRoomID(), 
                addQueryResult, chatRoom.isAutojoin());
        }
    }

    /**
     * Handles chat room presence status updates.
     * 
     * @param evt the <tt>LocalUserChatRoomPresenceChangeEvent</tt> instance
     * containing the chat room and the type, and reason of the change
     */
    @Override
    public void localUserPresenceChanged(
        LocalUserChatRoomPresenceChangeEvent evt)
    {
        ChatRoom sourceChatRoom = evt.getChatRoom();

        String eventType = evt.getEventType();

        boolean existingContact = false;
        ChatRoomSourceContact foundContact = null;
        synchronized (contactResults)
        {
            for (ChatRoomSourceContact contact : contactResults)
            {
                if (contactEqualsChatRoom(contact, sourceChatRoom))
                {
                    existingContact = true;
                    foundContact = contact;
                    contactResults.remove(contact);
                    break;
                }
            }
        }

        if (LocalUserChatRoomPresenceChangeEvent
            .LOCAL_USER_JOINED.equals(eventType))
        {
            if(existingContact)
            {
                foundContact.setPresenceStatus(
                    ChatRoomPresenceStatus.CHAT_ROOM_ONLINE);
                synchronized (contactResults)
                {
                    contactResults.add(foundContact);
                }
                fireContactChanged(foundContact);
            }
            else
            {
                ChatRoomWrapper chatRoom 
                    = MUCActivator.getMUCService()
                        .findChatRoomWrapperFromChatRoom(sourceChatRoom);
                if(chatRoom != null)
                    addChatRoom(sourceChatRoom, false, chatRoom.isAutojoin());
            }
        }
        else if ((LocalUserChatRoomPresenceChangeEvent
                        .LOCAL_USER_LEFT.equals(eventType)
                    || LocalUserChatRoomPresenceChangeEvent
                            .LOCAL_USER_KICKED.equals(eventType)
                    || LocalUserChatRoomPresenceChangeEvent
                            .LOCAL_USER_DROPPED.equals(eventType)) 
                    )
        {
            if(existingContact)
            {
                foundContact.setPresenceStatus(
                        ChatRoomPresenceStatus.CHAT_ROOM_OFFLINE);
                synchronized (contactResults)
                {
                    contactResults.add(foundContact);
                }
                fireContactChanged(foundContact);
            }
        }
    }

    /**
     * Adds found result to the query results.
     * 
     * @param room the chat room.
     * @param addQueryResult indicates whether we should add the chat room to
     * the query results or fire an event without adding it to the results.
     * @param isAutoJoin the auto join state of the contact.
     */
    private void addChatRoom(ChatRoom room, boolean addQueryResult, 
        boolean isAutoJoin)
    {
        if(queryString == null
            || ((room.getName().contains(
                            queryString)
                    || room.getIdentifier().contains(queryString)
                    )))
        {
            ChatRoomSourceContact contact 
                = new ChatRoomSourceContact(room, this, isAutoJoin);
            synchronized (contactResults)
            {
                contactResults.add(contact);
            }
            
            if(addQueryResult)
            {
                addQueryResult(contact, false);
            }
            else
            {
                fireContactReceived(contact, false);
            }
        }
    }

    /**
     * Adds found result to the query results.
     * 
     * @param pps the protocol provider associated with the found chat room.
     * @param chatRoomName the name of the chat room.
     * @param chatRoomID the id of the chat room.
     * @param addQueryResult indicates whether we should add the chat room to 
     * the query results or fire an event without adding it to the results.
     * @param isAutoJoin the auto join state of the contact.
     */
    private void addChatRoom(ProtocolProviderService pps, 
        String chatRoomName, String chatRoomID, boolean addQueryResult, 
        boolean isAutoJoin)
    {
        if(queryString == null
            || ((chatRoomName.contains(
                            queryString)
                    || chatRoomID.contains(queryString)
                    )))
        {
            ChatRoomSourceContact contact 
                = new ChatRoomSourceContact(chatRoomName, chatRoomID, this, pps,
                    isAutoJoin);
            synchronized (contactResults)
            {
                contactResults.add(contact);
            }
            
            if(addQueryResult)
            {
                addQueryResult(contact, false);
            }
            else
            {
                fireContactReceived(contact, false);
            }
        }
    }

    /**
     * Indicates that a change has occurred in the chat room data list.
     * @param evt the event that describes the change.
     */
    @Override
    public void contentChanged(final ChatRoomListChangeEvent evt)
    {
        ChatRoomWrapper chatRoom = evt.getSourceChatRoom();
        switch (evt.getEventID())
        {
            case ChatRoomListChangeEvent.CHAT_ROOM_ADDED:
                addChatRoom(chatRoom.getChatRoom(), false,
                    chatRoom.isAutojoin());
                break;
            case ChatRoomListChangeEvent.CHAT_ROOM_REMOVED:
                LinkedList<ChatRoomSourceContact> tmpContactResults;
                synchronized (contactResults)
                {
                    tmpContactResults
                        = new LinkedList<ChatRoomSourceContact>(contactResults);

                    for (ChatRoomSourceContact contact : tmpContactResults)
                    {
                    if (contactEqualsChatRoom(contact, chatRoom))
                        {
                            contactResults.remove(contact);
                            fireContactRemoved(contact);
                            break;
                        }
                    }
                }
                break;
            case ChatRoomListChangeEvent.CHAT_ROOM_CHANGED:
                synchronized (contactResults)
                {
                    for (ChatRoomSourceContact contact : contactResults)
                    {
                        if (contactEqualsChatRoom(contact,
                            chatRoom.getChatRoom()))
                        {
                            if (chatRoom.isAutojoin() != contact.isAutoJoin())
                            {
                                contact.setAutoJoin(chatRoom.isAutojoin());
                                fireContactChanged(contact);
                            }
                            break;
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void chatRoomProviderWrapperAdded(ChatRoomProviderWrapper provider)
    {
        providerAdded(provider, false);
    }

    @Override
    public void chatRoomProviderWrapperRemoved(ChatRoomProviderWrapper provider)
    {
        LinkedList<ChatRoomSourceContact> tmpContactResults;
        synchronized (contactResults)
        {
            tmpContactResults 
                = new LinkedList<ChatRoomSourceContact>(contactResults);
        
            for(ChatRoomSourceContact contact : tmpContactResults)
            {
                if(contact.getProvider().equals(provider.getProtocolProvider()))
                {
                    contactResults.remove(contact);
                    fireContactRemoved(contact);
                }
            }
        }
    }

    /**
     * Test equality of contact to chat room. This test recognizes that chat
     * rooms may have equal names but connected to different accounts.
     *
     * @param contact the contact
     * @param chatRoom the chat room
     * @return returns <tt>true</tt> if they are equal, or <tt>false</tt> if
     *         they are different
     */
    private boolean contactEqualsChatRoom(final ChatRoomSourceContact contact,
        final ChatRoom chatRoom)
    {
        return contact.getProvider() == chatRoom.getParentProvider()
            && chatRoom.getIdentifier().equals(contact.getContactAddress());
    }

    /**
     * Test equality of contact to chat room wrapper. This method does not rely
     * on a chat room instance, since that may not be available in case of
     * removal.
     *
     * @param contact the contact
     * @param chatRoomWrapper the chat room wrapper
     * @return returns <tt>true</tt> if they are equal, or <tt>false</tt> if
     *         they are different.
     */
    private boolean contactEqualsChatRoom(final ChatRoomSourceContact contact,
        final ChatRoomWrapper chatRoomWrapper)
    {
        return contact.getProvider() == chatRoomWrapper.getParentProvider()
            .getProtocolProvider()
            && contact.getContactAddress().equals(
                chatRoomWrapper.getChatRoomID());
    }

    /**
     * Returns the index of the contact in the contact results list.
     * @param contact the contact.
     * @return the index of the contact in the contact results list.
     */
    public synchronized int indexOf(ChatRoomSourceContact contact)
    {
       Iterator<ChatRoomSourceContact> it = contactResults.iterator();
       int i = 0;
       while(it.hasNext())
       {
           if(contact.equals(it.next()))
           {
               return i;
           }
           i++;
       }
       return -1;
    }

    /**
     * Clears any listener we used.
     */
    private void clearListeners()
    {
        mucService.removeChatRoomListChangeListener(this);
        mucService.removeChatRoomProviderWrapperListener(this);
        if(protolProviderRegistrationListener != null)
            MUCActivator.bundleContext.removeServiceListener(
                protolProviderRegistrationListener);
        protolProviderRegistrationListener = null;
        for(ProtocolProviderService pps : MUCActivator.getChatRoomProviders())
        {
            removeQueryFromProviderPresenceListeners(pps);
        }
    }

    /**
     * Cancels this <tt>ContactQuery</tt>.
     *
     * @see ContactQuery#cancel()
     */
    public void cancel()
    {
        clearListeners();

        super.cancel();
    }

    /**
     * If query has status changed to cancel, let's clear listeners.
     * @param status {@link ContactQuery#QUERY_CANCELED},
     * {@link ContactQuery#QUERY_COMPLETED}
     */
    public void setStatus(int status)
    {
        if(status == QUERY_CANCELED)
            clearListeners();

        super.setStatus(status);
    }

    @Override
    public void addContactQueryListener(ContactQueryListener l)
    {
        super.addContactQueryListener(l);
        contactQueryListenersCount++;
        if(contactQueryListenersCount == 1)
        {
            initListeners();
        }
    }

    @Override
    public void removeContactQueryListener(ContactQueryListener l)
    {
        super.removeContactQueryListener(l);
        contactQueryListenersCount--;
        if(contactQueryListenersCount == 0)
        {
            clearListeners();
        }
    }

    /**
     * Listens for <tt>ProtocolProviderService</tt> registrations.
     */
    private class ProtocolProviderRegListener
        implements ServiceListener
    {
        /**
         * Handles service change events.
         */
        public void serviceChanged(ServiceEvent event)
        {
            ServiceReference serviceRef = event.getServiceReference();

            // if the event is caused by a bundle being stopped, we don't want to
            // know
            if (serviceRef.getBundle().getState() == Bundle.STOPPING)
            {
                return;
            }

            Object service = MUCActivator.bundleContext.getService(serviceRef);

            // we don't care if the source service is not a protocol provider
            if (!(service instanceof ProtocolProviderService))
            {
                return;
            }

            switch (event.getType())
            {
            case ServiceEvent.REGISTERED:
                    addQueryToProviderPresenceListeners(
                        (ProtocolProviderService) service);
                break;
            case ServiceEvent.UNREGISTERING:
                    removeQueryFromProviderPresenceListeners(
                        (ProtocolProviderService) service);
                break;
            }
        }
    }
}