Search in sources :

Example 1 with TransportBuddy

use of net.sf.kraken.roster.TransportBuddy in project Openfire by igniterealtime.

the class IRCListener method updateCommand.

@Override
@SuppressWarnings("unchecked")
protected void updateCommand(InCommand inCommand) {
    Log.debug("IRC: Received incoming command:" + inCommand);
    if (inCommand instanceof CtcpMessage) {
        CtcpMessage cm = (CtcpMessage) inCommand;
        if (cm.getAction().equals("VERSION")) {
            getSession().getConnection().sendCommand(new CtcpNotice(cm.getSource().getNick(), "VERSION", "IMGateway" + getSession().getTransport().getVersionString() + ":Java:-"));
        } else if (cm.getAction().equals("PING")) {
            String timestamp = cm.getMessage();
            getSession().getConnection().sendCommand(new CtcpNotice(cm.getSource().getNick(), "PING", timestamp));
        } else if (cm.getAction().equals("TIME")) {
            Date current = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZZ");
            getSession().getConnection().sendCommand(new CtcpNotice(cm.getSource().getNick(), "TIME", format.format(current)));
        } else if (cm.getAction().equals("ACTION")) {
            if (cm.isPrivateToUs(getSession().getConnection().getClientState())) {
                getSession().getTransport().sendMessage(getSession().getJID(), getSession().getTransport().convertIDToJID(cm.getSource().getNick()), "/me " + cm.getMessage());
            } else {
                getSession().getTransport().sendMessage(getSession().getJID(), getSession().getTransport().getMUCTransport().convertIDToJID(cm.getDest(), cm.getSource().getNick()), "/me " + cm.getMessage(), Message.Type.groupchat);
            }
        }
    } else if (inCommand instanceof MessageCommand) {
        MessageCommand mc = (MessageCommand) inCommand;
        if (mc.isPrivateToUs(getSession().getConnection().getClientState())) {
            getSession().getTransport().sendMessage(getSession().getJID(), getSession().getTransport().convertIDToJID(mc.getSource().getNick()), IRCStringUtils.stripControlChars(mc.getMessage()));
        } else {
            getSession().getTransport().sendMessage(getSession().getJID(), getSession().getTransport().getMUCTransport().convertIDToJID(mc.getDest(), mc.getSource().getNick()), IRCStringUtils.stripControlChars(mc.getMessage()), Message.Type.groupchat);
        }
    } else if (inCommand instanceof NoticeCommand) {
        NoticeCommand nc = (NoticeCommand) inCommand;
        if (nc.getFrom() != null) {
            getSession().getTransport().sendMessage(getSession().getJID(), getSession().getTransport().convertIDToJID(nc.getFrom().getNick()), IRCStringUtils.stripControlChars(nc.getNotice()));
        }
    } else if (inCommand instanceof JoinCommand) {
        JoinCommand jc = (JoinCommand) inCommand;
        try {
            IRCMUCSession mucSession = (IRCMUCSession) getSession().getMUCSessionManager().getSession(jc.getChannel());
            mucSession.getContacts().add(jc.getUser().getNick());
            Presence p = new Presence();
            p.setFrom(getSession().getTransport().getMUCTransport().convertIDToJID(jc.getChannel(), jc.getUser().getNick()));
            p.setTo(getSession().getJID());
            Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
            Element item = elem.addElement("item");
            item.addAttribute("affiliation", "member");
            item.addAttribute("role", "participant");
            getSession().getTransport().sendPacket(p);
        } catch (NotFoundException e) {
            Log.debug("Received information for IRC session that doesn't exist.");
        }
    } else if (inCommand instanceof PartCommand) {
        PartCommand pc = (PartCommand) inCommand;
        try {
            IRCMUCSession mucSession = (IRCMUCSession) getSession().getMUCSessionManager().getSession(pc.getChannel());
            mucSession.getContacts().remove(pc.getUser().getNick());
            Presence p = new Presence();
            p.setType(Presence.Type.unavailable);
            p.setFrom(getSession().getTransport().getMUCTransport().convertIDToJID(pc.getChannel(), pc.getUser().getNick()));
            p.setTo(getSession().getJID());
            if (pc.getReason() != null && !pc.getReason().equals("")) {
                p.setStatus(pc.getReason());
            }
            Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
            Element item = elem.addElement("item");
            item.addAttribute("affiliation", "none");
            item.addAttribute("role", "none");
            getSession().getTransport().sendPacket(p);
        } catch (NotFoundException e) {
            Log.debug("Received information for IRC session that doesn't exist.");
        }
    } else if (inCommand instanceof QuitCommand) {
        QuitCommand qc = (QuitCommand) inCommand;
        for (MUCTransportSession session : getSession().getMUCSessionManager().getSessions()) {
            if (((IRCMUCSession) session).getContacts().contains(qc.getUser().getNick())) {
                ((IRCMUCSession) session).getContacts().remove(qc.getUser().getNick());
                Presence p = new Presence();
                p.setType(Presence.Type.unavailable);
                p.setFrom(getSession().getTransport().getMUCTransport().convertIDToJID(((IRCMUCSession) session).roomname, qc.getUser().getNick()));
                p.setTo(getSession().getJID());
                if (qc.getReason() != null && !qc.getReason().equals("")) {
                    p.setStatus(qc.getReason());
                }
                Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
                Element item = elem.addElement("item");
                item.addAttribute("affiliation", "none");
                item.addAttribute("role", "none");
                getSession().getTransport().sendPacket(p);
            }
        }
    } else if (inCommand instanceof InviteCommand) {
        InviteCommand ic = (InviteCommand) inCommand;
        BaseMUCTransport mucTransport = getSession().getTransport().getMUCTransport();
        Message m = new Message();
        m.setTo(getSession().getJID());
        m.setFrom(mucTransport.convertIDToJID(ic.getChannel(), null));
        Element x = m.addChildElement("x", "http://jabber.org/protocol/muc#user");
        Element invite = x.addElement("invite");
        invite.addAttribute("from", getSession().getTransport().convertIDToJID(ic.getSourceString()).toBareJID());
        getSession().getTransport().sendPacket(m);
    } else if (inCommand instanceof KickCommand) {
        KickCommand kc = (KickCommand) inCommand;
        BaseMUCTransport mucTransport = getSession().getTransport().getMUCTransport();
        try {
            IRCMUCSession mucSession = (IRCMUCSession) getSession().getMUCSessionManager().getSession(kc.getChannel());
            mucSession.getContacts().add(kc.getKicked().getNick());
            Presence p = new Presence();
            p.setType(Presence.Type.unavailable);
            p.setFrom(mucTransport.convertIDToJID(kc.getChannel(), kc.getKicked().getNick()));
            p.setTo(getSession().getJID());
            Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
            Element item = elem.addElement("item");
            item.addAttribute("affiliation", "none");
            item.addAttribute("role", "none");
            Element actor = item.addElement("actor");
            actor.addAttribute("jid", getSession().getTransport().convertIDToJID(kc.getKicker().getNick()).toBareJID());
            Element reason = item.addElement("reason");
            reason.addText(kc.getComment());
            Element status = elem.addElement("status");
            status.addAttribute("code", "307");
            getSession().getTransport().sendPacket(p);
        } catch (NotFoundException e) {
            Log.debug("Received information for IRC session that doesn't exist.");
        }
        if (kc.kickedUs(getSession().getConnection().getClientState())) {
            getSession().getMUCSessionManager().removeSession(kc.getChannel());
        }
    } else if (inCommand instanceof ChannelModeCommand) {
    //ChannelModeCommand cmc = (ChannelModeCommand)inCommand;
    // TODO: Fix up martyr to handle this then handle it here
    } else if (inCommand instanceof NickCommand) {
    //NickCommand nc = (NickCommand)inCommand;
    // TODO: Map to MUC event  (someone's nick just changed)
    } else if (inCommand instanceof ModeCommand) {
    //ModeCommand mc = (ModeCommand)inCommand;
    // TODO: Map to MUC event  (your mode just changed)
    } else if (inCommand instanceof TopicCommand) {
        TopicCommand tc = (TopicCommand) inCommand;
        Channel channel = getSession().getConnection().getClientState().getChannel(tc.getChannel());
        if (channel != null) {
            BaseMUCTransport mucTransport = getSession().getTransport().getMUCTransport();
            Message m = new Message();
            m.setType(Message.Type.groupchat);
            m.setTo(getSession().getJID());
            m.setFrom(mucTransport.convertIDToJID(channel.getName(), channel.getTopicAuthor()));
            m.setSubject(net.sf.kraken.util.StringUtils.removeInvalidXMLCharacters(channel.getTopic()));
            mucTransport.sendPacket(m);
        }
    } else if (inCommand instanceof TopicInfoReply) {
        TopicInfoReply tir = (TopicInfoReply) inCommand;
        Channel channel = getSession().getConnection().getClientState().getChannel(tir.getChannel());
        if (channel != null) {
            BaseMUCTransport mucTransport = getSession().getTransport().getMUCTransport();
            Message m = new Message();
            m.setType(Message.Type.groupchat);
            m.setTo(getSession().getJID());
            m.setFrom(mucTransport.convertIDToJID(channel.getName(), channel.getTopicAuthor()));
            m.setSubject(net.sf.kraken.util.StringUtils.removeInvalidXMLCharacters(channel.getTopic()));
            mucTransport.sendPacket(m);
        }
    } else if (inCommand instanceof NamesReply) {
        NamesReply nr = (NamesReply) inCommand;
        String channelName = nr.getChannel();
        List<MUCTransportRoomMember> members = new ArrayList<MUCTransportRoomMember>();
        for (String nick : nr.getNames()) {
            members.add(new MUCTransportRoomMember(getSession().getTransport().getMUCTransport().convertIDToJID(channelName, nick)));
        }
        // This will be ignored if no one asked for it.
        getSession().getTransport().getMUCTransport().sendRoomMembers(getSession().getJID(), getSession().getTransport().getMUCTransport().convertIDToJID(channelName, null), members);
    } else if (inCommand instanceof NamesEndReply) {
        NamesEndReply ner = (NamesEndReply) inCommand;
        BaseMUCTransport mucTransport = getSession().getTransport().getMUCTransport();
        try {
            IRCMUCSession mucSession = (IRCMUCSession) getSession().getMUCSessionManager().getSession(ner.getChannel());
            mucSession.getContacts().clear();
            Member myMember = null;
            Channel channel = getSession().getConnection().getClientState().getChannel(ner.getChannel());
            if (channel != null) {
                Enumeration members = channel.getMembers();
                while (members.hasMoreElements()) {
                    Member member = (Member) members.nextElement();
                    if (member.getNick().getNick().equals(mucSession.getNickname()) || member.getNick().getNick().equals(getSession().getRegistration().getNickname())) {
                        // Aha, this is us, save for the end.
                        myMember = member;
                        continue;
                    }
                    Presence p = new Presence();
                    p.setTo(getSession().getJID());
                    if (member.hasOps()) {
                        // Moderator.
                        mucSession.getContacts().add(member.getNick().getNick());
                        p.setFrom(mucTransport.convertIDToJID(ner.getChannel(), member.getNick().getNick()));
                        Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
                        Element item = elem.addElement("item");
                        item.addAttribute("affiliation", "admin");
                        item.addAttribute("role", "moderator");
                    } else {
                        // Regular participant.
                        mucSession.getContacts().add(member.getNick().getNick());
                        p.setFrom(mucTransport.convertIDToJID(ner.getChannel(), member.getNick().getNick()));
                        Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
                        Element item = elem.addElement("item");
                        item.addAttribute("affiliation", "member");
                        item.addAttribute("role", "participant");
                    }
                    mucTransport.sendPacket(p);
                }
            }
            if (myMember != null) {
                Presence p = new Presence();
                p.setTo(getSession().getJID());
                p.setFrom(mucTransport.convertIDToJID(ner.getChannel(), mucSession.getNickname()));
                Element elem = p.addChildElement("x", "http://jabber.org/protocol/muc#user");
                Element item = elem.addElement("item");
                if (myMember.hasOps()) {
                    item.addAttribute("affiliation", "admin");
                    item.addAttribute("role", "moderator");
                } else {
                    item.addAttribute("affiliation", "member");
                    item.addAttribute("role", "participant");
                }
                Element status = elem.addElement("status");
                status.addAttribute("code", "110");
                mucTransport.sendPacket(p);
            }
        } catch (NotFoundException e) {
            Log.debug("Received information for IRC session that doesn't exist.");
        }
    } else if (inCommand instanceof ListStartReply) {
    // Do nothing.
    } else if (inCommand instanceof ListReply) {
        ListReply lr = (ListReply) inCommand;
        String channelName = lr.getChannel();
        MUCTransportRoom mucRoom = getSession().getTransport().getMUCTransport().getCachedRoom(channelName);
        if (mucRoom == null) {
            mucRoom = new MUCTransportRoom(getSession().getTransport().getMUCTransport().convertIDToJID(channelName, ""), channelName);
        }
        mucRoom.setTopic(lr.getTopic());
        mucRoom.setOccupant_count(lr.getMemberCount());
        getSession().getTransport().getMUCTransport().cacheRoom(mucRoom);
        // This will be ignored if no one asked for it.
        getSession().getTransport().getMUCTransport().sendRoomInfo(getSession().getJID(), getSession().getTransport().getMUCTransport().convertIDToJID(mucRoom.getName(), null), mucRoom);
    } else if (inCommand instanceof ListEndReply) {
        // This will be ignored if no one asked for it.
        getSession().getTransport().getMUCTransport().sendRooms(getSession().getJID(), getSession().getTransport().getMUCTransport().getCachedRooms());
    } else if (inCommand instanceof IsonCommand) {
        IsonCommand ic = (IsonCommand) inCommand;
        List<String> newNicks = new ArrayList<String>();
        for (String nick : ic.getNicks()) {
            newNicks.add(nick.toLowerCase());
        }
        Log.debug("IRC: Got ISON for " + ic.getDest() + " of: " + ic.getNicks());
        for (TransportBuddy buddy : getSession().getBuddyManager().getBuddies()) {
            if (!newNicks.contains(buddy.getName())) {
                // Previously online nick went offline
                buddy.setPresence(PresenceType.unavailable);
            } else {
                // Previously online nick is still online
                buddy.setPresence(PresenceType.available);
            }
        }
    } else if (inCommand instanceof UnAwayReply) {
        getSession().setPresence(PresenceType.available);
    } else if (inCommand instanceof NowAwayReply) {
        getSession().setPresence(PresenceType.away);
    } else if (inCommand instanceof AwayReply) {
        AwayReply ar = (AwayReply) inCommand;
        getSession().getTransport().sendMessage(getSession().getJID(), getSession().getTransport().convertIDToJID(ar.getNick()), LocaleUtils.getLocalizedString("gateway.irc.autoreply", "kraken") + " " + ar.getMessage());
    }
}
Also used : CtcpNotice(f00f.net.irc.martyr.commands.CtcpNotice) Message(org.xmpp.packet.Message) CtcpMessage(f00f.net.irc.martyr.commands.CtcpMessage) JoinCommand(f00f.net.irc.martyr.commands.JoinCommand) Element(org.dom4j.Element) ArrayList(java.util.ArrayList) NotFoundException(org.jivesoftware.util.NotFoundException) NickCommand(f00f.net.irc.martyr.commands.NickCommand) UnAwayReply(f00f.net.irc.martyr.replies.UnAwayReply) AwayReply(f00f.net.irc.martyr.replies.AwayReply) NowAwayReply(f00f.net.irc.martyr.replies.NowAwayReply) UnAwayReply(f00f.net.irc.martyr.replies.UnAwayReply) InviteCommand(f00f.net.irc.martyr.commands.InviteCommand) TopicInfoReply(f00f.net.irc.martyr.replies.TopicInfoReply) PartCommand(f00f.net.irc.martyr.commands.PartCommand) ListStartReply(f00f.net.irc.martyr.replies.ListStartReply) NamesReply(f00f.net.irc.martyr.replies.NamesReply) KickCommand(f00f.net.irc.martyr.commands.KickCommand) Presence(org.xmpp.packet.Presence) ModeCommand(f00f.net.irc.martyr.commands.ModeCommand) ChannelModeCommand(f00f.net.irc.martyr.commands.ChannelModeCommand) ArrayList(java.util.ArrayList) List(java.util.List) MUCTransportRoomMember(net.sf.kraken.muc.MUCTransportRoomMember) Member(f00f.net.irc.martyr.clientstate.Member) NamesEndReply(f00f.net.irc.martyr.replies.NamesEndReply) BaseMUCTransport(net.sf.kraken.muc.BaseMUCTransport) IsonCommand(f00f.net.irc.martyr.commands.IsonCommand) MUCTransportSession(net.sf.kraken.muc.MUCTransportSession) Enumeration(java.util.Enumeration) TopicCommand(f00f.net.irc.martyr.commands.TopicCommand) NowAwayReply(f00f.net.irc.martyr.replies.NowAwayReply) MessageCommand(f00f.net.irc.martyr.commands.MessageCommand) Channel(f00f.net.irc.martyr.clientstate.Channel) TransportBuddy(net.sf.kraken.roster.TransportBuddy) CtcpMessage(f00f.net.irc.martyr.commands.CtcpMessage) NoticeCommand(f00f.net.irc.martyr.commands.NoticeCommand) MUCTransportRoomMember(net.sf.kraken.muc.MUCTransportRoomMember) ListEndReply(f00f.net.irc.martyr.replies.ListEndReply) Date(java.util.Date) ListReply(f00f.net.irc.martyr.replies.ListReply) MUCTransportRoom(net.sf.kraken.muc.MUCTransportRoom) QuitCommand(f00f.net.irc.martyr.commands.QuitCommand) ChannelModeCommand(f00f.net.irc.martyr.commands.ChannelModeCommand) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with TransportBuddy

