Roster.java 37.6 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
Matt Tucker's avatar
Matt Tucker committed
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
Matt Tucker's avatar
Matt Tucker committed
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10
 */
Matt Tucker's avatar
Matt Tucker committed
11

Matt Tucker's avatar
Matt Tucker committed
12
package org.jivesoftware.messenger.roster;
Matt Tucker's avatar
Matt Tucker committed
13 14

import org.jivesoftware.messenger.auth.UnauthorizedException;
Matt Tucker's avatar
Matt Tucker committed
15 16
import org.jivesoftware.messenger.user.UserNotFoundException;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
17 18
import org.jivesoftware.messenger.user.User;
import org.jivesoftware.messenger.user.UserManager;
19
import org.jivesoftware.messenger.*;
20 21
import org.jivesoftware.messenger.group.GroupManager;
import org.jivesoftware.messenger.group.Group;
22 23
import org.jivesoftware.util.Cacheable;
import org.jivesoftware.util.CacheSizes;
24
import org.jivesoftware.util.Log;
25
import org.xmpp.packet.*;
Matt Tucker's avatar
Matt Tucker committed
26

27 28
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
Matt Tucker's avatar
Matt Tucker committed
29 30 31

/**
 * <p>A roster is a list of users that the user wishes to know if they are online.</p>
32 33
 * <p>Rosters are similar to buddy groups in popular IM clients. The Roster class is
 * a representation of the roster data.<p/>
Matt Tucker's avatar
Matt Tucker committed
34
 *
35 36 37
 * <p>Updates to this roster is effectively a change to the user's roster. To reflect this,
 * the changes to this class will automatically update the persistently stored roster, as well as
 * send out update announcements to all logged in user sessions.</p>
Matt Tucker's avatar
Matt Tucker committed
38
 *
39
 * @author Gaston Dombiak
Matt Tucker's avatar
Matt Tucker committed
40
 */
41 42 43 44 45 46 47 48 49 50 51 52 53
public class Roster implements Cacheable {

    /**
     * <p>Roster item cache - table: key jabberid string; value roster item.</p>
     */
    protected ConcurrentHashMap<String, RosterItem> rosterItems = new ConcurrentHashMap<String, RosterItem>();

    private RosterItemProvider rosterItemProvider;
    private String username;
    private SessionManager sessionManager;
    private XMPPServer server;
    private RoutingTable routingTable;
    private PresenceManager presenceManager;
54 55 56 57
    /**
     * Note: Used only for shared groups logic.
     */
    private RosterManager rosterManager;
58 59 60 61


