org.spongepowered.api.service.user.UserStorageService Java Examples

The following examples show how to use org.spongepowered.api.service.user.UserStorageService. 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: 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 #2
Source File: SubjectListPane.java    From ChatUI with MIT License 6 votes vote down vote up
Text renderSubject(Subject subject) {
    HoverAction<?> hover = null;
    if (this.collection.getIdentifier().equals(PermissionService.SUBJECTS_USER)) {
        try {
            UUID uuid = UUID.fromString(subject.getIdentifier());
            Optional<User> user = Sponge.getServiceManager().provideUnchecked(UserStorageService.class).get(uuid);
            if (user.isPresent()) {
                hover = TextActions.showText(Text.of(user.get().getName()));
            }
        } catch (Exception e) {
        }
    }
    return Text.builder(subject.getIdentifier())
            .onHover(hover)
            .onClick(ExtraUtils.clickAction(() -> {
                this.tab.getSubjViewer().setActive(subject, true);
                this.tab.setRoot(this.tab.getSubjViewer());
            }, SubjectListPane.this.tab)).build();
}
 
Example #3
Source File: CacheService.java    From Web-API with MIT License 6 votes vote down vote up
/**
 * Gets a specific player by name or UUID.
 *
 * @param nameOrUuid Either the name or UUID of the player. Use {@link #getPlayer(UUID)}} if the UUID is
 *                   already parsed.
 * @return An optional containing the player, or empty if not found.
 */
public Optional<CachedPlayer> getPlayer(String nameOrUuid) {
    if (Util.isValidUUID(nameOrUuid)) {
        return getPlayer(UUID.fromString(nameOrUuid));
    }

    Optional<CachedPlayer> player = players.values().stream().filter(p -> p.getName().equalsIgnoreCase(nameOrUuid)).findAny();
    if (player.isPresent())
        return player.flatMap(p -> getPlayer(p.getUUID()));

    return WebAPI.runOnMain(() -> {
        Optional<UserStorageService> optSrv = Sponge.getServiceManager().provide(UserStorageService.class);
        if (!optSrv.isPresent())
            throw new InternalServerErrorException("User storage service is not available");

        Optional<User> optUser = optSrv.get().get(nameOrUuid);
        return optUser.<CachedPlayer>map(CachedPlayer::new);
    });
}
 
Example #4
Source File: CacheService.java    From Web-API with MIT License 6 votes vote down vote up
/**
 * Gets a specific player by UUID.
 * @param uuid The UUID of the player.
 * @return An optional containing the cached player if found, or empty otherwise.
 */
public Optional<CachedPlayer> getPlayer(UUID uuid) {
    if (!players.containsKey(uuid)) {
        return WebAPI.runOnMain(() -> {
            Optional<UserStorageService> optSrv = Sponge.getServiceManager().provide(UserStorageService.class);
            if (!optSrv.isPresent())
                throw new InternalServerErrorException("User storage service is not available");

            Optional<User> optUser = optSrv.get().get(uuid);
            return optUser.<CachedPlayer>map(CachedPlayer::new);
        });
    }

    final CachedPlayer res = players.get(uuid);
    if (res.isExpired()) {
        return WebAPI.runOnMain(() -> {
            Optional<Player> player = Sponge.getServer().getPlayer(uuid);
            return player.map(this::updatePlayer);
        });
    } else {
        return Optional.of(res);
    }
}
 
Example #5
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 #6
Source File: NbtDataHelper.java    From GriefPrevention with MIT License 6 votes vote down vote up
public static Optional<User> getOwnerOfEntity(net.minecraft.entity.Entity entity) {
    NBTTagCompound nbt = new NBTTagCompound();
    entity.writeToNBT(nbt);
    if (nbt.hasKey(FORGE_DATA)) {
        NBTTagCompound forgeNBT = nbt.getCompoundTag(FORGE_DATA);
        if (forgeNBT.hasKey(SPONGE_DATA) && forgeNBT.getCompoundTag(SPONGE_DATA).hasKey(SPONGE_ENTITY_CREATOR)) {
            NBTTagCompound creatorNBT = forgeNBT.getCompoundTag(SPONGE_DATA).getCompoundTag(SPONGE_ENTITY_CREATOR);
            UUID uuid = new UUID(creatorNBT.getLong("uuid_most"), creatorNBT.getLong("uuid_least"));
            // get player if online
            EntityPlayer player = entity.world.getPlayerEntityByUUID(uuid);
            if (player != null) {
                return Optional.of((User) player);
            }
            // player is not online, get user from storage if one exists
            return Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(uuid);
        }
    }
    return Optional.empty();
}
 
