--- /dev/null
+package net.pterodactylus.irc.connection;
+
+import java.util.List;
+
+import net.pterodactylus.irc.Connection;
+import net.pterodactylus.irc.Reply;
+import net.pterodactylus.irc.Source;
+import net.pterodactylus.irc.event.ChannelMessageReceived;
+import net.pterodactylus.irc.event.ChannelNoticeReceived;
+import net.pterodactylus.irc.event.PrivateMessageReceived;
+import net.pterodactylus.irc.event.PrivateNoticeReceived;
+
+import com.google.common.eventbus.EventBus;
+
+/**
+ * Handles {@code PRIVMSG}s and {@code NOTICE}s that are not CTCP messages.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+public class MessageHandler implements Handler {
+
+ private final EventBus eventBus;
+ private final Connection connection;
+ private final PrefixHandler prefixHandler;
+
+ public MessageHandler(EventBus eventBus, Connection connection,
+ PrefixHandler prefixHandler) {
+ this.eventBus = eventBus;
+ this.connection = connection;
+ this.prefixHandler = prefixHandler;
+ }
+
+ @Override
+ public boolean willHandle(Reply reply) {
+ return (commandIs(reply, "PRIVMSG") || commandIs(reply, "NOTICE"))
+ && !messageIsCtcp(reply.parameters().get(1));
+ }
+
+ private boolean commandIs(Reply reply, String command) {
+ return reply.command().equalsIgnoreCase(command);
+ }
+
+ private boolean messageIsCtcp(String message) {
+ return message.startsWith("\u0001") && message.endsWith("\u0001");
+ }
+
+ @Override
+ public void handleReply(Reply reply) {
+ boolean isNotice = commandIs(reply, "NOTICE");
+ List<String> parameters = reply.parameters();
+ String recipient = parameters.get(0);
+ String message = parameters.get(1);
+ Source source = reply.source().get();
+ if (!prefixHandler.isChannel(recipient)) {
+ if (isNotice) {
+ firePrivateNoticeEvent(source, message);
+ } else {
+ firePrivateMessageEvent(source, message);
+ }
+ } else {
+ if (isNotice) {
+ fireChannelNoticeEvent(source, recipient, message);
+ } else {
+ fireChannelMessageEvent(source, recipient, message);
+ }
+ }
+ }
+
+ private void firePrivateNoticeEvent(Source source, String message) {
+ eventBus.post(new PrivateNoticeReceived(connection, source, message));
+ }
+
+ private void firePrivateMessageEvent(Source source, String message) {
+ eventBus.post(new PrivateMessageReceived(connection, source, message));
+ }
+
+ private void fireChannelNoticeEvent(Source source, String channel, String message) {
+ eventBus.post(new ChannelNoticeReceived(connection, source, channel, message));
+ }
+
+ private void fireChannelMessageEvent(Source source, String channel, String message) {
+ eventBus.post(new ChannelMessageReceived(connection, source, channel, message));
+ }
+
+}