Search in sources :

Example 11 with GameProfile

use of org.spongepowered.api.profile.GameProfile in project RedProtect by FabioZumbi12.

the class RPUtil method PlayerToUUID.

public static String PlayerToUUID(String PlayerName) {
    if (PlayerName == null || PlayerName.equals("")) {
        return null;
    }
    // check if is already UUID
    if (isUUIDs(PlayerName) || isDefaultServer(PlayerName) || (PlayerName.startsWith("[") && PlayerName.endsWith("]"))) {
        return PlayerName;
    }
    String uuid = PlayerName;
    if (!RedProtect.get().OnlineMode) {
        uuid = uuid.toLowerCase();
        return uuid;
    }
    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()) {
        return ogpName.get().getUniqueId().toString();
    } else {
        Optional<Player> p = RedProtect.get().serv.getPlayer(PlayerName);
        if (p.isPresent()) {
            return p.get().getUniqueId().toString();
        }
    }
    return uuid;
}
Also used : UserStorageService(org.spongepowered.api.service.user.UserStorageService) Connection(java.sql.Connection) Date(java.util.Date) ConfigurationLoader(ninja.leaping.configurate.loader.ConfigurationLoader) UserStorageService(org.spongepowered.api.service.user.UserStorageService) ItemStack(org.spongepowered.api.item.inventory.ItemStack) ResultSet(java.sql.ResultSet) Map(java.util.Map) GameProfile(org.spongepowered.api.profile.GameProfile) ParseException(java.text.ParseException) ZipEntry(java.util.zip.ZipEntry) DateFormat(java.text.DateFormat) Location(org.spongepowered.api.world.Location) User(org.spongepowered.api.entity.living.player.User) Set(java.util.Set) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) UUID(java.util.UUID) PreparedStatement(java.sql.PreparedStatement) BlockState(org.spongepowered.api.block.BlockState) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) List(java.util.List) World(org.spongepowered.api.world.World) Optional(java.util.Optional) HandTypes(org.spongepowered.api.data.type.HandTypes) Player(org.spongepowered.api.entity.living.player.Player) ZipOutputStream(java.util.zip.ZipOutputStream) Keys(org.spongepowered.api.data.key.Keys) ItemTypes(org.spongepowered.api.item.ItemTypes) SimpleDateFormat(java.text.SimpleDateFormat) DatabaseMetaData(java.sql.DatabaseMetaData) HashMap(java.util.HashMap) TypeToken(com.google.common.reflect.TypeToken) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) Calendar(java.util.Calendar) Text(org.spongepowered.api.text.Text) LinkedList(java.util.LinkedList) HoconConfigurationLoader(ninja.leaping.configurate.hocon.HoconConfigurationLoader) CommentedConfigurationNode(ninja.leaping.configurate.commented.CommentedConfigurationNode) WEListener(br.net.fabiozumbi12.RedProtect.Sponge.hooks.WEListener) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Entity(org.spongepowered.api.entity.Entity) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) RPLang(br.net.fabiozumbi12.RedProtect.Sponge.config.RPLang) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) EntityType(org.spongepowered.api.entity.EntityType) Collections(java.util.Collections) ItemType(org.spongepowered.api.item.ItemType) DriverManager(java.sql.DriverManager) Player(org.spongepowered.api.entity.living.player.Player) GameProfile(org.spongepowered.api.profile.GameProfile)

Example 12 with GameProfile

use of org.spongepowered.api.profile.GameProfile in project ChangeSkin by games647.

the class LoginListener method onPlayerPreLogin.

@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);
        }
    }
}
Also used : GameProfile(org.spongepowered.api.profile.GameProfile) UserPreference(com.github.games647.changeskin.core.model.UserPreference) UUID(java.util.UUID) SkinStorage(com.github.games647.changeskin.core.SkinStorage) SkinModel(com.github.games647.changeskin.core.model.skin.SkinModel) Listener(org.spongepowered.api.event.Listener) SharedListener(com.github.games647.changeskin.core.shared.SharedListener)

