Search in sources :

Example 21 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Nucleus by NucleusPowered.

the class AFKHandler method onTick.

public void onTick() {
    synchronized (lock) {
        activity.forEach(u -> data.compute(u, ((uuid, afkData) -> afkData == null ? new AFKData(uuid) : updateActivity(uuid, afkData))));
        activity.clear();
    }
    List<UUID> uuidList = Sponge.getServer().getOnlinePlayers().stream().map(Player::getUniqueId).collect(Collectors.toList());
    // Remove all offline players.
    Set<Map.Entry<UUID, AFKData>> entries = data.entrySet();
    entries.removeIf(refactor -> !uuidList.contains(refactor.getKey()));
    entries.stream().filter(x -> !x.getValue().cacheValid).forEach(x -> x.getValue().updateFromPermissions());
    long now = System.currentTimeMillis();
    // Check AFK status.
    entries.stream().filter(x -> x.getValue().isKnownAfk && !x.getValue().willKick && x.getValue().timeToKick > 0).forEach(e -> {
        if (now - e.getValue().lastActivityTime > e.getValue().timeToKick) {
            // Kick them
            e.getValue().willKick = true;
            NucleusTextTemplateImpl message = config.getMessages().getKickMessage();
            TextRepresentable t;
            if (message == null || message.isEmpty()) {
                t = Nucleus.getNucleus().getMessageProvider().getTextMessageWithTextFormat("afk.kickreason");
            } else {
                t = message;
            }
            final NucleusTextTemplateImpl messageToServer = config.getMessages().getOnKick();
            Sponge.getServer().getPlayer(e.getKey()).ifPresent(player -> {
                MessageChannel mc;
                if (config.isBroadcastOnKick()) {
                    mc = MessageChannel.TO_ALL;
                } else {
                    mc = MessageChannel.permission(this.afkPermissionHandler.getPermissionWithSuffix("notify"));
                }
                AFKEvents.Kick events = new AFKEvents.Kick(player, messageToServer.getForCommandSource(player), mc);
                if (Sponge.getEventManager().post(events)) {
                    // Cancelled.
                    return;
                }
                Text toSend = t instanceof NucleusTextTemplateImpl ? ((NucleusTextTemplateImpl) t).getForCommandSource(player) : t.toText();
                Sponge.getScheduler().createSyncExecutor(Nucleus.getNucleus()).execute(() -> player.kick(toSend));
                events.getMessage().ifPresent(m -> events.getChannel().send(player, m, ChatTypes.SYSTEM));
            });
        }
    });
    // Check AFK status.
    entries.stream().filter(x -> !x.getValue().isKnownAfk && x.getValue().timeToAfk > 0).forEach(e -> {
        if (now - e.getValue().lastActivityTime > e.getValue().timeToAfk) {
            Sponge.getServer().getPlayer(e.getKey()).ifPresent(this::setAfk);
        }
    });
}
Also used : AFKConfig(io.github.nucleuspowered.nucleus.modules.afk.config.AFKConfig) ChatTypes(org.spongepowered.api.text.chat.ChatTypes) Keys(org.spongepowered.api.data.key.Keys) TextRepresentable(org.spongepowered.api.text.TextRepresentable) NoExceptionAutoClosable(io.github.nucleuspowered.nucleus.api.util.NoExceptionAutoClosable) NucleusPlugin(io.github.nucleuspowered.nucleus.NucleusPlugin) Multimap(com.google.common.collect.Multimap) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) Text(org.spongepowered.api.text.Text) Duration(java.time.Duration) Map(java.util.Map) Task(org.spongepowered.api.scheduler.Task) Util(io.github.nucleuspowered.nucleus.Util) NucleusAFKService(io.github.nucleuspowered.nucleus.api.service.NucleusAFKService) ServiceChangeListener(io.github.nucleuspowered.nucleus.internal.permissions.ServiceChangeListener) PluginContainer(org.spongepowered.api.plugin.PluginContainer) AFKConfigAdapter(io.github.nucleuspowered.nucleus.modules.afk.config.AFKConfigAdapter) CommandPermissionHandler(io.github.nucleuspowered.nucleus.internal.CommandPermissionHandler) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) User(org.spongepowered.api.entity.living.player.User) CauseStackHelper(io.github.nucleuspowered.nucleus.util.CauseStackHelper) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) Tuple(org.spongepowered.api.util.Tuple) UUID(java.util.UUID) Instant(java.time.Instant) GuardedBy(javax.annotation.concurrent.GuardedBy) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) AFKCommand(io.github.nucleuspowered.nucleus.modules.afk.commands.AFKCommand) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Player(org.spongepowered.api.entity.living.player.Player) NucleusTextTemplateImpl(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl) AFKEvents(io.github.nucleuspowered.nucleus.modules.afk.events.AFKEvents) TextRepresentable(org.spongepowered.api.text.TextRepresentable) NucleusTextTemplateImpl(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl) Text(org.spongepowered.api.text.Text) AFKEvents(io.github.nucleuspowered.nucleus.modules.afk.events.AFKEvents) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) UUID(java.util.UUID)

