mirror of
https://github.com/correl/mage.git
synced 2024-12-29 19:15:06 +00:00
remove usermap by name, introduced more optionals
This commit is contained in:
parent
ddd226e60c
commit
334ad729a8
5 changed files with 132 additions and 140 deletions
|
@ -106,27 +106,28 @@ public enum ChatManager {
|
|||
ChatSession chatSession = chatSessions.get(chatId);
|
||||
if (chatSession != null) {
|
||||
if (message.startsWith("\\") || message.startsWith("/")) {
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (user != null) {
|
||||
if (!performUserCommand(user, message, chatId, false)) {
|
||||
performUserCommand(user, message, chatId, true);
|
||||
Optional<User> user = UserManager.instance.getUserByName(userName);
|
||||
if (user.isPresent()) {
|
||||
if (!performUserCommand(user.get(), message, chatId, false)) {
|
||||
performUserCommand(user.get(), message, chatId, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (messageType != MessageType.GAME) {
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (message != null && userName != null && !userName.isEmpty()) {
|
||||
Optional<User> u = UserManager.instance.getUserByName(userName);
|
||||
if (u.isPresent()) {
|
||||
|
||||
User user = u.get();
|
||||
if (message.equals(userMessages.get(userName))) {
|
||||
// prevent identical messages
|
||||
String informUser = "Your message appears to be identical to your last message";
|
||||
chatSessions.get(chatId).broadcastInfoToUser(user, informUser);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.length() > 500) {
|
||||
|
||||
if (message.length() > 500) {
|
||||
message = message.replaceFirst("^(.{500}).*", "$1 (rest of message truncated)");
|
||||
}
|
||||
|
||||
|
@ -157,10 +158,9 @@ public enum ChatManager {
|
|||
}
|
||||
|
||||
userMessages.put(userName, message);
|
||||
}
|
||||
|
||||
if (messageType == MessageType.TALK) {
|
||||
if (user != null) {
|
||||
|
||||
if (messageType == MessageType.TALK) {
|
||||
if (user.getChatLockedUntil() != null) {
|
||||
if (user.getChatLockedUntil().compareTo(Calendar.getInstance().getTime()) > 0) {
|
||||
chatSessions.get(chatId).broadcastInfoToUser(user, "Your chat is muted until " + SystemUtil.dateFormat.format(user.getChatLockedUntil()));
|
||||
|
@ -169,11 +169,12 @@ public enum ChatManager {
|
|||
user.setChatLockedUntil(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
chatSession.broadcast(userName, message, color, withTime, messageType, soundToPlay);
|
||||
}
|
||||
chatSession.broadcast(userName, message, color, withTime, messageType, soundToPlay);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -213,9 +214,9 @@ public enum ChatManager {
|
|||
if (first > 1) {
|
||||
String userToName = rest.substring(0, first);
|
||||
rest = rest.substring(first + 1).trim();
|
||||
User userTo = UserManager.instance.getUserByName(userToName);
|
||||
if (userTo != null) {
|
||||
if (!chatSessions.get(chatId).broadcastWhisperToUser(user, userTo, rest)) {
|
||||
Optional<User> userTo = UserManager.instance.getUserByName(userToName);
|
||||
if (userTo.isPresent()) {
|
||||
if (!chatSessions.get(chatId).broadcastWhisperToUser(user, userTo.get(), rest)) {
|
||||
message += new StringBuilder("<br/>User ").append(userToName).append(" not found").toString();
|
||||
chatSessions.get(chatId).broadcastInfoToUser(user, message);
|
||||
}
|
||||
|
@ -244,7 +245,7 @@ public enum ChatManager {
|
|||
* @param color
|
||||
*/
|
||||
public void broadcast(UUID userId, String message, MessageColor color) throws UserNotFoundException {
|
||||
UserManager.instance.getUser(userId).ifPresent(user-> {
|
||||
UserManager.instance.getUser(userId).ifPresent(user -> {
|
||||
chatSessions.values()
|
||||
.stream()
|
||||
.filter(chat -> chat.hasUser(userId))
|
||||
|
|
|
@ -1071,12 +1071,11 @@ public class MageServerImpl implements MageServer {
|
|||
@Override
|
||||
public void muteUser(final String sessionId, final String userName, final long durationMinutes) throws MageException {
|
||||
execute("muteUser", sessionId, () -> {
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (user != null) {
|
||||
UserManager.instance.getUserByName(userName).ifPresent(user -> {
|
||||
Date muteUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE));
|
||||
user.showUserMessage("Admin info", "You were muted for chat messages until " + SystemUtil.dateFormat.format(muteUntil) + '.');
|
||||
user.setChatLockedUntil(muteUntil);
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
|
@ -1084,15 +1083,14 @@ public class MageServerImpl implements MageServer {
|
|||
@Override
|
||||
public void lockUser(final String sessionId, final String userName, final long durationMinutes) throws MageException {
|
||||
execute("lockUser", sessionId, () -> {
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (user != null) {
|
||||
UserManager.instance.getUserByName(userName).ifPresent(user -> {
|
||||
Date lockUntil = new Date(Calendar.getInstance().getTimeInMillis() + (durationMinutes * Timer.ONE_MINUTE));
|
||||
user.showUserMessage("Admin info", "Your user profile was locked until " + SystemUtil.dateFormat.format(lockUntil) + '.');
|
||||
user.setLockedUntil(lockUntil);
|
||||
if (user.isConnected()) {
|
||||
SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
|
@ -1101,8 +1099,9 @@ public class MageServerImpl implements MageServer {
|
|||
public void setActivation(final String sessionId, final String userName, boolean active) throws MageException {
|
||||
execute("setActivation", sessionId, () -> {
|
||||
AuthorizedUser authorizedUser = AuthorizedUserRepository.instance.getByName(userName);
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (user != null) {
|
||||
Optional<User> u = UserManager.instance.getUserByName(userName);
|
||||
if (u.isPresent()) {
|
||||
User user = u.get();
|
||||
user.setActive(active);
|
||||
if (!user.isActive() && user.isConnected()) {
|
||||
SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
|
||||
|
@ -1117,16 +1116,14 @@ public class MageServerImpl implements MageServer {
|
|||
|
||||
@Override
|
||||
public void toggleActivation(final String sessionId, final String userName) throws MageException {
|
||||
execute("toggleActivation", sessionId, () -> {
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (user != null) {
|
||||
user.setActive(!user.isActive());
|
||||
if (!user.isActive() && user.isConnected()) {
|
||||
SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
execute("toggleActivation", sessionId, () ->
|
||||
UserManager.instance.getUserByName(userName).ifPresent(user ->
|
||||
{
|
||||
user.setActive(!user.isActive());
|
||||
if (!user.isActive() && user.isConnected()) {
|
||||
SessionManager.instance.disconnectUser(sessionId, user.getSessionId());
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -1144,13 +1141,10 @@ public class MageServerImpl implements MageServer {
|
|||
@Override
|
||||
public void removeTable(final String sessionId, final UUID tableId) throws MageException {
|
||||
execute("removeTable", sessionId, () -> {
|
||||
Optional<Session> session = SessionManager.instance.getSession(sessionId);
|
||||
if (!session.isPresent()) {
|
||||
logger.error("Session not found : " + sessionId);
|
||||
} else {
|
||||
UUID userId = session.get().getUserId();
|
||||
SessionManager.instance.getSession(sessionId).ifPresent(session -> {
|
||||
UUID userId = session.getUserId();
|
||||
TableManager.instance.removeTable(userId, tableId);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -1162,15 +1156,12 @@ public class MageServerImpl implements MageServer {
|
|||
@Override
|
||||
public void sendFeedbackMessage(final String sessionId, final String username, final String title, final String type, final String message, final String email) throws MageException {
|
||||
if (title != null && message != null) {
|
||||
execute("sendFeedbackMessage", sessionId, () -> {
|
||||
Optional<Session> session = SessionManager.instance.getSession(sessionId);
|
||||
if (!session.isPresent()) {
|
||||
logger.error(String.format("Session not found: %s", sessionId));
|
||||
} else {
|
||||
FeedbackServiceImpl.instance.feedback(username, title, type, message, email, session.get().getHost());
|
||||
execute("sendFeedbackMessage", sessionId, () ->
|
||||
SessionManager.instance.getSession(sessionId).ifPresent(
|
||||
session -> FeedbackServiceImpl.instance.feedback(username, title, type, message, email, session.getHost())
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -217,55 +217,59 @@ public class Session {
|
|||
if (authorizedUser.lockedUntil.compareTo(Calendar.getInstance().getTime()) > 0) {
|
||||
return "Your profile is deactivated until " + SystemUtil.dateFormat.format(authorizedUser.lockedUntil);
|
||||
} else {
|
||||
User user = UserManager.instance.createUser(userName, host, authorizedUser);
|
||||
if (user != null && authorizedUser.lockedUntil != null) {
|
||||
user.setLockedUntil(null);
|
||||
UserManager.instance.createUser(userName, host, authorizedUser).ifPresent(user ->
|
||||
user.setLockedUntil(null)
|
||||
);
|
||||
|
||||
}
|
||||
Optional<User> selectUser = UserManager.instance.createUser(userName, host, authorizedUser);
|
||||
boolean reconnect = false;
|
||||
if (!selectUser.isPresent()) { // user already exists
|
||||
selectUser = UserManager.instance.getUserByName(userName);
|
||||
if (selectUser.isPresent()) {
|
||||
User user = selectUser.get();
|
||||
// If authentication is not activated, check the identity using IP address.
|
||||
if (ConfigSettings.instance.isAuthenticationActivated() || user.getHost().equals(host)) {
|
||||
user.updateLastActivity(null); // minimizes possible expiration
|
||||
this.userId = user.getId();
|
||||
if (user.getSessionId().isEmpty()) {
|
||||
logger.info("Reconnecting session for " + userName);
|
||||
reconnect = true;
|
||||
} else {
|
||||
//disconnect previous session
|
||||
logger.info("Disconnecting another user instance: " + userName);
|
||||
SessionManager.instance.disconnect(user.getSessionId(), DisconnectReason.ConnectingOtherInstance);
|
||||
}
|
||||
} else {
|
||||
return "User name " + userName + " already in use (or your IP address changed)";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
User user = UserManager.instance.createUser(userName, host, authorizedUser);
|
||||
boolean reconnect = false;
|
||||
if (user == null) { // user already exists
|
||||
user = UserManager.instance.getUserByName(userName);
|
||||
// If authentication is not activated, check the identity using IP address.
|
||||
if (ConfigSettings.instance.isAuthenticationActivated() || user.getHost().equals(host)) {
|
||||
user.updateLastActivity(null); // minimizes possible expiration
|
||||
this.userId = user.getId();
|
||||
if (user.getSessionId().isEmpty()) {
|
||||
logger.info("Reconnecting session for " + userName);
|
||||
reconnect = true;
|
||||
} else {
|
||||
//disconnect previous session
|
||||
logger.info("Disconnecting another user instance: " + userName);
|
||||
SessionManager.instance.disconnect(user.getSessionId(), DisconnectReason.ConnectingOtherInstance);
|
||||
User user = selectUser.get();
|
||||
if (!UserManager.instance.connectToSession(sessionId, user.getId())) {
|
||||
return "Error connecting " + userName;
|
||||
}
|
||||
this.userId = user.getId();
|
||||
if (reconnect) { // must be connected to receive the message
|
||||
Optional<GamesRoom> room = GamesRoomManager.instance.getRoom(GamesRoomManager.instance.getMainRoomId());
|
||||
if (!room.isPresent()) {
|
||||
logger.error("main room not found");
|
||||
return null;
|
||||
}
|
||||
ChatManager.instance.joinChat(room.get().getChatId(), userId);
|
||||
ChatManager.instance.sendReconnectMessage(userId);
|
||||
}
|
||||
} else {
|
||||
return "User name " + userName + " already in use (or your IP address changed)";
|
||||
}
|
||||
}
|
||||
if (!UserManager.instance.connectToSession(sessionId, user.getId())) {
|
||||
return "Error connecting " + userName;
|
||||
}
|
||||
this.userId = user.getId();
|
||||
if (reconnect) { // must be connected to receive the message
|
||||
Optional<GamesRoom> room = GamesRoomManager.instance.getRoom(GamesRoomManager.instance.getMainRoomId());
|
||||
if (!room.isPresent()) {
|
||||
logger.error("main room not found");
|
||||
return null;
|
||||
}
|
||||
ChatManager.instance.joinChat(room.get().getChatId(), userId);
|
||||
ChatManager.instance.sendReconnectMessage(userId);
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public void connectAdmin() {
|
||||
this.isAdmin = true;
|
||||
User user = UserManager.instance.createUser("Admin", host, null);
|
||||
if (user == null) {
|
||||
user = UserManager.instance.getUserByName("Admin");
|
||||
}
|
||||
User user = UserManager.instance.createUser("Admin", host, null).orElse(
|
||||
UserManager.instance.getUserByName("Admin").get());
|
||||
|
||||
UserData adminUserData = UserData.getDefaultUserDataView();
|
||||
adminUserData.setGroupId(UserGroup.ADMIN.getGroupId());
|
||||
user.setUserData(adminUserData);
|
||||
|
@ -276,8 +280,8 @@ public class Session {
|
|||
}
|
||||
|
||||
public boolean setUserData(String userName, UserData userData, String clientVersion, String userIdStr) {
|
||||
User user = UserManager.instance.getUserByName(userName);
|
||||
if (user != null) {
|
||||
Optional<User> _user = UserManager.instance.getUserByName(userName);
|
||||
_user.ifPresent(user -> {
|
||||
if (clientVersion != null) {
|
||||
user.setClientVersion(clientVersion);
|
||||
}
|
||||
|
@ -294,9 +298,8 @@ public class Session {
|
|||
if (user.getUserData().getAvatarId() == 11) {
|
||||
user.getUserData().setAvatarId(updateAvatar(user.getName()));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return _user.isPresent();
|
||||
}
|
||||
|
||||
private int updateAvatar(String userName) {
|
||||
|
|
|
@ -51,7 +51,11 @@ public enum SessionManager {
|
|||
|
||||
public Optional<Session> getSession(@Nonnull String sessionId) {
|
||||
Session session = sessions.get(sessionId);
|
||||
if (session != null && session.getUserId() != null && UserManager.instance.getUser(session.getUserId()) == null) {
|
||||
if(session == null){
|
||||
logger.error("Session with sessionId " + sessionId + " is not found");
|
||||
return Optional.empty();
|
||||
}
|
||||
if (session.getUserId() != null && UserManager.instance.getUser(session.getUserId()) == null) {
|
||||
logger.error("User for session " + sessionId + " with userId " + session.getUserId() + " is missing. Session removed.");
|
||||
// can happen if user from same host signs in multiple time with multiple clients, after he disconnects with one client
|
||||
disconnect(sessionId, DisconnectReason.ConnectingOtherInstance);
|
||||
|
|
|
@ -42,7 +42,7 @@ import java.util.concurrent.*;
|
|||
*
|
||||
* @author BetaSteward_at_googlemail.com
|
||||
*/
|
||||
public enum UserManager {
|
||||
public enum UserManager {
|
||||
instance;
|
||||
|
||||
protected final ScheduledExecutorService expireExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||
|
@ -50,7 +50,6 @@ public enum UserManager {
|
|||
private static final Logger LOGGER = Logger.getLogger(UserManager.class);
|
||||
|
||||
private final ConcurrentHashMap<UUID, User> users = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, User> usersByName = new ConcurrentHashMap<>();
|
||||
|
||||
private static final ExecutorService USER_EXECUTOR = ThreadExecutor.getInstance().getCallExecutor();
|
||||
|
||||
|
@ -58,32 +57,36 @@ public enum UserManager {
|
|||
expireExecutor.scheduleAtFixedRate(this::checkExpired, 60, 60, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public User createUser(String userName, String host, AuthorizedUser authorizedUser) {
|
||||
if (getUserByName(userName) != null) {
|
||||
return null; //user already exists
|
||||
public Optional<User> createUser(String userName, String host, AuthorizedUser authorizedUser) {
|
||||
if (getUserByName(userName).isPresent()) {
|
||||
return Optional.empty(); //user already exists
|
||||
}
|
||||
User user = new User(userName, host, authorizedUser);
|
||||
users.put(user.getId(), user);
|
||||
usersByName.put(userName, user);
|
||||
return user;
|
||||
return Optional.of(user);
|
||||
}
|
||||
|
||||
public Optional<User> getUser(UUID userId) {
|
||||
if (users.get(userId) == null) {
|
||||
if (!users.containsKey(userId)) {
|
||||
LOGGER.error(String.format("User with id %s could not be found", userId));
|
||||
|
||||
return Optional.empty();
|
||||
} else {
|
||||
return Optional.of(users.get(userId));
|
||||
}
|
||||
/* if (userId != null) {
|
||||
return users.get(userId);
|
||||
}
|
||||
return null;
|
||||
*/
|
||||
}
|
||||
|
||||
public User getUserByName(String userName) {
|
||||
return usersByName.get(userName);
|
||||
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 {
|
||||
|
||||
LOGGER.error("User with name " + userName + " could not be found");
|
||||
return Optional.empty();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<User> getUsers() {
|
||||
|
@ -103,12 +106,9 @@ public enum UserManager {
|
|||
|
||||
public void disconnect(UUID userId, DisconnectReason reason) {
|
||||
if (userId != null) {
|
||||
User user = users.get(userId);
|
||||
if (user != null) {
|
||||
user.setSessionId(""); // Session will be set again with new id if user reconnects
|
||||
}
|
||||
ChatManager.instance.removeUser(userId, reason);
|
||||
getUser(userId).ifPresent(user -> user.setSessionId(""));// Session will be set again with new id if user reconnects
|
||||
}
|
||||
ChatManager.instance.removeUser(userId, reason);
|
||||
}
|
||||
|
||||
public boolean isAdmin(UUID userId) {
|
||||
|
@ -123,25 +123,21 @@ public enum UserManager {
|
|||
|
||||
public void removeUser(final UUID userId, final DisconnectReason reason) {
|
||||
if (userId != null) {
|
||||
final User user = users.get(userId);
|
||||
if (user != null) {
|
||||
USER_EXECUTOR.execute(
|
||||
() -> {
|
||||
try {
|
||||
LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + ']');
|
||||
user.remove(reason);
|
||||
LOGGER.debug("USER REMOVE END - " + user.getName());
|
||||
} catch (Exception ex) {
|
||||
handleException(ex);
|
||||
} finally {
|
||||
users.remove(userId);
|
||||
usersByName.remove(user.getName());
|
||||
getUser(userId).ifPresent(user ->
|
||||
USER_EXECUTOR.execute(
|
||||
() -> {
|
||||
try {
|
||||
LOGGER.info("USER REMOVE - " + user.getName() + " (" + reason.toString() + ") userId: " + userId + " [" + user.getGameInfo() + ']');
|
||||
user.remove(reason);
|
||||
LOGGER.debug("USER REMOVE END - " + user.getName());
|
||||
} catch (Exception ex) {
|
||||
handleException(ex);
|
||||
} finally {
|
||||
users.remove(userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
} else {
|
||||
LOGGER.warn("Trying to remove userId: " + userId + " - but it does not exist.");
|
||||
}
|
||||
));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -183,9 +179,9 @@ public enum UserManager {
|
|||
}
|
||||
|
||||
public String getUserHistory(String userName) {
|
||||
User user = getUserByName(userName);
|
||||
if (user != null) {
|
||||
return "History of user " + userName + " - " + user.getUserData().getHistory();
|
||||
Optional<User> user = getUserByName(userName);
|
||||
if (user.isPresent()) {
|
||||
return "History of user " + userName + " - " + user.get().getUserData().getHistory();
|
||||
}
|
||||
|
||||
UserStats userStats = UserStatsRepository.instance.getUser(userName);
|
||||
|
@ -199,10 +195,7 @@ public enum UserManager {
|
|||
public void updateUserHistory() {
|
||||
USER_EXECUTOR.execute(() -> {
|
||||
for (String updatedUser : UserStatsRepository.instance.updateUserStats()) {
|
||||
User user = getUserByName(updatedUser);
|
||||
if (user != null) {
|
||||
user.resetUserStats();
|
||||
}
|
||||
getUserByName(updatedUser).ifPresent(User::resetUserStats);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue