Some more changes to the user handling.

This commit is contained in:
LevelX2 2017-08-18 00:12:38 +02:00
parent cb8b4d8cbf
commit fea9dfe8f8
8 changed files with 118 additions and 76 deletions

View file

@ -27,6 +27,9 @@
*/ */
package mage.server; package mage.server;
import java.text.DateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import mage.interfaces.callback.ClientCallback; import mage.interfaces.callback.ClientCallback;
import mage.interfaces.callback.ClientCallbackMethod; import mage.interfaces.callback.ClientCallbackMethod;
import mage.view.ChatMessage; import mage.view.ChatMessage;
@ -35,10 +38,6 @@ import mage.view.ChatMessage.MessageType;
import mage.view.ChatMessage.SoundToPlay; import mage.view.ChatMessage.SoundToPlay;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.text.DateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* @author BetaSteward_at_googlemail.com * @author BetaSteward_at_googlemail.com
*/ */
@ -78,7 +77,7 @@ public class ChatSession {
} }
if (userId != null && clients.containsKey(userId)) { if (userId != null && clients.containsKey(userId)) {
String userName = clients.get(userId); String userName = clients.get(userId);
if (reason != DisconnectReason.LostConnection) { // for lost connection the user will be reconnected or session expire so no remove of chat yet if (reason != DisconnectReason.LostConnection) { // for lost connection the user will be reconnected or session expire so no removeUserFromAllTables of chat yet
clients.remove(userId); clients.remove(userId);
logger.debug(userName + '(' + reason.toString() + ')' + " removed from chatId " + chatId); logger.debug(userName + '(' + reason.toString() + ')' + " removed from chatId " + chatId);
} }

View file

@ -796,13 +796,21 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void quitMatch(final UUID gameId, final String sessionId) throws MageException { public void quitMatch(final UUID gameId, final String sessionId) throws MageException {
execute("quitMatch", sessionId, () -> { execute("quitMatch", sessionId, () -> {
Optional<Session> session = SessionManager.instance.getSession(sessionId); try {
if (!session.isPresent()) { callExecutor.execute(
logger.error("Session not found : " + sessionId); () -> {
} else { Optional<Session> session = SessionManager.instance.getSession(sessionId);
UUID userId = session.get().getUserId(); if (!session.isPresent()) {
logger.error("Session not found : " + sessionId);
} else {
UUID userId = session.get().getUserId();
GameManager.instance.quitMatch(gameId, userId);
}
GameManager.instance.quitMatch(gameId, userId); }
);
} catch (Exception ex) {
handleException(ex);
} }
}); });
} }
@ -810,33 +818,51 @@ public class MageServerImpl implements MageServer {
@Override @Override
public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException { public void quitTournament(final UUID tournamentId, final String sessionId) throws MageException {
execute("quitTournament", sessionId, () -> { execute("quitTournament", sessionId, () -> {
Optional<Session> session = SessionManager.instance.getSession(sessionId); try {
if (!session.isPresent()) { callExecutor.execute(
logger.error("Session not found : " + sessionId); () -> {
} else { Optional<Session> session = SessionManager.instance.getSession(sessionId);
UUID userId = session.get().getUserId(); if (!session.isPresent()) {
logger.error("Session not found : " + sessionId);
} else {
UUID userId = session.get().getUserId();
TournamentManager.instance.quit(tournamentId, userId); TournamentManager.instance.quit(tournamentId, userId);
}
}
);
} catch (Exception ex) {
handleException(ex);
} }
}); });
} }
@Override @Override
public void quitDraft(final UUID draftId, final String sessionId) throws MageException { public void quitDraft(final UUID draftId, final String sessionId) throws MageException {
execute("quitDraft", sessionId, () -> { execute("quitDraft", sessionId, () -> {
Optional<Session> session = SessionManager.instance.getSession(sessionId); try {
if (!session.isPresent()) { callExecutor.execute(
logger.error("Session not found : " + sessionId); () -> {
} else { Optional<Session> session = SessionManager.instance.getSession(sessionId);
UUID userId = session.get().getUserId(); if (!session.isPresent()) {
UUID tableId = DraftManager.instance.getControllerByDraftId(draftId).getTableId(); logger.error("Session not found : " + sessionId);
Table table = TableManager.instance.getTable(tableId); } else {
if (table.isTournament()) { UUID userId = session.get().getUserId();
UUID tournamentId = table.getTournament().getId(); UUID tableId = DraftManager.instance.getControllerByDraftId(draftId).getTableId();
TournamentManager.instance.quit(tournamentId, userId); Table table = TableManager.instance.getTable(tableId);
} if (table.isTournament()) {
UUID tournamentId = table.getTournament().getId();
TournamentManager.instance.quit(tournamentId, userId);
}
}
}
);
} catch (Exception ex) {
handleException(ex);
} }
}); }
);
} }
@Override @Override
@ -1257,6 +1283,7 @@ public class MageServerImpl implements MageServer {
@Override @Override
public List<CardInfo> getMissingCardsData(List<String> classNames) { public List<CardInfo> getMissingCardsData(List<String> classNames) {
return CardRepository.instance.getMissingCards(classNames); return CardRepository.instance.getMissingCards(classNames);
} }
private static class MyActionWithNullNegativeResult extends ActionWithNullNegativeResult<Object> { private static class MyActionWithNullNegativeResult extends ActionWithNullNegativeResult<Object> {

View file

@ -356,7 +356,7 @@ public class Session {
} else { } else {
logger.error("SESSION LOCK - kill: userId " + userId); logger.error("SESSION LOCK - kill: userId " + userId);
} }
UserManager.instance.removeUser(userId, reason); UserManager.instance.removeUserFromAllTables(userId, reason);
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
logger.error("SESSION LOCK - kill: userId " + userId, ex); logger.error("SESSION LOCK - kill: userId " + userId, ex);
} finally { } finally {

View file

@ -511,7 +511,7 @@ public class TableController {
if (this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user if (this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user
&& (table.getState() == TableState.WAITING && (table.getState() == TableState.WAITING
|| table.getState() == TableState.READY_TO_START)) { || table.getState() == TableState.READY_TO_START)) {
// table not started yet and user is the owner, remove the table // table not started yet and user is the owner, removeUserFromAllTables the table
TableManager.instance.removeTable(table.getId()); TableManager.instance.removeTable(table.getId());
} else { } else {
UUID playerId = userPlayerMap.get(userId); UUID playerId = userPlayerMap.get(userId);
@ -826,7 +826,7 @@ public class TableController {
} }
user.showUserMessage("Match info", sb.toString()); user.showUserMessage("Match info", sb.toString());
} }
// remove table from user - table manager holds table for display of finished matches // removeUserFromAllTables table from user - table manager holds table for display of finished matches
if (!table.isTournamentSubTable()) { if (!table.isTournamentSubTable()) {
user.removeTable(entry.getValue()); user.removeTable(entry.getValue());
} }
@ -913,7 +913,7 @@ public class TableController {
return false; return false;
} }
} else { } else {
// check if table creator is still a valid user, if not remove table // check if table creator is still a valid user, if not removeUserFromAllTables table
return UserManager.instance.getUser(userId).isPresent(); return UserManager.instance.getUser(userId).isPresent();
} }
} }

