| 1 | package net.minecraft.server.players;
|
| 2 |
|
| 3 | import com.google.common.cache.CacheBuilder;
|
| 4 | import com.google.common.cache.CacheLoader;
|
| 5 | import com.google.common.cache.LoadingCache;
|
| 6 | import com.mojang.authlib.GameProfile;
|
| 7 | import com.mojang.authlib.minecraft.SessionService;
|
| 8 | import com.mojang.authlib.services.ProfileResult;
|
| 9 | import com.mojang.datafixers.util.Either;
|
| 10 | import java.time.Duration;
|
| 11 | import java.util.Optional;
|
| 12 | import java.util.UUID;
|
| 13 | import net.minecraft.util.StringUtil;
|
| 14 |
|
| 15 | public interface ProfileResolver {
|
| 16 | Optional<GameProfile> fetchByName(String name);
|
| 17 |
|
| 18 | Optional<GameProfile> fetchById(UUID id);
|
| 19 |
|
| 20 | default Optional<GameProfile> fetchByNameOrId(final Either<String, UUID> nameOrId) {
|
| 21 | return nameOrId.map(this::fetchByName, this::fetchById);
|
| 22 | }
|
| 23 |
|
| 24 | class Cached implements ProfileResolver {
|
| 25 | private final LoadingCache<String, Optional<GameProfile>> profileCacheByName;
|
| 26 | private final LoadingCache<UUID, Optional<GameProfile>> profileCacheById;
|
| 27 |
|
| 28 | public Cached(final SessionService sessionService, final UserNameToIdResolver nameToIdCache) {
|
| 29 | this.profileCacheById = CacheBuilder.newBuilder()
|
| 30 | .expireAfterAccess(Duration.ofMinutes(10L))
|
| 31 | .maximumSize(256L)
|
| 32 | .build(new CacheLoader<UUID, Optional<GameProfile>>() {
|
| 33 | public Optional<GameProfile> load(final UUID profileId) {
|
| 34 | ProfileResult result = sessionService.fetchProfile(profileId, true);
|
| 35 | return Optional.ofNullable(result).map(ProfileResult::profile);
|
| 36 | }
|
| 37 | });
|
| 38 | this.profileCacheByName = CacheBuilder.newBuilder()
|
| 39 | .expireAfterAccess(Duration.ofMinutes(10L))
|
| 40 | .maximumSize(256L)
|
| 41 | .build(new CacheLoader<String, Optional<GameProfile>>() {
|
| 42 | public Optional<GameProfile> load(final String name) {
|
| 43 | return nameToIdCache.get(name).flatMap(nameAndId -> Cached.this.profileCacheById.getUnchecked(nameAndId.id()));
|
| 44 | }
|
| 45 | });
|
| 46 | }
|
| 47 |
|
| 48 | @Override
|
| 49 | public Optional<GameProfile> fetchByName(final String name) {
|
| 50 | return StringUtil.isValidPlayerName(name) ? this.profileCacheByName.getUnchecked(name) : Optional.empty();
|
| 51 | }
|
| 52 |
|
| 53 | @Override
|
| 54 | public Optional<GameProfile> fetchById(final UUID id) {
|
| 55 | return this.profileCacheById.getUnchecked(id);
|
| 56 | }
|
| 57 | }
|
| 58 | }
|
| 59 |
|