aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/msn/OperationSetMultiUserChatMsnImpl.java
blob: 857fb5c8f6cbe25896b55bdb72e13afbfdf96674 (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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/*
 * 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.msn;

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 net.sf.jml.*;
import net.sf.jml.event.*;
import net.sf.jml.message.*;

/**
 * A MSN implementation of the multi user chat operation set.
 * 
 * @author Rupert Burchardi
 */
public class OperationSetMultiUserChatMsnImpl
    extends AbstractOperationSetMultiUserChat
    implements SubscriptionListener
{
    private static final Logger logger =
        Logger.getLogger(OperationSetMultiUserChatMsnImpl.class);

    /**
     * A list of the rooms that are currently open by this account. Note that
     * this list only contains chat rooms where the user is not the initiator.
     */
    private Hashtable<String, ChatRoom> chatRoomCache = new Hashtable<String, ChatRoom>();

    /**
     * A list of the rooms that are currently open and created by this account.
     */
    private Hashtable<Object, ChatRoom> userCreatedChatRoomList = new Hashtable<Object, ChatRoom>();

    /**
     * The currently valid MSN protocol provider service implementation.
     */
    private ProtocolProviderServiceMsnImpl msnProvider = null;

    /**
     * Instantiates the user operation set with a currently valid instance of
     * the MSN protocol provider.
     * 
     * @param msnProvider a currently valid instance of
     *            ProtocolProviderServiceMsnImpl.
     */
    OperationSetMultiUserChatMsnImpl(ProtocolProviderServiceMsnImpl msnProvider)
    {
        this.msnProvider = msnProvider;

        msnProvider
            .addRegistrationStateChangeListener(new RegistrationStateListener());

        OperationSetPersistentPresence presenceOpSet
            = (OperationSetPersistentPresence) msnProvider
                .getOperationSet(OperationSetPersistentPresence.class);

        presenceOpSet.addSubscriptionListener(this);
    }

    /**
     * Returns true if <tt>contact</tt> supports multi user chat sessions.
     * 
     * @param contact reference to the contact whose support for chat rooms we
     *            are currently querying.
     * @return a boolean indicating whether <tt>contact</tt> supports chatrooms.
     */
    public boolean isMultiChatSupportedByContact(Contact contact)
    {
        // if (contact.getProtocolProvider().getOperationSet(
        // OperationSetMultiUserChat.class) != null)
        // return true;
        //     
        // return false;

        return true;
    }

    /**
     * Creates a room with the named <tt>roomName</tt> and according to the
     * specified <tt>roomProperties</tt> on the server that this protocol
     * provider is currently connected to.
     * 
     * @param roomName the name of the <tt>ChatRoom</tt> to create.
     * @param roomProperties properties specifying how the room should be
     *            created.
     * 
     * @throws OperationFailedException if the room couldn't be created for some
     *             reason (e.g. room already exists; user already joined to an
     *             existent room or user has no permissions to create a chat
     *             room).
     * @throws OperationNotSupportedException if chat room creation is not
     *             supported by this server
     * 
     * @return ChatRoom the chat room that we've just created.
     */
    public ChatRoom createChatRoom( String roomName,
                                    Map<String, Object> roomProperties)
        throws  OperationFailedException,
                OperationNotSupportedException
    {
        return findRoom(roomName);
    }

    /**
     * Returns a reference to a chatRoom named <tt>roomName</tt> or creates a
     * new chat room and puts it into the userCreatedChatRoomList. Note: Only
     * called by user.
     * 
     * @param roomName the name of the <tt>ChatRoom</tt> that we're looking for.
     * @return the <tt>ChatRoom</tt> named <tt>roomName</tt> or null if no such
     *         room exists on the server that this provider is currently
     *         connected to.
     * @throws OperationFailedException if an error occurs while trying to
     *             discover the room on the server.
     * @throws OperationNotSupportedException if the server does not support
     *             multi user chat
     */

    public ChatRoom findRoom(String roomName)
        throws OperationFailedException,
        OperationNotSupportedException
    {
        assertConnected();

        ChatRoom room = chatRoomCache.get(roomName);

        if (room == null)
        { // when the room hasn't been created, we create it.
            room = createLocalChatRoomInstance(roomName);

            // we create an identifier object and create a new switchboard
            // we need to track this object to identify this chatRoom
            Object id = new Object();
            msnProvider.getMessenger().newSwitchboard(id);
            // we put it into a hash table
            userCreatedChatRoomList.put(id, room);
        }

        return room;
    }

    /**
     * Returns a reference to a chatRoom named <tt>roomName</tt>. If the chat
     * room doesn't exist, a new chat room is created for the given
     * MsnSwitchboard.
     * 
     * @param switchboard The specific switchboard for the chat room.
     * 
     * @return the corresponding chat room
     * 
     * @throws OperationFailedException if an error occurs while trying to
     *             discover the room on the server.
     * @throws OperationNotSupportedException if the server does not support
     *             multi user chat
     */

    public ChatRoom findRoom(MsnSwitchboard switchboard)
        throws OperationFailedException,
        OperationNotSupportedException
    {
        assertConnected();

        ChatRoomMsnImpl room =
            (ChatRoomMsnImpl) chatRoomCache.get(String.valueOf(switchboard
                .hashCode()));

        if (room == null)
        {
            String name = String.valueOf(switchboard.hashCode());
            room = createChatRoom(name, switchboard);
            room.setSwitchboard(switchboard);
            room.updateMemberList(switchboard);

            chatRoomCache.put(name, room);

            // fireInvitationEvent(room,
            // switchboard.getMessenger().getOwner().getDisplayName(),
            // "You have been invited to a group chat", null);
            room.join();
        }

        return room;
    }

    /**
     * Creates a <tt>ChatRoom</tt> from the specified chatRoomName.
     * 
     * @param chatRoomName the specific chat room name.
     * 
     * @return ChatRoom the chat room that we've just created.
     */
    private ChatRoom createLocalChatRoomInstance(String chatRoomName)
    {
        synchronized (chatRoomCache)
        {
            ChatRoomMsnImpl chatRoom =
                new ChatRoomMsnImpl(chatRoomName, msnProvider);

            this.chatRoomCache.put(chatRoom.getName(), chatRoom);
            return chatRoom;
        }
    }

    /**
     * Creates a <tt>ChatRoom</tt> from the specified chatRoomName and the
     * corresponding switchboard.
     * 
     * @param chatRoomName the specific chat room name.
     * @param switchboard The corresponding switchboard.
     * 
     * @return ChatRoom the chat room that we've just created.
     */
    private ChatRoomMsnImpl createChatRoom(String chatRoomName,
        MsnSwitchboard switchboard)
    {
        synchronized (chatRoomCache)
        {
            ChatRoomMsnImpl chatRoom =
                new ChatRoomMsnImpl(chatRoomName, msnProvider, switchboard);

            this.chatRoomCache.put(chatRoom.getName(), chatRoom);
            return chatRoom;
        }

    }

    /**
     * Makes sure that we are properly connected.
     * 
     * @throws OperationFailedException if the provider is not connected.
     * @throws OperationNotSupportedException if the service is not supported by
     *             the server.
     */
    private void assertConnected()
        throws OperationFailedException,
        OperationNotSupportedException
    {
        if (msnProvider == null)
            throw new IllegalStateException(
                "The provider must be non-null and signed on the "
                    + "service before being able to communicate.");
        if (!msnProvider.isRegistered())
            throw new IllegalStateException(
                "The provider must be signed on the service before "
                    + "being able to communicate.");
    }

    /**
     * Returns a list of the chat rooms that we have joined and are currently
     * active in.
     * 
     * @return a <tt>List</tt> of the rooms where the user has joined using a
     *         given connection.
     */
    public List<ChatRoom> getCurrentlyJoinedChatRooms()
    {
        synchronized (chatRoomCache)
        {
            List<ChatRoom> joinedRooms = new LinkedList<ChatRoom>(this.chatRoomCache.values());

            Iterator<ChatRoom> joinedRoomsIter = joinedRooms.iterator();

            while (joinedRoomsIter.hasNext())
            {
                if (!joinedRoomsIter.next().isJoined())
                    joinedRoomsIter.remove();
            }

            return joinedRooms;
        }
    }

    /**
     * Returns a list of the names of all chat rooms that <tt>contact</tt> is
     * currently a member of.
     * 
     * @param contact the contact whose current ChatRooms we will be querying.
     * @return a list of <tt>String</tt> indicating the names of the chat rooms
     *         that <tt>contact</tt> has joined and is currently active in.
     * 
     * @throws OperationFailedException if an error occurs while trying to
     *             discover the room on the server.
     * @throws OperationNotSupportedException if the server does not support
     *             multi user chat
     */
    public List<String> getCurrentlyJoinedChatRooms(
            ChatRoomMember chatRoomMember)
        throws OperationFailedException,
               OperationNotSupportedException
    {
        synchronized (chatRoomCache)
        {
            List<String> joinedRooms = new LinkedList<String>();

            for (Map.Entry<String, ChatRoom> chatRoomEntry
                    : chatRoomCache.entrySet())
                if (chatRoomEntry.getValue().isJoined())
                    joinedRooms.add(chatRoomEntry.getKey());
            return joinedRooms;
        }
    }

    /**
     * Note: This is not supported inside the MSN, so we just return an empty
     * list.
     */
    public List<String> getExistingChatRooms()
        throws OperationFailedException,
        OperationNotSupportedException
    {
        // we dont have any available chat rooms on the server.
        return new LinkedList<String>();
    }

    /**
     * Note: Not supported inside the MSN.
     */

    public void rejectInvitation(ChatRoomInvitation invitation,
        String rejectReason)
    {
        // there is no way to block invitations, because there arn't any
        // invitations.
        // the only way would be to block the Friend and that shouldn't be done
        // here.
        return;
    }

    /**
     * Creates a message by a given message text.
     * 
     * @param messageText The message text.
     * @return the newly created message.
     */

    public Message createMessage(String messageText)
    {
        return new MessageMsnImpl(messageText,
            OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE,
            OperationSetBasicInstantMessaging.DEFAULT_MIME_ENCODING, null);
    }

    /**
     * Checks if an incoming message is a multi user chat message. This is done
     * by the switchboard, if it is not created by the user, its an active file
     * transfer switchboard or the user count is too low then this method return
     * false.
     * 
     * @param switchboard The corresponding MSNswitchboard.
     * @return True if it is a group chat message or false in the other case.
     */

    public boolean isGroupChatMessage(MsnSwitchboard switchboard)
    {
        // //fileTransfer??
        // if (switchboard.getActiveFileTransfers() != null)
        // return false;

        Object attachment = switchboard.getAttachment();
        if (attachment == null)
        { // the user did not created the chat room by him/her self,
            // the only way to figure out if this is a group chat message
            // is to check the user count
            return (switchboard.getAllContacts().length > 1);

        }

        return userCreatedChatRoomList.containsKey(attachment);
    }

    protected void fireInvitationEvent(ChatRoom targetChatRoom, String inviter,
        String reason, byte[] password)
    {
        ChatRoomInvitationMsnImpl invitation
            = new ChatRoomInvitationMsnImpl(
                    targetChatRoom,
                    inviter,
                    reason,
                    password);

        fireInvitationReceived(invitation);
    }

    /**
     * Our listener that will tell us when we're registered to msn.
     * 
     */
    private class RegistrationStateListener
        implements RegistrationStateChangeListener
    {
        /**
         * The method is called by a ProtocolProvider implementation whenever 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)
        {
            if (evt.getNewState() == RegistrationState.REGISTERED)
            {
                msnProvider.getMessenger().addSwitchboardListener(
                    new MsnSwitchboardListener());
                msnProvider.getMessenger().addMessageListener(
                    new MsnMessageListener());
            }
        }

    }

    /**
     * Our group chat message listener, it extends the MsnMessageAdapter from
     * the the jml library.
     * 
     */
    private class MsnMessageListener
        extends MsnMessageAdapter
        implements MsnEmailListener
    {
        public void instantMessageReceived( MsnSwitchboard switchboard,
                                            MsnInstantMessage message,
                                            MsnContact contact)
        {
            if (!isGroupChatMessage(switchboard))
                return;

            Message newMessage = createMessage(message.getContent());

            logger.debug("Group chat message received.");
            Object attachment = switchboard.getAttachment();
            try
            {
                ChatRoomMsnImpl chatRoom = null;

                if (attachment == null) // chat room session NOT created by
                                        // yourself
                    chatRoom = (ChatRoomMsnImpl) findRoom(switchboard);

                // user created chat room session?
                if (attachment != null
                    && userCreatedChatRoomList.containsKey(attachment))
                    chatRoom =
                        (ChatRoomMsnImpl) userCreatedChatRoomList
                            .get(attachment);

                if (chatRoom == null)
                    return;

                ChatRoomMemberMsnImpl member =
                    chatRoom.getChatRoomMember(contact.getId());

                ChatRoomMessageReceivedEvent msgReceivedEvent =
                    new ChatRoomMessageReceivedEvent(
                        chatRoom,
                        member,
                        System.currentTimeMillis(),
                        newMessage,
                        ChatRoomMessageReceivedEvent
                            .CONVERSATION_MESSAGE_RECEIVED);

                chatRoom.fireMessageEvent(msgReceivedEvent);

            }
            catch (OperationFailedException e)
            {
                logger.error("Failed to find room with name: ", e);
            }
            catch (OperationNotSupportedException e)
            {
                logger.error("Failed to find room with name: ", e);
            }

        }

        public void initialEmailNotificationReceived(
            MsnSwitchboard switchboard, MsnEmailInitMessage message,
            MsnContact contact)
        {
        }

        public void initialEmailDataReceived(MsnSwitchboard switchboard,
            MsnEmailInitEmailData message, MsnContact contact)
        {
        }

        public void newEmailNotificationReceived(MsnSwitchboard switchboard,
            MsnEmailNotifyMessage message, MsnContact contact)
        {

        }

        public void activityEmailNotificationReceived(
            MsnSwitchboard switchboard, MsnEmailActivityMessage message,
            MsnContact contact)
        {
        }
    }

    /**
     * The Switchboard Listener, listens to all four switchboard events:
     * Switchboard started/closed and User joins/left.
     * 
     */
    private class MsnSwitchboardListener
        extends MsnSwitchboardAdapter
    {
        public void contactJoinSwitchboard(MsnSwitchboard switchboard,
            MsnContact contact)
        {
            logger.debug(contact.getDisplayName()
                + " has joined the Switchboard");
            if (!isGroupChatMessage(switchboard))
                return;

            Object attachment = switchboard.getAttachment();
            try
            {
                ChatRoomMsnImpl chatRoom = null;
                if (attachment == null) // chat room session NOT created by
                                        // yourself
                    chatRoom = (ChatRoomMsnImpl) findRoom(switchboard);

                // user created chat room session?
                if (attachment != null
                    && userCreatedChatRoomList.containsKey(attachment))
                    chatRoom =
                        (ChatRoomMsnImpl) userCreatedChatRoomList
                            .get(attachment);

                if (chatRoom == null)
                    return;

                String memberId = contact.getId();

                ChatRoomMemberMsnImpl member =
                    chatRoom.getChatRoomMember(memberId);

                if (member == null)
                {
                    member =
                        new ChatRoomMemberMsnImpl(chatRoom, contact
                            .getDisplayName(), contact.getEmail().toString(),
                            ChatRoomMemberRole.MEMBER);

                    chatRoom.addChatRoomMember(memberId, member);
                }
            }
            catch (Exception e)
            {

            }

        }

        public void contactLeaveSwitchboard(MsnSwitchboard switchboard,
                                            MsnContact contact)
        {
            logger
                .debug(contact.getDisplayName() + " has left the Switchboard");

            Object attachment = switchboard.getAttachment();

            try
            {
                ChatRoomMsnImpl chatRoom = null;
                if (attachment == null)// chat room session NOT created by
                                       // yourself
                    chatRoom = (ChatRoomMsnImpl) findRoom(switchboard);

                // user created chat room session?
                if (attachment != null
                    && userCreatedChatRoomList.containsKey(attachment))
                    chatRoom =
                        (ChatRoomMsnImpl) userCreatedChatRoomList
                            .get(attachment);

                if (chatRoom == null)
                    return;

                String memberId = contact.getId();

                ChatRoomMemberMsnImpl member =
                    chatRoom.getChatRoomMember(memberId);

                if (member != null)
                {
                    chatRoom.removeChatRoomMember(memberId);
                }
            }
            catch (OperationFailedException e)
            {
                logger.debug(   "Could not find a chat room corresponding" +
                                "to the given switchboard.", e);
            }
            catch (OperationNotSupportedException e)
            {
                logger.debug(   "Could not find a chat room corresponding" +
                                "to the given switchboard.", e);
            }
        }

        public void switchboardClosed(MsnSwitchboard switchboard)
        {
            logger.debug("Switchboard closed.");

            Object attachment = switchboard.getAttachment();
            try
            {
                ChatRoomMsnImpl chatRoom = null;
                if (attachment == null)// chat room session NOT created by
                                       // yourself
                    chatRoom = (ChatRoomMsnImpl) findRoom(switchboard);
                // user created chat room session?
                if (attachment != null
                    && userCreatedChatRoomList.containsKey(attachment))
                    chatRoom =
                        (ChatRoomMsnImpl) userCreatedChatRoomList
                            .get(attachment);

                if (chatRoom == null)
                    return;

                chatRoom.setSwitchboard(null);

                // chatRoom.leave();
                // fireLocalUserPresenceEvent(chatRoom,
                // LocalUserChatRoomPresenceChangeEvent.LOCAL_USER_DROPPED ,
                // "Switchboard closed.");
            }
            catch (Exception e)
            {
            }
        }

        public void switchboardStarted(MsnSwitchboard switchboard)
        {
            logger.debug("Switchboard started.");
            Object switchboardID = switchboard.getAttachment();
            try
            {
                ChatRoomMsnImpl chatRoom = null;
                if (switchboardID != null
                    && userCreatedChatRoomList.containsKey(switchboardID))
                {
                    chatRoom =
                        (ChatRoomMsnImpl) userCreatedChatRoomList
                            .get(switchboardID);

                    chatRoom.setSwitchboard(switchboard);
                    chatRoom.updateMemberList(switchboard);
                    chatRoom.join();
                }

            }
            catch (OperationFailedException ofe)
            {
                logger.debug("Could not join the ChatRoom: " + ofe);
            }
        }
    }

    /**
     * Updates corresponding chat room members when a contact has been modified
     * in our contact list.
     */
     public void contactModified(ContactPropertyChangeEvent evt)
     {
         Contact modifiedContact = evt.getSourceContact();

         this.updateChatRoomMembers(modifiedContact);
     }

     /**
      * Updates corresponding chat room members when a contact has been created
      * in our contact list.
      */
     public void subscriptionCreated(SubscriptionEvent evt)
     {
         Contact createdContact = evt.getSourceContact();

         this.updateChatRoomMembers(createdContact);
     }

     /**
      * Not interested in this event for our member update purposes.
      */
     public void subscriptionFailed(SubscriptionEvent evt)
     {}

     /**
      * Not interested in this event for our member update purposes.
      */
     public void subscriptionMoved(SubscriptionMovedEvent evt)
     {}

     /**
      * Updates corresponding chat room members when a contact has been removed
      * from our contact list.
      */
     public void subscriptionRemoved(SubscriptionEvent evt)
     {
         // Set to null the contact reference in all corresponding chat room
         // members.
         this.updateChatRoomMembers(null);
     }

     /**
      * Not interested in this event for our member update purposes.
      */
     public void subscriptionResolved(SubscriptionEvent evt)
     {}

     /**
      * Finds all chat room members, which name corresponds to the name of the
      * given contact and updates their contact references.
      * 
      * @param contact the contact we're looking correspondences for.
      */
     private void updateChatRoomMembers(Contact contact)
     {
         Enumeration<ChatRoom> chatRooms = chatRoomCache.elements();

         while (chatRooms.hasMoreElements())
         {
             ChatRoomMsnImpl chatRoom = (ChatRoomMsnImpl)chatRooms.nextElement();

             ChatRoomMemberMsnImpl member
                 = chatRoom.findMemberForAddress(contact.getAddress());

             if (member != null)
             {
                 member.setContact(contact);
                 member.setAvatar(contact.getImage());
             }
         }
     }
}