Search in sources :

Example 1 with UserCache

use of net.dzikoysk.funnyguilds.user.UserCache in project FunnyGuilds by FunnyGuilds.

the class BaseCommand method execute.

@FunnyCommand(name = "${user.base.name}", aliases = "${user.base.aliases}", description = "${user.base.description}", permission = "funnyguilds.base", acceptsExceeded = true, playerOnly = true)
public void execute(Player player, @IsMember User user, Guild guild) {
    when(!config.regionsEnabled, messages.regionsDisabled);
    when(!config.baseEnable, messages.baseTeleportationDisabled);
    when(user.getCache().getTeleportation() != null, messages.baseIsTeleportation);
    List<ItemStack> requiredItems = player.hasPermission("funnyguilds.vip.base") ? Collections.emptyList() : config.baseItems;
    if (!ItemUtils.playerHasEnoughItems(player, requiredItems)) {
        return;
    }
    ItemStack[] items = ItemUtils.toArray(requiredItems);
    player.getInventory().removeItem(items);
    if (config.baseDelay.isZero()) {
        guild.teleportHome(player);
        user.sendMessage(messages.baseTeleport);
        return;
    }
    Duration time = player.hasPermission("funnyguilds.vip.baseTeleportTime") ? config.baseDelayVip : config.baseDelay;
    Location before = player.getLocation();
    Instant teleportStart = Instant.now();
    UserCache cache = user.getCache();
    cache.setTeleportation(Bukkit.getScheduler().runTaskTimer(this.plugin, () -> {
        if (!player.isOnline()) {
            cache.getTeleportation().cancel();
            cache.setTeleportation(null);
            return;
        }
        if (!LocationUtils.equals(player.getLocation(), before)) {
            cache.getTeleportation().cancel();
            user.sendMessage(messages.baseMove);
            cache.setTeleportation(null);
            player.getInventory().addItem(items);
            return;
        }
        if (Duration.between(teleportStart, Instant.now()).compareTo(time) > 0) {
            cache.getTeleportation().cancel();
            user.sendMessage(messages.baseTeleport);
            guild.teleportHome(player);
            cache.setTeleportation(null);
        }
    }, 0L, 10L));
    user.sendMessage(messages.baseDontMove.replace("{TIME}", Long.toString(time.getSeconds())));
}
Also used : Instant(java.time.Instant) Duration(java.time.Duration) ItemStack(org.bukkit.inventory.ItemStack) UserCache(net.dzikoysk.funnyguilds.user.UserCache) Location(org.bukkit.Location) AbstractFunnyCommand(net.dzikoysk.funnyguilds.feature.command.AbstractFunnyCommand) FunnyCommand(net.dzikoysk.funnycommands.stereotypes.FunnyCommand)

Example 2 with UserCache

use of net.dzikoysk.funnyguilds.user.UserCache in project FunnyGuilds by FunnyGuilds.

the class SpyCommand method execute.

@FunnyCommand(name = "${admin.spy.name}", permission = "funnyguilds.admin", acceptsExceeded = true, playerOnly = true)
public void execute(CommandSender sender) {
    UserCache cache = UserValidation.requireUserByName(sender.getName()).getCache();
    if (cache.isSpy()) {
        cache.setSpy(false);
        sendMessage(sender, (messages.adminStopSpy));
    } else {
        cache.setSpy(true);
        sendMessage(sender, (messages.adminStartSpy));
    }
}
Also used : UserCache(net.dzikoysk.funnyguilds.user.UserCache) AbstractFunnyCommand(net.dzikoysk.funnyguilds.feature.command.AbstractFunnyCommand) FunnyCommand(net.dzikoysk.funnycommands.stereotypes.FunnyCommand)

Example 3 with UserCache

use of net.dzikoysk.funnyguilds.user.UserCache in project FunnyGuilds by FunnyGuilds.

the class PlayerDeath method onDeath.

