package de.mcripper.chatlib.xmpp;
import java.util.Collection;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import de.mcripper.chatlib.Chat;
import de.mcripper.chatlib.ChatLibRuntimeException;
import de.mcripper.chatlib.Message;
import de.mcripper.chatlib.MessageHandler;
import de.mcripper.chatlib.User;
import de.mcripper.chatlib.UserManager;
public class XmppChat implements Chat {
private final Logger logger = LoggerFactory.getLogger(XmppChat.class);
private final org.jivesoftware.smack.Chat chat;
private final XmppConnection connection;
@Inject
private UserManager userManager;
public XmppChat(final org.jivesoftware.smack.Chat chat,
final XmppConnection connection) {
super();
this.chat = chat;
this.connection = connection;
this.chat.addMessageListener(this.messageListener);
}
private final Collection<MessageHandler> messageHandlers = Sets
.newHashSet();
private final MessageListener messageListener = new MessageListener() {
@Override
public void processMessage(final org.jivesoftware.smack.Chat chat,
final org.jivesoftware.smack.packet.Message message) {
XmppChat.this.logger.debug("Message received from {}: {}",
message.getFrom(), message.getBody());
XmppChat.this.notifyMessageHandler(message);
}
};
@Override
public Collection<User> getParticipants() {
return this.userManager.getUsers(this.chat.getParticipant());
}
protected void notifyMessageHandler(
final org.jivesoftware.smack.packet.Message message) {
final User sender = this.userManager
.getUser(this.chat.getParticipant());
final Message newMessage = new Message(message.getBody(), this, sender);
for (final MessageHandler handler : this.messageHandlers) {
handler.receive(this, newMessage);
}
}
@Override
public void sendMessage(final Message message) {
this.logger.debug("Sending message {}", message);
final org.jivesoftware.smack.packet.Message newMessage = new org.jivesoftware.smack.packet.Message();
newMessage.setBody(message.getContent());
try {
this.chat.sendMessage(newMessage);
} catch (final XMPPException e) {
ChatLibRuntimeException.pack(e);
}
}
@Override
public void addMessageHandler(final MessageHandler messageHandler) {
this.messageHandlers.add(messageHandler);
}
@Override
public void removeMessageHandler(final MessageHandler messageHandler) {
this.messageHandlers.remove(messageHandler);
}
@Override
public void sendMessage(final String string) {
final Message message = new Message(string, this,
this.connection.getUser());
this.sendMessage(message);
}
public XmppConnection getConnection() {
return this.connection;
}
}