Skip to content

Commit

Permalink
port logout request
Browse files Browse the repository at this point in the history
  • Loading branch information
alyssaruth committed Nov 6, 2024
1 parent 6bfb8dd commit 908a13c
Show file tree
Hide file tree
Showing 14 changed files with 58 additions and 175 deletions.
10 changes: 1 addition & 9 deletions client/src/main/java/online/screen/EntropyLobby.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import http.dto.RoomSummary;
import object.RoomTable;
import online.util.HeartbeatRunnable;
import online.util.XmlBuilderClient;
import org.w3c.dom.Document;
import screen.MainScreen;
import screen.ScreenCache;
import util.*;
Expand All @@ -26,7 +24,6 @@
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static achievement.AchievementUtilKt.getAchievementsEarned;
import static util.Images.ICON_ONLINE;

public class EntropyLobby extends JFrame
Expand Down Expand Up @@ -373,12 +370,7 @@ public void exit(boolean forceClose)
if (!forceClose)
{
//Send a disconnect message.
Document disconnectRequest = XmlBuilderClient.factoryDisconnectRequest(username);
String messageString = XmlUtil.getStringFromDocument(disconnectRequest);

MessageSenderParams params = new MessageSenderParams(messageString, 0, 5);
params.setExpectResponse(false);
MessageUtil.sendMessage(params, true);
ClientGlobals.sessionApi.finishSession();
}

ScreenCache.get(MainScreen.class).maximise();
Expand Down
10 changes: 0 additions & 10 deletions client/src/main/java/online/util/XmlBuilderClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,6 @@ public static Document factoryHeartbeat(String username)
return XmlUtil.factorySimpleMessage(username, ROOT_TAG_HEARTBEAT);
}

public static Document factoryDisconnectRequest(String username)
{
Document document = XmlUtil.factoryNewDocument();
Element rootElement = document.createElement(ROOT_TAG_DISCONNECT_REQUEST);
rootElement.setAttribute("Username", username);

document.appendChild(rootElement);
return document;
}

public static Document factoryNewChatXml(String roomId, String username, String colour, String message)
{
Document document = XmlUtil.factoryNewDocument();
Expand Down
3 changes: 1 addition & 2 deletions client/src/main/java/util/MessageSender.java
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ private boolean isResponseIgnored(String xmlStr)

String name = rootElement.getTagName();

return name.equals(XmlConstants.ROOT_TAG_NEW_CHAT)
|| name.equals(XmlConstants.ROOT_TAG_DISCONNECT_REQUEST);
return name.equals(XmlConstants.ROOT_TAG_NEW_CHAT);
}
}
8 changes: 8 additions & 0 deletions client/src/main/kotlin/http/SessionApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import javax.swing.JOptionPane
import javax.swing.SwingUtilities
import kong.unirest.HttpMethod
import online.screen.EntropyLobby
import screen.MainScreen
import screen.ScreenCache
import util.ClientGlobals
import util.DialogUtilNew
Expand Down Expand Up @@ -40,6 +41,11 @@ class SessionApi(private val httpClient: HttpClient) {
)
}

fun finishSession() {
httpClient.doCall<Unit>(HttpMethod.POST, Routes.FINISH_SESSION)
ClientGlobals.httpClient.sessionId = null
}

