import io.ktor.http.*
import io.ktor.routing.*
import io.ktor.websocket.*
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import org.litote.kmongo.setValue
import starshipfights.auth.getUser
+import starshipfights.data.DocumentTable
import starshipfights.data.admiralty.getAllInGameAdmirals
import starshipfights.data.auth.User
import starshipfights.data.auth.UserStatus
val user = oldUser.copy(status = UserStatus.IN_MATCHMAKING)
User.put(user)
- matchmakingEndpoint(user)
+ currentCoroutineContext().job.invokeOnCompletion {
+ DocumentTable.launch {
+ val cancelUser = User.get(user.id)!!
+ if (cancelUser.status == UserStatus.IN_MATCHMAKING)
+ User.put(
+ cancelUser.copy(
+ status = UserStatus.AVAILABLE
+ )
+ )
+ }
+ }
- launch {
+ if (matchmakingEndpoint(user))
User.set(user.id, setValue(User::status, UserStatus.READY_FOR_BATTLE))
- }
}
webSocket("/game/{token}") {
val user = oldUser.copy(status = UserStatus.IN_BATTLE)
User.put(user)
- gameEndpoint(user, token)
-
- launch {
- User.set(user.id, setValue(User::status, UserStatus.AVAILABLE))
+ currentCoroutineContext().job.invokeOnCompletion {
+ DocumentTable.launch {
+ User.set(user.id, setValue(User::status, UserStatus.AVAILABLE))
+ }
}
+
+ gameEndpoint(user, token)
}
}
val gameIdHandler = CompletableDeferred<String>()
}
-suspend fun DefaultWebSocketServerSession.matchmakingEndpoint(user: User) {
- val playerLogin = receiveObject(PlayerLogin.serializer()) { closeAndReturn { return } }
+suspend fun DefaultWebSocketServerSession.matchmakingEndpoint(user: User): Boolean {
+ val playerLogin = receiveObject(PlayerLogin.serializer()) { closeAndReturn { return false } }
val admiralId = playerLogin.admiral
- val inGameAdmiral = getInGameAdmiral(admiralId) ?: closeAndReturn("That admiral does not exist") { return }
- if (inGameAdmiral.user.id != user.id) closeAndReturn("You do not own that admiral") { return }
+ val inGameAdmiral = getInGameAdmiral(admiralId) ?: closeAndReturn("That admiral does not exist") { return false }
+ if (inGameAdmiral.user.id != user.id) closeAndReturn("You do not own that admiral") { return false }
when (val loginMode = playerLogin.login) {
is LoginMode.Host -> {
val joinResponse = receiveObject(JoinResponse.serializer()) {
closeAndReturn {
joinInvitation.responseHandler.complete(JoinResponse(false))
- return
+ return false
}
}
val joinListing = JoinListing(openGames.mapValues { (_, invitation) -> invitation.joinable })
sendObject(JoinListing.serializer(), joinListing)
- val joinSelection = receiveObject(JoinSelection.serializer()) { closeAndReturn { return } }
+ val joinSelection = receiveObject(JoinSelection.serializer()) { closeAndReturn { return false } }
val hostInvitation = openGames.getValue(joinSelection.selectedId)
val joinResponseHandler = CompletableDeferred<JoinResponse>()
}
}
}
+
+ return true
}