Compare commits

...
10 Commits
Author SHA1 Message Date
jmp 09683f06ce Implement 'hide-player-count' option
Setting this to true will disable the player list hover (same as 'disable-player-list-hover'), but will also cause the player count to appear as '???'.
2021-03-16 15:31:22 -07:00
jmp c92c718ced Add ComponentColorDownsampler 2021-03-13 18:06:24 -08:00
jmp e468600d83 Parse MOTD MiniMessage in a single place
as opposed to in each platform
2021-03-12 15:35:40 -08:00
Renovate Bot 101915290e chore(deps): update dependency org.spongepowered.gradle.plugin:org.spongepowered.gradle.plugin.gradle.plugin to v1.0.2 2021-03-11 15:40:42 -08:00
Jason b0c8c7a11d Update issue templates 2021-03-11 14:57:42 -08:00
Jason 5bac39d149 Create config.yml 2021-03-11 14:56:15 -08:00
Jason 37dd141af4 Update bug-report.md 2021-03-11 14:47:59 -08:00
jmp d348ee6b1d Update loom and Adventure 2021-03-03 01:28:25 -08:00
jmp b1336df817 Work around issue with shadowJar and the sponge runServer task 2021-02-28 13:01:32 -08:00
jmp 8e9c8aac5f Refactor commands, implement commands on sponge-8 2021-02-28 03:38:27 -08:00
37 changed files with 795 additions and 577 deletions

No files matched your search

