forked from External/mage
* Some chnages to chat, user and player handling.
This commit is contained in:
parent
58627bfcf6
commit
52897094b3
9 changed files with 258 additions and 88 deletions
|
|
@ -27,6 +27,13 @@
|
|||
*/
|
||||
package mage.server;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import mage.cards.repository.CardInfo;
|
||||
import mage.cards.repository.CardRepository;
|
||||
import mage.server.exceptions.UserNotFoundException;
|
||||
|
|
@ -36,11 +43,6 @@ import mage.view.ChatMessage.MessageType;
|
|||
import mage.view.ChatMessage.SoundToPlay;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
|
|
@ -51,6 +53,7 @@ public enum ChatManager {
|
|||
private static final HashMap<String, String> userMessages = new HashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<UUID, ChatSession> chatSessions = new ConcurrentHashMap<>();
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
|
||||
public UUID createChatSession(String info) {
|
||||
ChatSession chatSession = new ChatSession(info);
|
||||
|
|
@ -68,6 +71,10 @@ public enum ChatManager {
|
|||
|
||||
}
|
||||
|
||||
public void clearUserMessageStorage() {
|
||||
userMessages.clear();
|
||||
}
|
||||
|
||||
public void leaveChat(UUID chatId, UUID userId) {
|
||||
ChatSession chatSession = chatSessions.get(chatId);
|
||||
if (chatSession != null && chatSession.hasUser(userId)) {
|
||||
|
|
@ -81,7 +88,13 @@ public enum ChatManager {
|
|||
if (chatSession != null) {
|
||||
synchronized (chatSession) {
|
||||
if (chatSessions.containsKey(chatId)) {
|
||||
chatSessions.remove(chatId);
|
||||
final Lock w = lock.writeLock();
|
||||
w.lock();
|
||||
try {
|
||||
chatSessions.remove(chatId);
|
||||
} finally {
|
||||
w.unlock();
|
||||
}
|
||||
logger.trace("Chat removed - chatId: " + chatId);
|
||||
} else {
|
||||
logger.trace("Chat to destroy does not exist - chatId: " + chatId);
|
||||
|
|
@ -263,10 +276,11 @@ public enum ChatManager {
|
|||
* @param userId
|
||||
* @param message
|
||||
* @param color
|
||||
* @throws mage.server.exceptions.UserNotFoundException
|
||||
*/
|
||||
public void broadcast(UUID userId, String message, MessageColor color) throws UserNotFoundException {
|
||||
UserManager.instance.getUser(userId).ifPresent(user -> {
|
||||
chatSessions.values()
|
||||
getChatSessions()
|
||||
.stream()
|
||||
.filter(chat -> chat.hasUser(userId))
|
||||
.forEach(session -> session.broadcast(user.getName(), message, color, true, MessageType.TALK, null));
|
||||
|
|
@ -276,15 +290,15 @@ public enum ChatManager {
|
|||
|
||||
public void sendReconnectMessage(UUID userId) {
|
||||
UserManager.instance.getUser(userId).ifPresent(user
|
||||
-> chatSessions.values()
|
||||
.stream()
|
||||
.filter(chat -> chat.hasUser(userId))
|
||||
.forEach(chatSession -> chatSession.broadcast(null, user.getName() + " has reconnected", MessageColor.BLUE, true, MessageType.STATUS, null)));
|
||||
-> getChatSessions()
|
||||
.stream()
|
||||
.filter(chat -> chat.hasUser(userId))
|
||||
.forEach(chatSession -> chatSession.broadcast(null, user.getName() + " has reconnected", MessageColor.BLUE, true, MessageType.STATUS, null)));
|
||||
|
||||
}
|
||||
|
||||
public void removeUser(UUID userId, DisconnectReason reason) {
|
||||
for (ChatSession chatSession : chatSessions.values()) {
|
||||
for (ChatSession chatSession : getChatSessions()) {
|
||||
if (chatSession.hasUser(userId)) {
|
||||
chatSession.kill(userId, reason);
|
||||
}
|
||||
|
|
@ -292,7 +306,13 @@ public enum ChatManager {
|
|||
}
|
||||
|
||||
public List<ChatSession> getChatSessions() {
|
||||
return new ArrayList<>(chatSessions.values());
|
||||
final Lock r = lock.readLock();
|
||||
r.lock();
|
||||
try {
|
||||
return new ArrayList<>(chatSessions.values());
|
||||
} finally {
|
||||
r.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,6 +30,9 @@ package mage.server;
|
|||
import java.text.DateFormat;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import mage.interfaces.callback.ClientCallback;
|
||||
import mage.interfaces.callback.ClientCallbackMethod;
|
||||
import mage.view.ChatMessage;
|
||||
|
|
@ -46,6 +49,8 @@ public class ChatSession {
|
|||
private static final Logger logger = Logger.getLogger(ChatSession.class);
|
||||
private static final DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.SHORT);
|
||||
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
|
||||
private final ConcurrentHashMap<UUID, String> clients = new ConcurrentHashMap<>();
|
||||
private final UUID chatId;
|
||||
private final Date createTime;
|
||||
|
|
@ -61,7 +66,13 @@ public class ChatSession {
|
|||
UserManager.instance.getUser(userId).ifPresent(user -> {
|
||||
if (!clients.containsKey(userId)) {
|
||||
String userName = user.getName();
|
||||
clients.put(userId, userName);
|
||||
final Lock w = lock.writeLock();
|
||||
w.lock();
|
||||
try {
|
||||
clients.put(userId, userName);
|
||||
} finally {
|
||||
w.unlock();
|
||||
}
|
||||
broadcast(null, userName + " has joined (" + user.getClientVersion() + ')', MessageColor.BLUE, true, MessageType.STATUS, null);
|
||||
logger.trace(userName + " joined chat " + chatId);
|
||||
}
|
||||
|
|
@ -77,8 +88,14 @@ public class ChatSession {
|
|||
}
|
||||
if (userId != null && clients.containsKey(userId)) {
|
||||
String userName = clients.get(userId);
|
||||
if (reason != DisconnectReason.LostConnection) { // for lost connection the user will be reconnected or session expire so no removeUserFromAllTables of chat yet
|
||||
clients.remove(userId);
|
||||
if (reason != DisconnectReason.LostConnection) { // for lost connection the user will be reconnected or session expire so no removeUserFromAllTablesAndChat of chat yet
|
||||
final Lock w = lock.writeLock();
|
||||
w.lock();
|
||||
try {
|
||||
clients.remove(userId);
|
||||
} finally {
|
||||
w.unlock();
|
||||
}
|
||||
logger.debug(userName + '(' + reason.toString() + ')' + " removed from chatId " + chatId);
|
||||
}
|
||||
String message = reason.getMessage();
|
||||
|
|
@ -117,7 +134,15 @@ public class ChatSession {
|
|||
if (!message.isEmpty()) {
|
||||
Set<UUID> clientsToRemove = new HashSet<>();
|
||||
ClientCallback clientCallback = new ClientCallback(ClientCallbackMethod.CHATMESSAGE, chatId, new ChatMessage(userName, message, (withTime ? timeFormatter.format(new Date()) : ""), color, messageType, soundToPlay));
|
||||
for (UUID userId : clients.keySet()) {
|
||||
List<UUID> chatUserIds = new ArrayList<>();
|
||||
final Lock r = lock.readLock();
|
||||
r.lock();
|
||||
try {
|
||||
chatUserIds.addAll(clients.keySet());
|
||||
} finally {
|
||||
r.unlock();
|
||||
}
|
||||
for (UUID userId : chatUserIds) {
|
||||
Optional<User> user = UserManager.instance.getUser(userId);
|
||||
if (user.isPresent()) {
|
||||
user.get().fireCallback(clientCallback);
|
||||
|
|
@ -125,7 +150,15 @@ public class ChatSession {
|
|||
clientsToRemove.add(userId);
|
||||
}
|
||||
}
|
||||
clients.keySet().removeAll(clientsToRemove);
|
||||
if (!clientsToRemove.isEmpty()) {
|
||||
final Lock w = lock.readLock();
|
||||
w.lock();
|
||||
try {
|
||||
clients.keySet().removeAll(clientsToRemove);
|
||||
} finally {
|
||||
w.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -356,7 +356,7 @@ public class Session {
|
|||
} else {
|
||||
logger.error("SESSION LOCK - kill: userId " + userId);
|
||||
}
|
||||
UserManager.instance.removeUserFromAllTables(userId, reason);
|
||||
UserManager.instance.removeUserFromAllTablesAndChat(userId, reason);
|
||||
} catch (InterruptedException ex) {
|
||||
logger.error("SESSION LOCK - kill: userId " + userId, ex);
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -511,7 +511,7 @@ public class TableController {
|
|||
if (this.userId != null && this.userId.equals(userId) // tourn. sub tables have no creator user
|
||||
&& (table.getState() == TableState.WAITING
|
||||
|| table.getState() == TableState.READY_TO_START)) {
|
||||
// table not started yet and user is the owner, removeUserFromAllTables the table
|
||||
// table not started yet and user is the owner, removeUserFromAllTablesAndChat the table
|
||||
TableManager.instance.removeTable(table.getId());
|
||||
} else {
|
||||
UUID playerId = userPlayerMap.get(userId);
|
||||
|
|
@ -826,7 +826,7 @@ public class TableController {
|
|||
}
|
||||
user.showUserMessage("Match info", sb.toString());
|
||||
}
|
||||
// removeUserFromAllTables table from user - table manager holds table for display of finished matches
|
||||
// removeUserFromAllTablesAndChat table from user - table manager holds table for display of finished matches
|
||||
if (!table.isTournamentSubTable()) {
|
||||
user.removeTable(entry.getValue());
|
||||
}
|
||||
|
|
@ -913,7 +913,7 @@ public class TableController {
|
|||
return false;
|
||||
}
|
||||
} else {
|
||||
// check if table creator is still a valid user, if not removeUserFromAllTables table
|
||||
// check if table creator is still a valid user, if not removeUserFromAllTablesAndChat table
|
||||
return UserManager.instance.getUser(userId).isPresent();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ public enum TableManager {
|
|||
TableManager() {
|
||||
expireExecutor.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
ChatManager.instance.clearUserMessageStorage();
|
||||
checkTableHealthState();
|
||||
} catch (Exception ex) {
|
||||
logger.fatal("Check table health state job error:", ex);
|
||||
|
|
@ -161,7 +162,7 @@ public enum TableManager {
|
|||
}
|
||||
}
|
||||
|
||||
// removeUserFromAllTables user from all tournament sub tables
|
||||
// removeUserFromAllTablesAndChat user from all tournament sub tables
|
||||
public void userQuitTournamentSubTables(UUID userId) {
|
||||
for (TableController controller : controllers.values()) {
|
||||
if (controller.getTable() != null) {
|
||||
|
|
@ -174,7 +175,7 @@ public enum TableManager {
|
|||
}
|
||||
}
|
||||
|
||||
// removeUserFromAllTables user from all sub tables of a tournament
|
||||
// removeUserFromAllTablesAndChat user from all sub tables of a tournament
|
||||
public void userQuitTournamentSubTables(UUID tournamentId, UUID userId) {
|
||||
for (TableController controller : controllers.values()) {
|
||||
if (controller.getTable().isTournamentSubTable() && controller.getTable().getTournament().getId().equals(tournamentId)) {
|
||||
|
|
@ -386,8 +387,8 @@ public enum TableManager {
|
|||
for (Table table : tableCopy) {
|
||||
try {
|
||||
if (table.getState() != TableState.FINISHED
|
||||
&& ((System.currentTimeMillis() - table.getStartTime().getTime()) / 1000) > 30) { // removeUserFromAllTables only if table started longer than 30 seconds ago
|
||||
// removeUserFromAllTables tables and games not valid anymore
|
||||
&& ((System.currentTimeMillis() - table.getStartTime().getTime()) / 1000) > 30) { // removeUserFromAllTablesAndChat only if table started longer than 30 seconds ago
|
||||
// removeUserFromAllTablesAndChat 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" : ""));
|
||||
getController(table.getId()).ifPresent(tableController -> {
|
||||
if ((table.isTournament() && !tableController.isTournamentStillValid())
|
||||
|
|
|
|||
|
|
@ -29,6 +29,9 @@ package mage.server;
|
|||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import mage.server.User.UserState;
|
||||
import mage.server.record.UserStats;
|
||||
import mage.server.record.UserStatsRepository;
|
||||
|
|
@ -54,6 +57,7 @@ public enum UserManager {
|
|||
|
||||
private static final Logger LOGGER = Logger.getLogger(UserManager.class);
|
||||
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<>();
|
||||
|
||||
private static final ExecutorService USER_EXECUTOR = ThreadExecutor.instance.getCallExecutor();
|
||||
|
|
@ -69,7 +73,13 @@ public enum UserManager {
|
|||
return Optional.empty(); //user already exists
|
||||
}
|
||||
User user = new User(userName, host, authorizedUser);
|
||||
users.put(user.getId(), user);
|
||||
final Lock w = lock.writeLock();
|
||||
w.lock();
|
||||
try {
|
||||
users.put(user.getId(), user);
|
||||
} finally {
|
||||
w.unlock();
|
||||
}
|
||||
return Optional.of(user);
|
||||
}
|
||||
|
||||
|
|
@ -83,17 +93,32 @@ public enum UserManager {
|
|||
}
|
||||
|
||||
public Optional<User> getUserByName(String userName) {
|
||||
Optional<User> u = users.values().stream().filter(user -> user.getName().equals(userName))
|
||||
.findFirst();
|
||||
if (u.isPresent()) {
|
||||
return u;
|
||||
} else {
|
||||
return Optional.empty();
|
||||
final Lock r = lock.readLock();
|
||||
r.lock();
|
||||
try {
|
||||
Optional<User> u = users.values().stream().filter(user -> user.getName().equals(userName))
|
||||
.findFirst();
|
||||
if (u.isPresent()) {
|
||||
return u;
|
||||
} else {
|
||||
return Optional.empty();
|
||||
}
|
||||
} finally {
|
||||
r.unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Collection<User> getUsers() {
|
||||
return users.values();
|
||||
ArrayList<User> userList = new ArrayList<>();
|
||||
final Lock r = lock.readLock();
|
||||
r.lock();
|
||||
try {
|
||||
userList.addAll(users.values());
|
||||
} finally {
|
||||
r.unlock();
|
||||
}
|
||||
return userList;
|
||||
}
|
||||
|
||||
public boolean connectToSession(String sessionId, UUID userId) {
|
||||
|
|
@ -112,13 +137,10 @@ public enum UserManager {
|
|||
if (user.isPresent()) {
|
||||
user.get().setSessionId("");
|
||||
if (reason == DisconnectReason.Disconnected) {
|
||||
removeUserFromAllTables(userId, reason);
|
||||
removeUserFromAllTablesAndChat(userId, reason);
|
||||
user.get().setUserState(UserState.Offline);
|
||||
}
|
||||
}
|
||||
if (userId != null) {
|
||||
ChatManager.instance.removeUser(userId, reason);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAdmin(UUID userId) {
|
||||
|
|
@ -131,7 +153,7 @@ public enum UserManager {
|
|||
return false;
|
||||
}
|
||||
|
||||
public void removeUserFromAllTables(final UUID userId, final DisconnectReason reason) {
|
||||
public void removeUserFromAllTablesAndChat(final UUID userId, final DisconnectReason reason) {
|
||||
if (userId != null) {
|
||||
getUser(userId).ifPresent(user
|
||||
-> USER_EXECUTOR.execute(
|
||||
|
|
@ -139,6 +161,7 @@ public enum UserManager {
|
|||
try {
|
||||
LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + ']');
|
||||
user.removeUserFromAllTables(reason);
|
||||
ChatManager.instance.removeUser(user.getId(), reason);
|
||||
LOGGER.debug("USER REMOVE END - " + user.getName());
|
||||
} catch (Exception ex) {
|
||||
handleException(ex);
|
||||
|
|
@ -173,7 +196,16 @@ public enum UserManager {
|
|||
Calendar calendarRemove = Calendar.getInstance();
|
||||
calendarRemove.add(Calendar.MINUTE, -8);
|
||||
List<User> toRemove = new ArrayList<>();
|
||||
for (User user : users.values()) {
|
||||
logger.info("Start Check Expired");
|
||||
ArrayList<User> userList = new ArrayList<>();
|
||||
final Lock r = lock.readLock();
|
||||
r.lock();
|
||||
try {
|
||||
userList.addAll(users.values());
|
||||
} finally {
|
||||
r.unlock();
|
||||
}
|
||||
for (User user : userList) {
|
||||
try {
|
||||
if (user.getUserState() == UserState.Offline) {
|
||||
if (user.isExpired(calendarRemove.getTime())) {
|
||||
|
|
@ -185,7 +217,7 @@ public enum UserManager {
|
|||
user.lostConnection();
|
||||
disconnect(user.getId(), DisconnectReason.BecameInactive);
|
||||
}
|
||||
removeUserFromAllTables(user.getId(), DisconnectReason.SessionExpired);
|
||||
removeUserFromAllTablesAndChat(user.getId(), DisconnectReason.SessionExpired);
|
||||
user.setUserState(UserState.Offline);
|
||||
// Remove the user from all tournaments
|
||||
|
||||
|
|
@ -195,9 +227,17 @@ public enum UserManager {
|
|||
handleException(ex);
|
||||
}
|
||||
}
|
||||
for (User user : toRemove) {
|
||||
users.remove(user.getId());
|
||||
logger.info("Users to remove " + toRemove.size());
|
||||
final Lock w = lock.readLock();
|
||||
w.lock();
|
||||
try {
|
||||
for (User user : toRemove) {
|
||||
users.remove(user.getId());
|
||||
}
|
||||
} finally {
|
||||
w.unlock();
|
||||
}
|
||||
logger.info("End Check Expired");
|
||||
} catch (Exception ex) {
|
||||
handleException(ex);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -95,7 +95,7 @@ public class GamesRoomImpl extends RoomImpl implements GamesRoom, Serializable {
|
|||
} else if (matchList.size() < 50) {
|
||||
matchList.add(new MatchView(table));
|
||||
} else {
|
||||
// more since 50 matches finished since this match so removeUserFromAllTables it
|
||||
// more since 50 matches finished since this match so removeUserFromAllTablesAndChat it
|
||||
if (table.isTournament()) {
|
||||
TournamentManager.instance.removeTournament(table.getTournament().getId());
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue