🚧 Parse token from DCC SEND
[xudocci.git] / irc / connection / ConnectionEstablishHandler.java
1 package net.pterodactylus.irc.connection;
2
3 import static java.util.Arrays.asList;
4
5 import net.pterodactylus.irc.Connection;
6 import net.pterodactylus.irc.Reply;
7 import net.pterodactylus.irc.event.ConnectionEstablished;
8
9 import com.google.common.eventbus.EventBus;
10
11 /**
12  * Handles the necessary commands that establish a connection.
13  *
14  * @author <a href="mailto:bombe@pterodactylus.net">David â€˜Bombe’ Roden</a>
15  */
16 public class ConnectionEstablishHandler implements Handler {
17
18         private static final int FIRST_COMMAND_RECEIVED = 0x01;
19         private static final int SECOND_COMMAND_RECEIVED = 0x02;
20         private static final int THIRD_COMMAND_RECEIVED = 0x04;
21         private static final int FOURTH_COMMAND_RECEIVED = 0x08;
22         private static final int ALL_COMMANDS_RECEIVED = 0x0f;
23
24         private final EventBus eventBus;
25         private final Connection connection;
26         private int connectionStatus;
27         private int oldConnectionStatus;
28
29         public ConnectionEstablishHandler(EventBus eventBus,
30                         Connection connection) {
31                 this.eventBus = eventBus;
32                 this.connection = connection;
33         }
34
35         @Override
36         public boolean willHandle(Reply reply) {
37                 return !isFinalConnectionStatusReached() &&
38                                 asList("001", "002", "003", "004").contains(reply.command());
39         }
40
41         @Override
42         public void handleReply(Reply reply) {
43                 String command = reply.command();
44                 /* replies 001-004 don’t hold information but they
45                  * have to be sent on a successful connection. */
46                 if (command.equals("001")) {
47                         connectionStatus |= FIRST_COMMAND_RECEIVED;
48                 } else if (command.equals("002")) {
49                         connectionStatus |= SECOND_COMMAND_RECEIVED;
50                 } else if (command.equals("003")) {
51                         connectionStatus |= THIRD_COMMAND_RECEIVED;
52                 } else if (command.equals("004")) {
53                         connectionStatus |= FOURTH_COMMAND_RECEIVED;
54                 }
55
56                 if (hasConnectionStatusChanged()
57                                 && isFinalConnectionStatusReached()) {
58                         eventBus.post(new ConnectionEstablished(connection));
59                 }
60                 oldConnectionStatus = connectionStatus;
61         }
62
63         private boolean hasConnectionStatusChanged() {
64                 return connectionStatus != oldConnectionStatus;
65         }
66
67         private boolean isFinalConnectionStatusReached() {
68                 return connectionStatus == ALL_COMMANDS_RECEIVED;
69         }
70
71 }