Example #7
Source File: PermissionHolderCache.java    From GriefDefender with MIT License 6 votes vote down vote up
public GDPermissionUser getOrCreateUser(String username) {
    if (username == null || username.length() > 16) {
        return null;
    }

    final UUID uuid = PermissionUtil.getInstance().lookupUserUniqueId(username);
    if (uuid != null) {
        return this.getOrCreateUser(uuid);
    }
    User user = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(username).orElse(null);
    if (user == null) {
        user = NMSUtil.getInstance().createUserFromCache(username);
    }
    if (user != null) {
        return this.getOrCreateUser(user);
    }

    return null;
}
 
Example #8
Source File: CommandHelper.java    From GriefPrevention with MIT License 6 votes vote down vote up
public static String lookupPlayerName(UUID playerID) {
    // parameter validation
    if (playerID == null) {
        return "somebody";
    }

    // check the cache
    Optional<User> player = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(playerID);
    if (player.isPresent()) {
        return player.get().getName();
    } else {
        try {
            return Sponge.getServer().getGameProfileManager().get(playerID).get().getName().get();
        } catch (Exception e) {
            return "someone";
        }
    }
}
 
Example #9
Source File: PlayerUtils.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static Optional<User> resolvePlayerByName(String name) {
    // try online players first
    Optional<Player> targetPlayer = Sponge.getGame().getServer().getPlayer(name);
    if (targetPlayer.isPresent()) {
        return Optional.of((User) targetPlayer.get());
    }

    Optional<User> user = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(name);
    if (user.isPresent()) {
        return user;
    }

    return Optional.empty();
}
 
Example #10
Source File: UCUserService.java    From UltimateCore with MIT License 5 votes vote down vote up
/**
 * Retrieve an {@link UltimateUser} by the user's uuid.
 *
 * @param uuid The uuid of the user to get
 * @return The user, or Optional.empty() if not found
 */
@Override
public Optional<UltimateUser> getUser(UUID uuid) {
    Optional<User> user = Sponge.getServiceManager().provideUnchecked(UserStorageService.class).get(uuid);
    if (!user.isPresent()) {
        return Optional.empty();
    }
    return Optional.of(getUser(user.get()));
}
 
Example #11
Source File: UltimateUser.java    From UltimateCore with MIT License 5 votes vote down vote up
/**
 * Get the {@link User} this class is associated with.
 *
 * @return The user
 */
public User getUser() {
    if (getPlayer().isPresent()) {
        return getPlayer().get();
    }
    return Sponge.getServiceManager().provideUnchecked(UserStorageService.class).get(this.uuid).orElse(null);
}
 
Example #12
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 #13
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public User getUser(String name) {
    UserStorageService uss = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get();
    if (isUUIDs(name)) {
        UUID uuid = UUID.fromString(name);
        if (uss.get(uuid).isPresent()) {
            return uss.get(uuid).get();
        }
    } else {
        if (uss.get(name).isPresent()) {
            return uss.get(name).get();
        }
    }
    return null;
}
 
Example #14
Source File: RedProtectUtil.java    From RedProtect with GNU General Public License v3.0 5 votes vote down vote up
public String UUIDtoPlayer(@Nonnull String uuid) {
    if (uuid.isEmpty()) return null;

    //check if is UUID
    if (isDefaultServer(uuid) || !isUUIDs(uuid)) {
        return uuid;
    }

    if (cachedUUIDs.containsKey(uuid)) {
        return cachedUUIDs.get(uuid);
    }

    String playerName = uuid;
    UUID uuids;

    try {
        uuids = UUID.fromString(uuid);
        UserStorageService uss = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get();
        if (uss.get(uuids).isPresent()) {
            playerName = uss.get(uuids).get().getName();
        }
    } catch (IllegalArgumentException e) {
        playerName = MojangUUIDs.getName(uuid);
    }

    if (playerName != null && playerName.isEmpty())
        cachedUUIDs.put(uuid, playerName);
    return playerName;
}
 
Example #15
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 #16
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 #17
Source File: PlayerUtils.java    From GriefPrevention with MIT License 5 votes vote down vote up
public static String lookupPlayerName(String uuid) {
    if (uuid.equals(GriefPreventionPlugin.WORLD_USER_UUID.toString())) {
        return "administrator";
    }
    Optional<User> user = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(UUID.fromString(uuid));
    if (!user.isPresent()) {
        GriefPreventionPlugin.addLogEntry("Error: Tried to look up a local player name for invalid UUID: " + uuid);
        return "someone";
    }

    return user.get().getName();
}
 