Example 22 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Nucleus by NucleusPowered.

the class KickCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Player pl = args.<Player>getOne(player).get();
    String r = args.<String>getOne(reason).orElse(plugin.getMessageProvider().getMessageWithFormat("command.kick.defaultreason"));
    if (permissions.testSuffix(pl, "exempt.target", src, false)) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.kick.exempt", pl.getName()));
    }
    pl.kick(TextSerializers.FORMATTING_CODE.deserialize(r));
    MessageChannel mc = new PermissionMessageChannel(permissions.getPermissionWithSuffix("notify"));
    mc.send(plugin.getMessageProvider().getTextMessageWithFormat("command.kick.message", pl.getName(), src.getName()));
    mc.send(plugin.getMessageProvider().getTextMessageWithFormat("command.reason", r));
    return CommandResult.success();
}
Also used : PermissionMessageChannel(io.github.nucleuspowered.nucleus.util.PermissionMessageChannel) Player(org.spongepowered.api.entity.living.player.Player) PermissionMessageChannel(io.github.nucleuspowered.nucleus.util.PermissionMessageChannel) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException)

Example 23 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Nucleus by NucleusPowered.

the class StaffChatCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Optional<String> toSend = args.getOne(message);
    if (toSend.isPresent()) {
        try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
            frame.addContext(EventContexts.SHOULD_FORMAT_CHANNEL, StaffChatMessageChannel.getInstance().formatMessages());
            if (src instanceof Player) {
                Player pl = (Player) src;
                frame.pushCause(pl);
                frame.addContext(EventContextKeys.PLAYER_SIMULATED, pl.getProfile());
                MessageChannel mc = pl.getMessageChannel();
                pl.setMessageChannel(StaffChatMessageChannel.getInstance());
                pl.simulateChat(TextParsingUtils.addUrls(toSend.get()), Sponge.getCauseStackManager().getCurrentCause());
                pl.setMessageChannel(mc);
            } else {
                StaffChatMessageChannel.getInstance().send(src, TextParsingUtils.addUrls(toSend.get()), ChatTypes.CHAT);
            }
            return CommandResult.success();
        }
    }
    if (!(src instanceof Player)) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.staffchat.consoletoggle"));
    }
    Player player = (Player) src;
    StaffChatTransientModule s = plugin.getUserDataManager().get(player).map(y -> y.getTransient(StaffChatTransientModule.class)).orElseGet(StaffChatTransientModule::new);
    boolean result = !(src.getMessageChannel() instanceof StaffChatMessageChannel);
    if (result) {
        s.setPreviousMessageChannel(player.getMessageChannel());
        src.setMessageChannel(StaffChatMessageChannel.getInstance());
    } else {
        src.setMessageChannel(s.getPreviousMessageChannel().orElse(MessageChannel.TO_ALL));
    }
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.staffchat." + (result ? "on" : "off")));
    return CommandResult.success();
}
Also used : ChatTypes(org.spongepowered.api.text.chat.ChatTypes) RegisterCommand(io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand) EventContextKeys(org.spongepowered.api.event.cause.EventContextKeys) RemainingStringsArgument(io.github.nucleuspowered.nucleus.argumentparsers.RemainingStringsArgument) TextParsingUtils(io.github.nucleuspowered.nucleus.internal.text.TextParsingUtils) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) SuggestedLevel(io.github.nucleuspowered.nucleus.internal.permissions.SuggestedLevel) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Permissions(io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions) NoModifiers(io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers) CommandResult(org.spongepowered.api.command.CommandResult) EventContexts(io.github.nucleuspowered.nucleus.api.EventContexts) CommandSource(org.spongepowered.api.command.CommandSource) StaffChatMessageChannel(io.github.nucleuspowered.nucleus.modules.staffchat.StaffChatMessageChannel) Sponge(org.spongepowered.api.Sponge) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) CommandElement(org.spongepowered.api.command.args.CommandElement) AbstractCommand(io.github.nucleuspowered.nucleus.internal.command.AbstractCommand) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) StaffChatTransientModule(io.github.nucleuspowered.nucleus.modules.staffchat.datamodules.StaffChatTransientModule) Player(org.spongepowered.api.entity.living.player.Player) StaffChatMessageChannel(io.github.nucleuspowered.nucleus.modules.staffchat.StaffChatMessageChannel) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) CauseStackManager(org.spongepowered.api.event.CauseStackManager) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) StaffChatTransientModule(io.github.nucleuspowered.nucleus.modules.staffchat.datamodules.StaffChatTransientModule) StaffChatMessageChannel(io.github.nucleuspowered.nucleus.modules.staffchat.StaffChatMessageChannel)

Example 24 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Nucleus by NucleusPowered.

the class MessageHandler method sendMessage.