    /**
     * <p>Create a roster for the given user, pulling the existing roster items
62 63 64 65 66
     * out of the backend storage provider. The roster will also include items that
     * belong to the user's shared groups.</p>
     *
     * <p>RosterItems that ONLY belong to shared groups won't be persistent unless the user
     * explicitly subscribes to the contact's presence, renames the contact in his roster or adds
67
     * the item to a personal group.</p>
68 69 70 71
     *
     * @param username The username of the user that owns this roster
     */
    public Roster(String username) {
72
        presenceManager = XMPPServer.getInstance().getPresenceManager();
73
        rosterManager = XMPPServer.getInstance().getRosterManager();
74 75
        sessionManager = SessionManager.getInstance();
        this.username = username;
76 77 78

        // Get the shared groups of this user
        Collection<Group> sharedGroups = null;
79
        Collection<Group> userGroups = null;
80 81
        try {
            User rosterUser = UserManager.getInstance().getUser(getUsername());
82 83
            sharedGroups = rosterManager.getSharedGroups(rosterUser);
            userGroups = GroupManager.getInstance().getGroups(rosterUser);
84 85 86 87 88 89
        }
        catch (UserNotFoundException e) {
            sharedGroups = new ArrayList<Group>();
        }

        // Add RosterItems that belong to the personal roster
90 91 92 93
        rosterItemProvider =  RosterItemProvider.getInstance();
        Iterator items = rosterItemProvider.getItems(username);
        while (items.hasNext()) {
            RosterItem item = (RosterItem)items.next();
94 95 96 97 98
            // Check if the item (i.e. contact) belongs to a shared group of the user. Add the
            // shared group (if any) to this item
            for (Group group : sharedGroups) {
                if (group.isUser(item.getJid().getNode())) {
                    // TODO Group name conflicts are not being considered (do we need this?)
99
                    item.addSharedGroup(group);
100 101
                }
            }
102 103
            rosterItems.put(item.getJid().toBareJID(), item);
        }
104
        // Add RosterItems that belong only to shared groups
105
        Map<JID,List<Group>> sharedUsers = getSharedUsers(sharedGroups);
106 107
        for (JID jid : sharedUsers.keySet()) {
            try {
108
                Collection<Group> itemGroups = new ArrayList<Group>();
109
                User user = UserManager.getInstance().getUser(jid.getNode());
110
                String nickname = "".equals(user.getName()) ? jid.getNode() : user.getName();
111
                RosterItem item = new RosterItem(jid, RosterItem.SUB_TO, RosterItem.ASK_NONE,
112
                        RosterItem.RECV_NONE, nickname , null);
113 114 115
                // Add the shared groups to the new roster item
                for (Group group : sharedUsers.get(jid)) {
                    if (group.isUser(jid.getNode())) {
116
                        item.addSharedGroup(group);
117 118 119
                        itemGroups.add(group);
                    }
                    else {
120
                        item.addInvisibleSharedGroup(group);
121 122 123 124 125 126 127
                    }
                }
                // Set subscription type to BOTH if the roster user belongs to a shared group
                // that is mutually visible with a shared group of the new roster item
                if (rosterManager.hasMutualVisibility(username, userGroups, jid.getNode(),
                        itemGroups)) {
                    item.setSubStatus(RosterItem.SUB_BOTH);
128 129
                }
                else {
130 131 132
                    // Set subscription type to FROM if the contact does not belong to any of
                    // the associated shared groups
                    boolean belongsToGroup = false;
133
                    for (Group group : sharedUsers.get(jid)) {
134 135
                        if (group.isUser(jid.getNode())) {
                            belongsToGroup = true;
136 137
                        }
                    }
138 139 140
                    if (!belongsToGroup) {
                        item.setSubStatus(RosterItem.SUB_FROM);
                    }
141 142 143 144 145 146 147 148 149
                }
                rosterItems.put(item.getJid().toBareJID(), item);
            }
            catch (UserNotFoundException e) {
                Log.error("Groups (" + sharedUsers.get(jid) + ") include non-existent username (" +
                        jid.getNode() +
                        ")");
            }
        }
150
    }
Matt Tucker's avatar
Matt Tucker committed
151 152 153 154 155 156 157

    /**
     * Returns true if the specified user is a member of the roster, false otherwise.
     *
     * @param user the user object to check.
     * @return true if the specified user is a member of the roster, false otherwise.
     */
158 159 160
    public boolean isRosterItem(JID user) {
        return rosterItems.containsKey(user.toBareJID());
    }
Matt Tucker's avatar
Matt Tucker committed
161 162

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
163
     * Returns a collection of users in this roster.
Matt Tucker's avatar
Matt Tucker committed
164
     *
Gaston Dombiak's avatar
Gaston Dombiak committed
165
     * @return a collection of users in this roster.
Matt Tucker's avatar
Matt Tucker committed
166
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
167 168
    public Collection<RosterItem> getRosterItems() {
        return Collections.unmodifiableCollection(rosterItems.values());
169
    }
Matt Tucker's avatar
Matt Tucker committed
170 171 172 173 174 175

    /**
     * Returns the total number of users in the roster.
     *
     * @return the number of online users in the roster.
     */
176 177 178
    public int getTotalRosterItemCount() {
        return rosterItems.size();
    }
Matt Tucker's avatar
Matt Tucker committed
179 180 181 182 183 184 185 186 187

    /**
     * Gets a user from the roster. If the roster item does not exist, an empty one is created.
     * The new roster item is not stored in the roster until it is added using
     * addRosterItem().
     *
     * @param user the XMPPAddress for the roster item to retrieve
     * @return The roster item associated with the user XMPPAddress
     */
188 189 190 191 192 193 194
    public RosterItem getRosterItem(JID user) throws UserNotFoundException {
        RosterItem item = rosterItems.get(user.toBareJID());
        if (item == null) {
            throw new UserNotFoundException(user.toBareJID());
        }
        return item;
    }
Matt Tucker's avatar
Matt Tucker committed
195 196

    /**
197 198
     * Create a new item to the roster. Roster items may not be created that contain the same user
     * address as an existing item.
Matt Tucker's avatar
Matt Tucker committed
199 200 201
     *
     * @param user the item to add to the roster.
     */
202 203
    public RosterItem createRosterItem(JID user) throws UserAlreadyExistsException,
            SharedGroupException {
204 205
        return createRosterItem(user, null, null);
    }
Matt Tucker's avatar
Matt Tucker committed
206 207