@EventHandler
public void onDeath(PlayerDeathEvent event) {
    Player playerVictim = event.getEntity();
    Player playerAttacker = event.getEntity().getKiller();
    Option<User> victimOption = this.userManager.findByPlayer(playerVictim);
    if (victimOption.isEmpty()) {
        return;
    }
    User victim = victimOption.get();
    UserCache victimCache = victim.getCache();
    DeathsChangeEvent deathsChangeEvent = new DeathsChangeEvent(EventCause.USER, victim, victim, 1);
    if (SimpleEventHandler.handle(deathsChangeEvent)) {
        victim.getRank().updateDeaths(currentValue -> currentValue + deathsChangeEvent.getDeathsChange());
    }
    if (playerAttacker == null) {
        if (!config.considerLastAttackerAsKiller) {
            victimCache.clearDamage();
            return;
        }
        User lastAttacker = victimCache.getLastKiller();
        if (lastAttacker == null || !lastAttacker.isOnline()) {
            victimCache.clearDamage();
            return;
        }
        Long attackTime = victimCache.wasVictimOf(lastAttacker);
        if (attackTime == null || attackTime + config.lastAttackerAsKillerConsiderationTimeout_ < System.currentTimeMillis()) {
            victimCache.clearDamage();
            return;
        }
        playerAttacker = lastAttacker.getPlayer().get();
    }
    Option<User> attackerOption = this.userManager.findByPlayer(playerAttacker);
    if (attackerOption.isEmpty()) {
        return;
    }
    User attacker = attackerOption.get();
    UserCache attackerCache = attacker.getCache();
    if (victim.equals(attacker)) {
        victimCache.clearDamage();
        return;
    }
    if (HookManager.WORLD_GUARD.isPresent()) {
        WorldGuardHook worldGuard = HookManager.WORLD_GUARD.get();
        if (worldGuard.isInNonPointsRegion(playerVictim.getLocation()) || worldGuard.isInNonPointsRegion(playerAttacker.getLocation())) {
            victimCache.clearDamage();
            return;
        }
    }
    if (config.rankFarmingProtect) {
        Long attackTimestamp = attackerCache.wasAttackerOf(victim);
        Long victimTimestamp = attackerCache.wasVictimOf(attacker);
        if (attackTimestamp != null) {
            if (attackTimestamp + (config.rankFarmingCooldown * 1000L) >= System.currentTimeMillis()) {
                ChatUtils.sendMessage(playerVictim, messages.rankLastVictimV);
                ChatUtils.sendMessage(playerAttacker, messages.rankLastVictimA);
                victimCache.clearDamage();
                event.setDeathMessage(null);
                return;
            }
        } else if (victimTimestamp != null) {
            if (victimTimestamp + (config.rankFarmingCooldown * 1000L) >= System.currentTimeMillis()) {
                ChatUtils.sendMessage(playerVictim, messages.rankLastAttackerV);
                ChatUtils.sendMessage(playerAttacker, messages.rankLastAttackerA);
                victimCache.clearDamage();
                event.setDeathMessage(null);
                return;
            }
        }
    }
    if (config.rankIPProtect) {
        String attackerIP = playerAttacker.getAddress().getHostString();
        if (attackerIP != null && attackerIP.equalsIgnoreCase(playerVictim.getAddress().getHostString())) {
            ChatUtils.sendMessage(playerVictim, messages.rankIPVictim);
            ChatUtils.sendMessage(playerAttacker, messages.rankIPAttacker);
            victimCache.clearDamage();
            event.setDeathMessage(null);
            return;
        }
    }
    int[] rankChanges = new int[2];
    int victimPoints = victim.getRank().getPoints();
    int attackerPoints = attacker.getRank().getPoints();
    RankSystem.RankResult result = rankSystem.calculate(config.rankSystem, attackerPoints, victimPoints);
    PointsChangeEvent attackerPointsChangeEvent = new PointsChangeEvent(EventCause.USER, attacker, attacker, result.getAttackerPoints());
    PointsChangeEvent victimPointsChangeEvent = new PointsChangeEvent(EventCause.USER, attacker, victim, -result.getVictimPoints());
    List<String> assistEntries = new ArrayList<>();
    List<User> messageReceivers = new ArrayList<>();
    int victimPointsBeforeChange = victim.getRank().getPoints();
    if (SimpleEventHandler.handle(attackerPointsChangeEvent) && SimpleEventHandler.handle(victimPointsChangeEvent)) {
        double attackerDamage = victimCache.killedBy(attacker);
        if (config.assistEnable && victimCache.isAssisted()) {
            double toShare = attackerPointsChangeEvent.getPointsChange() * (1 - config.assistKillerShare);
            double totalDamage = victimCache.getTotalDamage() + attackerDamage;
            int givenPoints = 0;
            Map<User, Double> damage = MapUtil.sortByValue(victimCache.getDamage());
            int assists = 0;
            for (Entry<User, Double> assist : damage.entrySet()) {
                User assistUser = assist.getKey();
                double assistFraction = assist.getValue() / totalDamage;
                int addedPoints = (int) Math.round(assistFraction * toShare);
                if (addedPoints <= 0) {
                    continue;
                }
                if (config.assistsLimit > 0) {
                    if (assists >= config.assistsLimit) {
                        break;
                    }
                    assists++;
                }
                PointsChangeEvent assistPointsChangeEvent = new PointsChangeEvent(EventCause.USER, assistUser, assistUser, addedPoints);
                if (!SimpleEventHandler.handle(assistPointsChangeEvent)) {
                    continue;
                }
                addedPoints = assistPointsChangeEvent.getPointsChange();
                if (!config.broadcastDeathMessage) {
                    messageReceivers.add(assistUser);
                }
                givenPoints += addedPoints;
                String assistEntry = StringUtils.replace(messages.rankAssistEntry, "{PLAYER}", assistUser.getName());
                assistEntry = StringUtils.replace(assistEntry, "{+}", Integer.toString(addedPoints));
                assistEntry = StringUtils.replace(assistEntry, "{SHARE}", ChatUtils.getPercent(assistFraction));
                assistEntries.add(assistEntry);
                int finalAddedPoints = addedPoints;
                assistUser.getRank().updatePoints(currentValue -> currentValue + finalAddedPoints);
                AssistsChangeEvent assistsChangeEvent = new AssistsChangeEvent(EventCause.USER, victim, assistUser, 1);
                if (SimpleEventHandler.handle(assistsChangeEvent)) {
                    assistUser.getRank().updateAssists(currentValue -> currentValue + assistsChangeEvent.getAssistsChange());
                }
            }
            double updatedAttackerPoints = attackerPointsChangeEvent.getPointsChange() - toShare + (givenPoints < toShare ? toShare - givenPoints : 0);
            attackerPointsChangeEvent.setPointsChange((int) Math.round(updatedAttackerPoints));
        }
        attacker.getRank().updatePoints(currentValue -> currentValue + attackerPointsChangeEvent.getPointsChange());
        KillsChangeEvent killsChangeEvent = new KillsChangeEvent(EventCause.USER, attacker, victim, 1);
        if (SimpleEventHandler.handle(killsChangeEvent)) {
            attacker.getRank().updateKills(currentValue -> currentValue + killsChangeEvent.getKillsChange());
        }
        attackerCache.registerVictim(victim);
        victimPointsBeforeChange = victim.getRank().getPoints();
        victim.getRank().updatePoints(currentValue -> currentValue + victimPointsChangeEvent.getPointsChange());
        victimCache.registerKiller(attacker);
        victimCache.clearDamage();
        if (!config.broadcastDeathMessage) {
            messageReceivers.add(attacker);
            messageReceivers.add(victim);
        }
    }
    ConcurrencyTaskBuilder taskBuilder = ConcurrencyTask.builder();
    if (config.dataModel == DataModel.MYSQL) {
        victim.getGuild().peek(guild -> taskBuilder.delegate(new DatabaseUpdateGuildPointsRequest(guild)));
        attacker.getGuild().peek(guild -> taskBuilder.delegate(new DatabaseUpdateGuildPointsRequest(guild)));
        taskBuilder.delegate(new DatabaseUpdateUserPointsRequest(victim));
        taskBuilder.delegate(new DatabaseUpdateUserPointsRequest(attacker));
    }
    this.concurrencyManager.postTask(taskBuilder.delegate(new DummyGlobalUpdateUserRequest(victim)).delegate(new DummyGlobalUpdateUserRequest(attacker)).build());
    Formatter killFormatter = new Formatter().register("{ATTACKER}", attacker.getName()).register("{VICTIM}", victim.getName()).register("{+}", Integer.toString(attackerPointsChangeEvent.getPointsChange())).register("{-}", Math.min(victimPointsBeforeChange, victimPointsChangeEvent.getPointsChange())).register("{POINTS-FORMAT}", NumberRange.inRangeToString(victimPoints, config.pointsFormat)).register("{POINTS}", Integer.toString(victim.getRank().getPoints())).register("{WEAPON}", MaterialUtils.getMaterialName(playerAttacker.getItemInHand().getType())).register("{WEAPON-NAME}", MaterialUtils.getItemCustomName(playerAttacker.getItemInHand())).register("{REMAINING-HEALTH}", String.format(Locale.US, "%.2f", playerAttacker.getHealth())).register("{REMAINING-HEARTS}", Integer.toString((int) (playerAttacker.getHealth() / 2))).register("{VTAG}", victim.getGuild().map(guild -> StringUtils.replace(config.chatGuild.getValue(), "{TAG}", guild.getTag())).orElseGet("")).register("{ATAG}", attacker.getGuild().map(guild -> StringUtils.replace(config.chatGuild.getValue(), "{TAG}", guild.getTag())).orElseGet("")).register("{ASSISTS}", config.assistEnable && !assistEntries.isEmpty() ? StringUtils.replace(messages.rankAssistMessage, "{ASSISTS}", String.join(messages.rankAssistDelimiter, assistEntries)) : "");
    if (config.displayTitleNotificationForKiller) {
        TitleMessage titleMessage = TitleMessage.builder().text(killFormatter.format(messages.rankKillTitle)).subText(killFormatter.format(messages.rankKillSubtitle)).fadeInDuration(config.notificationTitleFadeIn).stayDuration(config.notificationTitleStay).fadeOutDuration(config.notificationTitleFadeOut).build();
        plugin.getNmsAccessor().getMessageAccessor().sendTitleMessage(titleMessage, playerAttacker);
    }
    String deathMessage = killFormatter.format(messages.rankDeathMessage);
    if (config.broadcastDeathMessage) {
        if (config.ignoreDisabledDeathMessages) {
            for (Player player : event.getEntity().getWorld().getPlayers()) {
                event.setDeathMessage(null);
                ChatUtils.sendMessage(player, deathMessage);
            }
        } else {
            event.setDeathMessage(deathMessage);
        }
    } else {
        event.setDeathMessage(null);
        for (User fighter : messageReceivers) {
            fighter.sendMessage(deathMessage);
        }
    }
}
Also used : DummyGlobalUpdateUserRequest(net.dzikoysk.funnyguilds.concurrency.requests.dummy.DummyGlobalUpdateUserRequest) MaterialUtils(net.dzikoysk.funnyguilds.shared.bukkit.MaterialUtils) Player(org.bukkit.entity.Player) StringUtils(org.apache.commons.lang3.StringUtils) DeathsChangeEvent(net.dzikoysk.funnyguilds.event.rank.DeathsChangeEvent) ArrayList(java.util.ArrayList) Option(panda.std.Option) DatabaseUpdateGuildPointsRequest(net.dzikoysk.funnyguilds.concurrency.requests.database.DatabaseUpdateGuildPointsRequest) UserCache(net.dzikoysk.funnyguilds.user.UserCache) EventHandler(org.bukkit.event.EventHandler) AssistsChangeEvent(net.dzikoysk.funnyguilds.event.rank.AssistsChangeEvent) Locale(java.util.Locale) Map(java.util.Map) ConcurrencyTaskBuilder(net.dzikoysk.funnyguilds.concurrency.ConcurrencyTaskBuilder) DatabaseUpdateUserPointsRequest(net.dzikoysk.funnyguilds.concurrency.requests.database.DatabaseUpdateUserPointsRequest) RankSystem(net.dzikoysk.funnyguilds.rank.RankSystem) User(net.dzikoysk.funnyguilds.user.User) Formatter(panda.utilities.text.Formatter) DataModel(net.dzikoysk.funnyguilds.config.PluginConfiguration.DataModel) TitleMessage(net.dzikoysk.funnyguilds.nms.api.message.TitleMessage) PointsChangeEvent(net.dzikoysk.funnyguilds.event.rank.PointsChangeEvent) MapUtil(net.dzikoysk.funnyguilds.shared.MapUtil) ConcurrencyTask(net.dzikoysk.funnyguilds.concurrency.ConcurrencyTask) SimpleEventHandler(net.dzikoysk.funnyguilds.event.SimpleEventHandler) List(java.util.List) PlayerDeathEvent(org.bukkit.event.entity.PlayerDeathEvent) EventCause(net.dzikoysk.funnyguilds.event.FunnyEvent.EventCause) NumberRange(net.dzikoysk.funnyguilds.config.NumberRange) KillsChangeEvent(net.dzikoysk.funnyguilds.event.rank.KillsChangeEvent) Entry(java.util.Map.Entry) PluginConfiguration(net.dzikoysk.funnyguilds.config.PluginConfiguration) HookManager(net.dzikoysk.funnyguilds.feature.hooks.HookManager) WorldGuardHook(net.dzikoysk.funnyguilds.feature.hooks.worldguard.WorldGuardHook) ChatUtils(net.dzikoysk.funnyguilds.shared.bukkit.ChatUtils) User(net.dzikoysk.funnyguilds.user.User) Formatter(panda.utilities.text.Formatter) ArrayList(java.util.ArrayList) UserCache(net.dzikoysk.funnyguilds.user.UserCache) DatabaseUpdateUserPointsRequest(net.dzikoysk.funnyguilds.concurrency.requests.database.DatabaseUpdateUserPointsRequest) DatabaseUpdateGuildPointsRequest(net.dzikoysk.funnyguilds.concurrency.requests.database.DatabaseUpdateGuildPointsRequest) WorldGuardHook(net.dzikoysk.funnyguilds.feature.hooks.worldguard.WorldGuardHook) TitleMessage(net.dzikoysk.funnyguilds.nms.api.message.TitleMessage) ConcurrencyTaskBuilder(net.dzikoysk.funnyguilds.concurrency.ConcurrencyTaskBuilder) DeathsChangeEvent(net.dzikoysk.funnyguilds.event.rank.DeathsChangeEvent) Player(org.bukkit.entity.Player) RankSystem(net.dzikoysk.funnyguilds.rank.RankSystem) AssistsChangeEvent(net.dzikoysk.funnyguilds.event.rank.AssistsChangeEvent) KillsChangeEvent(net.dzikoysk.funnyguilds.event.rank.KillsChangeEvent) DummyGlobalUpdateUserRequest(net.dzikoysk.funnyguilds.concurrency.requests.dummy.DummyGlobalUpdateUserRequest) PointsChangeEvent(net.dzikoysk.funnyguilds.event.rank.PointsChangeEvent) EventHandler(org.bukkit.event.EventHandler) SimpleEventHandler(net.dzikoysk.funnyguilds.event.SimpleEventHandler)

