Search in sources :

Example 1 with ConnectionAware

use of com.faforever.server.client.ConnectionAware in project faf-java-server by FAForever.

the class GameService method disconnectPlayerFromGame.

/**
 * Tells all peers of the player with the specified ID to drop their connections to him/her.
 */
public void disconnectPlayerFromGame(Player requester, int playerId) {
    Optional<Player> optional = playerService.getOnlinePlayer(playerId);
    if (!optional.isPresent()) {
        log.warn("User '{}' tried to disconnect unknown player '{}' from game", requester, playerId);
        return;
    }
    Player player = optional.get();
    Game game = player.getCurrentGame();
    if (game == null) {
        log.warn("User '{}' tried to disconnect player '{}' from game, but no game is associated", requester, player);
        return;
    }
    Collection<? extends ConnectionAware> receivers = game.getConnectedPlayers().values().stream().filter(item -> !Objects.equals(item.getId(), playerId)).collect(Collectors.toList());
    clientService.disconnectPlayerFromGame(playerId, receivers);
    log.info("User '{}' disconnected player '{}' from game '{}'", requester, player, game);
}
Also used : Arrays(java.util.Arrays) ProgrammingError(com.faforever.server.error.ProgrammingError) ModVersion(com.faforever.server.entity.ModVersion) BiFunction(java.util.function.BiFunction) ArmyResult(com.faforever.server.entity.ArmyResult) PlayerOfflineEvent(com.faforever.server.player.PlayerOfflineEvent) PlayerService(com.faforever.server.player.PlayerService) Metrics(com.faforever.server.stats.Metrics) Player(com.faforever.server.entity.Player) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) Pair(org.springframework.data.util.Pair) ArmyStatistics(com.faforever.server.stats.ArmyStatistics) ClientService(com.faforever.server.client.ClientService) CounterService(org.springframework.boot.actuate.metrics.CounterService) ConnectionAware(com.faforever.server.client.ConnectionAware) RatingService(com.faforever.server.rating.RatingService) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) EventListener(org.springframework.context.event.EventListener) ErrorCode(com.faforever.server.error.ErrorCode) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) GameState(com.faforever.server.entity.GameState) MapService(com.faforever.server.map.MapService) Ladder1v1Rating(com.faforever.server.entity.Ladder1v1Rating) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Requests(com.faforever.server.error.Requests) Stream(java.util.stream.Stream) DivisionService(com.faforever.server.ladder1v1.DivisionService) RatingType(com.faforever.server.rating.RatingType) Game(com.faforever.server.entity.Game) GlobalRating(com.faforever.server.entity.GlobalRating) Entry(java.util.Map.Entry) Optional(java.util.Optional) RequestException(com.faforever.server.error.RequestException) Joiner(com.google.common.base.Joiner) ModService(com.faforever.server.mod.ModService) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) FeaturedMod(com.faforever.server.entity.FeaturedMod) Validity(com.faforever.server.entity.Validity) Function(java.util.function.Function) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) VictoryCondition(com.faforever.server.entity.VictoryCondition) GameResponses(com.faforever.server.client.GameResponses) Service(org.springframework.stereotype.Service) ServerProperties(com.faforever.server.config.ServerProperties) Iterator(java.util.Iterator) FeaturedModFileVersion(com.faforever.server.game.GameResponse.FeaturedModFileVersion) EntityManager(javax.persistence.EntityManager) Consumer(java.util.function.Consumer) SimMod(com.faforever.server.game.GameResponse.SimMod) ContextRefreshedEvent(org.springframework.context.event.ContextRefreshedEvent) ArmyStatisticsService(com.faforever.server.stats.ArmyStatisticsService) PlayerOnlineEvent(com.faforever.server.player.PlayerOnlineEvent) GamePlayerStats(com.faforever.server.entity.GamePlayerStats) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) Transactional(org.springframework.transaction.annotation.Transactional) Assert(org.springframework.util.Assert) Player(com.faforever.server.entity.Player) Game(com.faforever.server.entity.Game)

Example 2 with ConnectionAware

use of com.faforever.server.client.ConnectionAware in project faf-java-server by FAForever.

the class MatchMakerService method createMatch.

/**
 * <p>Creates a new match with the specified options and participants. All participants must be online and available
 * for matchmaking. A player can be unavailable for matchmaking if, for instance, he's currently playing a game or
 * offline. In this case, a {@link ErrorCode#PLAYER_NOT_AVAILABLE_FOR_MATCHMAKING} is thrown.</p>
 *
 * @throws RequestException if a player is not available for matchmaking or the map to be played is unknown by the
 * server.
 */