private fun handleConnectSuccess(response: BeginSessionResponse) {
ClientGlobals.httpClient.sessionId = response.sessionId

Expand All @@ -48,6 +54,8 @@ class SessionApi(private val httpClient: HttpClient) {
lobby.setLocationRelativeTo(null)
lobby.isVisible = true
lobby.init(response.lobby)

ScreenCache.get<MainScreen>().minimise()
}

private fun handleBeginSessionFailure(response: FailureResponse<*>) =
Expand Down
2 changes: 1 addition & 1 deletion client/src/main/kotlin/util/ClientGlobals.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ object ClientGlobals {
val consoleAppender = LoggingConsoleAppender(loggingConsole)
val healthCheckApi = HealthCheckApi(httpClient)
val devApi = DevApi(httpClient)
var sessionApi = SessionApi(httpClient)
@JvmField var sessionApi = SessionApi(httpClient)
var updateManager = UpdateManager()
val webSocketReceiver = WebSocketReceiver()
@JvmField var achievementStore: AbstractSettingStore = DefaultSettingStore("achievements")
Expand Down
3 changes: 0 additions & 3 deletions core/src/main/java/util/XmlConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ public interface XmlConstants
{
//Client
public static final String ROOT_TAG_HEARTBEAT = "Heartbeat";
public static final String ROOT_TAG_DISCONNECT_REQUEST = "DisconnectRequest";
public static final String ROOT_TAG_NEW_CHAT = "NewChat";
public static final String ROOT_TAG_ROOM_JOIN_REQUEST = "RoomJoinRequest";
public static final String ROOT_TAG_CLOSE_ROOM_REQUEST = "CloseRoomRequest";
Expand Down Expand Up @@ -41,6 +40,4 @@ public interface XmlConstants
public static final String RESPONSE_TAG_ACKNOWLEDGEMENT = "Acknowledgement";
public static final String RESPONSE_TAG_STACK_TRACE = "StackTrace";
public static final String RESPONSE_TAG_SOCKET_TIME_OUT = "SocketTimeOut";

public static final String REMOVAL_REASON_FAILED_USERNAME_CHECK = "There has been an authentication error.";
}
1 change: 1 addition & 0 deletions core/src/main/kotlin/http/Routes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ object Routes {
const val DEV_COMMAND = "/dev-command"
const val BEGIN_SESSION = "/begin-session"
const val ACHIEVEMENT_COUNT = "/achievement-count"
const val FINISH_SESSION = "/finish-session"
}
45 changes: 3 additions & 42 deletions server/src/main/java/server/EntropyServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import object.Room;
import object.ServerRunnable;
import object.ServerThread;
import org.w3c.dom.Document;
import util.*;

import java.util.ArrayList;
Expand Down Expand Up @@ -43,7 +42,6 @@ private void onStart() {

Debug.append("Starting permanent threads");

startInactiveCheckRunnable();
startListenerThreads();

Debug.appendBanner("Server is ready - accepting connections");
Expand Down Expand Up @@ -111,13 +109,6 @@ private void registerDefaultRooms() {
Debug.append("Finished creating " + hmRoomByName.size() + " rooms");
}

private void startInactiveCheckRunnable() {
InactiveCheckRunnable runnable = new InactiveCheckRunnable(this);

ServerThread inactiveCheckThread = new ServerThread(runnable, "InactiveCheck");
inactiveCheckThread.start();
}

private void startListenerThreads() {
try {
ServerThread listenerThread = new ServerThread(new MessageListener(this, SERVER_PORT_NUMBER));
Expand All @@ -132,37 +123,7 @@ public void executeInWorkerPool(ServerRunnable runnable) {
ServerGlobals.workerPool.executeServerRunnable(runnable);
}

public void removeFromUsersOnline(UserConnection usc) {
//Null these out so we don't try to send any more notifications
usc.destroyNotificationSockets();

//Need to remove them from rooms too
String username = usc.getName();
if (username != null) {
ColourGenerator.freeUpColour(usc.getColour());

List<Room> rooms = getRooms();
for (int i = 0; i < rooms.size(); i++) {
Room room = rooms.get(i);
room.removeFromObservers(username);
room.removePlayer(username, false);
}

Debug.append(username + " has disconnected");
}

//Now remove the user connection.
ServerGlobals.INSTANCE.getUscStore().remove(usc.getIpAddress());
if (ServerGlobals.INSTANCE.getUscStore().getAll().size() == 0
&& username != null) {
resetLobby();
return;
}

ServerGlobals.lobbyService.lobbyChanged();
}

private void resetLobby() {
public void resetLobby() {
int countRemoved = 0;

List<Room> rooms = getRooms();
Expand All @@ -178,10 +139,10 @@ private void resetLobby() {

//Log out if we've actually removed some rooms
if (countRemoved > 0) {
Debug.append("Removed " + countRemoved + " excess rooms");
logger.info("roomsRemoved", "Removed " + countRemoved + " excess rooms");
}

Debug.append("Cleared lobby messages");
logger.info("clearedMessages", "Cleared lobby messages");
lobbyMessages.clear();
}

Expand Down
86 changes: 0 additions & 86 deletions server/src/main/java/server/InactiveCheckRunnable.java

This file was deleted.

20 changes: 1 addition & 19 deletions server/src/main/java/server/MessageHandlerRunnable.java
Original file line number Diff line number Diff line change
Expand Up @@ -209,28 +209,10 @@ private Document getResponseForMessage() throws Throwable
String id = root.getAttribute("RoomId");
String username = root.getAttribute("Username");
String name = root.getNodeName();

String usernameForThisConnection = usc.getName();
if (usernameForThisConnection == null
|| !usernameForThisConnection.equals(username))
{
Debug.stackTrace("Failed username check for IP " + ipAddress + ": client passed up " + username
+ " but connected as " + usernameForThisConnection);
Debug.appendWithoutDate("Message passed up: " + messageStr);

server.removeFromUsersOnline(usc);

return XmlBuilderServer.getKickOffResponse(usernameForThisConnection, REMOVAL_REASON_FAILED_USERNAME_CHECK);
}

usc.setLastActiveNow();

if (name.equals(ROOT_TAG_DISCONNECT_REQUEST))
{
server.removeFromUsersOnline(usc);
return null;
}
else if (name.equals(ROOT_TAG_NEW_CHAT))
if (name.equals(ROOT_TAG_NEW_CHAT))
{
String newMessage = root.getAttribute("MessageText");
String colour = root.getAttribute("Colour");
Expand Down
11 changes: 8 additions & 3 deletions server/src/main/kotlin/routes/session/SessionController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,13 @@ import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import routes.requiresSession
import util.ServerGlobals
import util.ServerGlobals.sessionService

class SessionController {
private val sessionService = SessionService(ServerGlobals.sessionStore, ServerGlobals.uscStore)

fun installRoutes(application: Application) {
application.routing {
post(Routes.BEGIN_SESSION) { beginSession(call) }
post(Routes.FINISH_SESSION) { finishSession(call) }
post(Routes.ACHIEVEMENT_COUNT) { updateAchievementCount(call) }
}
}
Expand All @@ -29,6 +28,12 @@ class SessionController {
call.respond(response)
}

private suspend fun finishSession(call: ApplicationCall) =
requiresSession(call) { session ->
sessionService.finishSession(session)
call.respond(HttpStatusCode.NoContent)
}

private suspend fun updateAchievementCount(call: ApplicationCall) =
requiresSession(call) { session ->
val request = call.receive<UpdateAchievementCountRequest>()
Expand Down
28 changes: 28 additions & 0 deletions server/src/main/kotlin/routes/session/SessionService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ import http.dto.BeginSessionRequest
import http.dto.BeginSessionResponse
import io.ktor.http.*
import java.util.*
import `object`.Room
import routes.ClientException
import store.Store
import util.ColourGenerator
import util.OnlineConstants
import util.ServerGlobals
import utils.Achievement
import utils.CoreGlobals.logger

class SessionService(
private val sessionStore: Store<UUID, Session>,
Expand Down Expand Up @@ -72,6 +75,31 @@ class SessionService(
else nameToCheck
}

fun finishSession(session: Session) {
val usc = uscStore.get(session.ip)
usc.destroyNotificationSockets()

// Need to remove them from rooms too
ColourGenerator.freeUpColour(usc.colour)

val rooms: List<Room> = ServerGlobals.server.getRooms()
rooms.forEach { room ->
room.removeFromObservers(usc.name)
room.removePlayer(usc.name, false)
}

uscStore.remove(session.ip)
sessionStore.remove(session.id)

logger.info("finishSession", "Session ended for ${usc.name}")

if (sessionStore.count() == 0) {
ServerGlobals.server.resetLobby()
}

ServerGlobals.lobbyService.lobbyChanged()
}

fun updateAchievementCount(session: Session, achievementCount: Int) {
validateAchievementCount(achievementCount)

Expand Down
Loading

0 comments on commit 908a13c

Please sign in to comment.