    /**
208 209
     * Create a new item to the roster. Roster items may not be created that contain the same user
     * address as an existing item.
Matt Tucker's avatar
Matt Tucker committed
210 211 212 213 214
     *
     * @param user     the item to add to the roster.
     * @param nickname The nickname for the roster entry (can be null)
     * @param groups   The list of groups to assign this roster item to (can be null)
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
215
    public RosterItem createRosterItem(JID user, String nickname, List<String> groups)
216
            throws UserAlreadyExistsException, SharedGroupException {
217 218 219 220
        RosterItem item = provideRosterItem(user, nickname, groups);
        rosterItems.put(item.getJid().toBareJID(), item);
        return item;
    }
Matt Tucker's avatar
Matt Tucker committed
221 222 223 224 225 226 227 228

    /**
     * Create a new item to the roster based as a copy of the given item.
     * Roster items may not be created that contain the same user address
     * as an existing item in the roster.
     *
     * @param item the item to copy and add to the roster.
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
229
    public void createRosterItem(org.xmpp.packet.Roster.Item item)
230
            throws UserAlreadyExistsException, SharedGroupException {
231 232 233 234 235 236 237 238 239 240 241
        RosterItem rosterItem = provideRosterItem(item);
        rosterItems.put(item.getJID().toBareJID(), rosterItem);
    }

    /**
     * <p>Generate a new RosterItem for use with createRosterItem.<p>
     *
     * @param item The item to copy settings for the new item in this roster
     * @return The newly created roster items ready to be stored by the Roster item's hash table
     */
    protected RosterItem provideRosterItem(org.xmpp.packet.Roster.Item item)
242
            throws UserAlreadyExistsException, SharedGroupException {
243 244 245 246 247 248 249 250 251 252 253 254 255
        return provideRosterItem(item.getJID(), item.getName(),
                new ArrayList<String>(item.getGroups()));
    }

    /**
     * <p>Generate a new RosterItem for use with createRosterItem.<p>
     *
     * @param user     The roster jid address to create the roster item for
     * @param nickname The nickname to assign the item (or null for none)
     * @param groups   The groups the item belongs to (or null for none)
     * @return The newly created roster items ready to be stored by the Roster item's hash table
     */
    protected RosterItem provideRosterItem(JID user, String nickname, List<String> groups)
256 257 258 259 260 261
            throws UserAlreadyExistsException, SharedGroupException {
        if (groups != null && !groups.isEmpty()) {
            // Raise an error if the groups the item belongs to include a shared group
            Collection<Group> sharedGroups = GroupManager.getInstance().getGroups();
            for (String group : groups) {
                for (Group sharedGroup : sharedGroups) {
262
                    if (group.equals(sharedGroup.getProperties().get("sharedRoster.displayName"))) {
263 264 265 266 267
                        throw new SharedGroupException("Cannot add an item to a shared group");
                    }
                }
            }
        }
268 269 270 271 272 273 274 275 276 277 278 279
        org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
        roster.setType(IQ.Type.set);
        org.xmpp.packet.Roster.Item item = roster.addItem(user, nickname, null,
                org.xmpp.packet.Roster.Subscription.none, groups);

        RosterItem rosterItem = rosterItemProvider.createItem(username, new RosterItem(item));

        // Broadcast the roster push to the user
        broadcast(roster);

        return rosterItem;
    }
Matt Tucker's avatar
Matt Tucker committed
280 281 282 283 284 285 286

    /**
     * Update an item that is already in the roster.
     *
     * @param item the item to update in the roster.
     * @throws UserNotFoundException If the roster item for the given user doesn't already exist
     */
287 288 289 290 291
    public void updateRosterItem(RosterItem item) throws UserNotFoundException {
        if (rosterItems.putIfAbsent(item.getJid().toBareJID(), item) == null) {
            rosterItems.remove(item.getJid().toBareJID());
            throw new UserNotFoundException(item.getJid().toBareJID());
        }
292 293 294 295 296 297 298 299 300 301 302 303 304
        // If the item only had shared groups before this update then make it persistent
        if (item.isShared() && item.getID() == 0) {
            try {
                rosterItemProvider.createItem(username, item);
            }
            catch (UserAlreadyExistsException e) {
                // Do nothing. We shouldn't be here.
            }
        }
        else {
            // Update the backend data store
            rosterItemProvider.updateItem(username, item);
        }
305 306 307
        // broadcast roster update
        if (!(item.getSubStatus() == RosterItem.SUB_NONE
                && item.getAskStatus() == RosterItem.ASK_NONE)) {
308
            broadcast(item);
309
        }
310
        if (item.getSubStatus() == RosterItem.SUB_BOTH || item.getSubStatus() == RosterItem.SUB_TO) {
311
            probePresence(item.getJid());
312 313
        }
    }
Matt Tucker's avatar
Matt Tucker committed
314 315 316 317 318