Example #18
Source File: PlayerUtils.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Nullable
public static UUID getUUIDByName(String name) {
    // try online players first
    Player targetPlayer = Sponge.getGame().getServer().getPlayer(name).orElse(null);
    if (targetPlayer != null) {
        return targetPlayer.getUniqueId();
    }

    User user = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(name).orElse(null);
    if (user != null) {
        return user.getUniqueId();
    }

    return null;
}
 
Example #19
Source File: DataStore.java    From GriefPrevention with MIT License 5 votes vote down vote up
protected List<String> convertNameListToUUIDList(List<String> names) {
    // doesn't apply after schema has been updated to version 1
    if (this.getSchemaVersion() >= 1) {
        return names;
    }

    // list to build results
    List<String> resultNames = new ArrayList<String>();

    for (String name : names) {
        // skip non-player-names (groups and "public"), leave them as-is
        if (name.startsWith("[") || name.equals("public")) {
            resultNames.add(name);
            continue;
        }

        // otherwise try to convert to a UUID
        Optional<User> player = Optional.empty();
        try {
            player = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(name);
        } catch (Exception ex) {
        }

        // if successful, replace player name with corresponding UUID
        if (player.isPresent()) {
            resultNames.add(player.get().getUniqueId().toString());
        }
    }

    return resultNames;
}
 
Example #20
Source File: DynmapUtils.java    From EagleFactions with MIT License 5 votes vote down vote up
public static String getFactionInfoWindow(final Faction faction) {
    // TODO: fix missing line breaks. Sometimes they are missing. I don't know why.
    Optional<UserStorageService> userStorage = Sponge.getServiceManager().provide(UserStorageService.class);

    StringBuilder description = new StringBuilder();

    String factionName = faction.getName();
    String factionDesc = faction.getDescription();

    description.append("<div class=\"infowindow\">\n")
            .append("<span style=\"font-weight: bold; font-size: 150%;\">%name%</span></br>\n".replace("%name%", factionName))
            .append("<span style=\"font-style: italic; font-size: 110%;\">%description%</span></br>\n".replace("%description%", factionDesc.length() > 0 ? factionDesc : "No description"));

    if (faction.getTag().toPlain().length() > 0) {
        description.append("<span style=\"font-weight: bold;\">Tag:</span> %tag%</br>\n".replace("%tag%", faction.getTag().toPlain()))
                .append("</br>\n");
    }

    if (dynmapConfig.showDynmapFactionLeader() && userStorage.isPresent()) {
        if (userStorage.get().get(faction.getLeader()).isPresent()) {
            description.append("<span style=\"font-weight: bold;\">Leader:</span> %leader%</br>\n"
                    .replace("%leader%",
                            userStorage.get().get(faction.getLeader()).get().getName()));
        }
    }

    if (dynmapConfig.showDynmapMemberInfo()) {
        int memberCount = faction.getPlayers().size();
        description.append("<span style=\"font-weight: bold;\">Total members:</span> %players%</br>\n"
                .replace("%players%",
                        String.valueOf(memberCount)));
    }

    description.append("</br>\n</div>");

    return description.toString();
}
 
Example #21
Source File: PlayerManagerImpl.java    From EagleFactions with MIT License 5 votes vote down vote up
public PlayerManagerImpl(final StorageManager storageManager, final FactionLogic factionLogic, final FactionsConfig factionsConfig, final PowerConfig powerConfig)
{
    this.storageManager = storageManager;
    this.factionLogic = factionLogic;
    this.factionsConfig = factionsConfig;
    this.powerConfig = powerConfig;

    Optional<UserStorageService> optionalUserStorageService = Sponge.getServiceManager().provide(UserStorageService.class);
    optionalUserStorageService.ifPresent(x -> userStorageService = x);
}
 
Example #22
Source File: PlayerUtil.java    From GriefDefender with MIT License 5 votes vote down vote up
public String getPlayerName(String uuid) {
    if (uuid.equals(GriefDefenderPlugin.WORLD_USER_UUID.toString())) {
        return "administrator";
    }
    if (uuid.equals(GriefDefenderPlugin.ADMIN_USER_UUID.toString()) || uuid.equals(GriefDefenderPlugin.WORLD_USER_UUID.toString())) {
        return "administrator";
    }

    Optional<User> user = Sponge.getGame().getServiceManager().provide(UserStorageService.class).get().get(UUID.fromString(uuid));
    if (!user.isPresent()) {
        return "unknown";
    }

    return user.get().getName();
}
 
