Search in sources :

Example 46 with Presence

use of org.xmpp.packet.Presence in project Openfire by igniterealtime.

the class LocalOutgoingServerSession method returnErrorToSender.

private void returnErrorToSender(Packet packet) {
    RoutingTable routingTable = XMPPServer.getInstance().getRoutingTable();
    if (packet.getError() != null) {
        Log.debug("Possible double bounce: " + packet.toXML());
    }
    try {
        if (packet instanceof IQ) {
            if (((IQ) packet).isResponse()) {
                Log.debug("XMPP specs forbid us to respond with an IQ error to: " + packet.toXML());
                return;
            }
            IQ reply = new IQ();
            reply.setID(packet.getID());
            reply.setTo(packet.getFrom());
            reply.setFrom(packet.getTo());
            reply.setChildElement(((IQ) packet).getChildElement().createCopy());
            reply.setType(IQ.Type.error);
            reply.setError(PacketError.Condition.remote_server_not_found);
            routingTable.routePacket(reply.getTo(), reply, true);
        } else if (packet instanceof Presence) {
            if (((Presence) packet).getType() == Presence.Type.error) {
                Log.debug("Double-bounce of presence: " + packet.toXML());
                return;
            }
            Presence reply = new Presence();
            reply.setID(packet.getID());
            reply.setTo(packet.getFrom());
            reply.setFrom(packet.getTo());
            reply.setType(Presence.Type.error);
            reply.setError(PacketError.Condition.remote_server_not_found);
            routingTable.routePacket(reply.getTo(), reply, true);
        } else if (packet instanceof Message) {
            if (((Message) packet).getType() == Message.Type.error) {
                Log.debug("Double-bounce of message: " + packet.toXML());
                return;
            }
            Message reply = new Message();
            reply.setID(packet.getID());
            reply.setTo(packet.getFrom());
            reply.setFrom(packet.getTo());
            reply.setType(Message.Type.error);
            reply.setThread(((Message) packet).getThread());
            reply.setError(PacketError.Condition.remote_server_not_found);
            routingTable.routePacket(reply.getTo(), reply, true);
        }
    } catch (Exception e) {
        Log.error("Error returning error to sender. Original packet: " + packet, e);
    }
}
Also used : RoutingTable(org.jivesoftware.openfire.RoutingTable) Message(org.xmpp.packet.Message) IQ(org.xmpp.packet.IQ) Presence(org.xmpp.packet.Presence) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) DocumentException(org.dom4j.DocumentException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException)

Example 47 with Presence

use of org.xmpp.packet.Presence in project Openfire by igniterealtime.

the class Roster method deleteRosterItem.

/**
     * Remove a user from the roster.
     *
     * @param user       the user to remove from the roster.
     * @param doChecking flag that indicates if checkings should be done before deleting the user.
     * @return The roster item being removed or null if none existed
     * @throws SharedGroupException if the user to remove belongs to a shared group
     */
public RosterItem deleteRosterItem(JID user, boolean doChecking) throws SharedGroupException {
    // Answer an error if user (i.e. contact) to delete belongs to a shared group
    RosterItem itemToRemove = rosterItems.get(user.toBareJID());
    if (doChecking && itemToRemove != null && !itemToRemove.getSharedGroups().isEmpty()) {
        throw new SharedGroupException("Cannot remove contact that belongs to a shared group");
    }
    if (itemToRemove != null) {
        RosterItem.SubType subType = itemToRemove.getSubStatus();
        // Cancel any existing presence subscription between the user and the contact
        if (subType == RosterItem.SUB_TO || subType == RosterItem.SUB_BOTH) {
            Presence presence = new Presence();
            presence.setFrom(server.createJID(username, null));
            presence.setTo(itemToRemove.getJid());
            presence.setType(Presence.Type.unsubscribe);
            server.getPacketRouter().route(presence);
        }
        // cancel any existing presence subscription between the contact and the user
        if (subType == RosterItem.SUB_FROM || subType == RosterItem.SUB_BOTH) {
            Presence presence = new Presence();
            presence.setFrom(server.createJID(username, null));
            presence.setTo(itemToRemove.getJid());
            presence.setType(Presence.Type.unsubscribed);
            server.getPacketRouter().route(presence);
        }
        // If removing the user was successful, remove the user from the subscriber list:
        RosterItem item = rosterItems.remove(user.toBareJID());
        if (item != null) {
            // 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());
            }
            // 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);
            // Fire event indicating that a roster item has been deleted
            RosterEventDispatcher.contactDeleted(this, item);
        }
        return item;
    } else {
        // Verify if the item being removed is an implicit roster item
        // that only exists due to some shared group
        RosterItem item = getImplicitRosterItem(user);
        if (item != null) {
            implicitFrom.remove(user.toBareJID());
            // If the contact being removed is not a local user then ACK unsubscription
            if (!server.isLocal(user)) {
                Presence presence = new Presence();
                presence.setFrom(server.createJID(username, null));
                presence.setTo(user);
                presence.setType(Presence.Type.unsubscribed);
                server.getPacketRouter().route(presence);
            }
            // Fire event indicating that a roster item has been deleted
            RosterEventDispatcher.contactDeleted(this, item);
        }
    }
    return null;
}
Also used : Presence(org.xmpp.packet.Presence) SharedGroupException(org.jivesoftware.openfire.SharedGroupException)