    /**
     * Remove a user from the roster.
     *
     * @param user the user to remove from the roster.
319
     * @param doChecking flag that indicates if checkings should be done before deleting the user.
Matt Tucker's avatar
Matt Tucker committed
320
     * @return The roster item being removed or null if none existed
321
     * @throws SharedGroupException if the user to remove belongs to a shared group
Matt Tucker's avatar
Matt Tucker committed
322
     */
323
    public RosterItem deleteRosterItem(JID user, boolean doChecking) throws SharedGroupException {
324 325
        // Answer an error if user (i.e. contact) to delete belongs to a shared group
        RosterItem itemToRemove = rosterItems.get(user.toBareJID());
326
        if (doChecking && itemToRemove.isShared()) {
327 328 329
            throw new SharedGroupException("Cannot remove contact that belongs to a shared group");
        }

330 331 332
        // If removing the user was successful, remove the user from the subscriber list:
        RosterItem item = rosterItems.remove(user.toBareJID());
        if (item != null) {
333 334 335 336 337 338
            // Delete the item from the provider if the item is persistent. RosteItems that only
            // belong to shared groups won't be persistent
            if (item.getID() > 0) {
                // If removing the user was successful, remove the user from the backend store
                rosterItemProvider.deleteItem(username, item.getID());
            }
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

            // Broadcast the update to the user
            org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
            roster.setType(IQ.Type.set);
            roster.addItem(user, org.xmpp.packet.Roster.Subscription.remove);
            broadcast(roster);
        }
        return item;

    }

    /**
     * <p>Return the username of the user or chatbot that owns this roster.</p>
     *
     * @return the username of the user or chatbot that owns this roster
     */
    public String getUsername() {
        return username;
    }

    /**
     * <p>Obtain a 'roster reset', a snapshot of the full cached roster as an Roster.</p>
     *
     * @return The roster reset (snapshot) as an Roster
     */
    public org.xmpp.packet.Roster getReset() {
        org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
366 367

        // Add the roster items (includes the personal roster and shared groups) to the answer
Gaston Dombiak's avatar
Gaston Dombiak committed
368
        for (RosterItem item : rosterItems.values()) {
369 370 371 372
            // Do not include items with status FROM that exist only because of shared groups
            if (item.isOnlyShared() && item.getSubStatus() == RosterItem.SUB_FROM) {
                continue;
            }
373 374 375 376 377
            org.xmpp.packet.Roster.Ask ask = getAskStatus(item.getAskStatus());
            org.xmpp.packet.Roster.Subscription sub = org.xmpp.packet.Roster.Subscription.valueOf(item.getSubStatus()
                    .getName());
            // Set the groups to broadcast (include personal and shared groups)
            List<String> groups = new ArrayList<String>(item.getGroups());
378 379 380
            for (Group sharedGroup : item.getSharedGroups()) {
                groups.add(sharedGroup.getProperties().get("sharedRoster.displayName"));
            }
381 382 383
            if (item.getSubStatus() != RosterItem.SUB_NONE ||
                    item.getAskStatus() != RosterItem.ASK_NONE) {
                roster.addItem(item.getJid(), item.getNickname(), ask, sub, groups);
384 385 386 387 388 389
            }
        }
        return roster;
    }

    private org.xmpp.packet.Roster.Ask getAskStatus(RosterItem.AskType askType) {
390
        if (askType == null || "".equals(askType.getName())) {
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
            return null;
        }
        return org.xmpp.packet.Roster.Ask.valueOf(askType.getName());
    }

