18 Commits

Author SHA1 Message Date
91a28b4500 Merge branch 'master' into develop-backendUpdate 2025-10-27 17:11:01 +01:00
e745ff4721 added AntiFormattedBook to detect and sanitize illegal book formatting 2025-10-27 17:10:44 +01:00
23af3ff784 Merge branch 'master' into develop-backendUpdate 2025-10-27 16:14:24 +01:00
bc5c9a2a13 added AntiIllegalBundlePicker to track and notify admins on illegal bundle interactions 2025-10-27 16:02:13 +01:00
c220479052 WIP: refactored report and feedback systems; updated repository models, APIs, and component utilities 2025-10-27 14:25:44 +01:00
78f87d97f0 Merge remote-tracking branch 'origin/master' 2025-10-19 12:54:35 +02:00
db13a9f0a2 simplified event message handling logic in ChatMessagesListener 2025-10-19 12:54:31 +02:00
09abfefe33 added PhantomReducer 2025-10-17 18:39:05 +02:00
bd3546abc8 changed report appliance to craftattack 2025-10-17 18:00:15 +02:00
8a7a0453ce updated Whitelist api for new Backend 2025-10-17 17:28:25 +02:00
64d0d817c0 Merge pull request 'added IronGolemAnimation' (#8) from develop-animatedIronGolem into master
Reviewed-on: #8
Reviewed-by: Lars Neuhaus <larslukasneuhaus@gmx.de>
2025-10-14 22:42:52 +00:00
713561bf07 adjusted Iron Golem animation viewer calculation to account for block distance 2025-10-12 23:07:09 +02:00
4be3e528b1 fixed spawn reason check for Iron Golem spawning logic in NaturalIronGolemSpawnEvent 2025-10-12 23:05:19 +02:00
53fca580f3 added IronGolemAnimation 2025-10-12 23:04:05 +02:00
20fb4bf9fb added example local Gradle tasks for deploying and uploading plugins 2025-10-12 21:31:35 +02:00
c42d259909 Merge pull request 'added RecoveryCompass' (#7) from develop-recoveryCompass into master
Reviewed-on: #7
Reviewed-by: Lars Neuhaus <larslukasneuhaus@gmx.de>
2025-10-11 00:42:05 +00:00
5c82c8d6da resolved pr comments 2025-10-11 00:04:09 +02:00
5910847172 added RecoveryCompass 2025-10-10 23:39:29 +02:00
61 changed files with 591 additions and 661 deletions

View File

@@ -6,6 +6,7 @@ import org.bukkit.configuration.ConfigurationSection;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.util.Objects; import java.util.Objects;
public class CraftAttackApi { public class CraftAttackApi {
@@ -25,4 +26,8 @@ public class CraftAttackApi {
public static void withAuthorizationSecret(URIBuilder builder) { public static void withAuthorizationSecret(URIBuilder builder) {
builder.addParameter("secret", apiSecret); builder.addParameter("secret", apiSecret);
} }
public static void withAuthorizationHeader(HttpRequest.Builder builder) {
builder.header("Authorization", apiSecret);
}
} }

View File

@@ -6,20 +6,19 @@ import java.util.UUID;
public class CraftAttackReportRepository extends ReportRepository { public class CraftAttackReportRepository extends ReportRepository {
public CraftAttackReportRepository() { public CraftAttackReportRepository() {
super(CraftAttackApi.getBaseUri(), new RequestModifier(CraftAttackApi::withAuthorizationSecret, null)); super(CraftAttackApi.getBaseUri(), new RequestModifier(null, CraftAttackApi::withAuthorizationHeader));
} }
public ReqResp<PlayerReports> queryReports(UUID player) { public ReqResp<PlayerReports> queryReports(UUID player) {
return this.get( return this.get(
"report", "users/%s/reports".formatted(player.toString()),
(parameters) -> parameters.addParameter("uuid", player.toString()),
PlayerReports.class PlayerReports.class
); );
} }
public ReqResp<ReportUrl> createReport(ReportCreationInfo data) { public ReqResp<ReportUrl> createReport(ReportCreationInfo data) {
return this.post( return this.post(
"report", "reports",
data, data,
ReportUrl.class ReportUrl.class
); );

View File

@@ -23,19 +23,18 @@ public abstract class ReportRepository extends HttpRepository {
public record PlayerReports( public record PlayerReports(
List<Report> from_self, List<Report> from_self,
Object to_self List<Report> to_self
) { ) {
public record Report( public record Report(
@Nullable Reporter reported, @Nullable UUID reported,
@NotNull String subject, @NotNull String reason,
boolean draft, @Nullable Long created,
@NotNull String status, @Nullable Status status,
@NotNull String url @NotNull String url
) { ) {
public record Reporter( public enum Status {
@NotNull String username, open,
@NotNull String uuid closed,
) {
} }
} }
} }

View File

@@ -21,18 +21,17 @@ class ChatMessagesListener extends ApplianceListener<ChatMessages> {
public void onPlayerChatEvent(AsyncChatEvent event) { public void onPlayerChatEvent(AsyncChatEvent event) {
event.renderer( event.renderer(
(source, sourceDisplayName, message, viewer) -> (source, sourceDisplayName, message, viewer) ->
Component.text("") Component.text()
.append(this.getAppliance().getReportablePlayerName(source)) .append(this.getAppliance().getReportablePlayerName(source))
.append(Component.text(" > ").color(TextColor.color(Color.GRAY.asRGB()))) .append(Component.text(" > ").color(TextColor.color(Color.GRAY.asRGB())))
.append(message).color(TextColor.color(Color.SILVER.asRGB())) .append(message).color(TextColor.color(Color.SILVER.asRGB()))
.build()
); );
} }
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
boolean wasHidden = event.joinMessage() == null; if(event.joinMessage() == null) return;
event.joinMessage(null);
if(wasHidden) return;
IteratorUtil.onlinePlayers(player -> { IteratorUtil.onlinePlayers(player -> {
if(!Settings.instance().getSetting(player, Settings.Key.ShowJoinAndLeaveMessages, Boolean.class)) return; if(!Settings.instance().getSetting(player, Settings.Key.ShowJoinAndLeaveMessages, Boolean.class)) return;
player.sendMessage( player.sendMessage(
@@ -45,9 +44,7 @@ class ChatMessagesListener extends ApplianceListener<ChatMessages> {
@EventHandler @EventHandler
public void onPlayerLeave(PlayerQuitEvent event) { public void onPlayerLeave(PlayerQuitEvent event) {
boolean wasHidden = event.quitMessage() == null; if(event.quitMessage() == null) return;
event.quitMessage(null);
if(wasHidden) return;
IteratorUtil.onlinePlayers(player -> { IteratorUtil.onlinePlayers(player -> {
if(!Settings.instance().getSetting(player, Settings.Key.ShowJoinAndLeaveMessages, Boolean.class)) return; if(!Settings.instance().getSetting(player, Settings.Key.ShowJoinAndLeaveMessages, Boolean.class)) return;
player.sendMessage( player.sendMessage(

View File

@@ -1,12 +1,12 @@
package eu.mhsl.craftattack.spawn.common.appliances.metaGameplay.report; package eu.mhsl.craftattack.spawn.common.appliances.metaGameplay.report;
import eu.mhsl.craftattack.spawn.common.api.repositories.ReportRepository; import eu.mhsl.craftattack.spawn.common.api.repositories.ReportRepository;
import eu.mhsl.craftattack.spawn.common.api.repositories.VaroReportRepository;
import eu.mhsl.craftattack.spawn.core.Main; import eu.mhsl.craftattack.spawn.core.Main;
import eu.mhsl.craftattack.spawn.core.api.client.ReqResp; import eu.mhsl.craftattack.spawn.core.api.client.ReqResp;
import eu.mhsl.craftattack.spawn.common.api.repositories.CraftAttackReportRepository; import eu.mhsl.craftattack.spawn.common.api.repositories.CraftAttackReportRepository;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance; import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.core.appliance.ApplianceCommand;
import eu.mhsl.craftattack.spawn.core.util.text.ComponentUtil;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentBuilder; import net.kyori.adventure.text.ComponentBuilder;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
@@ -20,7 +20,9 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function;
public class Report extends Appliance { public class Report extends Appliance {
public static Component helpText() { public static Component helpText() {
@@ -64,7 +66,7 @@ public class Report extends Appliance {
} }
private void createReport(Player issuer, ReportRepository.ReportCreationInfo reportRequest) { private void createReport(Player issuer, ReportRepository.ReportCreationInfo reportRequest) {
ReqResp<ReportRepository.ReportUrl> createdReport = this.queryRepository(VaroReportRepository.class) ReqResp<ReportRepository.ReportUrl> createdReport = this.queryRepository(CraftAttackReportRepository.class) // TODO: Besser machen!!
.createReport(reportRequest); .createReport(reportRequest);
switch(createdReport.status()) { switch(createdReport.status()) {
@@ -79,7 +81,7 @@ public class Report extends Appliance {
.appendNewline() .appendNewline()
.append( .append(
Component Component
.text(createdReport.data().url(), NamedTextColor.GRAY) // URL mit Weltkugel-Emoji .text(createdReport.data().url(), NamedTextColor.GRAY)
.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, createdReport.data().url())) .clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, createdReport.data().url()))
) )
.appendNewline() .appendNewline()
@@ -115,7 +117,7 @@ public class Report extends Appliance {
} }
public void queryReports(Player issuer) { public void queryReports(Player issuer) {
ReqResp<ReportRepository.PlayerReports> userReports = this.queryRepository(VaroReportRepository.class) ReqResp<ReportRepository.PlayerReports> userReports = this.queryRepository(CraftAttackReportRepository.class) // TODO: Besser machen!!
.queryReports(issuer.getUniqueId()); .queryReports(issuer.getUniqueId());
if(userReports.status() != 200) { if(userReports.status() != 200) {
@@ -129,43 +131,50 @@ public class Report extends Appliance {
return; return;
} }
List<ReportRepository.PlayerReports.Report> reports = userReports Function<List<ReportRepository.PlayerReports.Report>, List<ReportRepository.PlayerReports.Report>> filterClosed = reports -> reports.stream()
.data() .filter(report -> Objects.equals(report.status(), ReportRepository.PlayerReports.Report.Status.closed))
.from_self() .toList();
.stream()
.filter(report -> !report.draft())
.toList()
.reversed();
if(reports.isEmpty()) { List<ReportRepository.PlayerReports.Report> reportsToOthers = filterClosed.apply(userReports.data().from_self()).reversed();
issuer.sendMessage( List<ReportRepository.PlayerReports.Report> reportsToSelf = filterClosed.apply(userReports.data().to_self()).reversed();
Component.text()
.append(Component.text("Du hast noch niemanden reportet.", NamedTextColor.RED))
.appendNewline()
.append(Component.text("Um jemanden zu melden, nutze /report", NamedTextColor.GRAY))
);
return;
}
ComponentBuilder<TextComponent, TextComponent.Builder> component = Component.text() ComponentBuilder<TextComponent, TextComponent.Builder> component = Component.text()
.append(Component.newline()) .append(Component.text(
.append(Component.text("Von dir erstellte Reports: ", NamedTextColor.GOLD)) !reportsToSelf.isEmpty()
.appendNewline(); ? "Du wurdest insgesamt %d mal von anderen Spielern gemeldet.".formatted(reportsToSelf.size())
: "Du wurdest von keinem anderen Spieler gemeldet.",
NamedTextColor.GOLD)
);
reports.forEach(report -> {
component
.append(Component.text(" - ", NamedTextColor.WHITE))
.append(
report.reported() != null
? Component.text(report.reported().username(), NamedTextColor.WHITE)
: Component.text("Unbekannt", NamedTextColor.YELLOW)
)
.append(Component.text(String.format(": %s", report.subject()), NamedTextColor.GRAY))
.clickEvent(ClickEvent.openUrl(report.url()))
.hoverEvent(HoverEvent.showText(Component.text("Klicke, um den Report einzusehen.", NamedTextColor.GOLD)));
component.appendNewline(); component.appendNewline();
component.append(Component.text("Von dir erstellte Reports: ", NamedTextColor.GOLD));
reportsToOthers.forEach(report -> {
Component button = Component.text("[\uD83D\uDC41/\uD83D\uDD8A]")
.clickEvent(ClickEvent.openUrl(report.url()))
.hoverEvent(HoverEvent.showText(ComponentUtil.clickLink(report.url())));
Component reportedDisplayName = report.reported() != null
? Component.text(Optional.ofNullable(Bukkit.getOfflinePlayer(report.reported()).getName()).orElse(report.reported().toString()), NamedTextColor.WHITE)
: Component.text("Unbekannt", NamedTextColor.YELLOW);
component
.appendNewline()
.append(Component.text(" \u27A1 ", NamedTextColor.GRAY))
.append(button)
.append(Component.text(" du gegen ", NamedTextColor.GRAY))
.append(reportedDisplayName)
.append(Component.text(String.format(": %s", report.reason()), NamedTextColor.GRAY));
}); });
if(reportsToOthers.isEmpty()) {
component
.appendNewline()
.append(Component.text("Du hast noch niemanden reportet.", NamedTextColor.RED))
.appendNewline()
.append(Component.text("Um jemanden zu melden, nutze /report", NamedTextColor.GRAY));
}
issuer.sendMessage(component.build()); issuer.sendMessage(component.build());
} }

View File

@@ -0,0 +1,66 @@
package eu.mhsl.craftattack.spawn.common.appliances.security.antiFormattedBook;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import net.kyori.adventure.text.*;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.event.Listener;
import org.bukkit.inventory.meta.BookMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Objects;
public class AntiFormattedBook extends Appliance {
private static final char SECTION = '\u00A7';
public boolean containsFormatting(BookMeta meta) {
if (this.hasFormattingDeep(meta.title())) return true;
if (this.hasFormattingDeep(meta.author())) return true;
for (Component c : meta.pages()) {
if (this.hasFormattingDeep(c)) return true;
}
return false;
}
private boolean hasFormattingDeep(@Nullable Component component) {
if(component == null) return false;
if (this.hastFormatting(component)) return true;
if (component instanceof TextComponent tc && tc.content().indexOf(SECTION) >= 0) return true;
if (component instanceof NBTComponent<?, ?> nbt) {
if (nbt.separator() != null && this.hasFormattingDeep(nbt.separator())) return true;
}
for (Component child : component.children()) {
if (this.hasFormattingDeep(child)) return true;
}
return false;
}
private boolean hastFormatting(Component component) {
Style style = component.style();
TextColor color = style.color();
if (color != null) return true;
if (style.font() != null) return true;
if (style.insertion() != null && !Objects.requireNonNull(style.insertion()).isEmpty()) return true;
for (var decoration : style.decorations().entrySet()) {
if (decoration.getValue() == TextDecoration.State.TRUE) return true;
}
return style.hoverEvent() != null || style.clickEvent() != null;
}
@Override
protected @NotNull List<Listener> listeners() {
return List.of(
new BookEditListener()
);
}
}

View File

@@ -0,0 +1,36 @@
package eu.mhsl.craftattack.spawn.common.appliances.security.antiFormattedBook;
import eu.mhsl.craftattack.spawn.common.appliances.tooling.acInform.AcInform;
import eu.mhsl.craftattack.spawn.core.Main;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import net.kyori.adventure.text.Component;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerEditBookEvent;
import org.bukkit.inventory.meta.BookMeta;
import java.util.List;
class BookEditListener extends ApplianceListener<AntiFormattedBook> {
@EventHandler
public void onBookEdit(PlayerEditBookEvent event) {
Player player = event.getPlayer();
BookMeta meta = event.getNewBookMeta();
if (this.getAppliance().containsFormatting(meta)) {
Main.instance().getAppliance(AcInform.class).notifyAdmins(
"internal",
player.getName(),
"illegalBookFormatting",
1f
);
BookMeta sanitized = meta.clone();
sanitized.title(null);
sanitized.author(null);
//noinspection ResultOfMethodCallIgnored
sanitized.pages(List.of(Component.empty()));
event.setNewBookMeta(sanitized);
}
}
}

View File

@@ -0,0 +1,78 @@
package eu.mhsl.craftattack.spawn.common.appliances.security.antiIllegalBundlePicker;
import eu.mhsl.craftattack.spawn.common.appliances.tooling.acInform.AcInform;
import eu.mhsl.craftattack.spawn.core.Main;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BundleMeta;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.stream.Collectors;
public class AntiIllegalBundlePicker extends Appliance {
private static final int visibleSlotsInBundle = 9;
public void trackBundle(InventoryClickEvent event) {
ItemStack bundle = Objects.requireNonNull(event.getCurrentItem());
final int rawSlot = event.getRawSlot();
final Player player = (Player) event.getWhoClicked();
final InventoryView view = event.getView();
final List<ItemStack> before = this.getBundleContents(bundle);
Bukkit.getScheduler().runTask(Main.instance(), () -> {
ItemStack afterStack = view.getItem(rawSlot);
if(afterStack == null || afterStack.getType() != Material.BUNDLE) return;
List<ItemStack> after = this.getBundleContents(afterStack);
int removedSlotIndex = this.findRemoved(before, after);
if(removedSlotIndex >= visibleSlotsInBundle) {
Main.instance().getAppliance(AcInform.class).notifyAdmins(
"internal",
player.getName(),
"illegalBundlePick",
(float) removedSlotIndex
);
}
});
}
private int findRemoved(@NotNull List<ItemStack> before, @NotNull List<ItemStack> after) {
for (int i = 0; i < Math.max(before.size(), after.size()); i++) {
ItemStack a = i < after.size() ? after.get(i) : null;
ItemStack b = i < before.size() ? before.get(i) : null;
if (b == null && a == null) continue;
if (b == null) throw new IllegalStateException("Size of bundle was smaller before pickup Action");
if (a == null) return i;
if (!a.isSimilar(b)) return i;
if (a.getAmount() != b.getAmount()) return i;
}
throw new IllegalStateException("Failed to find picked Item in bundle");
}
private List<ItemStack> getBundleContents(@NotNull ItemStack bundle) {
if (bundle.getType() != Material.BUNDLE)
throw new IllegalStateException("ItemStack is not a bundle");
BundleMeta meta = (BundleMeta) bundle.getItemMeta();
return meta.getItems().stream()
.map(ItemStack::clone)
.collect(Collectors.toCollection(ArrayList::new));
}
@Override
protected @NotNull List<Listener> listeners() {
return List.of(
new OnBundlePickListener()
);
}
}

View File

@@ -0,0 +1,18 @@
package eu.mhsl.craftattack.spawn.common.appliances.security.antiIllegalBundlePicker;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
class OnBundlePickListener extends ApplianceListener<AntiIllegalBundlePicker> {
@EventHandler
public void onBundlePick(InventoryClickEvent event) {
if(!event.getAction().equals(InventoryAction.PICKUP_FROM_BUNDLE)) return;
final ItemStack bundle = event.getCurrentItem();
if (bundle == null || bundle.getType() != Material.BUNDLE) return;
this.getAppliance().trackBundle(event);
}
}

View File

@@ -1,176 +0,0 @@
package eu.mhsl.craftattack.spawn.common.appliances.tooling.deviceFingerprinting;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import eu.mhsl.craftattack.spawn.core.Main;
import eu.mhsl.craftattack.spawn.core.api.server.HttpServer;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import net.kyori.adventure.resource.ResourcePackInfo;
import net.kyori.adventure.resource.ResourcePackRequest;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
import org.jetbrains.annotations.NotNull;
import spark.Response;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.*;
public class DeviceFingerprinting extends Appliance {
public record PackInfo(@NotNull String url, @NotNull UUID uuid, @NotNull String hash) {
private static final String failingUrl = "http://127.0.0.1:0";
public PackInfo asFailing() {
return new PackInfo(failingUrl, this.uuid, this.hash);
}
}
public enum PackStatus {
UNCACHED,
CACHED,
INVALID;
public static PackStatus fromBukkitStatus(PlayerResourcePackStatusEvent.Status status) {
return switch(status) {
case DISCARDED -> CACHED;
case FAILED_DOWNLOAD -> UNCACHED;
default -> INVALID;
};
}
}
public enum PlayerStatus {
PREPARATION,
TESTING,
FINISHED,
NEW
}
private List<PackInfo> packs;
private final Map<Player, FingerprintData> fingerprints = new WeakHashMap<>();
private final UUID basePackId = UUID.randomUUID();
@Override
public void onEnable() {
this.packs = this.readPacksFromConfig();
}
public void startFingerprinting(Player player) {
this.fingerprints.put(player, FingerprintData.create(player));
Main.logger().info(String.format("Sending base ressource-pack with id '%s' to '%s'%n", this.basePackId, player.getName()));
this.sendPack(player, new PackInfo("http://localhost:8080/api/devicefingerprinting/base.zip", this.basePackId, "3296e8bdd30b4f7cffd11c780a1dc70da2948e71"));
}
public void onPackUpdate(Player player, UUID packId, PlayerResourcePackStatusEvent.Status status) {
if(!this.fingerprints.containsKey(player)) return;
FingerprintData playerFingerprint = this.fingerprints.get(player);
if(!playerFingerprint.isInTestingOrPreparation()) return;
if(packId.equals(this.basePackId)) {
Main.logger().info(String.format("Base pack for '%s' updated: '%s'", player.getName(), status));
if(status != PlayerResourcePackStatusEvent.Status.ACCEPTED) return;
Main.logger().info(String.format("Base pack loaded successfully, sending now all packs to '%s'...", player.getName()));
playerFingerprint.setTesting();
this.packs.forEach(pack -> this.sendPack(player, pack.asFailing()));
return;
}
PackInfo pack = this.packs.stream()
.filter(packInfo -> Objects.equals(packInfo.uuid, packId))
.findAny()
.orElse(null);
if(pack == null) return;
int packIndex = this.packs.indexOf(pack);
List<PackStatus> pendingPacks = playerFingerprint.getPendingPacks();
PackStatus newPackStatus = PackStatus.fromBukkitStatus(status);
if(newPackStatus == PackStatus.INVALID) return;
pendingPacks.set(packIndex, newPackStatus);
playerFingerprint.updateFingerprint();
if(Objects.requireNonNull(playerFingerprint.getStatus()) == PlayerStatus.NEW) {
Main.logger().info(String.format("Sending fingerprint packs to Player '%s', as it is a unseen Player!", player.getName()));
this.sendNewFingerprint(player, Objects.requireNonNull(playerFingerprint.getFingerPrint()));
}
}
private void sendNewFingerprint(Player player, long fingerprintId) {
for (int i = 0; i < this.packs.size(); i++) {
if ((fingerprintId & (1L << i)) != 0) {
PackInfo pack = this.packs.get(i);
this.sendPack(player, pack);
}
}
}
public void sendPack(Player player, PackInfo pack) {
player.sendResourcePacks(
ResourcePackRequest.resourcePackRequest()
.required(true)
.packs(ResourcePackInfo.resourcePackInfo(pack.uuid, URI.create(pack.url), pack.hash))
);
}
private List<DeviceFingerprinting.PackInfo> readPacksFromConfig() {
try (InputStreamReader reader = new InputStreamReader(Objects.requireNonNull(Main.class.getResourceAsStream("/deviceFingerprinting/packs.json")))) {
Type packListType = new TypeToken<List<DeviceFingerprinting.PackInfo>>(){}.getType();
List<DeviceFingerprinting.PackInfo> packs = new Gson().fromJson(reader, packListType);
if (packs.isEmpty()) throw new IllegalStateException("No resource packs found in packs.json.");
return packs;
} catch (IOException e) {
throw new IllegalStateException("Failed to parse packs.json.", e);
}
}
@Override
public void httpApi(HttpServer.ApiBuilder apiBuilder) {
apiBuilder.rawGet(
"base.zip",
(request, response) -> this.servePack("base.zip", response)
);
for(int i = 0; i < this.packs.size(); i++) {
int packIndex = i;
apiBuilder.rawGet(
String.format("packs/%d", i),
(request, response) -> this.servePack(String.valueOf(packIndex), response)
);
}
}
private Object servePack(String name, Response response) {
try {
String resourcePath = String.format("/deviceFingerprinting/packs/%s", name);
var inputStream = Main.class.getResourceAsStream(resourcePath);
if (inputStream == null) {
throw new IllegalStateException("Pack file not found: " + resourcePath);
}
response.header("Content-Type", "application/zip");
response.header("Content-Disposition", String.format("attachment; filename=\"pack-%s.zip\"", name));
var outputStream = response.raw().getOutputStream();
inputStream.transferTo(outputStream);
outputStream.close();
return HttpServer.nothing;
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to serve pack '%s'", name), e);
}
}
public List<PackInfo> getPacks() {
return this.packs;
}
@Override
protected @NotNull List<Listener> listeners() {
return List.of(
new PlayerJoinListener()
);
}
}

View File

@@ -1,91 +0,0 @@
package eu.mhsl.craftattack.spawn.common.appliances.tooling.deviceFingerprinting;
import eu.mhsl.craftattack.spawn.core.Main;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
class FingerprintData {
public final Player player;
private DeviceFingerprinting.PlayerStatus status;
private @Nullable Long fingerPrint;
private final List<DeviceFingerprinting.PackStatus> pendingPacks;
int packCount = Main.instance().getAppliance(DeviceFingerprinting.class).getPacks().size();
private FingerprintData(Player player) {
this.player = player;
this.status = DeviceFingerprinting.PlayerStatus.PREPARATION;
this.fingerPrint = null;
this.pendingPacks = Arrays.asList(new DeviceFingerprinting.PackStatus[this.packCount]);
}
public static FingerprintData create(Player player) {
return new FingerprintData(player);
}
public void setTesting() {
this.status = DeviceFingerprinting.PlayerStatus.TESTING;
}
public void updateFingerprint() {
long fingerPrint = 0;
for (int i = 0; i < this.pendingPacks.size(); i++) {
var status = this.pendingPacks.get(i);
if(status == null) return;
switch (status) {
case CACHED:
fingerPrint |= 1L << i;
break;
case UNCACHED:
break;
default:
return;
}
}
if(fingerPrint == 0) {
this.status = DeviceFingerprinting.PlayerStatus.NEW;
this.fingerPrint = this.createNewFingerprint();
Main.logger().info(String.format("Player %s's was marked as a new Player!", this.player.getName()));
} else {
this.status = DeviceFingerprinting.PlayerStatus.FINISHED;
this.fingerPrint = fingerPrint;
}
Main.logger().info(String.format("Player %s's fingerprint is '%s'", this.player.getName(), fingerPrint));
}
private long createNewFingerprint() {
long id = 0;
Random random = new Random();
for (int i = 0; i < this.packCount / 2; i++) {
while (true) {
int bitIndex = random.nextInt(this.packCount);
if ((id & (1L << bitIndex)) == 0) {
id |= 1L << bitIndex;
break;
}
}
}
return id;
}
public List<DeviceFingerprinting.PackStatus> getPendingPacks() {
return this.pendingPacks;
}
public DeviceFingerprinting.PlayerStatus getStatus() {
return this.status;
}
public @Nullable Long getFingerPrint() {
return this.fingerPrint;
}
public boolean isInTestingOrPreparation() {
return this.status == DeviceFingerprinting.PlayerStatus.TESTING || this.status == DeviceFingerprinting.PlayerStatus.PREPARATION;
}
}

View File

@@ -1,22 +0,0 @@
package eu.mhsl.craftattack.spawn.common.appliances.tooling.deviceFingerprinting;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
class PlayerJoinListener extends ApplianceListener<DeviceFingerprinting> {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
this.getAppliance().startFingerprinting(event.getPlayer());
}
@EventHandler
public void onResourcePackEvent(PlayerResourcePackStatusEvent event) {
this.getAppliance().onPackUpdate(
event.getPlayer(),
event.getID(),
event.getStatus()
);
}
}

View File

@@ -9,6 +9,7 @@ import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
class PlayerLimiterListener extends ApplianceListener<PlayerLimit> { class PlayerLimiterListener extends ApplianceListener<PlayerLimit> {
@EventHandler @EventHandler
public void onLogin(AsyncPlayerPreLoginEvent playerPreLoginEvent) { public void onLogin(AsyncPlayerPreLoginEvent playerPreLoginEvent) {
if(Bukkit.getOnlinePlayers().size() >= this.getAppliance().getLimit()) {
playerPreLoginEvent.kickMessage( playerPreLoginEvent.kickMessage(
new DisconnectInfo( new DisconnectInfo(
"Hohe Serverauslastung", "Hohe Serverauslastung",
@@ -17,8 +18,7 @@ class PlayerLimiterListener extends ApplianceListener<PlayerLimit> {
playerPreLoginEvent.getUniqueId() playerPreLoginEvent.getUniqueId()
).getComponent() ).getComponent()
); );
if(Bukkit.getOnlinePlayers().size() >= this.getAppliance().getLimit())
playerPreLoginEvent.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_FULL); playerPreLoginEvent.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_FULL);
} }
} }
}

View File

@@ -1,5 +0,0 @@
## Files originally from "TrackPack"
https://github.com/ALaggyDev/TrackPack/blob/main/README.md
Discovered by: [Laggy](https://github.com/ALaggyDev/) and [NikOverflow](https://github.com/NikOverflow)

View File

@@ -1,33 +0,0 @@
import zipfile
import hashlib
import uuid
import json
SERVER_URL = "http://localhost:8080/api/devicefingerprinting"
packs = []
def file_sha1(path):
h = hashlib.sha1()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
for i in range(0, 24):
path = f"packs/{i}"
with zipfile.ZipFile(path, mode="w") as zf:
zf.writestr(
"pack.mcmeta",
'{"pack":{"pack_format":22,"supported_formats":[22,1000],"description":"pack ' + str(i) + '"}}',
)
hash = file_sha1(path)
packs.append({
"url": f"{SERVER_URL}/packs/{i}",
"uuid": str(uuid.uuid4()),
"hash": hash
})
with open("packs.json", "w") as f:
json.dump(packs, f, indent=4)

View File

@@ -1,122 +0,0 @@
[
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/0",
"uuid": "b35f6e2f-1b50-4493-85be-fb18bd90f9bb",
"hash": "7a39af839ea6484431f7b707759546bea991d435"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/1",
"uuid": "71095b62-d5ef-4ab2-ba3b-3c1b403f5e34",
"hash": "a9192ee73df1c5cff2c188fac6e9e638a1e7b6ce"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/2",
"uuid": "a4dba0a2-f8f2-4a81-bbb2-a9a818820330",
"hash": "6b85b0eb54865dae70bbda89746d83717dc2a214"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/3",
"uuid": "79fa2dc4-8c84-45fc-a09f-d89906f0d900",
"hash": "c7abf7a316f7e8c98985e8317a8b649e824e9f79"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/4",
"uuid": "15702c9b-a22b-426d-b48a-3d65b0368e9a",
"hash": "10cd0e2c46f192deb87ac75c149827d44a713017"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/5",
"uuid": "3d702d41-8e2f-4920-8dd0-1fd2146da9fb",
"hash": "8ad517d259e800b88a38ff00ee6721d5656822f2"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/6",
"uuid": "c20a2e47-ef43-49da-a80d-adf238df3695",
"hash": "798677405a4fd678892e1cf55585c8c91f82e1e2"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/7",
"uuid": "7ce51b81-1263-4919-9f4e-bb749ffe6e2e",
"hash": "af473b8eb7572f35d307bede5f2e20f263c0d804"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/8",
"uuid": "0c70d586-fe48-4ffc-86b0-6b9ec3bfe045",
"hash": "2fb698ff88f2436637641f3b2e6792201feb5144"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/9",
"uuid": "c7af75a8-0b72-495d-a0ff-c1c40e229c13",
"hash": "cf660460798eecf451d639873cc1fedc4661db1b"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/10",
"uuid": "248dbce6-4b2a-44b5-b038-8d718b0ced99",
"hash": "a8ebe708d0f3747c76e4e5e68db5dcb561922706"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/11",
"uuid": "10979174-cb02-40eb-a754-275551ad608d",
"hash": "54961b48db1582a1a0981c8cc9be5ae0f3122cf3"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/12",
"uuid": "a361cfa7-674c-4493-a4cf-4baff851f276",
"hash": "013719dc8da79c96b45a1c5319c20bffe1a56cc9"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/13",
"uuid": "24b39bdb-ada9-40ec-9e3a-132c74b81dc6",
"hash": "206898c6b6600d2648b2d79c61fc6255b19587d9"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/14",
"uuid": "158fc5b4-be2c-4f7a-98cb-af5993adcc90",
"hash": "061b266a7c526fb3a3152a4ea70ca5592e0b503c"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/15",
"uuid": "4f9097a7-be02-48ad-919c-f292307f8490",
"hash": "45a667a0fe06246defabca14ef1271fb6db5a1ac"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/16",
"uuid": "3ce31e60-7e8a-4fb1-8c6d-da9065bea798",
"hash": "75bb12e46203d49e89aa9a826d267552372758bc"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/17",
"uuid": "cd978e5c-3de0-4ada-8ec5-3a88a305eec6",
"hash": "5b20261f7be03e83e9c52307f1408b0c5e58358c"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/18",
"uuid": "75001e58-3999-4779-a1d1-43ab161770ce",
"hash": "544420cffb6c17113c06fb49eeba892c208719d3"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/19",
"uuid": "6a7005a9-c2ca-476d-9a12-07d120ee121a",
"hash": "fcc066a4d3193b60b102e3d906ad8dc0b0fcf65b"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/20",
"uuid": "521c0d84-d82e-49ef-b096-d9b90f15aa19",
"hash": "4545835983ec7f07d02675a69181a80dc396f038"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/21",
"uuid": "c1b590c5-43fc-41e3-83c0-47f35b14f845",
"hash": "8d4c670eaefc0482734e839b72758226dde13bc3"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/22",
"uuid": "43958a18-c087-4f2b-a6ea-066231606eb1",
"hash": "004282602f7bdbb7cd7724f23aae23876f224092"
},
{
"url": "http://localhost:8080/api/devicefingerprinting/packs/23",
"uuid": "4b91ac81-9de4-4c2b-a876-47e621496d10",
"hash": "dae68eae109e08ea4c4c943905502eb331939f64"
}
]

View File

@@ -1 +0,0 @@
!base.zip

View File

@@ -7,7 +7,6 @@ import org.bukkit.configuration.ConfigurationSection;
import spark.Request; import spark.Request;
import spark.Spark; import spark.Spark;
import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
@@ -44,16 +43,12 @@ public class HttpServer {
this.applianceName = appliance.getClass().getSimpleName().toLowerCase(); this.applianceName = appliance.getClass().getSimpleName().toLowerCase();
} }
public void rawGet(String path, BiFunction<Request, spark.Response, Object> onCall) {
Spark.get(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req, resp)));
}
public void get(String path, Function<Request, Object> onCall) { public void get(String path, Function<Request, Object> onCall) {
Spark.get(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req))); Spark.get(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req)));
} }
public void rawPost(String path, BiFunction<Request, spark.Response, Object> onCall) { public void rawPost(String path, Function<Request, Object> onCall) {
Spark.post(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req, resp))); Spark.post(this.buildRoute(path), (req, resp) -> this.process(() -> onCall.apply(req)));
} }
public <TRequest> void post(String path, Class<TRequest> clazz, RequestProvider<TRequest, Request, Object> onCall) { public <TRequest> void post(String path, Class<TRequest> clazz, RequestProvider<TRequest, Request, Object> onCall) {

View File

@@ -5,6 +5,7 @@ import eu.mhsl.craftattack.spawn.core.util.statistics.ServerMonitor;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentBuilder; import net.kyori.adventure.text.ComponentBuilder;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@@ -19,7 +20,12 @@ import java.util.stream.Stream;
public class ComponentUtil { public class ComponentUtil {
public static TextComponent pleaseWait() { public static TextComponent pleaseWait() {
return Component.text("Bitte warte einen Augenblick...", NamedTextColor.GRAY); return Component.text("\uD83D\uDCBE Daten werden geladen... Warte einen Augenblick!", NamedTextColor.GRAY);
}
public static TextComponent clickLink(String url) {
return Component.text("Klicke, um zu öffnen: \uD83D\uDD17[%s]".formatted(url))
.clickEvent(ClickEvent.openUrl(url));
} }
public static Component clearedSpace() { public static Component clearedSpace() {

View File

@@ -1,28 +1,26 @@
package eu.mhsl.craftattack.spawn.craftattack.api.repositories; package eu.mhsl.craftattack.spawn.craftattack.api.repositories;
import com.google.common.reflect.TypeToken;
import eu.mhsl.craftattack.spawn.core.api.client.HttpRepository; import eu.mhsl.craftattack.spawn.core.api.client.HttpRepository;
import eu.mhsl.craftattack.spawn.core.api.client.ReqResp; import eu.mhsl.craftattack.spawn.core.api.client.ReqResp;
import eu.mhsl.craftattack.spawn.common.api.CraftAttackApi; import eu.mhsl.craftattack.spawn.common.api.CraftAttackApi;
import java.lang.reflect.Type;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
public class FeedbackRepository extends HttpRepository { public class FeedbackRepository extends HttpRepository {
public FeedbackRepository() { public FeedbackRepository() {
super(CraftAttackApi.getBaseUri(), new RequestModifier(CraftAttackApi::withAuthorizationSecret, null)); super(CraftAttackApi.getBaseUri(), new RequestModifier(null, CraftAttackApi::withAuthorizationHeader));
} }
public record Request(String event, List<UUID> users) { public record Request(String event, String title, List<UUID> users) {
} }
public ReqResp<Map<UUID, String>> createFeedbackUrls(Request data) { public record Response(List<Feedback> feedback) {
final Type responseType = new TypeToken<Map<UUID, String>>() { public record Feedback(UUID uuid, String url) {
}.getType(); }
ReqResp<Object> rawData = this.post("feedback", data, Object.class); }
// TODO: use convertToTypeToken from ReqResp
return new ReqResp<>(rawData.status(), this.gson.fromJson(this.gson.toJson(rawData.data()), responseType)); public ReqResp<Response> createFeedbackUrls(Request data) {
return this.post("feedback", data, Response.class);
} }
} }

View File

@@ -4,11 +4,12 @@ import eu.mhsl.craftattack.spawn.core.api.client.HttpRepository;
import eu.mhsl.craftattack.spawn.core.api.client.ReqResp; import eu.mhsl.craftattack.spawn.core.api.client.ReqResp;
import eu.mhsl.craftattack.spawn.common.api.CraftAttackApi; import eu.mhsl.craftattack.spawn.common.api.CraftAttackApi;
import java.util.List;
import java.util.UUID; import java.util.UUID;
public class WhitelistRepository extends HttpRepository { public class WhitelistRepository extends HttpRepository {
public WhitelistRepository() { public WhitelistRepository() {
super(CraftAttackApi.getBaseUri(), new RequestModifier(CraftAttackApi::withAuthorizationSecret, null)); super(CraftAttackApi.getBaseUri(), new RequestModifier(null, CraftAttackApi::withAuthorizationHeader));
} }
public record UserData( public record UserData(
@@ -16,15 +17,15 @@ public class WhitelistRepository extends HttpRepository {
String username, String username,
String firstname, String firstname,
String lastname, String lastname,
Long banned_until, List<Strike> strikes
Long outlawed_until
) { ) {
public record Strike(int at, int weight) {
}
} }
public ReqResp<UserData> getUserData(UUID userId) { public ReqResp<UserData> getUserData(UUID userId) {
return this.get( return this.get(
"user", "users/%s".formatted(userId.toString()),
parameters -> parameters.addParameter("uuid", userId.toString()),
UserData.class UserData.class
); );
} }

View File

@@ -0,0 +1,113 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.gameplay.ironGolemAnimation;
import eu.mhsl.craftattack.spawn.core.Main;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Directional;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
public class IronGolemAnimation extends Appliance {
record BlockChange(Block original, BlockData fakeBlock) {}
public void onGolemSpawn(IronGolem golem) {
this.modifyGolem(golem, false);
Location golemLocation = golem.getLocation();
BlockData bodyBlockData = Bukkit.createBlockData(Material.IRON_BLOCK);
BlockData headBlockData = Bukkit.createBlockData(
Material.CARVED_PUMPKIN,
blockData -> ((Directional) blockData).setFacing(golem.getFacing())
);
Vector facingVector = golem.getFacing().getDirection().rotateAroundY(Math.toRadians(90));
Block golemCenterBlock = golemLocation.getBlock().getRelative(BlockFace.UP);
List<BlockChange> buildBlocks = List.of(
new BlockChange(golemCenterBlock.getRelative(BlockFace.DOWN), bodyBlockData),
new BlockChange(golemCenterBlock, bodyBlockData),
new BlockChange(golemCenterBlock.getLocation().add(facingVector).getBlock(), bodyBlockData),
new BlockChange(golemCenterBlock.getLocation().add(facingVector.multiply(-1)).getBlock(), bodyBlockData),
new BlockChange(golemCenterBlock.getRelative(BlockFace.UP), headBlockData)
);
Collection<Player> viewers = golemLocation.getNearbyPlayers(golemLocation.getWorld().getViewDistance() * 16);
BiConsumer<Location, BlockData> changeBlockForViewers = (location, blockData) -> {
viewers.forEach(player -> player.sendBlockChange(location, blockData));
golem.getWorld().playSound(
location,
blockData.getSoundGroup().getPlaceSound(),
SoundCategory.BLOCKS,
1f,
1f
);
};
for(int i = 0; i < buildBlocks.size(); i++) {
BlockChange blockChange = buildBlocks.get(i);
Bukkit.getScheduler().runTaskLater(
Main.instance(),
() -> changeBlockForViewers.accept(blockChange.original.getLocation(), blockChange.fakeBlock),
6L * i
);
}
Consumer<List<BlockChange>> restoreBlockChanges = (blocks) -> {
buildBlocks.forEach((blockChange) -> changeBlockForViewers.accept(
blockChange.original().getLocation(),
blockChange.original.getBlockData()
));
this.modifyGolem(golem, true);
this.spawnEffect(buildBlocks);
};
Bukkit.getScheduler().runTaskLater(
Main.instance(),
() -> restoreBlockChanges.accept(buildBlocks),
6L * buildBlocks.size() + 2
);
}
private void spawnEffect(List<BlockChange> buildBlocks) {
buildBlocks.forEach((blockChange) -> {
World world = blockChange.original.getLocation().getWorld();
world.spawnParticle(
Particle.BLOCK,
blockChange.original.getLocation().add(0.5, 0.5, 0.5),
50,
blockChange.fakeBlock
);
world.playSound(
blockChange.original.getLocation(),
blockChange.fakeBlock.getSoundGroup().getBreakSound(),
SoundCategory.BLOCKS,
1f,
1f
);
});
}
public void modifyGolem(IronGolem golem, boolean setVisible) {
golem.setInvisible(!setVisible);
golem.setInvulnerable(!setVisible);
golem.setAI(setVisible);
golem.setGravity(setVisible);
golem.setCollidable(setVisible);
}
@Override
protected @NotNull List<Listener> listeners() {
return List.of(
new NaturalIronGolemSpawnEvent()
);
}
}

View File

@@ -0,0 +1,15 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.gameplay.ironGolemAnimation;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import org.bukkit.entity.IronGolem;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.CreatureSpawnEvent;
class NaturalIronGolemSpawnEvent extends ApplianceListener<IronGolemAnimation> {
@EventHandler
public void onGolemSpawn(CreatureSpawnEvent event) {
if(!(event.getEntity() instanceof IronGolem golem)) return;
if(event.getSpawnReason() != CreatureSpawnEvent.SpawnReason.VILLAGE_DEFENSE) return;
this.getAppliance().onGolemSpawn(golem);
}
}

View File

@@ -0,0 +1,32 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.gameplay.recoveryCompass;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import java.util.Objects;
class KeepRecoveryCompassOnDeathListener extends ApplianceListener<RecoveryCompass> {
@EventHandler
public void onDeath(PlayerDeathEvent event) {
ItemStack source = event.getDrops().stream()
.filter(Objects::nonNull)
.filter(item -> item.getType() == Material.RECOVERY_COMPASS)
.findFirst()
.orElse(null);
if (source == null) return;
if (source.getAmount() > 1) {
source.setAmount(source.getAmount() - 1);
} else {
event.getDrops().remove(source);
}
ItemStack kept = source.clone();
kept.setAmount(1);
event.getItemsToKeep().add(kept);
}
}

View File

@@ -0,0 +1,24 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.gameplay.recoveryCompass;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
class PlayerFirstJoinCompassGift extends ApplianceListener<RecoveryCompass> {
private final NamespacedKey alreadyGiftedKey = new NamespacedKey(this.getClass().getSimpleName().toLowerCase(), "alreadyGifted".toLowerCase());
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
PersistentDataContainer container = player.getPersistentDataContainer();
if(container.has(alreadyGiftedKey)) return;
player.getInventory().addItem(ItemStack.of(Material.RECOVERY_COMPASS));
container.set(alreadyGiftedKey, PersistentDataType.BOOLEAN, true);
}
}

View File

@@ -0,0 +1,17 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.gameplay.recoveryCompass;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class RecoveryCompass extends Appliance {
@Override
protected @NotNull List<Listener> listeners() {
return List.of(
new PlayerFirstJoinCompassGift(),
new KeepRecoveryCompassOnDeathListener()
);
}
}

View File

@@ -1,7 +1,7 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.metaGameplay.feedback; package eu.mhsl.craftattack.spawn.craftattack.appliances.metaGameplay.feedback;
import eu.mhsl.craftattack.spawn.core.Main;
import eu.mhsl.craftattack.spawn.core.api.client.ReqResp; import eu.mhsl.craftattack.spawn.core.api.client.ReqResp;
import eu.mhsl.craftattack.spawn.core.util.text.ComponentUtil;
import eu.mhsl.craftattack.spawn.craftattack.api.repositories.FeedbackRepository; import eu.mhsl.craftattack.spawn.craftattack.api.repositories.FeedbackRepository;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance; import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceCommand; import eu.mhsl.craftattack.spawn.core.appliance.ApplianceCommand;
@@ -9,7 +9,6 @@ import eu.mhsl.craftattack.spawn.core.api.HttpStatus;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentBuilder; import net.kyori.adventure.text.ComponentBuilder;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent; import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
@@ -18,32 +17,27 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.UUID;
public class Feedback extends Appliance { public class Feedback extends Appliance {
public Feedback() { public Feedback() {
super("feedback"); super("feedback");
} }
public void requestFeedback(String eventName, List<Player> receivers, @Nullable String question) { public void requestFeedback(String eventName, String title, List<Player> receivers, @Nullable String question) {
ReqResp<Map<UUID, String>> response = this.queryRepository(FeedbackRepository.class).createFeedbackUrls( ReqResp<FeedbackRepository.Response> response = this.queryRepository(FeedbackRepository.class).createFeedbackUrls(
new FeedbackRepository.Request(eventName, receivers.stream().map(Entity::getUniqueId).toList()) new FeedbackRepository.Request(eventName, title, receivers.stream().map(Entity::getUniqueId).toList())
); );
System.out.println(response.toString()); if(response.status() != HttpStatus.OK) throw new RuntimeException();
System.out.println(response.status());
if(response.status() != HttpStatus.CREATED) throw new RuntimeException();
Component border = Component.text("-".repeat(40), NamedTextColor.GRAY); Component border = Component.text("-".repeat(40), NamedTextColor.GRAY);
receivers.forEach(player -> { receivers.forEach(player -> {
String feedbackUrl = response.data().get(player.getUniqueId()); String feedbackUrl = response.data().feedback().stream()
if(feedbackUrl == null) { .filter(feedback -> feedback.uuid().equals(player.getUniqueId()))
Main.logger().warning(String.format("FeedbackUrl not found for player '%s' from backend!", player.getUniqueId())); .findFirst()
return; .orElseThrow()
} .url();
ComponentBuilder<TextComponent, TextComponent.Builder> message = Component.text() ComponentBuilder<TextComponent, TextComponent.Builder> message = Component.text()
.append(border) .append(border)
@@ -58,8 +52,7 @@ public class Feedback extends Appliance {
message message
.append(Component.text("Klicke hier und gib uns Feedback, damit wir dein Spielerlebnis verbessern können!", NamedTextColor.DARK_GREEN) .append(Component.text("Klicke hier und gib uns Feedback, damit wir dein Spielerlebnis verbessern können!", NamedTextColor.DARK_GREEN)
.clickEvent(ClickEvent.openUrl(feedbackUrl))) .hoverEvent(HoverEvent.showText(ComponentUtil.clickLink(feedbackUrl))))
.hoverEvent(HoverEvent.showText(Component.text("Klicke, um Feedback zu geben.")))
.appendNewline() .appendNewline()
.append(border); .append(border);

View File

@@ -22,6 +22,7 @@ class FeedbackCommand extends ApplianceCommand.PlayerChecked<Feedback> {
Main.instance(), Main.instance(),
() -> this.getAppliance().requestFeedback( () -> this.getAppliance().requestFeedback(
"self-issued-ingame", "self-issued-ingame",
"Dein Feedback an uns",
List.of(this.getPlayer()), List.of(this.getPlayer()),
null null
) )

View File

@@ -20,6 +20,7 @@ class RequestFeedbackCommand extends ApplianceCommand<Feedback> {
Main.instance(), Main.instance(),
() -> this.getAppliance().requestFeedback( () -> this.getAppliance().requestFeedback(
"admin-issued-ingame", "admin-issued-ingame",
"Hilf uns dein Spielerlebnis zu verbessern!",
new ArrayList<>(Bukkit.getOnlinePlayers()), String.join(" ", args) new ArrayList<>(Bukkit.getOnlinePlayers()), String.join(" ", args)
) )
); );

View File

@@ -0,0 +1,21 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.tooling.strike;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import java.time.Duration;
import java.util.Map;
public class Strike extends Appliance {
public Strike() {
super("strike");
}
private final Map<Integer, Duration> strikePunishmentMap = Map.of(
1, Duration.ofHours(1),
2, Duration.ofHours(24),
3, Duration.ofDays(3),
4, Duration.ofDays(7)
);
}

View File

@@ -47,7 +47,7 @@ public class Whitelist extends Appliance {
player.getUniqueId() player.getUniqueId()
); );
} }
this.queryAppliance(Outlawed.class).updateForcedStatus(player, this.timestampRelevant(user.outlawed_until())); this.queryAppliance(Outlawed.class).updateForcedStatus(player, this.timestampRelevant(0L)); // TODO
String purePlayerName = Floodgate.isBedrock(player) String purePlayerName = Floodgate.isBedrock(player)
? Floodgate.getBedrockPlayer(player).getUsername() ? Floodgate.getBedrockPlayer(player).getUsername()
@@ -67,14 +67,14 @@ public class Whitelist extends Appliance {
Main.instance().getLogger().info(String.format("Running integrityCheck for %s", name)); Main.instance().getLogger().info(String.format("Running integrityCheck for %s", name));
boolean overrideCheck = this.localConfig().getBoolean("overrideIntegrityCheck", false); boolean overrideCheck = this.localConfig().getBoolean("overrideIntegrityCheck", false);
WhitelistRepository.UserData user = overrideCheck WhitelistRepository.UserData user = overrideCheck
? new WhitelistRepository.UserData(uuid, name, "", "", 0L, 0L) ? new WhitelistRepository.UserData(uuid, name, "", "", List.of())
: this.fetchUserData(uuid); : this.fetchUserData(uuid);
this.userData.put(uuid, user); this.userData.put(uuid, user);
Main.logger().info(String.format("got userdata %s", user.toString())); Main.logger().info(String.format("got userdata %s", user.toString()));
if(this.timestampRelevant(user.banned_until())) { if(this.timestampRelevant(0L)) { //TODO
Instant bannedDate = new Date(user.banned_until() * 1000L) Instant bannedDate = new Date(0 * 1000L) // TODO
.toInstant() .toInstant()
.plus(1, ChronoUnit.HOURS); .plus(1, ChronoUnit.HOURS);
@@ -118,7 +118,7 @@ public class Whitelist extends Appliance {
); );
if(response.status() != HttpStatus.OK) if(response.status() != HttpStatus.OK)
throw new IllegalStateException(String.format("Http Reponse %d", response.status())); throw new IllegalStateException(String.format("Unwanted response %d!", response.status()));
return response.data(); return response.data();
} }

View File

@@ -0,0 +1,16 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.tweaks.phantomReducer;
import eu.mhsl.craftattack.spawn.core.appliance.Appliance;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class PhantomReducer extends Appliance {
@Override
protected @NotNull List<Listener> listeners() {
return List.of(
new PhantomSpawnListener()
);
}
}

View File

@@ -0,0 +1,16 @@
package eu.mhsl.craftattack.spawn.craftattack.appliances.tweaks.phantomReducer;
import eu.mhsl.craftattack.spawn.core.appliance.ApplianceListener;
import org.bukkit.entity.Phantom;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.CreatureSpawnEvent;
import java.util.concurrent.ThreadLocalRandom;
class PhantomSpawnListener extends ApplianceListener<PhantomReducer> {
@EventHandler
public void onPhantomSpawn(CreatureSpawnEvent event) {
if(!(event.getEntity() instanceof Phantom)) return;
if(ThreadLocalRandom.current().nextDouble() > 0.8) event.setCancelled(true);
}
}

24
local.gradle.example Normal file
View File

@@ -0,0 +1,24 @@
tasks.register('deployVaroPlugin', Copy) {
dependsOn ":varo:shadowJar"
from { project(":varo").shadowJar.archivePath }
into file('path') // path to plugins folder
rename { fileName -> "varo.jar" }
}
tasks.register("uploadVaroPlugin") {
dependsOn(":varo:shadowJar")
doLast {
def jarFile = project(":varo").tasks.named("shadowJar").get().outputs.files.singleFile
exec {
commandLine "scp", "-4", "-P", "22", jarFile.absolutePath, "user@host:path/varo.jar"
}
}
}
tasks.register('deployCraftAttackPlugin', Copy) {
dependsOn ":craftattack:shadowJar"
from { project(":craftattack").shadowJar.archivePath }
into file('path') // path to plugins folder
rename { fileName -> "craftattack.jar" }
}

View File

@@ -1,49 +0,0 @@
package eu.mhsl.craftattack.spawn.appliances.tooling.antiGrief;
import eu.mhsl.craftattack.spawn.appliance.Appliance;
import eu.mhsl.craftattack.spawn.appliances.tooling.antiGrief.player.PlayerGriefListener;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.BlockDisplay;
import org.bukkit.entity.ItemDisplay;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Transformation;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class AntiGrief extends Appliance {
private final Map<Block, UUID> blockRegistry = new HashMap<>();
public void addTracking(Block block, UUID player) {
this.blockRegistry.put(block, player);
block.getLocation().getWorld().spawn(block.getLocation(), ItemDisplay.class, itemDisplay -> {
itemDisplay.setItemStack(ItemStack.of(Material.FIRE_CHARGE));
itemDisplay.teleport(block.getLocation().add(0.5, 0.5, 0.5));
});
}
public @Nullable UUID getTracked(Block block) {
return this.blockRegistry.get(block);
}
public void addDestroyed(Block block, UUID player) {
block.getLocation().getWorld().spawn(block.getLocation().add(0.5, 0.5, 0.5), BlockDisplay.class, blockDisplay -> {
blockDisplay.setBlock(Material.GOLD_BLOCK.createBlockData());
Transformation transformation = blockDisplay.getTransformation();
transformation.getScale().set(0.3);
blockDisplay.setTransformation(transformation);
});
}
@Override
protected @NotNull List<Listener> listeners() {
return List.of(new PlayerGriefListener());
}
}

View File

@@ -1,51 +0,0 @@
package eu.mhsl.craftattack.spawn.appliances.tooling.antiGrief.player;
import eu.mhsl.craftattack.spawn.appliance.ApplianceListener;
import eu.mhsl.craftattack.spawn.appliances.tooling.antiGrief.AntiGrief;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import java.util.UUID;
public class PlayerGriefListener extends ApplianceListener<AntiGrief> {
@EventHandler
public void onIgnite(BlockIgniteEvent event) {
Bukkit.broadcast(Component.text(event.getCause().toString()));
switch(event.getCause()) {
case LAVA:
case SPREAD:
case EXPLOSION:
if(event.getIgnitingBlock() == null) return;
UUID ignitedBy = this.getAppliance().getTracked(event.getIgnitingBlock());
this.getAppliance().addTracking(event.getBlock(), ignitedBy);
break;
case FLINT_AND_STEEL:
case ENDER_CRYSTAL:
case ARROW:
case FIREBALL:
if(event.getPlayer() == null) return;
this.getAppliance().addTracking(event.getBlock(), event.getPlayer().getUniqueId());
break;
}
}
@EventHandler
public void onSpread(BlockSpreadEvent event) {
if(!event.getBlock().getType().equals(Material.FIRE)) return;
UUID ignitedBy = this.getAppliance().getTracked(event.getBlock());
this.getAppliance().addTracking(event.getBlock(), ignitedBy);
}
@EventHandler
public void onDestroy(BlockBurnEvent event) {
UUID ignitedBy = this.getAppliance().getTracked(event.getIgnitingBlock());
if(ignitedBy == null) return;
this.getAppliance().addDestroyed(event.getBlock(), ignitedBy);
}
}