feat(Event): 2.6 - Traitement de l’évènement "AUTH"

This commit is contained in:
bouclyma 2024-12-28 02:42:16 +01:00
parent 9120d5c4ca
commit d2ad689b48
2 changed files with 70 additions and 0 deletions

View file

@ -1,5 +1,10 @@
package rtgre.server;
import org.json.JSONException;
import org.json.JSONObject;
import rtgre.modeles.ContactMap;
import rtgre.modeles.Event;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
@ -17,6 +22,7 @@ public class ChatServer {
private static final Logger LOGGER = Logger.getLogger(ChatServer.class.getCanonicalName());
private Vector<ChatClientHandler> clientList;
private ContactMap contactMap;
static {
try {
@ -43,6 +49,8 @@ public class ChatServer {
passiveSock = new ServerSocket(port);
LOGGER.info("Serveur en écoute " + passiveSock);
clientList = new Vector<>();
contactMap = new ContactMap();
contactMap.loadDefaultContacts();
}
public void close() throws IOException {
@ -101,6 +109,10 @@ public class ChatServer {
//client.echoLoop();
}
public ContactMap getContactMap() {
return contactMap;
}
private class ChatClientHandler {
public static final String END_MESSAGE = "fin";
/**
@ -160,6 +172,52 @@ public class ChatServer {
close();
}
public void eventReceiveLoop() {
try {
String message = null;
while (!END_MESSAGE.equals(message)) {
message = in.readLine();
if (message == null) {
break;
}
LOGGER.info("[%s] Réception de : %s".formatted(ipPort, message));
LOGGER.info("[%s] Envoi de : %s".formatted(ipPort, message));
try {
if (handleEvent(message)) {
break;
}
} catch (Exception e) {
break;
}
}
} catch (IOException e) {
LOGGER.severe("[%s] %s".formatted(ipPort, e));
}
close();
}
private boolean handleEvent(String message) throws JSONException, IllegalStateException {
Event event = Event.fromJson(message);
switch (event.getType()) {
case Event.AUTH:
doLogin(event.getContent());
return false;
default:
return true;
}
}
private void doLogin(JSONObject content) {
String login = content.getString("login");
if (login.equals("")) {
throw new JSONException("Aucun login fourni");
} else if (!contactMap.containsKey(login)) {
throw new IllegalStateException("Login non-authorisé");
} else {
contactMap.getContact(login).setConnected(true);
}
}
public void send(String message) throws IOException {
LOGGER.finest("send: %s".formatted(message));
out.println(message);