    /**
     * <p>Broadcast the presence update to all subscribers of the roter.</p>
     * <p/>
     * <p>Any presence change typically results in a broadcast to the roster members.</p>
     *
     * @param packet The presence packet to broadcast
     */
    public void broadcastPresence(Presence packet) {
        if (routingTable == null) {
            routingTable = XMPPServer.getInstance().getRoutingTable();
        }
        if (routingTable == null) {
            return;
        }
Gaston Dombiak's avatar
Gaston Dombiak committed
410
        for (RosterItem item : rosterItems.values()) {
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
            if (item.getSubStatus() == RosterItem.SUB_BOTH
                    || item.getSubStatus() == RosterItem.SUB_FROM) {
                JID searchNode = new JID(item.getJid().getNode(), item.getJid().getDomain(), null);
                Iterator sessions = routingTable.getRoutes(searchNode);
                packet.setTo(item.getJid());
                while (sessions.hasNext()) {
                    ChannelHandler session = (ChannelHandler)sessions.next();
                    try {
                        session.process(packet);
                    }
                    catch (Exception e) {
                        // Ignore any problems with sending - theoretically
                        // only happens if session has been closed
                    }
                }
            }
        }
    }

430 431 432 433 434 435 436
    /**
     * Returns the list of users that belong ONLY to a shared group of this user. If the contact
     * belongs to the personal roster and a shared group then it wont' be included in the answer.
     *
     * @param sharedGroups the shared groups of this user.
     * @return the list of users that belong ONLY to a shared group of this user.
     */
437
    private Map<JID,List<Group>> getSharedUsers(Collection<Group> sharedGroups) {
438 439
        // Get the users to process from the shared groups. Users that belong to different groups
        // will have one entry in the map associated with all the groups
440
        Map<JID,List<Group>> sharedGroupUsers = new HashMap<JID,List<Group>>();
441
        for (Group group : sharedGroups) {
442
            // Get all the users that should be in this roster
443
            Collection<String> users = rosterManager.getSharedUsersForRoster(group, this);
444
            // Add the users of the group to the general list of users to process
445
            for (String user : users) {
446 447
                // Add the user to the answer if the user doesn't belong to the personal roster
                // (since we have already added the user to the answer)
448 449 450
                JID jid = XMPPServer.getInstance().createJID(user, null);
                if (!isRosterItem(jid) && !getUsername().equals(user)) {
                    List<Group> groups = sharedGroupUsers.get(jid);
451
                    if (groups == null) {
452
                        groups = new ArrayList<Group>();
453 454
                        sharedGroupUsers.put(jid, groups);
                    }
455
                    groups.add(group);
456 457 458 459 460 461
                }
            }
        }
        return sharedGroupUsers;
    }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    private void broadcast(org.xmpp.packet.Roster roster) {
        if (server == null) {
            server = XMPPServer.getInstance();
        }
        JID recipient = server.createJID(username, null);
        roster.setTo(recipient);
        if (sessionManager == null) {
            sessionManager = SessionManager.getInstance();
        }
        try {
            sessionManager.userBroadcast(username, roster);
        }
        catch (UnauthorizedException e) {
            // Do nothing. We should never end here.
        }
    }

479
    void broadcast(RosterItem item) {
480 481 482 483
        // Do not broadcast items with status FROM that exist only because of shared groups
        if (item.isOnlyShared() && item.getSubStatus() == RosterItem.SUB_FROM) {
            return;
        }
484 485
        // Set the groups to broadcast (include personal and shared groups)
        List<String> groups = new ArrayList<String>(item.getGroups());
486 487 488
        for (Group sharedGroup : item.getSharedGroups()) {
            groups.add(sharedGroup.getProperties().get("sharedRoster.displayName"));
        }
489 490 491 492 493 494 495 496 497 498

        org.xmpp.packet.Roster roster = new org.xmpp.packet.Roster();
        roster.setType(IQ.Type.set);
        roster.addItem(item.getJid(), item.getNickname(),
                getAskStatus(item.getAskStatus()),
                org.xmpp.packet.Roster.Subscription.valueOf(item.getSubStatus().getName()),
                groups);
        broadcast(roster);
    }

499 500 501 502 503 504 505 506 507
    /**
     * Sends a presence probe to the probee for each connected resource of this user.
     */
    private void probePresence(JID probee) {
        for (ClientSession session : sessionManager.getSessions(username)) {
            presenceManager.probePresence(session.getAddress(), probee);
        }
    }

508 509 510 511 512 513 514 515 516
    public int getCachedSize() {
        // Approximate the size of the object in bytes by calculating the size
        // of each field.
        int size = 0;
        size += CacheSizes.sizeOfObject();                           // overhead of object
        size += CacheSizes.sizeOfCollection(rosterItems.values());   // roster item cache
        size += CacheSizes.sizeOfString(username);                   // username
        return size;
    }
517 518 519 520 521 522 523 524 525

