org.spongepowered.api.profile.GameProfile Java Examples

The following examples show how to use org.spongepowered.api.profile.GameProfile. 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 File: LoginListener.java    From SkinsRestorerX with 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
Source File: DataUtil.java    From Prism with 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 #3
Source File: GameprofileArgument.java    From UltimateCore with 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 #4
Source File: UserArgument.java    From UltimateCore with 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 #5
Source File: IpCommand.java    From UltimateCore with 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 #6
Source File: UnbanCommand.java    From UltimateCore with 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 #7
Source File: LoginListener.java    From ChangeSkin with 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 #8
Source File: GriefPreventionPlugin.java    From GriefPrevention with 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 #9
Source File: VirtualChestPlugin.java    From VirtualChest with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #10
Source File: PlayerOnlineListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #11
Source File: SkinApplier.java    From SkinsRestorerX with 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 #12
Source File: ParameterPlayer.java    From Prism with MIT License 5 votes vote down vote up
@Override
public Optional<CompletableFuture<?>> process(QuerySession session, String parameter, String value, Query query) {
    CompletableFuture<GameProfile> future = Sponge.getServer().getGameProfileManager().get(value, true);

    future.thenAccept(profile -> query.addCondition(FieldCondition.of(DataQueries.Player, MatchRule.EQUALS, profile.getUniqueId().toString())));

    return Optional.of(future);
}
 
Example #13
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #14
Source File: SendMailCommand.java    From UltimateCore with MIT License 5 votes vote down vote up
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    //Get sender
    checkIfPlayer(src);
    Player p = (Player) src;
    UltimateUser up = UltimateCore.get().getUserService().getUser(p);

    //Get target & construct mail
    GameProfile t = args.<GameProfile>getOne("player").get();
    UltimateUser ut = UltimateCore.get().getUserService().getUser(t.getUniqueId()).get();
    String message = args.<String>getOne("message").get();
    Mail mail = new Mail(p.getUniqueId(), Arrays.asList(t.getUniqueId()), System.currentTimeMillis(), message);

    //Offer to data api
    List<Mail> sentMail = up.get(MailKeys.MAILS_SENT).get();
    sentMail.add(mail);
    up.offer(MailKeys.MAILS_SENT, sentMail);
    List<Mail> receivedMail = ut.get(MailKeys.MAILS_RECEIVED).get();
    receivedMail.add(mail);
    ut.offer(MailKeys.MAILS_RECEIVED, receivedMail);

    //Increase unread count
    up.offer(MailKeys.UNREAD_MAIL, up.get(MailKeys.UNREAD_MAIL).get() + 1);

    Messages.send(src, "mail.command.mail.send", "%player%", t.getName().orElse(""));
    if (ut.getPlayer().isPresent()) {
        ut.getPlayer().get().sendMessage(Messages.getFormatted(ut.getPlayer().get(), "mail.command.mail.newmail", "%count%", up.get(MailKeys.UNREAD_MAIL).get()).toBuilder().onHover(TextActions.showText(Messages.getFormatted(ut.getPlayer().get(), "mail.command.mail.newmail.hover"))).onClick(TextActions.runCommand("/mail read")).build());
    }
    return CommandResult.success();
}
 
Example #15
Source File: BanListener.java    From UltimateCore with 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();
    }
}
 
Example #16
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #17
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #18
Source File: ConnectionListener.java    From FlexibleLogin with 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 #19
Source File: ConnectionListener.java    From FlexibleLogin with 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 #20
Source File: ConnectionListener.java    From FlexibleLogin with 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 #21
Source File: SpongeSkinAPI.java    From ChangeSkin with 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 #22
Source File: LoginListener.java    From ChangeSkin with 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 #23
Source File: RedProtectUtil.java    From RedProtect with 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 #24
Source File: FaweSponge.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@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 #25
Source File: FaweSponge.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: FaweSponge.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@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 #27
Source File: FaweSponge.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@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 #28
Source File: UserParser.java    From EssentialCmds with 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 #29
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #30
Source File: VirtualChestItemStackSerializer.java    From VirtualChest with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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));
    }
}