Example 48 with Presence

use of org.xmpp.packet.Presence in project Openfire by igniterealtime.

the class PresenceManagerImpl method getPresence.

@Override
public Presence getPresence(User user) {
    if (user == null) {
        return null;
    }
    Presence presence = null;
    for (ClientSession session : sessionManager.getSessions(user.getUsername())) {
        if (presence == null) {
            presence = session.getPresence();
        } else {
            // Get the ordinals of the presences to compare. If no ordinal is available then
            // assume a value of -1
            int o1 = presence.getShow() != null ? presence.getShow().ordinal() : -1;
            int o2 = session.getPresence().getShow() != null ? session.getPresence().getShow().ordinal() : -1;
            // Compare the presences' show ordinals
            if (o1 > o2) {
                presence = session.getPresence();
            }
        }
    }
    return presence;
}
Also used : ClientSession(org.jivesoftware.openfire.session.ClientSession) Presence(org.xmpp.packet.Presence)

Example 49 with Presence

use of org.xmpp.packet.Presence in project Openfire by igniterealtime.

the class ClientSessionInfo method readExternal.

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    Element packetElement = (Element) ExternalizableUtil.getInstance().readSerializable(in);
    presence = new Presence(packetElement, true);
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        defaultList = ExternalizableUtil.getInstance().readSafeUTF(in);
    }
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        activeList = ExternalizableUtil.getInstance().readSafeUTF(in);
    }
    offlineFloodStopped = ExternalizableUtil.getInstance().readBoolean(in);
}
Also used : DefaultElement(org.dom4j.tree.DefaultElement) Element(org.dom4j.Element) Presence(org.xmpp.packet.Presence)

Example 50 with Presence

use of org.xmpp.packet.Presence in project Openfire by igniterealtime.

the class Workgroup method roomActivity.

// ###############################################################################
// MUC related packets
// ###############################################################################
/**
     * Notification message indicating that there has been new activity in a room. This implies
     * that we need to update the conversation transcript of the group chat room and possibly
     * update the number of occupants within the room.<p>
     * <p/>
     * If only the workgroup is present in the room then leave the room (i.e. destroying room) and
     * proceed to save the room conversation transcript to the database.<p>
     *
     * @param packet the packet that was sent to the group chat room.
     */
