Skip to content

Commit

Permalink
Make user tint more random
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurentTreguier committed Sep 15, 2024
1 parent b4aa23f commit 560e9ad
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/main/java/app/fyreplace/api/data/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@
import jakarta.ws.rs.NotAuthorizedException;
import jakarta.ws.rs.core.SecurityContext;
import java.awt.Color;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.CRC32;
import lombok.SneakyThrows;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
Expand Down Expand Up @@ -154,11 +155,12 @@ public boolean getBlocked() {
return Block.count("source = ?1 and target = ?2", currentUser, this) > 0;
}

@SneakyThrows
@Schema(required = true, pattern = "^#[A-F0-9]{6}$")
public String getTint() {
final var crc = new CRC32();
crc.update(username.getBytes());
final var hue = (float) (crc.getValue() / Math.pow(2, 32));
final var md5 = MessageDigest.getInstance("MD5");
final var digest = md5.digest(username.getBytes());
final var hue = bytesToFloat(digest);
final var h = hue * 6;
final var variance = (h - (float) Math.floor(h)) * 0.25f;
final var brightness = (int) h % 2 == 0 ? 1f - variance : 0.75f + variance;
Expand Down Expand Up @@ -261,6 +263,17 @@ public static User getFromSecurityContext(final SecurityContext context, @Nullab
return user;
}

private static float bytesToFloat(byte[] bytes) {
final var bytesToUse = Math.min(bytes.length, Long.BYTES);
var result = 0L;

for (var i = 0; i < bytesToUse; i++) {
result = (result << Byte.SIZE) | (bytes[i] & 0xFF);
}

return (float)Math.abs((double)result / Long.MAX_VALUE);
}

public enum Rank {
CITIZEN,
MODERATOR,
Expand Down

0 comments on commit 560e9ad

Please sign in to comment.