org.jivesoftware.smackx.chatstates.ChatState Java Examples

The following examples show how to use org.jivesoftware.smackx.chatstates.ChatState. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ChatRoom.java    From Spark with Apache License 2.0 6 votes vote down vote up
protected void createChatStateTimerTask() {
     typingTimerTask = new TimerTask() {
         @Override
public void run() {
             final long lastUpdate = System.currentTimeMillis() - lastNotificationSentTime;
             switch ( lastNotificationSent ) {
                 case paused:
                 case active:
                     if ( lastUpdate > inactiveTimePeriod ) {
                         setChatState( ChatState.inactive );
                     }
                     break;

                 case composing:
                     if ( lastUpdate > pauseTimePeriod ) {
                         setChatState( ChatState.paused );
                     }
                     break;
             }
         }
     };
     TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, pauseTimePeriod /2, pauseTimePeriod / 2);
 }
 
Example #2
Source File: ChatStateIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@SmackIntegrationTest
public void testChatStateListeners() throws Exception {
    ChatStateManager manOne = ChatStateManager.getInstance(conOne);
    ChatStateManager manTwo = ChatStateManager.getInstance(conTwo);

    // Add chatState listeners.
    manTwo.addChatStateListener(this::composingListener);
    manTwo.addChatStateListener(this::activeListener);

    Chat chatOne = ChatManager.getInstanceFor(conOne)
            .chatWith(conTwo.getUser().asEntityBareJid());

    // Test, if setCurrentState works and the chatState arrives
    manOne.setCurrentState(ChatState.composing, chatOne);
    composingSyncPoint.waitForResult(timeout);

    // Test, if the OutgoingMessageInterceptor successfully adds a chatStateExtension of "active" to
    // an outgoing chat message and if it arrives at the other side.
    Chat chat = ChatManager.getInstanceFor(conOne)
            .chatWith(conTwo.getUser().asEntityBareJid());
    chat.send("Hi!");
    activeSyncPoint.waitForResult(timeout);
}
 
Example #3
Source File: OperationSetTypingNotificationsJabberImpl.java    From jitsi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and sends a packet for the new chat state.
 * @param chatState the new chat state.
 * @param jid the JID of the receiver.
 */
private void setCurrentState(ChatState chatState, Jid jid)
    throws NotConnectedException, InterruptedException
{
    String threadID = opSetBasicIM.getThreadIDForAddress(jid.asBareJid());
    if(threadID == null)
        return;

    Message message = new Message();
    ChatStateExtension extension = new ChatStateExtension(chatState);
    message.addExtension(extension);

    message.setTo(jid);
    message.setType(Message.Type.chat);
    message.setThread(threadID);
    message.setFrom(parentProvider.getConnection().getUser());
    parentProvider.getConnection().sendStanza(message);
}
 
Example #4
Source File: EligibleForChatMarkerFilter.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * From XEP-0333, Protocol Format: The Chat Marker MUST have an 'id' which is the 'id' of the
 * message being marked.<br>
 * In order to make Chat Markers works together with XEP-0085 as it said in
 * 8.5 Interaction with Chat States, only messages with <code>active</code> chat
 * state are accepted.
 *
 * @param message to be analyzed.
 * @return true if the message contains a stanza Id.
 * @see <a href="http://xmpp.org/extensions/xep-0333.html">XEP-0333: Chat Markers</a>
 */
@Override
public boolean accept(Stanza message) {
    if (!message.hasStanzaIdSet()) {
        return false;
    }

    if (super.accept(message)) {
        ExtensionElement extension = message.getExtension(ChatStateManager.NAMESPACE);
        String chatStateElementName = extension.getElementName();

        ChatState state;
        try {
            state = ChatState.valueOf(chatStateElementName);
            return state == ChatState.active;
        }
        catch (Exception ex) {
            return false;
        }
    }

    return true;
}
 
Example #5
Source File: Control.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Inform model (and view) about a received chat state notification.
 */
public void onChatStateNotification(MessageIDs ids,
        Optional<Date> serverDate,
        ChatState chatState) {
    if (serverDate.isPresent()) {
        long diff = new Date().getTime() - serverDate.get().getTime();
        if (diff > TimeUnit.SECONDS.toMillis(10)) {
            // too old
            return;
        }
    }
    Contact contact = mModel.contacts().get(ids.jid).orElse(null);
    if (contact == null) {
        LOGGER.info("can't find contact with jid: "+ids.jid);
        return;
    }
    // NOTE: assume chat states are only send for single chats
    SingleChat chat = mModel.chats().get(contact, ids.xmppThreadID).orElse(null);
    if (chat == null)
        // not that important
        return;

    chat.setChatState(contact, chatState);
}
 