Example 4 with UserCache

use of net.dzikoysk.funnyguilds.user.UserCache in project FunnyGuilds by FunnyGuilds.

the class PlayerQuit method handleQuit.

private void handleQuit(Player player) {
    Option<User> userOption = this.userManager.findByPlayer(player);
    if (userOption.isEmpty()) {
        return;
    }
    User user = userOption.get();
    UserCache cache = user.getCache();
    if (cache.isInCombat()) {
        user.getRank().updateLogouts(currentValue -> currentValue + 1);
    }
    cache.setIndividualPrefix(null);
    cache.setScoreboard(null);
    cache.setDummy(null);
    cache.setPlayerList(null);
    cache.clearDamage();
    user.getBossBar().removeNotification();
}
Also used : User(net.dzikoysk.funnyguilds.user.User) UserCache(net.dzikoysk.funnyguilds.user.UserCache)

Example 5 with UserCache

use of net.dzikoysk.funnyguilds.user.UserCache in project FunnyGuilds by FunnyGuilds.

the class FunnyGuilds method handleReload.

private void handleReload() {
    for (Player player : this.getServer().getOnlinePlayers()) {
        final FunnyGuildsChannelHandler channelHandler = nmsAccessor.getPacketAccessor().getOrInstallChannelHandler(player);
        Option<User> userOption = userManager.findByPlayer(player);
        if (userOption.isEmpty()) {
            continue;
        }
        User user = userOption.get();
        channelHandler.getPacketCallbacksRegistry().registerPacketCallback(new WarPacketCallbacks(user));
        UserCache cache = user.getCache();
        cache.updateScoreboardIfNull(player);
        cache.getDummy();
        if (!this.tablistConfiguration.playerListEnable) {
            continue;
        }
        IndividualPlayerList individualPlayerList = new IndividualPlayerList(user, this.getNmsAccessor().getPlayerListAccessor(), this.tablistConfiguration.playerList, this.tablistConfiguration.playerListHeader, this.tablistConfiguration.playerListFooter, this.tablistConfiguration.pages, this.tablistConfiguration.playerListPing, this.tablistConfiguration.playerListFillCells, this.pluginConfiguration.top.enableLegacyPlaceholders);
        cache.setPlayerList(individualPlayerList);
    }
    for (Guild guild : this.guildManager.getGuilds()) {
        if (this.pluginConfiguration.heart.createEntityType != null) {
            GuildEntityHelper.spawnGuildHeart(guild);
        }
    }
}
Also used : IndividualPlayerList(net.dzikoysk.funnyguilds.feature.tablist.IndividualPlayerList) Player(org.bukkit.entity.Player) User(net.dzikoysk.funnyguilds.user.User) FunnyGuildsChannelHandler(net.dzikoysk.funnyguilds.nms.api.packet.FunnyGuildsChannelHandler) WarPacketCallbacks(net.dzikoysk.funnyguilds.feature.war.WarPacketCallbacks) UserCache(net.dzikoysk.funnyguilds.user.UserCache) Guild(net.dzikoysk.funnyguilds.guild.Guild)

