chatroomimpl.java.svn-base

来自「开源项目openfire的完整源程序」· SVN-BASE 代码 · 共 688 行 · 第 1/2 页

SVN-BASE
688
字号
    }

    /**
     * Returns the users full jid (ex. macbeth@jivesoftware.com/spark).
     *
     * @return the users Full JID.
     */
    public String getJID() {
        presence = PresenceManager.getPresence(getParticipantJID());
        return presence.getFrom();
    }

    /**
     * Process incoming packets.
     *
     * @param packet - the packet to process
     */
    public void processPacket(final Packet packet) {
        final Runnable runnable = new Runnable() {
            public void run() {
                if (packet instanceof Presence) {
                    presence = (Presence)packet;

                    final Presence presence = (Presence)packet;

                    ContactList list = SparkManager.getWorkspace().getContactList();
                    ContactItem contactItem = list.getContactItemByJID(getParticipantJID());

                    final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
                    String time = formatter.format(new Date());

                    if (presence.getType() == Presence.Type.unavailable && contactItem != null) {
                        if (!isOnline()) {
                            getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.went.offline", participantNickname, time), ChatManager.NOTIFICATION_COLOR);
                        }
                    }
                    else if (presence.getType() == Presence.Type.available) {
                        if (!isOnline()) {
                            getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.came.online", participantNickname, time), ChatManager.NOTIFICATION_COLOR);
                        }
                    }
                }
                else if (packet instanceof Message) {
                    lastActivity = System.currentTimeMillis();

                    // Do something with the incoming packet here.
                    final Message message = (Message)packet;
                    if (message.getError() != null) {
                        if (message.getError().getCode() == 404) {
                            // Check to see if the user is online to recieve this message.
                            RosterEntry entry = roster.getEntry(participantJID);
                            if (!presence.isAvailable() && !offlineSent && entry != null) {
                                getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline.error"), ChatManager.ERROR_COLOR);
                                offlineSent = true;
                            }
                        }
                        return;
                    }

                    // Check to see if the user is online to recieve this message.
                    RosterEntry entry = roster.getEntry(participantJID);
                    if (!presence.isAvailable() && !offlineSent && entry != null) {
                        getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline"), ChatManager.ERROR_COLOR);
                        offlineSent = true;
                    }

                    if (threadID == null) {
                        threadID = message.getThread();
                        if (threadID == null) {
                            threadID = StringUtils.randomString(6);
                        }
                    }

                    boolean broadcast = message.getProperty("broadcast") != null;

                    // If this is a group chat message, discard
                    if (message.getType() == Message.Type.groupchat || broadcast || message.getType() == Message.Type.normal ||
                            message.getType() == Message.Type.headline) {
                        return;
                    }

                    // Do not accept Administrative messages.
                    final String host = SparkManager.getSessionManager().getServerAddress();
                    if (host.equals(message.getFrom())) {
                        return;
                    }

                    // If the message is not from the current agent. Append to chat.
                    if (message.getBody() != null) {
                        participantJID = message.getFrom();
                        insertMessage(message);

                        showTyping(false);
                    }
                }
            }
        };
        SwingUtilities.invokeLater(runnable);
    }

    /**
     * Returns the nickname of the user chatting with.
     *
     * @return the nickname of the chatting user.
     */
    public String getParticipantNickname() {
        return participantNickname;
    }


    /**
     * The current SendField has been updated somehow.
     *
     * @param e - the DocumentEvent to respond to.
     */
    public void insertUpdate(DocumentEvent e) {
        checkForText(e);

        if (!sendTypingNotification) {
            return;
        }
        lastTypedCharTime = System.currentTimeMillis();

        // If the user pauses for more than two seconds, send out a new notice.
        if (sendNotification) {
            try {
                SparkManager.getMessageEventManager().sendComposingNotification(getParticipantJID(), threadID);
                sendNotification = false;
            }
            catch (Exception exception) {
                Log.error("Error updating", exception);
            }
        }
    }

    public void insertMessage(Message message) {
        // Debug info
        super.insertMessage(message);
        MessageEvent messageEvent = (MessageEvent)message.getExtension("x", "jabber:x:event");
        if (messageEvent != null) {
            checkEvents(message.getFrom(), message.getPacketID(), messageEvent);
        }

        getTranscriptWindow().insertMessage(participantNickname, message, ChatManager.FROM_COLOR);

        // Set the participant jid to their full JID.
        participantJID = message.getFrom();
    }

    private void checkEvents(String from, String packetID, MessageEvent messageEvent) {
        if (messageEvent.isDelivered() || messageEvent.isDisplayed()) {
            // Create the message to send
            Message msg = new Message(from);
            // Create a MessageEvent Package and add it to the message
            MessageEvent event = new MessageEvent();
            if (messageEvent.isDelivered()) {
                event.setDelivered(true);
            }
            if (messageEvent.isDisplayed()) {
                event.setDisplayed(true);
            }
            event.setPacketID(packetID);
            msg.addExtension(event);
            // Send the packet
            SparkManager.getConnection().sendPacket(msg);
        }
    }

    public void addMessageEventListener(MessageEventListener listener) {
        messageEventListeners.add(listener);
    }

    public void removeMessageEventListener(MessageEventListener listener) {
        messageEventListeners.remove(listener);
    }

    public Collection getMessageEventListeners() {
        return messageEventListeners;
    }

    public void fireOutgoingMessageSending(Message message) {
        Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator();
        while (messageEventListeners.hasNext()) {
            ((MessageEventListener)messageEventListeners.next()).sendingMessage(message);
        }
    }

    public void fireReceivingIncomingMessage(Message message) {
        Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator();
        while (messageEventListeners.hasNext()) {
            ((MessageEventListener)messageEventListeners.next()).receivingMessage(message);
        }
    }


    /**
     * Show the typing notification.
     *
     * @param typing true if the typing notification should show, otherwise hide it.
     */
    public void showTyping(boolean typing) {
        if (typing) {
            String isTypingText = Res.getString("message.is.typing.a.message", participantNickname);
            getNotificationLabel().setText(isTypingText);
            getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_EDIT_IMAGE));
        }
        else {
            // Remove is typing text.
            getNotificationLabel().setText("");
            getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.BLANK_IMAGE));
        }

    }

    /**
     * The last time this chat room sent or received a message.
     *
     * @return the last time this chat room sent or receieved a message.
     */
    public long getLastActivity() {
        return lastActivity;
    }

    /**
     * Returns the current presence of the client this room was created for.
     *
     * @return the presence
     */
    public Presence getPresence() {
        return presence;
    }

    public void setSendTypingNotification(boolean isSendTypingNotification) {
        this.sendTypingNotification = isSendTypingNotification;
    }


    public void connectionClosed() {
        handleDisconnect();

        String message = Res.getString("message.disconnected.error");
        getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR);
    }

    public void connectionClosedOnError(Exception ex) {
        handleDisconnect();

        String message = Res.getString("message.disconnected.error");

        if (ex instanceof XMPPException) {
            XMPPException xmppEx = (XMPPException)ex;
            StreamError error = xmppEx.getStreamError();
            String reason = error.getCode();
            if ("conflict".equals(reason)) {
                message = Res.getString("message.disconnected.conflict.error");
            }
        }

        getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR);
    }

    public void reconnectionSuccessful() {
        Presence usersPresence = PresenceManager.getPresence(getParticipantJID());
        if (usersPresence.isAvailable()) {
            presence = usersPresence;
        }

        SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this);
        getChatInputEditor().setEnabled(true);
        getSendButton().setEnabled(true);
    }

    private void handleDisconnect() {
        presence = new Presence(Presence.Type.unavailable);
        getChatInputEditor().setEnabled(false);
        getSendButton().setEnabled(false);
        SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this);
    }


    private void loadHistory() {
        // Add VCard Panel
        final VCardPanel vcardPanel = new VCardPanel(participantJID);
        getToolBar().add(vcardPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 2), 0, 0));


        final LocalPreferences localPreferences = SettingsManager.getLocalPreferences();
        if (!localPreferences.isChatHistoryEnabled()) {
            return;
        }

        final String bareJID = StringUtils.parseBareAddress(getParticipantJID());
        final ChatTranscript chatTranscript = ChatTranscripts.getCurrentChatTranscript(bareJID);
        final String personalNickname = SparkManager.getUserManager().getNickname();

        for (HistoryMessage message : chatTranscript.getMessages()) {
            String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
            String messageBody = message.getBody();
            if (nickname.equals(message.getFrom())) {
                String otherJID = StringUtils.parseBareAddress(message.getFrom());
                String myJID = SparkManager.getSessionManager().getBareAddress();

                if (otherJID.equals(myJID)) {
                    nickname = personalNickname;
                }
                else {
                    nickname = StringUtils.parseName(nickname);
                }
            }

            if (ModelUtil.hasLength(messageBody) && messageBody.startsWith("/me ")) {
                messageBody = messageBody.replaceAll("/me", nickname);
            }

            final Date messageDate = message.getDate();
            getTranscriptWindow().insertHistoryMessage(nickname, messageBody, messageDate);
        }

    }

    private boolean isOnline() {
        Presence presence = roster.getPresence(getParticipantJID());
        return presence.isAvailable();
    }


    // I would normally use the command pattern, but
    // have no real use when dealing with just a couple options.
    public void actionPerformed(ActionEvent e) {
        super.actionPerformed(e);

        if (e.getSource() == infoButton) {
            VCardManager vcard = SparkManager.getVCardManager();
            vcard.viewProfile(participantJID, SparkManager.getChatManager().getChatContainer());
        }
        else if (e.getSource() == addToRosterButton) {
            RosterDialog rosterDialog = new RosterDialog();
            rosterDialog.setDefaultJID(participantJID);
            rosterDialog.setDefaultNickname(getParticipantNickname());
            rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame());
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?