Java Code Examples for org.spongepowered.api.profile.GameProfile

The following examples show how to use org.spongepowered.api.profile.GameProfile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: SkinsRestorerX   Source File: LoginListener.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handle(Auth e) {
    if (e.isCancelled())
        return;

    if (Config.DISABLE_ONJOIN_SKINS)
        return;

    GameProfile profile = e.getProfile();

    profile.getName().ifPresent(name -> {
        try {
            // Don't change skin if player has no custom skin-name set and his username is invalid
            if (plugin.getSkinStorage().getPlayerSkin(name) == null && !C.validUsername(name)) {
                System.out.println("[SkinsRestorer] Not applying skin to " + name + " (invalid username).");
                return;
            }

            String skin = plugin.getSkinStorage().getDefaultSkinNameIfEnabled(name);
            plugin.getSkinApplier().updateProfileSkin(profile, skin);
        } catch (SkinRequestException ignored) {
        }
    });
}
 
Example 2
@Listener
public void onClientConnectionJoin(ClientConnectionEvent.Join event)
{
    Server server = Sponge.getServer();
    if (server.getOnlineMode())
    {
        // prefetch the profile when a player joins the server
        // TODO: maybe we should also prefetch player profiles in offline mode
        GameProfile profile = event.getTargetEntity().getProfile();
        server.getGameProfileManager().fill(profile).thenRun(() ->
        {
            String message = "Successfully loaded the game profile for {} (player {})";
            this.logger.debug(message, profile.getUniqueId(), profile.getName().orElse("null"));
        });
    }
}
 
Example 3
Source Project: GriefPrevention   Source File: GriefPreventionPlugin.java    License: MIT License 6 votes vote down vote up
public static User getOrCreateUser(UUID uuid) {
    if (uuid == null) {
        return null;
    }

    if (uuid == WORLD_USER_UUID) {
        return WORLD_USER;
    }

    // check the cache
    Optional<User> player = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(uuid);
    if (player.isPresent()) {
        return player.get();
    } else {
        try {
            GameProfile gameProfile = Sponge.getServer().getGameProfileManager().get(uuid).get();
            return Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().getOrCreate(gameProfile);
        } catch (Exception e) {
            return null;
        }
    }
}
 
Example 4
Source Project: ChangeSkin   Source File: LoginListener.java    License: MIT License 6 votes vote down vote up
@Listener
public void onPlayerPreLogin(ClientConnectionEvent.Auth preLoginEvent) {
    SkinStorage storage = core.getStorage();
    GameProfile profile = preLoginEvent.getProfile();
    UUID playerUUID = profile.getUniqueId();

    UserPreference preferences = storage.getPreferences(playerUUID);
    Optional<SkinModel> optSkin = preferences.getTargetSkin();
    if (optSkin.isPresent()) {
        SkinModel targetSkin = optSkin.get();
        if (!preferences.isKeepSkin()) {
            targetSkin = core.checkAutoUpdate(targetSkin);
        }

        plugin.getApi().applyProperties(profile, targetSkin);
        save(preferences);
    } else {
        String playerName = profile.getName().get();
        if (!core.getConfig().getBoolean("restoreSkins") || !refetchSkin(playerName, preferences)) {
            setDefaultSkin(preferences, profile);
        }
    }
}
 
Example 5
Source Project: UltimateCore   Source File: UnbanCommand.java    License: MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    GameProfile profile = args.<GameProfile>getOne("player").orElse(null);
    InetAddress address = args.<InetAddress>getOne("ip").orElse(null);

    //Unban user + Send message
    BanService bs = Sponge.getServiceManager().provide(BanService.class).get();
    if (profile != null && bs.getBanFor(profile).isPresent()) {
        bs.removeBan(bs.getBanFor(profile).get());
        Messages.send(src, "ban.command.unban.success", "%player%", profile.getName().orElse(""));
        return CommandResult.success();
    }
    if (address != null && bs.getBanFor(address).isPresent()) {
        bs.removeBan(bs.getBanFor(address).get());
        Messages.send(src, "ban.command.unban.success-ip", "%ip%", address.toString().replace("/", ""));
        return CommandResult.success();
    }

    //Not banned
    throw Messages.error(src, "ban.command.unban.notbanned");
}
 