@Override
public boolean sendMessage(CommandSource sender, CommandSource receiver, String message) {
    // Message is about to be sent. Send the event out. If canceled, then that's that.
    boolean isBlocked = false;
    boolean isCancelled = Sponge.getEventManager().post(new InternalNucleusMessageEvent(sender, receiver, message));
    if (isCancelled) {
        sender.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("message.cancel"));
        // Only continue to show Social Spy messages if the subject is muted.
        if (!messageConfig.isShowMessagesInSocialSpyWhileMuted()) {
            return false;
        }
    }
    // What about msgtoggle?
    if (receiver instanceof Player && !sender.hasPermission(this.msgToggleBypass) && ucl.get((Player) receiver).map(x -> !x.get(MessageUserDataModule.class).isMsgToggle()).orElse(false)) {
        isCancelled = true;
        isBlocked = true;
        sender.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithTextFormat("message.blocked", Nucleus.getNucleus().getNameUtil().getName((Player) receiver)));
        if (!messageConfig.isShowMessagesInSocialSpyWhileMuted()) {
            return false;
        }
    }
    // Social Spies.
    final UUID uuidSender = getUUID(sender);
    final UUID uuidReceiver = getUUID(receiver);
    final Map<String, Object> variables = Maps.newHashMap();
    variables.put("from", sender);
    variables.put("to", receiver);
    // Create the tokens.
    Map<String, Function<CommandSource, Optional<Text>>> tokens = Maps.newHashMap();
    tokens.put("from", cs -> getNameFromCommandSource(sender, textParsingUtils::addCommandToName));
    tokens.put("to", cs -> getNameFromCommandSource(receiver, textParsingUtils::addCommandToName));
    tokens.put("fromdisplay", cs -> getNameFromCommandSource(sender, textParsingUtils::addCommandToDisplayName));
    tokens.put("todisplay", cs -> getNameFromCommandSource(receiver, textParsingUtils::addCommandToDisplayName));
    Text tm = useMessage(sender, message);
    if (!isCancelled) {
        sender.sendMessage(constructMessage(sender, tm, messageConfig.getMessageSenderPrefix(), tokens, variables));
        receiver.sendMessage(constructMessage(sender, tm, messageConfig.getMessageReceiverPrefix(), tokens, variables));
    }
    NucleusTextTemplateImpl prefix = messageConfig.getMessageSocialSpyPrefix();
    if (isBlocked) {
        prefix = NucleusTextTemplateFactory.createFromAmpersandString(messageConfig.getBlockedTag() + prefix.getRepresentation());
    }
    if (isCancelled) {
        prefix = NucleusTextTemplateFactory.createFromAmpersandString(messageConfig.getMutedTag() + prefix.getRepresentation());
    }
    MessageConfig.Targets targets = messageConfig.spyOn();
    if (sender instanceof Player && targets.isPlayer() || sender instanceof ConsoleSource && targets.isCustom() || targets.isCustom()) {
        Set<CommandSource> lm = onlinePlayersCanSpyOn(!uuidSender.equals(Util.consoleFakeUUID) && !uuidReceiver.equals(Util.consoleFakeUUID), sender, receiver);
        MessageChannel mc = MessageChannel.fixed(lm);
        if (!mc.getMembers().isEmpty()) {
            mc.send(constructMessage(sender, tm, prefix, tokens, variables));
        }
    }
    // Add the UUIDs to the reply list - the receiver will now reply to the sender.
    if (!isCancelled) {
        messagesReceived.put(uuidReceiver, uuidSender);
    }
    return !isCancelled;
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) NucleusTextTemplateImpl(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl) Text(org.spongepowered.api.text.Text) CommandSource(org.spongepowered.api.command.CommandSource) Function(java.util.function.Function) MessageConfig(io.github.nucleuspowered.nucleus.modules.message.config.MessageConfig) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) MessageUserDataModule(io.github.nucleuspowered.nucleus.modules.message.datamodules.MessageUserDataModule) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) UUID(java.util.UUID) InternalNucleusMessageEvent(io.github.nucleuspowered.nucleus.modules.message.events.InternalNucleusMessageEvent)

Aggregations

MessageChannel (org.spongepowered.api.text.channel.MessageChannel)24 Player (org.spongepowered.api.entity.living.player.Player)17 Text (org.spongepowered.api.text.Text)17 MessageEvent (org.spongepowered.api.event.message.MessageEvent)11 UUID (java.util.UUID)6 ClientConnectionEvent (org.spongepowered.api.event.network.ClientConnectionEvent)5 Instant (java.time.Instant)4 MessageChannelEvent (org.spongepowered.api.event.message.MessageChannelEvent)4 NucleusTextTemplateImpl (io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl)3 Optional (java.util.Optional)3 Sponge (org.spongepowered.api.Sponge)3 User (org.spongepowered.api.entity.living.player.User)3 Listener (org.spongepowered.api.event.Listener)3 Cause (org.spongepowered.api.event.cause.Cause)3 ChatTypes (org.spongepowered.api.text.chat.ChatTypes)3 Preconditions (com.google.common.base.Preconditions)2 HashMultimap (com.google.common.collect.HashMultimap)2 Lists (com.google.common.collect.Lists)2 Maps (com.google.common.collect.Maps)2 Multimap (com.google.common.collect.Multimap)2