whisper & other command cleanup

This commit is contained in:
Jason Penilla authored and Jason committed 2023-08-08 09:23:57 -07:00
1 parent b46f6c6016
commit 44b6c26554
9 files changed
+141 -237

No files matched your search

@@ -1,40 +1,35 @@
//
// MIT License
//
// Copyright (c) 2021 Alexander Söderberg & Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.command.argument;
import cloud.commandframework.ArgumentDescription;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.captions.Caption;
import cloud.commandframework.captions.CaptionVariable;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.exceptions.parsing.NoInputProvidedException;
import cloud.commandframework.exceptions.parsing.ParserException;
import cloud.commandframework.keys.CloudKey;
import cloud.commandframework.keys.SimpleCloudKey;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import io.leangen.geantyref.TypeToken;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
@@ -42,14 +37,13 @@ import java.util.function.BiFunction;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.exception.ComponentException;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.users.ProfileResolver;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* Argument that parses into a {@link CarbonPlayer}.
*/
@DefaultQualifier(NonNull.class)
public final class CarbonPlayerArgument extends CommandArgument<Commander, CarbonPlayer> {
@@ -60,26 +54,21 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
final @Nullable BiFunction<CommandContext<Commander>, String,
List<String>> suggestionsProvider,
final ArgumentDescription defaultDescription,
final CarbonPlayerParser parser
final Parser parser
) {
super(required, name, parser, defaultValue, CarbonPlayer.class, suggestionsProvider, defaultDescription);
}
public static final class Builder extends CommandArgument.TypedBuilder<Commander, CarbonPlayer, Builder> {
private final CarbonPlayerParser parser;
private final Parser parser;
@AssistedInject
private Builder(final @Assisted String name, final CarbonPlayerParser parser) {
private Builder(final @Assisted String name, final Parser parser) {
super(CarbonPlayer.class, name);
this.parser = parser;
}
/**
* Builder a new boolean component.
*
* @return constructed component
*/
@Override
public CarbonPlayerArgument build() {
return new CarbonPlayerArgument(
@@ -94,21 +83,27 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
}
public static final class CarbonPlayerParser implements ArgumentParser<Commander, CarbonPlayer> {
public static final class Parser implements ArgumentParser<Commander, CarbonPlayer> {
// This hack only works properly when there is 0 or 1 CarbonPlayerArguments in a chain, since we don't use the arg name
public static CloudKey<String> INPUT_STRING = SimpleCloudKey.of(Parser.class.getSimpleName() + "-input", TypeToken.get(String.class));
private final PlayerSuggestions suggestions;
private final UserManager<?> userManager;
private final ProfileResolver profileResolver;
private final CarbonMessages messages;
@Inject
private CarbonPlayerParser(
private Parser(
final PlayerSuggestions suggestions,
final UserManager<?> userManager,
final ProfileResolver profileResolver
final ProfileResolver profileResolver,
final CarbonMessages messages
) {
this.suggestions = suggestions;
this.userManager = userManager;
this.profileResolver = profileResolver;
this.messages = messages;
}
@Override
@@ -116,14 +111,7 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
final CommandContext<Commander> commandContext,
final Queue<String> inputQueue
) {
final @Nullable String input = inputQueue.peek();
if (input == null) {
return ArgumentParseResult.failure(new NoInputProvidedException(
CarbonPlayerParser.class,
commandContext
));
}
final String input = inputQueue.peek();
final @Nullable CarbonPlayer join = this.profileResolver.resolveUUID(input, commandContext.isSuggestions()).thenCompose(uuid -> {
if (uuid == null) {
@@ -133,9 +121,10 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
}).join();
if (join == null) {
return ArgumentParseResult.failure(new CarbonPlayerParseException(input, commandContext));
return ArgumentParseResult.failure(new ParseException(input, this.messages));
}
commandContext.store(INPUT_STRING, input);
inputQueue.remove();
return ArgumentParseResult.success(join);
}
@@ -150,38 +139,16 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
}
/**
* CarbonPlayer parse exception.
*/
public static final class CarbonPlayerParseException extends ParserException {
public static final class ParseException extends ComponentException {
private static final long serialVersionUID = -8331761537951077684L;
private final String input;
/**
* Construct a new CarbonPlayer parse exception.
*
* @param input string input
* @param context command context
*/
public CarbonPlayerParseException(
final String input,
final CommandContext<?> context
) {
super(
CarbonPlayerParser.class,
context,
Caption.of("argument.parse.failure.player"),
CaptionVariable.of("input", input)
);
public ParseException(final String input, final CarbonMessages messages) {
super(messages.errorCommandInvalidPlayer(input));
this.input = input;
}
/**
* Get the supplied input.
*
* @return string value
*/
public String input() {
return this.input;
}
@@ -1,117 +0,0 @@
/*
* PermissionsEx
* Copyright (C) zml and PermissionsEx contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.draycia.carbon.common.command.argument;
import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.exceptions.parsing.NoInputProvidedException;
import java.util.Queue;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public final class OptionValueParser<C> implements ArgumentParser<C, String> {
private static final char ESCAPE = '\\';
private static final String FLAG_STARTER = "-";
public OptionValueParser() {
}
@Override
public @NonNull ArgumentParseResult<@NonNull String> parse(
@NonNull final CommandContext<@NonNull C> commandContext,
@NonNull final Queue<@NonNull String> inputQueue
) {
final @Nullable String input = inputQueue.peek();
if (input == null || input.startsWith(FLAG_STARTER)) {
return ArgumentParseResult.failure(new NoInputProvidedException(
OptionValueParser.class,
commandContext
));
}
final char startChar = input.charAt(0);
// If quoted string: read until a word ending with a quote
if (startChar == '\'' || startChar == '\"') {
final StringBuilder result = new StringBuilder();
result.append(inputQueue.remove(), 1, input.length());
@Nullable String next;
while ((next = inputQueue.peek()) != null) {
result.append(" ");
if (next.length() > 0 && next.charAt(next.length() - 1) == startChar) {
// We've found the end of a quoted string, maybe
// if escaped, append without escape then continue
if (next.charAt(next.length() - 1) == ESCAPE) {
result.append(inputQueue.remove(), 0, next.length() - 2)
.append(startChar);
continue;
} else {
result.append(inputQueue.remove(), 0, next.length() - 1);
// then return our full quoted string
return ArgumentParseResult.success(result.toString());
}
}
result.append(inputQueue.remove());
}
// If we made it to the end without finding an end quote, throw an error
return ArgumentParseResult.failure(new MissingEndQuoteException(input));
} else { // otherwise, read until end of line, or a word starting with '-'
final StringBuilder result = new StringBuilder();
result.append(inputQueue.remove());
@Nullable String next;
while ((next = inputQueue.peek()) != null) {
if (next.startsWith(FLAG_STARTER)) {
break;
}
result.append(" ").append(inputQueue.remove());
}
return ArgumentParseResult.success(result.toString());
}
}
@Override
public boolean isContextFree() {
return true;
}
public static final class MissingEndQuoteException extends RuntimeException {
private static final long serialVersionUID = 2969516711506622423L;
private final String input;
public MissingEndQuoteException(
final @NonNull String input
) {
this.input = input;
}
public @NonNull String input() {
return this.input;
}
@Override
public String getMessage() {
return "Missing end quote for input: '" + this.input + "'";
}
}
}
@@ -80,15 +80,15 @@ public class ContinueCommand extends CarbonCommand {
.permission("carbon.whisper.continue")
.senderType(PlayerCommander.class)
.meta(MinecraftExtrasMetaKeys.DESCRIPTION, this.carbonMessages.commandContinueDescription())
.handler(handler -> {
final CarbonPlayer sender = ((PlayerCommander) handler.getSender()).carbonPlayer();
.handler(ctx -> {
final CarbonPlayer sender = ((PlayerCommander) ctx.getSender()).carbonPlayer();
if (sender.muted()) {
this.carbonMessages.muteCannotSpeak(sender);
return;
}
final String message = handler.get("message");
final String message = ctx.get("message");
final UUID whisperTarget = sender.lastWhisperTarget();
if (whisperTarget == null) {
@@ -81,15 +81,15 @@ public class ReplyCommand extends CarbonCommand {
.permission("carbon.whisper.reply")
.senderType(PlayerCommander.class)
.meta(MinecraftExtrasMetaKeys.DESCRIPTION, this.carbonMessages.commandReplyDescription())
.handler(handler -> {
final CarbonPlayer sender = ((PlayerCommander) handler.getSender()).carbonPlayer();
.handler(ctx -> {
final CarbonPlayer sender = ((PlayerCommander) ctx.getSender()).carbonPlayer();
if (sender.muted()) {
this.carbonMessages.muteCannotSpeak(sender);
return;
}
final String message = handler.get("message");
final String message = ctx.get("message");
final @Nullable UUID replyTarget = sender.whisperReplyTarget();
if (replyTarget == null) {
@@ -36,6 +36,7 @@ import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl;
import net.draycia.carbon.common.messages.CarbonMessages;
@@ -43,6 +44,7 @@ import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.messaging.packets.PacketFactory;
import net.draycia.carbon.common.messaging.packets.WhisperPacket;
import net.draycia.carbon.common.users.NetworkUsers;
import net.draycia.carbon.common.util.CloudUtils;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
@@ -85,7 +87,7 @@ public class WhisperCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(this.argumentFactory.carbonPlayer("player").asRequired(),
.argument(this.argumentFactory.carbonPlayer("player"),
RichDescription.of(this.carbonMessages.commandWhisperArgumentPlayer()))
.argument(StringArgument.greedy("message"),
RichDescription.of(this.carbonMessages.commandWhisperArgumentMessage()))
@@ -103,7 +105,7 @@ public class WhisperCommand extends CarbonCommand {
final String message = ctx.get("message");
final CarbonPlayer recipient = ctx.get("player");
this.whisper.whisper(sender, recipient, message);
this.whisper.whisper(sender, recipient, message, ctx.getOrDefault(CarbonPlayerArgument.Parser.INPUT_STRING, null));
})
.build();
@@ -113,7 +115,7 @@ public class WhisperCommand extends CarbonCommand {
public static final class WhisperHandler {
private final Logger logger;
private final CarbonMessages carbonMessages;
private final CarbonMessages messages;
private final ConfigFactory configFactory;
private final Provider<MessagingManager> messaging;
private final PacketFactory packetFactory;
@@ -125,7 +127,7 @@ public class WhisperCommand extends CarbonCommand {
@Inject
private WhisperHandler(
final Logger logger,
final CarbonMessages carbonMessages,
final CarbonMessages messages,
final ConfigFactory configFactory,
final Provider<MessagingManager> messaging,
final PacketFactory packetFactory,
@@ -135,7 +137,7 @@ public class WhisperCommand extends CarbonCommand {
final NetworkUsers network
) {
this.logger = logger;
this.carbonMessages = carbonMessages;
this.messages = messages;
this.configFactory = configFactory;
this.messaging = messaging;
this.packetFactory = packetFactory;
@@ -149,30 +151,39 @@ public class WhisperCommand extends CarbonCommand {
final CarbonPlayer sender,
final CarbonPlayer recipient,
final String message
) {
this.whisper(sender, recipient, message, null);
}
public void whisper(
final CarbonPlayer sender,
final CarbonPlayer recipient,
final String message,
final @Nullable String recipientInputString
) {
if (sender.equals(recipient)) {
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
this.messages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
return;
}
if (!this.network.online(recipient) || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
//final var rawNameInput = CloudUtils.rawInputByMatchingName(ctx.getRawInput(), recipient);
//final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(/*rawNameInput*/ recipient.username(), null);
// todo
this.carbonMessages.errorCommandArgumentParsing(sender, Component.text("No such player " + recipient.username()));
final var exception = new CarbonPlayerArgument.ParseException(
recipientInputString == null ? recipient.username() : recipientInputString,
this.messages
);
this.messages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
}
final boolean localRecipient = recipient.online();
if (sender.ignoring(recipient)) {
this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient));
this.messages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient));
return;
}
if (recipient.ignoring(sender)) {
this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient));
this.messages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient));
return;
}
@@ -183,15 +194,15 @@ public class WhisperCommand extends CarbonCommand {
this.events.emit(privateChatEvent);
if (privateChatEvent.cancelled()) {
this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient));
this.messages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient));
return;
}
this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message());
this.messages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message());
if (localRecipient) {
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message());
this.messages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message());
}
this.carbonMessages.whisperConsoleLog(this.server.console(), senderName, recipientName, privateChatEvent.message());
this.messages.whisperConsoleLog(this.server.console(), senderName, recipientName, privateChatEvent.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (localRecipient && messageSound != null) {
@@ -222,8 +233,8 @@ public class WhisperCommand extends CarbonCommand {
final Component recipientName = CarbonPlayer.renderName(recipient);
recipient.whisperReplyTarget(sender.uuid());
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, packet.message());
this.carbonMessages.whisperConsoleLog(this.server.console(), senderName, recipientName, packet.message());
this.messages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, packet.message());
this.messages.whisperConsoleLog(this.server.console(), senderName, recipientName, packet.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (messageSound != null) {
recipient.playSound(messageSound);
@@ -21,21 +21,17 @@ package net.draycia.carbon.common.command.exception;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.kyori.adventure.util.ComponentMessageThrowable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class CommandCompleted extends RuntimeException implements ComponentMessageThrowable {
public final class CommandCompleted extends ComponentException {
private static final long serialVersionUID = -2370043338216128339L;
private final @Nullable Component message;
private static final long serialVersionUID = 1352215898395889299L;
private CommandCompleted(final @Nullable Component message) {
this.message = message;
super(message);
}
public static CommandCompleted withoutMessage() {
@@ -46,14 +42,4 @@ public final class CommandCompleted extends RuntimeException implements Componen
return new CommandCompleted(message.asComponent());
}
@Override
public @Nullable Component componentMessage() {
return this.message;
}
@Override
public String getMessage() {
return PlainTextComponentSerializer.plainText().serializeOr(this.message, "No message.");
}
}
@@ -0,0 +1,59 @@
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.command.exception;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.kyori.adventure.util.ComponentMessageThrowable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class ComponentException extends RuntimeException implements ComponentMessageThrowable {
private static final long serialVersionUID = 132203031250316968L;
private final @Nullable Component message;
protected ComponentException(final @Nullable Component message) {
this.message = message;
}
public static ComponentException withoutMessage() {
return new ComponentException(null);
}
public static ComponentException withMessage(final ComponentLike message) {
return new ComponentException(message.asComponent());
}
@Override
public @Nullable Component componentMessage() {
return this.message;
}
@Override
public String getMessage() {
return PlainTextComponentSerializer.plainText().serializeOr(this.message, "No message.");
}
}
@@ -250,7 +250,7 @@ public interface CarbonMessages {
void errorCommandArgumentParsing(final Audience audience, @Placeholder("throwable_message") final Component throwableMessage);
@Message("error.command.invalid_player")
Component errorCommandInvalidPlayer(final Audience audience, final String input);
Component errorCommandInvalidPlayer(String input);
@Message("error.command.invalid_sender")
void errorCommandInvalidSender(final Audience audience, final String sender_type);