Allow setting a username with explicit descriminator

Fixes #1469
This commit is contained in:
AsamK 2024-02-22 19:59:19 +01:00
parent 0bb2a64781
commit 83d471818d
3 changed files with 32 additions and 3 deletions

View file

@ -321,21 +321,42 @@ public class AccountHelper {
public static final int USERNAME_MIN_LENGTH = 3;
public static final int USERNAME_MAX_LENGTH = 32;
public void reserveUsername(String nickname) throws IOException, BaseUsernameException {
public void reserveUsernameFromNickname(String nickname) throws IOException, BaseUsernameException {
final var currentUsername = account.getUsername();
if (currentUsername != null) {
final var currentNickname = currentUsername.substring(0, currentUsername.indexOf('.'));
if (currentNickname.equals(nickname)) {
try {
refreshCurrentUsername();
return;
} catch (IOException | BaseUsernameException e) {
logger.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
}
return;
}
}
final var candidates = Username.candidatesFrom(nickname, USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH);
reserveUsername(candidates);
}
public void reserveExactUsername(String username) throws IOException, BaseUsernameException {
final var currentUsername = account.getUsername();
if (currentUsername != null) {
if (currentUsername.equals(username)) {
try {
refreshCurrentUsername();
return;
} catch (IOException | BaseUsernameException e) {
logger.warn("[reserveUsername] Failed to refresh current username, trying to claim new username");
}
}
}
final var candidates = List.of(new Username(username));
reserveUsername(candidates);
}
private void reserveUsername(final List<Username> candidates) throws IOException {
final var candidateHashes = new ArrayList<String>();
for (final var candidate : candidates) {
candidateHashes.add(Base64.encodeUrlSafeWithoutPadding(candidate.getHash()));

View file

@ -361,7 +361,11 @@ public class ManagerImpl implements Manager {
@Override
public void setUsername(final String username) throws IOException, InvalidUsernameException {
try {
context.getAccountHelper().reserveUsername(username);
if (username.contains(".")) {
context.getAccountHelper().reserveExactUsername(username);
} else {
context.getAccountHelper().reserveUsernameFromNickname(username);
}
} catch (BaseUsernameException e) {
throw new InvalidUsernameException(e.getMessage() + " (" + e.getClass().getSimpleName() + ")", e);
}