Example 6
Source Project: UltimateCore   Source File: IpCommand.java    License: MIT License 6 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    String ip;
    GameProfile profile = args.<GameProfile>getOne("player").get();

    if (UltimateCore.get().getUserService().getUser(profile).get().getUser().isOnline()) {
        Player p = UltimateCore.get().getUserService().getUser(profile).get().getUser().getPlayer().get();
        ip = p.getConnection().getAddress().getAddress().toString().replace("/", "");
    } else {
        PlayerDataFile config = new PlayerDataFile(profile.getUniqueId());
        CommentedConfigurationNode node = config.get();
        ip = node.getNode("lastip").getString();
    }

    Messages.send(src, "ban.command.ip.success", "%player%", profile.getName().orElse(""), "%ip%", ip);
    return CommandResult.success();
}
 
Example 7
Source Project: UltimateCore   Source File: UserArgument.java    License: MIT License 6 votes vote down vote up
@Nullable
@Override
public User parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
    String player = args.next();
    Optional<Player> t = Selector.one(source, player);
    if (t.isPresent()) {
        return t.get();
    } else {
        try {
            UserStorageService service = Sponge.getServiceManager().provide(UserStorageService.class).get();
            GameProfile profile = Sponge.getServer().getGameProfileManager().get(player).get();
            return service.get(profile).get();
        } catch (Exception ex) {
            throw args.createError(Messages.getFormatted("core.playernotfound", "%player%", player));
        }
    }
}
 
Example 8
Source Project: UltimateCore   Source File: GameprofileArgument.java    License: MIT License 6 votes vote down vote up
@Nullable
@Override
public GameProfile parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
    //Try online player
    String player = args.next();
    Optional<Player> t = Selector.one(source, player);
    if (t.isPresent()) {
        return t.get().getProfile();
    } else {
        try {
            return Sponge.getServer().getGameProfileManager().get(player).get();
        } catch (Exception e) {
            throw args.createError(Messages.getFormatted("core.playernotfound", "%player%", player));
        }
    }
}
 
Example 9
Source Project: Prism   Source File: DataUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Helper method to translate Player UUIDs to names.
 *
 * @param results List of results
 * @param uuidsPendingLookup Lists of UUIDs pending lookup
 * @return CompletableFuture
 */
public static CompletableFuture<List<Result>> translateUuidsToNames(List<Result> results, List<UUID> uuidsPendingLookup) {
    CompletableFuture<List<Result>> future = new CompletableFuture<>();

    CompletableFuture<Collection<GameProfile>> futures = Sponge.getServer().getGameProfileManager().getAllById(uuidsPendingLookup, true);
    futures.thenAccept((profiles) -> {
        for (GameProfile profile : profiles) {
            for (Result r : results) {
                Optional<Object> cause = r.data.get(DataQueries.Cause);
                if (cause.isPresent() && cause.get().equals(profile.getUniqueId().toString())) {
                    r.data.set(DataQueries.Cause, profile.getName().orElse("unknown"));
                }
            }
        }

        future.complete(results);
    });

    return future;
}
 
Example 10
Source Project: SkinsRestorerX   Source File: SkinApplier.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void updateProfileSkin(GameProfile profile, String skin) throws SkinRequestException {
    try {
        // Todo: new function for this duplicated code
        Property textures = (Property) plugin.getSkinStorage().getOrCreateSkinForPlayer(skin);
        Collection<ProfileProperty> oldProperties = profile.getPropertyMap().get("textures");
        ProfileProperty newTextures = Sponge.getServer().getGameProfileManager().createProfileProperty("textures", textures.getValue(), textures.getSignature());
        oldProperties.clear();
        oldProperties.add(newTextures);
    } catch (SkinRequestException e) {
        e.printStackTrace();
    }
}
 
Example 11
VirtualChestItemStackSerializer(VirtualChestPlugin plugin)
{
    this.plugin = plugin;
    this.serializers = TypeSerializers.getDefaultSerializers().newChild()
            .registerType(TypeToken.of(Text.class), TEXT_SERIALIZER)
            .registerType(ITEM_ENCHANTMENT, ITEM_ENCHANTMENT_SERIALIZER)
            .registerType(TypeToken.of(GameProfile.class), GAME_PROFILE_SERIALIZER);
}
 