public void createMatch(ConnectionAware requester, UUID requestId, String title, String featuredMod, List<MatchParticipant> participants, int mapVersionId) {
    log.debug("Creating match '{}' with '{}' participants on map '{}'", title, participants.size(), mapVersionId);
    Requests.verify(participants.size() > 1, ErrorCode.INSUFFICIENT_MATCH_PARTICIPANTS, participants.size(), 2);
    List<Player> players = participants.stream().map(matchParticipant -> playerService.getOnlinePlayer(matchParticipant.getId()).orElseThrow(() -> new RequestException(requestId, ErrorCode.PLAYER_NOT_AVAILABLE_FOR_MATCHMAKING, matchParticipant.getId()))).peek(player -> Requests.verify(player.getCurrentGame() == null, requestId, ErrorCode.PLAYER_NOT_AVAILABLE_FOR_MATCHMAKING, player)).peek(this::removePlayer).collect(Collectors.toList());
    String mapFileName = mapService.findMap(mapVersionId).map(MapVersion::getFilename).orElseThrow(() -> new RequestException(requestId, ErrorCode.UNKNOWN_MAP, mapVersionId));
    Player host = players.get(0);
    List<Player> guests = players.subList(1, players.size());
    gameService.createGame(title, featuredMod, mapFileName, null, GameVisibility.PRIVATE, null, null, host).handle((game, throwable) -> {
        if (throwable != null) {
            log.debug("The host of match '{}' failed to start his game", title, throwable);
            throw new RequestException(requestId, ErrorCode.HOST_FAILED_TO_START_GAME, title, host);
        }
        AtomicInteger counter = new AtomicInteger();
        Integer hostId = host.getId();
        setPlayerOptionsForMatchParticipant(participants, host, counter, hostId);
        log.trace("Host '{}' for match '{}' is ready", host, title);
        clientService.sendMatchCreatedNotification(requestId, game.getId(), requester);
        List<CompletableFuture<Game>> guestGameFutures = guests.stream().peek(player -> log.trace("Telling player '{}' to start the game process for match '{}'", player, title)).map(player -> gameService.joinGame(game.getId(), null, player).thenApply(gameStartedFuture -> {
            setPlayerOptionsForMatchParticipant(participants, host, counter, player.getId());
            return gameStartedFuture;
        })).collect(Collectors.toList());
        return CompletableFuture.allOf(guestGameFutures.toArray(new CompletableFuture[guests.size()])).thenAccept(aVoid -> log.debug("All players launched their game for match '{}'", title)).exceptionally(throwable1 -> {
            log.debug("At least one player failed to launch their game for match '{}'", title, throwable1);
            return null;
        });
    });
}
Also used : ModService(com.faforever.server.mod.ModService) PlayerService(com.faforever.server.player.PlayerService) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) GameVisibility(com.faforever.server.game.GameVisibility) Scheduled(org.springframework.scheduling.annotation.Scheduled) FeaturedMod(com.faforever.server.entity.FeaturedMod) Value(lombok.Value) Player(com.faforever.server.entity.Player) HashSet(java.util.HashSet) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Service(org.springframework.stereotype.Service) Duration(java.time.Duration) Map(java.util.Map) ServerProperties(com.faforever.server.config.ServerProperties) ClientService(com.faforever.server.client.ClientService) ConnectionAware(com.faforever.server.client.ConnectionAware) RatingService(com.faforever.server.rating.RatingService) Set(java.util.Set) ErrorCode(com.faforever.server.error.ErrorCode) Faction(com.faforever.server.game.Faction) GameService(com.faforever.server.game.GameService) UUID(java.util.UUID) EqualsAndHashCode(lombok.EqualsAndHashCode) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) MapService(com.faforever.server.map.MapService) Ladder1v1Rating(com.faforever.server.entity.Ladder1v1Rating) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Requests(com.faforever.server.error.Requests) Game(com.faforever.server.entity.Game) MapVersion(com.faforever.server.entity.MapVersion) Optional(java.util.Optional) RequestException(com.faforever.server.error.RequestException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AllArgsConstructor(lombok.AllArgsConstructor) NotNull(org.jetbrains.annotations.NotNull) Comparator(java.util.Comparator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Player(com.faforever.server.entity.Player) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RequestException(com.faforever.server.error.RequestException)

Example 3 with ConnectionAware

use of com.faforever.server.client.ConnectionAware in project faf-java-server by FAForever.

the class MatchMakerServiceTest method createMatch.

@Test
public void createMatch() throws Exception {
    MatchParticipant participant1 = new MatchParticipant().setId(1).setFaction(Faction.UEF).setTeam(1).setSlot(1).setStartSpot(1);
    MatchParticipant participant2 = new MatchParticipant().setId(2).setFaction(Faction.AEON).setTeam(2).setSlot(2).setStartSpot(2);
    ConnectionAware requester = mock(ConnectionAware.class);
    UUID requestId = UUID.randomUUID();
    List<MatchParticipant> participants = Arrays.asList(participant1, participant2);
    int mapVersionId = 1;
    Player player1 = (Player) new Player().setId(1);
    Player player2 = (Player) new Player().setId(2);
    when(playerService.getOnlinePlayer(participant1.getId())).thenReturn(Optional.of(player1));
    when(playerService.getOnlinePlayer(participant2.getId())).thenReturn(Optional.of(player2));
    when(mapService.findMap(mapVersionId)).thenReturn(Optional.of(new MapVersion().setFilename("maps/foo.zip")));
    Game game = new Game();
    when(gameService.createGame("Test match", "faf", "null", null, GameVisibility.PRIVATE, null, null, player1)).thenReturn(CompletableFuture.completedFuture(game));
    when(gameService.joinGame(1, null, player2)).thenReturn(CompletableFuture.completedFuture(game));
    instance.createMatch(requester, requestId, "Test match", "faf", participants, mapVersionId);
    verify(clientService, timeout(5000)).sendMatchCreatedNotification(requestId, 1, requester);
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player1.getId(), GameService.OPTION_TEAM, participant1.getTeam());
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player1.getId(), GameService.OPTION_FACTION, participant1.getFaction().toFaValue());
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player1.getId(), GameService.OPTION_START_SPOT, participant1.getStartSpot());
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player1.getId(), GameService.OPTION_COLOR, 1);
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player1.getId(), GameService.OPTION_ARMY, 1);
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player2.getId(), GameService.OPTION_TEAM, participant2.getTeam());
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player2.getId(), GameService.OPTION_FACTION, participant2.getFaction().toFaValue());
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player2.getId(), GameService.OPTION_START_SPOT, participant2.getStartSpot());
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player2.getId(), GameService.OPTION_COLOR, 2);
    verify(gameService, timeout(1000)).updatePlayerOption(player1, player2.getId(), GameService.OPTION_ARMY, 2);
}
Also used : Player(com.faforever.server.entity.Player) Game(com.faforever.server.entity.Game) MapVersion(com.faforever.server.entity.MapVersion) ConnectionAware(com.faforever.server.client.ConnectionAware) UUID(java.util.UUID) Test(org.junit.Test)