Example #23
Source File: GriefPreventionPlugin.java    From GriefPrevention with MIT License 4 votes vote down vote up
@Listener
public void onServerAboutToStart(GameAboutToStartServerEvent event) {
    if (!validateSpongeVersion()) {
        return;
    }

    if (this.permissionService == null) {
        this.logger.error("Unable to initialize plugin. GriefPrevention requires a permissions plugin such as LuckPerms.");
        return;
    }

    this.loadConfig();
    this.customLogger = new CustomLogger();
    this.executor = Executors.newFixedThreadPool(GriefPreventionPlugin.getGlobalConfig().getConfig().thread.numExecutorThreads);
    this.economyService = Sponge.getServiceManager().provide(EconomyService.class);
    if (Sponge.getPluginManager().getPlugin("mcclans").isPresent()) {
        this.clanApiProvider = new MCClansApiProvider();
    }
    if (Sponge.getPluginManager().getPlugin("nucleus").isPresent()) {
        this.nucleusApiProvider = new NucleusApiProvider();
    }
    if (Sponge.getPluginManager().getPlugin("worldedit").isPresent() || Sponge.getPluginManager().getPlugin("fastasyncworldedit").isPresent()) {
        this.worldEditProvider = new WorldEditApiProvider();
    }

    if (this.dataStore == null) {
        try {
            this.dataStore = new FlatFileDataStore();
            // Migrator currently only handles pixelmon
            // Remove pixelmon check after GP 5.0.0 update
            if (Sponge.getPluginManager().getPlugin("pixelmon").isPresent()) {
                if (this.dataStore.getMigrationVersion() < DataStore.latestMigrationVersion) {
                    GPPermissionMigrator.getInstance().migrateSubject(GLOBAL_SUBJECT);
                    permissionService.getUserSubjects().applyToAll(GPPermissionMigrator.getInstance().migrateSubjectPermissions());
                    permissionService.getGroupSubjects().applyToAll(GPPermissionMigrator.getInstance().migrateSubjectPermissions());
                    this.dataStore.setMigrationVersion(DataStore.latestMigrationVersion);
                }
            }
            this.dataStore.initialize();
        } catch (Exception e) {
            this.getLogger().info("Unable to initialize the file system data store.  Details:");
            this.getLogger().info(e.getMessage());
            e.printStackTrace();
            return;
        }
    }

    String dataMode = (this.dataStore instanceof FlatFileDataStore) ? "(File Mode)" : "(Database Mode)";
    Sponge.getEventManager().registerListeners(this, new BlockEventHandler(dataStore));
    Sponge.getEventManager().registerListeners(this, new PlayerEventHandler(dataStore, this));
    Sponge.getEventManager().registerListeners(this, new EntityEventHandler(dataStore));
    Sponge.getEventManager().registerListeners(this, new WorldEventHandler());
    if (this.nucleusApiProvider != null) {
        Sponge.getEventManager().registerListeners(this, new NucleusEventHandler());
        this.nucleusApiProvider.registerTokens();
    }
    if (this.clanApiProvider != null) {
        Sponge.getEventManager().registerListeners(this, new MCClansEventHandler());
    }
    addLogEntry("Finished loading data " + dataMode + ".");

    PUBLIC_USER = Sponge.getServiceManager().provide(UserStorageService.class).get()
            .getOrCreate(GameProfile.of(GriefPreventionPlugin.PUBLIC_UUID, GriefPreventionPlugin.PUBLIC_NAME));
    WORLD_USER = Sponge.getServiceManager().provide(UserStorageService.class).get()
            .getOrCreate(GameProfile.of(GriefPreventionPlugin.WORLD_USER_UUID, GriefPreventionPlugin.WORLD_USER_NAME));

    // run cleanup task
    int cleanupTaskInterval = GriefPreventionPlugin.getGlobalConfig().getConfig().claim.expirationCleanupInterval;
    if (cleanupTaskInterval > 0) {
        CleanupUnusedClaimsTask cleanupTask = new CleanupUnusedClaimsTask();
        Sponge.getScheduler().createTaskBuilder().delay(cleanupTaskInterval, TimeUnit.MINUTES).execute(cleanupTask)
                .submit(GriefPreventionPlugin.instance);
    }

    // if economy is enabled
    if (this.economyService.isPresent()) {
        GriefPreventionPlugin.addLogEntry("GriefPrevention economy integration enabled.");
        GriefPreventionPlugin.addLogEntry(
                "Hooked into economy: " + Sponge.getServiceManager().getRegistration(EconomyService.class).get().getPlugin().getId() + ".");
        GriefPreventionPlugin.addLogEntry("Ready to buy/sell claim blocks!");
    }

    // load ignore lists for any already-online players
    Collection<Player> players = Sponge.getGame().getServer().getOnlinePlayers();
    for (Player player : players) {
        new IgnoreLoaderThread(player.getUniqueId(), this.dataStore.getOrCreatePlayerData(player.getWorld(), player.getUniqueId()).ignoredPlayers)
                .start();
    }

    // TODO - rewrite /gp command
    //Sponge.getGame().getCommandManager().register(this, CommandGriefPrevention.getCommand().getCommandSpec(),
    //CommandGriefPrevention.getCommand().getAliases());
    registerBaseCommands();
    this.dataStore.loadClaimTemplates();
}
 