Example 12
private Optional<GameProfile> getNullGameProfile()
{
    // noinspection ConstantConditions
    return ItemStack.builder()
            .itemType(ItemTypes.SKULL).quantity(1)
            .add(Keys.SKULL_TYPE, SkullTypes.PLAYER).build()
            .getOrCreate(RepresentedPlayerData.class).map(data -> data.owner().get());
}
 
Example 13
private static GameProfile getFilledGameProfileOrElseFallback(GameProfile profile)
{
    if (!IS_ONLINE_MODE_ENABLED)
    {
        return profile; // TODO: maybe we should also load player skins in offline mode
    }
    try
    {
        return GAME_PROFILE_MANAGER.fill(profile).get(50, TimeUnit.MILLISECONDS); // TODO: asynchronous action
    }
    catch (InterruptedException | ExecutionException | TimeoutException e)
    {
        return profile;
    }
}
 
Example 14
@Override
public GameProfile deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException
{
    String name = value.getNode(KEY_NAME).getString(), uuid = value.getNode(KEY_UUID).getString();
    if (Objects.isNull(uuid))
    {
        return this.nullProfile.orElseThrow(() -> new ObjectMappingException("Empty profile is not allowed"));
    }
    return getFilledGameProfileOrElseFallback(GameProfile.of(getUUIDByString(uuid), name));
}
 
Example 15
@Override
public void serialize(TypeToken<?> type, GameProfile p, ConfigurationNode value) throws ObjectMappingException
{
    if (!Objects.isNull(p) && !(nullProfile.isPresent() && nullProfile.get().equals(p)))
    {
        value.getNode(KEY_UUID).setValue(p.getUniqueId());
        p.getName().ifPresent(name -> value.getNode(KEY_NAME).setValue(name));
    }
}
 
Example 16
private boolean isBanned(GameProfile profile) {
    Optional<ProviderRegistration<BanService>> banService = Sponge.getServiceManager().getRegistration(BanService.class);
    boolean banned = false;
    if (banService.isPresent()) {
        banned = banService.get().getProvider().isBanned(profile);
    }
    return banned;
}
 
Example 17
Source Project: LuckPerms   Source File: LPSpongeBootstrap.java    License: MIT License 5 votes vote down vote up
@Override
public Optional<String> lookupUsername(UUID uniqueId) {
    return getServer().flatMap(server -> server.getGameProfileManager().get(uniqueId)
            .thenApply(GameProfile::getName)
            .exceptionally(x -> Optional.empty())
            .join()
    );
}
 
Example 18
Source Project: LuckPerms   Source File: SpongeConnectionListener.java    License: MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST)
@IsCancelled(Tristate.UNDEFINED)
public void onClientLogin(ClientConnectionEvent.Login e) {
    /* Called when the player starts logging into the server.
       At this point, the users data should be present and loaded.
       Listening on LOW priority to allow plugins to further modify data here. (auth plugins, etc.) */

    final GameProfile profile = e.getProfile();

    if (this.plugin.getConfiguration().get(ConfigKeys.DEBUG_LOGINS)) {
        this.plugin.getLogger().info("Processing login event for " + profile.getUniqueId() + " - " + profile.getName());
    }

    final User user = this.plugin.getUserManager().getIfLoaded(profile.getUniqueId());

    /* User instance is null for whatever reason. Could be that it was unloaded between asyncpre and now. */
    if (user == null) {
        this.deniedLogin.add(profile.getUniqueId());

        if (!getUniqueConnections().contains(profile.getUniqueId())) {
            this.plugin.getLogger().warn("User " + profile.getUniqueId() + " - " + profile.getName() +
                    " doesn't have data pre-loaded, they have never been processed during pre-login in this session." +
                    " - denying login.");
        } else {
            this.plugin.getLogger().warn("User " + profile.getUniqueId() + " - " + profile.getName() +
                    " doesn't currently have data pre-loaded, but they have been processed before in this session." +
                    " - denying login.");
        }

        e.setCancelled(true);
        e.setMessageCancelled(false);
        //noinspection deprecation
        e.setMessage(TextSerializers.LEGACY_FORMATTING_CODE.deserialize(Message.LOADING_STATE_ERROR.asString(this.plugin.getLocaleManager())));
    }
}
 