+2 -2
View File
@@ -2,7 +2,7 @@
name: Bug Report
about: Report a bug
title: "[Bug Report] This happens when another thing should have"
labels: bug
labels: bug, unconfirmed
assignees: ''
---
@@ -24,7 +24,7 @@ A clear and concise description of what you expected to happen.
If applicable, add screenshots to help explain your problem.
**Server Software and Version:**
- Vendor: [e.g. Paper, Spigot, Tuinity, Velocity, BungeeCord, Waterfall]
- Vendor: [e.g. Paper, Tuinity, Velocity, BungeeCord, Waterfall, Fabric, Sponge]
- Minecraft Version: [e.g. 1.15.2, 1.16.3]
- Output of /version command: [e.g. This server is running Paper version git-Paper-53 (MC: 1.16.1) (Implementing API version 1.16.1-R0.1-SNAPSHOT)]
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+33 -48
View File
@@ -1,3 +1,5 @@
import com.adarshr.gradle.testlogger.TestLoggerPlugin
import com.adarshr.gradle.testlogger.theme.ThemeType
import com.github.jengelman.gradle.plugins.shadow.ShadowPlugin
import net.kyori.indra.IndraCheckstylePlugin
import net.kyori.indra.IndraLicenseHeaderPlugin
@@ -9,11 +11,13 @@ plugins {
`java-library`
id("net.kyori.indra") version "1.3.1"
id("com.github.johnrengelman.shadow") version "6.1.0"
id("com.adarshr.test-logger") version "2.1.1"
id("net.kyori.blossom") version "1.1.0" apply false
}
allprojects {
group = "xyz.jpenilla"
version = "2.0.1+${latestCommitHash()}-SNAPSHOT"
version = "2.0.1+${lastCommitHash()}-SNAPSHOT"
description = "Use MiniMessage text formatting in your servers MOTD."
}
@@ -25,6 +29,7 @@ subprojects {
apply<IndraPlugin>()
apply<IndraCheckstylePlugin>()
apply<IndraLicenseHeaderPlugin>()
apply<TestLoggerPlugin>()
repositories {
//mavenLocal()
@@ -41,76 +46,56 @@ subprojects {
maven("https://repo.codemc.org/repository/maven-public")
}
dependencies {
testImplementation("org.junit.jupiter", "junit-jupiter-engine", "5.7.0")
}
indra {
javaVersions.target.set(8)
javaVersions {
testWith(8, 11, 15)
target.set(8)
}
github("jpenilla", "MiniMOTD") {
issues = true
}
mitLicense()
}
testlogger {
theme = ThemeType.MOCHA_PARALLEL
showPassed = false
}
tasks {
shadowJar {
minimize()
if (!project.name.contains("fabric")) {
archiveClassifier.set("")
doLast {
val output = outputs.files.singleFile
output.copyTo(rootProject.buildDir.resolve("libs").resolve(output.name), overwrite = true)
}
}
}
withType<JavaCompile> {
options.compilerArgs.add("-Xlint:-processing")
}
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
allprojects {
tasks.withType<Jar> {
onlyIf {
val classifier = archiveClassifier.get()
classifier != "javadoc"
&& project.name != rootProject.name
withType<Jar> {
onlyIf { archiveClassifier.get() != "javadoc" }
}
withType<Javadoc> {
onlyIf { false }
}
}
tasks.withType<Javadoc> {
onlyIf { false }
}
}
configurations.archives {
artifacts.removeAll { true }
tasks.withType<Jar> {
onlyIf { false }
}
tasks {
val aggregate = create("aggregateJars") {
val artifacts = arrayListOf<File>()
dependsOn(project(":minimotd-universal").tasks.getByName("build"))
arrayOf("spigot", "bungeecord", "velocity", "sponge8").forEach {
val subProject = project(":minimotd-$it")
val shadow = subProject.tasks.getByName("shadowJar")
artifacts.add(shadow.outputs.files.singleFile)
}
doLast {
artifacts.add(project(":minimotd-fabric").tasks.getByName("remapJar").outputs.files.singleFile)
artifacts.add(project(":minimotd-universal").project.tasks.getByName("universal").outputs.files.singleFile)
val libs = rootProject.buildDir.resolve("libs")
libs.listFiles()?.forEach { it.delete() }
artifacts.forEach { it.copyTo(libs.resolve(it.name)) }
}
}
build {
dependsOn(aggregate)
}
}
fun latestCommitHash(): String {
val byteOut = ByteArrayOutputStream()
fun lastCommitHash(): String = ByteArrayOutputStream().apply {
exec {
commandLine = listOf("git", "rev-parse", "--short", "HEAD")
standardOutput = byteOut
standardOutput = this@apply
}
return byteOut.toString(Charsets.UTF_8.name()).trim()
}
}.toString(Charsets.UTF_8.name()).trim()
@@ -23,93 +23,58 @@
*/
package xyz.jpenilla.minimotd.bungee;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
import xyz.jpenilla.minimotd.common.CommandHandlerFactory;
public class BungeeCommand extends Command {
private final MiniMOTDPlugin plugin;
private final MiniMessage miniMessage;
private final CommandHandlerFactory handlerFactory;
public BungeeCommand(final @NonNull MiniMOTDPlugin plugin) {
super("minimotd");
this.plugin = plugin;
this.miniMessage = MiniMessage.get();
this.handlerFactory = new CommandHandlerFactory(plugin.miniMOTD());
}
@Override
public void execute(final @NonNull CommandSender sender, final @NonNull String @NonNull [] args) {
final Audience audience = this.plugin.audiences().sender(sender);
if (!sender.hasPermission("minimotd.admin")) {
this.onNoPermission(sender, args);
audience.sendMessage(Component.text("No permission.", NamedTextColor.RED));
return;
}
if (args.length == 0) {
this.onInvalidUse(sender, args);
this.onInvalidUse(audience);
return;
}
switch (args[0]) {
case "about":
this.onAbout(sender, args);
this.handlerFactory.about().execute(audience);
return;
case "help":
this.onHelp(sender, args);
this.handlerFactory.help().execute(audience);
return;
case "reload":
this.onReload(sender, args);
this.handlerFactory.reload().execute(audience);
return;
}
this.onInvalidUse(sender, args);
this.onInvalidUse(audience);
}
private void onHelp(final @NonNull CommandSender sender, final @NonNull String[] args) {
final List<String> messages = new ArrayList<>();
messages.add("<gradient:blue:green>MiniMOTD Commands:");
messages.add(" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd about'><click:run_command:/minimotd about><yellow>/minimotd about");
messages.add(" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd reload'><click:run_command:/minimotd reload><yellow>/minimotd reload");
messages.add(" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd help'><click:run_command:/minimotd help><yellow>/minimotd help");
this.send(sender, messages);
}
private void onReload(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.plugin.miniMOTD().configManager().loadConfigs();
this.plugin.miniMOTD().configManager().loadExtraConfigs();
this.plugin.miniMOTD().iconManager().loadIcons();
this.send(sender, "<green>Done reloading.");
}
private void onAbout(final @NonNull CommandSender sender, final @NonNull String[] args) {
final ArrayList<String> messages = new ArrayList<>();
final String header = "<gradient:white:black>=============</gradient><gradient:black:white>=============";
messages.add(header);
messages.add("<hover:show_text:'<rainbow>click me!'><click:open_url:https://github.com/jmanpenilla/MiniMOTD/>" + this.plugin.getDescription().getName() + " <gradient:red:yellow>" + this.plugin.getDescription().getVersion());
messages.add("<yellow>By</yellow><gray>:</gray> <gradient:blue:green>jmp");
messages.add(header);
this.send(sender, messages);
}
private void onInvalidUse(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.send(sender, "<hover:show_text:'<green>Click for <yellow>/minimotd help'><click:run_command:/minimotd help><italic><gradient:red:gold>Invalid usage.</gradient> <blue>Try <yellow>/minimotd help</yellow> or click here");
}
private void onNoPermission(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.send(sender, "<gradient:red:yellow>No permission.");
}
private void send(final @NonNull CommandSender sender, final @NonNull String message) {
this.plugin.audiences().sender(sender).sendMessage(Identity.nil(), this.miniMessage.parse(message));
}
private void send(final @NonNull CommandSender sender, final @NonNull List<String> messages) {
for (final String message : messages) {
this.send(sender, message);
}
private void onInvalidUse(final @NonNull Audience audience) {
audience.sendMessage(
Component.text("Invalid command usage. Use '/minimotd help' for a list of command provided by MiniMOTD.", NamedTextColor.RED)
.hoverEvent(Component.text("Click to execute '/minimotd help'"))
.clickEvent(ClickEvent.runCommand("/minimotd help"))
);
}
}
@@ -58,7 +58,7 @@ public class MiniMOTDPlugin extends Plugin implements MiniMOTDPlatform<Favicon>
if (this.miniMOTD.configManager().pluginSettings().updateChecker()) {
this.getProxy().getScheduler().runAsync(this, () ->
new UpdateChecker(this.getDescription().getVersion()).checkVersion().forEach(getLogger()::info));
new UpdateChecker().checkVersion().forEach(getLogger()::info));
}
}
@@ -80,4 +80,9 @@ public class MiniMOTDPlugin extends Plugin implements MiniMOTDPlatform<Favicon>
public @NonNull BungeeAudiences audiences() {
return this.audiences;
}
@Override
public void onReload() {
this.miniMOTD.configManager().loadExtraConfigs();
}
}
@@ -24,9 +24,7 @@
package xyz.jpenilla.minimotd.bungee;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.md_5.bungee.api.Favicon;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.chat.TextComponent;
@@ -35,6 +33,7 @@ import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
import org.checkerframework.checker.nullness.qual.NonNull;
import xyz.jpenilla.minimotd.common.ComponentColorDownsampler;
import xyz.jpenilla.minimotd.common.Constants;
import xyz.jpenilla.minimotd.common.MOTDIconPair;
import xyz.jpenilla.minimotd.common.MiniMOTD;
@@ -43,7 +42,6 @@ import xyz.jpenilla.minimotd.common.config.MiniMOTDConfig;
import java.util.Optional;
public class PingListener implements Listener {
private final MiniMessage miniMessage = MiniMessage.get();
private final MiniMOTD<Favicon> miniMOTD;
public PingListener(final @NonNull MiniMOTD<Favicon> miniMOTD) {
@@ -53,43 +51,45 @@ public class PingListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onPing(final @NonNull ProxyPingEvent e) {
final ServerPing response = e.getResponse();
if (response == null) {
return;
}
if (response != null) {
final String configString = this.miniMOTD.configManager().pluginSettings().configStringForHost(
Optional.ofNullable(e.getConnection().getVirtualHost())
.map(inetSocketAddress -> String.format("%s:%s", inetSocketAddress.getHostName(), inetSocketAddress.getPort()))
.orElse("default")
).orElse("default");
final MiniMOTDConfig cfg = this.miniMOTD.configManager().resolveConfig(configString);
final ServerPing.Players players = response.getPlayers();
final int onlinePlayers = this.miniMOTD.calculateOnlinePlayers(cfg, players.getOnline());
final String configString = this.miniMOTD.configManager().pluginSettings().configStringForHost(
Optional.ofNullable(e.getConnection().getVirtualHost())
.map(inetSocketAddress -> String.format("%s:%s", inetSocketAddress.getHostName(), inetSocketAddress.getPort()))
.orElse("default")
).orElse("default");
final MiniMOTDConfig cfg = this.miniMOTD.configManager().resolveConfig(configString);
final ServerPing.Players players = response.getPlayers();
final int onlinePlayers = this.miniMOTD.calculateOnlinePlayers(cfg, players.getOnline());
final int maxPlayers = cfg.adjustedMaxPlayers(onlinePlayers, players.getMax());
if (cfg.hidePlayerCount()) {
response.setPlayers(null);
} else {
players.setOnline(onlinePlayers);
final int maxPlayers = cfg.adjustedMaxPlayers(onlinePlayers, players.getMax());
players.setMax(maxPlayers);
if (cfg.disablePlayerListHover()) {
players.setSample(new ServerPing.PlayerInfo[]{});
}
final MOTDIconPair<Favicon> pair = this.miniMOTD.createMOTD(cfg, onlinePlayers, maxPlayers);
final String motdString = pair.motd();
if (motdString != null) {
Component motdComponent = this.miniMessage.parse(motdString);
if (e.getConnection().getVersion() < Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
motdComponent = GsonComponentSerializer.colorDownsamplingGson().deserialize(GsonComponentSerializer.colorDownsamplingGson().serialize(motdComponent));
}
response.setDescriptionComponent(new TextComponent(BungeeComponentSerializer.get().serialize(motdComponent)));
}
final Favicon favicon = pair.icon();
if (favicon != null) {
response.setFavicon(favicon);
}
response.setPlayers(players);
e.setResponse(response);
}
final MOTDIconPair<Favicon> pair = this.miniMOTD.createMOTD(cfg, onlinePlayers, maxPlayers);
Component motdComponent = pair.motd();
if (motdComponent != null) {
if (e.getConnection().getVersion() < Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
motdComponent = ComponentColorDownsampler.downsampler().downsample(motdComponent);
}
response.setDescriptionComponent(new TextComponent(BungeeComponentSerializer.get().serialize(motdComponent)));
}
final Favicon favicon = pair.icon();
if (favicon != null) {
response.setFavicon(favicon);
}
e.setResponse(response);
}
}
+18 -1
View File
@@ -1,8 +1,25 @@
plugins {
id("net.kyori.blossom")
}
dependencies {
api("org.slf4j", "slf4j-api", "1.7.30")
api("org.spongepowered", "configurate-hocon", "4.1.0-SNAPSHOT")
api("net.kyori", "adventure-api", "4.3.0")
platform(api("net.kyori", "adventure-bom", "4.7.0"))
api("net.kyori", "adventure-text-serializer-gson")
api("net.kyori", "adventure-text-minimessage", "4.1.0-SNAPSHOT")
compileOnlyApi("com.google.code.gson", "gson", "2.8.0")
compileOnlyApi("com.google.guava", "guava", "21.0")
}
blossom {
fun replaceTokens(file: String, vararg tokens: Pair<String, String>) = tokens.forEach { (k, v) ->
replaceToken("\${$k}", v, file)
}
replaceTokens(
"src/main/java/xyz/jpenilla/minimotd/common/Constants.java",
"PLUGIN_NAME" to rootProject.name,
"PLUGIN_VERSION" to project.version.toString(),
"PLUGIN_WEBSITE" to rootProject.ext["url"].toString()
)
}
@@ -0,0 +1,124 @@
/*
* This file is part of MiniMOTD, licensed under the MIT License.
*
* Copyright (c) 2021 Jason Penilla
*
* 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.
*/
package xyz.jpenilla.minimotd.common;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.stream.Stream;
import static net.kyori.adventure.text.Component.space;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.LinearComponents.linear;
import static net.kyori.adventure.text.event.ClickEvent.openUrl;
import static net.kyori.adventure.text.event.ClickEvent.runCommand;
import static net.kyori.adventure.text.format.NamedTextColor.GRAY;
import static net.kyori.adventure.text.format.NamedTextColor.WHITE;
import static net.kyori.adventure.text.format.TextColor.color;
import static net.kyori.adventure.text.format.TextDecoration.STRIKETHROUGH;
public final class CommandHandlerFactory {
private final MiniMOTD<?> miniMOTD;
public CommandHandlerFactory(final @NonNull MiniMOTD<?> miniMOTD) {
this.miniMOTD = miniMOTD;
}
public @NonNull CommandHandler about() {
return audience -> {
final Component header = miniMessage("<gradient:white:#007FFF:white> ").decorate(STRIKETHROUGH);
Stream.of(
header,
text()
.hoverEvent(miniMessage("<rainbow>click me!"))
.clickEvent(openUrl(Constants.PluginMetadata.WEBSITE))
.content(Constants.PluginMetadata.NAME)
.color(WHITE)
.append(space())
.append(miniMessage("<gradient:#0047AB:#007FFF>" + Constants.PluginMetadata.VERSION))
.build(),
text()
.content("By ")
.color(GRAY)
.append(text("jmp", WHITE))
.build(),
header
).forEach(audience::sendMessage);
};
}
public @NonNull CommandHandler reload() {
return audience -> {
this.miniMOTD.reload();
audience.sendMessage(linear(Constants.COMMAND_PREFIX, space(), text("Done reloading configuration.", NamedTextColor.GREEN)));
};
}
public @NonNull CommandHandler help() {
return audience -> Stream.of(
linear(Constants.COMMAND_PREFIX, space(), text(Constants.PluginMetadata.NAME + " command help", WHITE)),
commandInfo("/minimotd about", "Show information about MiniMOTD"),
commandInfo("/minimotd reload", "Reload MiniMOTD configuration files"),
commandInfo("/minimotd help", "Show this help menu")
).forEach(audience::sendMessage);
}
private static @NonNull Component commandInfo(final @NonNull String command, final @NonNull String description) {
return text()
.content(" - ")
.color(GRAY)
.append(
text(command, color(0x007FFF))
.replaceText(config -> {
config.matchLiteral("/");
config.replacement(builder -> builder.color(WHITE));
})
)
.append(text(':', GRAY))
.append(space())
.append(text(description, WHITE))
.hoverEvent(
text()
.content("Click to execute '")
.color(GRAY)
.append(text(command, WHITE))
.append(text("'"))
.build()
)
.clickEvent(runCommand(command))
.build();
}
private static @NonNull Component miniMessage(final @NonNull String message) {
return MiniMessage.get().parse(message);
}
@FunctionalInterface
public interface CommandHandler {
void execute(@NonNull Audience audience);
}
}
@@ -0,0 +1,50 @@
/*
* This file is part of MiniMOTD, licensed under the MIT License.
*
* Copyright (c) 2021 Jason Penilla
*
* 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.
*/
package xyz.jpenilla.minimotd.common;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.NonNull;
public interface ComponentColorDownsampler {
static @NonNull ComponentColorDownsampler downsampler() {
return ComponentColorDownsamplerImpl.INSTANCE;
}
@NonNull Component downsample(@NonNull Component component);
final class ComponentColorDownsamplerImpl implements ComponentColorDownsampler {
private static final ComponentColorDownsampler INSTANCE = new ComponentColorDownsamplerImpl();
private ComponentColorDownsamplerImpl() {
}
@Override
public @NonNull Component downsample(final @NonNull Component component) {
return GsonComponentSerializer.gson().deserializeFromTree(
GsonComponentSerializer.colorDownsamplingGson().serializeToTree(component)
);
}
}
}
@@ -23,9 +23,23 @@
*/
package xyz.jpenilla.minimotd.common;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
public final class Constants {
private Constants() {
}
public static final class PluginMetadata {
private PluginMetadata() {
}
public static final String NAME = "${PLUGIN_NAME}";
public static final String VERSION = "${PLUGIN_VERSION}";
public static final String WEBSITE = "${PLUGIN_WEBSITE}";
}
public static final int MINECRAFT_1_16_PROTOCOL_VERSION = 735;
public static final Component COMMAND_PREFIX = MiniMessage.get().parse("<white>[</white><gradient:#0047AB:#ADD8E6>" + PluginMetadata.NAME + "<white>]</white>");
}
@@ -23,14 +23,15 @@
*/
package xyz.jpenilla.minimotd.common;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.Nullable;
public final class MOTDIconPair<I> {
private final I icon;
private final String motd;
private final Component motd;
public MOTDIconPair(final @Nullable I icon, final @Nullable String motd) {
public MOTDIconPair(final @Nullable I icon, final @Nullable Component motd) {
this.icon = icon;
this.motd = motd;
}
@@ -39,7 +40,7 @@ public final class MOTDIconPair<I> {
return this.icon;
}
public @Nullable String motd() {
public @Nullable Component motd() {
return this.motd;
}
@@ -23,6 +23,9 @@
*/
package xyz.jpenilla.minimotd.common;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import xyz.jpenilla.minimotd.common.config.ConfigManager;
@@ -63,19 +66,23 @@ public final class MiniMOTD<I> {
return this.configManager;
}
// todo: move deserialization from MM -> Component, color down-sampling here, take protocolVersion int as param
// todo: move color down-sampling here, take protocolVersion int as param
public final @NonNull MOTDIconPair<I> createMOTD(final @NonNull MiniMOTDConfig config, final int onlinePlayers, final int maxPlayers) {
I icon = null;
String motd = null;
Component motd = null;
String iconString = null;
if (config.motdEnabled()) {
if (config.motds().size() == 0) {
throw new IllegalStateException("MOTD is enabled, but there are no MOTDs in the config file?");
}
final int index = config.motds().size() == 1 ? 0 : ThreadLocalRandom.current().nextInt(config.motds().size());
final MiniMOTDConfig.MOTD m = config.motds().get(index);
motd = String.format("%s<reset>\n%s", m.line1(), m.line2())
.replace("{onlinePlayers}", String.valueOf(onlinePlayers))
.replace("{maxPlayers}", String.valueOf(maxPlayers))
.replace("{br}", "\n");
iconString = m.icon();
final MiniMOTDConfig.MOTD motdConfig = config.motds().get(index);
motd = TextComponent.ofChildren(
MiniMessage.get().parse(replacePlayerCount(motdConfig.line1(), onlinePlayers, maxPlayers)),
Component.newline(),
MiniMessage.get().parse(replacePlayerCount(motdConfig.line2(), onlinePlayers, maxPlayers))
);
iconString = motdConfig.icon();
}
if (config.iconEnabled()) {
icon = this.iconManager().icon(iconString);
@@ -83,6 +90,11 @@ public final class MiniMOTD<I> {
return new MOTDIconPair<>(icon, motd);
}
private static @NonNull String replacePlayerCount(final @NonNull String input, final int onlinePlayers, final int maxPlayers) {
return input.replace("{onlinePlayers}", String.valueOf(onlinePlayers))
.replace("{maxPlayers}", String.valueOf(maxPlayers));
}
public final int calculateOnlinePlayers(final @NonNull MiniMOTDConfig config, final int realOnlinePlayers) {
if (config.fakePlayersEnabled()) {
try {
@@ -108,4 +120,10 @@ public final class MiniMOTD<I> {
}
return realOnlinePlayers;
}
public void reload() {
this.iconManager.loadIcons();
this.configManager.loadConfigs();
this.platform.onReload();
}
}
@@ -35,4 +35,7 @@ public interface MiniMOTDPlatform<I> {
@NonNull Logger logger();
@NonNull I loadIcon(@NonNull BufferedImage image) throws Exception;
default void onReload() {
}
}
@@ -24,6 +24,7 @@
package xyz.jpenilla.minimotd.common;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -31,7 +32,7 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
@@ -39,39 +40,33 @@ import java.util.Map;
public final class UpdateChecker {
private final JsonParser parser = new JsonParser();
private final String currentVersion;
public UpdateChecker(final @NonNull String currentVersion) {
this.currentVersion = currentVersion;
}
public List<String> checkVersion() {
final List<String> messages = new ArrayList<>();
public @NonNull List<String> checkVersion() {
final JsonArray result;
try {
result = this.parser.parse(new InputStreamReader(new URL("https://api.github.com/repos/jpenilla/MiniMOTD/releases").openStream(), Charsets.UTF_8)).getAsJsonArray();
} catch (final IOException exception) {
messages.add("Cannot look for updates: " + exception.getMessage());
return messages;
return Collections.singletonList("Cannot look for updates: " + exception.getMessage());
}
final Map<String, String> versionMap = new LinkedHashMap<>();
result.forEach(element -> versionMap.put(element.getAsJsonObject().get("tag_name").getAsString(), element.getAsJsonObject().get("html_url").getAsString()));
final List<String> versionList = new LinkedList<>(versionMap.keySet());
final String currentVersion = "v" + this.currentVersion;
final String currentVersion = "v" + Constants.PluginMetadata.VERSION;
if (versionList.get(0).equals(currentVersion)) {
messages.add("You are running the latest version of MiniMOTD! :)");
return messages;
return Collections.emptyList(); // Up to date, do nothing
}
if (currentVersion.contains("SNAPSHOT")) {
messages.add("You are running a development build of MiniMOTD! (" + currentVersion + ")");
messages.add("The latest official release is " + versionList.get(0));
return messages;
return ImmutableList.of(
"This server is running a development build of MiniMOTD! (" + currentVersion + ")",
"The latest official release is " + versionList.get(0)
);
}
final int versionsBehind = versionList.indexOf(currentVersion);
messages.add("There is an update available for MiniMOTD!");
messages.add("You are running version " + currentVersion + ", which is " + (versionsBehind == -1 ? "many" : versionsBehind) + " versions outdated.");
messages.add("Download the latest version, " + versionList.get(0) + " from GitHub at the link below:");
messages.add(versionMap.get(versionList.get(0)));
return messages;
return ImmutableList.of(
"There is an update available for " + Constants.PluginMetadata.NAME + "!",
"This server is running version " + currentVersion + ", which is " + (versionsBehind == -1 ? "UNKNOWN" : versionsBehind) + " versions outdated.",
"Download the latest version, " + versionList.get(0) + " from GitHub at the link below:",
versionMap.get(versionList.get(0))
);
}
}
@@ -81,7 +81,7 @@ public final class ConfigManager {
try {
if (!Files.exists(extraConfigsDir)) {
Files.createDirectories(extraConfigsDir);
this.createDefaultProxyConfigs(extraConfigsDir);
this.createDefaultExtraConfigs(extraConfigsDir);
}
for (final Path path : Files.list(extraConfigsDir).collect(Collectors.toList())) {
if (path.toString().endsWith(".conf")) {
@@ -101,7 +101,7 @@ public final class ConfigManager {
}
}
private void createDefaultProxyConfigs(final @NonNull Path extraConfigsDir) throws ConfigurateException {
private void createDefaultExtraConfigs(final @NonNull Path extraConfigsDir) throws ConfigurateException {
final List<Pair<Path, MiniMOTDConfig.MOTD>> defaults = ImmutableList.of(
Pair.of(extraConfigsDir.resolve("skyblock.conf"), new MiniMOTDConfig.MOTD("<green><italic>Skyblock</green>", "<bold><rainbow>MiniMOTD Skyblock Server")),
Pair.of(extraConfigsDir.resolve("survival.conf"), new MiniMOTDConfig.MOTD("<gradient:blue:red>Survival Mode Hardcore", "<green><bold>MiniMOTD Survival Server"))
@@ -61,7 +61,9 @@ public final class MiniMOTDConfig {
public int adjustedMaxPlayers(final int onlinePlayers, final int actualMaxPlayers) {
if (this.playerCountSettings.maxPlayersEnabled) {
return this.playerCountSettings.justXMoreSettings.justXMoreEnabled ? onlinePlayers + this.playerCountSettings.justXMoreSettings.xValue : this.playerCountSettings.maxPlayers;
return this.playerCountSettings.justXMoreSettings.justXMoreEnabled
? onlinePlayers + this.playerCountSettings.justXMoreSettings.xValue
: this.playerCountSettings.maxPlayers;
} else {
return actualMaxPlayers;
}
@@ -114,6 +116,10 @@ public final class MiniMOTDConfig {
@Comment("Setting this to true will disable the hover text showing online player usernames")
private boolean disablePlayerListHover = false;
@Comment("Setting this to true will disable the player list hover (same as 'disable-player-list-hover'),\n"
+ "but will also cause the player count to appear as '???'")
private boolean hidePlayerCount = false;
@Comment("Settings for the fake player count feature")
private FakePlayers fakePlayers = new FakePlayers();
@@ -174,4 +180,8 @@ public final class MiniMOTDConfig {
public boolean disablePlayerListHover() {
return this.playerCountSettings.disablePlayerListHover;
}
public boolean hidePlayerCount() {
return this.playerCountSettings.hidePlayerCount;
}
}
@@ -0,0 +1,65 @@
/*
* This file is part of MiniMOTD, licensed under the MIT License.
*
* Copyright (c) 2021 Jason Penilla
*
* 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.
*/
package xyz.jpenilla.minimotd.common;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.format.TextColor;
import org.junit.jupiter.api.Test;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.format.NamedTextColor.nearestTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ComponentColorDownsamplerTest {
private static final TextColor GREEN = TextColor.color(0x04E762);
private static final TextColor ORANGE_YELLOW = TextColor.color(0xF5B700);
private static final TextColor PINK = TextColor.color(0xDC0073);
private static final TextColor BLUE = TextColor.color(0x008BF8);
private static final TextColor LIME_GREEN = TextColor.color(0x89FC00);
@Test
void testColorDownsampling() {
final Component fullColor = TextComponent.ofChildren(
text("Green ", GREEN),
text("Orange Yellow ", ORANGE_YELLOW),
text("Pink ", PINK),
text("Blue ", BLUE),
text("Lime Green", LIME_GREEN)
);
final Component expectedDownsample = TextComponent.ofChildren(
text("Green ", nearestTo(GREEN)),
text("Orange Yellow ", nearestTo(ORANGE_YELLOW)),
text("Pink ", nearestTo(PINK)),
text("Blue ", nearestTo(BLUE)),
text("Lime Green", nearestTo(LIME_GREEN))
);
final Component actualDownsample = ComponentColorDownsampler.downsampler().downsample(fullColor);
assertEquals(
expectedDownsample,
actualDownsample
);
}
}
+11 -16
View File
@@ -1,11 +1,8 @@
plugins {
id("fabric-loom") version "0.5-SNAPSHOT"
id("net.kyori.blossom") version "1.1.0"
id("fabric-loom") version "0.6-SNAPSHOT"
}
configurations {
create("shade")
}
val shade: Configuration by configurations.creating
val minecraftVersion = "1.16.5"
@@ -13,9 +10,9 @@ dependencies {
minecraft("com.mojang", "minecraft", minecraftVersion)
mappings(minecraft.officialMojangMappings())
modImplementation("net.fabricmc", "fabric-loader", "0.11.1")
modImplementation("net.fabricmc.fabric-api", "fabric-api", "0.29.4+1.16")
modImplementation("net.fabricmc.fabric-api", "fabric-api", "0.31.0+1.16")
add("shade", implementation(project(":minimotd-common")) {
shade(implementation(project(":minimotd-common")) {
exclude("net.kyori")
exclude("org.slf4j")
})
@@ -29,7 +26,7 @@ dependencies {
tasks {
shadowJar {
configurations = listOf(project.configurations.getByName("shade"))
configurations = listOf(shade)
relocate("io.leangen.geantyref", "xyz.jpenilla.minimotd.lib.io.leangen.geantyref")
relocate("org.spongepowered.configurate", "xyz.jpenilla.minimotd.lib.spongepowered.configurate")
relocate("com.typesafe.config", "xyz.jpenilla.minimotd.lib.typesafe.config")
@@ -40,20 +37,18 @@ tasks {
dependsOn(shadowJar)
input.set(shadowJar.get().outputs.files.singleFile)
archiveFileName.set("${project.name}-mc$minecraftVersion-${project.version}.jar")
destinationDirectory.set(rootProject.buildDir.resolve("libs"))
}
processResources {
filesMatching("fabric.mod.json") {
mapOf(
"{project.name}" to project.name,
"{rootProject.name}" to rootProject.name,
"{version}" to version.toString(),
"{description}" to project.description,
"{url}" to rootProject.ext["url"].toString()
).entries.forEach { (k, v) -> filter { it.replace(k, v as String) } }
"{project.version}" to project.version.toString(),
"{project.description}" to project.description.toString()
).forEach { (k, v) ->
filter { resource -> resource.replace(k, v) }
}
}
}
}
blossom {
replaceToken("{version}", version.toString(), "src/main/java/xyz/jpenilla/minimotd/fabric/MiniMOTDFabric.java")
}
@@ -23,6 +23,8 @@
*/
package xyz.jpenilla.minimotd.fabric;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.context.CommandContext;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
@@ -30,14 +32,13 @@ import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.minecraft.commands.Commands;
import net.minecraft.commands.CommandSourceStack;
import org.apache.commons.lang3.Validate;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.jpenilla.minimotd.common.CommandHandlerFactory;
import xyz.jpenilla.minimotd.common.MiniMOTD;
import xyz.jpenilla.minimotd.common.MiniMOTDPlatform;
import xyz.jpenilla.minimotd.common.UpdateChecker;
@@ -50,12 +51,13 @@ import java.nio.file.Path;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;
public class MiniMOTDFabric implements ModInitializer, MiniMOTDPlatform<String> {
import static net.minecraft.commands.Commands.literal;
public final class MiniMOTDFabric implements ModInitializer, MiniMOTDPlatform<String> {
private static MiniMOTDFabric instance = null;
private final Logger logger = LoggerFactory.getLogger(MiniMOTD.class);
private final Path dataDirectory = FabricLoader.getInstance().getConfigDir().resolve("MiniMOTD");
private final MiniMessage miniMessage = MiniMessage.get();
private final MiniMOTD<String> miniMOTD = new MiniMOTD<>(this);
private FabricServerAudiences audiences;
@@ -71,54 +73,41 @@ public class MiniMOTDFabric implements ModInitializer, MiniMOTDPlatform<String>
return this.miniMOTD;
}
public @NonNull MiniMessage miniMessage() {
return this.miniMessage;
}
@Override
public void onInitialize() {
this.registerCommand();
ServerLifecycleEvents.SERVER_STARTED.register(minecraftServer -> {
this.audiences = FabricServerAudiences.of(minecraftServer);
if (this.miniMOTD.configManager().pluginSettings().updateChecker()) {
CompletableFuture.runAsync(() -> new UpdateChecker("{version}").checkVersion().forEach(this.logger()::info));
CompletableFuture.runAsync(() -> new UpdateChecker().checkVersion().forEach(this.logger()::info));
}
});
this.miniMOTD.logger().info("Done initializing MiniMOTD");
}
private void registerCommand() {
CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> dispatcher.register(
Commands.literal("minimotd")
.requires(source -> source.hasPermission(4))
.then(Commands.literal("reload")
.executes(ctx -> {
final Audience audience = this.audiences.audience(ctx.getSource());
this.send(audience, "<white>[<gradient:blue:aqua>MiniMOTD</gradient>] <italic><gray>Reloading MiniMOTD...");
this.miniMOTD.configManager().loadConfigs();
this.miniMOTD.iconManager().loadIcons();
this.send(audience, "<white>[<gradient:blue:aqua>MiniMOTD</gradient>] <green>Done reloading MiniMOTD.");
return 1;
})
)
.then(Commands.literal("about")
.executes(ctx -> {
this.send(this.audiences.audience(ctx.getSource()),
"<strikethrough><gradient:black:white>------------------",
"<hover:show_text:'<gradient:blue:aqua>click me!'><click:open_url:https://github.com/jpenilla/MiniMOTD> MiniMOTD v{version}",
"<gray> By <gradient:gold:yellow>jmp",
"<strikethrough><gradient:black:white>------------------"
);
return 1;
})
)
));
}
final class WrappingExecutor implements Command<CommandSourceStack> {
private final CommandHandlerFactory.CommandHandler handler;
private void send(final @NonNull Audience audience, final String... strings) {
for (final String string : strings) {
audience.sendMessage(this.miniMessage.parse(string));
WrappingExecutor(final CommandHandlerFactory.@NonNull CommandHandler handler) {
this.handler = handler;
}
@Override
public int run(final @NonNull CommandContext<CommandSourceStack> context) {
this.handler.execute(MiniMOTDFabric.this.audiences.audience(context.getSource()));
return Command.SINGLE_SUCCESS;
}
}
final CommandHandlerFactory handlerFactory = new CommandHandlerFactory(this.miniMOTD);
CommandRegistrationCallback.EVENT.register((dispatcher, $) -> dispatcher.register(
literal("minimotd")
.requires(source -> source.hasPermission(4))
.then(literal("reload").executes(new WrappingExecutor(handlerFactory.reload())))
.then(literal("about").executes(new WrappingExecutor(handlerFactory.about())))
.then(literal("help").executes(new WrappingExecutor(handlerFactory.help())))
));
}
public @NonNull FabricServerAudiences audiences() {
@@ -24,7 +24,7 @@
package xyz.jpenilla.minimotd.fabric.access;
public interface ConnectionAccess {
void minimotd$protocolVersion(int protocolVersion);
void protocolVersion(int protocolVersion);
int minimotd$protocolVersion();
int protocolVersion();
}
@@ -24,21 +24,24 @@
package xyz.jpenilla.minimotd.fabric.mixin;
import net.minecraft.network.Connection;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import xyz.jpenilla.minimotd.fabric.access.ConnectionAccess;
@SuppressWarnings("checkstyle:FinalLocalVariable")
@Unique
@Mixin(Connection.class)
abstract class ConnectionMixin implements ConnectionAccess {
@Unique
@Implements({@Interface(iface = ConnectionAccess.class, prefix = "tabtps$")})
abstract class ConnectionMixin {
private int protocolVersion = -1;
public void minimotd$protocolVersion(int protocolVersion) {
public void tabtps$protocolVersion(int protocolVersion) {
this.protocolVersion = protocolVersion;
}
public int minimotd$protocolVersion() {
public int tabtps$protocolVersion() {
return this.protocolVersion;
}
}
@@ -29,17 +29,19 @@ import net.minecraft.server.network.ServerHandshakePacketListenerImpl;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import xyz.jpenilla.minimotd.fabric.access.ConnectionAccess;
@Unique
@Mixin(ServerHandshakePacketListenerImpl.class)
abstract class ServerHandshakePacketListenerImplMixin {
@Shadow @Final private Connection connection;
@Inject(method = "handleIntention", at = @At("HEAD"))
public void onRequest(final ClientIntentionPacket packet, final CallbackInfo ci) {
((ConnectionAccess) this.connection).minimotd$protocolVersion(packet.getProtocolVersion());
public void injectHandleIntention(final ClientIntentionPacket packet, final CallbackInfo ci) {
((ConnectionAccess) this.connection).protocolVersion(packet.getProtocolVersion());
}
}
@@ -25,7 +25,6 @@ package xyz.jpenilla.minimotd.fabric.mixin;
import com.mojang.authlib.GameProfile;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.minecraft.network.Connection;
import net.minecraft.network.protocol.status.ServerStatus;
import net.minecraft.server.MinecraftServer;
@@ -33,8 +32,10 @@ import net.minecraft.server.network.ServerStatusPacketListenerImpl;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
import xyz.jpenilla.minimotd.common.ComponentColorDownsampler;
import xyz.jpenilla.minimotd.common.Constants;
import xyz.jpenilla.minimotd.common.MOTDIconPair;
import xyz.jpenilla.minimotd.common.MiniMOTD;
@@ -42,18 +43,18 @@ import xyz.jpenilla.minimotd.common.config.MiniMOTDConfig;
import xyz.jpenilla.minimotd.fabric.MiniMOTDFabric;
import xyz.jpenilla.minimotd.fabric.access.ConnectionAccess;
@Unique
@Mixin(ServerStatusPacketListenerImpl.class)
abstract class ServerStatusPacketListenerImplMixin {
@Shadow @Final private Connection connection;
@Redirect(method = "handleStatusRequest", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getStatus()Lnet/minecraft/network/protocol/status/ServerStatus;"))
public ServerStatus method(final MinecraftServer minecraftServer) {
public ServerStatus injectHandleStatusRequest(final MinecraftServer minecraftServer) {
final ServerStatus vanillaStatus = minecraftServer.getStatus();
final ServerStatus modifiedStatus = new ServerStatus();
modifiedStatus.setDescription(vanillaStatus.getDescription());
modifiedStatus.setFavicon(vanillaStatus.getFavicon());
modifiedStatus.setPlayers(vanillaStatus.getPlayers());
modifiedStatus.setVersion(vanillaStatus.getVersion());
final MiniMOTDFabric miniMOTDFabric = MiniMOTDFabric.get();
@@ -61,19 +62,18 @@ abstract class ServerStatusPacketListenerImplMixin {
final MiniMOTDConfig config = miniMOTD.configManager().mainConfig();
final int onlinePlayers = miniMOTD.calculateOnlinePlayers(config, minecraftServer.getPlayerCount());
final int maxPlayers = config.adjustedMaxPlayers(onlinePlayers, modifiedStatus.getPlayers().getMaxPlayers());
final int maxPlayers = config.adjustedMaxPlayers(onlinePlayers, vanillaStatus.getPlayers().getMaxPlayers());
final MOTDIconPair<String> pair = miniMOTD.createMOTD(config, onlinePlayers, maxPlayers);
final String motdString = pair.motd();
if (motdString != null) {
final Component motdComponent = miniMOTDFabric.miniMessage().parse(motdString);
if (((ConnectionAccess) this.connection).minimotd$protocolVersion() >= Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
final Component motdComponent = pair.motd();
if (motdComponent != null) {
if (((ConnectionAccess) this.connection).protocolVersion() >= Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
modifiedStatus.setDescription(miniMOTDFabric.audiences().toNative(motdComponent));
} else {
modifiedStatus.setDescription(net.minecraft.network.chat.Component.Serializer.fromJson(
GsonComponentSerializer.colorDownsamplingGson().serialize(motdComponent))
);
modifiedStatus.setDescription(miniMOTDFabric.audiences().toNative(
ComponentColorDownsampler.downsampler().downsample(motdComponent)
));
}
}
@@ -82,17 +82,17 @@ abstract class ServerStatusPacketListenerImplMixin {
modifiedStatus.setFavicon(favicon);
}
final GameProfile[] oldSample = modifiedStatus.getPlayers().getSample();
final ServerStatus.Players newPlayers = new ServerStatus.Players(maxPlayers, onlinePlayers);
if (config.disablePlayerListHover()) {
newPlayers.setSample(new GameProfile[]{});
} else {
newPlayers.setSample(oldSample);
if (!config.hidePlayerCount()) {
final GameProfile[] oldSample = vanillaStatus.getPlayers().getSample();
final ServerStatus.Players newPlayers = new ServerStatus.Players(maxPlayers, onlinePlayers);
if (config.disablePlayerListHover()) {
newPlayers.setSample(new GameProfile[]{});
} else {
newPlayers.setSample(oldSample);
}
modifiedStatus.setPlayers(newPlayers);
}
modifiedStatus.setPlayers(newPlayers);
return modifiedStatus;
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
{
"schemaVersion": 1,
"id": "{project.name}",
"version": "{version}",
"version": "{project.version}",
"name": "{rootProject.name}",
"description": "{description}",
"description": "{project.description}",
"authors": [
"jmp"
],
@@ -19,7 +19,7 @@
],
"depends": {
"fabricloader": ">=0.11.1",
"fabric": "*",
"fabric": ">=0.31.0",
"minecraft": "1.16.x"
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
@@ -84,7 +84,7 @@ public final class MiniMOTDPlugin extends JavaPlugin implements MiniMOTDPlatform
if (this.miniMOTD.configManager().pluginSettings().updateChecker()) {
Bukkit.getScheduler().runTaskAsynchronously(this, () ->
new UpdateChecker(this.getDescription().getVersion()).checkVersion().forEach(getLogger()::info));
new UpdateChecker().checkVersion().forEach(getLogger()::info));
}
}
@@ -25,7 +25,6 @@ package xyz.jpenilla.minimotd.spigot;
import com.destroystokyo.paper.event.server.PaperServerListPingEvent;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -38,7 +37,6 @@ import xyz.jpenilla.minimotd.common.config.MiniMOTDConfig;
public class PaperPingListener implements Listener {
private final MiniMOTDPlugin plugin;
private final LegacyComponentSerializer serializer = LegacyComponentSerializer.builder().hexColors().useUnusualXRepeatedCharacterHexFormat().build();
private final MiniMessage miniMessage = MiniMessage.get();
private final LegacyComponentSerializer legacySerializer = LegacyComponentSerializer.builder().build();
private final MiniMOTD<CachedServerIcon> miniMOTD;
@@ -58,9 +56,8 @@ public class PaperPingListener implements Listener {
final MOTDIconPair<CachedServerIcon> pair = this.miniMOTD.createMOTD(cfg, onlinePlayers, maxPlayers);
final String motdString = pair.motd();
if (motdString != null) {
final Component motdComponent = this.miniMessage.parse(motdString);
final Component motdComponent = pair.motd();
if (motdComponent != null) {
if (e.getClient().getProtocolVersion() < 735 || this.plugin.majorMinecraftVersion() < 16) {
e.setMotd(this.legacySerializer.serialize(motdComponent));
} else {
@@ -76,5 +73,8 @@ public class PaperPingListener implements Listener {
if (cfg.disablePlayerListHover()) {
e.getPlayerSample().clear();
}
if (cfg.hidePlayerCount()) {
e.setHidePlayers(true);
}
}
}
@@ -23,7 +23,7 @@
*/
package xyz.jpenilla.minimotd.spigot;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -38,7 +38,6 @@ public class PingListener implements Listener {
private final MiniMOTD<CachedServerIcon> miniMOTD;
private final LegacyComponentSerializer serializer = LegacyComponentSerializer.builder().hexColors().useUnusualXRepeatedCharacterHexFormat().build();
private final LegacyComponentSerializer legacySerializer = LegacyComponentSerializer.builder().build();
private final MiniMessage miniMessage = MiniMessage.get();
private final MiniMOTDPlugin plugin;
public PingListener(final @NonNull MiniMOTDPlugin plugin, final @NonNull MiniMOTD<CachedServerIcon> miniMOTD) {
@@ -56,12 +55,12 @@ public class PingListener implements Listener {
e.setMaxPlayers(maxPlayers);
final MOTDIconPair<CachedServerIcon> pair = this.miniMOTD.createMOTD(cfg, onlinePlayers, maxPlayers);
final String motdString = pair.motd();
if (motdString != null) {
final Component motdComponent = pair.motd();
if (motdComponent != null) {
if (this.plugin.majorMinecraftVersion() > 15) {
e.setMotd(this.serializer.serialize(this.miniMessage.parse(motdString)));
e.setMotd(this.serializer.serialize(motdComponent));
} else {
e.setMotd(this.legacySerializer.serialize(this.miniMessage.parse(motdString)));
e.setMotd(this.legacySerializer.serialize(motdComponent));
}
}
@@ -24,112 +24,70 @@
package xyz.jpenilla.minimotd.spigot;
import com.google.common.collect.ImmutableList;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import xyz.jpenilla.minimotd.common.CommandHandlerFactory;
import java.util.Collections;
import java.util.List;
public class SpigotCommand implements CommandExecutor, TabCompleter {
private final MiniMOTDPlugin plugin;
private final MiniMessage miniMessage;
private final CommandHandlerFactory handlerFactory;
public SpigotCommand(final @NonNull MiniMOTDPlugin plugin) {
this.plugin = plugin;
this.miniMessage = MiniMessage.get();
this.handlerFactory = new CommandHandlerFactory(plugin.miniMOTD());
}
@Override
public boolean onCommand(final @NonNull CommandSender sender,
final @NonNull Command command,
final @NonNull String label,
final @NonNull String[] args) {
public boolean onCommand(final @NonNull CommandSender sender, final @NonNull Command command, final @NonNull String label, final @NonNull String[] args) {
final Audience audience = this.plugin.audiences().sender(sender);
if (!sender.hasPermission("minimotd.admin")) {
this.onNoPermission(sender, args);
audience.sendMessage(Component.text("No permission.", NamedTextColor.RED));
return true;
}
if (args.length == 0) {
this.onInvalidUse(sender, args);
this.onInvalidUse(audience);
return true;
}
switch (args[0]) {
case "about":
this.onAbout(sender, args);
this.handlerFactory.about().execute(audience);
return true;
case "help":
this.onHelp(sender, args);
this.handlerFactory.help().execute(audience);
return true;
case "reload":
this.onReload(sender, args);
this.handlerFactory.reload().execute(audience);
return true;
}
this.onInvalidUse(sender, args);
this.onInvalidUse(audience);
return true;
}
private void onHelp(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.send(sender, ImmutableList.of(
"<gradient:blue:green>MiniMOTD Commands:",
" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd about'><click:run_command:/minimotd about><yellow>/minimotd about",
" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd reload'><click:run_command:/minimotd reload><yellow>/minimotd reload",
" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd help'><click:run_command:/minimotd help><yellow>/minimotd help"
));
}
private void onReload(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.plugin.miniMOTD().iconManager().loadIcons();
this.plugin.miniMOTD().configManager().loadConfigs();
this.send(sender, "<green>Done reloading.");
}
private void onAbout(final @NonNull CommandSender sender, final @NonNull String[] args) {
final String header = "<gradient:white:black>=============</gradient><gradient:black:white>=============";
this.send(sender, ImmutableList.of(
header,
"<hover:show_text:'<rainbow>click me!'><click:open_url:" + this.plugin.getDescription().getWebsite() + ">" + this.plugin.getName() + " <gradient:red:yellow>" + this.plugin.getDescription().getVersion(),
"<yellow>By</yellow><gray>:</gray> <gradient:blue:green>jmp",
header
));
}
private void onInvalidUse(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.send(sender, "<hover:show_text:'<green>Click for <yellow>/minimotd help'><click:run_command:/minimotd help><italic><gradient:red:gold>Invalid usage.</gradient> <blue>Try <yellow>/minimotd help</yellow> or click here");
}
private void onNoPermission(final @NonNull CommandSender sender, final @NonNull String[] args) {
this.send(sender, "<gradient:red:yellow>No permission.");
}
private void send(final @NonNull CommandSender sender, final @NonNull String message) {
if (sender instanceof Player) {
this.plugin.audiences().player((Player) sender).sendMessage(Identity.nil(), this.miniMessage.parse(message));
} else {
this.plugin.audiences().console().sendMessage(Identity.nil(), this.miniMessage.parse(message));
}
}
private void send(final @NonNull CommandSender sender, final @NonNull List<String> messages) {
for (final String message : messages) {
this.send(sender, message);
}
private void onInvalidUse(final @NonNull Audience audience) {
audience.sendMessage(
Component.text("Invalid command usage. Use '/minimotd help' for a list of command provided by MiniMOTD.", NamedTextColor.RED)
.hoverEvent(Component.text("Click to execute '/minimotd help'"))
.clickEvent(ClickEvent.runCommand("/minimotd help"))
);
}
private static final List<String> COMMANDS = ImmutableList.of("about", "reload", "help");
@Override
public List<String> onTabComplete(final @NonNull CommandSender sender,
final @NonNull Command command,
final @NonNull String alias,
final @NonNull String[] args) {
public List<String> onTabComplete(final @NonNull CommandSender sender, final @NonNull Command command, final @NonNull String alias, final @NonNull String[] args) {
if (args.length < 2 && sender.hasPermission("minimotd.admin")) {
return COMMANDS;
}
+32 -13
View File
@@ -1,8 +1,35 @@
import org.spongepowered.gradle.plugin.config.PluginLoaders.JAVA_PLAIN
import org.spongepowered.plugin.metadata.PluginDependency.LoadOrder.AFTER
plugins {
id("org.spongepowered.gradle.plugin") version "1.0.2"
}
dependencies {
implementation(project(":minimotd-common"))
implementation("net.kyori", "adventure-text-serializer-legacy", "4.4.0")
compileOnly("org.spongepowered", "spongeapi", "8.0.0-SNAPSHOT")
annotationProcessor("org.spongepowered", "spongeapi", "8.0.0-SNAPSHOT")
}
sponge {
apiVersion("8.0.0")
plugin(project.name) {
loader(JAVA_PLAIN)
displayName(rootProject.name)
mainClass("xyz.jpenilla.minimotd.sponge8.MiniMOTDPlugin")
description(project.description)
links {
val url = rootProject.ext["url"].toString()
homepage(url)
source(url)
issues("${url}issues/")
}
contributor("jmp") {
description("Lead Developer")
}
dependency("spongeapi") {
loadOrder(AFTER)
optional(false)
}
}
}
tasks {
@@ -19,16 +46,8 @@ tasks {
exclude(dependency("org.slf4j:slf4j-api"))
}
}
processResources {
filesMatching("**/plugins.json") {
mapOf(
"{project.name}" to project.name,
"{rootProject.name}" to rootProject.name,
"{version}" to version.toString(),
"{description}" to project.description,
"{url}" to rootProject.ext["url"].toString()
).entries.forEach { (k, v) -> filter { it.replace(k, v as String) } }
}
runServer {
classpath(shadowJar)
}
build {
dependsOn(shadowJar)
@@ -0,0 +1,104 @@
/*
* This file is part of MiniMOTD, licensed under the MIT License.
*
* Copyright (c) 2021 Jason Penilla
*
* 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.
*/
package xyz.jpenilla.minimotd.sponge8;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.spongepowered.api.MinecraftVersion;
import org.spongepowered.api.event.EventListener;
import org.spongepowered.api.event.server.ClientPingServerEvent;
import org.spongepowered.api.network.status.Favicon;
import xyz.jpenilla.minimotd.common.ComponentColorDownsampler;
import xyz.jpenilla.minimotd.common.Constants;
import xyz.jpenilla.minimotd.common.MOTDIconPair;
import xyz.jpenilla.minimotd.common.MiniMOTD;
import xyz.jpenilla.minimotd.common.config.MiniMOTDConfig;
import java.lang.reflect.Method;
final class ClientPingServerEventListener implements EventListener<ClientPingServerEvent> {
private final MiniMOTD<Favicon> miniMOTD;
private Method SpongeMinecraftVersion_getProtocol;
ClientPingServerEventListener(final @NonNull MiniMOTD<Favicon> miniMOTD) {
this.miniMOTD = miniMOTD;
}
@Override
public void handle(final @NonNull ClientPingServerEvent event) {
final ClientPingServerEvent.Response response = event.getResponse();
final ClientPingServerEvent.Response.Players players;
final ClientPingServerEvent.Response.Players players0 = response.getPlayers().orElse(null);
if (players0 != null) {
players = players0;
} else {
response.setHidePlayers(false);
players = response.getPlayers().orElse(null);
if (players == null) {
this.miniMOTD.logger().warn(String.format("Failed to handle ClientPingServerEvent: '%s', response.getPlayers() was null.", event.toString()));
return;
}
}
final MiniMOTDConfig config = this.miniMOTD.configManager().mainConfig();
final int onlinePlayers = this.miniMOTD.calculateOnlinePlayers(config, players.getOnline());
players.setOnline(onlinePlayers);
final int maxPlayers = config.adjustedMaxPlayers(onlinePlayers, players.getMax());
players.setMax(maxPlayers);
final @NonNull MOTDIconPair<Favicon> pair = this.miniMOTD.createMOTD(config, onlinePlayers, maxPlayers);
final Component motdComponent = pair.motd();
try {
if (motdComponent != null) {
final MinecraftVersion version = event.getClient().getVersion();
if (!version.isLegacy() && this.SpongeMinecraftVersion_getProtocol == null) {
this.SpongeMinecraftVersion_getProtocol = version.getClass().getMethod("getProtocol");
}
if (version.isLegacy() || (int) this.SpongeMinecraftVersion_getProtocol.invoke(version) < Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
response.setDescription(ComponentColorDownsampler.downsampler().downsample(motdComponent));
} else {
response.setDescription(motdComponent);
}
}
} catch (final ReflectiveOperationException e) {
throw new IllegalStateException("Failed to get protocol version", e);
}
final Favicon favicon = pair.icon();
if (favicon != null) {
response.setFavicon(favicon);
}
if (config.disablePlayerListHover()) {
players.getProfiles().clear();
}
if (config.hidePlayerCount()) {
response.setHidePlayers(true);
}
}
}
@@ -24,41 +24,39 @@
package xyz.jpenilla.minimotd.sponge8;
import com.google.inject.Inject;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.api.MinecraftVersion;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.Command;
import org.spongepowered.api.command.CommandExecutor;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.parameter.CommandContext;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.lifecycle.LoadedGameEvent;
import org.spongepowered.api.event.lifecycle.RefreshGameEvent;
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
import org.spongepowered.api.event.server.ClientPingServerEvent;
import org.spongepowered.api.network.status.Favicon;
import org.spongepowered.api.scheduler.Task;
import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.jvm.Plugin;
import org.spongepowered.plugin.metadata.PluginMetadata;
import xyz.jpenilla.minimotd.common.Constants;
import xyz.jpenilla.minimotd.common.MOTDIconPair;
import xyz.jpenilla.minimotd.common.CommandHandlerFactory;
import xyz.jpenilla.minimotd.common.MiniMOTD;
import xyz.jpenilla.minimotd.common.MiniMOTDPlatform;
import xyz.jpenilla.minimotd.common.UpdateChecker;
import xyz.jpenilla.minimotd.common.config.MiniMOTDConfig;
import java.awt.image.BufferedImage;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.Objects;
@Plugin("minimotd-sponge8") // todo commands
public class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
@Plugin("minimotd-sponge8")
public final class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
private final Path dataDirectory;
private final PluginMetadata pluginMetadata;
private final Logger logger;
private final MiniMessage miniMessage = MiniMessage.get();
private final PluginContainer pluginContainer;
private final MiniMOTD<Favicon> miniMOTD;
@@ -72,58 +70,62 @@ public class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
this.pluginMetadata = pluginContainer.getMetadata();
this.logger = LoggerFactory.getLogger(this.pluginMetadata.getId());
this.miniMOTD = new MiniMOTD<>(this);
Sponge.getEventManager().registerListener(
pluginContainer,
ClientPingServerEvent.class,
new ClientPingServerEventListener(this.miniMOTD)
);
}
@Listener
public void onServerStart(final @NonNull LoadedGameEvent event) {
Sponge.getAsyncScheduler().submit(Task.builder().plugin(this.pluginContainer).execute(() ->
new UpdateChecker(this.pluginMetadata.getVersion()).checkVersion().forEach(this.logger::info)
).build());
public void onGameLoaded(final @NonNull LoadedGameEvent event) {
Sponge.getAsyncScheduler().submit(Task.builder()
.plugin(this.pluginContainer)
.execute(() -> new UpdateChecker().checkVersion().forEach(this.logger::info))
.build());
}
private Method SpongeMinecraftVersion_getProtocol;
@Listener
public void registerCommands(final @NonNull RegisterCommandEvent<Command.Parameterized> event) {
final class WrappingExecutor implements CommandExecutor {
private final CommandHandlerFactory.CommandHandler handler;
WrappingExecutor(final CommandHandlerFactory.@NonNull CommandHandler handler) {
this.handler = handler;
}
@Override
public CommandResult execute(final @NonNull CommandContext context) {
this.handler.execute(context.getCause().getAudience());
return CommandResult.success();
}
}
final CommandHandlerFactory handlerFactory = new CommandHandlerFactory(this.miniMOTD);
final Command.Parameterized about = Command.builder()
.setExecutor(new WrappingExecutor(handlerFactory.about()))
.build();
final Command.Parameterized help = Command.builder()
.setExecutor(new WrappingExecutor(handlerFactory.help()))
.build();
final Command.Parameterized reload = Command.builder()
.setExecutor(new WrappingExecutor(handlerFactory.reload()))
.build();
event.register(
this.pluginContainer,
Command.builder()
.setPermission("minimotd.admin")
.child(about, "about")
.child(help, "help")
.child(reload, "reload")
.build(),
"minimotd"
);
}
@Listener
public void onPing(final @NonNull ClientPingServerEvent event) {
final ClientPingServerEvent.Response response = event.getResponse();
response.getPlayers().ifPresent(players -> {
final MiniMOTDConfig config = this.miniMOTD.configManager().mainConfig();
final int onlinePlayers = this.miniMOTD.calculateOnlinePlayers(config, players.getOnline());
players.setOnline(onlinePlayers);
final int maxPlayers = config.adjustedMaxPlayers(onlinePlayers, players.getMax());
players.setMax(maxPlayers);
final @NonNull MOTDIconPair<Favicon> pair = this.miniMOTD.createMOTD(config, onlinePlayers, maxPlayers);
final String motdString = pair.motd();
try {
if (motdString != null) {
Component motdComponent = this.miniMessage.parse(motdString);
final MinecraftVersion version = event.getClient().getVersion();
if (!version.isLegacy() && this.SpongeMinecraftVersion_getProtocol == null) {
this.SpongeMinecraftVersion_getProtocol = version.getClass().getMethod("getProtocol");
}
if (version.isLegacy() || (int) this.SpongeMinecraftVersion_getProtocol.invoke(version) < Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
motdComponent = GsonComponentSerializer.colorDownsamplingGson().deserialize(GsonComponentSerializer.colorDownsamplingGson().serialize(motdComponent));
}
response.setDescription(motdComponent);
}
} catch (final ReflectiveOperationException e) {
throw new IllegalStateException("Failed to get protocol version", e);
}
final Favicon favicon = pair.icon();
if (favicon != null) {
response.setFavicon(favicon);
}
if (config.disablePlayerListHover()) {
players.getProfiles().clear();
}
});
public void onRefresh(final @NonNull RefreshGameEvent event) {
this.miniMOTD.reload();
}
@Override
@@ -1,29 +0,0 @@
{
"plugins": [
{
"loader": "java_plain",
"id": "{project.name}",
"name": "{rootProject.name}",
"version": "{version}",
"main-class": "xyz.jpenilla.minimotd.sponge8.MiniMOTDPlugin",
"description": "{description}",
"links": {
"homepage": "{url}",
"source": "{url}",
"issues": "{url}issues"
},
"contributors": [
{
"name": "jmp",
"description": "Lead Developer"
}
],
"dependencies": [
{
"id": "spongeapi",
"version": "8.0.0"
}
]
}
]
}
+1
View File
@@ -2,6 +2,7 @@ tasks {
val universal = register<Jar>("universal") {
artifacts.add("archives", this)
archiveClassifier.set("")
destinationDirectory.set(rootProject.buildDir.resolve("libs"))
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
arrayOf("spigot", "bungeecord", "velocity", "sponge8").forEach {
val shadowJar = rootProject.project(":minimotd-$it").tasks.getByName("shadowJar")
+7 -15
View File
@@ -1,7 +1,5 @@
import net.kyori.blossom.BlossomExtension
plugins {
id("net.kyori.blossom") version "1.1.0"
id("net.kyori.blossom")
}
dependencies {
@@ -32,19 +30,13 @@ tasks {
}
blossom {
fun replaceTokens(file: String, vararg tokens: Pair<String, String>) = tokens.forEach { (k, v) ->
replaceToken("\${$k}", v, file)
}
replaceTokens(
"src/main/java/xyz/jpenilla/minimotd/velocity/MiniMOTDPlugin.java",
"{project.name}" to project.name,
"{rootProject.name}" to rootProject.name,
"{version}" to version.toString(),
"{description}" to description!!,
"{url}" to rootProject.ext["url"].toString()
"project.name" to project.name,
"description" to description!!,
"url" to rootProject.ext["url"].toString()
)
}
fun BlossomExtension.replaceTokens(
filePath: String,
vararg replacements: Pair<String, String>
) {
for ((token, replacement) in replacements) replaceToken(token, replacement, filePath)
}
@@ -24,7 +24,12 @@
package xyz.jpenilla.minimotd.velocity;
import com.google.inject.Inject;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandManager;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyPingEvent;
@@ -37,10 +42,11 @@ import com.velocitypowered.api.proxy.server.ServerPing;
import com.velocitypowered.api.util.Favicon;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bstats.velocity.Metrics;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import xyz.jpenilla.minimotd.common.CommandHandlerFactory;
import xyz.jpenilla.minimotd.common.ComponentColorDownsampler;
import xyz.jpenilla.minimotd.common.Constants;
import xyz.jpenilla.minimotd.common.MOTDIconPair;
import xyz.jpenilla.minimotd.common.MiniMOTD;
@@ -52,14 +58,14 @@ import java.awt.image.BufferedImage;
import java.nio.file.Path;
@Plugin(
id = "{project.name}",
name = "{rootProject.name}",
version = "{version}",
description = "{description}",
url = "{url}",
id = "${project.name}",
name = Constants.PluginMetadata.NAME,
version = Constants.PluginMetadata.VERSION,
description = "${description}",
url = "${url}",
authors = {"jmp"}
)
public class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
public final class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
private final MiniMOTD<Favicon> miniMOTD;
private final ProxyServer server;
private final Logger logger;
@@ -90,16 +96,41 @@ public class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
@Subscribe
public void onProxyInitialization(final @NonNull ProxyInitializeEvent event) {
this.commandManager.register(this.commandManager.metaBuilder("minimotd").build(), new VelocityCommand(this));
this.registerCommand();
this.metricsFactory.make(this, 10257);
if (this.miniMOTD.configManager().pluginSettings().updateChecker()) {
this.server.getScheduler().buildTask(this, () ->
new UpdateChecker(this.pluginDescription().getVersion().orElse("")).checkVersion().forEach(this.logger::info)
this.server.getScheduler().buildTask(
this,
() -> new UpdateChecker().checkVersion().forEach(this.logger::info)
).schedule();
}
}
private void registerCommand() {
final class WrappingExecutor implements Command<CommandSource> {
private final CommandHandlerFactory.CommandHandler handler;
WrappingExecutor(final CommandHandlerFactory.@NonNull CommandHandler handler) {
this.handler = handler;
}
@Override
public int run(final @NonNull CommandContext<CommandSource> context) {
this.handler.execute(context.getSource());
return Command.SINGLE_SUCCESS;
}
}
final CommandHandlerFactory handlerFactory = new CommandHandlerFactory(this.miniMOTD);
this.commandManager.register(this.commandManager.metaBuilder("minimotd").build(), new BrigadierCommand(
LiteralArgumentBuilder.<CommandSource>literal("minimotd")
.requires(source -> source.hasPermission("minimotd.admin"))
.then(LiteralArgumentBuilder.<CommandSource>literal("help").executes(new WrappingExecutor(handlerFactory.help())))
.then(LiteralArgumentBuilder.<CommandSource>literal("about").executes(new WrappingExecutor(handlerFactory.about())))
.then(LiteralArgumentBuilder.<CommandSource>literal("reload").executes(new WrappingExecutor(handlerFactory.reload())))
));
}
@Subscribe
public void onServerListPing(final @NonNull ProxyPingEvent ping) {
final String configString = this.miniMOTD.configManager().pluginSettings().configStringForHost(
@@ -123,18 +154,21 @@ public class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
pong.favicon(favicon);
}
final String motdString = pair.motd();
if (motdString != null) {
Component motdComponent = this.miniMessage.parse(motdString);
final Component motdComponent = pair.motd();
if (motdComponent != null) {
if (pong.getVersion().getProtocol() < Constants.MINECRAFT_1_16_PROTOCOL_VERSION) {
motdComponent = GsonComponentSerializer.colorDownsamplingGson().deserialize(GsonComponentSerializer.colorDownsamplingGson().serialize(motdComponent));
pong.description(ComponentColorDownsampler.downsampler().downsample(motdComponent));
} else {
pong.description(motdComponent);
}
pong.description(motdComponent);
}
if (config.disablePlayerListHover()) {
pong.clearSamplePlayers();
}
if (config.hidePlayerCount()) {
pong.nullPlayers();
}
ping.setPing(pong.build());
}
@@ -165,4 +199,9 @@ public class MiniMOTDPlugin implements MiniMOTDPlatform<Favicon> {
public @NonNull PluginDescription pluginDescription() {
return this.pluginContainer.getDescription();
}
@Override
public void onReload() {
this.miniMOTD.configManager().loadExtraConfigs();
}
}
@@ -1,109 +0,0 @@
/*
* This file is part of MiniMOTD, licensed under the MIT License.
*
* Copyright (c) 2021 Jason Penilla
*
* 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.
*/
package xyz.jpenilla.minimotd.velocity;
import com.google.common.collect.ImmutableList;
import com.velocitypowered.api.command.SimpleCommand;
import net.kyori.adventure.identity.Identity;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
public class VelocityCommand implements SimpleCommand {
private final MiniMOTDPlugin plugin;
public VelocityCommand(final @NonNull MiniMOTDPlugin plugin) {
this.plugin = plugin;
}
@Override
public void execute(final @NonNull Invocation invocation) {
final String[] args = invocation.arguments();
if (args.length == 0) {
this.onInvalidUse(invocation);
return;
}
switch (args[0]) {
case "about":
this.onAbout(invocation);
return;
case "help":
this.onHelp(invocation);
return;
case "reload":
this.onReload(invocation);
return;
}
this.onInvalidUse(invocation);
}
private void onInvalidUse(final @NonNull Invocation invocation) {
this.sendMessages(invocation, ImmutableList.of("<hover:show_text:'<green>Click for <yellow>/minimotd help'><click:run_command:/minimotd help><italic><gradient:red:gold>Invalid usage.</gradient> <blue>Try <yellow>/minimotd help</yellow> or click here"));
}
private void onReload(final @NonNull Invocation invocation) {
this.plugin.miniMOTD().iconManager().loadIcons();
this.plugin.miniMOTD().configManager().loadExtraConfigs();
this.plugin.miniMOTD().configManager().loadConfigs();
this.sendMessages(invocation, ImmutableList.of("<green>Done reloading."));
}
private void onHelp(final @NonNull Invocation invocation) {
this.sendMessages(invocation, ImmutableList.of(
"<gradient:blue:green>MiniMOTD Commands:",
" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd about'><click:run_command:/minimotd about><yellow>/minimotd about",
" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd reload'><click:run_command:/minimotd reload><yellow>/minimotd reload",
" <gray>-</gray> <hover:show_text:'<green>Click for <yellow>/minimotd help'><click:run_command:/minimotd help><yellow>/minimotd help"
));
}
private void onAbout(final @NonNull Invocation invocation) {
final String header = "<gradient:white:black>=============</gradient><gradient:black:white>=============";
this.sendMessages(invocation, ImmutableList.of(
header,
"<hover:show_text:'<rainbow>click me!'><click:open_url:" + this.plugin.pluginDescription().getUrl().orElse("") + ">" + this.plugin.pluginDescription().getName().orElse("") + " <gradient:red:yellow>" + this.plugin.pluginDescription().getVersion().orElse(""),
"<yellow>By</yellow><gray>:</gray> <gradient:blue:green>jmp",
header
));
}
private void sendMessages(final @NonNull Invocation invocation, final @NonNull List<String> messages) {
messages.forEach(message -> invocation.source().sendMessage(Identity.nil(), this.plugin.miniMessage().parse(message)));
}
private static final List<String> COMMANDS = ImmutableList.of("about", "reload", "help");
@Override
public List<String> suggest(final @NonNull Invocation invocation) {
return COMMANDS;
}
@Override
public boolean hasPermission(final @NonNull Invocation invocation) {
return invocation.source().hasPermission("minimotd.admin");
}
}