Example 4 with ConnectionAware

use of com.faforever.server.client.ConnectionAware in project faf-java-server by FAForever.

the class GameServiceTest method disconnectFromGame.

/**
 * Tests whether all but the affected player are informed to drop someone.
 */
@Test
@SuppressWarnings("unchecked")
public void disconnectFromGame() throws Exception {
    Game game = hostGame(player1);
    Player player3 = (Player) new Player().setId(3);
    Player player4 = (Player) new Player().setId(4);
    addPlayer(game, player2);
    addPlayer(game, player3);
    addPlayer(game, player4);
    when(playerService.getOnlinePlayer(3)).thenReturn(Optional.of(player3));
    instance.disconnectPlayerFromGame(player1, 3);
    ArgumentCaptor<List<ConnectionAware>> captor = ArgumentCaptor.forClass((Class) List.class);
    verify(clientService).disconnectPlayerFromGame(eq(3), captor.capture());
    List<ConnectionAware> recipients = captor.getValue();
    assertThat(recipients, hasSize(3));
    assertThat(recipients, hasItems(player1, player2, player4));
}
Also used : Player(com.faforever.server.entity.Player) Game(com.faforever.server.entity.Game) List(java.util.List) ConnectionAware(com.faforever.server.client.ConnectionAware) Test(org.junit.Test)

Aggregations

ConnectionAware (com.faforever.server.client.ConnectionAware)4 Game (com.faforever.server.entity.Game)4 Player (com.faforever.server.entity.Player)4 List (java.util.List)3 ClientService (com.faforever.server.client.ClientService)2 ServerProperties (com.faforever.server.config.ServerProperties)2 FeaturedMod (com.faforever.server.entity.FeaturedMod)2 Ladder1v1Rating (com.faforever.server.entity.Ladder1v1Rating)2 MapVersion (com.faforever.server.entity.MapVersion)2 ErrorCode (com.faforever.server.error.ErrorCode)2 RequestException (com.faforever.server.error.RequestException)2 Requests (com.faforever.server.error.Requests)2 MapService (com.faforever.server.map.MapService)2 ModService (com.faforever.server.mod.ModService)2 PlayerService (com.faforever.server.player.PlayerService)2 RatingService (com.faforever.server.rating.RatingService)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Duration (java.time.Duration)2 Instant (java.time.Instant)2 Comparator (java.util.Comparator)2