Example 13 with GameProfile

use of org.spongepowered.api.profile.GameProfile in project core by CubeEngine.

the class UserMatcher method match.

public Optional<User> match(String name, boolean searchOffline) {
    Game game = Sponge.getGame();
    if (name == null) {
        return null;
    }
    // Direct Match Online Players:
    Optional<Player> player = game.getServer().getPlayer(name);
    if (player.isPresent()) {
        return Optional.of(player.get());
    }
    // Find Online Players with similar name
    Map<String, Player> onlinePlayerMap = new HashMap<>();
    for (Player onlineUser : game.getServer().getOnlinePlayers()) {
        onlinePlayerMap.put(onlineUser.getName(), onlineUser);
    }
    String foundUser = sm.matchString(name, onlinePlayerMap.keySet());
    if (foundUser != null) {
        return Optional.of(onlinePlayerMap.get(foundUser));
    }
    UserStorageService storage = game.getServiceManager().provideUnchecked(UserStorageService.class);
    Optional<User> directMatchOffline;
    try {
        directMatchOffline = storage.get(name);
    } catch (IllegalArgumentException ignore) {
        return Optional.empty();
    }
    if (directMatchOffline.isPresent()) {
        return directMatchOffline;
    }
    if (searchOffline) {
        String match = sm.matchString(name, storage.getAll().stream().map(GameProfile::getName).filter(Optional::isPresent).map(Optional::get).collect(toList()));
        if (match != null) {
            return storage.get(match);
        }
    }
    return Optional.empty();
}
Also used : UserStorageService(org.spongepowered.api.service.user.UserStorageService) Player(org.spongepowered.api.entity.living.player.Player) Game(org.spongepowered.api.Game) User(org.spongepowered.api.entity.living.player.User) Optional(java.util.Optional) HashMap(java.util.HashMap) GameProfile(org.spongepowered.api.profile.GameProfile)

Example 14 with GameProfile

use of org.spongepowered.api.profile.GameProfile in project LanternServer by LanternPowered.

the class NetworkSession method initPlayer.

/**
 * Initializes the {@link LanternPlayer} instance
 * and spawns it in a world if permitted to join
 * the server.
 */