Example #6
Source File: ChatStateManager.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
private void setNewState(ChatState state) {
    // currently set states from XEP-0085: active, inactive, composing
    mCurrentState = state;

    if (state == ChatState.active || !(mChat instanceof SingleChat))
        // don't send for groups (TODO (?))
        // 'active' is send inside a message
        return;

    Contact contact = ((SingleChat) mChat).getMember().getContact();
    if (contact.isMe() || contact.isBlocked() || contact.isDeleted())
        return;

    if (Config.getInstance().getBoolean(Config.NET_SEND_CHAT_STATE))
        mClient.sendChatState(contact.getJID(), mChat.getXMPPID(), state);
}
 
Example #7
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendChatState(ChatState state) throws SmackException.NotConnectedException, InterruptedException
{
    if ( !active )
    {
        return;
    }

    final Message message = new Message();
    message.setType( Message.Type.chat );
    message.setTo( participantJID );
    message.setFrom( SparkManager.getSessionManager().getJID());

    if (threadID == null) {
        threadID = StringUtils.randomString(6);
    }
    message.setThread(threadID);
    message.addExtension( new ChatStateExtension( state ) );

    SparkManager.getConnection().sendStanza( message );
}
 
Example #8
Source File: GroupChatRoom.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendChatState(ChatState state) throws SmackException.NotConnectedException, InterruptedException
{
    if (!chatStatEnabled || !SparkManager.getConnection().isConnected() )
    {
        return;
    }

    // XEP-0085: SHOULD NOT send 'gone' in a MUC.
    if ( state == ChatState.gone )
    {
        return;
    }

    for ( final EntityFullJid occupant : chat.getOccupants() )
    {
        final Resourcepart occupantNickname = occupant.getResourcepart();
        final Resourcepart myNickname = chat.getNickname();
        if (occupantNickname != null && !occupantNickname.equals(myNickname))
        {
            SparkManager.getMessageEventManager().sendComposingNotification(occupant, "djn");
        }
    }
}
 
Example #9
Source File: ChatRoom.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the chat state, causing an update to be sent to all peers if the new state warrants an update.
 *
 * @param state the chat state (never null).
 */
public final void setChatState(ChatState state)
{
    if ( state == null ) {
        throw new IllegalArgumentException( "Argument 'state' cannot be null." );
    }

    // Only sent out a chat state notification when it is different from the last one that was transmitted...
    final boolean isDifferentState = lastNotificationSent != state;

    // ... unless it's 'composing' - that can be repeated every so many seconds.
    final boolean isStillComposing = state == ChatState.composing && System.currentTimeMillis() - lastNotificationSentTime > 2000;

    final long now = System.currentTimeMillis();
    if ( isDifferentState || isStillComposing )
    {
        try
        {
            sendChatState( state );
        } catch ( SmackException.NotConnectedException | InterruptedException e ) {
            Log.warning( "Unable to update the chat state to " + state, e );
        }
        lastNotificationSent = state;
        lastNotificationSentTime = now;
    }
}
 
Example #10
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
private void sendChatState (String to, ChatState currentChatState)
{
    try {
        if (mConnection != null && mConnection.isConnected())
        {
            Chat thisChat = mChatMap.get(to);

            if (thisChat == null) {
                thisChat = mChatManager.chatWith(JidCreate.from(to).asEntityBareJidIfPossible());
                mChatMap.put(to,thisChat);
            }

            if (mChatStateManager != null)
                mChatStateManager.setCurrentState(currentChatState,thisChat);
        }
    }
    catch (Exception e)
    {
        Log.w(ImApp.LOG_TAG,"error sending chat state: " + e.getMessage());
    }
}
 
Example #11
Source File: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
public void composingNotification(final Jid from) {
    SwingUtilities.invokeLater( () -> {
        final ContactList contactList = SparkManager.getWorkspace().getContactList();

        ChatRoom chatRoom;
        try {
            chatRoom = getChatContainer().getChatRoom( from.asBareJid() );
            if (chatRoom != null && chatRoom instanceof ChatRoomImpl) {
                typingNotificationList.add(chatRoom);
                // Notify Decorators
                notifySparkTabHandlers(chatRoom);
                ((ChatRoomImpl)chatRoom).notifyChatStateChange(ChatState.composing);
            }
        }
        catch (ChatRoomNotFoundException e) {
            // Do nothing
        }
        contactList.setIconFor(from, SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_EDIT_IMAGE));
    } );
}
 