Example 19
Source Project: EssentialCmds   Source File: UserParser.java    License: MIT License 5 votes vote down vote up
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException
{
	String user = args.next();

	// Check for exact match from the GameProfile service first.
	UserStorageService uss = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get();
	Optional<GameProfile> ogp = uss.getAll().stream().filter(f -> f.getName().isPresent() && f.getName().get()
		.equalsIgnoreCase(user)).findFirst();
	if (ogp.isPresent())
	{
		Optional<User> retUser = uss.get(ogp.get());
		if (retUser.isPresent())
		{
			return retUser.get();
		}
	}

	// No match. Check against all online players only.
	List<User> listUser = Sponge.getGame().getServer().getOnlinePlayers().stream()
		.filter(x -> x.getName().toLowerCase().startsWith(user.toLowerCase())).collect(Collectors.toList());
	if (listUser.isEmpty())
	{
		throw args.createError(Text.of(TextColors.RED, "Could not find user with the name " + user));
	}

	if (listUser.size() == 1)
	{
		return listUser.get(0);
	}

	return listUser;
}
 
Example 20
@Override
public UUID getUUID(String name) {
    try {
        GameProfileManager pm = Sponge.getServer().getGameProfileManager();
        GameProfile profile = pm.get(name).get();
        return profile != null ? profile.getUniqueId() : null;
    } catch (Exception e) {
        return null;
    }
}
 
Example 21
@Override
public String getName(UUID uuid) {
    try {
        GameProfileManager pm = Sponge.getServer().getGameProfileManager();
        GameProfile profile = pm.get(uuid).get();
        return profile != null ? profile.getName().orElse(null) : null;
    } catch (Exception e) {
        return null;
    }
}
 
Example 22
@Override
public UUID getUUID(String name) {
    try {
        GameProfileManager pm = Sponge.getServer().getGameProfileManager();
        GameProfile profile = pm.get(name).get();
        return profile != null ? profile.getUniqueId() : null;
    } catch (Exception e) {
        return null;
    }
}
 
Example 23
@Override
public String getName(UUID uuid) {
    try {
        GameProfileManager pm = Sponge.getServer().getGameProfileManager();
        GameProfile profile = pm.get(uuid).get();
        return profile != null ? profile.getName().orElse(null) : null;
    } catch (Exception e) {
        return null;
    }
}
 
Example 24
Source Project: RedProtect   Source File: RedProtectUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String PlayerToUUID(@Nonnull String playerName) {
    if (playerName.isEmpty()) return null;

    //check if is already UUID
    if (isUUIDs(playerName) || isDefaultServer(playerName) || (playerName.startsWith("[") && playerName.endsWith("]"))) {
        return playerName;
    }

    if (cachedUUIDs.containsValue(playerName)) {
        return cachedUUIDs.entrySet().stream().filter(e -> e.getValue().equalsIgnoreCase(playerName)).findFirst().get().getKey();
    }

    String uuid = playerName;

    UserStorageService uss = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get();

    Optional<GameProfile> ogpName = uss.getAll().stream().filter(f -> f.getName().isPresent() && f.getName().get().equalsIgnoreCase(playerName)).findFirst();
    if (ogpName.isPresent()) {
        uuid = ogpName.get().getUniqueId().toString();
    } else {
        Optional<Player> p = RedProtect.get().getServer().getPlayer(playerName);
        if (p.isPresent()) {
            uuid = p.get().getUniqueId().toString();
        }
    }

    cachedUUIDs.put(uuid, playerName);
    return uuid;
}
 
Example 25
Source Project: ChangeSkin   Source File: LoginListener.java    License: MIT License 5 votes vote down vote up
private void setDefaultSkin(UserPreference preferences, GameProfile profile) {
    Optional<SkinModel> randomSkin = getRandomSkin();
    if (randomSkin.isPresent()) {
        SkinModel targetSkin = randomSkin.get();
        preferences.setTargetSkin(targetSkin);
        plugin.getApi().applyProperties(profile, targetSkin);
    }
}
 