public void initPlayer() {
    initKeepAliveTask();
    if (this.gameProfile == null) {
        throw new IllegalStateException("The game profile must first be available!");
    }
    this.player = new LanternPlayer(this.gameProfile, this);
    this.player.setNetworkId(EntityProtocolManager.acquireEntityId());
    this.player.setEntityProtocolType(EntityProtocolTypes.PLAYER);
    LanternWorld world = this.player.getWorld();
    if (world == null) {
        LanternWorldProperties worldProperties = this.player.getUserWorld();
        boolean fixSpawnLocation = false;
        if (worldProperties == null) {
            Lantern.getLogger().warn("The player [{}] attempted to login in a non-existent world, this is not possible " + "so we have moved them to the default's world spawn point.", this.gameProfile.getName().get());
            worldProperties = (LanternWorldProperties) Lantern.getServer().getDefaultWorld().get();
            fixSpawnLocation = true;
        } else if (!worldProperties.isEnabled()) {
            Lantern.getLogger().warn("The player [{}] attempted to login in a unloaded and not-enabled world [{}], this is not possible " + "so we have moved them to the default's world spawn point.", this.gameProfile.getName().get(), worldProperties.getWorldName());
            worldProperties = (LanternWorldProperties) Lantern.getServer().getDefaultWorld().get();
            fixSpawnLocation = true;
        }
        final Optional<World> optWorld = Lantern.getWorldManager().loadWorld(worldProperties);
        // Use the raw method to avoid triggering any network messages
        this.player.setRawWorld((LanternWorld) optWorld.get());
        this.player.setUserWorld(null);
        if (fixSpawnLocation) {
            // TODO: Use a proper spawn position
            this.player.setRawPosition(new Vector3d(0, 100, 0));
            this.player.setRawRotation(new Vector3d(0, 0, 0));
        }
    }
    // The kick reason
    Text kickReason = null;
    final BanService banService = Sponge.getServiceManager().provideUnchecked(BanService.class);
    // Check whether the player is banned and kick if necessary
    Ban ban = banService.getBanFor(this.gameProfile).orElse(null);
    if (ban == null) {
        final SocketAddress address = getChannel().remoteAddress();
        if (address instanceof InetSocketAddress) {
            ban = banService.getBanFor(((InetSocketAddress) address).getAddress()).orElse(null);
        }
    }
    if (ban != null) {
        final Optional<Instant> optExpirationDate = ban.getExpirationDate();
        final Optional<Text> optReason = ban.getReason();
        // Generate the kick message
        Text.Builder builder = Text.builder();
        if (ban instanceof Ban.Profile) {
            builder.append(t("multiplayer.disconnect.ban.banned"));
        } else {
            builder.append(t("multiplayer.disconnect.ban.ip_banned"));
        }
        // There is optionally a reason
        optReason.ifPresent(reason -> builder.append(Text.NEW_LINE).append(t("multiplayer.disconnect.ban.reason", reason)));
        // And a expiration date if present
        optExpirationDate.ifPresent(expirationDate -> {
            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(tr("multiplayer.disconnect.ban.expiration_date_format").get());
            builder.append(Text.NEW_LINE).append(t("multiplayer.disconnect.ban.expiration", formatter.format(expirationDate)));
        });
        kickReason = builder.build();
    // Check for white-list
    } else if (!isWhitelisted(this.gameProfile)) {
        kickReason = t("multiplayer.disconnect.not_whitelisted");
    // Check whether the server is full
    } else if (Lantern.getServer().getOnlinePlayers().size() >= Lantern.getServer().getMaxPlayers() && !canBypassPlayerLimit(this.gameProfile)) {
        kickReason = t("multiplayer.disconnect.server_full");
    }
    final MessageEvent.MessageFormatter messageFormatter = new MessageEvent.MessageFormatter(kickReason != null ? kickReason : t("multiplayer.disconnect.not_allowed_to_join"));
    final Cause cause = Cause.builder().append(this).build(EventContext.builder().add(EventContextKeys.PLAYER, this.player).build());
    final Transform<World> fromTransform = this.player.getTransform();
    final ClientConnectionEvent.Login loginEvent = SpongeEventFactory.createClientConnectionEventLogin(cause, fromTransform, fromTransform, this, messageFormatter, this.gameProfile, this.player, false);
    if (kickReason != null) {
        loginEvent.setCancelled(true);
    }
    Sponge.getEventManager().post(loginEvent);
    if (loginEvent.isCancelled()) {
        disconnect(loginEvent.isMessageCancelled() ? t("multiplayer.disconnect.generic") : loginEvent.getMessage());
        return;
    }
    Lantern.getLogger().debug("The player {} successfully to joined from {}.", this.gameProfile.getName().get(), this.channel.remoteAddress());
    // Update the first join and last played data
    final Instant lastJoined = Instant.now();
    this.player.offer(Keys.LAST_DATE_PLAYED, lastJoined);
    if (!this.player.get(Keys.FIRST_DATE_PLAYED).isPresent()) {
        this.player.offer(Keys.FIRST_DATE_PLAYED, lastJoined);
    }
    final Transform<World> toTransform = loginEvent.getToTransform();
    world = (LanternWorld) toTransform.getExtent();
    final WorldConfig config = world.getProperties().getConfig();
    // Update the game mode if necessary
    if (config.isGameModeForced() || this.player.get(Keys.GAME_MODE).get().equals(GameModes.NOT_SET)) {
        this.player.offer(Keys.GAME_MODE, config.getGameMode());
    }
    // Reset the raw world
    this.player.setRawWorld(null);
    // Set the transform, this will trigger the initial
    // network messages to be send
    this.player.setTransform(toTransform);
    final MessageChannel messageChannel = this.player.getMessageChannel();
    final Text joinMessage;
    final GameProfile previousProfile = this.channel.attr(PREVIOUS_GAME_PROFILE).getAndSet(null);
    if (previousProfile != null && previousProfile.getName().isPresent() && !previousProfile.getName().get().equals(this.gameProfile.getName().get())) {
        joinMessage = t("multiplayer.player.joined.renamed", this.player.getName(), previousProfile.getName().get());
    } else {
        joinMessage = t("multiplayer.player.joined", this.player.getName());
    }
    final ClientConnectionEvent.Join joinEvent = SpongeEventFactory.createClientConnectionEventJoin(cause, messageChannel, Optional.of(messageChannel), new MessageEvent.MessageFormatter(joinMessage), this.player, false);
    Sponge.getEventManager().post(joinEvent);
    if (!joinEvent.isMessageCancelled()) {
        joinEvent.getChannel().ifPresent(channel -> channel.send(this.player, joinEvent.getMessage()));
    }
    this.server.getDefaultResourcePack().ifPresent(this.player::sendResourcePack);
    this.player.resetIdleTimeoutCounter();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) MessageEvent(org.spongepowered.api.event.message.MessageEvent) WorldConfig(org.lanternpowered.server.config.world.WorldConfig) LanternWorld(org.lanternpowered.server.world.LanternWorld) World(org.spongepowered.api.world.World) LanternWorld(org.lanternpowered.server.world.LanternWorld) GameProfile(org.spongepowered.api.profile.GameProfile) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) Cause(org.spongepowered.api.event.cause.Cause) BanService(org.spongepowered.api.service.ban.BanService) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties) Instant(java.time.Instant) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) Text(org.spongepowered.api.text.Text) Ban(org.spongepowered.api.util.ban.Ban) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Vector3d(com.flowpowered.math.vector.Vector3d) GameProfile(org.spongepowered.api.profile.GameProfile) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) DateTimeFormatter(java.time.format.DateTimeFormatter) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 15 with GameProfile