    /**
     * Update the roster since a group user has been added to a shared group. Create a new
     * RosterItem if the there doesn't exist an item for the added user. The new RosterItem won't be
     * saved to the backend store unless the user explicitly subscribes to the contact's presence,
     * renames the contact in his roster or adds the item to a personal group. Otherwise the shared
     * group will be added to the shared groups lists. In any case an update broadcast will be sent
     * to all the users logged resources.
     *
526
     * @param group the shared group where the user was added.
527 528
     * @param addedUser the contact to update in the roster.
     */
529
    void addSharedUser(Group group, String addedUser) {
530
        boolean newItem = false;
531 532
        RosterItem item = null;
        JID jid = XMPPServer.getInstance().createJID(addedUser, "");
533 534
        try {
            // Get the RosterItem for the *local* user to add
535
            item = getRosterItem(jid);
536
            // Do nothing if the item already includes the shared group
537
            if (item.getSharedGroups().contains(group)) {
538 539
                return;
            }
540
            newItem = false;
541 542 543 544 545
        }
        catch (UserNotFoundException e) {
            try {
                // Create a new RosterItem for this new user
                User user = UserManager.getInstance().getUser(addedUser);
546
                String nickname = "".equals(user.getName()) ? jid.getNode() : user.getName();
547 548
                item =
                        new RosterItem(jid, RosterItem.SUB_BOTH, RosterItem.ASK_NONE,
549
                                RosterItem.RECV_NONE, nickname, null);
550 551
                // Add the new item to the list of items
                rosterItems.put(item.getJid().toBareJID(), item);
552
                newItem = true;
553 554
            }
            catch (UserNotFoundException ex) {
555
                Log.error("Group (" + group.getName() + ") includes non-existent username (" +
556 557 558 559
                        addedUser +
                        ")");
            }
        }
560 561 562 563 564 565 566 567
        // Update the subscription of the item **based on the item groups**
        if (newItem || item.isOnlyShared()) {
            Collection<Group> userGroups = null;
            Collection<Group> sharedGroups = new ArrayList<Group>();
            try {
                User rosterUser = UserManager.getInstance().getUser(getUsername());
                GroupManager groupManager = GroupManager.getInstance();
                userGroups = groupManager.getGroups(rosterUser);
568
                sharedGroups.addAll(item.getSharedGroups());
569
                // Add the new group to the list of groups to check
570
                sharedGroups.add(group);
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
                // Set subscription type to BOTH if the roster user belongs to a shared group
                // that is mutually visible with a shared group of the new roster item
                if (rosterManager.hasMutualVisibility(getUsername(), userGroups, jid.getNode(),
                        sharedGroups)) {
                    item.setSubStatus(RosterItem.SUB_BOTH);
                }
                // Update the subscription status depending on the group membership of the new
                // user and this user
                else if (group.isUser(addedUser) && !group.isUser(getUsername())) {
                    item.setSubStatus(RosterItem.SUB_TO);
                }
                else if (!group.isUser(addedUser) && group.isUser(getUsername())) {
                    item.setSubStatus(RosterItem.SUB_FROM);
                }
            }
            catch (UserNotFoundException e) {
            }
588
        }
589 590 591

        // Add the shared group to the list of shared groups
        if (item.getSubStatus() != RosterItem.SUB_FROM) {
592
            item.addSharedGroup(group);
593 594
        }
        else {
595
            item.addInvisibleSharedGroup(group);
596 597 598 599 600
        }
        // Brodcast to all the user resources of the updated roster item
        broadcast(item);
        // Probe the presence of the new group user
        if (item.getSubStatus() == RosterItem.SUB_BOTH || item.getSubStatus() == RosterItem.SUB_TO) {
601
            probePresence(item.getJid());
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
        }
    }