View file

@ -161,7 +161,7 @@ public enum TableManager {
} }
} }
// remove user from all tournament sub tables // removeUserFromAllTables user from all tournament sub tables
public void userQuitTournamentSubTables(UUID userId) { public void userQuitTournamentSubTables(UUID userId) {
for (TableController controller : controllers.values()) { for (TableController controller : controllers.values()) {
if (controller.getTable() != null) { if (controller.getTable() != null) {
@ -174,7 +174,7 @@ public enum TableManager {
} }
} }
// remove user from all sub tables of a tournament // removeUserFromAllTables user from all sub tables of a tournament
public void userQuitTournamentSubTables(UUID tournamentId, UUID userId) { public void userQuitTournamentSubTables(UUID tournamentId, UUID userId) {
for (TableController controller : controllers.values()) { for (TableController controller : controllers.values()) {
if (controller.getTable().isTournamentSubTable() && controller.getTable().getTournament().getId().equals(tournamentId)) { if (controller.getTable().isTournamentSubTable() && controller.getTable().getTournament().getId().equals(tournamentId)) {
@ -386,8 +386,8 @@ public enum TableManager {
for (Table table : tableCopy) { for (Table table : tableCopy) {
try { try {
if (table.getState() != TableState.FINISHED if (table.getState() != TableState.FINISHED
&& ((System.currentTimeMillis() - table.getStartTime().getTime()) / 1000) > 30) { // remove only if table started longer than 30 seconds ago && ((System.currentTimeMillis() - table.getStartTime().getTime()) / 1000) > 30) { // removeUserFromAllTables only if table started longer than 30 seconds ago
// remove tables and games not valid anymore // removeUserFromAllTables tables and games not valid anymore
logger.debug(table.getId() + " [" + table.getName() + "] " + formatter.format(table.getStartTime() == null ? table.getCreateTime() : table.getCreateTime()) + " (" + table.getState().toString() + ") " + (table.isTournament() ? "- Tournament" : "")); logger.debug(table.getId() + " [" + table.getName() + "] " + formatter.format(table.getStartTime() == null ? table.getCreateTime() : table.getCreateTime()) + " (" + table.getState().toString() + ") " + (table.isTournament() ? "- Tournament" : ""));
getController(table.getId()).ifPresent(tableController -> { getController(table.getId()).ifPresent(tableController -> {
if ((table.isTournament() && !tableController.isTournamentStillValid()) if ((table.isTournament() && !tableController.isTournamentStillValid())

View file

@ -437,7 +437,7 @@ public class User {
sideboarding.remove(tableId); sideboarding.remove(tableId);
} }
public void remove(DisconnectReason reason) { public void removeUserFromAllTables(DisconnectReason reason) {
logger.trace("REMOVE " + userName + " Draft sessions " + draftSessions.size()); logger.trace("REMOVE " + userName + " Draft sessions " + draftSessions.size());
for (DraftSession draftSession : draftSessions.values()) { for (DraftSession draftSession : draftSessions.values()) {
draftSession.setKilled(); draftSession.setKilled();

View file

@ -112,6 +112,7 @@ public enum UserManager {
if (user.isPresent()) { if (user.isPresent()) {
user.get().setSessionId(""); user.get().setSessionId("");
if (reason == DisconnectReason.Disconnected) { if (reason == DisconnectReason.Disconnected) {
removeUserFromAllTables(userId, reason);
user.get().setUserState(UserState.Offline); user.get().setUserState(UserState.Offline);
} }
} }
@ -130,19 +131,17 @@ public enum UserManager {
return false; return false;
} }
public void removeUser(final UUID userId, final DisconnectReason reason) { public void removeUserFromAllTables(final UUID userId, final DisconnectReason reason) {
if (userId != null) { if (userId != null) {
getUser(userId).ifPresent(user getUser(userId).ifPresent(user
-> USER_EXECUTOR.execute( -> USER_EXECUTOR.execute(
() -> { () -> {
try { try {
LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + ']'); LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + ']');
user.remove(reason); user.removeUserFromAllTables(reason);
LOGGER.debug("USER REMOVE END - " + user.getName()); LOGGER.debug("USER REMOVE END - " + user.getName());
} catch (Exception ex) { } catch (Exception ex) {
handleException(ex); handleException(ex);
} finally {
users.remove(userId);
} }
} }
)); ));
@ -168,26 +167,39 @@ public enum UserManager {
* *
*/ */
private void checkExpired() { private void checkExpired() {
Calendar calendarExp = Calendar.getInstance(); try {
calendarExp.add(Calendar.MINUTE, -3); Calendar calendarExp = Calendar.getInstance();
Calendar calendarRemove = Calendar.getInstance(); calendarExp.add(Calendar.MINUTE, -3);
calendarRemove.add(Calendar.MINUTE, -8); Calendar calendarRemove = Calendar.getInstance();
List<User> toRemove = new ArrayList<>(); calendarRemove.add(Calendar.MINUTE, -8);
for (User user : users.values()) { List<User> toRemove = new ArrayList<>();
if (user.getUserState() != UserState.Offline for (User user : users.values()) {
&& user.isExpired(calendarExp.getTime())) { try {
if (user.getUserState() == UserState.Connected) { if (user.getUserState() == UserState.Offline) {
user.lostConnection(); if (user.isExpired(calendarRemove.getTime())) {
disconnect(user.getId(), DisconnectReason.BecameInactive); toRemove.add(user);
}
} else {
if (user.isExpired(calendarExp.getTime())) {
if (user.getUserState() == UserState.Connected) {
user.lostConnection();
disconnect(user.getId(), DisconnectReason.BecameInactive);
}
removeUserFromAllTables(user.getId(), DisconnectReason.SessionExpired);
user.setUserState(UserState.Offline);
// Remove the user from all tournaments
}
}
} catch (Exception ex) {
handleException(ex);
} }
user.setUserState(UserState.Offline);
} }
if (user.getUserState() == UserState.Offline && user.isExpired(calendarRemove.getTime())) { for (User user : toRemove) {
toRemove.add(user); users.remove(user.getId());
} }
} } catch (Exception ex) {
for (User user : toRemove) { handleException(ex);
removeUser(user.getId(), DisconnectReason.SessionExpired);
} }
} }
@ -196,23 +208,27 @@ public enum UserManager {
* *
*/ */
private void updateUserInfoList() { private void updateUserInfoList() {
List<UserView> newUserInfoList = new ArrayList<>(); try {
for (User user : UserManager.instance.getUsers()) { List<UserView> newUserInfoList = new ArrayList<>();
newUserInfoList.add(new UserView( for (User user : UserManager.instance.getUsers()) {
user.getName(), newUserInfoList.add(new UserView(
user.getHost(), user.getName(),
user.getSessionId(), user.getHost(),
user.getConnectionTime(), user.getSessionId(),
user.getLastActivity(), user.getConnectionTime(),
user.getGameInfo(), user.getLastActivity(),
user.getUserState().toString(), user.getGameInfo(),
user.getChatLockedUntil(), user.getUserState().toString(),
user.getClientVersion(), user.getChatLockedUntil(),
user.getEmail(), user.getClientVersion(),
user.getUserIdStr() user.getEmail(),
)); user.getUserIdStr()
));
}
userInfoList = newUserInfoList;
} catch (Exception ex) {
handleException(ex);
} }
userInfoList = newUserInfoList;
} }
public List<UserView> getUserInfoList() { public List<UserView> getUserInfoList() {

View file

@ -95,7 +95,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
} else if (matchList.size() < 50) { } else if (matchList.size() < 50) {
matchList.add(new MatchView(table)); matchList.add(new MatchView(table));
} else { } else {
// more since 50 matches finished since this match so remove it // more since 50 matches finished since this match so removeUserFromAllTables it
if (table.isTournament()) { if (table.isTournament()) {
TournamentManager.instance.removeTournament(table.getTournament().getId()); TournamentManager.instance.removeTournament(table.getTournament().getId());
} }