Example #12
Source File: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
public void cancelledNotification(final Jid from, final ChatState state) {
    SwingUtilities.invokeLater( () -> {
        ContactList contactList = SparkManager.getWorkspace().getContactList();

        ChatRoom chatRoom;
        try {
            chatRoom = getChatContainer().getChatRoom(from.asBareJid());
            if (chatRoom != null && chatRoom instanceof ChatRoomImpl) {
                typingNotificationList.remove(chatRoom);
                // Notify Decorators
                notifySparkTabHandlers(chatRoom);
                ((ChatRoomImpl)chatRoom).notifyChatStateChange(state);
            }
        }
        catch (ChatRoomNotFoundException e) {
            // Do nothing
        }
        contactList.useDefaults(from);
    } );
}
 
Example #13
Source File: RoomManager.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
public void updateTypingStatus(final ChatState chatState, final String jid, final int chatType) {
    if (!Preferences.isTesting()) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Message message = new Message(JidCreate.from(jid));
                    message.addExtension(new ChatStateExtension(chatState));

                    if (chatType == Chat.TYPE_1_T0_1) {
                        message.setType(Message.Type.chat);
                    } else {
                        message.setType(Message.Type.groupchat);
                    }

                    sendMessageDependingOnType(message, jid, chatType);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
 
Example #14
Source File: SysTrayPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public void stateChanged(Chat chat, ChatState state, Message message) {
	presence = Workspace.getInstance().getStatusBar().getPresence();
	if (ChatState.composing.equals(state)) {
		changeSysTrayIcon();
	} else {
		if (!newMessage) {
			if (presence.getMode() == Presence.Mode.available) {
				trayIcon.setImage(availableIcon.getImage());
			} else if (presence.getMode() == Presence.Mode.away
					|| presence.getMode() == Presence.Mode.xa) {
				trayIcon.setImage(awayIcon.getImage());
			} else if (presence.getMode() == Presence.Mode.dnd) {
				trayIcon.setImage(dndIcon.getImage());
			} else {
				trayIcon.setImage(newMessageIcon.getImage());
			}
		}
	}
}
 
Example #15
Source File: ChatRoom.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Close the ChatRoom.
 */
public void closeChatRoom() {
    fireClosingListeners();

    setChatState(ChatState.gone);

    if (typingTimerTask != null) {
        TaskEngine.getInstance().cancelScheduledTask(typingTimerTask);
        typingTimerTask = null;
    }

    getTranscriptWindow().removeContextMenuListener(this);
    getTranscriptWindow().removeMouseListener(transcriptWindowMouseListener);
    getChatInputEditor().removeKeyListener(chatEditorKeyListener);
    this.removeAll();

    textScroller.getViewport().remove(transcriptWindow);

    // Remove Connection Listener
    SparkManager.getConnection().removeConnectionListener(this);
    getTranscriptWindow().setTransferHandler(null);
    getChatInputEditor().setTransferHandler(null);

    transferHandler = null;

    packetIDList.clear();
    messageListeners.clear();
    fileDropListeners.clear();
    getChatInputEditor().close();

    getChatInputEditor().getActionMap().remove("closeTheRoom");
    chatAreaButton.getButton().removeActionListener(this);
    bottomPanel.remove(chatAreaButton);
    // TODO: We are seeing NPEs in the next line. Find out why _chatFrame is null.
    _chatFrame.removeWindowToFrontListener(this);
}
 
Example #16
Source File: ChatRoom.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void insertUpdate(DocumentEvent e) {
       // Meant to be overriden
       checkForText(e);

       setChatState( ChatState.composing );
   }
 
Example #17
Source File: ChatActivity.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
private void sendInactiveTypingStatus() {
    if (wasComposingMessage()) {
        mRoomManager.updateTypingStatus(ChatState.paused, mChatJID, mChat.getType());
    } else {
        mRoomManager.updateTypingStatus(ChatState.inactive, mChatJID, mChat.getType());
    }
}
 
Example #18
Source File: ChatStatePanel.java    From Spark with Apache License 2.0 5 votes vote down vote up
public ChatStatePanel(ChatState state, CharSequence nickname) {
	setLayout(new FlowLayout(FlowLayout.LEFT, 1, 1));
	JLabel label = new JLabel( Res.getString( state.name(), nickname.toString() ) );
	label.setFont(new Font("Courier New", Font.PLAIN, 9));
	label.setForeground(Color.gray);
	label.setHorizontalTextPosition(JLabel.LEFT);
	label.setVerticalTextPosition(JLabel.BOTTOM);
	add( label );
}
 
Example #19
Source File: ChatRoom.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void focusGained(FocusEvent focusEvent) {
       validate();
       invalidate();
       repaint();

       if(focusEvent.getComponent().equals(getChatInputEditor())) {
           setChatState( ChatState.active );
       }

   }
 
Example #20
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 5 votes vote down vote up
public void notifyChatStateChange(ChatState state) {
	if (chatStatePanel != null) {
		getEditorWrapperBar().remove(chatStatePanel);
	}
	
	chatStatePanel = new ChatStatePanel(state, getParticipantNickname());   	
	getEditorWrapperBar().add(chatStatePanel, BorderLayout.SOUTH);
	getEditorWrapperBar().revalidate();
	getEditorWrapperBar().repaint();
}
 
Example #21
Source File: ChatRoomImpl.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
    * Sends a message to the appropriate jid. The message is automatically added to the transcript.
    *
    * @param message the message to send.
    */
   @Override
public void sendMessage(Message message) {
       //Before sending message, let's add our full jid for full verification
       //Set message attributes before insertMessage is called - this is useful when transcript window is extended
       //more information will be available to be displayed for the chat area Document
       message.setType(Message.Type.chat);
       message.setTo(participantJID);
       message.setFrom(SparkManager.getSessionManager().getJID());

       displaySendMessage( message );

       // No need to request displayed or delivered as we aren't doing anything with this
       // information.
       MessageEventManager.addNotificationsRequests(message, true, false, false, true);

       // Set chat state to 'active'
       message.addExtension( new ChatStateExtension( ChatState.active ) );

       // Send the message that contains the notifications request
       try {
           fireOutgoingMessageSending(message);
           SparkManager.getConnection().sendStanza(message);
       }
       catch (Exception ex) {
           Log.error("Error sending message", ex);
       }
   }
 
Example #22
Source File: OperationSetTypingNotificationsJabberImpl.java    From jitsi with Apache License 2.0 5 votes vote down vote up
@Override
public void processStanza(Stanza packet)
{
    Message msg = (Message) packet;
    ChatStateExtension ext = (ChatStateExtension) msg.getExtension(
        "http://jabber.org/protocol/chatstates");
    if(ext == null)
        return;
    stateChanged(ChatState.valueOf(ext.getElementName()), msg);
}
 
Example #23
Source File: ChatManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
    * Called by smack when the state of a chat changes.
    *
    * @param chat the chat that is concerned by this event.
    * @param state the new state of the chat.
    */
@Override
   public void stateChanged(Chat chat, ChatState state, Message message) {
    Jid participant = chat.getXmppAddressOfChatPartner();
       if (ChatState.composing.equals(state)) {
           composingNotification(participant);
       } else {
       	cancelledNotification(participant, state);
       }
       
   }
 
Example #24
Source File: BaseInstrumentedTest.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
private void mockRoomManager() {
    mRoomManagerMock = mock(RoomManager.class);
    RoomManager.setSpecialInstanceForTesting(mRoomManagerMock);
    doNothing().when(mRoomManagerMock).updateTypingStatus(any(ChatState.class), any(String.class), any(int.class));
    doNothing().when(mRoomManagerMock).addToMUCLight(any(User.class), any(String.class));
    doNothing().when(mRoomManagerMock).removeFromMUCLight(any(User.class), any(String.class));
}
 
Example #25
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendTypingStatus (final String to, final boolean isTyping)
{
    if (mExecutor != null)
        mExecutor.execute(new Runnable() {
            public void run() {
                sendChatState(to, isTyping ? ChatState.composing : ChatState.inactive);
            }
        });
}
 
Example #26
Source File: ChatStateExtensionProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public ChatStateExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) {
    String chatStateString = parser.getName();
    ChatState state = ChatState.valueOf(chatStateString);

    return new ChatStateExtension(state);
}
 