Example #24
Source File: CachedPlayer.java    From Web-API with MIT License 4 votes vote down vote up
@JsonIgnore
public Optional<User> getUser() {
    Optional<UserStorageService> optSrv = Sponge.getServiceManager().provide(UserStorageService.class);
    return optSrv.flatMap(srv -> srv.get(uuid));
}
 
Example #25
Source File: BanCommand.java    From UltimateCore with MIT License 4 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);

    Long time = args.<Long>getOne("time").orElse(-1L);
    Text reason = args.<String>getOne("reason").map(Messages::toText).orElse(Messages.getFormatted(src, "ban.command.ban.defaultreason"));

    //Try to find user
    User user = null;
    if (profile != null) {
        user = Sponge.getServiceManager().provide(UserStorageService.class).get().get(profile).get();
    } else {
        //Try to find user from ip address
        for (GameProfile prof : Sponge.getServer().getGameProfileManager().getCache().getProfiles()) {
            PlayerDataFile config = new PlayerDataFile(prof.getUniqueId());
            CommentedConfigurationNode node = config.get();
            if (node.getNode("lastip").getString("").equalsIgnoreCase(address.toString().replace("/", ""))) {
                user = Sponge.getServiceManager().provide(UserStorageService.class).get().get(prof).get();
            }
        }
    }

    //If user is present, check exempt
    if (user != null) {
        if ((BanPermissions.UC_BAN_EXEMPTPOWER.getIntFor(user) > BanPermissions.UC_BAN_POWER.getIntFor(src)) && src instanceof Player) {
            throw new ErrorMessageException(Messages.getFormatted(src, "ban.command.ban.exempt", "%player%", user));
        }
    }

    //Ban user
    BanService bs = Sponge.getServiceManager().provide(BanService.class).get();
    Ban.Builder bb = Ban.builder();
    if (profile != null) {
        bb = bb.type(BanTypes.PROFILE).profile(profile);
    } else {
        bb = bb.type(BanTypes.IP).address(address);
    }
    bb = bb.source(src).startDate(Instant.now());
    if (time > 0) bb = bb.expirationDate(Instant.now().plusMillis(time));
    bb = bb.reason(reason);
    bs.addBan(bb.build());

    //Kick player
    if (user != null && user.getPlayer().isPresent()) {
        if (profile != null) {
            user.getPlayer().get().kick(Messages.getFormatted(user.getPlayer().get(), "ban.banned", "%time%", (time == -1L ? Messages.getFormatted("core.time.ever") : TimeUtil.format(time)), "%reason%", reason));
        } else {
            user.getPlayer().get().kick(Messages.getFormatted(user.getPlayer().get(), "ban.ipbanned", "%time%", (time == -1L ? Messages.getFormatted("core.time.ever") : TimeUtil.format(time)), "%reason%", reason));
        }
    }

    //Send message
    if (profile != null) {
        Messages.send(src, "ban.command.ban.success", "%player%", profile.getName().orElse(""), "%time%", (time == -1L ? Messages.getFormatted("core.time.ever") : TimeUtil.format(time)), "%reason%", reason);
    } else {
        Messages.send(src, "ban.command.ban.success-ip", "%ip%", address.toString().replace("/", ""), "%time%", (time == -1L ? Messages.getFormatted("core.time.ever") : TimeUtil.format(time)), "%reason%", reason);
    }
    return CommandResult.success();
}
 
Example #26
Source File: FactionPlayerImpl.java    From EagleFactions with MIT License 4 votes vote down vote up
@Override
public Optional<User> getUser()
{
    final Optional<UserStorageService> userStorageService = Sponge.getServiceManager().provide(UserStorageService.class);
    return userStorageService.flatMap(storageService -> storageService.get(this.uniqueId));
}