Improves username login/logout checking by using a proper regex match

Additionally, this commit fixes a bug where instead of Username, users are shown as Username[IP:PORT]
This commit is contained in:
Kristian Knarvik 2021-01-28 03:08:10 +01:00
parent a4d7b1041c
commit b1454b1156

View File

@ -19,6 +19,8 @@ import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.knarcraft.minecraftserverlauncher.utility.CommonFunctions.stringBetween;
@ -461,23 +463,43 @@ public class Server {
*/
private String getPlayer(String text, boolean joined) {
String playerName;
String loginPattern1 = " ([A-Z0-9a-z]+)\\[/[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+:[0-9]+] logged in";
String loginPattern2 = "UUID of player ([A-Z0-9a-z]+) is";
String logoutPattern1 = "INFO]: ([A-Z0-9a-z]+) lost connection";
String logoutPattern2 = " ([A-Z0-9a-z]+) left the game";
if (joined) {
playerName = stringBetween(text, "[Server thread/INFO]: ", " joined the game");
playerName = getFirstRegexCaptureGroup(loginPattern1, text);
if (playerName.equals("")) {
playerName = stringBetween(text, "UUID of player ", " is ");
playerName = getFirstRegexCaptureGroup(loginPattern2, text);
}
} else {
playerName = stringBetween(text, "INFO]: ", " lost connection");
playerName = getFirstRegexCaptureGroup(logoutPattern1, text);
if (playerName.equals("")) {
playerName = stringBetween(text, "[Server thread/INFO]: ", " left the game");
}
if (playerName.equals("")) {
playerName = stringBetween(text, "INFO]: ", " left the game");
playerName = getFirstRegexCaptureGroup(logoutPattern2, text);
}
}
return playerName;
}
/**
* Returns the first regex capture group found in a pattern
* @param pattern <p>The regex pattern to use.</p>
* @param text <p>The string to execute the pattern on.</p>
* @return <p>The first capture group if a match is found. An empty string otherwise.</p>
*/
private String getFirstRegexCaptureGroup(String pattern, String text) {
Pattern compiledPattern = Pattern.compile(pattern);
Matcher patternMatcher = compiledPattern.matcher(text);
if (patternMatcher.find()) {
return patternMatcher.group(1);
} else {
return "";
}
}
/**
* Delays the server's startup for the given amount of time
*