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,20 +796,31 @@ 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, () -> {
try {
callExecutor.execute(
() -> {
Optional<Session> session = SessionManager.instance.getSession(sessionId); Optional<Session> session = SessionManager.instance.getSession(sessionId);
if (!session.isPresent()) { if (!session.isPresent()) {
logger.error("Session not found : " + sessionId); logger.error("Session not found : " + sessionId);
} else { } else {
UUID userId = session.get().getUserId(); UUID userId = session.get().getUserId();
GameManager.instance.quitMatch(gameId, userId); GameManager.instance.quitMatch(gameId, userId);
} }
}
);
} catch (Exception ex) {
handleException(ex);
}
}); });
} }
@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, () -> {
try {
callExecutor.execute(
() -> {
Optional<Session> session = SessionManager.instance.getSession(sessionId); Optional<Session> session = SessionManager.instance.getSession(sessionId);
if (!session.isPresent()) { if (!session.isPresent()) {
logger.error("Session not found : " + sessionId); logger.error("Session not found : " + sessionId);
@ -818,12 +829,21 @@ public class MageServerImpl implements MageServer {
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, () -> {
try {
callExecutor.execute(
() -> {
Optional<Session> session = SessionManager.instance.getSession(sessionId); Optional<Session> session = SessionManager.instance.getSession(sessionId);
if (!session.isPresent()) { if (!session.isPresent()) {
logger.error("Session not found : " + sessionId); logger.error("Session not found : " + sessionId);
@ -836,7 +856,13 @@ public class MageServerImpl implements MageServer {
TournamentManager.instance.quit(tournamentId, userId); 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() {
try {
Calendar calendarExp = Calendar.getInstance(); Calendar calendarExp = Calendar.getInstance();
calendarExp.add(Calendar.MINUTE, -3); calendarExp.add(Calendar.MINUTE, -3);
Calendar calendarRemove = Calendar.getInstance(); Calendar calendarRemove = Calendar.getInstance();
calendarRemove.add(Calendar.MINUTE, -8); calendarRemove.add(Calendar.MINUTE, -8);
List<User> toRemove = new ArrayList<>(); List<User> toRemove = new ArrayList<>();
for (User user : users.values()) { for (User user : users.values()) {
if (user.getUserState() != UserState.Offline try {
&& user.isExpired(calendarExp.getTime())) { if (user.getUserState() == UserState.Offline) {
if (user.isExpired(calendarRemove.getTime())) {
toRemove.add(user);
}
} else {
if (user.isExpired(calendarExp.getTime())) {
if (user.getUserState() == UserState.Connected) { if (user.getUserState() == UserState.Connected) {
user.lostConnection(); user.lostConnection();
disconnect(user.getId(), DisconnectReason.BecameInactive); disconnect(user.getId(), DisconnectReason.BecameInactive);
} }
removeUserFromAllTables(user.getId(), DisconnectReason.SessionExpired);
user.setUserState(UserState.Offline); user.setUserState(UserState.Offline);
// Remove the user from all tournaments
} }
if (user.getUserState() == UserState.Offline && user.isExpired(calendarRemove.getTime())) { }
toRemove.add(user); } catch (Exception ex) {
handleException(ex);
} }
} }
for (User user : toRemove) { for (User user : toRemove) {
removeUser(user.getId(), DisconnectReason.SessionExpired); users.remove(user.getId());
}
} catch (Exception ex) {
handleException(ex);
} }
} }
@ -196,6 +208,7 @@ public enum UserManager {
* *
*/ */
private void updateUserInfoList() { private void updateUserInfoList() {
try {
List<UserView> newUserInfoList = new ArrayList<>(); List<UserView> newUserInfoList = new ArrayList<>();
for (User user : UserManager.instance.getUsers()) { for (User user : UserManager.instance.getUsers()) {
newUserInfoList.add(new UserView( newUserInfoList.add(new UserView(
@ -213,6 +226,9 @@ public enum UserManager {
)); ));
} }
userInfoList = newUserInfoList; userInfoList = newUserInfoList;
} catch (Exception ex) {
handleException(ex);
}
} }
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());
} }