private void roomActivity(Packet packet) {
    // Skip packet sent from this workgroup in the room
    if (packet.getFrom().toBareJID().equals(getGroupChatRoomName())) {
        return;
    }
    RoomInterceptorManager interceptorManager = RoomInterceptorManager.getInstance();
    String roomID = packet.getFrom().getNode();
    // Get the sessionID
    String sessionID = packet.getFrom().getNode();
    synchronized (sessionID.intern()) {
        if (packet instanceof Presence) {
            Presence presence = (Presence) packet;
            if (Presence.Type.error == presence.getType()) {
                // A configuration must be wrong (eg. workgroup is not allowed to create rooms).
                // Log the error presence
                String warnMessage = "Possible server misconfiguration. Received error " + "presence:" + presence.toXML();
                Log.warn(warnMessage);
                return;
            }
            // Get the JID of the presence's user
            Element mucUser = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
            // Skip this presence if no extended info was included in the presence
            if (mucUser == null) {
                return;
            }
            Element item = mucUser.element("item");
            // Skip this presence if no item was included in the presence
            if (item == null) {
                return;
            }
            // Skip this presence if it's the presence of this workgroup in the room
            if (workgroupName.equals(packet.getFrom().getResource())) {
                return;
            }
            JID presenceFullJID = new JID(item.attributeValue("jid"));
            String presenceJID = presenceFullJID.toBareJID();
            // Invoke the room interceptor before processing the presence
            interceptorManager.invokeInterceptors(getJID().toBareJID(), packet, false, false);
            // Get the userID associated to this sessionID
            UserRequest initialRequest = requests.get(sessionID);
            // Add the new presence to the list of sent packets
            Map<Packet, java.util.Date> messageList = transcripts.get(roomID);
            if (messageList == null) {
                messageList = new LinkedHashMap<Packet, java.util.Date>();
                transcripts.put(roomID, messageList);
                // Trigger the event that a chat support has started
                WorkgroupEventDispatcher.chatSupportStarted(this, sessionID);
            }
            messageList.put(packet.createCopy(), new java.util.Date());
            // Update the number of occupants in the room.
            boolean occupantAdded = false;
            Set<String> set = occupantsCounter.get(roomID);
            if (set == null) {
                set = new HashSet<String>();
                occupantsCounter.put(roomID, set);
            }
            if (presence.isAvailable()) {
                occupantAdded = set.add(presenceJID);
            } else {
                String xpath = "/presence/*[name()='x']/*[name()='status']";
                Element status = (Element) presence.getElement().selectSingleNode(xpath);
                if (status == null || !"303".equals(status.attributeValue("code"))) {
                    // Remove the occupant unless the occupant is changing his nickname
                    set.remove(presenceJID);
                }
            }
            // If the presence belongs to an Agent then create/update a track
            // Look for an agent whose JID matches the presence's JID
            String agentJID = null;
            for (Agent agent : getAgents()) {
                if (agent.getAgentJID().toBareJID().equals(presenceJID)) {
                    agentJID = agent.getAgentJID().toBareJID();
                }
            }
            if (agentJID != null) {
                AgentSession agentSession;
                // Update the current chats that the agent is having
                try {
                    agentSession = agentManager.getAgentSession(presenceFullJID);
                    if (agentSession != null) {
                        if (presence.isAvailable()) {
                            if (occupantAdded) {
                                agentSession.addChatInfo(this, sessionID, initialRequest, new java.util.Date());
                                // Trigger the event that an agent has joined a chat session
                                WorkgroupEventDispatcher.agentJoinedChatSupport(this, sessionID, agentSession);
                            }
                        } else {
                            agentSession.removeChatInfo(this, sessionID);
                            // Trigger the event that an agent has left a chat session
                            WorkgroupEventDispatcher.agentLeftChatSupport(this, sessionID, agentSession);
                        }
                    }
                } catch (AgentNotFoundException e) {
                // Do nothing since the AgentSession was not found
                }
                if (presence.isAvailable()) {
                    if (occupantAdded) {
                        // Store in the DB that an agent has joined a room
                        DbWorkgroup.updateJoinedSession(sessionID, agentJID, true);
                    }
                } else {
                    // Store in the DB that an agent has left a room
                    DbWorkgroup.updateJoinedSession(sessionID, agentJID, false);
                }
            } else {
                if (occupantAdded) {
                    // Notify the request that the user has joined a support session
                    initialRequest.supportStarted(roomID);
                }
            }
            if (occupantAdded) {
                initialRequest.userJoinedRoom(new JID(packet.getFrom().toBareJID()), presenceFullJID);
            }
            // If just the user has left the room, just persist the transcript
            boolean isAgent = false;
            try {
                isAgent = agentManager.getAgentSession(presenceFullJID) != null;
            } catch (AgentNotFoundException e) {
            // Ignore.
            }
            if (!((Presence) packet).isAvailable() && !isAgent) {
                // Build the XML for the transcript
                Map<Packet, java.util.Date> map = transcripts.get(roomID);
                StringBuilder buf = new StringBuilder();
                buf.append("<transcript>");
                for (Packet p : map.keySet()) {
                    java.util.Date date = map.get(p);
                    // Add the delay information
                    if (p instanceof Message) {
                        Message storedMessage = (Message) p;
                        Element delay = storedMessage.addChildElement("x", "jabber:x:delay");
                        delay.addAttribute("stamp", UTC_FORMAT.format(date));
                        if (ModelUtil.hasLength(storedMessage.getBody())) {
                            buf.append(p.toXML());
                        }
                    } else {
                        Presence storedPresence = (Presence) p;
                        Element delay = storedPresence.addChildElement("x", "jabber:x:delay");
                        delay.addAttribute("stamp", UTC_FORMAT.format(date));
                        buf.append(p.toXML());
                    }
                // Append an XML representation of the packet to the string buffer
                }
                buf.append("</transcript>");
                // Save the transcript (in XML) to the DB
                DbWorkgroup.updateTranscript(sessionID, buf.toString(), new java.util.Date());
            }
            // the DB and destroy the room
            if (!((Presence) packet).isAvailable() && set.isEmpty()) {
                // Delete the counter of occupants for this room
                occupantsCounter.remove(roomID);
                initialRequest = requests.remove(sessionID);
                if (initialRequest != null && initialRequest.hasJoinedRoom()) {
                    // Notify the request that the support session has finished
                    initialRequest.supportEnded();
                }
                // Build the XML for the transcript
                Map<Packet, java.util.Date> map = transcripts.get(roomID);
                StringBuilder buf = new StringBuilder();
                buf.append("<transcript>");
                for (Packet p : map.keySet()) {
                    java.util.Date date = map.get(p);
                    // Add the delay information
                    if (p instanceof Message) {
                        Message storedMessage = (Message) p;
                        Element delay = storedMessage.addChildElement("x", "jabber:x:delay");
                        delay.addAttribute("stamp", UTC_FORMAT.format(date));
                        if (ModelUtil.hasLength(storedMessage.getBody())) {
                            buf.append(p.toXML());
                        }
                    } else {
                        Presence storedPresence = (Presence) p;
                        Element delay = storedPresence.addChildElement("x", "jabber:x:delay");
                        delay.addAttribute("stamp", UTC_FORMAT.format(date));
                        buf.append(p.toXML());
                    }
                // Append an XML representation of the packet to the string buffer
                }
                buf.append("</transcript>");
                // Save the transcript (in XML) to the DB
                //DbWorkgroup.updateTranscript(sessionID, buf.toString(), new java.util.Date());
                // Leave Chat Room (the room will be destroyed)
                String roomJID = packet.getFrom().toString() + "/" + getJID().getNode();
                LeaveRoom leaveRoom = new LeaveRoom(getFullJID().toString(), roomJID);
                send(leaveRoom);
                // Remove the transcript information of this room since the room no
                // longer exists
                transcripts.remove(roomID);
                // Trigger the event that a chat support has finished
                WorkgroupEventDispatcher.chatSupportFinished(this, sessionID);
            }
            // Invoke the room interceptor after the presence has been processed
            interceptorManager.invokeInterceptors(getJID().toBareJID(), packet, false, true);
        } else if (packet instanceof Message) {
            // transcript to include things like "room locked"
            if (packet.getFrom().getResource() != null) {
                // Invoke the room interceptor before processing the presence
                interceptorManager.invokeInterceptors(getJID().toBareJID(), packet, false, false);
                // Add the new message to the list of sent packets
                Map<Packet, java.util.Date> messageList = transcripts.get(roomID);
                if (messageList == null) {
                    messageList = new LinkedHashMap<Packet, java.util.Date>();
                    transcripts.put(roomID, messageList);
                }
                messageList.put(packet.createCopy(), new java.util.Date());
                // Invoke the room interceptor after the presence has been processed
                interceptorManager.invokeInterceptors(getJID().toBareJID(), packet, false, true);
            }
        }
    }
}
Also used : Packet(org.xmpp.packet.Packet) JID(org.xmpp.packet.JID) Message(org.xmpp.packet.Message) LeaveRoom(org.xmpp.muc.LeaveRoom) Element(org.dom4j.Element) RoomInterceptorManager(org.jivesoftware.xmpp.workgroup.interceptor.RoomInterceptorManager) Date(java.sql.Date) LinkedHashMap(java.util.LinkedHashMap) Presence(org.xmpp.packet.Presence) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UserRequest(org.jivesoftware.xmpp.workgroup.request.UserRequest)

Aggregations

Presence (org.xmpp.packet.Presence)109 JID (org.xmpp.packet.JID)38 Element (org.dom4j.Element)34 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)20 Message (org.xmpp.packet.Message)17 IQ (org.xmpp.packet.IQ)16 UpdatePresence (org.jivesoftware.openfire.muc.cluster.UpdatePresence)14 NotFoundException (org.jivesoftware.util.NotFoundException)12 ArrayList (java.util.ArrayList)11 MUCRole (org.jivesoftware.openfire.muc.MUCRole)10 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)9 DefaultElement (org.dom4j.tree.DefaultElement)8 IOException (java.io.IOException)7 SQLException (java.sql.SQLException)7 GroupJID (org.jivesoftware.openfire.group.GroupJID)7 NotAllowedException (org.jivesoftware.openfire.muc.NotAllowedException)7 Date (java.util.Date)6 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)6 ConflictException (org.jivesoftware.openfire.muc.ConflictException)6 ForbiddenException (org.jivesoftware.openfire.muc.ForbiddenException)6