    /**
     * Adds a new contact that belongs to a certain list of groups to the roster. Depending on
     * the contact's groups and this user's groups, the presence subscription of the roster item may
     * vary.
     *
     * @param addedUser the new contact to add to the roster
     * @param groups the groups where the contact is a member
     */
    void addSharedUser(String addedUser, Collection<Group> groups, Group addedGroup) {
        boolean newItem = false;
        RosterItem item = null;
        JID jid = XMPPServer.getInstance().createJID(addedUser, "");
        try {
            // Get the RosterItem for the *local* user to add
            item = getRosterItem(jid);
            newItem = false;
        }
        catch (UserNotFoundException e) {
            try {
                // Create a new RosterItem for this new user
                User user = UserManager.getInstance().getUser(addedUser);
                String nickname = "".equals(user.getName()) ? jid.getNode() : user.getName();
                item =
                        new RosterItem(jid, RosterItem.SUB_BOTH, RosterItem.ASK_NONE,
                                RosterItem.RECV_NONE, nickname, null);
                // Add the new item to the list of items
                rosterItems.put(item.getJid().toBareJID(), item);
                newItem = true;
            }
            catch (UserNotFoundException ex) {
                Log.error("Couldn't find a user with username (" + addedUser + ")");
            }
        }
        // Update the subscription of the item **based on the item groups**
        if (newItem || item.isOnlyShared()) {
            Collection<Group> userGroups = null;
            try {
                User rosterUser = UserManager.getInstance().getUser(getUsername());
                GroupManager groupManager = GroupManager.getInstance();
                userGroups = groupManager.getGroups(rosterUser);
                // Set subscription type to BOTH if the roster user belongs to a shared group
                // that is mutually visible with a shared group of the new roster item
                if (rosterManager.hasMutualVisibility(getUsername(), userGroups, jid.getNode(),
                        groups)) {
                    item.setSubStatus(RosterItem.SUB_BOTH);
                    for (Group group : groups) {
                        if (rosterManager.isGroupVisible(group, getUsername())) {
                            // Add the shared group to the list of shared groups
653 654 655 656 657 658 659 660 661 662 663 664
                            item.addSharedGroup(group);
                        }
                    }
                    // Add to the item the groups of this user that generated a FROM subscription
                    // Note: This FROM subscription is overridden by the BOTH subscription but in
                    // fact there is a TO-FROM relation between these two users that ends up in a
                    // BOTH subscription
                    for (Group group : userGroups) {
                        if (!group.isUser(addedUser) &&
                                rosterManager.isGroupVisible(group, addedUser)) {
                            // Add the shared group to the list of invisible shared groups
                            item.addInvisibleSharedGroup(group);
665 666 667 668 669 670 671 672 673 674 675
                        }
                    }
                }
                else {
                    // Assume by default that the contact has subscribed from the presence of
                    // this user
                    item.setSubStatus(RosterItem.SUB_FROM);
                    // Check if the user may see the new contact in a shared group
                    for (Group group : groups) {
                        if (rosterManager.isGroupVisible(group, getUsername())) {
                            // Add the shared group to the list of shared groups
676
                            item.addSharedGroup(group);
677 678 679 680
                            item.setSubStatus(RosterItem.SUB_TO);
                        }
                    }
                    if (item.getSubStatus() == RosterItem.SUB_FROM) {
681
                        item.addInvisibleSharedGroup(addedGroup);
682 683 684 685 686
                    }
                }
            }
            catch (UserNotFoundException e) {
            }
687
        }
688 689
        // Brodcast to all the user resources of the updated roster item
        broadcast(item);
690 691
        // Probe the presence of the new group user
        if (item.getSubStatus() == RosterItem.SUB_BOTH || item.getSubStatus() == RosterItem.SUB_TO) {
692
            probePresence(item.getJid());
693
        }
694 695 696 697 698 699 700 701 702 703 704 705
    }

    /**
     * Update the roster since a group user has been deleted from a shared group. If the RosterItem
     * (of the deleted contact) exists only because of of the sahred group then the RosterItem will
     * be deleted physically from the backend store. Otherwise the shared group will be removed from
     * the shared groups lists. In any case an update broadcast will be sent to all the users
     * logged resources.
     *
     * @param sharedGroup the shared group from where the user was deleted.
     * @param deletedUser the contact to update in the roster.
     */
706
    void deleteSharedUser(Group sharedGroup, String deletedUser) {
707
        JID jid = XMPPServer.getInstance().createJID(deletedUser, "");
708 709 710
        try {
            // Get the RosterItem for the *local* user to remove
            RosterItem item = getRosterItem(jid);
711 712
            int groupSize = item.getSharedGroups().size() + item.getInvisibleSharedGroups().size();
            if (item.isOnlyShared() && groupSize == 1) {
713 714 715 716
                // Do nothing if the existing shared group is not the sharedGroup to remove
                if (!item.getSharedGroups().contains(sharedGroup)) {
                    return;
                }
717 718 719 720 721 722 723
                // Delete the roster item from the roster since it exists only because of this
                // group which is being removed
                deleteRosterItem(jid, false);
            }
            else {
                // Remove the removed shared group from the list of shared groups
                item.removeSharedGroup(sharedGroup);
724 725 726 727 728 729 730 731
                // Update the subscription of the item based on the remaining groups
                if (item.isOnlyShared()) {
                    Collection<Group> userGroups = null;
                    Collection<Group> sharedGroups = new ArrayList<Group>();
                    try {
                        User rosterUser = UserManager.getInstance().getUser(getUsername());
                        GroupManager groupManager = GroupManager.getInstance();
                        userGroups = groupManager.getGroups(rosterUser);
732
                        sharedGroups.addAll(item.getSharedGroups());
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
                        // Set subscription type to BOTH if the roster user belongs to a shared group
                        // that is mutually visible with a shared group of the new roster item
                        if (rosterManager.hasMutualVisibility(getUsername(), userGroups,
                                jid.getNode(), sharedGroups)) {
                            item.setSubStatus(RosterItem.SUB_BOTH);
                        }
                        else if (item.getSharedGroups().isEmpty() &&
                                !item.getInvisibleSharedGroups().isEmpty()) {
                            item.setSubStatus(RosterItem.SUB_FROM);
                        }
                        else {
                            item.setSubStatus(RosterItem.SUB_TO);
                        }

                    }
                    catch (UserNotFoundException e) {
                    }
                }
                // Brodcast to all the user resources of the updated roster item
                broadcast(item);
            }
        }
        catch (SharedGroupException e) {
            // Do nothing. Checkings are disabled so this exception should never happen.
        }
        catch (UserNotFoundException e) {
            // Do nothing since the contact does not exist in the user's roster. (strange case!)
        }
    }

