summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorjoffrey-bion <joffrey.bion@gmail.com>2021-02-09 17:11:19 +0100
committerjoffrey-bion <joffrey.bion@gmail.com>2021-02-09 17:22:24 +0100
commit6c3280a7ca9be4c7dcbbff92f5ac1bba50dfe12d (patch)
tree187a98d2ec869b79a49eddc15e8f816352bb62d1
parentRename find->get to imply non-null check (diff)
downloadseven-wonders-6c3280a7ca9be4c7dcbbff92f5ac1bba50dfe12d.tar.gz
seven-wonders-6c3280a7ca9be4c7dcbbff92f5ac1bba50dfe12d.tar.bz2
seven-wonders-6c3280a7ca9be4c7dcbbff92f5ac1bba50dfe12d.zip
Add disconnection listener to cleanup lobbies/games
Resolves: https://github.com/joffrey-bion/seven-wonders/issues/94
-rw-r--r--sw-server/src/main/kotlin/org/luxons/sevenwonders/server/config/StompDisconnectionListener.kt43
1 files changed, 43 insertions, 0 deletions
diff --git a/sw-server/src/main/kotlin/org/luxons/sevenwonders/server/config/StompDisconnectionListener.kt b/sw-server/src/main/kotlin/org/luxons/sevenwonders/server/config/StompDisconnectionListener.kt
new file mode 100644
index 00000000..893abe19
--- /dev/null
+++ b/sw-server/src/main/kotlin/org/luxons/sevenwonders/server/config/StompDisconnectionListener.kt
@@ -0,0 +1,43 @@
+package org.luxons.sevenwonders.server.config
+
+import org.luxons.sevenwonders.server.controllers.GameController
+import org.luxons.sevenwonders.server.controllers.LobbyController
+import org.luxons.sevenwonders.server.repositories.PlayerRepository
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.springframework.context.ApplicationListener
+import org.springframework.stereotype.Component
+import org.springframework.web.socket.messaging.SessionDisconnectEvent
+
+@Component
+internal class StompDisconnectionListener(
+ private val lobbyController: LobbyController,
+ private val playerRepository: PlayerRepository,
+ private val gameController: GameController,
+) : ApplicationListener<SessionDisconnectEvent> {
+
+ private val logger: Logger = LoggerFactory.getLogger(StompDisconnectionListener::class.java)
+
+ override fun onApplicationEvent(event: SessionDisconnectEvent) {
+ val principal = event.user
+ if (principal == null) {
+ logger.error("Received session disconnect event without a principal (sessionId = ${event.sessionId})")
+ return
+ }
+
+ val player = playerRepository.find(principal.name)
+ if (player == null) {
+ logger.error("Received session disconnect event from unknown player '${principal.name}'")
+ return
+ }
+
+ logger.info("User $player disconnected (sessionId = ${event.sessionId})")
+
+ when {
+ // TODO auto-play until the end? https://github.com/joffrey-bion/seven-wonders/issues/85
+ player.isInGame -> gameController.leave(principal)
+ player.isInLobby -> lobbyController.leave(principal)
+ else -> playerRepository.remove(principal.name)
+ }
+ }
+}
bgstack15