Compare commits

...

47 Commits

Author SHA1 Message Date
TeamCity
410b4829f4 ci: bump version to v4.29.0 2026-01-14 09:14:51 +00:00
4b17af2c2f feat: CORE-4 Rework the delay handler (#113)
Reviewed-on: #113
Co-authored-by: Janis <janis.e.20@gmx.de>
Co-committed-by: Janis <janis.e.20@gmx.de>
2026-01-14 10:12:09 +01:00
TeamCity
a163d9f8fe ci: bump version to v4.28.0 2026-01-13 13:37:03 +00:00
dc3da9a75c feat(ui): Tie selection (#111)
Added ability to pick a tie card in the backend

Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #111
2026-01-13 14:33:25 +01:00
TeamCity
4a4e9c48fc ci: bump version to v4.27.0 2026-01-07 21:06:02 +00:00
859dfce521 feat: Implement PlayDogCard functionality in user session and update Vue component 2026-01-07 22:02:43 +01:00
61ae9b5a5e feat: Implement PlayDogCard functionality in user session and update Vue component 2026-01-07 22:02:21 +01:00
TeamCity
98fa5f63d6 ci: bump version to v4.26.0 2026-01-07 20:50:18 +00:00
0e555cdfeb fix: Update knockoutwhistfrontend hash for consistency 2026-01-07 21:47:30 +01:00
b4bf2ceb4d feat: Enhance user state management with polling and WebSocket connection handling 2026-01-07 21:43:17 +01:00
TeamCity
1542906edf ci: bump version to v4.25.0 2026-01-07 15:59:57 +00:00
cf1854976a feat: Update joinGame endpoint to accept gameId as a path parameter 2026-01-07 16:56:35 +01:00
TeamCity
723a4be33f ci: bump version to v4.24.0 2026-01-07 15:27:29 +00:00
2f89951c25 feat: Update Gateway to use ArrayList for game IDs and bound users 2026-01-07 16:24:51 +01:00
TeamCity
f330c5f3d8 ci: bump version to v4.23.0 2026-01-07 14:26:56 +00:00
4a5af36ae0 feat: Add Health and Login endpoints with updated Redis configuration 2026-01-07 15:24:21 +01:00
TeamCity
edcab594a7 ci: bump version to v4.22.0 2026-01-07 14:07:31 +00:00
26157076d6 feat: Add logging to Gateway for pod synchronization and startup events 2026-01-07 15:04:52 +01:00
TeamCity
103b341488 ci: bump version to v4.21.0 2026-01-07 13:57:09 +00:00
6ef7401443 feat: Add logging to Gateway for pod synchronization and startup events 2026-01-07 14:54:26 +01:00
TeamCity
bbbbf33c41 ci: bump version to v4.20.0 2026-01-07 13:37:05 +00:00
dbad818fda feat: Add caching headers for env.js in Nginx configuration 2026-01-07 14:33:35 +01:00
TeamCity
5f8afbf236 ci: bump version to v4.19.0 2026-01-07 13:02:56 +00:00
3b7a1e3c64 feat: Update configuration files for CORS settings and add production environment 2026-01-07 14:00:12 +01:00
TeamCity
5af5785fa0 ci: bump version to v4.18.1 2026-01-07 12:19:47 +00:00
TeamCity
9510147806 ci: bump version to v4.18.0 2026-01-07 11:07:11 +00:00
e17f59e614 feat: Simplify Dockerfile by removing multi-stage build and adjusting file copy paths 2026-01-07 12:04:44 +01:00
8126b46a0a feat: Update build.sbt and Dockerfile for improved GitHub credentials handling 2026-01-07 11:52:00 +01:00
25dd9264b5 feat: Update build.sbt and Dockerfile for improved GitHub credentials handling 2026-01-07 11:47:31 +01:00
5f9ef2beb0 feat: Enhance Dockerfile with secret management for GitHub credentials 2026-01-07 11:40:10 +01:00
ccf993bff2 feat: Update Dockerfile for multi-platform support and add nginx configuration 2026-01-07 11:24:00 +01:00
1d05bd43b4 feat: Add GatewayModule for enhanced module configuration 2026-01-07 10:17:13 +01:00
3e067346ff feat: Update Dockerfile for multi-platform support and add nginx configuration 2026-01-06 16:49:27 +01:00
b2527ed041 feat: Update Dockerfile for multi-platform support and add nginx configuration 2026-01-06 16:38:33 +01:00
TeamCity
06d150b8c5 ci: bump version to v4.17.0 2026-01-06 11:18:43 +00:00
0cbac61b4a fix: Fixed dockerfile 2026-01-06 12:13:32 +01:00
088dda8d52 feat: Enhance win effects and animations in OfflineView component 2026-01-06 12:07:08 +01:00
TeamCity
c3d10f31ac ci: bump version to v4.16.0 2025-12-18 08:51:00 +00:00
e4384ee894 feat(ui): FRO-36 PWA (#110)
Added localhost:3000 to CORS for PWA to work

Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #110
Reviewed-by: Janis <janis-e@gmx.de>
Co-authored-by: lq64 <lq@blackhole.local>
Co-committed-by: lq64 <lq@blackhole.local>
2025-12-18 09:47:25 +01:00
TeamCity
d667a2f68c ci: bump version to v4.15.0 2025-12-14 14:15:11 +00:00
35f608513d feat: Update routing and websocket configuration for game state management (#109)
Reviewed-on: #109
2025-12-14 15:10:43 +01:00
TeamCity
13038b0cb9 ci: bump version to v4.14.0 2025-12-11 06:13:24 +00:00
b17aae5795 feat: FRO-31 Small backend changes (#108)
Force pushing Janis changes

Co-authored-by: Janis <janis.e.20@gmx.de>
Co-authored-by: Janis <janis-e@gmx.de>
Reviewed-on: #108
Co-authored-by: lq64 <lq@blackhole.local>
Co-committed-by: lq64 <lq@blackhole.local>
2025-12-11 07:10:24 +01:00
TeamCity
421f769cb6 ci: bump version to v4.13.0 2025-12-10 14:19:44 +00:00
bd7a055a09 feat(api): FRO-14 Create Game (#107)
Added functionality to create Game so that it creates a game in the Backend

Co-authored-by: LQ63 <lkhermann@web.de>
Reviewed-on: #107
Reviewed-by: Janis <janis-e@gmx.de>
Co-authored-by: lq64 <lq@blackhole.local>
Co-committed-by: lq64 <lq@blackhole.local>
2025-12-10 15:16:53 +01:00
TeamCity
e2a2b56174 ci: bump version to v4.12.0 2025-12-10 13:15:50 +00:00
2a29ca8cdd feat: FRO-20 Create scoreboard component (#106)
Reviewed-on: #106
Co-authored-by: Janis <janis.e.20@gmx.de>
Co-committed-by: Janis <janis.e.20@gmx.de>
2025-12-10 14:12:48 +01:00
31 changed files with 367 additions and 83 deletions

View File

@@ -234,3 +234,106 @@
### Features ### Features
* FRO-2 Implement Login Component ([#105](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/105)) ([e8b31b1](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/e8b31b174819b5f033034501856c4b1189c4c4ee)) * FRO-2 Implement Login Component ([#105](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/105)) ([e8b31b1](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/e8b31b174819b5f033034501856c4b1189c4c4ee))
## (2025-12-10)
### Features
* FRO-20 Create scoreboard component ([#106](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/106)) ([2a29ca8](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/2a29ca8cdd3ef55f6f66f00b5e7727e1b1af1458))
## (2025-12-10)
### Features
* **api:** FRO-14 Create Game ([#107](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/107)) ([bd7a055](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/bd7a055a0944a1c5219f21bb080bf658229f49e9))
## (2025-12-11)
### Features
* FRO-31 Small backend changes ([#108](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/108)) ([b17aae5](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/b17aae5795b35ce3805db87c9bf741a5a96cd5ac))
## (2025-12-14)
### Features
* Update routing and websocket configuration for game state management ([#109](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/109)) ([35f6085](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/35f608513dd80eece46d49b40ecf31c8e915d307))
## (2025-12-18)
### Features
* **ui:** FRO-36 PWA ([#110](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/110)) ([e4384ee](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/e4384ee8945ac462fe1f3580215117e0a438f71a))
## (2026-01-06)
### Features
* Enhance win effects and animations in OfflineView component ([088dda8](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/088dda8d528edb9f3fd420e7e69eb44144d39eff))
## (2026-01-07)
### Features
* Add GatewayModule for enhanced module configuration ([1d05bd4](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/1d05bd43b482564636345322a2cecf58f7d229d0))
* Enhance Dockerfile with secret management for GitHub credentials ([5f9ef2b](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/5f9ef2beb0a6e7d5e8caf436f545bbd78a6b242e))
* Simplify Dockerfile by removing multi-stage build and adjusting file copy paths ([e17f59e](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/e17f59e614a0060b70514c2337ac6fd84688546e))
* Update build.sbt and Dockerfile for improved GitHub credentials handling ([8126b46](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/8126b46a0a1649d2b20b31975603f7610fafd18b))
* Update build.sbt and Dockerfile for improved GitHub credentials handling ([25dd926](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/25dd9264b57ffafc5b01587ff5dda2e2188b5fbd))
* Update Dockerfile for multi-platform support and add nginx configuration ([ccf993b](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/ccf993bff25b4551a70c1f0263695f828df15a02))
* Update Dockerfile for multi-platform support and add nginx configuration ([3e06734](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/3e067346ffe3bdc62dc936ea8e79ae9293d86351))
* Update Dockerfile for multi-platform support and add nginx configuration ([b2527ed](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/b2527ed041568d20f880515b406fe0b0e10c12c1))
## (2026-01-07)
## (2026-01-07)
### Features
* Update configuration files for CORS settings and add production environment ([3b7a1e3](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/3b7a1e3c646d870134d8d06b4962498b0e282cbd))
## (2026-01-07)
### Features
* Add caching headers for env.js in Nginx configuration ([dbad818](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/dbad818fdaeb237a05f583e5402773a4339e7aa1))
## (2026-01-07)
### Features
* Add logging to Gateway for pod synchronization and startup events ([6ef7401](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/6ef74014430673e725245bf37e44c5b90b81abb3))
## (2026-01-07)
### Features
* Add logging to Gateway for pod synchronization and startup events ([2615707](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/26157076d686a5dd3f8157ec2b2d1ae9d9e9eedf))
## (2026-01-07)
### Features
* Add Health and Login endpoints with updated Redis configuration ([4a5af36](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/4a5af36ae0dcb540e02b7a1cd042e54cc6342c78))
## (2026-01-07)
### Features
* Update Gateway to use ArrayList for game IDs and bound users ([2f89951](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/2f89951c25484d6bc412536a83019ee6d0b7f780))
## (2026-01-07)
### Features
* Update joinGame endpoint to accept gameId as a path parameter ([cf18549](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/cf1854976a51eb4931d50cf93640498ed18686fc))
## (2026-01-07)
### Features
* Enhance user state management with polling and WebSocket connection handling ([b4bf2ce](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/b4bf2ceb4dc76ac388124b9705a1aa9e577582af))
### Bug Fixes
* Update knockoutwhistfrontend hash for consistency ([0e555cd](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/0e555cdfeb114464c9438bfd5dc397201a073867))
## (2026-01-07)
### Features
* Implement PlayDogCard functionality in user session and update Vue component ([859dfce](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/859dfce521b193b9208d0c70fca88016f8fe08f4))
* Implement PlayDogCard functionality in user session and update Vue component ([61ae9b5](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/61ae9b5a5e7cd9fd82b77e9159814b0066874c2d))
## (2026-01-13)
### Features
* **ui:** Tie selection ([#111](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/111)) ([dc3da9a](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/dc3da9a75c75597ce81ce4d023af5390197012c9))
## (2026-01-14)
### Features
* CORE-4 Rework the delay handler ([#113](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/issues/113)) ([4b17af2](https://git.janis-eccarius.de/KnockOutWhist/KnockOutWhist-Web/commit/4b17af2c2f50a9d67cf1cf49cafdaac8f807d4b6))

View File

@@ -1,26 +1,4 @@
# === Stage 1: Build the Play application === FROM --platform=$TARGETPLATFORM eclipse-temurin:22-jre-alpine
FROM sbtscala/scala-sbt:eclipse-temurin-alpine-22_36_1.10.3_3.5.1 AS builder
WORKDIR /app
# Install Node.js and Less CSS preprocessor
USER root
RUN apk add --no-cache nodejs npm && \
npm install -g less
# Cache dependencies first
COPY project ./project
COPY build.sbt ./
RUN sbt -Dscoverage.skip=true update
# Copy the rest of the code
COPY . .
# Build the app and stage it
RUN sbt -Dscoverage.skip=true clean stage
# === Stage 2: Runtime image ===
FROM eclipse-temurin:21-jre-alpine
# Install Argon2 CLI and libraries # Install Argon2 CLI and libraries
RUN apk add --no-cache bash argon2 argon2-libs RUN apk add --no-cache bash argon2 argon2-libs
@@ -28,7 +6,7 @@ RUN apk add --no-cache bash argon2 argon2-libs
WORKDIR /opt/playapp WORKDIR /opt/playapp
# Copy staged Play build # Copy staged Play build
COPY --from=builder /app/knockoutwhistweb/target/universal/stage /opt/playapp COPY ./knockoutwhistweb/target/universal/stage /opt/playapp
# Expose the default Play port # Expose the default Play port
EXPOSE 9000 EXPOSE 9000

View File

@@ -1,6 +1,6 @@
meta { meta {
name: Game name: Game
seq: 3 seq: 2
} }
auth { auth {

View File

@@ -0,0 +1,16 @@
meta {
name: Health
type: http
seq: 3
}
get {
url: {{host}}/health/simple
body: none
auth: inherit
}
settings {
encodeUrl: true
timeout: 0
}

View File

@@ -0,0 +1,15 @@
meta {
name: Request Status
type: http
seq: 1
}
get {
url: {{host}}/status
body: none
auth: inherit
}
settings {
encodeUrl: true
}

View File

@@ -0,0 +1,8 @@
meta {
name: Login
seq: 3
}
auth {
mode: inherit
}

View File

@@ -0,0 +1,3 @@
vars {
host: https://knockout.janis-eccarius.de/api
}

View File

@@ -0,0 +1,3 @@
vars {
host: https://st.knockout.janis-eccarius.de/api
}

View File

@@ -1,5 +1,12 @@
ThisBuild / scalaVersion := "3.5.1" ThisBuild / scalaVersion := "3.5.1"
credentials += Credentials(
"GitHub Package Registry",
"maven.pkg.github.com",
sys.env.getOrElse("GITHUB_USER", sys.error("GITHUB_USER not set")),
sys.env.getOrElse("GITHUB_TOKEN", sys.error("GITHUB_TOKEN not set"))
)
lazy val commonSettings = Seq( lazy val commonSettings = Seq(
libraryDependencies += "org.scalactic" %% "scalactic" % "3.2.19", libraryDependencies += "org.scalactic" %% "scalactic" % "3.2.19",
libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.19" % "test", libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.19" % "test",
@@ -35,12 +42,16 @@ lazy val knockoutwhistweb = project.in(file("knockoutwhistweb"))
.enablePlugins(PlayScala) .enablePlugins(PlayScala)
.dependsOn(knockoutwhist % "compile->compile;test->test") .dependsOn(knockoutwhist % "compile->compile;test->test")
.settings( .settings(
resolvers += "GitHub Packages" at "https://maven.pkg.github.com/16Janis12/KnockOutWhist-Web",
commonSettings, commonSettings,
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "7.0.2" % Test, libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "7.0.2" % Test,
libraryDependencies += "de.mkammerer" % "argon2-jvm" % "2.12", libraryDependencies += "de.mkammerer" % "argon2-jvm" % "2.12",
libraryDependencies += "com.auth0" % "java-jwt" % "4.5.0", libraryDependencies += "com.auth0" % "java-jwt" % "4.5.0",
libraryDependencies += "com.github.ben-manes.caffeine" % "caffeine" % "3.2.3", libraryDependencies += "com.github.ben-manes.caffeine" % "caffeine" % "3.2.3",
libraryDependencies += "tools.jackson.module" %% "jackson-module-scala" % "3.0.2", libraryDependencies += "tools.jackson.module" %% "jackson-module-scala" % "3.0.2",
libraryDependencies += "de.janis" % "knockoutwhist-data" % "1.0-SNAPSHOT",
JsEngineKeys.engineType := JsEngineKeys.EngineType.Node JsEngineKeys.engineType := JsEngineKeys.EngineType.Node
) )

View File

@@ -0,0 +1,30 @@
package controllers
import auth.{AuthAction, AuthenticatedRequest}
import dto.subDTO.UserDTO
import logic.user.{SessionManager, UserManager}
import model.users.User
import play.api.*
import play.api.libs.json.Json
import play.api.mvc.*
import play.api.mvc.Cookie.SameSite.{Lax, None, Strict}
import javax.inject.*
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
@Singleton
class HealthController @Inject()(
val controllerComponents: ControllerComponents,
) extends BaseController {
def simple(): Action[AnyContent] = {
Action { implicit request =>
Ok("OK")
}
}
}

View File

@@ -44,8 +44,7 @@ class MainMenuController @Inject()(
) )
Ok(Json.obj( Ok(Json.obj(
"status" -> "success", "status" -> "success",
"redirectUrl" -> routes.IngameController.game(gameLobby.id).url, "gameId" -> gameLobby.id,
"content" -> IngameController.returnInnerHTML(gameLobby, gameLobby.logic.getCurrentState, request.user).toString
)) ))
} else { } else {
BadRequest(Json.obj( BadRequest(Json.obj(
@@ -56,13 +55,8 @@ class MainMenuController @Inject()(
} }
def joinGame(): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] => def joinGame(gameId: String): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>
val jsonBody = request.body.asJson val game = PodManager.getGame(gameId)
val gameId: Option[String] = jsonBody.flatMap { jsValue =>
(jsValue \ "gameId").asOpt[String]
}
if (gameId.isDefined) {
val game = PodManager.getGame(gameId.get)
game match { game match {
case Some(g) => case Some(g) =>
g.addUser(request.user) g.addUser(request.user)
@@ -77,12 +71,6 @@ class MainMenuController @Inject()(
"errorMessage" -> "No Game found" "errorMessage" -> "No Game found"
)) ))
} }
} else {
BadRequest(Json.obj(
"status" -> "failure",
"errorMessage" -> "Invalid form submission"
))
}
} }
def rules(): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] => def rules(): Action[AnyContent] = authAction { implicit request: AuthenticatedRequest[AnyContent] =>

View File

@@ -34,7 +34,8 @@ class StatusController @Inject()(
Json.obj( Json.obj(
"status" -> "authenticated", "status" -> "authenticated",
"username" -> user.name, "username" -> user.name,
"inGame" -> "false" "userId" -> user.id,
"inGame" -> false
) )
) )
} else { } else {
@@ -43,7 +44,8 @@ class StatusController @Inject()(
Json.obj( Json.obj(
"status" -> "authenticated", "status" -> "authenticated",
"username" -> user.name, "username" -> user.name,
"inGame" -> "true", "userId" -> user.id,
"inGame" -> true,
"gameId" -> game.id "gameId" -> game.id
) )
) )
@@ -80,7 +82,7 @@ class StatusController @Inject()(
}} }}
private def getUserFromSession(request: RequestHeader): Option[User] = { private def getUserFromSession(request: RequestHeader): Option[User] = {
val session = request.cookies.get("sessionId") val session = request.cookies.get("accessToken")
if (session.isDefined) if (session.isDefined)
return sessionManager.getUserBySession(session.get.value) return sessionManager.getUserBySession(session.get.value)
None None

View File

@@ -21,7 +21,7 @@ class WebsocketController @Inject()(
)(implicit system: ActorSystem, mat: Materializer) extends AbstractController(cc) { )(implicit system: ActorSystem, mat: Materializer) extends AbstractController(cc) {
def socket(): WebSocket = WebSocket.accept[String, String] { request => def socket(): WebSocket = WebSocket.accept[String, String] { request =>
val session = request.cookies.get("sessionId") val session = request.cookies.get("accessToken")
if (session.isEmpty) throw new Exception("No session cookie found") if (session.isEmpty) throw new Exception("No session cookie found")
val userOpt = sessionManger.getUserBySession(session.get.value) val userOpt = sessionManger.getUserBySession(session.get.value)
if (userOpt.isEmpty) throw new Exception("Invalid session") if (userOpt.isEmpty) throw new Exception("Invalid session")

View File

@@ -28,7 +28,7 @@ object GameInfoDTO {
hand = selfPlayer.flatMap(_.currentHand()).map(HandDTO(_)), hand = selfPlayer.flatMap(_.currentHand()).map(HandDTO(_)),
playerQueue = PlayerQueueDTO(lobby.logic), playerQueue = PlayerQueueDTO(lobby.logic),
currentTrick = lobby.logic.getCurrentTrick.map(TrickDTO(_)), currentTrick = lobby.logic.getCurrentTrick.map(TrickDTO(_)),
currentRound = lobby.logic.getCurrentRound.map(RoundDTO(_)) currentRound = lobby.logic.getCurrentRound.map(r => RoundDTO(r, lobby.logic.getCurrentMatch))
) )
} }

View File

@@ -2,13 +2,13 @@ package dto.subDTO
import de.knockoutwhist.cards.Hand import de.knockoutwhist.cards.Hand
case class HandDTO(card: List[CardDTO]) case class HandDTO(cards: List[CardDTO])
object HandDTO { object HandDTO {
def apply(hand: Hand): HandDTO = { def apply(hand: Hand): HandDTO = {
HandDTO( HandDTO(
card = hand.cards.zipWithIndex.map { case (card, idx) => CardDTO(card, idx) } cards = hand.cards.zipWithIndex.map { case (card, idx) => CardDTO(card, idx) }
) )
} }

View File

@@ -2,14 +2,16 @@ package dto.subDTO
import de.knockoutwhist.cards.Card import de.knockoutwhist.cards.Card
import de.knockoutwhist.cards.CardValue.Ace import de.knockoutwhist.cards.CardValue.Ace
import de.knockoutwhist.rounds.{Match, Round}
case class RoundDTO(trumpSuit: CardDTO, firstRound: Boolean, trickList: List[TrickDTO]) case class RoundDTO(trumpSuit: CardDTO, playersIn: Seq[PlayerDTO], firstRound: Boolean, trickList: List[TrickDTO])
object RoundDTO { object RoundDTO {
def apply(round: de.knockoutwhist.rounds.Round): RoundDTO = { def apply(round: Round, matchImpl: Option[Match]): RoundDTO = {
RoundDTO( RoundDTO(
trumpSuit = CardDTO(Card(Ace, round.trumpSuit)), trumpSuit = CardDTO(Card(Ace, round.trumpSuit)),
playersIn = matchImpl.map(_.playersIn.map(PlayerDTO(_))).getOrElse(Seq.empty),
firstRound = round.firstRound, firstRound = round.firstRound,
trickList = round.tricklist.map(trick => TrickDTO(trick)) trickList = round.tricklist.map(trick => TrickDTO(trick))
) )

View File

@@ -8,7 +8,7 @@ object TrickDTO {
def apply(trick: Trick): TrickDTO = { def apply(trick: Trick): TrickDTO = {
TrickDTO( TrickDTO(
cards = trick.cards.map { case (card, player) => player.id.toString -> CardDTO(card) }, cards = trick.cards.map { case (card, player) => player.name -> CardDTO(card) },
firstCard = trick.firstCard.map(card => CardDTO(card)), firstCard = trick.firstCard.map(card => CardDTO(card)),
winner = trick.winner.map(player => PlayerDTO(player)) winner = trick.winner.map(player => PlayerDTO(player))
) )

View File

@@ -0,0 +1,54 @@
package logic
import de.knockoutwhist.data.Pod
import de.knockoutwhist.data.redis.RedisManager
import org.apache.pekko.actor.ActorSystem
import org.redisson.config.Config
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import java.util
import java.util.UUID
import javax.inject.*
import scala.concurrent.ExecutionContext
import scala.jdk.CollectionConverters.*
@Singleton
class Gateway @Inject()(
lifecycle: ApplicationLifecycle,
actorSystem: ActorSystem
)(implicit ec: ExecutionContext) {
private val logger = Logger(getClass.getName)
val redis: RedisManager = {
val config: Config = Config()
val url = "redis://" + sys.env.getOrElse("REDIS_HOST", "localhost") + ":" + sys.env.getOrElse("REDIS_PORT", "6379")
logger.info(s"Connecting to Redis at $url")
config.useSingleServer.setAddress(url)
RedisManager(config)
}
redis.continuousSyncPod(() => {
logger.info("Syncing pod with Redis")
createPod()
})
logger.info("Gateway started")
def syncPod(): Unit = {
redis.syncPod(createPod())
}
private def createPod(): Pod = {
Pod(
UUID.randomUUID().toString,
PodManager.podName,
PodManager.podIp,
9000,
new util.ArrayList[String](PodManager.getAllGameIds().asJava),
new util.ArrayList[String](PodManager.allBoundUsers().asJava)
)
}
}

View File

@@ -21,6 +21,8 @@ object PodManager {
private val userSession: mutable.Map[User, String] = mutable.Map() private val userSession: mutable.Map[User, String] = mutable.Map()
private val injector: Injector = Guice.createInjector(KnockOutWebConfigurationModule()) private val injector: Injector = Guice.createInjector(KnockOutWebConfigurationModule())
private[logic] var redis: Option[Gateway] = None
def createGame( def createGame(
host: User, host: User,
name: String, name: String,
@@ -35,7 +37,8 @@ object PodManager {
host = host host = host
) )
sessions += (gameLobby.id -> gameLobby) sessions += (gameLobby.id -> gameLobby)
userSession += (host -> gameLobby.id) registerUserToGame(host, gameLobby.id)
redis.foreach(gateway => gateway.syncPod())
gameLobby gameLobby
} }
@@ -46,6 +49,7 @@ object PodManager {
def registerUserToGame(user: User, gameId: String): Boolean = { def registerUserToGame(user: User, gameId: String): Boolean = {
if (sessions.contains(gameId)) { if (sessions.contains(gameId)) {
userSession += (user -> gameId) userSession += (user -> gameId)
redis.foreach(gateway => gateway.syncPod())
true true
} else { } else {
false false
@@ -54,6 +58,7 @@ object PodManager {
def unregisterUserFromGame(user: User): Unit = { def unregisterUserFromGame(user: User): Unit = {
userSession.remove(user) userSession.remove(user)
redis.foreach(gateway => gateway.redis.invalidateUser(user.id.toString))
} }
def identifyGameOfUser(user: User): Option[GameLobby] = { def identifyGameOfUser(user: User): Option[GameLobby] = {
@@ -65,9 +70,12 @@ object PodManager {
private[logic] def removeGame(gameId: String): Unit = { private[logic] def removeGame(gameId: String): Unit = {
sessions.remove(gameId) sessions.remove(gameId)
redis.foreach(gateway => gateway.redis.invalidateGame(gameId))
// Also remove all user sessions associated with this game // Also remove all user sessions associated with this game
userSession.filterInPlace((_, v) => v != gameId) userSession.filterInPlace((_, v) => v != gameId)
} }
private[logic] def getAllGameIds(): List[String] = sessions.keys.toList
private[logic] def allBoundUsers(): List[String] = userSession.keys.map(_.id.toString).toList
} }

View File

@@ -9,6 +9,7 @@ import de.knockoutwhist.events.player.PlayerEvent
import de.knockoutwhist.player.Playertype.HUMAN import de.knockoutwhist.player.Playertype.HUMAN
import de.knockoutwhist.player.{AbstractPlayer, PlayerFactory} import de.knockoutwhist.player.{AbstractPlayer, PlayerFactory}
import de.knockoutwhist.rounds.{Match, Round, Trick} import de.knockoutwhist.rounds.{Match, Round, Trick}
import de.knockoutwhist.utils.DelayHandler
import de.knockoutwhist.utils.events.{EventListener, SimpleEvent} import de.knockoutwhist.utils.events.{EventListener, SimpleEvent}
import events.{KickEvent, LeftEvent, LobbyUpdateEvent, UserEvent} import events.{KickEvent, LeftEvent, LobbyUpdateEvent, UserEvent}
import exceptions.* import exceptions.*
@@ -33,6 +34,7 @@ class GameLobby private(
private val users: mutable.Map[UUID, UserSession] = mutable.Map() private val users: mutable.Map[UUID, UserSession] = mutable.Map()
logic.addListener(this) logic.addListener(this)
logic.addListener(DelayHandler)
logic.createSession() logic.createSession()
def addUser(user: User): UserSession = { def addUser(user: User): UserSession = {
@@ -106,6 +108,9 @@ class GameLobby private(
} }
if (sessionOpt.get.host) { if (sessionOpt.get.host) {
logic.invoke(SessionClosed()) logic.invoke(SessionClosed())
for (session <- users.values) {
PodManager.unregisterUserFromGame(session.user)
}
users.clear() users.clear()
PodManager.removeGame(id) PodManager.removeGame(id)
return return

View File

@@ -46,13 +46,23 @@ class UserSession(val user: User, val host: Boolean, val gameLobby: GameLobby) e
case "StartGame" => case "StartGame" =>
gameLobby.startGame(user) gameLobby.startGame(user)
case "PlayCard" => case "PlayCard" =>
val maybeCardIndex: Option[String] = (data \ "cardindex").asOpt[String] val maybeCardIndex: Option[Int] = (data \ "cardindex").asOpt[Int]
maybeCardIndex match { maybeCardIndex match {
case Some(index) => case Some(index) =>
val session = gameLobby.getUserSession(user.id) val session = gameLobby.getUserSession(user.id)
gameLobby.playCard(session, index.toInt) gameLobby.playCard(session, index)
case None => case None =>
println("Card Index not found or is not a number.") println("Card Index not found or is not a number." + data)
}
case "PlayDogCard" =>
val maybeCardIndex: Option[Int] = (data \ "cardindex").asOpt[Int]
maybeCardIndex match {
case Some(index) =>
val session = gameLobby.getUserSession(user.id)
gameLobby.playDogCard(session, index)
case None =>
val session = gameLobby.getUserSession(user.id)
gameLobby.playDogCard(session, -1)
} }
case "PickTrumpsuit" => case "PickTrumpsuit" =>
val maybeSuitIndex: Option[Int] = (data \ "suitIndex").asOpt[Int] val maybeSuitIndex: Option[Int] = (data \ "suitIndex").asOpt[Int]
@@ -63,6 +73,15 @@ class UserSession(val user: User, val host: Boolean, val gameLobby: GameLobby) e
case None => case None =>
println("Card Index not found or is not a number.") println("Card Index not found or is not a number.")
} }
case "PickTie" =>
val maybeCardIndex: Option[Int] = (data \ "cardIndex").asOpt[Int]
maybeCardIndex match {
case Some(index) =>
val session = gameLobby.getUserSession(user.id)
gameLobby.selectTie(session, index)
case None =>
println("Card Index not found or is not a number.")
}
case "KickPlayer" => case "KickPlayer" =>
val maybePlayerId: Option[String] = (data \ "playerId").asOpt[String] val maybePlayerId: Option[String] = (data \ "playerId").asOpt[String]
maybePlayerId match { maybePlayerId match {
@@ -74,6 +93,10 @@ class UserSession(val user: User, val host: Boolean, val gameLobby: GameLobby) e
} }
case "ReturnToLobby" => case "ReturnToLobby" =>
gameLobby.returnToLobby(this) gameLobby.returnToLobby(this)
case "LeaveGame" =>
gameLobby.leaveGame(user.id, false)
case _ =>
println("Unknown event type: " + eventType + " with data: " + data)
} }
} }

View File

@@ -0,0 +1,10 @@
package modules
import com.google.inject.AbstractModule
import logic.Gateway
class GatewayModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[Gateway]).asEagerSingleton()
}
}

View File

@@ -36,7 +36,7 @@ object WebsocketEventMapper {
// Register all custom mappers here // Register all custom mappers here
registerCustomMapper(ReceivedHandEventMapper) registerCustomMapper(ReceivedHandEventMapper)
registerCustomMapper(GameStateEventMapper) //registerCustomMapper(GameStateEventMapper)
registerCustomMapper(CardPlayedEventMapper) registerCustomMapper(CardPlayedEventMapper)
registerCustomMapper(NewRoundEventMapper) registerCustomMapper(NewRoundEventMapper)
registerCustomMapper(NewTrickEventMapper) registerCustomMapper(NewTrickEventMapper)
@@ -54,10 +54,12 @@ object WebsocketEventMapper {
}else { }else {
None None
} }
//println(s"This is getting sent to client: EVENT: ${obj.id}, STATE: ${session.gameLobby.getLogic.getCurrentState.toString}, STATEDATA: ${stateToJson(session)}, DATA: ${data}")
Json.obj( Json.obj(
"id" -> ("request-" + java.util.UUID.randomUUID().toString), "id" -> ("request-" + java.util.UUID.randomUUID().toString),
"event" -> obj.id, "event" -> obj.id,
"state" -> stateToJson(session), "state" -> session.gameLobby.getLogic.getCurrentState.toString,
"stateData" -> stateToJson(session),
"data" -> data "data" -> data
) )
} }

View File

@@ -0,0 +1,14 @@
include "application.conf"
play.http.secret.key="zg8^v0R*:7-m.>^8T2B1q)sE3MV_9=M{K9zx8,<3}"
play.http.context="/api"
play.modules.enabled += "modules.GatewayModule"
play.filters.cors {
allowedOrigins = ["https://knockout.janis-eccarius.de"]
allowedCredentials = true
allowedHttpMethods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allowedHttpHeaders = ["Accept", "Content-Type", "Origin", "X-Requested-With"]
}

View File

@@ -15,7 +15,7 @@ GET /rules controllers.MainMenuController.rules()
GET /navSPA/:pType controllers.MainMenuController.navSPA(pType) GET /navSPA/:pType controllers.MainMenuController.navSPA(pType)
POST /createGame controllers.MainMenuController.createGame() POST /createGame controllers.MainMenuController.createGame()
POST /joinGame controllers.MainMenuController.joinGame() POST /joinGame/:gameId controllers.MainMenuController.joinGame(gameId: String)
# User authentication routes # User authentication routes
POST /login controllers.UserController.login_Post() POST /login controllers.UserController.login_Post()
@@ -31,3 +31,6 @@ GET /websocket controllers.WebsocketController.socket()
# Status # Status
GET /status controllers.StatusController.requestStatus() GET /status controllers.StatusController.requestStatus()
GET /status/:gameId controllers.StatusController.game(gameId: String) GET /status/:gameId controllers.StatusController.game(gameId: String)
# Health
GET /health/simple controllers.HealthController.simple()

View File

@@ -0,0 +1,12 @@
include "application.conf"
play.http.context="/api"
play.modules.enabled += "modules.GatewayModule"
play.filters.cors {
allowedOrigins = ["https://st.knockout.janis-eccarius.de"]
allowedCredentials = true
allowedHttpMethods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allowedHttpHeaders = ["Accept", "Content-Type", "Origin", "X-Requested-With"]
}

View File

@@ -1,11 +1,9 @@
// javascript let ws = null;
let ws = null; // will be created by connectWebSocket() const pending = new Map();
const pending = new Map(); // id -> { resolve, reject, timer } const handlers = new Map();
const handlers = new Map(); // eventType -> handler(data) -> (value|Promise)
let timer = null; let timer = null;
// helper to attach message/error/close handlers to a socket
function setupSocketHandlers(socket) { function setupSocketHandlers(socket) {
socket.onmessage = (event) => { socket.onmessage = (event) => {
console.debug("SERVER MESSAGE:", event.data); console.debug("SERVER MESSAGE:", event.data);
@@ -48,7 +46,6 @@ function setupSocketHandlers(socket) {
}; };
if (!handler) { if (!handler) {
// no handler: respond with an error object in data so server can fail it
console.warn("No handler for event:", eventType); console.warn("No handler for event:", eventType);
sendResponse({error: "No handler for event: " + eventType}); sendResponse({error: "No handler for event: " + eventType});
return; return;
@@ -91,7 +88,6 @@ function setupSocketHandlers(socket) {
}; };
} }
// connect/disconnect helpers
function connectWebSocket(url = null) { function connectWebSocket(url = null) {
if (!url) { if (!url) {
const loc = window.location; const loc = window.location;
@@ -100,7 +96,6 @@ function connectWebSocket(url = null) {
} }
if (ws && ws.readyState === WebSocket.OPEN) return Promise.resolve(); if (ws && ws.readyState === WebSocket.OPEN) return Promise.resolve();
if (ws && ws.readyState === WebSocket.CONNECTING) { if (ws && ws.readyState === WebSocket.CONNECTING) {
// already connecting - return a promise that resolves on open
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const prevOnOpen = ws.onopen; const prevOnOpen = ws.onopen;
const prevOnError = ws.onerror; const prevOnError = ws.onerror;
@@ -121,7 +116,6 @@ function connectWebSocket(url = null) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
ws.onopen = () => { ws.onopen = () => {
console.log("WebSocket connection established!"); console.log("WebSocket connection established!");
// start heartbeat
timer = setInterval(() => { timer = setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN) { if (ws && ws.readyState === WebSocket.OPEN) {
sendEventAndWait("ping", {}).then( sendEventAndWait("ping", {}).then(

View File

@@ -1,3 +1,3 @@
MAJOR=4 MAJOR=4
MINOR=11 MINOR=29
PATCH=0 PATCH=0