Example #27
Source File: ChatView.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
void onKeyTypeEvent(boolean empty) {
    this.updateEnabledButtons();

    Chat chat = this.getCurrentChat().orElse(null);
    if (chat == null)
        return;

    // workaround: clearing the text area is not a key event
    if (!empty)
        mView.getControl().handleOwnChatStateEvent(chat, ChatState.composing);
}
 
Example #28
Source File: ChatStateManager.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
void handleOwnChatStateEvent(Chat chat, ChatState state) {
    if (!mChatStateCache.containsKey(chat)) {
        if (state == ChatState.gone)
            // weare and stay at the default state
            return;
        mChatStateCache.put(chat, new MyChatState(chat));
    }

    mChatStateCache.get(chat).handleState(state);
}
 
Example #29
Source File: Client.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
public void sendChatState(JID jid, String threadID, ChatState state) {
    Message message = new Message(jid.toBareSmack(), Message.Type.chat);
    if (!threadID.isEmpty())
        message.setThread(threadID);
    message.addExtension(new ChatStateExtension(state));

    this.sendPacket(message);
}
 
Example #30
Source File: GroupChat.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setChatState(final Contact contact, ChatState chatState) {
    Member member = mMemberSet.stream()
            .filter(m -> m.getContact().equals(contact))
            .findFirst().orElse(null);

    if (member == null) {
        LOGGER.warning("can't find member in member set!?");
        return;
    }

    member.setState(chatState);
    this.changed(ViewChange.MEMBER_STATE);
}