Aggregations

UserCache (net.dzikoysk.funnyguilds.user.UserCache)9 User (net.dzikoysk.funnyguilds.user.User)6 Player (org.bukkit.entity.Player)5 Location (org.bukkit.Location)3 EventHandler (org.bukkit.event.EventHandler)3 Option (panda.std.Option)3 FunnyCommand (net.dzikoysk.funnycommands.stereotypes.FunnyCommand)2 DummyGlobalUpdateUserRequest (net.dzikoysk.funnyguilds.concurrency.requests.dummy.DummyGlobalUpdateUserRequest)2 PluginConfiguration (net.dzikoysk.funnyguilds.config.PluginConfiguration)2 EventCause (net.dzikoysk.funnyguilds.event.FunnyEvent.EventCause)2 SimpleEventHandler (net.dzikoysk.funnyguilds.event.SimpleEventHandler)2 AbstractFunnyCommand (net.dzikoysk.funnyguilds.feature.command.AbstractFunnyCommand)2 IndividualPlayerList (net.dzikoysk.funnyguilds.feature.tablist.IndividualPlayerList)2 WarPacketCallbacks (net.dzikoysk.funnyguilds.feature.war.WarPacketCallbacks)2 Guild (net.dzikoysk.funnyguilds.guild.Guild)2 TitleMessage (net.dzikoysk.funnyguilds.nms.api.message.TitleMessage)2 FunnyGuildsChannelHandler (net.dzikoysk.funnyguilds.nms.api.packet.FunnyGuildsChannelHandler)2 ChatUtils (net.dzikoysk.funnyguilds.shared.bukkit.ChatUtils)2 Bukkit (org.bukkit.Bukkit)2 Formatter (panda.utilities.text.Formatter)2