Added basic command structure with console feedback

This commit is contained in:
J-onasJones 2022-06-12 17:26:51 +02:00
parent c215bc41dd
commit 7784f65c74
20 changed files with 478 additions and 37 deletions

View file

@ -1,2 +1,26 @@
# ConsoleMC
A mod that allows console commands to be executed over the ingame Minecraft chat.
## //TODO
- Readme
- proper terminal input chat
- config file
- running -> allow /cmd
- allow-commandblock -> allow the use of /cmd in command blocks
- require-op -> require op to run /cmd
- blacklist -> players that are not allowed to run /cmd even though match all criteria
- whitelist -> players that are allowed to run /cmd even though don't match the criteria
- command
- /cmd [command] -> run command
- /cmd reload -> reload config
- /cmd disable -> toggle cmd off
- /cmd enable -> toggle cmd on
- /cmd help -> print help
- /cmd whitelist
- /cmd whitelist add [player]
- /cmd whitelist remove [player]
- /cmd blacklist
- /cmd blacklist add [player]
- /cmd blacklist remove [player]
- /cmd allow-commandBlock [True/False]
- /cmd require-op [True/False]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 453 B

After

Width:  |  Height:  |  Size: 31 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 453 B

View file

@ -16,7 +16,7 @@
"license": "CC0-1.0",
"icon": "assets/consolemc/icon.png",
"environment": "*",
"environment": "server",
"entrypoints": {
"main": [
"me.jonasjones.consolemc.ConsoleMC"

View file

@ -1,14 +0,0 @@
{
"required": true,
"minVersion": "0.8",
"package": "net.fabricmc.example.mixin",
"compatibilityLevel": "JAVA_17",
"mixins": [
],
"client": [
"ExampleMixin"
],
"injectors": {
"defaultRequire": 1
}
}

View file

@ -1,6 +1,7 @@
package me.jonasjones.consolemc;
import me.jonasjones.consolemc.command.RunCommand;
import me.jonasjones.consolemc.config.ModConfigs;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import org.slf4j.Logger;
@ -11,13 +12,15 @@ public class ConsoleMC implements ModInitializer {
// It is considered best practice to use your mod id as the logger's name.
// That way, it's clear which mod wrote info, warnings, and errors.
public static final Logger LOGGER = LoggerFactory.getLogger("consolemc");
public static String MOD_ID = "consolemc";
private static void registerCommands() {
public static void registerCommands() {
CommandRegistrationCallback.EVENT.register(RunCommand::register);
}
@Override
public void onInitialize() {
ModConfigs.registerConfigs();
registerCommands();
}
}

View file

@ -1,63 +1,171 @@
package me.jonasjones.consolemc.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.IntegerArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import me.jonasjones.consolemc.ConsoleMC;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.command.argument.MessageArgumentType;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import org.apache.logging.log4j.core.jmx.Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static me.jonasjones.consolemc.ConsoleMC.registerCommands;
public class RunCommand {
public static void register(CommandDispatcher<ServerCommandSource> serverCommandSourceCommandDispatcher, CommandRegistryAccess commandRegistryAccess, CommandManager.RegistrationEnvironment registrationEnvironment) {
serverCommandSourceCommandDispatcher.register(CommandManager.literal("cmd")
.requires(source -> source.hasPermissionLevel(4)) //requires OP
.then(CommandManager.argument("Console Command", MessageArgumentType.message())
.executes((ctx -> {
serverCommandSourceCommandDispatcher.register((((((((((((CommandManager.literal("cmd").requires(source -> source.hasPermissionLevel(4)) //requires OP //TODO: implement config "require-op:[True/False]"
.then(CommandManager.literal("run")
.then(CommandManager.argument("Console Command", MessageArgumentType.message())
.executes((context -> run(MessageArgumentType.getMessage(context, "Console Command").getString(), context)))))
//Debug Command
).then(CommandManager.literal("debug")
.then(CommandManager.literal("reloadCommand")
.executes(context -> reloadCommands(context))))
Text broadcastText = Text.of("Ran Console Command \"" + MessageArgumentType.getMessage(ctx, "Console Command").getString() + "\"");
ctx.getSource().sendFeedback(broadcastText, true);
//reload Command
).then(CommandManager.literal("reload")
.executes(context -> reload(context)))
if (MessageArgumentType.getMessage(ctx, "Console Command").getString() != "") {
//allow-commandBlocks Command
).then(CommandManager.literal("allow-commandBlocks")
.then(CommandManager.literal("True")
.executes(context -> toggleAllow(context))))
).then(CommandManager.literal("allow-commandBlocks")
.then(CommandManager.literal("False")
.executes(context -> toggleAllow(context))))
run(MessageArgumentType.getMessage(ctx, "Console Command").getString(), ctx);
return 1;
} else {
return -1;
}
}))));
//op-permissionLevel Command
).then(CommandManager.literal("op-permissionLevel")
.then(CommandManager.argument("level", IntegerArgumentType.integer(1, 4))
.executes(context -> setLevel(IntegerArgumentType.integer(IntegerArgumentType.getInteger(context, "level")), context))))
//enable command
).then(CommandManager.literal("enable")
.executes(context -> toggle(context)))
//disable command
).then(CommandManager.literal("disable")
.executes(context -> toggle(context)))
//help command
).then(CommandManager.literal("help")
.executes(context -> help()))
//whitelist [add <player>/remove <player>]
).then(CommandManager.literal("whitelist")
.then(CommandManager.literal("add")
.then(CommandManager.argument("target", EntityArgumentType.players())
.executes(context -> whitelistAdd(EntityArgumentType.getPlayer(context, "Player"), context)))))
).then(CommandManager.literal("whitelist")
.then(CommandManager.literal("remove")
.then((CommandManager.argument("target", EntityArgumentType.players())
.executes(context -> whitelistRemove(EntityArgumentType.getPlayer(context, "Player"), context)))))
//blacklist [add/remove]
).then(CommandManager.literal("blacklist")
.then(CommandManager.literal("add")
.then(CommandManager.argument("target", EntityArgumentType.players())
.executes(context -> blacklistAdd(EntityArgumentType.getPlayer(context, "Player"), context)))))
).then(CommandManager.literal("blacklist")
.then(CommandManager.literal("remove")
.then(CommandManager.argument("targets", EntityArgumentType.players())
.executes(context -> blacklistRemove(EntityArgumentType.getPlayer(context, "Player"), context)))))
);
}
public static void run(String command, CommandContext<ServerCommandSource> ctx) throws CommandSyntaxException {
runCommand(command, ctx);
public static void broadcastToOP(String message, CommandContext<ServerCommandSource> context) {
context.getSource().sendFeedback(Text.of(message), true);
}
public static void runCommand(String cmd, CommandContext<ServerCommandSource> ctx) {
public static int run(String command, CommandContext<ServerCommandSource> context) {
broadcastToOP("Ran Console Command \"" + command + "\"", context);
if (command != "") {
return runCommand(command, context);
} else {
return -1;
}
}
public static int runCommand(String cmd, CommandContext<ServerCommandSource> context) {
Process process = null;
try {
process = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {returnCommandOutput(cmd, s, ctx);
while ((s = stdInput.readLine()) != null) {
returnCommandOutput(cmd, s, context);
}
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((s = stdError.readLine()) != null) {returnCommandOutput(cmd, s, ctx);
while ((s = stdError.readLine()) != null) {
returnCommandOutput(cmd, s, context);
}
return 1;
} catch (IOException e) {
//e.printStackTrace();
String errorLog = "Error: \"" + cmd + "\", No such file or directory!";
ConsoleMC.LOGGER.info(errorLog);
ctx.getSource().sendFeedback(Text.of(errorLog), false);
context.getSource().sendFeedback(Text.of(errorLog), false);
return -1;
}
}
public static void returnCommandOutput(String cmd, String commandFeedback, CommandContext<ServerCommandSource> ctx) {
public static void returnCommandOutput(String cmd, String commandFeedback, CommandContext<ServerCommandSource> context) {
String consoleLog = " [" + cmd + "]: " + commandFeedback;
ctx.getSource().sendFeedback(Text.of(consoleLog), false);
context.getSource().sendFeedback(Text.of(consoleLog), false);
ConsoleMC.LOGGER.info(consoleLog);
}
public static int toggleAllow(CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Toggle Allow-CommandBlocks");
return 1;
}
public static int blacklistAdd(ServerPlayerEntity player, CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Add " + player.toString() + " to the blacklist");
return 1;
}
public static int blacklistRemove(ServerPlayerEntity player, CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Remove " + player.toString() + " from the blacklist");
return 1;
}
public static int reloadCommands(CommandContext<ServerCommandSource> context) {
registerCommands();
ConsoleMC.LOGGER.info("Reloaded Commands!");
return 1;
}
public static int setLevel(IntegerArgumentType level, CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Set Command OP Permission Level to: " + level.toString());
return 1;
}
public static int help() {
ConsoleMC.LOGGER.info("Print help");
return 1;
}
public static int reload(CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Reloading!");
return 1;
}
public static int toggle(CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Toggle Enable");
return 1;
}
public static int whitelistAdd(ServerPlayerEntity player, CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Add " + player.toString() + " to whitelist");
return 1;
}
public static int whitelistRemove(ServerPlayerEntity player, CommandContext<ServerCommandSource> context) {
ConsoleMC.LOGGER.info("Remove " + player.toString() + " from whitelist");
return 1;
}
}

View file

@ -0,0 +1,28 @@
package me.jonasjones.consolemc.config;
import com.mojang.datafixers.util.Pair;
import java.util.ArrayList;
import java.util.List;
public class ModConfigProvider implements SimpleConfig.DefaultConfig {
private String configContents = "";
public List<Pair> getConfigsList() {
return configsList;
}
private final List<Pair> configsList = new ArrayList<>();
public void addKeyValuePair(Pair<String, ?> keyValuePair, String comment) {
configsList.add(keyValuePair);
configContents += keyValuePair.getFirst() + "=" + keyValuePair.getSecond() + " #"
+ comment + " | default: " + keyValuePair.getSecond() + "\n";
}
@Override
public String get(String namespace) {
return configContents;
}
}

View file

@ -0,0 +1,39 @@
package me.jonasjones.consolemc.config;
import com.mojang.datafixers.util.Pair;
import me.jonasjones.consolemc.ConsoleMC;
public class ModConfigs {
public static SimpleConfig CONFIG;
private static ModConfigProvider configs;
public static String TEST;
public static int SOME_INT;
public static double SOME_DOUBLE;
public static int MAX_DAMAGE_DOWSING_ROD;
public static void registerConfigs() {
configs = new ModConfigProvider();
createConfigs();
CONFIG = SimpleConfig.of(ConsoleMC.MOD_ID + "config").provider(configs).request();
assignConfigs();
}
private static void createConfigs() {
configs.addKeyValuePair(new Pair<>("key.test.value1", "Just a Testing string!"), "String");
configs.addKeyValuePair(new Pair<>("key.test.value2", 50), "int");
configs.addKeyValuePair(new Pair<>("key.test.value3", 4142.5), "double");
configs.addKeyValuePair(new Pair<>("dowsing.rod.max.damage", 32), "int");
}
private static void assignConfigs() {
TEST = CONFIG.getOrDefault("key.test.value1", "Nothing");
SOME_INT = CONFIG.getOrDefault("key.test.value2", 42);
SOME_DOUBLE = CONFIG.getOrDefault("key.test.value3", 42.0d);
MAX_DAMAGE_DOWSING_ROD = CONFIG.getOrDefault("dowsing.rod.max.damage", 32);
System.out.println("All " + configs.getConfigsList().size() + " have been set properly");
}
}

View file

@ -0,0 +1,253 @@
package me.jonasjones.consolemc.config;
/*
* Copyright (c) 2021 magistermaks
* Slightly modified by Jonas_Jones 2022
*
* 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.
*/
import net.fabricmc.loader.api.FabricLoader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Scanner;
public class SimpleConfig {
private static final Logger LOGGER = LogManager.getLogger("SimpleConfig");
private final HashMap<String, String> config = new HashMap<>();
private final ConfigRequest request;
private boolean broken = false;
public interface DefaultConfig {
String get( String namespace );
static String empty( String namespace ) {
return "";
}
}
public static class ConfigRequest {
private final File file;
private final String filename;
private DefaultConfig provider;
private ConfigRequest(File file, String filename ) {
this.file = file;
this.filename = filename;
this.provider = DefaultConfig::empty;
}
/**
* Sets the default config provider, used to generate the
* config if it's missing.
*
* @param provider default config provider
* @return current config request object
* @see DefaultConfig
*/
public ConfigRequest provider( DefaultConfig provider ) {
this.provider = provider;
return this;
}
/**
* Loads the config from the filesystem.
*
* @return config object
* @see SimpleConfig
*/
public SimpleConfig request() {
return new SimpleConfig( this );
}
private String getConfig() {
return provider.get( filename ) + "\n";
}
}
/**
* Creates new config request object, ideally `namespace`
* should be the name of the mod id of the requesting mod
*
* @param filename - name of the config file
* @return new config request object
*/
public static ConfigRequest of( String filename ) {
Path path = FabricLoader.getInstance().getConfigDir();
return new ConfigRequest( path.resolve( filename + ".properties" ).toFile(), filename );
}
private void createConfig() throws IOException {
// try creating missing files
request.file.getParentFile().mkdirs();
Files.createFile( request.file.toPath() );
// write default config data
PrintWriter writer = new PrintWriter(request.file, "UTF-8");
writer.write( request.getConfig() );
writer.close();
}
private void loadConfig() throws IOException {
Scanner reader = new Scanner( request.file );
for( int line = 1; reader.hasNextLine(); line ++ ) {
parseConfigEntry( reader.nextLine(), line );
}
}
private void parseConfigEntry( String entry, int line ) {
if( !entry.isEmpty() && !entry.startsWith( "#" ) ) {
String[] parts = entry.split("=", 2);
if( parts.length == 2 ) {
//Recognise comments after a value
String temp = parts[1].split(" #")[0];
config.put( parts[0], temp);
}else{
throw new RuntimeException("Syntax error in config file on line " + line + "!");
}
}
}
private SimpleConfig( ConfigRequest request ) {
this.request = request;
String identifier = "Config '" + request.filename + "'";
if( !request.file.exists() ) {
LOGGER.info( identifier + " is missing, generating default one..." );
try {
createConfig();
} catch (IOException e) {
LOGGER.error( identifier + " failed to generate!" );
LOGGER.trace( e );
broken = true;
}
}
if( !broken ) {
try {
loadConfig();
} catch (Exception e) {
LOGGER.error( identifier + " failed to load!" );
LOGGER.trace( e );
broken = true;
}
}
}
/**
* Queries a value from config, returns `null` if the
* key does not exist.
*
* @return value corresponding to the given key
* @see SimpleConfig#getOrDefault
*/
@Deprecated
public String get( String key ) {
return config.get( key );
}
/**
* Returns string value from config corresponding to the given
* key, or the default string if the key is missing.
*
* @return value corresponding to the given key, or the default value
*/
public String getOrDefault( String key, String def ) {
String val = get(key);
return val == null ? def : val;
}
/**
* Returns integer value from config corresponding to the given
* key, or the default integer if the key is missing or invalid.
*
* @return value corresponding to the given key, or the default value
*/
public int getOrDefault( String key, int def ) {
try {
return Integer.parseInt( get(key) );
} catch (Exception e) {
return def;
}
}
/**
* Returns boolean value from config corresponding to the given
* key, or the default boolean if the key is missing.
*
* @return value corresponding to the given key, or the default value
*/
public boolean getOrDefault( String key, boolean def ) {
String val = get(key);
if( val != null ) {
return val.equalsIgnoreCase("true");
}
return def;
}
/**
* Returns double value from config corresponding to the given
* key, or the default string if the key is missing or invalid.
*
* @return value corresponding to the given key, or the default value
*/
public double getOrDefault( String key, double def ) {
try {
return Double.parseDouble( get(key) );
} catch (Exception e) {
return def;
}
}
/**
* If any error occurred during loading or reading from the config
* a 'broken' flag is set, indicating that the config's state
* is undefined and should be discarded using `delete()`
*
* @return the 'broken' flag of the configuration
*/
public boolean isBroken() {
return broken;
}
/**
* deletes the config file from the filesystem
*
* @return true if the operation was successful
*/
public boolean delete() {
LOGGER.warn( "Config '" + request.filename + "' was removed from existence! Restart the game to regenerate it." );
return request.file.delete();
}
}