001package net.tnemc.plugincore.core.id;
002
003/*
004 * This class provides UUID-related functions, and has a concept of
005 * "live" UUIDs and "stored" UUIDs.
006 *
007 * live UUIDs are any UUID that is directly associated with a Player account.
008 *
009 * stored UUIDs are any UUID that is generated for use inside the plugin
010 * only. This could be a fake account related to an NPC account, or related
011 * to a name that has never been registered on Minecraft.net.
012 */
013
014import java.nio.charset.StandardCharsets;
015import java.util.Optional;
016import java.util.UUID;
017
018import static net.tnemc.plugincore.core.utils.PlayerHelper.playerMatcher;
019
020/**
021 * Represents a provider that is used to resolve and store UUID<->Username Pairs.
022 *
023 * @author creatorfromhell
024 * @since 0.1.2.0
025 */
026public interface UUIDProvider {
027
028  /**
029   * Used to determine if a string is a valid minecraft username or not.
030   *
031   * @param name The name to check.
032   *
033   * @return True if the name is a valid minecraft username, otherwise false.
034   */
035  static boolean validate(final String name) {
036
037    if(name.length() >= 3 && name.length() <= 16) {
038      return playerMatcher().matcher(name).matches();
039    }
040    return false;
041  }
042
043  /**
044   * Used to determine if a string is a valid UUID.
045   *
046   * @param identifier The string to check.
047   *
048   * @return True if the name is a valid UUID, otherwise false.
049   */
050  static boolean isUUID(final String identifier) {
051
052    try {
053      UUID.fromString(identifier);
054      return true;
055    } catch(Exception ignore) {
056      return false;
057    }
058  }
059
060  /**
061   * Returns the associated {@link UUIDAPI uuid api} associated with this provider.
062   *
063   * @return The associated {@link UUIDAPI uuid api} associated with this provider.
064   *
065   * @see UUIDAPI
066   */
067  UUIDAPI api();
068
069  /**
070   * Used to retrieve a {@link UUIDPair}.
071   *
072   * @param name The username of the pair.
073   *
074   * @return An optional containing the pair if found, otherwise an empty optional.
075   */
076  Optional<UUIDPair> retrieve(final String name);
077
078  /**
079   * Used to retrieve a name from its associated {@link UUID}.
080   *
081   * @param id The {@link UUID} to use in the search.
082   *
083   * @return An optional containing the name if found, otherwise an empty optional.
084   */
085  Optional<String> retrieveName(final UUID id);
086
087  /**
088   * Used to store a Username & UUID pair. This could be to a map, or to a database for persistent
089   * usage or to both.
090   *
091   * @param pair The {@link UUIDPair}
092   */
093  void store(final UUIDPair pair);
094
095  default UUID generateOffline(final String name) {
096
097    return UUID.nameUUIDFromBytes(("Offline:" + name).getBytes(StandardCharsets.UTF_8));
098  }
099}