    void deleteSharedUser(String deletedUser, Collection<Group> groups, Group deletedGroup) {
        JID jid = XMPPServer.getInstance().createJID(deletedUser, "");
        try {
            // Get the RosterItem for the *local* user to remove
            RosterItem item = getRosterItem(jid);
            int groupSize = item.getSharedGroups().size() + item.getInvisibleSharedGroups().size();
            if (item.isOnlyShared() && groupSize == 1) {
                // Delete the roster item from the roster since it exists only because of this
                // group which is being removed
                deleteRosterItem(jid, false);
            }
            else {
775
                item.removeSharedGroup(deletedGroup);
776 777 778 779
                // Remove all invalid shared groups from the roster item
                for (Group group : groups) {
                    if (!rosterManager.isGroupVisible(group, getUsername())) {
                        // Remove the shared group from the list of shared groups
780
                        item.removeSharedGroup(group);
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
                    }
                }

                // Update the subscription of the item **based on the item groups**
                if (item.isOnlyShared()) {
                    Collection<Group> userGroups = null;
                    try {
                        User rosterUser = UserManager.getInstance().getUser(getUsername());
                        GroupManager groupManager = GroupManager.getInstance();
                        userGroups = groupManager.getGroups(rosterUser);
                        // Set subscription type to BOTH if the roster user belongs to a shared group
                        // that is mutually visible with a shared group of the new roster item
                        if (rosterManager.hasMutualVisibility(getUsername(), userGroups,
                                jid.getNode(), groups)) {
                            item.setSubStatus(RosterItem.SUB_BOTH);
                        }
                        else {
                            // Assume by default that the contact has subscribed from the presence of
                            // this user
                            item.setSubStatus(RosterItem.SUB_FROM);
                            // Check if the user may see the new contact in a shared group
                            for (Group group : groups) {
                                if (rosterManager.isGroupVisible(group, getUsername())) {
                                    item.setSubStatus(RosterItem.SUB_TO);
                                }
                            }
                        }
                    }
                    catch (UserNotFoundException e) {
                    }
                }
812 813 814 815 816 817 818 819 820 821 822
                // Brodcast to all the user resources of the updated roster item
                broadcast(item);
            }
        }
        catch (SharedGroupException e) {
            // Do nothing. Checkings are disabled so this exception should never happen.
        }
        catch (UserNotFoundException e) {
            // Do nothing since the contact does not exist in the user's roster. (strange case!)
        }
    }
823 824 825 826 827 828 829

    /**
     * A shared group of the user has been renamed. Update the existing roster items with the new
     * name of the shared group and make a roster push for all the available resources.
     *
     * @param users group users of the renamed group.
     */
830
    void shareGroupRenamed(Collection<String> users) {
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        for (String user : users) {
            if (username.equals(user)) {
                continue;
            }
            RosterItem item = null;
            JID jid = XMPPServer.getInstance().createJID(user, "");
            try {
                // Get the RosterItem for the *local* user to add
                item = getRosterItem(jid);
                // Brodcast to all the user resources of the updated roster item
                broadcast(item);
            }
            catch (UserNotFoundException e) {
                // Do nothing since the contact does not exist in the user's roster. (strange case!)
            }
        }
    }
Matt Tucker's avatar
Matt Tucker committed
848
}