Compare commits
No commits in common. "trunk" and "v0.0.0-rc.4" have entirely different histories.
trunk
...
v0.0.0-rc.
61 changed files with 144 additions and 2395 deletions
|
@ -36,11 +36,6 @@ jobs:
|
||||||
with:
|
with:
|
||||||
name: api.yml
|
name: api.yml
|
||||||
path: api/api.yml
|
path: api/api.yml
|
||||||
- name: Upload Websocket Spec as Artifact
|
|
||||||
uses: "https://git.euph.dev/actions/upload-artifact@v3"
|
|
||||||
with:
|
|
||||||
name: ws.yml
|
|
||||||
path: ws/ws.yml
|
|
||||||
- name: "Stop Gradle"
|
- name: "Stop Gradle"
|
||||||
run: gradle --stop
|
run: gradle --stop
|
||||||
|
|
||||||
|
@ -90,11 +85,6 @@ jobs:
|
||||||
with:
|
with:
|
||||||
name: api.yml
|
name: api.yml
|
||||||
path: release
|
path: release
|
||||||
- name: Download Websocket Spec
|
|
||||||
uses: "https://git.euph.dev/actions/download-artifact@v3"
|
|
||||||
with:
|
|
||||||
name: ws.yml
|
|
||||||
path: release
|
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
uses: "https://git.euph.dev/actions/release@v2"
|
uses: "https://git.euph.dev/actions/release@v2"
|
||||||
with:
|
with:
|
||||||
|
@ -106,3 +96,6 @@ jobs:
|
||||||
release-notes: |
|
release-notes: |
|
||||||
# Tower Defence - Server ${{ github.ref_name }}
|
# Tower Defence - Server ${{ github.ref_name }}
|
||||||
Read the [Documentation](https://git.euph.dev/TowerDefence/Dokumentation/wiki/Server/Config) to see how to setup the server.
|
Read the [Documentation](https://git.euph.dev/TowerDefence/Dokumentation/wiki/Server/Config) to see how to setup the server.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
69
api/api.yml
69
api/api.yml
|
@ -7,7 +7,7 @@ servers:
|
||||||
- url: /api/v1
|
- url: /api/v1
|
||||||
- url: http://localhost:8080/api/v1
|
- url: http://localhost:8080/api/v1
|
||||||
security:
|
security:
|
||||||
- JWTAuth: [ ]
|
- JWTAuth: []
|
||||||
|
|
||||||
components:
|
components:
|
||||||
securitySchemes:
|
securitySchemes:
|
||||||
|
@ -83,47 +83,9 @@ components:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
username:
|
username:
|
||||||
type: string
|
type: string
|
||||||
required:
|
required:
|
||||||
- username
|
- username
|
||||||
#############################################
|
|
||||||
# AdministratablePlayer #
|
|
||||||
#############################################
|
|
||||||
AdministratablePlayer:
|
|
||||||
description: a Player
|
|
||||||
type: object
|
|
||||||
properties:
|
|
||||||
username:
|
|
||||||
type: string
|
|
||||||
required:
|
|
||||||
- username
|
|
||||||
#############################################
|
|
||||||
# PlayerFilter #
|
|
||||||
#############################################
|
|
||||||
PlayerFilter:
|
|
||||||
description: Configuration data for query for the getting all players endpoint
|
|
||||||
type: object
|
|
||||||
properties:
|
|
||||||
page:
|
|
||||||
type: integer
|
|
||||||
description: "Page number (zero-based index)."
|
|
||||||
pageSize:
|
|
||||||
type: integer
|
|
||||||
description: "Number of players per page."
|
|
||||||
sortBy:
|
|
||||||
type: string
|
|
||||||
description: "Field to sort by (default is username)."
|
|
||||||
order:
|
|
||||||
type: string
|
|
||||||
enum: [ ascending, descending ]
|
|
||||||
description: "Sorting order (asc or desc)."
|
|
||||||
username:
|
|
||||||
type: string
|
|
||||||
description: "Filter players by username (case-insensitive, partial match)."
|
|
||||||
required:
|
|
||||||
- page
|
|
||||||
- pageSize
|
|
||||||
- order
|
|
||||||
responses:
|
responses:
|
||||||
201PlayerCreated:
|
201PlayerCreated:
|
||||||
description: "201 - Player Created"
|
description: "201 - Player Created"
|
||||||
|
@ -236,32 +198,5 @@ paths:
|
||||||
$ref: "#/components/responses/401Unauthorized"
|
$ref: "#/components/responses/401Unauthorized"
|
||||||
500:
|
500:
|
||||||
$ref: "#/components/responses/500InternalError"
|
$ref: "#/components/responses/500InternalError"
|
||||||
503:
|
|
||||||
$ref: "#/components/responses/503ServiceUnavailable"
|
|
||||||
/admin/players:
|
|
||||||
post:
|
|
||||||
operationId: "GetAllPlayers"
|
|
||||||
tags:
|
|
||||||
- admin
|
|
||||||
summary: "Retrieve a paginated list of players"
|
|
||||||
description: "Returns a paginat#ed list of players, optionally filtered by username."
|
|
||||||
requestBody:
|
|
||||||
content:
|
|
||||||
application/json:
|
|
||||||
schema:
|
|
||||||
$ref: "#/components/schemas/PlayerFilter"
|
|
||||||
responses:
|
|
||||||
200:
|
|
||||||
description: "A List of all Player"
|
|
||||||
content:
|
|
||||||
application/json:
|
|
||||||
schema:
|
|
||||||
type: array
|
|
||||||
items:
|
|
||||||
$ref: "#/components/schemas/AdministratablePlayer"
|
|
||||||
401:
|
|
||||||
$ref: "#/components/responses/401Unauthorized"
|
|
||||||
500:
|
|
||||||
$ref: "#/components/responses/500InternalError"
|
|
||||||
503:
|
503:
|
||||||
$ref: "#/components/responses/503ServiceUnavailable"
|
$ref: "#/components/responses/503ServiceUnavailable"
|
|
@ -53,11 +53,6 @@ dependencies {
|
||||||
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
|
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
|
||||||
developmentOnly("org.springframework.boot:spring-boot-devtools")
|
developmentOnly("org.springframework.boot:spring-boot-devtools")
|
||||||
|
|
||||||
//JWT
|
|
||||||
implementation("io.jsonwebtoken:jjwt-api:0.12.6")
|
|
||||||
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.6")
|
|
||||||
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.6")
|
|
||||||
|
|
||||||
// Postgres
|
// Postgres
|
||||||
runtimeOnly("org.postgresql:postgresql")
|
runtimeOnly("org.postgresql:postgresql")
|
||||||
|
|
||||||
|
|
|
@ -1,26 +1,16 @@
|
||||||
package de.towerdefence.server.admin;
|
package de.towerdefence.server.admin;
|
||||||
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import de.towerdefence.server.auth.UserSession;
|
import de.towerdefence.server.auth.UserSession;
|
||||||
import de.towerdefence.server.oas.AdminApi;
|
import de.towerdefence.server.oas.AdminApi;
|
||||||
import de.towerdefence.server.oas.models.AdminAuthInfo;
|
import de.towerdefence.server.oas.models.AdminAuthInfo;
|
||||||
import de.towerdefence.server.oas.models.AdministratablePlayer;
|
|
||||||
import de.towerdefence.server.oas.models.PlayerFilter;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import de.towerdefence.server.player.PlayerRepository;
|
|
||||||
import de.towerdefence.server.utils.OrderToDirectionMapperService;
|
|
||||||
import de.towerdefence.server.utils.PlayerMapperService;
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.domain.Page;
|
|
||||||
import org.springframework.data.domain.PageRequest;
|
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
import org.springframework.data.domain.Sort;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
|
@ -30,16 +20,6 @@ public class AdminApiController implements AdminApi {
|
||||||
@Autowired
|
@Autowired
|
||||||
UserSession userSession;
|
UserSession userSession;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
PlayerRepository playerRepository;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
PlayerMapperService playerMapperService;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
OrderToDirectionMapperService orderToDirectionMapperService;
|
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<ObjectMapper> getObjectMapper() {
|
public Optional<ObjectMapper> getObjectMapper() {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
|
@ -56,31 +36,4 @@ public class AdminApiController implements AdminApi {
|
||||||
authInfo.setUsername(this.userSession.getUsername());
|
authInfo.setUsername(this.userSession.getUsername());
|
||||||
return ResponseEntity.ok(authInfo);
|
return ResponseEntity.ok(authInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public ResponseEntity<List<AdministratablePlayer>> getAllPlayers(PlayerFilter body) {
|
|
||||||
|
|
||||||
PlayerFilter.OrderEnum order = body.getOrder();
|
|
||||||
Integer page = body.getPage();
|
|
||||||
Integer pageSize = body.getPageSize();
|
|
||||||
String sortBy = body.getSortBy();
|
|
||||||
String username = body.getUsername();
|
|
||||||
|
|
||||||
Sort.Direction direction = orderToDirectionMapperService.orderToDirection(order);
|
|
||||||
|
|
||||||
Pageable pageable = PageRequest.of(page, pageSize, Sort.by(direction, sortBy));
|
|
||||||
|
|
||||||
Page<Player> playerPage;
|
|
||||||
|
|
||||||
if (username != null && !username.isEmpty()) {
|
|
||||||
playerPage = playerRepository.findByUsernameContainingIgnoreCase(username, pageable);
|
|
||||||
} else {
|
|
||||||
playerPage = playerRepository.findAll(pageable);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<AdministratablePlayer> playersMapped =
|
|
||||||
playerMapperService.mapPlayersToAdministratablePlayers(playerPage.getContent());
|
|
||||||
|
|
||||||
return ResponseEntity.ok(playersMapped);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +0,0 @@
|
||||||
package de.towerdefence.server.match;
|
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class Enemy {
|
|
||||||
private int poxX;
|
|
||||||
private int posY;
|
|
||||||
}
|
|
|
@ -1,54 +0,0 @@
|
||||||
package de.towerdefence.server.match;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.callbacks.PlayerHitpointsCallback;
|
|
||||||
import de.towerdefence.server.match.callbacks.PlayerMoneyCallback;
|
|
||||||
import de.towerdefence.server.match.exeptions.InvalidPlacementException;
|
|
||||||
import de.towerdefence.server.match.exeptions.InvalidPlacementReason;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
public class GameSession {
|
|
||||||
final static int START_HITPOINTS = 100;
|
|
||||||
final static int START_MONEY = 50;
|
|
||||||
final static int MAP_SIZE_X = 10;
|
|
||||||
final static int MAP_SIZE_Y = 20;
|
|
||||||
|
|
||||||
private final Tower[][] towers = new Tower[MAP_SIZE_X][MAP_SIZE_Y];
|
|
||||||
|
|
||||||
private final Player player;
|
|
||||||
@Getter
|
|
||||||
private int money;
|
|
||||||
@Getter
|
|
||||||
private int playerHitpoints;
|
|
||||||
private final PlayerMoneyCallback moneyCallback;
|
|
||||||
//private final PlayerHitpointsCallback hitpointsCallback;
|
|
||||||
|
|
||||||
public GameSession(Player player, PlayerMoneyCallback moneyCallback) {
|
|
||||||
this.player = player;
|
|
||||||
this.moneyCallback = moneyCallback;
|
|
||||||
//this.hitpointsCallback = hitpointsCallback;
|
|
||||||
this.money = START_MONEY;
|
|
||||||
this.playerHitpoints = START_HITPOINTS;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void placeTower(Tower tower, int x, int y) throws InvalidPlacementException {
|
|
||||||
if (x < 0 || y < 0 || x + 1 > MAP_SIZE_X || y + 1 > MAP_SIZE_Y) {
|
|
||||||
throw new InvalidPlacementException(InvalidPlacementReason.OUT_OF_BOUNDS);
|
|
||||||
}
|
|
||||||
if (towers[x][y] != null) {
|
|
||||||
throw new InvalidPlacementException(InvalidPlacementReason.LOCATION_USED);
|
|
||||||
}
|
|
||||||
if (money < Tower.COST) {
|
|
||||||
throw new InvalidPlacementException(InvalidPlacementReason.NOT_ENOUGH_MONEY);
|
|
||||||
}
|
|
||||||
money -= Tower.COST;
|
|
||||||
moneyCallback.call(player, money);
|
|
||||||
towers[x][y] = tower;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addMoney(int amount) {
|
|
||||||
money += amount;
|
|
||||||
moneyCallback.call(player, money);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,74 +0,0 @@
|
||||||
package de.towerdefence.server.match;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.callbacks.PlayerHitpointsCallback;
|
|
||||||
import de.towerdefence.server.match.callbacks.PlayerMoneyCallback;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
public class Match {
|
|
||||||
|
|
||||||
private final String matchId;
|
|
||||||
private final Player player1;
|
|
||||||
private final Player player2;
|
|
||||||
|
|
||||||
private GameSession player1Session;
|
|
||||||
private GameSession player2Session;
|
|
||||||
|
|
||||||
public Match(String matchId, Player player1, Player player2) {
|
|
||||||
this.matchId = matchId;
|
|
||||||
this.player1 = player1;
|
|
||||||
this.player2 = player2;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<Player> getOpponent(Player player) {
|
|
||||||
boolean isPlayer1 = player1.equals(player);
|
|
||||||
boolean isPlayer2 = player2.equals(player);
|
|
||||||
if (!isPlayer1 && !isPlayer2) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
if (isPlayer1) {
|
|
||||||
return Optional.of(player2);
|
|
||||||
}
|
|
||||||
return Optional.of(player1);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<GameSession> getPlayerGameSession(Player player) {
|
|
||||||
boolean isPlayer1 = player1.equals(player);
|
|
||||||
boolean isPlayer2 = player2.equals(player);
|
|
||||||
if (!isPlayer1 && !isPlayer2) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
if (isPlayer1) {
|
|
||||||
return Optional.of(player1Session);
|
|
||||||
}
|
|
||||||
return Optional.of(player2Session);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void connectPlayer(
|
|
||||||
Player player,
|
|
||||||
PlayerMoneyCallback moneyCallback,
|
|
||||||
PlayerHitpointsCallback hitpointsCallback
|
|
||||||
) {
|
|
||||||
boolean isPlayer1 = player1.equals(player);
|
|
||||||
boolean isPlayer2 = player2.equals(player);
|
|
||||||
if (!isPlayer1 && !isPlayer2) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (isPlayer1 && player1Session == null) {
|
|
||||||
this.player1Session = new GameSession(player, moneyCallback);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (isPlayer2 && player2Session == null) {
|
|
||||||
this.player2Session = new GameSession(player, moneyCallback);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean hasMatchStarted() {
|
|
||||||
return player1Session != null && player2Session != null;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,89 +0,0 @@
|
||||||
package de.towerdefence.server.match;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.callbacks.PlayerHitpointsCallback;
|
|
||||||
import de.towerdefence.server.match.callbacks.PlayerMoneyCallback;
|
|
||||||
import de.towerdefence.server.match.exeptions.InvalidPlacementException;
|
|
||||||
import de.towerdefence.server.match.exeptions.InvalidPlacementReason;
|
|
||||||
import de.towerdefence.server.match.exeptions.NotInMatchException;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class MatchService {
|
|
||||||
private final Map<Player, Match> playerMatches = new HashMap<>();
|
|
||||||
private final Map<Match, ScheduledFuture<?>> moneyTasks = new HashMap<>();
|
|
||||||
private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
|
||||||
|
|
||||||
public void createMatch(String matchId, Player player1, Player player2) {
|
|
||||||
Match match = new Match(matchId, player1, player2);
|
|
||||||
playerMatches.put(player1, match);
|
|
||||||
playerMatches.put(player2, match);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Match get(Player player) {
|
|
||||||
return playerMatches.get(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return opponent
|
|
||||||
*/
|
|
||||||
public Player placeTower(Player player, int x, int y) throws NotInMatchException, InvalidPlacementException {
|
|
||||||
Match match = playerMatches.get(player);
|
|
||||||
if (!match.hasMatchStarted()) {
|
|
||||||
throw new InvalidPlacementException(InvalidPlacementReason.MATCH_NOT_STARTED);
|
|
||||||
}
|
|
||||||
Optional<GameSession> playerSession = match.getPlayerGameSession(player);
|
|
||||||
if (playerSession.isEmpty()) {
|
|
||||||
throw new NotInMatchException();
|
|
||||||
}
|
|
||||||
Optional<Player> opponent = match.getOpponent(player);
|
|
||||||
if (opponent.isEmpty()) {
|
|
||||||
throw new NotInMatchException();
|
|
||||||
}
|
|
||||||
playerSession.get().placeTower(new Tower(), x, y);
|
|
||||||
return opponent.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void playerConnected(
|
|
||||||
Player player,
|
|
||||||
PlayerMoneyCallback moneyCallback,
|
|
||||||
PlayerHitpointsCallback hitpointsCallback
|
|
||||||
) {
|
|
||||||
Match match = playerMatches.get(player);
|
|
||||||
match.connectPlayer(player, moneyCallback, hitpointsCallback);
|
|
||||||
Optional<GameSession> optionalPlayerSession = match.getPlayerGameSession(player);
|
|
||||||
if (optionalPlayerSession.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
GameSession playerSession = optionalPlayerSession.get();
|
|
||||||
moneyCallback.call(player, playerSession.getMoney());
|
|
||||||
hitpointsCallback.call(player, playerSession.getPlayerHitpoints() );
|
|
||||||
if (!match.hasMatchStarted()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Optional<Player> optionalOpponent = match.getOpponent(player);
|
|
||||||
if (optionalOpponent.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Player opponent = optionalOpponent.get();
|
|
||||||
Optional<GameSession> optionalOpponentSession = match.getPlayerGameSession(opponent);
|
|
||||||
if (optionalOpponentSession.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
GameSession opponentSession = optionalOpponentSession.get();
|
|
||||||
ScheduledFuture<?> moneyTask = scheduler.scheduleAtFixedRate(
|
|
||||||
() -> {
|
|
||||||
playerSession.addMoney(3);
|
|
||||||
opponentSession.addMoney(3);
|
|
||||||
},
|
|
||||||
5,
|
|
||||||
5,
|
|
||||||
TimeUnit.SECONDS);
|
|
||||||
moneyTasks.put(match, moneyTask);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,5 +0,0 @@
|
||||||
package de.towerdefence.server.match;
|
|
||||||
|
|
||||||
public class Tower {
|
|
||||||
public static final int COST = 20;
|
|
||||||
}
|
|
|
@ -1,8 +0,0 @@
|
||||||
package de.towerdefence.server.match.callbacks;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface PlayerHitpointsCallback {
|
|
||||||
void call(Player player, int playerHitpoints);
|
|
||||||
}
|
|
|
@ -1,8 +0,0 @@
|
||||||
package de.towerdefence.server.match.callbacks;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface PlayerMoneyCallback {
|
|
||||||
void call(Player player, int playerMoney);
|
|
||||||
}
|
|
|
@ -1,8 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface AbortCallback {
|
|
||||||
void call(Player player, String matchId);
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.queue.FoundCallback;
|
|
||||||
import de.towerdefence.server.match.queue.QueuedCallback;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class ConfirmationCallbacks {
|
|
||||||
private final FoundCallback foundCallback;
|
|
||||||
private final QueuedCallback queuedCallback;
|
|
||||||
private final AbortCallback abortCallback;
|
|
||||||
private final EstablishedCallback establishedCallback;
|
|
||||||
private final RequeueCallback requeueCallback;
|
|
||||||
}
|
|
|
@ -1,10 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface EstablishedCallback {
|
|
||||||
void call(Player player, String matchId, Player opponent) throws IOException;
|
|
||||||
}
|
|
|
@ -1,222 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.MatchService;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Service
|
|
||||||
public class MatchConfirmationService {
|
|
||||||
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
|
||||||
private final Map<Player, UnconfirmedMatch> unconfirmedMatch = new HashMap<>();
|
|
||||||
final Map<UnconfirmedMatch, ScheduledFuture<?>> matchAbortTasks = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private final MatchService matchService;
|
|
||||||
|
|
||||||
public UnconfirmedMatch createMatch(Player player1,
|
|
||||||
Player player2,
|
|
||||||
ConfirmationCallbacks player1Callbacks,
|
|
||||||
ConfirmationCallbacks player2Callbacks) {
|
|
||||||
UnconfirmedMatch match = new UnconfirmedMatch(
|
|
||||||
player1,
|
|
||||||
player2,
|
|
||||||
player1Callbacks,
|
|
||||||
player2Callbacks);
|
|
||||||
unconfirmedMatch.put(player1, match);
|
|
||||||
unconfirmedMatch.put(player2, match);
|
|
||||||
ScheduledFuture<?> scheduledTask = scheduler.schedule(
|
|
||||||
() -> {
|
|
||||||
matchAbortTasks.remove(match);
|
|
||||||
unconfirmedMatch.remove(match.getPlayer1());
|
|
||||||
unconfirmedMatch.remove(match.getPlayer2());
|
|
||||||
if (match.getPlayer1State() == PlayerMatchConfirmState.CONFIRMED ) {
|
|
||||||
player1Callbacks.getRequeueCallback().call(
|
|
||||||
match.getPlayer1(),
|
|
||||||
match.getMatchId(),
|
|
||||||
player1Callbacks.getFoundCallback(),
|
|
||||||
player1Callbacks.getQueuedCallback(),
|
|
||||||
player1Callbacks.getAbortCallback(),
|
|
||||||
player1Callbacks.getEstablishedCallback());
|
|
||||||
} else {
|
|
||||||
player1Callbacks.getAbortCallback().call(
|
|
||||||
match.getPlayer1(),
|
|
||||||
match.getMatchId()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (match.getPlayer2State() == PlayerMatchConfirmState.CONFIRMED) {
|
|
||||||
player2Callbacks.getRequeueCallback().call(
|
|
||||||
match.getPlayer2(),
|
|
||||||
match.getMatchId(),
|
|
||||||
player2Callbacks.getFoundCallback(),
|
|
||||||
player2Callbacks.getQueuedCallback(),
|
|
||||||
player2Callbacks.getAbortCallback(),
|
|
||||||
player2Callbacks.getEstablishedCallback());
|
|
||||||
} else {
|
|
||||||
player2Callbacks.getAbortCallback().call(
|
|
||||||
match.getPlayer2(),
|
|
||||||
match.getMatchId()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
UnconfirmedMatch.TTL,
|
|
||||||
TimeUnit.MILLISECONDS
|
|
||||||
);
|
|
||||||
matchAbortTasks.put(match, scheduledTask);
|
|
||||||
return match;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void accept(Player player, String matchId) {
|
|
||||||
setPlayerAcceptState(player, matchId, PlayerMatchConfirmState.CONFIRMED);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void decline(Player player, String matchId) {
|
|
||||||
setPlayerAcceptState(player, matchId, PlayerMatchConfirmState.ABORTED);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setPlayerAcceptState(Player player, String matchId, PlayerMatchConfirmState state) {
|
|
||||||
Optional<UnconfirmedMatch> optionalMatch = getPlayerMatch(player, matchId);
|
|
||||||
if (optionalMatch.isEmpty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
UnconfirmedMatch match = optionalMatch.get();
|
|
||||||
|
|
||||||
Optional<PlayerMatchConfirmState> optionalPlayerState = match.getPlayerState(player);
|
|
||||||
if (optionalPlayerState.isEmpty()) {
|
|
||||||
unconfirmedMatch.remove(player);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (optionalPlayerState.get() != PlayerMatchConfirmState.UNKNOWN) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Optional<UnconfirmedMatchState> matchState = match.setPlayerConfirmState(player, state);
|
|
||||||
if (matchState.isEmpty()) {
|
|
||||||
unconfirmedMatch.remove(player);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
handleMatchConfirmation(match, matchState.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleMatchConfirmation(UnconfirmedMatch match, UnconfirmedMatchState state) {
|
|
||||||
if (state == UnconfirmedMatchState.WAITING) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
matchAbortTasks.get(match).cancel(true);
|
|
||||||
matchAbortTasks.remove(match);
|
|
||||||
|
|
||||||
unconfirmedMatch.remove(match.getPlayer1());
|
|
||||||
unconfirmedMatch.remove(match.getPlayer2());
|
|
||||||
|
|
||||||
ConfirmationCallbacks player1Callbacks = match.getPlayer1Callbacks();
|
|
||||||
ConfirmationCallbacks player2Callbacks = match.getPlayer2Callbacks();
|
|
||||||
|
|
||||||
switch (state) {
|
|
||||||
case ABORTED -> {
|
|
||||||
if (match.getPlayer1State() != PlayerMatchConfirmState.ABORTED ) {
|
|
||||||
player1Callbacks.getRequeueCallback().call(
|
|
||||||
match.getPlayer1(),
|
|
||||||
match.getMatchId(),
|
|
||||||
player1Callbacks.getFoundCallback(),
|
|
||||||
player1Callbacks.getQueuedCallback(),
|
|
||||||
player1Callbacks.getAbortCallback(),
|
|
||||||
player1Callbacks.getEstablishedCallback());
|
|
||||||
} else {
|
|
||||||
player1Callbacks.getAbortCallback().call(
|
|
||||||
match.getPlayer1(),
|
|
||||||
match.getMatchId()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (match.getPlayer2State() != PlayerMatchConfirmState.ABORTED) {
|
|
||||||
player2Callbacks.getRequeueCallback().call(
|
|
||||||
match.getPlayer2(),
|
|
||||||
match.getMatchId(),
|
|
||||||
player2Callbacks.getFoundCallback(),
|
|
||||||
player2Callbacks.getQueuedCallback(),
|
|
||||||
player2Callbacks.getAbortCallback(),
|
|
||||||
player2Callbacks.getEstablishedCallback());
|
|
||||||
} else {
|
|
||||||
player2Callbacks.getAbortCallback().call(
|
|
||||||
match.getPlayer2(),
|
|
||||||
match.getMatchId()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case CONFIRMED -> {
|
|
||||||
|
|
||||||
boolean player1successful = sendPlayerEstablished(
|
|
||||||
match.getMatchId(),
|
|
||||||
player1Callbacks.getEstablishedCallback(),
|
|
||||||
match.getPlayer1(),
|
|
||||||
match.getPlayer2()
|
|
||||||
);
|
|
||||||
boolean player2successful = sendPlayerEstablished(
|
|
||||||
match.getMatchId(),
|
|
||||||
player2Callbacks.getEstablishedCallback(),
|
|
||||||
match.getPlayer2(),
|
|
||||||
match.getPlayer1()
|
|
||||||
);
|
|
||||||
if (!player1successful || !player2successful) {
|
|
||||||
if (player1successful) {
|
|
||||||
player1Callbacks.getRequeueCallback().call(
|
|
||||||
match.getPlayer1(),
|
|
||||||
match.getMatchId(),
|
|
||||||
player1Callbacks.getFoundCallback(),
|
|
||||||
player1Callbacks.getQueuedCallback(),
|
|
||||||
player1Callbacks.getAbortCallback(),
|
|
||||||
player1Callbacks.getEstablishedCallback());
|
|
||||||
}
|
|
||||||
if (player2successful) {
|
|
||||||
player2Callbacks.getRequeueCallback().call(
|
|
||||||
match.getPlayer2(),
|
|
||||||
match.getMatchId(),
|
|
||||||
player2Callbacks.getFoundCallback(),
|
|
||||||
player2Callbacks.getQueuedCallback(),
|
|
||||||
player2Callbacks.getAbortCallback(),
|
|
||||||
player2Callbacks.getEstablishedCallback());
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
matchService.createMatch(match.getMatchId(), match.getPlayer1(), match.getPlayer2());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return if successful
|
|
||||||
*/
|
|
||||||
private boolean sendPlayerEstablished(
|
|
||||||
String matchId,
|
|
||||||
EstablishedCallback callback,
|
|
||||||
Player player,
|
|
||||||
Player opponent
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
callback.call(player, matchId, opponent);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Optional<UnconfirmedMatch> getPlayerMatch(Player player, String matchId) {
|
|
||||||
UnconfirmedMatch match = unconfirmedMatch.get(player);
|
|
||||||
if (match == null) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
if (!match.getMatchId().equals(matchId)) {
|
|
||||||
unconfirmedMatch.remove(player);
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
return Optional.of(match);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
public enum PlayerMatchConfirmState {
|
|
||||||
UNKNOWN,
|
|
||||||
CONFIRMED,
|
|
||||||
ABORTED
|
|
||||||
}
|
|
|
@ -1,18 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.queue.FoundCallback;
|
|
||||||
import de.towerdefence.server.match.queue.QueuedCallback;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface RequeueCallback {
|
|
||||||
void call(
|
|
||||||
Player player,
|
|
||||||
String matchId,
|
|
||||||
FoundCallback foundCallback,
|
|
||||||
QueuedCallback queuedCallback,
|
|
||||||
AbortCallback abortCallback,
|
|
||||||
EstablishedCallback establishedCallback
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,90 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
public class UnconfirmedMatch {
|
|
||||||
private final String matchId;
|
|
||||||
private final long created;
|
|
||||||
public static final long TTL = 30 * 1000;
|
|
||||||
private final Player player1;
|
|
||||||
private final Player player2;
|
|
||||||
private final ConfirmationCallbacks player1Callbacks;
|
|
||||||
private final ConfirmationCallbacks player2Callbacks;
|
|
||||||
|
|
||||||
public UnconfirmedMatch(
|
|
||||||
Player player1,
|
|
||||||
Player player2,
|
|
||||||
ConfirmationCallbacks player1Callbacks,
|
|
||||||
ConfirmationCallbacks player2Callbacks) {
|
|
||||||
this.player1 = player1;
|
|
||||||
this.player2 = player2;
|
|
||||||
this.player1Callbacks = player1Callbacks;
|
|
||||||
this.player2Callbacks = player2Callbacks;
|
|
||||||
this.created = Instant.now().toEpochMilli();
|
|
||||||
this.matchId = UUID.randomUUID().toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private PlayerMatchConfirmState player1State = PlayerMatchConfirmState.UNKNOWN;
|
|
||||||
private PlayerMatchConfirmState player2State = PlayerMatchConfirmState.UNKNOWN;
|
|
||||||
|
|
||||||
public Optional<UnconfirmedMatchState> setPlayerConfirmState(Player player, PlayerMatchConfirmState state) {
|
|
||||||
Optional<MatchPlayer> matchPlayer = getMatchPlayer(player);
|
|
||||||
if (matchPlayer.isEmpty()) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (matchPlayer.get()) {
|
|
||||||
case ONE -> player1State = state;
|
|
||||||
case TWO -> player2State = state;
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean timedOut = Instant.now().toEpochMilli() > created + TTL;
|
|
||||||
if (
|
|
||||||
timedOut
|
|
||||||
|| player1State == PlayerMatchConfirmState.ABORTED
|
|
||||||
|| player2State == PlayerMatchConfirmState.ABORTED
|
|
||||||
) {
|
|
||||||
return Optional.of(UnconfirmedMatchState.ABORTED);
|
|
||||||
}
|
|
||||||
if (player1State == PlayerMatchConfirmState.UNKNOWN || player2State == PlayerMatchConfirmState.UNKNOWN) {
|
|
||||||
return Optional.of(UnconfirmedMatchState.WAITING);
|
|
||||||
}
|
|
||||||
return Optional.of(UnconfirmedMatchState.CONFIRMED);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<PlayerMatchConfirmState> getPlayerState(Player player) {
|
|
||||||
Optional<MatchPlayer> matchPlayer = getMatchPlayer(player);
|
|
||||||
if (matchPlayer.isEmpty()) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
return switch (matchPlayer.get()) {
|
|
||||||
case ONE -> Optional.of(player1State);
|
|
||||||
case TWO -> Optional.of(player2State);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum MatchPlayer {
|
|
||||||
ONE,
|
|
||||||
TWO
|
|
||||||
}
|
|
||||||
|
|
||||||
private Optional<MatchPlayer> getMatchPlayer(Player player) {
|
|
||||||
boolean isPlayerOne = player.equals(player1);
|
|
||||||
boolean isPlayerTwo = player.equals(player2);
|
|
||||||
if (!isPlayerOne && !isPlayerTwo) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isPlayerOne) {
|
|
||||||
return Optional.of(MatchPlayer.ONE);
|
|
||||||
}
|
|
||||||
return Optional.of(MatchPlayer.TWO);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
package de.towerdefence.server.match.confirmation;
|
|
||||||
|
|
||||||
public enum UnconfirmedMatchState {
|
|
||||||
WAITING,
|
|
||||||
ABORTED,
|
|
||||||
CONFIRMED
|
|
||||||
}
|
|
|
@ -1,10 +0,0 @@
|
||||||
package de.towerdefence.server.match.exeptions;
|
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class InvalidPlacementException extends RuntimeException {
|
|
||||||
private final InvalidPlacementReason reason;
|
|
||||||
}
|
|
|
@ -1,15 +0,0 @@
|
||||||
package de.towerdefence.server.match.exeptions;
|
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public enum InvalidPlacementReason {
|
|
||||||
MATCH_NOT_STARTED("match-not-started"),
|
|
||||||
OUT_OF_BOUNDS("out-of-bounds"),
|
|
||||||
LOCATION_USED("location-used"),
|
|
||||||
NOT_ENOUGH_MONEY("not-enough-money");
|
|
||||||
|
|
||||||
private final String jsonName;
|
|
||||||
}
|
|
|
@ -1,4 +0,0 @@
|
||||||
package de.towerdefence.server.match.exeptions;
|
|
||||||
|
|
||||||
public class NotInMatchException extends RuntimeException {
|
|
||||||
}
|
|
|
@ -1,10 +0,0 @@
|
||||||
package de.towerdefence.server.match.queue;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface FoundCallback {
|
|
||||||
void call(Player player, String matchId, long created, long ttl) throws IOException;
|
|
||||||
}
|
|
|
@ -1,143 +0,0 @@
|
||||||
package de.towerdefence.server.match.queue;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.confirmation.*;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class MatchQueueService {
|
|
||||||
private final static int REQUIRED_PLAYER_COUNT = 2;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private final MatchConfirmationService matchConfirmationService;
|
|
||||||
|
|
||||||
private final List<Player> queue = new ArrayList<>();
|
|
||||||
private final Map<Player, ConfirmationCallbacks> confirmationCallbacks = new HashMap<>();
|
|
||||||
|
|
||||||
public void queuePlayer(
|
|
||||||
Player player,
|
|
||||||
FoundCallback foundCallback,
|
|
||||||
QueuedCallback queuedCallback,
|
|
||||||
AbortCallback abortCallback,
|
|
||||||
EstablishedCallback establishedCallback) {
|
|
||||||
queue.add(player);
|
|
||||||
confirmationCallbacks.put(player, new ConfirmationCallbacks(
|
|
||||||
foundCallback,
|
|
||||||
queuedCallback,
|
|
||||||
abortCallback,
|
|
||||||
establishedCallback,
|
|
||||||
this::onRequeue));
|
|
||||||
tryMatching();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void onRequeue(
|
|
||||||
Player player,
|
|
||||||
String matchId,
|
|
||||||
FoundCallback foundCallback,
|
|
||||||
QueuedCallback queuedCallback,
|
|
||||||
AbortCallback abortCallback,
|
|
||||||
EstablishedCallback establishedCallback) {
|
|
||||||
abortCallback.call(player, matchId);
|
|
||||||
try {
|
|
||||||
queuedCallback.call(player);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
queuePlayer(player, foundCallback, queuedCallback, abortCallback, establishedCallback);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void unQueuePlayer(Player player) {
|
|
||||||
queue.remove(player);
|
|
||||||
confirmationCallbacks.remove(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void tryMatching() {
|
|
||||||
if (queue.size() < REQUIRED_PLAYER_COUNT) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Player> loopQueue = new ArrayList<>(queue);
|
|
||||||
for (int i = 0; i < loopQueue.size() / REQUIRED_PLAYER_COUNT; i++) {
|
|
||||||
Player player1 = loopQueue.get(REQUIRED_PLAYER_COUNT * i);
|
|
||||||
Player player2 = loopQueue.get(REQUIRED_PLAYER_COUNT * i + 1);
|
|
||||||
|
|
||||||
ConfirmationCallbacks player1Callbacks = confirmationCallbacks.get(player1);
|
|
||||||
ConfirmationCallbacks player2Callbacks = confirmationCallbacks.get(player2);
|
|
||||||
|
|
||||||
UnconfirmedMatch match = this.matchConfirmationService.createMatch(
|
|
||||||
player1,
|
|
||||||
player2,
|
|
||||||
player1Callbacks,
|
|
||||||
player2Callbacks);
|
|
||||||
sentMatchFound(
|
|
||||||
match,
|
|
||||||
player1,
|
|
||||||
player2,
|
|
||||||
player1Callbacks,
|
|
||||||
player2Callbacks);
|
|
||||||
|
|
||||||
}
|
|
||||||
if (queue.size() > REQUIRED_PLAYER_COUNT) {
|
|
||||||
tryMatching();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void sentMatchFound(
|
|
||||||
UnconfirmedMatch match,
|
|
||||||
Player player1,
|
|
||||||
Player player2,
|
|
||||||
ConfirmationCallbacks player1Callbacks,
|
|
||||||
ConfirmationCallbacks player2Callbacks) {
|
|
||||||
boolean player1disconnected = setMatchFoundToPlayer(player1, player1Callbacks.getFoundCallback(), match);
|
|
||||||
boolean player2disconnected = setMatchFoundToPlayer(player2, player2Callbacks.getFoundCallback(), match);
|
|
||||||
|
|
||||||
queue.remove(player1);
|
|
||||||
queue.remove(player2);
|
|
||||||
|
|
||||||
if (!player1disconnected && !player2disconnected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (player1disconnected && match.getPlayer2State() != PlayerMatchConfirmState.ABORTED) {
|
|
||||||
player2Callbacks.getRequeueCallback().call(
|
|
||||||
player2,
|
|
||||||
match.getMatchId(),
|
|
||||||
player2Callbacks.getFoundCallback(),
|
|
||||||
player2Callbacks.getQueuedCallback(),
|
|
||||||
player2Callbacks.getAbortCallback(),
|
|
||||||
player2Callbacks.getEstablishedCallback());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (player2disconnected && match.getPlayer1State() != PlayerMatchConfirmState.ABORTED) {
|
|
||||||
player1Callbacks.getRequeueCallback().call(
|
|
||||||
player1,
|
|
||||||
match.getMatchId(),
|
|
||||||
player1Callbacks.getFoundCallback(),
|
|
||||||
player1Callbacks.getQueuedCallback(),
|
|
||||||
player1Callbacks.getAbortCallback(),
|
|
||||||
player1Callbacks.getEstablishedCallback());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean setMatchFoundToPlayer(Player player, FoundCallback callback, UnconfirmedMatch match) {
|
|
||||||
try {
|
|
||||||
callback.call(
|
|
||||||
player,
|
|
||||||
match.getMatchId(),
|
|
||||||
match.getCreated(),
|
|
||||||
UnconfirmedMatch.TTL);
|
|
||||||
} catch (IOException e) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,10 +0,0 @@
|
||||||
package de.towerdefence.server.match.queue;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
public interface QueuedCallback {
|
|
||||||
void call(Player player) throws IOException;
|
|
||||||
}
|
|
|
@ -1,11 +1,8 @@
|
||||||
package de.towerdefence.server.player;
|
package de.towerdefence.server.player;
|
||||||
|
|
||||||
import org.springframework.data.domain.Page;
|
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
public interface PlayerRepository extends JpaRepository<Player, Long> {
|
public interface PlayerRepository extends JpaRepository<Player, Long> {
|
||||||
Player findByUsername(String username);
|
Player findByUsername(String username);
|
||||||
boolean existsByUsername(String username);
|
boolean existsByUsername(String username);
|
||||||
Page<Player> findByUsernameContainingIgnoreCase(String username, Pageable pageable);
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,67 @@
|
||||||
|
package de.towerdefence.server.player.session;
|
||||||
|
|
||||||
|
import de.towerdefence.server.player.Player;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class PlayerLoginSessions {
|
||||||
|
public static final int PLAYER_LOGIN_SESSION_TOKEN_BYTE_LENGTH = 64;
|
||||||
|
private final SecureRandom random;
|
||||||
|
private final Map<String, String> playerLoginSessionTokens = new HashMap<>();
|
||||||
|
private final Map<String, Player> playerLoginSessionPlayers = new HashMap<>();
|
||||||
|
private final Map<String, ScheduledFuture<?>> playerLoginSessionSchedule = new HashMap<>();
|
||||||
|
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||||
|
|
||||||
|
public PlayerLoginSessions() {
|
||||||
|
random = new SecureRandom();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String createPlayerLoginSession(Player player) {
|
||||||
|
byte[] token_data = new byte[PLAYER_LOGIN_SESSION_TOKEN_BYTE_LENGTH];
|
||||||
|
this.random.nextBytes(token_data);
|
||||||
|
String token = new String(token_data, StandardCharsets.UTF_8);
|
||||||
|
String playerName = player.getUsername();
|
||||||
|
this.playerLoginSessionTokens.put(playerName, token);
|
||||||
|
this.playerLoginSessionPlayers.put(playerName, player);
|
||||||
|
this.playerLoginSessionSchedule.put(playerName, scheduler.schedule(
|
||||||
|
() -> {
|
||||||
|
this.playerLoginSessionTokens.remove(playerName);
|
||||||
|
this.playerLoginSessionPlayers.remove(playerName);
|
||||||
|
this.playerLoginSessionSchedule.remove(playerName);
|
||||||
|
},
|
||||||
|
30,
|
||||||
|
TimeUnit.SECONDS
|
||||||
|
));
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return an Optional Player. If it is empty, that Player has no valid Login Session
|
||||||
|
*/
|
||||||
|
public Optional<Player> getPlayerFromLoginSession(String username, String token) {
|
||||||
|
if (!this.playerLoginSessionTokens.containsKey(username)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
if (!this.playerLoginSessionTokens.get(username).equals(token)) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
this.playerLoginSessionTokens.remove(username);
|
||||||
|
Player player = this.playerLoginSessionPlayers.get(username);
|
||||||
|
ScheduledFuture<?> task = this.playerLoginSessionSchedule.get(username);
|
||||||
|
if (task != null) {
|
||||||
|
task.cancel(true);
|
||||||
|
}
|
||||||
|
this.playerLoginSessionSchedule.remove(username);
|
||||||
|
return Optional.of(player);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,37 +0,0 @@
|
||||||
package de.towerdefence.server.server;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.springframework.web.socket.TextMessage;
|
|
||||||
import org.springframework.web.socket.WebSocketSession;
|
|
||||||
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public abstract class JsonMessage {
|
|
||||||
protected abstract String getMessageId();
|
|
||||||
protected abstract Map<String, JsonNode> getData(JsonNodeFactory factory);
|
|
||||||
|
|
||||||
public void send(WebSocketSession session) throws IOException {
|
|
||||||
session.sendMessage(new TextMessage(getPayload()));
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPayload() {
|
|
||||||
JsonNodeFactory factory = new JsonNodeFactory(false);
|
|
||||||
ObjectNode msg = factory.objectNode().put("$id", getMessageId());
|
|
||||||
for (Map.Entry<String, JsonNode> entry : getData(factory).entrySet()) {
|
|
||||||
if(entry.getKey().equals("$id")){
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
msg.set(entry.getKey(), entry.getValue());
|
|
||||||
}
|
|
||||||
return msg.toString();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,50 +0,0 @@
|
||||||
package de.towerdefence.server.server;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import de.towerdefence.server.session.Channel;
|
|
||||||
import de.towerdefence.server.session.SessionsService;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.web.socket.CloseStatus;
|
|
||||||
import org.springframework.web.socket.WebSocketSession;
|
|
||||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public abstract class JsonWebsocketHandler extends TextWebSocketHandler {
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(JsonWebsocketHandler.class);
|
|
||||||
public final Channel channel;
|
|
||||||
protected final SessionsService sessionsService;
|
|
||||||
protected final Map<WebSocketSession, Player> sessionPlayers = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void afterConnectionEstablished(WebSocketSession session) {
|
|
||||||
String jwt = session.getHandshakeHeaders().getFirst("Authorization");
|
|
||||||
if (jwt == null){
|
|
||||||
closeSession(session, CloseStatus.NOT_ACCEPTABLE);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Optional<Player> player = sessionsService.getSession(jwt, channel);
|
|
||||||
if(player.isEmpty()){
|
|
||||||
closeSession(session, CloseStatus.NOT_ACCEPTABLE);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sessionPlayers.put(session, player.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void closeSession(WebSocketSession session, CloseStatus reason){
|
|
||||||
if(session.isOpen()){
|
|
||||||
try{
|
|
||||||
sessionPlayers.remove(session);
|
|
||||||
session.close(reason);
|
|
||||||
} catch (Exception exception) {
|
|
||||||
logger.info("Unable to Close the Session", exception);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -9,8 +9,7 @@ import de.towerdefence.server.oas.models.ServerHealth;
|
||||||
import de.towerdefence.server.player.Player;
|
import de.towerdefence.server.player.Player;
|
||||||
import de.towerdefence.server.player.PlayerRepository;
|
import de.towerdefence.server.player.PlayerRepository;
|
||||||
import de.towerdefence.server.player.PlayerService;
|
import de.towerdefence.server.player.PlayerService;
|
||||||
import de.towerdefence.server.session.Channel;
|
import de.towerdefence.server.player.session.PlayerLoginSessions;
|
||||||
import de.towerdefence.server.session.SessionsService;
|
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
|
@ -30,7 +29,7 @@ public class ServerApiController implements ServerApi {
|
||||||
@Autowired
|
@Autowired
|
||||||
private PlayerService playerService;
|
private PlayerService playerService;
|
||||||
@Autowired
|
@Autowired
|
||||||
private SessionsService sessionsService;
|
private PlayerLoginSessions playerLoginSessions;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<ObjectMapper> getObjectMapper() {
|
public Optional<ObjectMapper> getObjectMapper() {
|
||||||
|
@ -71,7 +70,7 @@ public class ServerApiController implements ServerApi {
|
||||||
} catch (NoSuchAlgorithmException e) {
|
} catch (NoSuchAlgorithmException e) {
|
||||||
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
|
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
String token = sessionsService.createSession(player, Channel.CONNECTION);
|
String token = playerLoginSessions.createPlayerLoginSession(player);
|
||||||
PlayerLoginSession session = new PlayerLoginSession();
|
PlayerLoginSession session = new PlayerLoginSession();
|
||||||
session.setUsername(player.getUsername());
|
session.setUsername(player.getUsername());
|
||||||
session.setToken(token);
|
session.setToken(token);
|
||||||
|
|
|
@ -0,0 +1,47 @@
|
||||||
|
package de.towerdefence.server.server;
|
||||||
|
|
||||||
|
import org.springframework.web.socket.TextMessage;
|
||||||
|
import org.springframework.web.socket.WebSocketSession;
|
||||||
|
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
public class ServerWebsocketHandler extends TextWebSocketHandler {
|
||||||
|
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
||||||
|
private final Map<WebSocketSession, ScheduledFuture<?>> sessionTaskMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
|
||||||
|
ScheduledFuture<?> scheduledTask = scheduler.scheduleAtFixedRate(
|
||||||
|
() -> sendCurrentTime(session),
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
TimeUnit.MILLISECONDS
|
||||||
|
);
|
||||||
|
sessionTaskMap.put(session, scheduledTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void handleTextMessage(WebSocketSession session, TextMessage message) {
|
||||||
|
try {
|
||||||
|
String responseMessage = "You are Connected to the Tower Defence Server Websocket";
|
||||||
|
session.sendMessage(new TextMessage(responseMessage));
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendCurrentTime(WebSocketSession session) {
|
||||||
|
ScheduledFuture<?> task = sessionTaskMap.get(session);
|
||||||
|
try {
|
||||||
|
session.sendMessage(new TextMessage(String.valueOf(System.currentTimeMillis())));
|
||||||
|
} catch (IllegalStateException | IOException e) {
|
||||||
|
task.cancel(true);
|
||||||
|
sessionTaskMap.remove(session);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package de.towerdefence.server.server;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||||
|
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||||
|
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSocket
|
||||||
|
public class WebSocketConfig implements WebSocketConfigurer {
|
||||||
|
@Override
|
||||||
|
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||||
|
registry.addHandler(new ServerWebsocketHandler(), "/ws/server").setAllowedOrigins("*");
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,49 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.MatchService;
|
|
||||||
import de.towerdefence.server.match.confirmation.MatchConfirmationService;
|
|
||||||
import de.towerdefence.server.match.queue.MatchQueueService;
|
|
||||||
import de.towerdefence.server.server.JsonWebsocketHandler;
|
|
||||||
import de.towerdefence.server.server.channels.connection.ConnectionWebsocketHandler;
|
|
||||||
import de.towerdefence.server.server.channels.match.MatchWebsocketHandler;
|
|
||||||
import de.towerdefence.server.server.channels.matchmaking.MatchmakingWebsocketHandler;
|
|
||||||
import de.towerdefence.server.session.SessionsService;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
|
||||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
|
||||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
@Configuration
|
|
||||||
@EnableWebSocket
|
|
||||||
public class WebsocketConfig implements WebSocketConfigurer {
|
|
||||||
private static final String CHANNEL_BASE_PATH = "/ws/";
|
|
||||||
@Autowired
|
|
||||||
private final SessionsService sessionsService;
|
|
||||||
@Autowired
|
|
||||||
private final MatchQueueService matchQueueService;
|
|
||||||
@Autowired
|
|
||||||
private final MatchConfirmationService matchConfirmationService;
|
|
||||||
@Autowired
|
|
||||||
private final MatchService matchService;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
|
||||||
registerJsonChannel(registry, new ConnectionWebsocketHandler(this.sessionsService));
|
|
||||||
registerJsonChannel(registry, new MatchmakingWebsocketHandler(
|
|
||||||
this.sessionsService,
|
|
||||||
this.matchQueueService,
|
|
||||||
this.matchConfirmationService
|
|
||||||
));
|
|
||||||
registerJsonChannel(registry, new MatchWebsocketHandler(this.sessionsService, this.matchService));
|
|
||||||
}
|
|
||||||
|
|
||||||
private void registerJsonChannel(WebSocketHandlerRegistry registry, JsonWebsocketHandler handler){
|
|
||||||
registry.addHandler(
|
|
||||||
handler,
|
|
||||||
CHANNEL_BASE_PATH + handler.channel.getJsonName()
|
|
||||||
).setAllowedOrigins("*");
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,43 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.connection;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import de.towerdefence.server.server.JsonWebsocketHandler;
|
|
||||||
import de.towerdefence.server.server.channels.connection.in.RequestConnectionTokenMessage;
|
|
||||||
import de.towerdefence.server.server.channels.connection.out.ProvidedConnectionTokenMessage;
|
|
||||||
import de.towerdefence.server.session.Channel;
|
|
||||||
import de.towerdefence.server.session.SessionsService;
|
|
||||||
import org.springframework.web.socket.CloseStatus;
|
|
||||||
import org.springframework.web.socket.TextMessage;
|
|
||||||
import org.springframework.web.socket.WebSocketSession;
|
|
||||||
|
|
||||||
public class ConnectionWebsocketHandler extends JsonWebsocketHandler {
|
|
||||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
|
|
||||||
public ConnectionWebsocketHandler(SessionsService sessionsService) {
|
|
||||||
super(Channel.CONNECTION, sessionsService);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
|
|
||||||
try{
|
|
||||||
String payload = message.getPayload();
|
|
||||||
switch ( objectMapper.readTree(payload).get("$id").asText()) {
|
|
||||||
case RequestConnectionTokenMessage.MESSAGE_ID -> handleRequestConnectionToken(session, payload);
|
|
||||||
default -> this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleRequestConnectionToken(WebSocketSession session, String payload) throws Exception {
|
|
||||||
RequestConnectionTokenMessage msg = objectMapper.readValue(payload, RequestConnectionTokenMessage.class);
|
|
||||||
Player player = this.sessionPlayers.get(session);
|
|
||||||
if (msg.getChannel() != Channel.MATCHMAKING) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String jwt = this.sessionsService.createSession(player, msg.getChannel());
|
|
||||||
new ProvidedConnectionTokenMessage(msg.getChannel(), jwt).send(session);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.connection.in;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
||||||
import de.towerdefence.server.session.Channel;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
import lombok.*;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@NotNull
|
|
||||||
public class RequestConnectionTokenMessage {
|
|
||||||
public static final String MESSAGE_ID = "RequestConnectionToken";
|
|
||||||
|
|
||||||
@JsonProperty("$id")
|
|
||||||
private String messageId;
|
|
||||||
private Channel channel;
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.connection.out;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import de.towerdefence.server.session.Channel;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class ProvidedConnectionTokenMessage extends JsonMessage {
|
|
||||||
private final Channel channel;
|
|
||||||
private final String token;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "ProvidedConnectionToken";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"channel", factory.textNode(channel.getJsonName()),
|
|
||||||
"token", factory.textNode(token)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,112 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import de.towerdefence.server.match.MatchService;
|
|
||||||
import de.towerdefence.server.match.exeptions.InvalidPlacementException;
|
|
||||||
import de.towerdefence.server.match.exeptions.NotInMatchException;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import de.towerdefence.server.server.JsonWebsocketHandler;
|
|
||||||
import de.towerdefence.server.server.channels.match.hitpoints.PlayerHitpointsMessage;
|
|
||||||
import de.towerdefence.server.server.channels.match.money.PlayerMoneyMessage;
|
|
||||||
import de.towerdefence.server.server.channels.match.placing.GamePlayerMap;
|
|
||||||
import de.towerdefence.server.server.channels.match.placing.InvalidPlacementMessage;
|
|
||||||
import de.towerdefence.server.server.channels.match.placing.RequestTowerPlacingMessage;
|
|
||||||
import de.towerdefence.server.server.channels.match.placing.TowerPlacedMessage;
|
|
||||||
import de.towerdefence.server.session.Channel;
|
|
||||||
import de.towerdefence.server.session.SessionsService;
|
|
||||||
import org.springframework.web.socket.CloseStatus;
|
|
||||||
import org.springframework.web.socket.TextMessage;
|
|
||||||
import org.springframework.web.socket.WebSocketSession;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
public class MatchWebsocketHandler extends JsonWebsocketHandler {
|
|
||||||
|
|
||||||
protected final Map<Player, WebSocketSession> playerSessions = new ConcurrentHashMap<>();
|
|
||||||
private final MatchService matchService;
|
|
||||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
|
|
||||||
public MatchWebsocketHandler(SessionsService sessionsService, MatchService matchService) {
|
|
||||||
super(Channel.MATCH, sessionsService);
|
|
||||||
this.matchService = matchService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void afterConnectionEstablished(WebSocketSession session) {
|
|
||||||
super.afterConnectionEstablished(session);
|
|
||||||
playerSessions.put(sessionPlayers.get(session), session);
|
|
||||||
matchService.playerConnected(
|
|
||||||
sessionPlayers.get(session),
|
|
||||||
this::onPlayerMoneyChanged,
|
|
||||||
this::onPlayerHitpointsChanged
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onPlayerMoneyChanged(Player player, int playerMoney) {
|
|
||||||
WebSocketSession session = playerSessions.get(player);
|
|
||||||
try {
|
|
||||||
new PlayerMoneyMessage(playerMoney).send(session);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onPlayerHitpointsChanged(Player player, int playerHitpoints) {
|
|
||||||
WebSocketSession session = playerSessions.get(player);
|
|
||||||
try {
|
|
||||||
new PlayerHitpointsMessage(playerHitpoints).send(session);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void closeSession(WebSocketSession session, CloseStatus reason) {
|
|
||||||
Player player = sessionPlayers.get(session);
|
|
||||||
super.closeSession(session, reason);
|
|
||||||
playerSessions.remove(player);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
|
|
||||||
try {
|
|
||||||
String payload = message.getPayload();
|
|
||||||
if (!Objects.equals(
|
|
||||||
objectMapper.readTree(payload).get("$id").asText(),
|
|
||||||
RequestTowerPlacingMessage.MESSAGE_ID
|
|
||||||
)) {
|
|
||||||
this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
handleRequestTowerPlacingMessage(session, payload);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleRequestTowerPlacingMessage(
|
|
||||||
WebSocketSession session,
|
|
||||||
String payload
|
|
||||||
) throws IOException {
|
|
||||||
RequestTowerPlacingMessage msg = objectMapper.readValue(payload, RequestTowerPlacingMessage.class);
|
|
||||||
Player opponent;
|
|
||||||
try {
|
|
||||||
opponent = this.matchService.placeTower(
|
|
||||||
this.sessionPlayers.get(session),
|
|
||||||
msg.getX(),
|
|
||||||
msg.getY()
|
|
||||||
);
|
|
||||||
} catch (InvalidPlacementException exception) {
|
|
||||||
new InvalidPlacementMessage(msg.getX(), msg.getY(), exception.getReason()).send(session);
|
|
||||||
return;
|
|
||||||
} catch (NotInMatchException ignored) {
|
|
||||||
this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
WebSocketSession opponentSession = playerSessions.get(opponent);
|
|
||||||
new TowerPlacedMessage(msg.getX(), msg.getY(), GamePlayerMap.PLAYER).send(session);
|
|
||||||
new TowerPlacedMessage(msg.getX(), msg.getY(), GamePlayerMap.OPPONENT).send(opponentSession);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match.hitpoints;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class PlayerHitpointsMessage extends JsonMessage {
|
|
||||||
|
|
||||||
private final int playerHitpoints;
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "PlayerHitpoints";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"playerHitpoints", factory.numberNode(this.playerHitpoints)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,26 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match.money;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class PlayerMoneyMessage extends JsonMessage {
|
|
||||||
|
|
||||||
private final int playerMoney;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "PlayerMoney";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"playerMoney", factory.numberNode(this.playerMoney)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,13 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match.placing;
|
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public enum GamePlayerMap {
|
|
||||||
PLAYER("player"),
|
|
||||||
OPPONENT("opponent");
|
|
||||||
|
|
||||||
private final String jsonName;
|
|
||||||
}
|
|
|
@ -1,31 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match.placing;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
|
|
||||||
import de.towerdefence.server.match.exeptions.InvalidPlacementReason;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class InvalidPlacementMessage extends JsonMessage {
|
|
||||||
|
|
||||||
private final int x;
|
|
||||||
private final int y;
|
|
||||||
private final InvalidPlacementReason reason;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "InvalidPlacement";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"x", factory.numberNode(this.x),
|
|
||||||
"y", factory.numberNode(this.y),
|
|
||||||
"reason", factory.textNode(this.reason.getJsonName()));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match.placing;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@NotNull
|
|
||||||
public class RequestTowerPlacingMessage {
|
|
||||||
public static final String MESSAGE_ID = "RequestTowerPlacing";
|
|
||||||
|
|
||||||
@JsonProperty("$id")
|
|
||||||
private String messageId;
|
|
||||||
private int x;
|
|
||||||
private int y;
|
|
||||||
}
|
|
|
@ -1,30 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.match.placing;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class TowerPlacedMessage extends JsonMessage {
|
|
||||||
|
|
||||||
private final int x;
|
|
||||||
private final int y;
|
|
||||||
private final GamePlayerMap map;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "TowerPlaced";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"x", factory.numberNode(this.x),
|
|
||||||
"y", factory.numberNode(this.y),
|
|
||||||
"map", factory.textNode(this.map.getJsonName())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,114 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.matchmaking;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import de.towerdefence.server.match.confirmation.MatchConfirmationService;
|
|
||||||
import de.towerdefence.server.match.queue.MatchQueueService;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import de.towerdefence.server.server.JsonWebsocketHandler;
|
|
||||||
import de.towerdefence.server.server.channels.matchmaking.bi.MatchSetSearchStateMessage;
|
|
||||||
import de.towerdefence.server.server.channels.matchmaking.in.MatchAcceptedMessage;
|
|
||||||
import de.towerdefence.server.server.channels.matchmaking.out.MatchAbortedMessage;
|
|
||||||
import de.towerdefence.server.server.channels.matchmaking.out.MatchEstablishedMessage;
|
|
||||||
import de.towerdefence.server.server.channels.matchmaking.out.MatchFoundMessage;
|
|
||||||
import de.towerdefence.server.session.Channel;
|
|
||||||
import de.towerdefence.server.session.SessionsService;
|
|
||||||
import org.springframework.web.socket.CloseStatus;
|
|
||||||
import org.springframework.web.socket.TextMessage;
|
|
||||||
import org.springframework.web.socket.WebSocketSession;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
public class MatchmakingWebsocketHandler extends JsonWebsocketHandler {
|
|
||||||
protected final Map<Player, WebSocketSession> playerSessions = new ConcurrentHashMap<>();
|
|
||||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
private final MatchQueueService matchQueueService;
|
|
||||||
private final MatchConfirmationService matchConfirmationService;
|
|
||||||
|
|
||||||
|
|
||||||
public MatchmakingWebsocketHandler(
|
|
||||||
SessionsService sessionsService,
|
|
||||||
MatchQueueService matchQueueService,
|
|
||||||
MatchConfirmationService matchConfirmationService
|
|
||||||
) {
|
|
||||||
super(Channel.MATCHMAKING, sessionsService);
|
|
||||||
this.matchQueueService = matchQueueService;
|
|
||||||
this.matchConfirmationService = matchConfirmationService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void afterConnectionEstablished(WebSocketSession session) {
|
|
||||||
super.afterConnectionEstablished(session);
|
|
||||||
playerSessions.put(sessionPlayers.get(session), session);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
|
|
||||||
try {
|
|
||||||
|
|
||||||
String payload = message.getPayload();
|
|
||||||
switch (objectMapper.readTree(payload).get("$id").asText()) {
|
|
||||||
case MatchSetSearchStateMessage.MESSAGE_ID -> handleMatchSetSearchStateMessage(session, payload);
|
|
||||||
case MatchAcceptedMessage.MESSAGE_ID -> handleMatchAcceptedMessage(session, payload);
|
|
||||||
default -> this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
this.closeSession(session, CloseStatus.BAD_DATA);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleMatchSetSearchStateMessage(WebSocketSession session, String payload) throws Exception {
|
|
||||||
MatchSetSearchStateMessage msg = objectMapper.readValue(payload, MatchSetSearchStateMessage.class);
|
|
||||||
Player player = sessionPlayers.get(session);
|
|
||||||
if (!msg.isSearching()) {
|
|
||||||
this.matchQueueService.unQueuePlayer(player);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.matchQueueService.queuePlayer(
|
|
||||||
player,
|
|
||||||
this::onFound,
|
|
||||||
this::onQueued,
|
|
||||||
this::onAbort,
|
|
||||||
this::onEstablished
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onFound(Player player, String matchId, long created, long ttl) throws IOException {
|
|
||||||
WebSocketSession session = playerSessions.get(player);
|
|
||||||
MatchFoundMessage msg = new MatchFoundMessage(matchId, created, ttl);
|
|
||||||
msg.send(session);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onQueued(Player player) throws IOException{
|
|
||||||
WebSocketSession session = playerSessions.get(player);
|
|
||||||
MatchSetSearchStateMessage msg = new MatchSetSearchStateMessage(true);
|
|
||||||
msg.send(session);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onAbort(Player player, String matchId) {
|
|
||||||
WebSocketSession session = playerSessions.get(player);
|
|
||||||
MatchAbortedMessage msg = new MatchAbortedMessage(matchId);
|
|
||||||
try {
|
|
||||||
msg.send(session);
|
|
||||||
} catch (IOException ignored) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void onEstablished(Player player, String matchId, Player opponent) throws IOException {
|
|
||||||
WebSocketSession session = playerSessions.get(player);
|
|
||||||
String token = this.sessionsService.createSession(player, Channel.MATCH);
|
|
||||||
MatchEstablishedMessage msg = new MatchEstablishedMessage(matchId, opponent.getUsername(), token);
|
|
||||||
msg.send(session);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleMatchAcceptedMessage(WebSocketSession session, String payload) throws Exception {
|
|
||||||
MatchAcceptedMessage msg = objectMapper.readValue(payload, MatchAcceptedMessage.class);
|
|
||||||
Player player = sessionPlayers.get(session);
|
|
||||||
if (msg.isAccepted()) {
|
|
||||||
this.matchConfirmationService.accept(player, msg.getMatchId());
|
|
||||||
} else {
|
|
||||||
this.matchConfirmationService.decline(player, msg.getMatchId());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,44 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.matchmaking.bi;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@NotNull
|
|
||||||
public class MatchSetSearchStateMessage extends JsonMessage {
|
|
||||||
public static final String MESSAGE_ID = "MatchSetSearchState";
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@JsonProperty("$id")
|
|
||||||
private String messageId;
|
|
||||||
|
|
||||||
private boolean searching;
|
|
||||||
|
|
||||||
public MatchSetSearchStateMessage(boolean searching) {
|
|
||||||
this(MESSAGE_ID, searching);
|
|
||||||
}
|
|
||||||
|
|
||||||
@JsonCreator
|
|
||||||
public MatchSetSearchStateMessage(
|
|
||||||
@JsonProperty("$id") String messageId,
|
|
||||||
@JsonProperty("searching") boolean searching
|
|
||||||
) {
|
|
||||||
this.messageId = messageId;
|
|
||||||
this.searching = searching;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"searching", factory.booleanNode(this.searching)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,15 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.matchmaking.in;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
|
||||||
import jakarta.validation.constraints.NotNull;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
@Data
|
|
||||||
@NotNull
|
|
||||||
public class MatchAcceptedMessage {
|
|
||||||
public static final String MESSAGE_ID = "MatchAccepted";
|
|
||||||
@JsonProperty("$id")
|
|
||||||
private String messageId;
|
|
||||||
private String matchId;
|
|
||||||
private boolean accepted;
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.matchmaking.out;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class MatchAbortedMessage extends JsonMessage {
|
|
||||||
private String matchId;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "MatchAborted";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"matchId", factory.textNode(this.matchId)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.matchmaking.out;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class MatchEstablishedMessage extends JsonMessage {
|
|
||||||
private String matchId;
|
|
||||||
private String opponentName;
|
|
||||||
private String token;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "MatchEstablished";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"matchId", factory.textNode(this.matchId),
|
|
||||||
"opponentName", factory.textNode(this.opponentName),
|
|
||||||
"token", factory.textNode(this.token)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
package de.towerdefence.server.server.channels.matchmaking.out;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
|
||||||
import de.towerdefence.server.server.JsonMessage;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class MatchFoundMessage extends JsonMessage {
|
|
||||||
private String matchId;
|
|
||||||
private long created;
|
|
||||||
private long ttl;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected String getMessageId() {
|
|
||||||
return "MatchFound";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected Map<String, JsonNode> getData(JsonNodeFactory factory) {
|
|
||||||
return Map.of(
|
|
||||||
"matchId", factory.textNode(this.matchId),
|
|
||||||
"created", factory.numberNode(this.created),
|
|
||||||
"ttl", factory.numberNode(this.ttl)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
package de.towerdefence.server.session;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public enum Channel {
|
|
||||||
CONNECTION("connection"),
|
|
||||||
MATCHMAKING("matchmaking"),
|
|
||||||
MATCH("match");
|
|
||||||
|
|
||||||
private final String jsonName;
|
|
||||||
|
|
||||||
@JsonCreator
|
|
||||||
public static Channel fromJsonName(String jsonName) {
|
|
||||||
for (Channel channel : Channel.values()) {
|
|
||||||
if (channel.getJsonName().equalsIgnoreCase(jsonName)) {
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new IllegalArgumentException("Unknown channel: " + jsonName);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,61 +0,0 @@
|
||||||
package de.towerdefence.server.session;
|
|
||||||
|
|
||||||
import io.jsonwebtoken.Claims;
|
|
||||||
import io.jsonwebtoken.Jwts;
|
|
||||||
import io.jsonwebtoken.security.Keys;
|
|
||||||
import io.jsonwebtoken.security.WeakKeyException;
|
|
||||||
import jakarta.annotation.PostConstruct;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class JwtService {
|
|
||||||
|
|
||||||
private final SecretKey secretKey;
|
|
||||||
|
|
||||||
public JwtService(JwtServiceConfig config) throws WeakKeyException {
|
|
||||||
this.secretKey = Keys.hmacShaKeyFor(config.getSecret().getBytes(StandardCharsets.UTF_8));
|
|
||||||
}
|
|
||||||
|
|
||||||
public String generateToken(String username, Channel channel, long ttl) {
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
Date issueDate = new Date(now);
|
|
||||||
Date expirationDate = new Date(now + ttl * 1000);
|
|
||||||
|
|
||||||
return Jwts.builder()
|
|
||||||
.subject(username)
|
|
||||||
.claim("channel", channel.getJsonName())
|
|
||||||
.issuedAt(issueDate)
|
|
||||||
.expiration(expirationDate)
|
|
||||||
.signWith(secretKey)
|
|
||||||
.compact();
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<String> verifyToken(String token, Channel channel) {
|
|
||||||
Claims claims = Jwts.parser()
|
|
||||||
.verifyWith(secretKey)
|
|
||||||
.build()
|
|
||||||
.parseSignedClaims(token)
|
|
||||||
.getPayload();
|
|
||||||
|
|
||||||
if (claims.getExpiration().before(new Date())) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
Channel tokenChannel;
|
|
||||||
try {
|
|
||||||
tokenChannel = Channel.fromJsonName(claims.get("channel", String.class));
|
|
||||||
} catch (IllegalArgumentException ignored) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
if(!channel.equals(tokenChannel)) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
return Optional.of(claims.getSubject());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,14 +0,0 @@
|
||||||
package de.towerdefence.server.session;
|
|
||||||
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
@Configuration
|
|
||||||
@ConfigurationProperties(prefix = "jwt")
|
|
||||||
public class JwtServiceConfig {
|
|
||||||
private String secret;
|
|
||||||
}
|
|
|
@ -1,63 +0,0 @@
|
||||||
package de.towerdefence.server.session;
|
|
||||||
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class SessionsService {
|
|
||||||
private static final int TIME_TO_LIVE_SECONDS = 30;
|
|
||||||
|
|
||||||
private final Map<String, Channel> tokenGrants = new ConcurrentHashMap<>();
|
|
||||||
private final Map<String, Player> sessions = new ConcurrentHashMap<>();
|
|
||||||
private final Map<String, ScheduledFuture<?>> tokenGarbageCollectors = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private final JwtService jwtService;
|
|
||||||
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
|
|
||||||
|
|
||||||
public String createSession(Player player, Channel channel){
|
|
||||||
String jwt = jwtService.generateToken(player.getUsername(), channel, TIME_TO_LIVE_SECONDS);
|
|
||||||
if(tokenGrants.containsKey(jwt)){
|
|
||||||
throw new IllegalStateException("The exact same JWT allready exists");
|
|
||||||
}
|
|
||||||
tokenGrants.put(jwt, channel);
|
|
||||||
sessions.put(jwt, player);
|
|
||||||
this.tokenGarbageCollectors.put(jwt, scheduler.schedule(() -> {
|
|
||||||
tokenGrants.remove(jwt);
|
|
||||||
sessions.remove(jwt);
|
|
||||||
tokenGarbageCollectors.remove(jwt);
|
|
||||||
}, TIME_TO_LIVE_SECONDS, TimeUnit.SECONDS));
|
|
||||||
return jwt;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<Player> getSession(String jwt, Channel channel){
|
|
||||||
Channel grantedChannel = tokenGrants.get(jwt);
|
|
||||||
if (grantedChannel == null || !grantedChannel.equals(channel)) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
Optional<String> username = jwtService.verifyToken(jwt, channel);
|
|
||||||
if (username.isEmpty()) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
Player player = sessions.get(jwt);
|
|
||||||
if (!Objects.equals(player.getUsername(), username.get())) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
ScheduledFuture<?> garbageCollector = tokenGarbageCollectors.get(jwt);
|
|
||||||
if (garbageCollector != null && !garbageCollector.isCancelled() && !garbageCollector.isDone()) {
|
|
||||||
garbageCollector.cancel(false);
|
|
||||||
}
|
|
||||||
tokenGarbageCollectors.remove(jwt);
|
|
||||||
tokenGrants.remove(jwt);
|
|
||||||
sessions.remove(jwt);
|
|
||||||
return Optional.of(player);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,18 +0,0 @@
|
||||||
package de.towerdefence.server.utils;
|
|
||||||
|
|
||||||
import de.towerdefence.server.oas.models.PlayerFilter;
|
|
||||||
import org.springframework.data.domain.Sort;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class OrderToDirectionMapperService {
|
|
||||||
|
|
||||||
public Sort.Direction orderToDirection(PlayerFilter.OrderEnum order) {
|
|
||||||
|
|
||||||
if (order == PlayerFilter.OrderEnum.ASCENDING) {
|
|
||||||
return Sort.Direction.ASC;
|
|
||||||
} else {
|
|
||||||
return Sort.Direction.DESC;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package de.towerdefence.server.utils;
|
|
||||||
|
|
||||||
import de.towerdefence.server.oas.models.AdministratablePlayer;
|
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class PlayerMapperService {
|
|
||||||
|
|
||||||
public List<AdministratablePlayer> mapPlayersToAdministratablePlayers(List<Player> players) {
|
|
||||||
List<AdministratablePlayer> administratablePlayers = new ArrayList<>();
|
|
||||||
for (Player player : players) {
|
|
||||||
AdministratablePlayer apiPlayer = new AdministratablePlayer();
|
|
||||||
apiPlayer.setUsername(player.getUsername());
|
|
||||||
administratablePlayers.add(apiPlayer);
|
|
||||||
}
|
|
||||||
return administratablePlayers;
|
|
||||||
}
|
|
||||||
|
|
||||||
public AdministratablePlayer mapPlayerToAdministratablePlayer(Player player) {
|
|
||||||
AdministratablePlayer administratablePlayer = new AdministratablePlayer();
|
|
||||||
administratablePlayer.setUsername(player.getUsername());
|
|
||||||
return administratablePlayer;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -9,11 +9,8 @@ spring.datasource.username=${TD_DB_USER:td_user}
|
||||||
spring.datasource.password=${TD_DB_PASS:td123}
|
spring.datasource.password=${TD_DB_PASS:td123}
|
||||||
spring.jpa.hibernate.ddl-auto=create-drop
|
spring.jpa.hibernate.ddl-auto=create-drop
|
||||||
|
|
||||||
# Signing JWT
|
|
||||||
jwt.secret=i-am-secret-key-that-you-wont-guess
|
|
||||||
|
|
||||||
# TODO: Replace with our own IAM (After completion of the project)
|
# TODO: Replace with our own IAM (After completion of the project)
|
||||||
# JWT Auth for Keycloak
|
# JWT Auth
|
||||||
spring.security.oauth2.client.registration.keycloak.client-id=employee-management-service
|
spring.security.oauth2.client.registration.keycloak.client-id=employee-management-service
|
||||||
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
|
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
|
||||||
spring.security.oauth2.client.registration.keycloak.scope=openid
|
spring.security.oauth2.client.registration.keycloak.scope=openid
|
||||||
|
|
|
@ -2,27 +2,11 @@
|
||||||
xmlns="https://raw.githubusercontent.com/spotbugs/spotbugs/4.8.6/spotbugs/etc/findbugsfilter.xsd">
|
xmlns="https://raw.githubusercontent.com/spotbugs/spotbugs/4.8.6/spotbugs/etc/findbugsfilter.xsd">
|
||||||
<Match>
|
<Match>
|
||||||
<Source name="~.*" />
|
<Source name="~.*" />
|
||||||
<Bug code="EI,EI2,UuF" /> <!-- We don't care about these codes -->
|
<Bug code="EI,EI2" /> <!-- We don't care about these codes -->
|
||||||
</Match>
|
</Match>
|
||||||
<Match>
|
<Match>
|
||||||
<!--Ignore
|
<!--Ignore
|
||||||
Auto Generated Code -->
|
Auto Generated Code -->
|
||||||
<Source name="~.*build/.*" />
|
<Source name="~.*build/.*" />
|
||||||
</Match>
|
</Match>
|
||||||
<Match>
|
|
||||||
<!-- We are not Vulnerable to that Attack in our Context-->
|
|
||||||
<Class name="de.towerdefence.server.session.JwtService"/>
|
|
||||||
<Bug code="M,B,CT"/>
|
|
||||||
</Match>
|
|
||||||
<Match>
|
|
||||||
<!-- Spotbugs does not detect that the other cases are handled above in an if-->
|
|
||||||
<Class name="de.towerdefence.server.match.confirmation.MatchConfirmationService"/>
|
|
||||||
<Bug code="M,D,SF"/>
|
|
||||||
</Match>
|
|
||||||
<Match>
|
|
||||||
<!-- This is Only a Placeholder Object, thus it's not a bad practice to instance it-->
|
|
||||||
<Class name="de.towerdefence.server.match.MatchService"/>
|
|
||||||
<Method name="placeTower"/>
|
|
||||||
<Bug code="L,B,ISC"/>
|
|
||||||
</Match>
|
|
||||||
</FindBugsFilter>
|
</FindBugsFilter>
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
package de.towerdefence.server;
|
package de.towerdefence.server;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import de.towerdefence.server.player.Player;
|
|
||||||
import de.towerdefence.server.player.PlayerRepository;
|
import de.towerdefence.server.player.PlayerRepository;
|
||||||
import de.towerdefence.server.player.PlayerService;
|
import de.towerdefence.server.player.PlayerService;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
@ -12,10 +11,6 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
@AutoConfigureMockMvc(addFilters = false)
|
@AutoConfigureMockMvc(addFilters = false)
|
||||||
@ActiveProfiles("test")
|
@ActiveProfiles("test")
|
||||||
|
@ -29,27 +24,10 @@ public abstract class IntegrationTest {
|
||||||
protected ObjectMapper objectMapper;
|
protected ObjectMapper objectMapper;
|
||||||
@Autowired
|
@Autowired
|
||||||
protected PlayerRepository playerRepository;
|
protected PlayerRepository playerRepository;
|
||||||
@Autowired
|
|
||||||
protected PlayerService playerService;
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
playerRepository.deleteAll();
|
playerRepository.deleteAll();
|
||||||
|
|
||||||
Map<String, String> players = new HashMap<>();
|
|
||||||
players.put("Alex", "1234");
|
|
||||||
players.put("Zorro", "1234");
|
|
||||||
|
|
||||||
players.forEach((username, password) -> {
|
|
||||||
Player player = new Player();
|
|
||||||
player.setUsername(username);
|
|
||||||
try {
|
|
||||||
playerService.setPassword(player, password);
|
|
||||||
playerRepository.saveAndFlush(player);
|
|
||||||
} catch (NoSuchAlgorithmException e) {
|
|
||||||
System.err.println("Error setting password for player: " + username);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
|
@ -57,5 +35,5 @@ public abstract class IntegrationTest {
|
||||||
playerRepository.deleteAll();
|
playerRepository.deleteAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,85 +0,0 @@
|
||||||
package de.towerdefence.server.server;
|
|
||||||
|
|
||||||
import de.towerdefence.server.IntegrationTest;
|
|
||||||
import de.towerdefence.server.oas.models.PlayerFilter;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
|
||||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
|
|
||||||
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
|
||||||
|
|
||||||
class GetAllPlayersTest extends IntegrationTest {
|
|
||||||
|
|
||||||
private MockHttpServletRequestBuilder createGetAllPlayersRequest(String requestBody) {
|
|
||||||
return MockMvcRequestBuilders.post(baseUri + "/admin/players")
|
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
|
||||||
.content(requestBody);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void playersExist() throws Exception {
|
|
||||||
PlayerFilter playerFilter = new PlayerFilter();
|
|
||||||
playerFilter.setPage(0);
|
|
||||||
playerFilter.setPageSize(10);
|
|
||||||
playerFilter.setOrder(PlayerFilter.OrderEnum.DESCENDING);
|
|
||||||
playerFilter.setUsername("");
|
|
||||||
playerFilter.setSortBy("username");
|
|
||||||
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
|
|
||||||
|
|
||||||
this.mvc.perform(createGetAllPlayersRequest(requestBody))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$").isArray())
|
|
||||||
.andExpect(jsonPath("$[0]").exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void playersSortedByAsc() throws Exception {
|
|
||||||
|
|
||||||
PlayerFilter playerFilter = new PlayerFilter();
|
|
||||||
playerFilter.setPage(0);
|
|
||||||
playerFilter.setPageSize(10);
|
|
||||||
playerFilter.setOrder(PlayerFilter.OrderEnum.ASCENDING);
|
|
||||||
playerFilter.setUsername("");
|
|
||||||
playerFilter.setSortBy("username");
|
|
||||||
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
|
|
||||||
|
|
||||||
this.mvc.perform(createGetAllPlayersRequest(requestBody))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$[0].username").value("Alex"))
|
|
||||||
.andExpect(jsonPath("$[1].username").value("Zorro"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void playersSortedByDesc() throws Exception {
|
|
||||||
PlayerFilter playerFilter = new PlayerFilter();
|
|
||||||
playerFilter.setPage(0);
|
|
||||||
playerFilter.setPageSize(10);
|
|
||||||
playerFilter.setOrder(PlayerFilter.OrderEnum.DESCENDING);
|
|
||||||
playerFilter.setUsername("");
|
|
||||||
playerFilter.setSortBy("username");
|
|
||||||
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
|
|
||||||
|
|
||||||
this.mvc.perform(createGetAllPlayersRequest(requestBody))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$[1].username").value("Alex"))
|
|
||||||
.andExpect(jsonPath("$[0].username").value("Zorro"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void playersFiltered() throws Exception {
|
|
||||||
PlayerFilter playerFilter = new PlayerFilter();
|
|
||||||
playerFilter.setPage(0);
|
|
||||||
playerFilter.setPageSize(10);
|
|
||||||
playerFilter.setOrder(PlayerFilter.OrderEnum.ASCENDING);
|
|
||||||
playerFilter.setUsername("Alex");
|
|
||||||
playerFilter.setSortBy("username");
|
|
||||||
String requestBody = this.objectMapper.writeValueAsString(playerFilter);
|
|
||||||
|
|
||||||
this.mvc.perform(createGetAllPlayersRequest(requestBody))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andExpect(jsonPath("$[0].username").value("Alex"))
|
|
||||||
.andExpect(jsonPath("$").isNotEmpty());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -30,4 +30,6 @@ public class PlayerRegistrationTest extends IntegrationTest {
|
||||||
.content(this.objectMapper.writeValueAsString(playerRegistrationData))
|
.content(this.objectMapper.writeValueAsString(playerRegistrationData))
|
||||||
.contentType(MediaType.APPLICATION_JSON);
|
.contentType(MediaType.APPLICATION_JSON);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
366
ws/ws.yml
366
ws/ws.yml
|
@ -1,366 +0,0 @@
|
||||||
asyncapi: 3.0.0
|
|
||||||
info:
|
|
||||||
title: Game Server
|
|
||||||
version: 0.0.1
|
|
||||||
description: |
|
|
||||||
This is the Websocket Specification for the Tower Defence Game. <br>
|
|
||||||
Because of the limitations of Async API, we expect that the actual json,
|
|
||||||
which is send as payload to always contain a field called `$id` with
|
|
||||||
the corresponding `messageId`. <br>
|
|
||||||
The `messageId` should be handled case sensitive.
|
|
||||||
defaultContentType: application/json
|
|
||||||
servers:
|
|
||||||
localhost:
|
|
||||||
host: localhost:8080
|
|
||||||
protocol: ws
|
|
||||||
pathname: /ws
|
|
||||||
security:
|
|
||||||
- $ref: "#/components/securitySchemes/JwtAuth"
|
|
||||||
|
|
||||||
channels:
|
|
||||||
connection:
|
|
||||||
title: Connection
|
|
||||||
description: |
|
|
||||||
The Base Channel used for:
|
|
||||||
- Authentication
|
|
||||||
- Receiving Tokens for other channels
|
|
||||||
- Reconnection
|
|
||||||
messages:
|
|
||||||
RequestConnectionToken:
|
|
||||||
description: |
|
|
||||||
A Message telling the Server, that
|
|
||||||
you want an Connection Token for a
|
|
||||||
Specific Channel
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
channel:
|
|
||||||
$ref: "#/components/schemas/Channel"
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- channel
|
|
||||||
ProvidedConnectionToken:
|
|
||||||
description: |
|
|
||||||
A Message telling the Server, that
|
|
||||||
you want an Connection Token for a
|
|
||||||
Specific Channel
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
channel:
|
|
||||||
$ref: "#/components/schemas/Channel"
|
|
||||||
token:
|
|
||||||
$ref: "#/components/schemas/JWT"
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- channel
|
|
||||||
- token
|
|
||||||
|
|
||||||
matchmaking:
|
|
||||||
title: Matchmaking
|
|
||||||
description: |
|
|
||||||
A Channel used to search for a match and
|
|
||||||
to receive one
|
|
||||||
messages:
|
|
||||||
MatchSetSearchState:
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
searching:
|
|
||||||
type: boolean
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- searching
|
|
||||||
MatchFound:
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
matchId:
|
|
||||||
type: string
|
|
||||||
created:
|
|
||||||
description: "Unix Timestamp describing when this Match was found"
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
ttl:
|
|
||||||
description: "Time in Milliseconds, how long this Match is open for accepting"
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- matchId
|
|
||||||
- created
|
|
||||||
- ttl
|
|
||||||
MatchAccepted:
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
matchId:
|
|
||||||
type: string
|
|
||||||
accepted:
|
|
||||||
type: boolean
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- matchId
|
|
||||||
- accepted
|
|
||||||
MatchAborted:
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
matchId:
|
|
||||||
type: string
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- matchId
|
|
||||||
MatchEstablished:
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
matchId:
|
|
||||||
type: string
|
|
||||||
opponentName:
|
|
||||||
type: string
|
|
||||||
token:
|
|
||||||
$ref: "#/components/schemas/JWT"
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- matchId
|
|
||||||
- opponentName
|
|
||||||
- token
|
|
||||||
|
|
||||||
match:
|
|
||||||
title: Match
|
|
||||||
description: |
|
|
||||||
Channel for managing an active match
|
|
||||||
messages:
|
|
||||||
RequestTowerPlacing:
|
|
||||||
description: Requesting a placement of a tower
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
x:
|
|
||||||
type: integer
|
|
||||||
y:
|
|
||||||
type: integer
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- x
|
|
||||||
- y
|
|
||||||
TowerPlaced:
|
|
||||||
description: A tower was placed
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
x:
|
|
||||||
type: integer
|
|
||||||
y:
|
|
||||||
type: integer
|
|
||||||
map:
|
|
||||||
type: string
|
|
||||||
enum:
|
|
||||||
- player
|
|
||||||
- opponent
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- x
|
|
||||||
- y
|
|
||||||
- map
|
|
||||||
InvalidPlacement:
|
|
||||||
description: A tower was placed
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
x:
|
|
||||||
type: integer
|
|
||||||
y:
|
|
||||||
type: integer
|
|
||||||
reason:
|
|
||||||
type: string
|
|
||||||
enum:
|
|
||||||
- "match-not-started"
|
|
||||||
- "out-of-bounds"
|
|
||||||
- "location-used"
|
|
||||||
- "not-enough-money"
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- x
|
|
||||||
- y
|
|
||||||
- reason
|
|
||||||
PlayerMoney:
|
|
||||||
description: Money a player currently has
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
playerMoney:
|
|
||||||
type: integer
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- playerMoney
|
|
||||||
PlayerHitpoints:
|
|
||||||
description: Hitpoints a player currently has
|
|
||||||
payload:
|
|
||||||
type: object
|
|
||||||
additionalProperties: false
|
|
||||||
properties:
|
|
||||||
$id:
|
|
||||||
type: string
|
|
||||||
format: messageId
|
|
||||||
playerHitpoints:
|
|
||||||
type: integer
|
|
||||||
required:
|
|
||||||
- $id
|
|
||||||
- playerHitpoints
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
operations:
|
|
||||||
requestConnectionToken:
|
|
||||||
title: RequestConnectionToken
|
|
||||||
action: send
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/connection"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/connection/messages/RequestConnectionToken"
|
|
||||||
reply:
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/connection"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/connection/messages/ProvidedConnectionToken"
|
|
||||||
searchMatch:
|
|
||||||
title: SearchMatch
|
|
||||||
action: send
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/matchmaking"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/matchmaking/messages/MatchSetSearchState"
|
|
||||||
setPlayerMatchSearching:
|
|
||||||
title: SetPlayerMatchSearching
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/matchmaking"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/matchmaking/messages/MatchSetSearchState"
|
|
||||||
foundMatch:
|
|
||||||
title: FoundGame
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/matchmaking"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/matchmaking/messages/MatchFound"
|
|
||||||
reply:
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/matchmaking"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/matchmaking/messages/MatchAccepted"
|
|
||||||
abortedMatch:
|
|
||||||
title: AbortedMatch
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/matchmaking"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/matchmaking/messages/MatchAborted"
|
|
||||||
establishedMatch:
|
|
||||||
title: EstablishedMatch
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/matchmaking"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/matchmaking/messages/MatchEstablished"
|
|
||||||
towerPlacing:
|
|
||||||
title: TowerPlacing
|
|
||||||
action: send
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/match"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/match/messages/RequestTowerPlacing"
|
|
||||||
reply:
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/match"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/match/messages/TowerPlaced"
|
|
||||||
- $ref: "#/channels/match/messages/InvalidPlacement"
|
|
||||||
enemyPlacedTower:
|
|
||||||
title: EnemyPlacedTower
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/match"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/match/messages/TowerPlaced"
|
|
||||||
playerMoney:
|
|
||||||
title: PlayerMoney
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/match"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/match/messages/PlayerMoney"
|
|
||||||
playerHitpoints:
|
|
||||||
title: PlayerHitpoints
|
|
||||||
action: receive
|
|
||||||
channel:
|
|
||||||
$ref: "#/channels/match"
|
|
||||||
messages:
|
|
||||||
- $ref: "#/channels/match/messages/PlayerHitpoints"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
components:
|
|
||||||
securitySchemes:
|
|
||||||
JwtAuth:
|
|
||||||
name: Authorization
|
|
||||||
description: |
|
|
||||||
A JWT Token has to be provided in the Handshake Header. <br>
|
|
||||||
This Field is expected to be called `Authorization`. <br>
|
|
||||||
It is expected to not have a prefix like `bearer`.
|
|
||||||
type: httpApiKey
|
|
||||||
in: header
|
|
||||||
schemas:
|
|
||||||
JWT:
|
|
||||||
type: string
|
|
||||||
format: jwt
|
|
||||||
Channel:
|
|
||||||
type: string
|
|
||||||
enum:
|
|
||||||
- matchmaking
|
|
Loading…
Add table
Reference in a new issue