use of org.spongepowered.api.profile.GameProfile in project LanternServer by LanternPowered.

the class HandlerStatusRequest method handle.

@Override
public void handle(NetworkContext context, MessageStatusInRequest message) {
    final NetworkSession session = context.getSession();
    final LanternServer server = session.getServer();
    final Gson gson = new Gson();
    final Text description = server.getMotd();
    final InetSocketAddress address = session.getAddress();
    final InetSocketAddress virtualAddress = session.getVirtualHost();
    final int protocol = session.getProtocolVersion();
    final MinecraftVersion clientVersion = Lantern.getGame().getMinecraftVersionCache().getVersionOrUnknown(protocol, false);
    if (clientVersion == LanternMinecraftVersion.UNKNOWN) {
        Lantern.getLogger().debug("Client with unknown protocol version {} pinged the server.", protocol);
    }
    final LanternStatusClient client = new LanternStatusClient(address, clientVersion, virtualAddress);
    final ClientPingServerEvent.Response.Players players = LanternStatusHelper.createPlayers(server);
    final LanternStatusResponse response = new LanternStatusResponse(Lantern.getGame().getPlatform().getMinecraftVersion(), server.getFavicon(), description, players);
    final Cause cause = Cause.of(EventContext.empty(), new WrappedRemoteConnection(session));
    final ClientPingServerEvent event = SpongeEventFactory.createClientPingServerEvent(cause, client, response);
    Sponge.getEventManager().post(event);
    // Cancelled, we are done here
    if (event.isCancelled()) {
        context.getChannel().close();
        return;
    }
    final JsonObject rootObject = new JsonObject();
    final JsonObject versionObject = new JsonObject();
    checkState(response.getVersion() instanceof LanternMinecraftVersion);
    final LanternMinecraftVersion serverVersion = (LanternMinecraftVersion) response.getVersion();
    versionObject.addProperty("name", serverVersion.getName());
    versionObject.addProperty("protocol", serverVersion.getProtocol());
    if (response.getPlayers().isPresent()) {
        final JsonObject playersObject = new JsonObject();
        playersObject.addProperty("max", players.getMax());
        playersObject.addProperty("online", players.getOnline());
        List<GameProfile> profiles = players.getProfiles();
        if (!profiles.isEmpty()) {
            final JsonArray array = new JsonArray();
            for (GameProfile profile : profiles) {
                Optional<String> optName = profile.getName();
                if (!optName.isPresent()) {
                    continue;
                }
                final JsonObject profileObject = new JsonObject();
                profileObject.addProperty("name", optName.get());
                profileObject.addProperty("id", profile.getUniqueId().toString());
                array.add(profileObject);
            }
            playersObject.add("sample", array);
        }
        rootObject.add("players", playersObject);
    }
    rootObject.add("version", versionObject);
    rootObject.add("description", ((LanternJsonTextSerializer) TextSerializers.JSON).getGson().toJsonTree(response.getDescription()));
    response.getFavicon().ifPresent(icon -> rootObject.addProperty("favicon", ((LanternFavicon) icon).getEncoded()));
    final JsonObject fmlObject = new JsonObject();
    // Trick the client that the server is fml, we support fml channels anyway
    fmlObject.addProperty("type", "FML");
    // The client shouldn't know the plugins (mods) list
    fmlObject.add("modList", new JsonArray());
    // Add the fml info
    rootObject.add("modinfo", fmlObject);
    session.send(new MessageStatusOutResponse(gson.toJson(rootObject)));
}
Also used : NetworkSession(org.lanternpowered.server.network.NetworkSession) MessageStatusOutResponse(org.lanternpowered.server.network.vanilla.message.type.status.MessageStatusOutResponse) LanternMinecraftVersion(org.lanternpowered.server.game.version.LanternMinecraftVersion) InetSocketAddress(java.net.InetSocketAddress) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Text(org.spongepowered.api.text.Text) LanternJsonTextSerializer(org.lanternpowered.server.text.gson.LanternJsonTextSerializer) LanternStatusResponse(org.lanternpowered.server.network.status.LanternStatusResponse) MessageStatusOutResponse(org.lanternpowered.server.network.vanilla.message.type.status.MessageStatusOutResponse) JsonArray(com.google.gson.JsonArray) LanternStatusClient(org.lanternpowered.server.network.status.LanternStatusClient) ClientPingServerEvent(org.spongepowered.api.event.server.ClientPingServerEvent) LanternServer(org.lanternpowered.server.LanternServer) GameProfile(org.spongepowered.api.profile.GameProfile) Cause(org.spongepowered.api.event.cause.Cause) LanternFavicon(org.lanternpowered.server.network.status.LanternFavicon) LanternStatusResponse(org.lanternpowered.server.network.status.LanternStatusResponse) LanternMinecraftVersion(org.lanternpowered.server.game.version.LanternMinecraftVersion) MinecraftVersion(org.spongepowered.api.MinecraftVersion) WrappedRemoteConnection(org.lanternpowered.server.network.WrappedRemoteConnection)

Aggregations

GameProfile (org.spongepowered.api.profile.GameProfile)44 Optional (java.util.Optional)12 UUID (java.util.UUID)12 Text (org.spongepowered.api.text.Text)9 User (org.spongepowered.api.entity.living.player.User)8 IOException (java.io.IOException)7 List (java.util.List)6 Sponge (org.spongepowered.api.Sponge)6 Cause (org.spongepowered.api.event.cause.Cause)6 World (org.spongepowered.api.world.World)6 Vector3d (com.flowpowered.math.vector.Vector3d)5 Collectors (java.util.stream.Collectors)5 Keys (org.spongepowered.api.data.key.Keys)5 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)4 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)4 ImmutableList (com.google.common.collect.ImmutableList)4 Lists (com.google.common.collect.Lists)4 Collection (java.util.Collection)4 Iterator (java.util.Iterator)4 Set (java.util.Set)4