Example 26
Source Project: ChangeSkin   Source File: SpongeSkinAPI.java    License: MIT License 5 votes vote down vote up
@Override
public void applyProperties(GameProfile profile, SkinModel targetSkin) {
    //remove existing skins
    profile.getPropertyMap().clear();

    if (targetSkin != null) {
        GameProfileManager profileManager = Sponge.getServer().getGameProfileManager();
        ProfileProperty profileProperty = profileManager.createProfileProperty(SkinProperty.SKIN_KEY
                , targetSkin.getEncodedValue(), targetSkin.getSignature());
        profile.getPropertyMap().put(SkinProperty.SKIN_KEY, profileProperty);
    }
}
 
Example 27
Source Project: FlexibleLogin   Source File: ConnectionListener.java    License: MIT License 5 votes vote down vote up
@Listener(order = Order.FIRST)
public void verifyPlayerName(Auth authEvent, @First GameProfile profile) {
    if (!namePredicate.test(profile.getName().get())) {
        //validate invalid characters
        authEvent.setMessage(settings.getText().getInvalidUsername());
        authEvent.setCancelled(true);
    }
}
 
Example 28
Source Project: FlexibleLogin   Source File: ConnectionListener.java    License: MIT License 5 votes vote down vote up
@Listener(order = Order.EARLY)
public void checkAlreadyOnline(Auth authEvent, @First GameProfile profile) {
    String playerName = profile.getName().get();
    if (Sponge.getServer().getPlayer(playerName)
            .map(Player::getName)
            .filter(name -> name.equals(playerName))
            .isPresent()) {
        authEvent.setMessage(settings.getText().getAlreadyOnline());
        authEvent.setCancelled(true);
    }
}
 
Example 29
Source Project: FlexibleLogin   Source File: ConnectionListener.java    License: MIT License 5 votes vote down vote up
@Listener(order = Order.LATE)
public void checkCaseSensitive(Auth authEvent, @First GameProfile profile) {
    String playerName = profile.getName().get();
    if (settings.getGeneral().isCaseSensitiveNameCheck()) {
        plugin.getDatabase().exists(playerName)
                .filter(databaseName -> !playerName.equals(databaseName))
                .ifPresent(databaseName -> {
                    authEvent.setMessage(settings.getText().getInvalidCase(databaseName));
                    authEvent.setCancelled(true);
                });
    }
}
 
Example 30
Source Project: UltimateCore   Source File: BanListener.java    License: MIT License 5 votes vote down vote up
@Listener(order = Order.LATE)
public void onMotd(ClientPingServerEvent event) {
    try {
        ModuleConfig config = Modules.BAN.get().getConfig().get();
        if (!config.get().getNode("ban-motd", "enabled").getBoolean()) return;

        String ip = event.getClient().getAddress().getAddress().toString().replace("/", "");
        GlobalDataFile file = new GlobalDataFile("ipcache");
        if (file.get().getChildrenMap().keySet().contains(ip)) {
            //Player
            GameProfile profile = Sponge.getServer().getGameProfileManager().get(UUID.fromString(file.get().getNode(ip, "uuid").getString())).get();
            InetAddress address = InetAddress.getByName(ip);

            //Check if banned
            BanService bs = Sponge.getServiceManager().provide(BanService.class).get();
            UserStorageService us = Sponge.getServiceManager().provide(UserStorageService.class).get();
            if (bs.isBanned(profile) || bs.isBanned(address)) {
                Text motd = VariableUtil.replaceVariables(Messages.toText(config.get().getNode("ban-motd", "text").getString()), us.get(profile.getUniqueId()).orElse(null));

                //Replace ban vars
                Ban ban = bs.isBanned(profile) ? bs.getBanFor(profile).get() : bs.getBanFor(address).get();
                Long time = ban.getExpirationDate().map(date -> (date.toEpochMilli() - System.currentTimeMillis())).orElse(-1L);
                motd = TextUtil.replace(motd, "%time%", (time == -1L ? Messages.getFormatted("core.time.ever") : Text.of(TimeUtil.format(time))));
                motd = TextUtil.replace(motd, "%reason%", ban.getReason().orElse(Messages.getFormatted("ban.command.ban.defaultreason")));

                event.getResponse().setDescription(motd);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}