use of net.sf.kraken.roster.TransportBuddy in project Openfire by igniterealtime.

the class BaseTransport method interceptPacket.

/**
     * Intercepts disco items packets to filter out users who aren't allowed to register.
     *
     * @see org.jivesoftware.openfire.interceptor.PacketInterceptor#interceptPacket(org.xmpp.packet.Packet, org.jivesoftware.openfire.session.Session, boolean, boolean)
     */
@SuppressWarnings("unchecked")
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) {
    // If not IQ, return immediately.
    if (!(packet instanceof IQ)) {
        return;
    }
    // If it's a result IQ, process for possible filtering.
    if (((IQ) packet).getType().equals(IQ.Type.result)) {
        // If the packet is not outgoing back to the user or not processed yet, we don't care.
        if (processed || incoming) {
            return;
        }
        // If not query, return immediately.
        Element child = packet.getElement().element("query");
        if (child == null) {
            return;
        }
        // If no namespace uri, return immediately.
        if (child.getNamespaceURI() == null) {
            return;
        }
        // If not disco#items, return immediately.
        if (!child.getNamespaceURI().equals(NameSpace.DISCO_ITEMS)) {
            return;
        }
        // If the node is null, we don't care, not directly related to a user.
        JID to = packet.getTo();
        if (to.getNode() == null) {
            return;
        }
        JID from = packet.getFrom();
        // If not from server itself, return immediately.
        if (!XMPPServer.getInstance().isLocal(from)) {
            return;
        }
        // If user registered, return immediately.
        if (RegistrationManager.getInstance().isRegistered(to, transportType)) {
            return;
        }
        // Check if allowed, if so return immediately.
        if (permissionManager.hasAccess(to)) {
            return;
        }
        // Filter out item associated with transport.
        Iterator iter = child.elementIterator();
        while (iter.hasNext()) {
            Element elem = (Element) iter.next();
            try {
                if (elem.attribute("jid").getText().equals(this.jid.toString())) {
                    child.remove(elem);
                }
            } catch (Exception e) {
            // No worries.  Wasn't what we were looking for.
            }
        }
        return;
    }
    // If it's a set IQ, process for possible roster activity.
    if (((IQ) packet).getType().equals(IQ.Type.set)) {
        // If the packet is not coming from the user, we don't care.
        if (!incoming) {
            return;
        }
        // If not query, return immediately.
        Element child = packet.getElement().element("query");
        if (child == null) {
            return;
        }
        // If not jabber:iq:roster, return immediately.
        if (!child.getNamespaceURI().equals(NameSpace.IQ_ROSTER)) {
            return;
        }
        // Example items in roster modification.
        Iterator iter = child.elementIterator();
        while (iter.hasNext()) {
            Element elem = (Element) iter.next();
            if (!elem.getName().equals("item")) {
                continue;
            }
            String jidStr;
            String nickname = null;
            String sub = null;
            ArrayList<String> groups = new ArrayList<String>();
            try {
                jidStr = elem.attributeValue("jid");
            } catch (Exception e) {
                // No JID found, we don't want this then.
                continue;
            }
            JID jid = new JID(jidStr);
            if (!jid.getDomain().equals(this.getJID().toString())) {
                // Not for our domain, moving on.
                continue;
            }
            if (jid.getNode() == null) {
                // Gateway itself, don't care.
                return;
            }
            try {
                nickname = elem.attributeValue("name");
            } catch (Exception e) {
            // No nickname, ok then.
            }
            try {
                sub = elem.attributeValue("subscription");
            } catch (Exception e) {
            // No subscription, no worries.
            }
            Iterator groupIter = elem.elementIterator();
            while (groupIter.hasNext()) {
                Element groupElem = (Element) groupIter.next();
                if (!groupElem.getName().equals("group")) {
                    continue;
                }
                groups.add(groupElem.getText());
            }
            if (sub != null && sub.equals("remove")) {
                try {
                    TransportSession trSession = sessionManager.getSession(session.getAddress().getNode());
                    if (!trSession.isRosterLocked(jid.toString())) {
                        Log.debug(getType().toString() + ": contact delete " + session.getAddress().getNode() + ":" + jid);
                        trSession.getBuddyManager().removeBuddy(convertJIDToID(jid));
                    }
                } catch (NotFoundException e) {
                // Well we just don't care then.
                }
            } else {
                try {
                    TransportSession trSession = sessionManager.getSession(session.getAddress().getNode());
                    if (!trSession.isRosterLocked(jid.toString())) {
                        try {
                            TransportBuddy buddy = trSession.getBuddyManager().getBuddy(jid);
                            Log.debug(getType().toString() + ": contact update " + session.getAddress().getNode() + ":" + jid + ":" + nickname + ":" + groups);
                            buddy.setNicknameAndGroups(nickname, groups);
                        } catch (NotFoundException e) {
                            Log.debug(getType().toString() + ": contact add " + session.getAddress().getNode() + ":" + jid + ":" + nickname + ":" + groups);
                            trSession.addContact(jid, nickname, groups);
                        }
                    }
                } catch (NotFoundException e) {
                // Well we just don't care then.
                }
            }
        }
    }
}
Also used : Element(org.dom4j.Element) TransportBuddy(net.sf.kraken.roster.TransportBuddy) NotFoundException(org.jivesoftware.util.NotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) TransportSession(net.sf.kraken.session.TransportSession) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) NotFoundException(org.jivesoftware.util.NotFoundException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 3 with TransportBuddy

use of net.sf.kraken.roster.TransportBuddy in project Openfire by igniterealtime.

the class BaseTransport method syncLegacyRoster.

/**
     * Sync a user's roster with their legacy contact list.
     *
     * Given a collection of transport buddies, syncs up the user's
     * roster by fixing any nicknames, group assignments, adding and removing
     * roster items, and generally trying to make the jabber roster list
     * assigned to the transport's JID look at much like the legacy buddy
     * list as possible.  This is a very extensive operation.  You do not
     * want to do this very often.  Typically once right after the person
     * has logged into the legacy service.
     *
     * @param userjid JID of user who's roster we are syncing with.
     * @param legacyitems List of TransportBuddy's to be synced.
     * @throws UserNotFoundException if userjid not found.
     */
public void syncLegacyRoster(JID userjid, Collection<B> legacyitems) throws UserNotFoundException {
    Log.debug("Syncing Legacy Roster: " + legacyitems);
    try {
        Roster roster = rosterManager.getRoster(userjid.getNode());
        // Lets lock down the roster from update notifications if there's an active session.
        try {
            TransportSession<B> session = sessionManager.getSession(userjid.getNode());
            session.lockRoster();
        } catch (NotFoundException e) {
        // No active session?  Then no problem.
        }
        // First thing first, we want to build ourselves an easy mapping.
        Map<JID, TransportBuddy> legacymap = new HashMap<JID, TransportBuddy>();
        for (TransportBuddy buddy : legacyitems) {
            //                Log.debug("ROSTERSYNC: Mapping "+buddy.getName());
            legacymap.put(buddy.getJID(), buddy);
        }
        // Now, lets go through the roster and see what matches up.
        for (RosterItem ri : roster.getRosterItems()) {
            if (!ri.getJid().getDomain().equals(this.jid.getDomain())) {
                // Not our contact to care about.
                continue;
            }
            if (ri.getJid().getNode() == null) {
                // This is a transport instance, lets leave it alone.
                continue;
            }
            JID jid = new JID(ri.getJid().toBareJID());
            if (legacymap.containsKey(jid)) {
                Log.debug("ROSTERSYNC: We found, updating " + jid.toString());
                // Ok, matched a legacy to jabber roster item
                // Lets update if there are differences
                TransportBuddy buddy = legacymap.get(jid);
                try {
                    if (buddy.getAskType() != null && buddy.getSubType() != null) {
                        this.addOrUpdateRosterItem(userjid, buddy.getName(), buddy.getNickname(), buddy.getGroups(), buddy.getSubType(), buddy.getAskType());
                    } else {
                        this.addOrUpdateRosterItem(userjid, buddy.getName(), buddy.getNickname(), buddy.getGroups());
                    }
                } catch (UserNotFoundException e) {
                    Log.debug("Failed updating roster item", e);
                }
                legacymap.remove(jid);
            } else {
                Log.debug("ROSTERSYNC: We did not find, removing " + jid.toString());
                // This person is apparantly no longer in the legacy roster.
                try {
                    this.removeFromRoster(userjid, jid);
                } catch (UserNotFoundException e) {
                    Log.debug("Failed removing roster item", e);
                }
            }
        }
        // Ok, we should now have only new items from the legacy roster
        for (TransportBuddy buddy : legacymap.values()) {
            Log.debug("ROSTERSYNC: We have new, adding " + buddy.getName());
            try {
                this.addOrUpdateRosterItem(userjid, buddy.getName(), buddy.getNickname(), buddy.getGroups());
            } catch (UserNotFoundException e) {
                Log.debug("Failed adding new roster item", e);
            }
        }
        // All done, lets unlock the roster.
        try {
            TransportSession<B> session = sessionManager.getSession(userjid.getNode());
            session.unlockRoster();
        } catch (NotFoundException e) {
        // No active session?  Then no problem.
        }
    } catch (UserNotFoundException e) {
        throw new UserNotFoundException("Could not find roster for " + userjid.toString());
    }
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Roster(org.jivesoftware.openfire.roster.Roster) TransportBuddy(net.sf.kraken.roster.TransportBuddy) NotFoundException(org.jivesoftware.util.NotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 4 with TransportBuddy

use of net.sf.kraken.roster.TransportBuddy in project Openfire by igniterealtime.

the class BaseTransport method processPacket.

/**
     * Handles all incoming presence stanzas.
     *
     * @param packet The presence packet to be processed.
     * @return list of packets that will be sent back to the presence requester.
     */
private List<Packet> processPacket(Presence packet) {
    Log.debug("Received presence packet: " + packet.toXML());
    List<Packet> reply = new ArrayList<Packet>();
    JID from = packet.getFrom();
    JID to = packet.getTo();
    if (to == null) {
        // Well clearly it's for us or it wouldn't have gotten here...
        packet.setTo(getJID());
        to = getJID();
    }
    if (packet.getType() == Presence.Type.error) {
        // We don't want to do anything with this.  Ignore it.
        return reply;
    }
    try {
        if (to.getNode() == null) {
            Collection<Registration> registrations = RegistrationManager.getInstance().getRegistrations(from, this.transportType);
            if (registrations.isEmpty()) {
                // User is not registered with us.
                Log.debug("Unable to find registration.");
                Presence p = new Presence();
                p.setTo(from);
                p.setFrom(to);
                p.setError(PacketError.Condition.forbidden);
                p.setType(Presence.Type.unavailable);
                reply.add(p);
                return reply;
            }
            if (JiveGlobals.getBooleanProperty("plugin.gateway." + getType() + ".registrationstrict", false) && !permissionManager.hasAccess(from)) {
                Log.debug("Attempt to log in by restricted account: " + from);
                Presence p = new Presence();
                p.setTo(from);
                p.setFrom(to);
                p.setError(PacketError.Condition.forbidden);
                p.setType(Presence.Type.unavailable);
                reply.add(p);
                return reply;
            }
            Registration registration = registrations.iterator().next();
            // This packet is to the transport itself.
            if (packet.getType() == null) {
                // A user's resource has come online.
                TransportSession<B> session;
                Lock l = CacheFactory.getLock(registration.getJID() + "@" + transportType.toString() + "ns", sessionRouter.sessionLocations);
                try {
                    l.lock();
                    session = sessionManager.getSession(from);
                    if (session.hasResource(from.getResource())) {
                        Log.debug("An existing resource has changed status: " + from);
                        if (session.getPriority(from.getResource()) != packet.getPriority()) {
                            session.updatePriority(from.getResource(), packet.getPriority());
                        }
                        if (session.isHighestPriority(from.getResource())) {
                            // Well, this could represent a status change.
                            session.updateStatus(getPresenceType(packet), packet.getStatus());
                        }
                    } else {
                        Log.debug("A new resource has come online: " + from);
                        // This is a new resource, lets send them what we know.
                        session.addResource(from.getResource(), packet.getPriority());
                        // Tell the new resource what the state of their buddy list is.
                        session.getBuddyManager().sendAllAvailablePresences(from);
                        // If this priority is the highest, treat it's status as golden
                        if (session.isHighestPriority(from.getResource())) {
                            session.updateStatus(getPresenceType(packet), packet.getStatus());
                        }
                    }
                    // Attach the session
                    session.attachSession();
                } catch (NotFoundException e) {
                    Log.debug("A new session has come online: " + from);
                    session = this.registrationLoggedIn(registration, from, getPresenceType(packet), packet.getStatus(), packet.getPriority());
                    sessionManager.storeSession(from, session);
                } finally {
                    l.unlock();
                }
            } else if (packet.getType() == Presence.Type.unavailable) {
                // A user's resource has gone offline.
                TransportSession<B> session;
                try {
                    session = sessionManager.getSession(from);
                    String resource = from.getResource();
                    if (session.hasResource(resource)) {
                        if (session.getResourceCount() > 1) {
                            // Just one of the resources, lets adjust accordingly.
                            if (session.isHighestPriority(resource)) {
                                Log.debug("A high priority resource (of multiple) has gone offline: " + from);
                                // Ooh, the highest resource went offline, drop to next highest.
                                session.removeResource(resource);
                                // Lets ask the next highest resource what it's presence is.
                                Presence p = new Presence(Presence.Type.probe);
                                p.setTo(session.getJIDWithHighestPriority());
                                p.setFrom(this.getJID());
                                sendPacket(p);
                            } else {
                                Log.debug("A low priority resource (of multiple) has gone offline: " + from);
                                // Meh, lower priority, big whoop.
                                session.removeResource(resource);
                            }
                        } else {
                            Log.debug("A final resource has gone offline: " + from);
                            // No more resources, byebye.
                            this.registrationLoggedOut(session);
                            sessionManager.removeSession(from);
                        }
                    }
                } catch (NotFoundException e) {
                    Log.debug("Ignoring unavailable presence for inactive seession.");
                }
            } else if (packet.getType() == Presence.Type.probe) {
                // Client is asking for presence status.
                TransportSession<B> session;
                try {
                    session = sessionManager.getSession(from);
                    session.sendPresence(from);
                } catch (NotFoundException e) {
                    Log.debug("Ignoring probe presence for inactive session.");
                }
            } else {
                Log.debug("Ignoring this packet:" + packet.toString());
            // Anything else we will ignore for now.
            }
        } else {
            // This packet is to a user at the transport.
            try {
                TransportSession<B> session = sessionManager.getSession(from);
                if (packet.getType() == Presence.Type.probe) {
                    // Presence probe, lets try to answer appropriately.
                    if (session.isLoggedIn()) {
                        try {
                            TransportBuddy buddy = session.getBuddyManager().getBuddy(to);
                            buddy.sendPresence(from);
                        } catch (NotFoundException e) {
                            // User was not found so send an error presence
                            Presence p = new Presence();
                            p.setTo(from);
                            p.setFrom(to);
                            // TODO: this causes some ugliness in some clients
                            //                                p.setError(PacketError.Condition.forbidden);
                            // If the user tries to check on a buddy before we are totally logged in
                            // and have the full list, this gets thrown for legit contacts.
                            // We'll send unavailable for now.
                            p.setType(Presence.Type.unavailable);
                            sendPacket(p);
                        }
                    }
                } else if (packet.getType() == Presence.Type.subscribe) {
                    // For the time being, we are going to lie to the end user that the subscription has worked.
                    Presence p = new Presence();
                    p.setType(Presence.Type.subscribed);
                    p.setTo(from);
                    p.setFrom(to);
                    sendPacket(p);
                } else if (packet.getType() == Presence.Type.unsubscribe) {
                    // For the time being, we are going to lie to the end user that the unsubscription has worked.
                    Presence p = new Presence();
                    p.setType(Presence.Type.unsubscribed);
                    p.setTo(from);
                    p.setFrom(to);
                    sendPacket(p);
                } else if (packet.getType() == Presence.Type.subscribed) {
                    // let the legacy domain know that the contact was accepted.
                    session.acceptAddContact(packet.getTo());
                } else {
                // Anything else we will ignore for now.
                }
            } catch (NotFoundException e) {
                // Well we just don't care then.
                Log.debug("User not found while processing " + "presence stanza: " + packet.toXML(), e);
            }
        }
    } catch (Exception e) {
        Log.debug("Exception while processing packet: ", e);
    }
    return reply;
}
Also used : TransportBuddy(net.sf.kraken.roster.TransportBuddy) NotFoundException(org.jivesoftware.util.NotFoundException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) TransportSession(net.sf.kraken.session.TransportSession) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) NotFoundException(org.jivesoftware.util.NotFoundException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Lock(java.util.concurrent.locks.Lock) Registration(net.sf.kraken.registration.Registration)

Example 5 with TransportBuddy

use of net.sf.kraken.roster.TransportBuddy in project Openfire by igniterealtime.

the class IRCSession method logIn.

@Override
public void logIn(PresenceType presenceType, String verboseStatus) {
    connection = new IRCConnection();
    autoResponder = new AutoResponder(connection);
    //        autoReconnect = new AutoReconnect(connection);
    autoRegister = new AutoRegister(connection, getRegistration().getNickname(), getRegistration().getNickname(), "IM Gateway User", getRegistration().getPassword());
    listener = new IRCListener(this);
    listener.enable();
    new Thread() {

        @Override
        public void run() {
            try {
                connection.connect(JiveGlobals.getProperty("plugin.gateway.irc.connecthost", "irc.freenode.net"), JiveGlobals.getIntProperty("plugin.gateway.irc.connectport", 7000));
                setPresence(PresenceType.available);
                setLoginStatus(TransportLoginStatus.LOGGED_IN);
                try {
                    getTransport().syncLegacyRoster(getJID(), getBuddyManager().getBuddies());
                } catch (UserNotFoundException e) {
                    Log.debug("IRC: Error finding user while syncing legacy roster.");
                }
                List<String> buddyList = new ArrayList<String>();
                for (TransportBuddy buddy : getBuddyManager().getBuddies()) {
                    buddyList.add(buddy.getName());
                }
                if (!buddyList.isEmpty()) {
                    connection.sendCommand(new IsonCommand(StringUtils.join(buddyList, " ")));
                }
                statusCheck = new StatusCheck();
                timer.schedule(statusCheck, timerInterval, timerInterval);
                getBuddyManager().activate();
            } catch (UnknownHostException e) {
                Log.debug("IRC: Unable to connect to host:", e);
                setFailureStatus(ConnectionFailureReason.CAN_NOT_CONNECT);
                sessionDisconnected("IRC server does not appear to exist.");
            } catch (IOException e) {
                Log.debug("IRC: Connection error while trying to connect ot IRC server:", e);
                setFailureStatus(ConnectionFailureReason.CAN_NOT_CONNECT);
                sessionDisconnected("Connection failed while trying to contact IRC server..");
            }
        }
    }.start();
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) IsonCommand(f00f.net.irc.martyr.commands.IsonCommand) UnknownHostException(java.net.UnknownHostException) TransportBuddy(net.sf.kraken.roster.TransportBuddy) IOException(java.io.IOException) IRCConnection(f00f.net.irc.martyr.IRCConnection) AutoResponder(f00f.net.irc.martyr.services.AutoResponder) AutoRegister(f00f.net.irc.martyr.services.AutoRegister) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

TransportBuddy (net.sf.kraken.roster.TransportBuddy)6 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)5 NotFoundException (org.jivesoftware.util.NotFoundException)5 IsonCommand (f00f.net.irc.martyr.commands.IsonCommand)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 TransportSession (net.sf.kraken.session.TransportSession)2 Element (org.dom4j.Element)2 IRCConnection (f00f.net.irc.martyr.IRCConnection)1 Channel (f00f.net.irc.martyr.clientstate.Channel)1 Member (f00f.net.irc.martyr.clientstate.Member)1 ChannelModeCommand (f00f.net.irc.martyr.commands.ChannelModeCommand)1 CtcpMessage (f00f.net.irc.martyr.commands.CtcpMessage)1 CtcpNotice (f00f.net.irc.martyr.commands.CtcpNotice)1 InviteCommand (f00f.net.irc.martyr.commands.InviteCommand)1 JoinCommand (f00f.net.irc.martyr.commands.JoinCommand)1 KickCommand (f00f.net.irc.martyr.commands.KickCommand)1 MessageCommand (f00f.net.irc.martyr.commands.MessageCommand)1 ModeCommand (f00f.net.irc.martyr.commands.ModeCommand)1