Merge pull request 'Format code' (#370) from Format into main

Reviewed-on: SteamWar/SteamWar#370
Reviewed-by: Chaoscaot <max@chaoscaot.de>
This commit is contained in:
2026-05-17 10:59:30 +02:00
574 changed files with 11473 additions and 10504 deletions
@@ -76,13 +76,21 @@ public class AttributesCopyCommand extends SWCommand {
if (itemStack.getType() == Material.ZOMBIE_HEAD && block.getType() == Material.ZOMBIE_WALL_HEAD) return true; if (itemStack.getType() == Material.ZOMBIE_HEAD && block.getType() == Material.ZOMBIE_WALL_HEAD) return true;
if (itemStack.getType() == Material.CREEPER_HEAD && block.getType() == Material.CREEPER_WALL_HEAD) return true; if (itemStack.getType() == Material.CREEPER_HEAD && block.getType() == Material.CREEPER_WALL_HEAD) return true;
if (itemStack.getType() == Material.DRAGON_HEAD && block.getType() == Material.DRAGON_WALL_HEAD) return true; if (itemStack.getType() == Material.DRAGON_HEAD && block.getType() == Material.DRAGON_WALL_HEAD) return true;
if (itemStack.getType() == Material.SKELETON_SKULL && block.getType() == Material.SKELETON_WALL_SKULL) return true; if (itemStack.getType() == Material.SKELETON_SKULL && block.getType() == Material.SKELETON_WALL_SKULL) {
if (itemStack.getType() == Material.WITHER_SKELETON_SKULL && block.getType() == Material.WITHER_SKELETON_WALL_SKULL) return true; return true;
}
if (itemStack.getType() == Material.WITHER_SKELETON_SKULL && block.getType() == Material.WITHER_SKELETON_WALL_SKULL) {
return true;
}
if (itemStack.getType() == Material.TORCH && block.getType() == Material.WALL_TORCH) return true; if (itemStack.getType() == Material.TORCH && block.getType() == Material.WALL_TORCH) return true;
if (itemStack.getType() == Material.SOUL_TORCH && block.getType() == Material.SOUL_WALL_TORCH) return true; if (itemStack.getType() == Material.SOUL_TORCH && block.getType() == Material.SOUL_WALL_TORCH) return true;
if (itemStack.getType() == Material.REDSTONE_TORCH && block.getType() == Material.REDSTONE_WALL_TORCH) return true; if (itemStack.getType() == Material.REDSTONE_TORCH && block.getType() == Material.REDSTONE_WALL_TORCH) {
return true;
}
if (itemStack.getType() == Material.WHEAT_SEEDS && block.getType() == Material.WHEAT) return true; if (itemStack.getType() == Material.WHEAT_SEEDS && block.getType() == Material.WHEAT) return true;
if (itemStack.getType().name().contains("_BANNER") && block.getType().name().contains("_WALL_BANNER")) return true; if (itemStack.getType().name().contains("_BANNER") && block.getType().name().contains("_WALL_BANNER")) {
return true;
}
return false; return false;
} }
} }
@@ -104,7 +104,8 @@ public class BackupCommand extends SWCommand {
List<String> lore = Arrays.asList(BauSystem.MESSAGE.parse("BACKUP_LORE", p)); List<String> lore = Arrays.asList(BauSystem.MESSAGE.parse("BACKUP_LORE", p));
for (int i = 0; i < backups.size(); i++) { for (int i = 0; i < backups.size(); i++) {
RegionBackups.Backup backup = backups.get(i); RegionBackups.Backup backup = backups.get(i);
SWItem swItem = new SWItem(Material.BRICK, BauSystem.MESSAGE.parse("BACKUP_ITEM_NAME", p, backup.getName()), lore, false, clickType -> {}); SWItem swItem = new SWItem(Material.BRICK, BauSystem.MESSAGE.parse("BACKUP_ITEM_NAME", p, backup.getName()), lore, false, clickType -> {
});
swItem.getItemStack().setAmount(i + 1); swItem.getItemStack().setAmount(i + 1);
swListEntries.add(new SWListInv.SWListEntry<>(swItem, backup)); swListEntries.add(new SWListInv.SWListEntry<>(swItem, backup));
} }
@@ -50,7 +50,8 @@ public class InventoryFillBauGuiItem extends BauGuiItem {
@Override @Override
public ItemStack getItem(Player player) { public ItemStack getItem(Player player) {
String loreKey = Config.getInstance().get(player).getPlainValueOrDefault("inventoryfill", false) ? "OTHER_ITEMS_INVENTORY_FILL_LORE_ACTIVE" : "OTHER_ITEMS_INVENTORY_FILL_LORE_INACTIVE"; String loreKey = Config.getInstance().get(player).getPlainValueOrDefault("inventoryfill", false) ? "OTHER_ITEMS_INVENTORY_FILL_LORE_ACTIVE" : "OTHER_ITEMS_INVENTORY_FILL_LORE_INACTIVE";
return new SWItem(Material.HOPPER, BauSystem.MESSAGE.parse("OTHER_ITEMS_INVENTORY_FILL_NAME", player), Collections.singletonList(BauSystem.MESSAGE.parse(loreKey, player)), false, clickType -> {}).getItemStack(); return new SWItem(Material.HOPPER, BauSystem.MESSAGE.parse("OTHER_ITEMS_INVENTORY_FILL_NAME", player), Collections.singletonList(BauSystem.MESSAGE.parse(loreKey, player)), false, clickType -> {
}).getItemStack();
} }
@Override @Override
@@ -104,7 +104,9 @@ public class KillcheckerVisualizer {
Block block = WORLD.getBlockAt(x, y, z); Block block = WORLD.getBlockAt(x, y, z);
if (block.getType().isAir()) continue; if (block.getType().isAir()) continue;
String name = block.getType().name(); String name = block.getType().name();
if (!name.endsWith("_WOOL") && !name.endsWith("_STAINED_GLASS") && !name.endsWith("_CONCRETE") && !name.endsWith("_TERRACOTTA")) continue; if (!name.endsWith("_WOOL") && !name.endsWith("_STAINED_GLASS") && !name.endsWith("_CONCRETE") && !name.endsWith("_TERRACOTTA")) {
continue;
}
if (name.equals("_GLAZED_TERRACOTTA")) continue; if (name.equals("_GLAZED_TERRACOTTA")) continue;
Cuboid cuboid = create(block.getType(), x, y, z); Cuboid cuboid = create(block.getType(), x, y, z);
cuboids.add(cuboid); cuboids.add(cuboid);
@@ -283,7 +285,9 @@ public class KillcheckerVisualizer {
} }
kill.forEach((point, count) -> { kill.forEach((point, count) -> {
if (rEntities.containsKey(point)) { if (rEntities.containsKey(point)) {
if (killCount.get(point) == count && outlinePoints.contains(point) == outlinePointsCacheLast.contains(point)) return; if (killCount.get(point) == count && outlinePoints.contains(point) == outlinePointsCacheLast.contains(point)) {
return;
}
rEntities.get(point).die(); rEntities.get(point).die();
} }
RFallingBlockEntity entity = new RFallingBlockEntity(outlinePoints.contains(point) ? outline : inner, point.toLocation(WORLD, 0.5, 0, 0.5), MATERIALS[Math.min(count - 1, MATERIALS.length) - 1]); RFallingBlockEntity entity = new RFallingBlockEntity(outlinePoints.contains(point) ? outline : inner, point.toLocation(WORLD, 0.5, 0, 0.5), MATERIALS[Math.min(count - 1, MATERIALS.length) - 1]);
@@ -213,7 +213,8 @@ public class Loader implements Listener, SWPlayer.Component {
}; };
updateRunnable.run(); updateRunnable.run();
SWListInv<LoaderElement> swListInv = new SWListInv<>(p, BauSystem.MESSAGE.parse("LOADER_GUI_TITLE", p), false, list, (clickType, loaderElement) -> {}); SWListInv<LoaderElement> swListInv = new SWListInv<>(p, BauSystem.MESSAGE.parse("LOADER_GUI_TITLE", p), false, list, (clickType, loaderElement) -> {
});
swListInv.setCallback((clickType, entry) -> entry.click(p, () -> { swListInv.setCallback((clickType, entry) -> entry.click(p, () -> {
updateRunnable.run(); updateRunnable.run();
swListInv.open(); swListInv.open();
@@ -363,7 +364,9 @@ public class Loader implements Listener, SWPlayer.Component {
public static int LENGTH = SettingsSorting.values().length; public static int LENGTH = SettingsSorting.values().length;
public abstract Material getMaterial(); public abstract Material getMaterial();
public abstract String getName(); public abstract String getName();
public abstract boolean shouldShow(LoaderElement previous, LoaderElement current, LoaderElement next); public abstract boolean shouldShow(LoaderElement previous, LoaderElement current, LoaderElement next);
} }
@@ -26,6 +26,8 @@ import java.util.function.Consumer;
public interface LoaderElement { public interface LoaderElement {
SWItem menu(Player player); SWItem menu(Player player);
void execute(Consumer<Long> delay); void execute(Consumer<Long> delay);
void click(Player player, Runnable backAction); void click(Player player, Runnable backAction);
} }
@@ -95,7 +95,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
}; };
updateRunnable.run(); updateRunnable.run();
SWListInv<Integer> listInv = new SWListInv<>(player, "Interaction Settings", false, entries, (clickType, entry) -> {}); SWListInv<Integer> listInv = new SWListInv<>(player, "Interaction Settings", false, entries, (clickType, entry) -> {
});
listInv.setCallback((clickType, entry) -> { listInv.setCallback((clickType, entry) -> {
openIndividualSettingsMenu(player, entry, () -> { openIndividualSettingsMenu(player, entry, () -> {
updateRunnable.run(); updateRunnable.run();
@@ -150,7 +151,10 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
} }
SWInventory swInventory = new SWInventory(player, guiSize, BauSystem.MESSAGE.parse("LOADER_GUI_SETTINGS_TITLE", player)); SWInventory swInventory = new SWInventory(player, guiSize, BauSystem.MESSAGE.parse("LOADER_GUI_SETTINGS_TITLE", player));
for (int i = guiSize - 9; i < guiSize; i++) swInventory.setItem(i, new SWItem(Material.GRAY_STAINED_GLASS_PANE, "§7", clickType -> {})); for (int i = guiSize - 9; i < guiSize; i++) {
swInventory.setItem(i, new SWItem(Material.GRAY_STAINED_GLASS_PANE, "§7", clickType -> {
}));
}
swInventory.setItem(guiSize - 9, new SWItem(Material.ARROW, BauSystem.MESSAGE.parse("LOADER_GUI_SETTINGS_BACK", player)).setCustomModelData(CMDs.BACK).getItemStack(), clickType -> back.run()); swInventory.setItem(guiSize - 9, new SWItem(Material.ARROW, BauSystem.MESSAGE.parse("LOADER_GUI_SETTINGS_BACK", player)).setCustomModelData(CMDs.BACK).getItemStack(), clickType -> back.run());
swInventory.setItem(guiSize - 5, new SWItem(Material.WOODEN_AXE, BauSystem.MESSAGE.parse("LOADER_GUI_SETTINGS_COPY", player)).getItemStack(), clickType -> { swInventory.setItem(guiSize - 5, new SWItem(Material.WOODEN_AXE, BauSystem.MESSAGE.parse("LOADER_GUI_SETTINGS_COPY", player)).getItemStack(), clickType -> {
SWAnvilInv swAnvilInv = new SWAnvilInv(player, BauSystem.MESSAGE.parse("LOADER_GUI_COPY_TITLE", player), "1"); SWAnvilInv swAnvilInv = new SWAnvilInv(player, BauSystem.MESSAGE.parse("LOADER_GUI_COPY_TITLE", player), "1");
@@ -197,7 +201,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
for (int power = 0; power < 16; power++) { for (int power = 0; power < 16; power++) {
int finalPowerPosition = power; int finalPowerPosition = power;
if (power >= 9) finalPowerPosition++; if (power >= 9) finalPowerPosition++;
SWItem powerItem = new SWItem(Material.REDSTONE, BauSystem.MESSAGE.parse("LOADER_SETTING_POWER", player, power), Arrays.asList(), false, clickType -> {}); SWItem powerItem = new SWItem(Material.REDSTONE, BauSystem.MESSAGE.parse("LOADER_SETTING_POWER", player, power), Arrays.asList(), false, clickType -> {
});
powerItem.getItemStack().setAmount(Math.max(power, 1)); powerItem.getItemStack().setAmount(Math.max(power, 1));
if (extraPower.get(index) == power) powerItem.setEnchanted(true); if (extraPower.get(index) == power) powerItem.setEnchanted(true);
@@ -210,7 +215,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
} }
if (currentElement.hasTicks(this)) { if (currentElement.hasTicks(this)) {
swInventory.setItem(ticksStart + 3, new SWItem(Material.RED_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE_SHIFT", player)), false, clickType -> {}).getItemStack(), clickType -> { swInventory.setItem(ticksStart + 3, new SWItem(Material.RED_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE_SHIFT", player)), false, clickType -> {
}).getItemStack(), clickType -> {
long ticks = extraTicks.get(index); long ticks = extraTicks.get(index);
ticks -= clickType.isShiftClick() ? 5 : 1; ticks -= clickType.isShiftClick() ? 5 : 1;
if (ticks < 1) ticks = 1; if (ticks < 1) ticks = 1;
@@ -218,7 +224,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
openIndividualSettingsMenu(player, index, back, delete); openIndividualSettingsMenu(player, index, back, delete);
}); });
SWItem ticksItem = new SWItem(Material.CLOCK, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS", player, extraTicks.get(index)), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_GUI_CLICK_TO_EDIT", player)), false, clickType -> {}); SWItem ticksItem = new SWItem(Material.CLOCK, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS", player, extraTicks.get(index)), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_GUI_CLICK_TO_EDIT", player)), false, clickType -> {
});
ticksItem.getItemStack().setAmount((int) Math.min(extraTicks.get(index), 64)); ticksItem.getItemStack().setAmount((int) Math.min(extraTicks.get(index), 64));
swInventory.setItem(ticksStart + 4, ticksItem.getItemStack(), clickType -> { swInventory.setItem(ticksStart + 4, ticksItem.getItemStack(), clickType -> {
SWAnvilInv swAnvilInv = new SWAnvilInv(player, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_NAME", player), extraTicks.get(index) + ""); SWAnvilInv swAnvilInv = new SWAnvilInv(player, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_NAME", player), extraTicks.get(index) + "");
@@ -234,7 +241,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
swAnvilInv.open(); swAnvilInv.open();
}); });
swInventory.setItem(ticksStart + 5, new SWItem(Material.LIME_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE_SHIFT", player)), false, clickType -> {}).getItemStack(), clickType -> { swInventory.setItem(ticksStart + 5, new SWItem(Material.LIME_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE_SHIFT", player)), false, clickType -> {
}).getItemStack(), clickType -> {
long ticks = extraTicks.get(index); long ticks = extraTicks.get(index);
ticks += clickType.isShiftClick() ? 5 : 1; ticks += clickType.isShiftClick() ? 5 : 1;
extraTicks.set(index, ticks); extraTicks.set(index, ticks);
@@ -28,10 +28,13 @@ import java.util.function.Consumer;
public interface LoaderSettingsEnum<T, P extends LoaderInteractionElement<E>, E extends Enum<E> & LoaderSettingsEnum<T, P, E>> { public interface LoaderSettingsEnum<T, P extends LoaderInteractionElement<E>, E extends Enum<E> & LoaderSettingsEnum<T, P, E>> {
int getPos(); int getPos();
SWItem menu(Player player, P parent, int power, long ticks); SWItem menu(Player player, P parent, int power, long ticks);
default boolean hasPower(P parent) { default boolean hasPower(P parent) {
return false; return false;
} }
default boolean hasTicks(P parent) { default boolean hasTicks(P parent) {
return false; return false;
} }
@@ -63,7 +63,8 @@ public class LoaderWait implements LoaderElement {
for (int i = 9; i < 18; i++) swInventory.setItem(i, new SWItem(Material.GRAY_STAINED_GLASS_PANE, "§7")); for (int i = 9; i < 18; i++) swInventory.setItem(i, new SWItem(Material.GRAY_STAINED_GLASS_PANE, "§7"));
swInventory.setItem(9, new SWItem(Material.ARROW, BauSystem.MESSAGE.parse("LOADER_GUI_WAIT_BACK", player)).setCustomModelData(CMDs.BACK).getItemStack(), clickType -> backAction.run()); swInventory.setItem(9, new SWItem(Material.ARROW, BauSystem.MESSAGE.parse("LOADER_GUI_WAIT_BACK", player)).setCustomModelData(CMDs.BACK).getItemStack(), clickType -> backAction.run());
swInventory.setItem(3, new SWItem(Material.RED_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE_SHIFT", player)), false, clickType -> {}).getItemStack(), clickType -> { swInventory.setItem(3, new SWItem(Material.RED_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_REMOVE_ONE_SHIFT", player)), false, clickType -> {
}).getItemStack(), clickType -> {
delay -= clickType.isShiftClick() ? 5 : 1; delay -= clickType.isShiftClick() ? 5 : 1;
if (delay < 0) delay = 0; if (delay < 0) delay = 0;
swInventory.setItem(4, menu(player)); swInventory.setItem(4, menu(player));
@@ -80,7 +81,8 @@ public class LoaderWait implements LoaderElement {
}); });
swAnvilInv.open(); swAnvilInv.open();
}); });
swInventory.setItem(5, new SWItem(Material.LIME_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE_SHIFT", player)), false, clickType -> {}).getItemStack(), clickType -> { swInventory.setItem(5, new SWItem(Material.LIME_DYE, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE", player), Arrays.asList(BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_ADD_ONE_SHIFT", player)), false, clickType -> {
}).getItemStack(), clickType -> {
delay += clickType.isShiftClick() ? 5 : 1; delay += clickType.isShiftClick() ? 5 : 1;
swInventory.setItem(4, menu(player)); swInventory.setItem(4, menu(player));
}); });
@@ -146,8 +146,7 @@ public class Loadtimer implements Listener {
if ((stage == Stage.COUNTING || stage == Stage.ACTIVATED)) { if ((stage == Stage.COUNTING || stage == Stage.ACTIVATED)) {
stage = Stage.IGNITION; stage = Stage.IGNITION;
ignite = TPSUtils.currentRealTick.get(); ignite = TPSUtils.currentRealTick.get();
if (activate == -1) if (activate == -1) activate = TPSUtils.currentRealTick.get();
activate = TPSUtils.currentRealTick.get();
if (finishOnActive) { if (finishOnActive) {
stage = Stage.END; stage = Stage.END;
print(); print();
@@ -184,8 +183,7 @@ public class Loadtimer implements Listener {
long ignTime = ignite - activate; long ignTime = ignite - activate;
long explTime = explode - ignTime - activate; long explTime = explode - ignTime - activate;
if (explTime < 0) if (explTime < 0) explTime = loadTime;
explTime = loadTime;
int finalAllTnt = allTnt; int finalAllTnt = allTnt;
long finalExplTime = explTime; long finalExplTime = explTime;
@@ -40,17 +40,19 @@ public class LoadtimerCommand extends SWCommand {
public void start(@Validator Player p, TimerMode mode) { public void start(@Validator Player p, TimerMode mode) {
Region r = Region.getRegion(p.getLocation()); Region r = Region.getRegion(p.getLocation());
if (r.getType().isGlobal()) return; if (r.getType().isGlobal()) return;
if (!Loadtimer.hasTimer(r)) if (!Loadtimer.hasTimer(r)) {
Loadtimer.createLoadtimer(r, mode == TimerMode.HALF); Loadtimer.createLoadtimer(r, mode == TimerMode.HALF);
} }
}
@Register(value = "stop", description = "LOADTIMER_HELP_STOP") @Register(value = "stop", description = "LOADTIMER_HELP_STOP")
public void stop(@Validator Player p) { public void stop(@Validator Player p) {
Region r = Region.getRegion(p.getLocation()); Region r = Region.getRegion(p.getLocation());
if (r.getType().isGlobal()) return; if (r.getType().isGlobal()) return;
if (Loadtimer.hasTimer(r)) if (Loadtimer.hasTimer(r)) {
Loadtimer.getTimer(r).delete(); Loadtimer.getTimer(r).delete();
} }
}
public enum TimerMode { public enum TimerMode {
FULL, FULL,
@@ -46,8 +46,9 @@ public class LoadtimerGuiItem extends BauGuiItem {
@Override @Override
public ItemStack getItem(Player player) { public ItemStack getItem(Player player) {
Region r = Region.getRegion(player.getLocation()); Region r = Region.getRegion(player.getLocation());
if (r.getType().isGlobal()) if (r.getType().isGlobal()) {
return new SWItem(Material.BOWL, BauSystem.MESSAGE.parse("LOADTIMER_GUI_GLOBAL", player)).getItemStack(); return new SWItem(Material.BOWL, BauSystem.MESSAGE.parse("LOADTIMER_GUI_GLOBAL", player)).getItemStack();
}
if (Loadtimer.hasTimer(r)) { if (Loadtimer.hasTimer(r)) {
return new SWItem(Material.BOW, BauSystem.MESSAGE.parse("LOADTIMER_GUI_STOP", player)).getItemStack(); return new SWItem(Material.BOW, BauSystem.MESSAGE.parse("LOADTIMER_GUI_STOP", player)).getItemStack();
} else { } else {
@@ -36,12 +36,16 @@ public class FireListener implements Listener, ScoreboardElement {
@EventHandler @EventHandler
public void onFireDamage(BlockBurnEvent e) { public void onFireDamage(BlockBurnEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FIRE).isWithDefault(FireMode.DENY)) e.setCancelled(true); if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FIRE).isWithDefault(FireMode.DENY)) {
e.setCancelled(true);
}
} }
@EventHandler @EventHandler
public void onFireSpread(BlockSpreadEvent e) { public void onFireSpread(BlockSpreadEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FIRE).isWithDefault(FireMode.DENY)) e.setCancelled(true); if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FIRE).isWithDefault(FireMode.DENY)) {
e.setCancelled(true);
}
} }
@Override @Override
@@ -47,7 +47,9 @@ public class FreezeListener implements Listener, ScoreboardElement {
@EventHandler @EventHandler
public void onBlockExplode(BlockExplodeEvent e) { public void onBlockExplode(BlockExplodeEvent e) {
if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) return; if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) {
return;
}
e.setCancelled(true); e.setCancelled(true);
BlockState state = e.getBlock().getState(); BlockState state = e.getBlock().getState();
Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> { Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
@@ -57,7 +59,9 @@ public class FreezeListener implements Listener, ScoreboardElement {
@EventHandler @EventHandler
public void onEntitySpawn(EntitySpawnEvent e) { public void onEntitySpawn(EntitySpawnEvent e) {
if (Region.getRegion(e.getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) return; if (Region.getRegion(e.getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) {
return;
}
e.setCancelled(true); e.setCancelled(true);
if (e.getEntityType() == EntityType.TNT) { if (e.getEntityType() == EntityType.TNT) {
Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> { Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
@@ -69,7 +73,9 @@ public class FreezeListener implements Listener, ScoreboardElement {
@EventHandler @EventHandler
public void onBlockCanBuild(BlockCanBuildEvent e) { public void onBlockCanBuild(BlockCanBuildEvent e) {
if (!e.isBuildable()) return; if (!e.isBuildable()) return;
if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) return; if (Region.getRegion(e.getBlock().getLocation()).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.INACTIVE)) {
return;
}
if (e.getMaterial() == Material.TNT) { if (e.getMaterial() == Material.TNT) {
e.setBuildable(false); e.setBuildable(false);
e.getBlock().setType(Material.TNT, false); e.getBlock().setType(Material.TNT, false);
@@ -59,7 +59,9 @@ public class RegionListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockPhysics(final BlockPhysicsEvent event) { public void onBlockPhysics(final BlockPhysicsEvent event) {
if (event.getBlock().getType() != event.getChangedType()) RegionListener.tagChangedRegion(event.getBlock().getLocation()); if (event.getBlock().getType() != event.getChangedType()) {
RegionListener.tagChangedRegion(event.getBlock().getLocation());
}
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@@ -36,7 +36,9 @@ public class WaterDestroyListener implements Listener, ScoreboardElement {
@EventHandler @EventHandler
public void onBlockFromTo(BlockFromToEvent event) { public void onBlockFromTo(BlockFromToEvent event) {
if (event.getBlock().getType() == Material.WATER && event.getToBlock().getType() != Material.AIR && Region.getRegion(event.getBlock().getLocation()).getRegionData().get(Flag.WATER_DESTROY).isWithDefault(WaterDestroyMode.DENY)) event.setCancelled(true); if (event.getBlock().getType() == Material.WATER && event.getToBlock().getType() != Material.AIR && Region.getRegion(event.getBlock().getLocation()).getRegionData().get(Flag.WATER_DESTROY).isWithDefault(WaterDestroyMode.DENY)) {
event.setCancelled(true);
}
} }
@Override @Override
@@ -75,7 +75,8 @@ public class ScriptGUI implements Listener {
lore.add(BauSystem.MESSAGE.parse("SCRIPT_MENU_GUI_ITEM_LORE_3", player)); lore.add(BauSystem.MESSAGE.parse("SCRIPT_MENU_GUI_ITEM_LORE_3", player));
lore.add(BauSystem.MESSAGE.parse("SCRIPT_MENU_GUI_ITEM_LORE_4", player)); lore.add(BauSystem.MESSAGE.parse("SCRIPT_MENU_GUI_ITEM_LORE_4", player));
entries.add(new SWListInv.SWListEntry<>(new SWItem(Material.ENCHANTED_BOOK, script.getName(), new ArrayList<>(lore), false, clickType -> {}), script)); entries.add(new SWListInv.SWListEntry<>(new SWItem(Material.ENCHANTED_BOOK, script.getName(), new ArrayList<>(lore), false, clickType -> {
}), script));
lore.clear(); lore.clear();
}); });
@@ -82,7 +82,9 @@ public interface LuaLib {
default Class<? extends LuaLib> parent() { default Class<? extends LuaLib> parent() {
return null; return null;
} }
String name(); String name();
LuaTable get(Player player); LuaTable get(Player player);
@AllArgsConstructor @AllArgsConstructor
@@ -103,27 +105,33 @@ public interface LuaLib {
try { try {
consumer.accept(luaValue.toboolean()); consumer.accept(luaValue.toboolean());
return NIL; return NIL;
} catch (Exception ingored) {} } catch (Exception ingored) {
}
try { try {
consumer.accept((long) luaValue.toint()); consumer.accept((long) luaValue.toint());
return NIL; return NIL;
} catch (Exception ignored) {} } catch (Exception ignored) {
}
try { try {
consumer.accept(luaValue.toint()); consumer.accept(luaValue.toint());
return NIL; return NIL;
} catch (Exception ignored) {} } catch (Exception ignored) {
}
try { try {
consumer.accept(luaValue.todouble()); consumer.accept(luaValue.todouble());
return NIL; return NIL;
} catch (Exception ignored) {} } catch (Exception ignored) {
}
try { try {
consumer.accept((float) luaValue.todouble()); consumer.accept((float) luaValue.todouble());
return NIL; return NIL;
} catch (Exception ignored) {} } catch (Exception ignored) {
}
try { try {
consumer.accept(luaValue.toString()); consumer.accept(luaValue.toString());
return NIL; return NIL;
} catch (Exception ignored) {} } catch (Exception ignored) {
}
throw new LuaError("Invalid lua type: " + luaValue.typename()); throw new LuaError("Invalid lua type: " + luaValue.typename());
} catch (Throwable throwable) { } catch (Throwable throwable) {
throw new LuaError("Error in '" + name + "' " + throwable.getMessage()); throw new LuaError("Error in '" + name + "' " + throwable.getMessage());
@@ -62,7 +62,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
jsonObject.keySet().forEach(key -> { jsonObject.keySet().forEach(key -> {
GLOBAL_STORAGE.put(key, fromJson(jsonObject.get(key))); GLOBAL_STORAGE.put(key, fromJson(jsonObject.get(key)));
}); });
} catch (Exception e) {} } catch (Exception e) {
}
File regionStorageDirectory = new File(storageDirectory, "region"); File regionStorageDirectory = new File(storageDirectory, "region");
regionStorageDirectory.mkdirs(); regionStorageDirectory.mkdirs();
@@ -75,7 +76,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
}); });
Region region = RegionSystem.INSTANCE.getRegion(UUID.fromString(regionStorage.getName().substring(0, regionStorage.getName().length() - ".json".length()))).orElse(null); Region region = RegionSystem.INSTANCE.getRegion(UUID.fromString(regionStorage.getName().substring(0, regionStorage.getName().length() - ".json".length()))).orElse(null);
REGION_STORAGE.put(region, map); REGION_STORAGE.put(region, map);
} catch (Exception e) {} } catch (Exception e) {
}
} }
File playerStorageDirectory = new File(storageDirectory, "player"); File playerStorageDirectory = new File(storageDirectory, "player");
@@ -89,7 +91,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
}); });
SteamwarUser steamwarUser = SteamwarUser.byId(Integer.parseInt(playerStorage.getName().substring(0, playerStorage.getName().length() - ".json".length()))); SteamwarUser steamwarUser = SteamwarUser.byId(Integer.parseInt(playerStorage.getName().substring(0, playerStorage.getName().length() - ".json".length())));
PLAYER_STORAGE.put(steamwarUser.getUUID(), map); PLAYER_STORAGE.put(steamwarUser.getUUID(), map);
} catch (Exception e) {} } catch (Exception e) {
}
} }
} }
@@ -105,10 +108,12 @@ public class StorageLib implements LuaLib, Enable, Disable {
if (jsonPrimitive.isNumber()) { if (jsonPrimitive.isNumber()) {
try { try {
return LuaValue.valueOf(jsonPrimitive.getAsInt()); return LuaValue.valueOf(jsonPrimitive.getAsInt());
} catch (NumberFormatException e) {} } catch (NumberFormatException e) {
}
try { try {
return LuaValue.valueOf(jsonPrimitive.getAsDouble()); return LuaValue.valueOf(jsonPrimitive.getAsDouble());
} catch (NumberFormatException e) {} } catch (NumberFormatException e) {
}
} }
if (jsonPrimitive.isString()) { if (jsonPrimitive.isString()) {
return LuaValue.valueOf(jsonPrimitive.getAsString()); return LuaValue.valueOf(jsonPrimitive.getAsString());
@@ -135,7 +140,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
FileWriter fileWriter = new FileWriter(new File(storageDirectory, "global.json")); FileWriter fileWriter = new FileWriter(new File(storageDirectory, "global.json"));
gson.toJson(toJson(GLOBAL_STORAGE), fileWriter); gson.toJson(toJson(GLOBAL_STORAGE), fileWriter);
fileWriter.close(); fileWriter.close();
} catch (IOException e) {} } catch (IOException e) {
}
File regionStorageDirectory = new File(storageDirectory, "region"); File regionStorageDirectory = new File(storageDirectory, "region");
regionStorageDirectory.mkdirs(); regionStorageDirectory.mkdirs();
@@ -144,7 +150,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
FileWriter fileWriter = new FileWriter(new File(regionStorageDirectory, entry.getKey().getID().toString() + ".json")); FileWriter fileWriter = new FileWriter(new File(regionStorageDirectory, entry.getKey().getID().toString() + ".json"));
gson.toJson(toJson(entry.getValue()), fileWriter); gson.toJson(toJson(entry.getValue()), fileWriter);
fileWriter.close(); fileWriter.close();
} catch (IOException e) {} } catch (IOException e) {
}
} }
File playerStorageDirectory = new File(storageDirectory, "player"); File playerStorageDirectory = new File(storageDirectory, "player");
@@ -154,7 +161,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
FileWriter fileWriter = new FileWriter(new File(playerStorageDirectory, SteamwarUser.get(entry.getKey()).getId() + ".json")); FileWriter fileWriter = new FileWriter(new File(playerStorageDirectory, SteamwarUser.get(entry.getKey()).getId() + ".json"));
gson.toJson(toJson(entry.getValue()), fileWriter); gson.toJson(toJson(entry.getValue()), fileWriter);
fileWriter.close(); fileWriter.close();
} catch (IOException e) {} } catch (IOException e) {
}
} }
} }
@@ -174,13 +182,16 @@ public class StorageLib implements LuaLib, Enable, Disable {
} }
try { try {
return new JsonPrimitive(luaValue.checkboolean()); return new JsonPrimitive(luaValue.checkboolean());
} catch (Exception e) {} } catch (Exception e) {
}
try { try {
return new JsonPrimitive(luaValue.checkint()); return new JsonPrimitive(luaValue.checkint());
} catch (Exception e) {} } catch (Exception e) {
}
try { try {
return new JsonPrimitive(luaValue.checkdouble()); return new JsonPrimitive(luaValue.checkdouble());
} catch (Exception e) {} } catch (Exception e) {
}
if (luaValue.isstring()) { if (luaValue.isstring()) {
return new JsonPrimitive(luaValue.tojstring()); return new JsonPrimitive(luaValue.tojstring());
@@ -193,7 +204,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
if (value == null) continue; if (value == null) continue;
try { try {
jsonObject.add(key.checkjstring(), value); jsonObject.add(key.checkjstring(), value);
} catch (Exception e) {} } catch (Exception e) {
}
} }
return jsonObject; return jsonObject;
} }
@@ -249,7 +261,9 @@ public class StorageLib implements LuaLib, Enable, Disable {
} }
} }
}; };
}; }
;
}); });
storageLib.set("global", global); storageLib.set("global", global);
@@ -294,7 +308,9 @@ public class StorageLib implements LuaLib, Enable, Disable {
} }
} }
}; };
}; }
;
}); });
storageLib.set("player", playerStorage); storageLib.set("player", playerStorage);
@@ -343,7 +359,9 @@ public class StorageLib implements LuaLib, Enable, Disable {
} }
} }
}; };
}; }
;
}); });
storageLib.set("region", regionStorage); storageLib.set("region", regionStorage);
@@ -26,7 +26,9 @@ import org.bukkit.entity.Player;
public interface BlockDataConfiguration<T extends BlockData> { public interface BlockDataConfiguration<T extends BlockData> {
void previous(); void previous();
void next(); void next();
SWItem get(Player player); SWItem get(Player player);
void apply(T copied, T worldOriginal); void apply(T copied, T worldOriginal);
@@ -293,8 +293,9 @@ public class SimulatorCursor implements Listener {
if (!player.isSneaking()) { if (!player.isSneaking()) {
pos.setX(pos.getBlockX() + 0.5); pos.setX(pos.getBlockX() + 0.5);
if (face == null || face.getModY() == 0) if (face == null || face.getModY() == 0) {
pos.setY(pos.getBlockY() + 0.0); pos.setY(pos.getBlockY() + 0.0);
}
pos.setZ(pos.getBlockZ() + 0.5); pos.setZ(pos.getBlockZ() + 0.5);
} }
@@ -120,6 +120,10 @@ public abstract class SimulatorElement<T extends SimulatorPhase> {
} }
public abstract String getType(); public abstract String getType();
public void saveExtra(YAPIONObject elementObject) {}
public void loadExtra(YAPIONObject elementObject) {} public void saveExtra(YAPIONObject elementObject) {
}
public void loadExtra(YAPIONObject elementObject) {
}
} }
@@ -37,6 +37,10 @@ public abstract class SimulatorPhase {
protected int order = 0; protected int order = 0;
public abstract void toSimulatorActions(Vector position, BiConsumer<Integer, SimulatorAction> tickStart, BiConsumer<Integer, SimulatorAction> tickEnd); public abstract void toSimulatorActions(Vector position, BiConsumer<Integer, SimulatorAction> tickStart, BiConsumer<Integer, SimulatorAction> tickEnd);
public void saveExtra(YAPIONObject phaseObject) {}
public void loadExtra(YAPIONObject phaseObject) {} public void saveExtra(YAPIONObject phaseObject) {
}
public void loadExtra(YAPIONObject phaseObject) {
}
} }
@@ -65,7 +65,9 @@ public final class TNTPhase extends SimulatorPhase {
@Override @Override
public void accept(World world) { public void accept(World world) {
Location location = position.toLocation(world); Location location = position.toLocation(world);
if (Region.getRegion(location).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) return; if (Region.getRegion(location).getRegionData().get(Flag.FREEZE).isWithDefault(FreezeMode.ACTIVE)) {
return;
}
TNTPrimed tnt = world.spawn(location, TNTPrimed.class); TNTPrimed tnt = world.spawn(location, TNTPrimed.class);
if (!xJump) tnt.setVelocity(tnt.getVelocity().setX(0)); if (!xJump) tnt.setVelocity(tnt.getVelocity().setX(0));
if (!yJump) tnt.setVelocity(tnt.getVelocity().setY(0)); if (!yJump) tnt.setVelocity(tnt.getVelocity().setY(0));
@@ -55,8 +55,9 @@ public class StabGenerator extends StabStep implements Listener {
if (!(event.getEntity() instanceof TNTPrimed)) return; if (!(event.getEntity() instanceof TNTPrimed)) return;
if (Region.getRegion(event.getEntity().getLocation()) == data.region) { if (Region.getRegion(event.getEntity().getLocation()) == data.region) {
event.blockList().forEach(block -> { event.blockList().forEach(block -> {
if (!data.region.getTestblockArea().inRegion(block.getLocation(), true)) if (!data.region.getTestblockArea().inRegion(block.getLocation(), true)) {
return; return;
}
int component = data.direction.component.apply(block.getLocation().toVector()); int component = data.direction.component.apply(block.getLocation().toVector());
destroyedBlocksPerSlice.computeIfAbsent(component, __ -> new HashSet<>()) destroyedBlocksPerSlice.computeIfAbsent(component, __ -> new HashSet<>())
.add(block.getLocation()); .add(block.getLocation());
@@ -33,6 +33,7 @@ import java.util.*;
public class LaufbauSettings { public class LaufbauSettings {
private static Map<Pair<Material, String>, List<BlockBoundingBox>> groupMap = new LinkedHashMap<>(); private static Map<Pair<Material, String>, List<BlockBoundingBox>> groupMap = new LinkedHashMap<>();
static { static {
BlockBoundingBox.elements.forEach(blockBoundingBox -> { BlockBoundingBox.elements.forEach(blockBoundingBox -> {
if (blockBoundingBox.getSwItem() == null) return; if (blockBoundingBox.getSwItem() == null) return;
@@ -115,12 +116,15 @@ public class LaufbauSettings {
} else { } else {
long count = blockBoundingBoxes.stream().filter(bb -> LaufbauUtils.isDeactivated(p, bb)).count(); long count = blockBoundingBoxes.stream().filter(bb -> LaufbauUtils.isDeactivated(p, bb)).count();
if (count == 0) { if (count == 0) {
return new SWItem(material, BauSystem.MESSAGE.parse(group, p), Arrays.asList("", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ACTIVE", p), "", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ADVANCED", p), BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_TOGGLE", p)), false, clickType -> {}); return new SWItem(material, BauSystem.MESSAGE.parse(group, p), Arrays.asList("", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ACTIVE", p), "", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ADVANCED", p), BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_TOGGLE", p)), false, clickType -> {
});
} }
if (count == blockBoundingBoxes.size()) { if (count == blockBoundingBoxes.size()) {
return new SWItem(material, BauSystem.MESSAGE.parse(group, p), Arrays.asList("", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_INACTIVE", p), "", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ADVANCED", p), BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_TOGGLE", p)), false, clickType -> {}); return new SWItem(material, BauSystem.MESSAGE.parse(group, p), Arrays.asList("", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_INACTIVE", p), "", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ADVANCED", p), BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_TOGGLE", p)), false, clickType -> {
});
} }
return new SWItem(material, BauSystem.MESSAGE.parse(group, p), Arrays.asList("", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_MIXED", p, blockBoundingBoxes.size() - count, blockBoundingBoxes.size()), "", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ADVANCED", p), BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_TOGGLE", p)), false, clickType -> {}); return new SWItem(material, BauSystem.MESSAGE.parse(group, p), Arrays.asList("", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_MIXED", p, blockBoundingBoxes.size() - count, blockBoundingBoxes.size()), "", BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_ADVANCED", p), BauSystem.MESSAGE.parse("LAUFBAU_SETTINGS_TOGGLE", p)), false, clickType -> {
});
} }
} }
@@ -87,8 +87,9 @@ public class ProcessingTracesState implements LaufbauState {
TNTPoint current = TNTPoints.remove(0); TNTPoint current = TNTPoints.remove(0);
if (FlatteningWrapper.impl.inWater(world, current.getLocation().toVector())) return; if (FlatteningWrapper.impl.inWater(world, current.getLocation().toVector())) return;
if (!(inRegion(current.getLocation().toVector(), 1) || (current.getPrevious().isPresent() && inRegion(current.getPrevious().get().getLocation().toVector(), 1)))) if (!(inRegion(current.getLocation().toVector(), 1) || (current.getPrevious().isPresent() && inRegion(current.getPrevious().get().getLocation().toVector(), 1)))) {
return; return;
}
Location location = current.getLocation(); Location location = current.getLocation();
if (current.getPrevious().isPresent()) { if (current.getPrevious().isPresent()) {
@@ -40,6 +40,7 @@ import java.util.*;
public class Panzern { public class Panzern {
private static List<PanzernAlgorithm> panzernAlgorithmList = new ArrayList<>(); private static List<PanzernAlgorithm> panzernAlgorithmList = new ArrayList<>();
public static void add(PanzernAlgorithm panzernAlgorithm) { public static void add(PanzernAlgorithm panzernAlgorithm) {
panzernAlgorithmList.add(panzernAlgorithm); panzernAlgorithmList.add(panzernAlgorithm);
} }
@@ -144,8 +144,9 @@ public class Trace {
entityServer = new REntityServer(); entityServer = new REntityServer();
entityServer.addPlayer(player); entityServer.addPlayer(player);
entityServer.setCallback((p, rEntity, entityAction) -> { entityServer.setCallback((p, rEntity, entityAction) -> {
if (entityAction != REntityServer.EntityAction.INTERACT) if (entityAction != REntityServer.EntityAction.INTERACT) {
return; return;
}
if (rEntity instanceof TraceEntity) { if (rEntity instanceof TraceEntity) {
((TraceEntity) rEntity).printIntoChat(p); ((TraceEntity) rEntity).printIntoChat(p);
} }
@@ -167,8 +168,9 @@ public class Trace {
REntityServer newEntityServer = new REntityServer(); REntityServer newEntityServer = new REntityServer();
newEntityServer.addPlayer(k); newEntityServer.addPlayer(k);
newEntityServer.setCallback((p, rEntity, entityAction) -> { newEntityServer.setCallback((p, rEntity, entityAction) -> {
if (entityAction != REntityServer.EntityAction.INTERACT) if (entityAction != REntityServer.EntityAction.INTERACT) {
return; return;
}
if (rEntity instanceof TraceEntity) { if (rEntity instanceof TraceEntity) {
((TraceEntity) rEntity).printIntoChat(p); ((TraceEntity) rEntity).printIntoChat(p);
} }
@@ -46,12 +46,10 @@ public class TraceManager implements Listener {
} }
public void init() { public void init() {
if (!tracesFolder.exists()) if (!tracesFolder.exists()) tracesFolder.mkdir();
tracesFolder.mkdir();
File[] traceFiles = tracesFolder.listFiles(); File[] traceFiles = tracesFolder.listFiles();
if (traceFiles == null) if (traceFiles == null) return;
return;
boolean hasMetaFiles = false; boolean hasMetaFiles = false;
for (File traceFile : traceFiles) { for (File traceFile : traceFiles) {
@@ -152,7 +150,9 @@ public class TraceManager implements Listener {
.map(Map.Entry::getKey) .map(Map.Entry::getKey)
.findFirst() .findFirst()
.orElse(null); .orElse(null);
if (traceId == null) throw new RuntimeException("Trace not found while trying to remove see (c978eb98-b0b2-4009-91d8-acfa34e2831a)"); if (traceId == null) {
throw new RuntimeException("Trace not found while trying to remove see (c978eb98-b0b2-4009-91d8-acfa34e2831a)");
}
traces.remove(traceId); traces.remove(traceId);
trace.hide(); trace.hide();
trace.getRecordsSaveFile().delete(); trace.getRecordsSaveFile().delete();
@@ -70,7 +70,9 @@ public class TraceEntity extends RFallingBlockEntity {
* @param player the player the message should be printed for * @param player the player the message should be printed for
*/ */
public void printIntoChat(Player player) { public void printIntoChat(Player player) {
if (!Config.getInstance().get(player).getOrSetDefault(TNT_CLICK_DETAILS, new YAPIONValue<>(true)).asBoolean().orElse(true)) return; if (!Config.getInstance().get(player).getOrSetDefault(TNT_CLICK_DETAILS, new YAPIONValue<>(true)).asBoolean().orElse(true)) {
return;
}
TNTPoint representative = records.get(0); TNTPoint representative = records.get(0);
BauSystem.MESSAGE.sendPrefixless("TNT_CLICK_HEADER", player); BauSystem.MESSAGE.sendPrefixless("TNT_CLICK_HEADER", player);
@@ -102,8 +102,7 @@ public abstract class ViewFlag {
} }
} }
if (!hasMicromotion) if (!hasMicromotion) toRemove.add(uniqueRecord);
toRemove.add(uniqueRecord);
seen.add(uniqueRecord.getTntId()); seen.add(uniqueRecord.getTntId());
} }
@@ -104,6 +104,7 @@ public class MaterialCommand extends SWCommand implements Listener {
} }
private static final Map<String, BiConsumer<SearchParameter, SearchType>> elements = new HashMap<>(); private static final Map<String, BiConsumer<SearchParameter, SearchType>> elements = new HashMap<>();
static { static {
elements.put("-transparent", (search, searchType) -> search.transparent = searchType); elements.put("-transparent", (search, searchType) -> search.transparent = searchType);
elements.put("-solid", (search, searchType) -> search.solid = searchType); elements.put("-solid", (search, searchType) -> search.solid = searchType);
@@ -282,8 +282,9 @@ public class PistonCalculator implements Listener {
immovableBlocks.add(block.getLocation()); immovableBlocks.add(block.getLocation());
return; return;
} }
if (facing != direction && (block.equals(origin) || block.getRelative(facing.getOppositeFace()).equals(origin))) if (facing != direction && (block.equals(origin) || block.getRelative(facing.getOppositeFace()).equals(origin))) {
return; return;
}
if (!movedBlocks.contains(block.getLocation())) toCalc.add(block); if (!movedBlocks.contains(block.getLocation())) toCalc.add(block);
} }
} }
@@ -60,7 +60,9 @@ public class TNTClickListener extends SWCommand implements Listener {
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (!Permission.BUILD.hasPermission(event.getPlayer())) return; if (!Permission.BUILD.hasPermission(event.getPlayer())) return;
if (event.getHand() != EquipmentSlot.HAND) return; if (event.getHand() != EquipmentSlot.HAND) return;
if (!Config.getInstance().get(event.getPlayer()).getOrSetDefault(TNT_CLICK_DETAILS, new YAPIONValue<>(true)).asBoolean().orElse(true)) return; if (!Config.getInstance().get(event.getPlayer()).getOrSetDefault(TNT_CLICK_DETAILS, new YAPIONValue<>(true)).asBoolean().orElse(true)) {
return;
}
Entity entity = event.getRightClicked(); Entity entity = event.getRightClicked();
if (event.getRightClicked() instanceof TNTPrimed) { if (event.getRightClicked() instanceof TNTPrimed) {
@@ -41,7 +41,8 @@ public class GamemodeBauGuiItem extends BauGuiItem {
@Override @Override
public ItemStack getItem(Player player) { public ItemStack getItem(Player player) {
return new SWItem(Material.BARRIER, BauSystem.MESSAGE.parse("OTHER_ITEMS_GAMEMODE_NAME", player), Arrays.asList(BauSystem.MESSAGE.parse("OTHER_ITEMS_GAMEMODE_LORE_1", player), BauSystem.MESSAGE.parse("OTHER_ITEMS_GAMEMODE_LORE_2", player)), false, clickType -> {}).getItemStack(); return new SWItem(Material.BARRIER, BauSystem.MESSAGE.parse("OTHER_ITEMS_GAMEMODE_NAME", player), Arrays.asList(BauSystem.MESSAGE.parse("OTHER_ITEMS_GAMEMODE_LORE_1", player), BauSystem.MESSAGE.parse("OTHER_ITEMS_GAMEMODE_LORE_2", player)), false, clickType -> {
}).getItemStack();
} }
@Override @Override
@@ -46,7 +46,8 @@ public class KillAllBauGuiItem extends BauGuiItem {
@Override @Override
public ItemStack getItem(Player player) { public ItemStack getItem(Player player) {
return new SWItem(Material.LAVA_BUCKET, BauSystem.MESSAGE.parse("OTHER_ITEMS_KILLALL_NAME", player), Arrays.asList(BauSystem.MESSAGE.parse("OTHER_ITEMS_KILLALL_LORE_1", player), BauSystem.MESSAGE.parse("OTHER_ITEMS_KILLALL_LORE_2", player)), false, clickType -> {}).getItemStack(); return new SWItem(Material.LAVA_BUCKET, BauSystem.MESSAGE.parse("OTHER_ITEMS_KILLALL_NAME", player), Arrays.asList(BauSystem.MESSAGE.parse("OTHER_ITEMS_KILLALL_LORE_1", player), BauSystem.MESSAGE.parse("OTHER_ITEMS_KILLALL_LORE_2", player)), false, clickType -> {
}).getItemStack();
} }
@Override @Override
@@ -38,16 +38,19 @@ public class NavWandBauGuiItem extends BauGuiItem {
super(27); super(27);
} }
@Override public Permission permission() { @Override
public Permission permission() {
return Permission.MEMBER; return Permission.MEMBER;
} }
@Override public ItemStack getItem(Player player) { @Override
public ItemStack getItem(Player player) {
return new SWItem(Material.COMPASS, BauSystem.MESSAGE.parse("NAVIGATION_WAND", player), Arrays.asList(BauSystem.MESSAGE.parse("NAVIGATION_WAND_LEFT_CLICK", player), BauSystem.MESSAGE.parse("NAVIGATION_WAND_RIGHT_CLICK", player)), false, clickType -> { return new SWItem(Material.COMPASS, BauSystem.MESSAGE.parse("NAVIGATION_WAND", player), Arrays.asList(BauSystem.MESSAGE.parse("NAVIGATION_WAND_LEFT_CLICK", player), BauSystem.MESSAGE.parse("NAVIGATION_WAND_RIGHT_CLICK", player)), false, clickType -> {
}).getItemStack(); }).getItemStack();
} }
@Override public boolean click(ClickType click, Player p) { @Override
public boolean click(ClickType click, Player p) {
p.performCommand("/wand -n"); p.performCommand("/wand -n");
p.closeInventory(); p.closeInventory();
return false; return false;
@@ -42,34 +42,38 @@ public class AFKStopperListener implements Listener {
Bukkit.getScheduler().runTaskTimer(BauSystem.getInstance(), () -> { Bukkit.getScheduler().runTaskTimer(BauSystem.getInstance(), () -> {
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
if (currentTime - lastMovementTime > 10 * 60000) { // 10 Minutes if (currentTime - lastMovementTime > 10 * 60000) { // 10 Minutes
for (Player p : Bukkit.getOnlinePlayers()) for (Player p : Bukkit.getOnlinePlayers()) {
p.kickPlayer(BauSystem.MESSAGE.parse("AFK_KICK_MESSAGE", p)); p.kickPlayer(BauSystem.MESSAGE.parse("AFK_KICK_MESSAGE", p));
} else if(currentTime - lastMovementTime > 9*60000) }
} else if (currentTime - lastMovementTime > 9 * 60000) {
BauSystem.MESSAGE.broadcast("AFK_WARNING_MESSAGE"); BauSystem.MESSAGE.broadcast("AFK_WARNING_MESSAGE");
}
}, 1200, 1200); //every minute }, 1200, 1200); //every minute
} }
@EventHandler @EventHandler
public void onPlayerMove(PlayerMoveEvent event) { public void onPlayerMove(PlayerMoveEvent event) {
Location to = event.getTo(); Location to = event.getTo();
if (to == null) if (to == null) return;
return;
Location from = event.getFrom(); Location from = event.getFrom();
if (from.getPitch() != to.getPitch() || from.getYaw() != to.getYaw()) if (from.getPitch() != to.getPitch() || from.getYaw() != to.getYaw()) {
lastMovementTime = System.currentTimeMillis(); lastMovementTime = System.currentTimeMillis();
} }
}
@EventHandler(priority = EventPriority.LOWEST) //Potential fix for potential race condition with WE axe spontaneously not working @EventHandler(priority = EventPriority.LOWEST)
//Potential fix for potential race condition with WE axe spontaneously not working
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
event.getPlayer().setOp(true); event.getPlayer().setOp(true);
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
if(Bukkit.getOnlinePlayers().isEmpty() || (Bukkit.getOnlinePlayers().size() == 1 && Bukkit.getOnlinePlayers().contains(event.getPlayer()))) if (Bukkit.getOnlinePlayers().isEmpty() || (Bukkit.getOnlinePlayers().size() == 1 && Bukkit.getOnlinePlayers().contains(event.getPlayer()))) {
CheckpointUtils.freeze(); CheckpointUtils.freeze();
} }
}
@EventHandler @EventHandler
public void onCRIUWakeup(CRIUWakeupEvent event) { public void onCRIUWakeup(CRIUWakeupEvent event) {
@@ -105,8 +105,9 @@ public class SignEdit implements Listener {
Bukkit.getScheduler().runTask(BauSystem.getInstance(), () -> { Bukkit.getScheduler().runTask(BauSystem.getInstance(), () -> {
ServerLevel serverLevel = ((CraftWorld) player.getWorld()).getHandle(); ServerLevel serverLevel = ((CraftWorld) player.getWorld()).getHandle();
Block signLoc = CraftBlock.at(serverLevel, o.getPos()); Block signLoc = CraftBlock.at(serverLevel, o.getPos());
if (!signLoc.getType().name().contains("SIGN")) if (!signLoc.getType().name().contains("SIGN")) {
return; return;
}
String[] lines = o.getLines(); String[] lines = o.getLines();
Sign sign = ((Sign) signLoc.getState()); Sign sign = ((Sign) signLoc.getState());
@@ -32,8 +32,7 @@ public class SignListener implements Listener {
public void onSignChange(SignChangeEvent event) { public void onSignChange(SignChangeEvent event) {
for (int i = 0; i <= 3; ++i) { for (int i = 0; i <= 3; ++i) {
String line = event.getLine(i); String line = event.getLine(i);
if (line == null) if (line == null) continue;
continue;
line = ChatColor.translateAlternateColorCodes('&', line); line = ChatColor.translateAlternateColorCodes('&', line);
event.setLine(i, line); event.setLine(i, line);
} }
@@ -51,6 +51,7 @@ public class ColorReplaceCommand extends SWCommand {
} }
private Set<String> types = new HashSet<>(); private Set<String> types = new HashSet<>();
{ {
WorldEditListener.addOtherCommand("//colorreplace"); WorldEditListener.addOtherCommand("//colorreplace");
WorldEditListener.addOtherCommand("//cr"); WorldEditListener.addOtherCommand("//cr");
@@ -218,12 +218,10 @@ public class FlatteningWrapper {
public boolean inWater(org.bukkit.World world, Vector tntPosition) { public boolean inWater(org.bukkit.World world, Vector tntPosition) {
Block block = world.getBlockAt(tntPosition.getBlockX(), tntPosition.getBlockY(), tntPosition.getBlockZ()); Block block = world.getBlockAt(tntPosition.getBlockX(), tntPosition.getBlockY(), tntPosition.getBlockZ());
if (block.getType() == Material.WATER) if (block.getType() == Material.WATER) return true;
return true;
BlockData data = block.getBlockData(); BlockData data = block.getBlockData();
if (!(data instanceof Waterlogged)) if (!(data instanceof Waterlogged)) return false;
return false;
return ((Waterlogged) data).isWaterlogged(); return ((Waterlogged) data).isWaterlogged();
} }
@@ -49,7 +49,9 @@ public class RayTraceUtils {
RRayTraceResult nearestHitResult = null; RRayTraceResult nearestHitResult = null;
double nearestDistanceSq = Double.MAX_VALUE; double nearestDistanceSq = Double.MAX_VALUE;
for (REntity entity : entityList) { for (REntity entity : entityList) {
if (!isOccluded(startPos.toVector(), direction, new Vector(entity.getX(), entity.getY() + 0.5, entity.getZ()))) continue; if (!isOccluded(startPos.toVector(), direction, new Vector(entity.getX(), entity.getY() + 0.5, entity.getZ()))) {
continue;
}
double distanceSq = new Vector(entity.getX(), entity.getY() + 0.5, entity.getZ()).distanceSquared(startPos.toVector()); double distanceSq = new Vector(entity.getX(), entity.getY() + 0.5, entity.getZ()).distanceSquared(startPos.toVector());
if (distanceSq > 100.0) continue; if (distanceSq > 100.0) continue;
if (distanceSq < nearestDistanceSq) { if (distanceSq < nearestDistanceSq) {
@@ -24,6 +24,7 @@ import org.bukkit.entity.Player;
public interface ScoreboardElement { public interface ScoreboardElement {
ScoreboardGroup getGroup(); ScoreboardGroup getGroup();
int order(); int order();
String get(Region region, Player p); String get(Region region, Player p);
@@ -27,22 +27,29 @@ import org.bukkit.boss.BarStyle;
public interface BauSystemBossbar { public interface BauSystemBossbar {
String getTitle(); String getTitle();
void setTitle(String title); void setTitle(String title);
double getProgress(); double getProgress();
void setProgress(double progress); void setProgress(double progress);
BarColor getColor(); BarColor getColor();
void setColor(BarColor color); void setColor(BarColor color);
BarStyle getStyle(); BarStyle getStyle();
void setStyle(BarStyle style); void setStyle(BarStyle style);
boolean hasFlag(BarFlag flag); boolean hasFlag(BarFlag flag);
void addFlag(BarFlag flag); void addFlag(BarFlag flag);
void removeFlag(BarFlag flag); void removeFlag(BarFlag flag);
boolean isVisible(); boolean isVisible();
void setVisible(boolean visible); void setVisible(boolean visible);
Region getRegion(); Region getRegion();
+52 -12
View File
@@ -2,6 +2,7 @@
--- ---
<!-- TOC --> <!-- TOC -->
* [SteamWar.de - Script System](#steamwarde---script-system) * [SteamWar.de - Script System](#steamwarde---script-system)
* [Einleitung](#einleitung) * [Einleitung](#einleitung)
* [Nutzung mit einer IDE](#nutzung-mit-einer-ide) * [Nutzung mit einer IDE](#nutzung-mit-einer-ide)
@@ -37,32 +38,39 @@
* [Code](#code-3) * [Code](#code-3)
* [Inventory](#inventory-1) * [Inventory](#inventory-1)
* [Code](#code-4) * [Code](#code-4)
<!-- TOC --> <!-- TOC -->
## Einleitung ## Einleitung
Das Script System auf SteamWar.de basiert auf [Lua](https://www.lua.org/docs.html). Das Script System auf SteamWar.de basiert auf [Lua](https://www.lua.org/docs.html).
Der Code wird einfach in ein Minecraft Buch geschrieben und kann mit einem Links-Klick ausgeführt werden. Der Code wird einfach in ein Minecraft Buch geschrieben und kann mit einem Links-Klick ausgeführt werden.
## Nutzung mit einer IDE ## Nutzung mit einer IDE
Im Repository liegen [Lua-Definitionen](sw.def.lua) für [Luanalysis](https://plugins.jetbrains.com/plugin/14698-luanalysis).
Im Repository liegen [Lua-Definitionen](sw.def.lua)
für [Luanalysis](https://plugins.jetbrains.com/plugin/14698-luanalysis).
Diese können in der IDE genutzt werden, um die APIs zu nutzen. Diese können in der IDE genutzt werden, um die APIs zu nutzen.
Einfach die `sw.def.lua` in denselben Ordner wie das Script legen und die IDE sollte die APIs erkennen. Einfach die `sw.def.lua` in denselben Ordner wie das Script legen und die IDE sollte die APIs erkennen.
# Basis-Apis # Basis-Apis
Es werden folgende Standard-Apis zur Verfügung gestellt: Es werden folgende Standard-Apis zur Verfügung gestellt:
- [`math`](https://www.lua.org/manual/5.4/manual.html#6.7) - [`math`](https://www.lua.org/manual/5.4/manual.html#6.7)
- [`string`](https://www.lua.org/manual/5.4/manual.html#6.4) - [`string`](https://www.lua.org/manual/5.4/manual.html#6.4)
- [`table`](https://www.lua.org/manual/5.4/manual.html#6.6) - [`table`](https://www.lua.org/manual/5.4/manual.html#6.6)
- [`bit32`](https://www.lua.org/manual/5.2/manual.html#6.7) - [`bit32`](https://www.lua.org/manual/5.2/manual.html#6.7)
# SteamWar.de-Api # SteamWar.de-Api
APIs, die mit einem `_` beginnen sind noch nicht stabil und können sich jederzeit ändern. APIs, die mit einem `_` beginnen sind noch nicht stabil und können sich jederzeit ändern.
Sie sollten daher nicht verwendet werden, da sie sich noch in der Entwicklung befinden. Sie sollten daher nicht verwendet werden, da sie sich noch in der Entwicklung befinden.
Diese können auch undokumentierte Funktionen enthalten, die nicht in der Dokumentation aufgeführt sind. Diese können auch undokumentierte Funktionen enthalten, die nicht in der Dokumentation aufgeführt sind.
In den Scripten gibt es dazu noch folgende globale Variablen: In den Scripten gibt es dazu noch folgende globale Variablen:
- [`player`](#player) - [`player`](#player)
- [`random`](#random) - [`random`](#random)
- [`region`](#region) - [`region`](#region)
@@ -84,6 +92,7 @@ Ohne eine Kategorie sind folgende Funktionen verfügbar, die nicht allgemein sin
| `join` | length(String, String...): String | Füge die Texte mit den ersten Parameter zusammen | | `join` | length(String, String...): String | Füge die Texte mit den ersten Parameter zusammen |
### player ### player
Das `player`-Modul stellt Funktionen zur Verfügung, die den Spieler betreffen. Das `player`-Modul stellt Funktionen zur Verfügung, die den Spieler betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -105,6 +114,7 @@ Es gibt folgende Funktionen:
| `closeInventory` | closeInventory() | Schließe das aktuell geöffnete Inventar des Spielers | | `closeInventory` | closeInventory() | Schließe das aktuell geöffnete Inventar des Spielers |
### random ### random
Das `random`-Modul stellt Funktionen zur Verfügung, die Zufallszahlen betreffen. Das `random`-Modul stellt Funktionen zur Verfügung, die Zufallszahlen betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -119,6 +129,7 @@ Es gibt folgende Funktionen:
| nextBool | nextBool(): Boolean | Gibt true oder false zurück | | nextBool | nextBool(): Boolean | Gibt true oder false zurück |
### region ### region
Das `region`-Modul stellt Funktion zur Verfügung, die die Region des Spielers betreffen. Das `region`-Modul stellt Funktion zur Verfügung, die die Region des Spielers betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -141,6 +152,7 @@ Es gibt folgende weitere Module:
| `trace` | [trace](#trace) | | `trace` | [trace](#trace) |
#### tnt #### tnt
Das `tnt`-Modul stellt Funktionen zur Verfügung, die den TNT-Modus in der Region des Spielers betreffen. Das `tnt`-Modul stellt Funktionen zur Verfügung, die den TNT-Modus in der Region des Spielers betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -151,8 +163,8 @@ Es gibt folgende Funktionen:
| `onlyTb` | onlyTb(): Boolean | Gibt zurück, ob der TNT-Modus auf Only-Tb ist | | `onlyTb` | onlyTb(): Boolean | Gibt zurück, ob der TNT-Modus auf Only-Tb ist |
| `onlyBuild` | onlyBuild(): Boolean | Gibt zurück, ob der TNT-Modus auf Only-Build ist | | `onlyBuild` | onlyBuild(): Boolean | Gibt zurück, ob der TNT-Modus auf Only-Build ist |
#### trace #### trace
Das `trace`-Modul stellt Funktionen zur Verfügung, die den Status des Tracers der Region betreffen. Das `trace`-Modul stellt Funktionen zur Verfügung, die den Status des Tracers der Region betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -164,6 +176,7 @@ Es gibt folgende Funktionen:
| `time` | time(): String | Gibt die Zeit des Tracers zurück | | `time` | time(): String | Gibt die Zeit des Tracers zurück |
## server ## server
Das `server`-Modul stellt Funktionen zur Verfügung, die den Server betreffen. Das `server`-Modul stellt Funktionen zur Verfügung, die den Server betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -181,6 +194,7 @@ Es gibt folgende weitere Module:
| `tps` | [tps](#tps) | | `tps` | [tps](#tps) |
#### tps #### tps
Das `tps`-Modul stellt Funktionen zur Verfügung, die die TPS des Servers betreffen. Das `tps`-Modul stellt Funktionen zur Verfügung, die die TPS des Servers betreffen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
@@ -195,6 +209,7 @@ Es gibt folgende Funktionen:
| `limit` | limit(): Number | Gibt das TPS-Limit zurück | | `limit` | limit(): Number | Gibt das TPS-Limit zurück |
## storage ## storage
Das `storage`-Modul stellt Funktionen zur Verfügung, mit welchen man Werte speichern kann. Das `storage`-Modul stellt Funktionen zur Verfügung, mit welchen man Werte speichern kann.
Es gibt folgende Module: Es gibt folgende Module:
@@ -217,6 +232,7 @@ Alle Module haben folgende Funktionen:
Ein Accessor ist ein Objekt, womit du direkt auf einen Wert zugreifen kannst und es ändern kannst. Ein Accessor ist ein Objekt, womit du direkt auf einen Wert zugreifen kannst und es ändern kannst.
Es geht wie folgt: Es geht wie folgt:
```lua ```lua
keyAccessor = storage.player.accessor("key") keyAccessor = storage.player.accessor("key")
@@ -225,11 +241,12 @@ print(keyAccessor()) -- Gibt den Wert zurück
``` ```
## inventory ## inventory
Das `inventory`-Modul stellt Funktionen zur Verfügung, um ein Inventar zu öffnen. Das `inventory`-Modul stellt Funktionen zur Verfügung, um ein Inventar zu öffnen.
Es gibt folgende Funktionen: Es gibt folgende Funktionen:
| Name | Signature | Beschreibung | | Name | Signature | Beschreibung |
|----------|-----------------------------------|-------------------------------------------------------------------| |----------|-----------------------------------|--------------------------------------------------------------|
| `create` | create(String, Number): Inventory | Erstellt ein Inventar mit dem Title und der Anzahl an Zeilen | | `create` | create(String, Number): Inventory | Erstellt ein Inventar mit dem Title und der Anzahl an Zeilen |
Das `Inventory`-Objekt hat folgende Funktionen: Das `Inventory`-Objekt hat folgende Funktionen:
@@ -256,6 +273,7 @@ Wenn eine Barrier statt des richtigen Items angezeigt wird, dann ist das angegeb
``` ```
# SteamWar.de-Global-Api # SteamWar.de-Global-Api
Mit `/script` kann man Script-Bücher global abspeichern. Diese haben dann zugrif auf die `global`-Api. Mit `/script` kann man Script-Bücher global abspeichern. Diese haben dann zugrif auf die `global`-Api.
Die `global`-Api stellt Funktionen zur Verfügung um auf Events, Commands und Hotkeys mit einem Script zu reagieren. Die `global`-Api stellt Funktionen zur Verfügung um auf Events, Commands und Hotkeys mit einem Script zu reagieren.
@@ -274,20 +292,28 @@ Es gibt folgende Variablen:
| `events` | Siehe: [Event Type](#eventtypen) | | `events` | Siehe: [Event Type](#eventtypen) |
## Commands ## Commands
Der Command Handler kriegt eine Liste aller angegeben argumenten. Die Argumente sind vom Typ `String`. Mit dem Wert gespeichert unter `args.alias` oder `args["alias"]` erhältst du, welcher command eingegeben wurde. Wenn ein handler für mehrere Befehle registriert wurde kannst du es hiermit erkennen.
Du kannst `args.hasShortFlag(String)` um herauszufinden ob eine Flag angegeben wurde wie zum Beispiel `-f`. Mit `args.removeShortFlag(String)` kannst du die Flag entfernen und erhältst ob sie angegeben wurde. Der Command Handler kriegt eine Liste aller angegeben argumenten. Die Argumente sind vom Typ `String`. Mit dem Wert
gespeichert unter `args.alias` oder `args["alias"]` erhältst du, welcher command eingegeben wurde. Wenn ein handler für
mehrere Befehle registriert wurde kannst du es hiermit erkennen.
Du kannst `args.hasShortFlag(String)` um herauszufinden ob eine Flag angegeben wurde wie zum Beispiel `-f`. Mit
`args.removeShortFlag(String)` kannst du die Flag entfernen und erhältst ob sie angegeben wurde.
## Hotkeys ## Hotkeys
Hotkeys werden im folgenden Format angegeben: `MODIFIER+KEY`. Bei den Hotkey erstellung ist die Großschreibung egal. Es gibt folgende Modifier: Hotkeys werden im folgenden Format angegeben: `MODIFIER+KEY`. Bei den Hotkey erstellung ist die Großschreibung egal. Es
gibt folgende Modifier:
- `ctrl` - `ctrl`
- `shift` - `shift`
- `alt` - `alt`
- `meta` - `meta`
Es können auch mehrere Modifier angegeben werden, z.B. `ctrl+shift+alt+c`. Die Reihenfolge der Modifier und des Keys ist egal. Es können auch mehrere Modifier angegeben werden, z.B. `ctrl+shift+alt+c`. Die Reihenfolge der Modifier und des Keys ist
egal.
## Eventtypen ## Eventtypen
Einige Events sind auch abbrechbar, dazu muss die Funktion `setCancelled()` aufgerufen werden. Einige Events sind auch abbrechbar, dazu muss die Funktion `setCancelled()` aufgerufen werden.
| Name | Wenn | Parameter | Abbrechbar | | Name | Wenn | Parameter | Abbrechbar |
@@ -306,6 +332,7 @@ Einige Events sind auch abbrechbar, dazu muss die Funktion `setCancelled()` aufg
| `EntityDeath` | Wenn ein Entity stirbt | (type: Entity Type) | false | | `EntityDeath` | Wenn ein Entity stirbt | (type: Entity Type) | false |
### BlockEvent ### BlockEvent
Das übergebene Objekt an den Handler hat folgende Variablen: Das übergebene Objekt an den Handler hat folgende Variablen:
| Name | Beschreibung | | Name | Beschreibung |
@@ -316,6 +343,7 @@ Das übergebene Objekt an den Handler hat folgende Variablen:
| `type` | Das Material des Blocks | | `type` | Das Material des Blocks |
### InteractEvent ### InteractEvent
Das übergebene Objekt an den Handler hat folgende Variablen: Das übergebene Objekt an den Handler hat folgende Variablen:
| Name | Beschreibung | | Name | Beschreibung |
@@ -334,8 +362,8 @@ Wenn `hasBlock` wahr ist, gibt es folgende Variablen:
| `blockZ` | Die Z-Koordinate des Blocks | | `blockZ` | Die Z-Koordinate des Blocks |
| `blockFace` | Die Seite des Blocks die geklickt wurde | | `blockFace` | Die Seite des Blocks die geklickt wurde |
### Position ### Position
Die Position ist ein Objekt mit folgenden Variablen: Die Position ist ein Objekt mit folgenden Variablen:
| Name | Beschreibung | | Name | Beschreibung |
@@ -345,6 +373,7 @@ Die Position ist ein Objekt mit folgenden Variablen:
| `z` | Die Z-Koordinate | | `z` | Die Z-Koordinate |
# Instabile APIs # Instabile APIs
Hier sind einige APIs aufgelistet, die nicht stabil sind und sich jederzeit ändern können. Hier sind einige APIs aufgelistet, die nicht stabil sind und sich jederzeit ändern können.
## _worldedit ## _worldedit
@@ -353,27 +382,30 @@ Hier sind einige APIs aufgelistet, die nicht stabil sind und sich jederzeit änd
|-------------|-----------------------------------------------------------|-----------------------------------| |-------------|-----------------------------------------------------------|-----------------------------------|
| `selection` | selection(Liste\<Pos>), selection(): {min: Pos, max: Pos} | Die aktuelle auswahl des Spielers | | `selection` | selection(Liste\<Pos>), selection(): {min: Pos, max: Pos} | Die aktuelle auswahl des Spielers |
# Beispiele # Beispiele
## Hello, World! ## Hello, World!
Ein einfaches Hello, World!-Script. Ein einfaches Hello, World!-Script.
#### Code #### Code
```lua ```lua
print("Hello, World!") print("Hello, World!")
``` ```
#### Ausgabe #### Ausgabe
``` ```
Hello, World! Hello, World!
``` ```
## BauGUI on DoubleSwap ## BauGUI on DoubleSwap
Das Standardskript für das Öffnen des BauGUIs Das Standardskript für das Öffnen des BauGUIs
#### Code #### Code
```lua ```lua
function handler(event) function handler(event)
exec("gui") exec("gui")
@@ -383,9 +415,11 @@ event(events.DoubleSwap, handler)
``` ```
## SL Command ## SL Command
Ein einfacher Command Redefiner. Ein einfacher Command Redefiner.
#### Code #### Code
```lua ```lua
function handler(args) function handler(args)
exec("stoplag") exec("stoplag")
@@ -395,9 +429,11 @@ command("sl", handler)
``` ```
## Paste Hotkey ## Paste Hotkey
Ein Hotkey zum Pasten des Clipboard-Inhalts. Ein Hotkey zum Pasten des Clipboard-Inhalts.
#### Code #### Code
```lua ```lua
function handler(pressed) function handler(pressed)
if pressed then if pressed then
@@ -409,11 +445,15 @@ hotkey("ctrl+v", handler)
``` ```
## Inventory ## Inventory
Ein Beispiel für ein Inventar. Ein Beispiel für ein Inventar.
#### Code #### Code
```lua ```lua
inv = inventory.create("Test Inv", 3) inv = inventory.create("Test Inv", 3)
inv.item(13, "STONE", "Ich bin ein Stein", function(e) player.chat(e) end, {"Die Lore", "Die Zweite Zeile"}, true) inv.item(13, "STONE", "Ich bin ein Stein", function(e)
player.chat(e)
end, { "Die Lore", "Die Zweite Zeile" }, true)
inv.open() inv.open()
``` ```
+213 -81
View File
@@ -26,7 +26,9 @@ inventory = {}
---@param title string ---@param title string
---@param size number ---@param size number
---@return Inventory ---@return Inventory
function inventory.create(title, size) return nil end function inventory.create(title, size)
return nil
end
---@alias InventoryClick 'LEFT' | 'SHIFT_LEFT' | 'RIGHT' | 'SHIFT_RIGHT' | 'MIDDLE' | 'NUMBER_KEY' ---@alias InventoryClick 'LEFT' | 'SHIFT_LEFT' | 'RIGHT' | 'SHIFT_RIGHT' | 'MIDDLE' | 'NUMBER_KEY'
@@ -44,66 +46,88 @@ local Inventory = {}
---@param enchanted boolean ---@param enchanted boolean
---@param amount number ---@param amount number
---@return void ---@return void
function Inventory.item(slot, material, name, handler, lore, enchanted, amount) end function Inventory.item(slot, material, name, handler, lore, enchanted, amount)
end
---@param handler fun(): void ---@param handler fun(): void
---@return void ---@return void
function Inventory.setCloseHandler(handler) end function Inventory.setCloseHandler(handler)
end
---@return void ---@return void
function Inventory.open() end function Inventory.open()
end
player = {} player = {}
---@return string ---@return string
---Get the name of the player. ---Get the name of the player.
function player.name() return "" end function player.name()
return ""
end
---@return void ---@return void
function player.chat(...) end function player.chat(...)
end
---@return void ---@return void
---Send a message to the actionbar of the player. ---Send a message to the actionbar of the player.
function player.actionbar(...) end function player.actionbar(...)
end
---@overload fun(): number ---@overload fun(): number
---@param newX number ---@param newX number
function player.x(newX) end function player.x(newX)
end
---@overload fun(): number ---@overload fun(): number
---@param newY number ---@param newY number
function player.y(newY) end function player.y(newY)
end
---@overload fun(): number ---@overload fun(): number
---@param newZ number ---@param newZ number
function player.z(newZ) end function player.z(newZ)
end
---@overload fun(): number ---@overload fun(): number
---@param newYaw number ---@param newYaw number
function player.yaw(newYaw) end function player.yaw(newYaw)
end
---@overload fun(): number ---@overload fun(): number
---@param newPitch number ---@param newPitch number
function player.pitch(newPitch) end function player.pitch(newPitch)
end
---@return boolean ---@return boolean
function player.sneaking() return nil end function player.sneaking()
return nil
end
---@return boolean ---@return boolean
function player.sprinting() return nil end function player.sprinting()
return nil
end
---@overload fun(): number ---@overload fun(): number
---@param newSlot number ---@param newSlot number
function player.slot(newSlot) end function player.slot(newSlot)
end
---@return string ---@return string
function player.item() return nil end function player.item()
return nil
end
---@return string ---@return string
function player.offHandItem() return nil end function player.offHandItem()
return nil
end
---@return void ---@return void
function player.closeInventory() end function player.closeInventory()
end
---@field nextBool fun(): boolean ---@field nextBool fun(): boolean
random = {} random = {}
@@ -113,17 +137,23 @@ random = {}
---@param origin number ---@param origin number
---@param bound number ---@param bound number
---@return number ---@return number
function random.nextInt(origin, bound) return nil end function random.nextInt(origin, bound)
return nil
end
---@overload fun(): number ---@overload fun(): number
---@overload fun(bound: number): number ---@overload fun(bound: number): number
---@param origin number ---@param origin number
---@param bound number ---@param bound number
---@return number ---@return number
function random.nextDouble(origin, bound) return nil end function random.nextDouble(origin, bound)
return nil
end
---@return boolean ---@return boolean
function random.nextBool() return nil end function random.nextBool()
return nil
end
---@alias RegionType 'wg' | 'mwg' | 'as' | 'ws' | 'ws_inner' | 'ws_rumpf' | 'ws_rahmen' | 'spawn' ---@alias RegionType 'wg' | 'mwg' | 'as' | 'ws' | 'ws_inner' | 'ws_rumpf' | 'ws_rahmen' | 'spawn'
@@ -136,52 +166,84 @@ local iregion = {}
region = {} region = {}
---@return string ---@return string
function iregion.name() return nil end function iregion.name()
return nil
end
---@return RegionType ---@return RegionType
function iregion.type() return nil end function iregion.type()
return nil
end
---@return boolean ---@return boolean
function iregion.fire() return nil end function iregion.fire()
return nil
end
---@return boolean ---@return boolean
function iregion.freeze() return nil end function iregion.freeze()
return nil
end
---@return boolean ---@return boolean
function iregion.protect() return nil end function iregion.protect()
return nil
end
---@return string ---@return string
function iregion.loader() return nil end function iregion.loader()
return nil
end
---@return Position ---@return Position
function iregion.copyPoint() return nil end function iregion.copyPoint()
return nil
end
---@return Position ---@return Position
function iregion.minPointBuild() return nil end function iregion.minPointBuild()
return nil
end
---@return Position ---@return Position
function iregion.maxPointBuild() return nil end function iregion.maxPointBuild()
return nil
end
---@return Position ---@return Position
function iregion.minPointBuildExtension() return nil end function iregion.minPointBuildExtension()
return nil
end
---@return Position ---@return Position
function iregion.maxPointBuildExtension() return nil end function iregion.maxPointBuildExtension()
return nil
end
---@return Position ---@return Position
function iregion.testblockPoint() return nil end function iregion.testblockPoint()
return nil
end
---@return Position ---@return Position
function iregion.minPointTestblock() return nil end function iregion.minPointTestblock()
return nil
end
---@return Position ---@return Position
function iregion.maxPointTestblock() return nil end function iregion.maxPointTestblock()
return nil
end
---@return Position ---@return Position
function iregion.minPointTestblockExtension() return nil end function iregion.minPointTestblockExtension()
return nil
end
---@return Position ---@return Position
function iregion.maxPointTestblockExtension() return nil end function iregion.maxPointTestblockExtension()
return nil
end
---@alias TNTMode 'ALLOW' | 'DENY' | 'ONLY_TB' ---@alias TNTMode 'ALLOW' | 'DENY' | 'ONLY_TB'
@@ -189,23 +251,35 @@ function iregion.maxPointTestblockExtension() return nil end
local tnt = {} local tnt = {}
---@return TNTMode ---@return TNTMode
function tnt.mode() return nil end function tnt.mode()
return nil
end
---@return boolean ---@return boolean
function tnt.enabled() return nil end function tnt.enabled()
return nil
end
---@return boolean ---@return boolean
function tnt.onlyTb() return nil end function tnt.onlyTb()
return nil
end
---@return boolean ---@return boolean
function tnt.onlyBuild() return nil end function tnt.onlyBuild()
return nil
end
---@param name string ---@param name string
---@return iregion ---@return iregion
function region.get(name) return nil end function region.get(name)
return nil
end
---@return iregion[] ---@return iregion[]
function region.list() return nil end function region.list()
return nil
end
---@class tracerLib ---@class tracerLib
tracer = {} tracer = {}
@@ -224,7 +298,9 @@ tracer = {}
---@field getId fun(): string ---@field getId fun(): string
---@field getRecords fun(): {[number]: {[number]: TraceRecord}} ---@field getRecords fun(): {[number]: {[number]: TraceRecord}}
function tracer.getTraces() return nil end function tracer.getTraces()
return nil
end
---@class Position ---@class Position
---@field x number ---@field x number
@@ -236,43 +312,65 @@ function tracer.getTraces() return nil end
server = {} server = {}
---@return string ---@return string
function server.time() return nil end function server.time()
return nil
end
---@return number ---@return number
function server.ticks() return nil end function server.ticks()
return nil
end
---@param position Position ---@param position Position
---@return string ---@return string
function getBlockAt(position) return nil end function getBlockAt(position)
return nil
end
---@param position Position ---@param position Position
---@param material string ---@param material string
---@return void ---@return void
function setBlockAt(position, material) return nil end function setBlockAt(position, material)
return nil
end
---@class tps ---@class tps
local tps = {} local tps = {}
---@return number ---@return number
function tps.oneSecond() return nil end function tps.oneSecond()
return nil
end
---@return number ---@return number
function tps.tenSecond() return nil end function tps.tenSecond()
return nil
end
---@return number ---@return number
function tps.oneMinute() return nil end function tps.oneMinute()
return nil
end
---@return number ---@return number
function tps.fiveMinute() return nil end function tps.fiveMinute()
return nil
end
---@return number ---@return number
function tps.tenMinute() return nil end function tps.tenMinute()
return nil
end
---@return number ---@return number
function tps.current() return nil end function tps.current()
return nil
end
---@return number ---@return number
function tps.limit() return nil end function tps.limit()
return nil
end
---@class storage ---@class storage
---@field global storageLib ---@field global storageLib
@@ -286,24 +384,32 @@ local storageLib = {}
---@param key string ---@param key string
---@return any ---@return any
function storageLib.get(key) return nil end function storageLib.get(key)
return nil
end
---@param key string ---@param key string
---@param value any ---@param value any
---@return void ---@return void
function storageLib.set(key, value) end function storageLib.set(key, value)
end
---@param key string ---@param key string
---@return boolean ---@return boolean
function storageLib.has(key) return nil end function storageLib.has(key)
return nil
end
---@param key string ---@param key string
---@return void ---@return void
function storageLib.remove(key) end function storageLib.remove(key)
end
---@param key string ---@param key string
---@return Accessor ---@return Accessor
function storageLib.accessor(key) return nil end function storageLib.accessor(key)
return nil
end
---@class Accessor ---@class Accessor
---@overload fun(): any ---@overload fun(): any
@@ -318,35 +424,46 @@ _worldedit = {}
---@overload fun(pos: Position[]): void ---@overload fun(pos: Position[]): void
---@return Selection ---@return Selection
function _worldedit.selection() return nil end function _worldedit.selection()
return nil
end
---@param msg string ---@param msg string
---@param callback fun(value: string): void ---@param callback fun(value: string): void
---@return void ---@return void
function input(msg, callback) end function input(msg, callback)
end
---@param ticks number ---@param ticks number
---@param callback fun(): void ---@param callback fun(): void
---@return void ---@return void
function delayed(ticks, callback) end function delayed(ticks, callback)
end
---@param x number ---@param x number
---@param y number ---@param y number
---@param z number ---@param z number
---@return Position ---@return Position
function pos(x, y, z) return nil end function pos(x, y, z)
return nil
end
---@return void ---@return void
function exec(...) end function exec(...)
end
---@param obj any ---@param obj any
---@return number ---@return number
function length(obj) return 0 end function length(obj)
return 0
end
---@param separator string ---@param separator string
---@param table any[] ---@param table any[]
---@return string ---@return string
function join(separator, table) return "" end function join(separator, table)
return ""
end
---@class EventType ---@class EventType
---@class events ---@class events
@@ -364,21 +481,23 @@ function join(separator, table) return "" end
---@field EntityDeath EventType ---@field EntityDeath EventType
events = {} events = {}
---@param id EventType ---@param id EventType
---@param handler fun(params: any): void ---@param handler fun(params: any): void
---@return void ---@return void
function event(id, handler) end function event(id, handler)
end
---@param command string ---@param command string
---@param handler fun(params: string[]): void ---@param handler fun(params: string[]): void
---@return void ---@return void
function command(command, handler) end function command(command, handler)
end
---@param trigger string ---@param trigger string
---@param handler fun(pressed: boolean): void ---@param handler fun(pressed: boolean): void
---@return void ---@return void
function hotkey(trigger, handler) end function hotkey(trigger, handler)
end
---@class bossbar ---@class bossbar
bossbar = {} bossbar = {}
@@ -394,39 +513,52 @@ local BossBar = {}
---@param color BossBarColor ---@param color BossBarColor
---@param style BossBarStyle ---@param style BossBarStyle
---@return BossBar ---@return BossBar
function bossbar.create(title, color, style) return nil end function bossbar.create(title, color, style)
return nil
end
---@return string ---@return string
---@overload fun(title: string): void ---@overload fun(title: string): void
function BossBar.title() end function BossBar.title()
end
---@return BossBarColor ---@return BossBarColor
---@overload fun(color: BossBarColor): void ---@overload fun(color: BossBarColor): void
function BossBar.color() end function BossBar.color()
end
---@return BossBarStyle ---@return BossBarStyle
---@overload fun(style: BossBarStyle): void ---@overload fun(style: BossBarStyle): void
function BossBar.style() end function BossBar.style()
end
---@return number ---@return number
---@overload fun(progress: number): void ---@overload fun(progress: number): void
function BossBar.progress() end function BossBar.progress()
end
---@return boolean ---@return boolean
---@overload fun(visible: boolean): void ---@overload fun(visible: boolean): void
function BossBar.visible() end function BossBar.visible()
end
---@return boolean ---@return boolean
---@param flag BossBarFlag ---@param flag BossBarFlag
function BossBar.hasFlag(flag) return nil end function BossBar.hasFlag(flag)
return nil
end
---@return void ---@return void
---@param flag BossBarFlag ---@param flag BossBarFlag
function BossBar.addFlag(flag) end function BossBar.addFlag(flag)
end
---@return boolean ---@return boolean
---@param flag BossBarFlag ---@param flag BossBarFlag
function BossBar.removeFlag(flag) return nil end function BossBar.removeFlag(flag)
return nil
end
---@return void ---@return void
function BossBar.destroy() end function BossBar.destroy()
end
+2 -1
View File
@@ -12,7 +12,8 @@ import de.steamwar.commands.user.UserCommand
import de.steamwar.commands.user.UserInfoCommand import de.steamwar.commands.user.UserInfoCommand
import de.steamwar.commands.user.UserSearchCommand import de.steamwar.commands.user.UserSearchCommand
fun main(args: Array<String>) = SteamWar() fun main(args: Array<String>) =
SteamWar()
.subcommands( .subcommands(
DatabaseCommand().subcommands(InfoCommand(), ResetCommand()), DatabaseCommand().subcommands(InfoCommand(), ResetCommand()),
UserCommand().subcommands(UserInfoCommand(), UserSearchCommand()), UserCommand().subcommands(UserInfoCommand(), UserSearchCommand()),
+2 -1
View File
@@ -12,7 +12,8 @@ class DatabaseCommand: CliktCommand(name = "db") {
val useProduction by option().flag() val useProduction by option().flag()
val db by findOrSetObject { Database } val db by findOrSetObject { Database }
override fun help(context: Context): String = "Run database commands" override fun help(context: Context): String =
"Run database commands"
override fun run() { override fun run() {
if (!useProduction && db.database == "production") { if (!useProduction && db.database == "production") {
+2 -1
View File
@@ -10,7 +10,8 @@ import de.steamwar.db.useDb
class InfoCommand : CliktCommand() { class InfoCommand : CliktCommand() {
val db by requireObject<Database>() val db by requireObject<Database>()
override fun run() = useDb { override fun run() =
useDb {
val tables = execute("SHOW TABLES") { it.getString(1) } val tables = execute("SHOW TABLES") { it.getString(1) }
echo( echo(
+2 -1
View File
@@ -13,7 +13,8 @@ import java.io.File
class ResetCommand : CliktCommand() { class ResetCommand : CliktCommand() {
val db by requireObject<Database>() val db by requireObject<Database>()
override fun run() = useDb { override fun run() =
useDb {
val schemaFile = File("/var/Schema.sql") val schemaFile = File("/var/Schema.sql")
if (!schemaFile.exists()) { if (!schemaFile.exists()) {
throw CliktError("Schema file not found!") throw CliktError("Schema file not found!")
+26 -10
View File
@@ -46,7 +46,8 @@ const val LOG4J_CONFIG = """<?xml version="1.0" encoding="UTF-8"?>
</Configuration>""" </Configuration>"""
class DevCommand : CliktCommand("dev") { class DevCommand : CliktCommand("dev") {
override fun help(context: Context): String = "Start a dev Server" override fun help(context: Context): String =
"Start a dev Server"
override val treatUnknownOptionsAsArgs = true override val treatUnknownOptionsAsArgs = true
@@ -73,12 +74,21 @@ class DevCommand : CliktCommand("dev") {
if (serverDirectory.exists() && serverDirectory.isDirectory) serverDirectory else File(workingDir, server) if (serverDirectory.exists() && serverDirectory.isDirectory) serverDirectory else File(workingDir, server)
if (isVelocity(server)) { if (isVelocity(server)) {
runServer(args, jvmArgs, listOf(jar?.absolutePath ?: File("/jar/Velocity.jar").absolutePath), serverDir) runServer(
args, jvmArgs, listOf(
jar?.absolutePath
?: File("/jar/Velocity.jar").absolutePath
), serverDir
)
} else { } else {
setLogConfig(args) setLogConfig(args)
val version = findVersion(server) ?: throw CliktError("Unknown Server Version") val version = findVersion(server)
val worldFile = world?.absolute()?.toFile() ?: File(serverDir, "devtempworld") ?: throw CliktError("Unknown Server Version")
val jarFile = jar?.absolutePath ?: additionalVersions[server]?.let { supportedVersionJars[it] } ?: supportedVersionJars[version] val worldFile = world?.absolute()?.toFile()
?: File(serverDir, "devtempworld")
val jarFile = jar?.absolutePath
?: additionalVersions[server]?.let { supportedVersionJars[it] }
?: supportedVersionJars[version]
?: throw CliktError("Unknown Server Version") ?: throw CliktError("Unknown Server Version")
if (!worldFile.exists()) { if (!worldFile.exists()) {
@@ -108,7 +118,8 @@ class DevCommand : CliktCommand("dev") {
try { try {
devFile.delete() devFile.delete()
} catch (_: Exception) { /* ignored */ } } catch (_: Exception) { /* ignored */
}
} }
} }
@@ -145,11 +156,15 @@ class DevCommand : CliktCommand("dev") {
"Lobby" to 20 "Lobby" to 20
) )
fun findVersion(server: String): Int? = server.dropWhile { !it.isDigit() }.toIntOrNull() fun findVersion(server: String): Int? =
server.dropWhile { !it.isDigit() }.toIntOrNull()
fun isJava8(server: String): Boolean = findVersion(server)?.let { it <= 10 } ?: false fun isJava8(server: String): Boolean =
findVersion(server)?.let { it <= 10 }
?: false
fun isVelocity(server: String): Boolean = server.endsWith("Velocity") fun isVelocity(server: String): Boolean =
server.endsWith("Velocity")
fun setLogConfig(args: MutableList<String>) { fun setLogConfig(args: MutableList<String>) {
args += "-DlogPath=${workingDir.absolutePath}/logs" args += "-DlogPath=${workingDir.absolutePath}/logs"
@@ -162,7 +177,8 @@ class DevCommand : CliktCommand("dev") {
fun runServer(args: List<String>, jvmArgs: List<String>, cmd: List<String>, serverDir: File) { fun runServer(args: List<String>, jvmArgs: List<String>, cmd: List<String>, serverDir: File) {
val process = ProcessBuilder( val process = ProcessBuilder(
jvm?.absolutePath ?: if (isJava8(server)) "/usr/lib/jvm/openj9-8/bin/java" else "java", jvm?.absolutePath
?: if (isJava8(server)) "/usr/lib/jvm/openj9-8/bin/java" else "java",
*jvmArgs.toTypedArray(), *jvmArgs.toTypedArray(),
*args.toTypedArray(), *args.toTypedArray(),
*jvmDefaultParams, *jvmDefaultParams,
+2 -1
View File
@@ -38,5 +38,6 @@ class ProfilerCommand: CliktCommand("profiler") {
} }
} }
override fun help(context: Context): String = "Start a profiler" override fun help(context: Context): String =
"Start a profiler"
} }
+5 -2
View File
@@ -4,6 +4,9 @@ import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.Context import com.github.ajalt.clikt.core.Context
class UserCommand : CliktCommand("user") { class UserCommand : CliktCommand("user") {
override fun run() = Unit override fun run() =
override fun help(context: Context): String = "User related commands" Unit
override fun help(context: Context): String =
"User related commands"
} }
+8 -3
View File
@@ -17,11 +17,15 @@ import java.time.Duration
class UserInfoCommand : CliktCommand("info") { class UserInfoCommand : CliktCommand("info") {
val userId by argument().help("Id, Name, UUID or DiscordId") val userId by argument().help("Id, Name, UUID or DiscordId")
val user by lazy { findUser(userId) ?: throw CliktError("User not found") } val user by lazy {
findUser(userId)
?: throw CliktError("User not found")
}
override val printHelpOnEmptyArgs = true override val printHelpOnEmptyArgs = true
override fun run() = useDb { override fun run() =
useDb {
val sessions = val sessions =
SessionTable.selectAll().where { SessionTable.userId eq user.id.value } SessionTable.selectAll().where { SessionTable.userId eq user.id.value }
.map { it[SessionTable.startTime] to it[SessionTable.endTime] } .map { it[SessionTable.startTime] to it[SessionTable.endTime] }
@@ -49,7 +53,8 @@ class UserInfoCommand : CliktCommand("info") {
punishments.map { punishments.map {
row( row(
it.type, it.type,
SteamwarUser.byId(it.punisher)?.userName ?: it.punisher, SteamwarUser.byId(it.punisher)?.userName
?: it.punisher,
it.startTime.toString(), it.startTime.toString(),
if (it.perma) "Perma" else it.endTime.toString(), if (it.perma) "Perma" else it.endTime.toString(),
it.reason it.reason
+4 -2
View File
@@ -18,9 +18,11 @@ class UserSearchCommand : CliktCommand("search") {
override val printHelpOnEmptyArgs = true override val printHelpOnEmptyArgs = true
override fun help(context: Context): String = "Search for users" override fun help(context: Context): String =
"Search for users"
override fun run() = useDb { override fun run() =
useDb {
val users = SteamwarUser.find { val users = SteamwarUser.find {
joinedOr( joinedOr(
SteamwarUserTable.username like "%$query%", SteamwarUserTable.username like "%$query%",
+2 -1
View File
@@ -49,7 +49,8 @@ object Database {
} }
} }
fun <T: BaseCliktCommand<T>> BaseCliktCommand<T>.findUser(query: String): SteamwarUser? = transaction { fun <T : BaseCliktCommand<T>> BaseCliktCommand<T>.findUser(query: String): SteamwarUser? =
transaction {
SteamwarUser.find { joinedOr(query.toIntOrNull()?.let { SteamwarUserTable.id eq it }, (SteamwarUserTable.username eq query), SteamwarUserTable.uuid eq query, query.toLongOrNull()?.let { SteamwarUserTable.discordId eq it }) } SteamwarUser.find { joinedOr(query.toIntOrNull()?.let { SteamwarUserTable.id eq it }, (SteamwarUserTable.username eq query), SteamwarUserTable.uuid eq query, query.toLongOrNull()?.let { SteamwarUserTable.discordId eq it }) }
.firstOrNull() .firstOrNull()
?.let { return@transaction it } ?.let { return@transaction it }
@@ -182,8 +182,9 @@ public abstract class AbstractSWCommand<T> {
if (!checkType(method.getAnnotations(), method.getReturnType(), false, annotation -> { if (!checkType(method.getAnnotations(), method.getReturnType(), false, annotation -> {
CommandMetaData.Method methodMetaData = annotation.annotationType().getAnnotation(CommandMetaData.Method.class); CommandMetaData.Method methodMetaData = annotation.annotationType().getAnnotation(CommandMetaData.Method.class);
if (methodMetaData == null) return (aClass, varArg) -> true; if (methodMetaData == null) return (aClass, varArg) -> true;
if (method.getParameterCount() > methodMetaData.maxParameterCount() || method.getParameterCount() < methodMetaData.minParameterCount()) if (method.getParameterCount() > methodMetaData.maxParameterCount() || method.getParameterCount() < methodMetaData.minParameterCount()) {
return (aClass, varArg) -> false; return (aClass, varArg) -> false;
}
return (aClass, varArg) -> { return (aClass, varArg) -> {
Class<?>[] types = methodMetaData.value(); Class<?>[] types = methodMetaData.value();
if (types == null) return true; if (types == null) return true;
@@ -33,7 +33,9 @@ public @interface CommandMetaData {
@Target(ElementType.ANNOTATION_TYPE) @Target(ElementType.ANNOTATION_TYPE)
@interface Method { @interface Method {
Class<?>[] value(); Class<?>[] value();
int minParameterCount() default 0; int minParameterCount() default 0;
int maxParameterCount() default Integer.MAX_VALUE; int maxParameterCount() default Integer.MAX_VALUE;
} }
@@ -44,6 +46,7 @@ public @interface CommandMetaData {
@Target(ElementType.ANNOTATION_TYPE) @Target(ElementType.ANNOTATION_TYPE)
@interface Parameter { @interface Parameter {
Class<?>[] value() default {}; Class<?>[] value() default {};
Class<?> handler() default void.class; Class<?> handler() default void.class;
} }
@@ -148,7 +148,8 @@ class CommandPart<T> {
List<Object> currentArgs = new ArrayList<>(mappedArgs); List<Object> currentArgs = new ArrayList<>(mappedArgs);
List<Object> varArgs = new ArrayList<>(); List<Object> varArgs = new ArrayList<>();
for (int i = startIndex; i < args.length - 1; i++) { for (int i = startIndex; i < args.length - 1; i++) {
CheckArgumentResult validArgument = checkArgument((ignore) -> {}, sender, args, mappedArgs, i); CheckArgumentResult validArgument = checkArgument((ignore) -> {
}, sender, args, mappedArgs, i);
if (!validArgument.success) return; if (!validArgument.success) return;
varArgs.add(validArgument.value); varArgs.add(validArgument.value);
} }
@@ -162,7 +163,8 @@ class CommandPart<T> {
} }
if (args.length - 1 > startIndex) { if (args.length - 1 > startIndex) {
CheckArgumentResult checkArgumentResult = checkArgument((ignore) -> {}, sender, args, mappedArgs, startIndex); CheckArgumentResult checkArgumentResult = checkArgument((ignore) -> {
}, sender, args, mappedArgs, startIndex);
if (checkArgumentResult.success && next != null) { if (checkArgumentResult.success && next != null) {
if (!ignoreAsArgument) { if (!ignoreAsArgument) {
mappedArgs.add(checkArgumentResult.value); mappedArgs.add(checkArgumentResult.value);
@@ -138,7 +138,8 @@ public class SubCommand<T> implements Comparable<SubCommand<T>> {
} }
List<String> tabComplete(T sender, String[] args) { List<String> tabComplete(T sender, String[] args) {
if (validator != null && !validator.validate(sender, sender, (s, objects) -> {})) { if (validator != null && !validator.validate(sender, sender, (s, objects) -> {
})) {
return null; return null;
} }
if (commandPart == null) { if (commandPart == null) {
@@ -26,6 +26,7 @@ import java.lang.annotation.*;
@Repeatable(PluginCheck.PluginChecks.class) @Repeatable(PluginCheck.PluginChecks.class)
public @interface PluginCheck { public @interface PluginCheck {
Has has() default Has.THIS; Has has() default Has.THIS;
String value(); String value();
enum Has { enum Has {
@@ -73,5 +73,6 @@ public abstract class PacketHandler {
} }
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
protected @interface Handler {} protected @interface Handler {
}
} }
@@ -22,12 +22,14 @@ package de.steamwar;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
public class ImplementationProvider { public class ImplementationProvider {
private ImplementationProvider() {} private ImplementationProvider() {
}
public static <T> T getImpl(String className) { public static <T> T getImpl(String className) {
try { try {
return (T) Class.forName(className).getDeclaredConstructor().newInstance(); return (T) Class.forName(className).getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException |
ClassNotFoundException e) {
throw new SecurityException("Could not load implementation", e); throw new SecurityException("Could not load implementation", e);
} }
} }
+18 -9
View File
@@ -46,7 +46,8 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
actor: SteamwarUser, actor: SteamwarUser,
actionType: Type, actionType: Type,
text: String = "" text: String = ""
) = useDb { ) =
useDb {
new { new {
this.time = Instant.now() this.time = Instant.now()
this.server = serverName this.server = serverName
@@ -58,13 +59,16 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun createJoin(jointServerName: String, serverOwner: SteamwarUser?, joinedPlayer: SteamwarUser) = create(jointServerName, serverOwner, joinedPlayer, Type.JOIN) fun createJoin(jointServerName: String, serverOwner: SteamwarUser?, joinedPlayer: SteamwarUser) =
create(jointServerName, serverOwner, joinedPlayer, Type.JOIN)
@JvmStatic @JvmStatic
fun createLeave(leftServerName: String, serverOwner: SteamwarUser?, joinedPlayer: SteamwarUser) = create(leftServerName, serverOwner, joinedPlayer, Type.LEAVE) fun createLeave(leftServerName: String, serverOwner: SteamwarUser?, joinedPlayer: SteamwarUser) =
create(leftServerName, serverOwner, joinedPlayer, Type.LEAVE)
@JvmStatic @JvmStatic
fun createCommand(serverName: String, serverOwner: SteamwarUser?, player: SteamwarUser?, command: String) = player?.let { create(serverName, serverOwner, it, Type.COMMAND, command) } fun createCommand(serverName: String, serverOwner: SteamwarUser?, player: SteamwarUser?, command: String) =
player?.let { create(serverName, serverOwner, it, Type.COMMAND, command) }
@JvmStatic @JvmStatic
fun createSensitiveCommand( fun createSensitiveCommand(
@@ -72,13 +76,16 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
serverOwner: SteamwarUser?, serverOwner: SteamwarUser?,
player: SteamwarUser?, player: SteamwarUser?,
command: String command: String
) = player?.let { create(serverName, serverOwner, it, Type.SENSITIVE_COMMAND, command) } ) =
player?.let { create(serverName, serverOwner, it, Type.SENSITIVE_COMMAND, command) }
@JvmStatic @JvmStatic
fun createChat(serverName: String, serverOwner: SteamwarUser?, chatter: SteamwarUser, chat: String) = create(serverName, serverOwner, chatter, Type.CHAT, chat) fun createChat(serverName: String, serverOwner: SteamwarUser?, chatter: SteamwarUser, chat: String) =
create(serverName, serverOwner, chatter, Type.CHAT, chat)
@JvmStatic @JvmStatic
fun createGuiOpen(serverName: String, serverOwner: SteamwarUser?, player: SteamwarUser, guiName: String) = create(serverName, serverOwner, player, Type.GUI_OPEN, guiName) fun createGuiOpen(serverName: String, serverOwner: SteamwarUser?, player: SteamwarUser, guiName: String) =
create(serverName, serverOwner, player, Type.GUI_OPEN, guiName)
@JvmStatic @JvmStatic
fun createGuiClick( fun createGuiClick(
@@ -89,7 +96,8 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
clickType: String, clickType: String,
slot: Int, slot: Int,
itemName: String itemName: String
) = create( ) =
create(
serverName, serverName,
serverOwner, serverOwner,
player, player,
@@ -98,7 +106,8 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
) )
@JvmStatic @JvmStatic
fun createGuiClose(serverName: String, serverOwner: SteamwarUser?, player: SteamwarUser, guiName: String) = create(serverName, serverOwner, player, Type.GUI_CLOSE, guiName) fun createGuiClose(serverName: String, serverOwner: SteamwarUser?, player: SteamwarUser, guiName: String) =
create(serverName, serverOwner, player, Type.GUI_CLOSE, guiName)
} }
var time by AuditLogTable.time var time by AuditLogTable.time
@@ -48,17 +48,20 @@ class BannedUserIPs(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<BannedUserIPs>(BannedUserIPsTable) { companion object : CompositeEntityClass<BannedUserIPs>(BannedUserIPsTable) {
@JvmStatic @JvmStatic
fun get(userId: Int) = useDb { fun get(userId: Int) =
useDb {
find { BannedUserIPsTable.userId eq userId }.toList() find { BannedUserIPsTable.userId eq userId }.toList()
} }
@JvmStatic @JvmStatic
fun get(ip: String) = useDb { fun get(ip: String) =
useDb {
find { BannedUserIPsTable.ip eq ip }.toList() find { BannedUserIPsTable.ip eq ip }.toList()
} }
@JvmStatic @JvmStatic
fun banIP(userId: Int, ip: String) = useDb { fun banIP(userId: Int, ip: String) =
useDb {
BannedUserIPsTable.insertIgnore { BannedUserIPsTable.insertIgnore {
it[BannedUserIPsTable.userId] = userId it[BannedUserIPsTable.userId] = userId
it[BannedUserIPsTable.ip] = ip it[BannedUserIPsTable.ip] = ip
@@ -67,7 +70,8 @@ class BannedUserIPs(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun unbanIPs(userId: Int) = useDb { fun unbanIPs(userId: Int) =
useDb {
BannedUserIPsTable.deleteWhere { BannedUserIPsTable.userId eq userId } BannedUserIPsTable.deleteWhere { BannedUserIPsTable.userId eq userId }
} }
} }
@@ -76,7 +80,8 @@ class BannedUserIPs(id: EntityID<CompositeID>): CompositeEntity(id) {
val timestamp: Timestamp by BannedUserIPsTable.timestamp.transform({ it.toInstant() }, { Timestamp.from(it) }) val timestamp: Timestamp by BannedUserIPsTable.timestamp.transform({ it.toInstant() }, { Timestamp.from(it) })
val ip by BannedUserIPsTable.ip val ip by BannedUserIPsTable.ip
fun remove() = useDb { fun remove() =
useDb {
delete() delete()
} }
} }
@@ -50,19 +50,24 @@ class BauweltMember(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<BauweltMember>(BauweltMemberTable) { companion object : CompositeEntityClass<BauweltMember>(BauweltMemberTable) {
private val cache = mutableMapOf<Int, BauweltMember>() private val cache = mutableMapOf<Int, BauweltMember>()
private fun cache(member: BauweltMember) = cache.put(member.memberID, member) private fun cache(member: BauweltMember) =
cache.put(member.memberID, member)
@JvmStatic @JvmStatic
fun clear() = cache.clear() fun clear() =
cache.clear()
@JvmStatic @JvmStatic
@Deprecated("Use addMember(ownerId: Int, newMemberId: Int)") @Deprecated("Use addMember(ownerId: Int, newMemberId: Int)")
fun addMember(ownerId: UUID, newMemberId: UUID) = addMember(SteamwarUser.get(ownerId)!!.id, SteamwarUser.get(newMemberId)!!.id) fun addMember(ownerId: UUID, newMemberId: UUID) =
addMember(SteamwarUser.get(ownerId)!!.id, SteamwarUser.get(newMemberId)!!.id)
@JvmStatic @JvmStatic
fun addMember(ownerId: Int, newMemberId: Int) = addMember(EntityID(ownerId, SteamwarUserTable), EntityID(newMemberId, SteamwarUserTable)) fun addMember(ownerId: Int, newMemberId: Int) =
addMember(EntityID(ownerId, SteamwarUserTable), EntityID(newMemberId, SteamwarUserTable))
fun addMember(ownerId: EntityID<Int>, newMemberId: EntityID<Int>) = useDb { fun addMember(ownerId: EntityID<Int>, newMemberId: EntityID<Int>) =
useDb {
BauweltMemberTable.insertIgnore { BauweltMemberTable.insertIgnore {
it[bauweltId] = ownerId it[bauweltId] = ownerId
it[memberId] = newMemberId it[memberId] = newMemberId
@@ -74,21 +79,25 @@ class BauweltMember(id: EntityID<CompositeID>): CompositeEntity(id) {
@JvmStatic @JvmStatic
@Deprecated("Use getBauMember(bauwelt: Int, member: Int)") @Deprecated("Use getBauMember(bauwelt: Int, member: Int)")
fun getBauMember(bauwelt: UUID, member: UUID) = useDb { fun getBauMember(bauwelt: UUID, member: UUID) =
useDb {
find { (bauweltId eq SteamwarUser.get(bauwelt)!!.id) and (BauweltMemberTable.memberId eq SteamwarUser.get(member)!!.id) }.firstOrNull()?.also { cache(it) } find { (bauweltId eq SteamwarUser.get(bauwelt)!!.id) and (BauweltMemberTable.memberId eq SteamwarUser.get(member)!!.id) }.firstOrNull()?.also { cache(it) }
} }
@JvmStatic @JvmStatic
fun getBauMember(bauwelt: Int, member: Int) = useDb { fun getBauMember(bauwelt: Int, member: Int) =
useDb {
find { (bauweltId eq bauwelt) and (BauweltMemberTable.memberId eq member) }.firstOrNull()?.also { cache(it) } find { (bauweltId eq bauwelt) and (BauweltMemberTable.memberId eq member) }.firstOrNull()?.also { cache(it) }
} }
@JvmStatic @JvmStatic
@Deprecated("Use getMembers(bauwelt: Int)") @Deprecated("Use getMembers(bauwelt: Int)")
fun getMembers(bauwelt: UUID) = getMembers(SteamwarUser.get(bauwelt)!!.id.value) fun getMembers(bauwelt: UUID) =
getMembers(SteamwarUser.get(bauwelt)!!.id.value)
@JvmStatic @JvmStatic
fun getMembers(bauwelt: Int) = useDb { fun getMembers(bauwelt: Int) =
useDb {
find { bauweltId eq bauwelt }.toList().also { it.forEach { cache(it) } } find { bauweltId eq bauwelt }.toList().also { it.forEach { cache(it) } }
} }
} }
@@ -119,12 +128,20 @@ class BauweltMember(id: EntityID<CompositeID>): CompositeEntity(id) {
world = value world = value
} }
fun isBuild() = build fun isBuild() =
fun isSupervisor() = world build
fun isWorldEdit() = build
fun isWorld() = world
fun remove() = useDb { fun isSupervisor() =
world
fun isWorldEdit() =
build
fun isWorld() =
world
fun remove() =
useDb {
delete() delete()
} }
} }
@@ -54,7 +54,8 @@ object CheckedSchematicTable: CompositeIdTable("CheckedSchematic") {
class CheckedSchematic(id: EntityID<CompositeID>) : CompositeEntity(id) { class CheckedSchematic(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<CheckedSchematic>(CheckedSchematicTable) { companion object : CompositeEntityClass<CheckedSchematic>(CheckedSchematicTable) {
@JvmStatic @JvmStatic
fun create(node: SchematicNode, validator: Int, startTime: Timestamp, endTime: Timestamp, reason: String, seen: Boolean) = useDb { fun create(node: SchematicNode, validator: Int, startTime: Timestamp, endTime: Timestamp, reason: String, seen: Boolean) =
useDb {
CheckedSchematicTable.insertIgnore { CheckedSchematicTable.insertIgnore {
it[this.nodeId] = node.id it[this.nodeId] = node.id
it[this.nodeOwner] = EntityID(node.owner, SteamwarUserTable) it[this.nodeOwner] = EntityID(node.owner, SteamwarUserTable)
@@ -69,17 +70,20 @@ class CheckedSchematic(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun getLastDeclinedOfNode(node: Int) = useDb { fun getLastDeclinedOfNode(node: Int) =
useDb {
find { (CheckedSchematicTable.nodeId eq node) and (CheckedSchematicTable.declineReason neq "Prüfvorgang abgebrochen") }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList() find { (CheckedSchematicTable.nodeId eq node) and (CheckedSchematicTable.declineReason neq "Prüfvorgang abgebrochen") }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList()
} }
@JvmStatic @JvmStatic
fun previousChecks(node: SchematicNode) = useDb { fun previousChecks(node: SchematicNode) =
useDb {
find { (CheckedSchematicTable.nodeId eq node.id) and (CheckedSchematicTable.declineReason neq "") and (CheckedSchematicTable.declineReason neq "Prüfvorgang abgebrochen") }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList() find { (CheckedSchematicTable.nodeId eq node.id) and (CheckedSchematicTable.declineReason neq "") and (CheckedSchematicTable.declineReason neq "Prüfvorgang abgebrochen") }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList()
} }
@JvmStatic @JvmStatic
fun getUnseen(owner: SteamwarUser) = useDb { fun getUnseen(owner: SteamwarUser) =
useDb {
find { (CheckedSchematicTable.nodeOwner eq owner.id) and (CheckedSchematicTable.seen eq false) }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList() find { (CheckedSchematicTable.nodeOwner eq owner.id) and (CheckedSchematicTable.seen eq false) }.orderBy(CheckedSchematicTable.endTime to SortOrder.DESC).toList()
} }
} }
+21 -10
View File
@@ -48,7 +48,8 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
private var current: Event? = null private var current: Event? = null
@JvmStatic @JvmStatic
fun get(): Event? = if (current?.now() == true) { fun get(): Event? =
if (current?.now() == true) {
current current
} else useDb { } else useDb {
find { EventTable.start.lessEq(Instant.now()) and EventTable.end.greater(Instant.now()) }.firstOrNull() find { EventTable.start.lessEq(Instant.now()) and EventTable.end.greater(Instant.now()) }.firstOrNull()
@@ -56,10 +57,12 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun getAll() = useDb { all().toList() } fun getAll() =
useDb { all().toList() }
@JvmStatic @JvmStatic
fun create(name: String, start: Timestamp, end: Timestamp) = useDb { fun create(name: String, start: Timestamp, end: Timestamp) =
useDb {
EventTable.insertAndGetId { EventTable.insertAndGetId {
it[this.name] = name it[this.name] = name
it[this.deadline] = start.toInstant() it[this.deadline] = start.toInstant()
@@ -71,13 +74,16 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun byId(id: Int) = useDb { findById(id) } fun byId(id: Int) =
useDb { findById(id) }
@JvmStatic @JvmStatic
fun get(name: String) = useDb { find { EventTable.name eq name }.firstOrNull() } fun get(name: String) =
useDb { find { EventTable.name eq name }.firstOrNull() }
@JvmStatic @JvmStatic
fun getComing() = useDb { find { EventTable.start greater Instant.now() }.toList() } fun getComing() =
useDb { find { EventTable.start greater Instant.now() }.toList() }
} }
val eventID by EventTable.id.transform({ EntityID(it, EventTable) }, { it.value }) val eventID by EventTable.id.transform({ EntityID(it, EventTable) }, { it.value })
@@ -96,8 +102,11 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
var publicSchemsOnly by EventTable.publicsOnly var publicSchemsOnly by EventTable.publicsOnly
private set private set
fun publicSchemsOnly() = publicSchemsOnly fun publicSchemsOnly() =
fun now() = Instant.now().let { it.isAfter(start.toInstant()) && it.isBefore(end.toInstant()) } publicSchemsOnly
fun now() =
Instant.now().let { it.isAfter(start.toInstant()) && it.isBefore(end.toInstant()) }
fun update( fun update(
name: String, name: String,
@@ -107,7 +116,8 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
schematicType: SchematicType?, schematicType: SchematicType?,
maxPlayers: Int, maxPlayers: Int,
publicSchemsOnly: Boolean publicSchemsOnly: Boolean
) = useDb { ) =
useDb {
this@Event.eventName = name this@Event.eventName = name
this@Event.deadline = deadline this@Event.deadline = deadline
this@Event.start = start this@Event.start = start
@@ -117,5 +127,6 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
this@Event.publicSchemsOnly = publicSchemsOnly this@Event.publicSchemsOnly = publicSchemsOnly
} }
override fun delete() = useDb { super.delete() } override fun delete() =
useDb { super.delete() }
} }
@@ -52,15 +52,18 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
@JvmStatic get @JvmStatic get
@JvmStatic @JvmStatic
fun byId(fightId: Int) = useDb { findById(fightId) } fun byId(fightId: Int) =
useDb { findById(fightId) }
@JvmStatic @JvmStatic
fun byId(group: EventGroup) = useDb { fun byId(group: EventGroup) =
useDb {
find { EventFightTable.groupId eq group.id }.orderBy(EventFightTable.startTime to SortOrder.DESC).toList() find { EventFightTable.groupId eq group.id }.orderBy(EventFightTable.startTime to SortOrder.DESC).toList()
} }
@JvmStatic @JvmStatic
fun getLast(group: EventGroup) = useDb { fun getLast(group: EventGroup) =
useDb {
Optional.ofNullable( Optional.ofNullable(
find { EventFightTable.groupId eq group.id }.orderBy(EventFightTable.startTime to SortOrder.DESC) find { EventFightTable.groupId eq group.id }.orderBy(EventFightTable.startTime to SortOrder.DESC)
.firstOrNull() .firstOrNull()
@@ -68,13 +71,15 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
} }
@JvmStatic @JvmStatic
fun loadAllComingFights() = useDb { fun loadAllComingFights() =
useDb {
fights.clear() fights.clear()
fights.addAll(find { EventFightTable.startTime greaterEq Instant.now() }.orderBy(EventFightTable.startTime to SortOrder.ASC)) fights.addAll(find { EventFightTable.startTime greaterEq Instant.now() }.orderBy(EventFightTable.startTime to SortOrder.ASC))
} }
@JvmStatic @JvmStatic
fun getEvent(eventId: Int) = useDb { fun getEvent(eventId: Int) =
useDb {
find { EventFightTable.eventId eq eventId }.orderBy(EventFightTable.startTime to SortOrder.ASC).toList() find { EventFightTable.eventId eq eventId }.orderBy(EventFightTable.startTime to SortOrder.ASC).toList()
} }
@@ -111,7 +116,8 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
blueTeam: Int, blueTeam: Int,
redTeam: Int, redTeam: Int,
spectatePort: Int? spectatePort: Int?
) = useDb { ) =
useDb {
get( get(
EventFightTable.insertAndGetId { EventFightTable.insertAndGetId {
it[eventId] = EntityID(event, EventTable) it[eventId] = EntityID(event, EventTable)
@@ -155,16 +161,25 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
val losser: Team? val losser: Team?
get() = useDb { if (ergebnis == 1) Team[teamRed] else if (ergebnis == 2) Team[teamBlue] else null } get() = useDb { if (ergebnis == 1) Team[teamRed] else if (ergebnis == 2) Team[teamBlue] else null }
fun setGroup(group: Int?) = useDb { groupId = group?.let { EntityID(it, EventGroupTable) } } fun setGroup(group: Int?) =
fun hasFinished() = fight != null || ergebnis != 0 useDb { groupId = group?.let { EntityID(it, EventGroupTable) } }
fun reschedule() = useDb { fun hasFinished() =
fight != null || ergebnis != 0
fun reschedule() =
useDb {
startTime = Timestamp.from(Instant.now().plusSeconds(30)) startTime = Timestamp.from(Instant.now().plusSeconds(30))
} }
override fun hashCode() = fightID override fun hashCode() =
override fun equals(other: Any?) = other is EventFight && other.fightID == fightID fightID
override fun compareTo(other: EventFight): Int = startTime.compareTo(other.startTime)
override fun equals(other: Any?) =
other is EventFight && other.fightID == fightID
override fun compareTo(other: EventFight): Int =
startTime.compareTo(other.startTime)
fun update( fun update(
startTime: Timestamp, startTime: Timestamp,
@@ -173,7 +188,8 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
teamBlue: Int, teamBlue: Int,
teamRed: Int, teamRed: Int,
spectatePort: Int? spectatePort: Int?
) = useDb { ) =
useDb {
this@EventFight.startTime = startTime this@EventFight.startTime = startTime
this@EventFight.spielmodus = spielmodus this@EventFight.spielmodus = spielmodus
this@EventFight.map = map this@EventFight.map = map
@@ -182,7 +198,8 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
this@EventFight.spectatePort = spectatePort this@EventFight.spectatePort = spectatePort
} }
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
} }
@@ -44,13 +44,16 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<EventGroup>(EventGroupTable) { companion object : IntEntityClass<EventGroup>(EventGroupTable) {
@JvmStatic @JvmStatic
fun get(event: Event) = useDb { find { EventGroupTable.event eq event.id }.toList() } fun get(event: Event) =
useDb { find { EventGroupTable.event eq event.id }.toList() }
@JvmStatic @JvmStatic
fun byId(groupId: Int) = useDb { Optional.ofNullable(findById(groupId)) } fun byId(groupId: Int) =
useDb { Optional.ofNullable(findById(groupId)) }
@JvmStatic @JvmStatic
fun create(event: Event, name: String, type: EventGroupType) = useDb { fun create(event: Event, name: String, type: EventGroupType) =
useDb {
new { new {
this.eventID = event.id.value this.eventID = event.id.value
this.groupName = name this.groupName = name
@@ -97,7 +100,8 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
val dependents by lazy { EventRelation.getGroupRelations(this) } val dependents by lazy { EventRelation.getGroupRelations(this) }
val lastFight by lazy { Optional.ofNullable(fights.maxByOrNull { it.startTime }) } val lastFight by lazy { Optional.ofNullable(fights.maxByOrNull { it.startTime }) }
fun getId() = id.value fun getId() =
id.value
private var points: Map<Team, Int>? = null private var points: Map<Team, Int>? = null
@@ -118,18 +122,22 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
blueTeamAdd += pointsPerWin blueTeamAdd += pointsPerWin
redTeamAdd += pointsPerLoss redTeamAdd += pointsPerLoss
} }
2 -> { 2 -> {
blueTeamAdd += pointsPerLoss blueTeamAdd += pointsPerLoss
redTeamAdd += pointsPerWin redTeamAdd += pointsPerWin
} }
0 -> if (fight.fight != null) { 0 -> if (fight.fight != null) {
blueTeamAdd += pointsPerDraw blueTeamAdd += pointsPerDraw
redTeamAdd += pointsPerDraw redTeamAdd += pointsPerDraw
} }
} }
p[fight.teamBlue] = p[fight.teamBlue]?.plus(blueTeamAdd) ?: blueTeamAdd p[fight.teamBlue] = p[fight.teamBlue]?.plus(blueTeamAdd)
p[fight.teamRed] = p[fight.teamRed]?.plus(redTeamAdd) ?: redTeamAdd ?: blueTeamAdd
p[fight.teamRed] = p[fight.teamRed]?.plus(redTeamAdd)
?: redTeamAdd
} }
return p.mapKeys { Team.byId(it.key) }.also { points = it } return p.mapKeys { Team.byId(it.key) }.also { points = it }
@@ -138,9 +146,11 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
} }
} }
fun needsTieBreak() = calculatePoints().values.let { it.size == it.toSet().size } fun needsTieBreak() =
calculatePoints().values.let { it.size == it.toSet().size }
fun update(name: String, type: EventGroupType, pointsPerWin: Int, pointsPerLoss: Int, pointsPerDraw: Int) = useDb { fun update(name: String, type: EventGroupType, pointsPerWin: Int, pointsPerLoss: Int, pointsPerDraw: Int) =
useDb {
this@EventGroup.name = name this@EventGroup.name = name
this@EventGroup.type = type this@EventGroup.type = type
this@EventGroup.pointsPerWin = pointsPerWin this@EventGroup.pointsPerWin = pointsPerWin
@@ -148,7 +158,8 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
this@EventGroup.pointsPerDraw = pointsPerDraw this@EventGroup.pointsPerDraw = pointsPerDraw
} }
override fun delete() = useDb { super.delete() } override fun delete() =
useDb { super.delete() }
enum class EventGroupType { enum class EventGroupType {
GROUP_STAGE, GROUP_STAGE,
@@ -39,7 +39,8 @@ object EventRelationTable : IntIdTable("EventRelation") {
class EventRelation(id: EntityID<Int>) : IntEntity(id) { class EventRelation(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<EventRelation>(EventRelationTable) { companion object : IntEntityClass<EventRelation>(EventRelationTable) {
@JvmStatic @JvmStatic
fun get(event: Event) = useDb { fun get(event: Event) =
useDb {
EventRelationTable.innerJoin(EventFightTable) EventRelationTable.innerJoin(EventFightTable)
.select(EventRelationTable.columns) .select(EventRelationTable.columns)
.where { EventFightTable.eventId eq event.id } .where { EventFightTable.eventId eq event.id }
@@ -47,7 +48,8 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun byId(id: Int) = useDb { findById(id) } fun byId(id: Int) =
useDb { findById(id) }
@JvmStatic @JvmStatic
fun getFightRelations(fight: EventFight) = fun getFightRelations(fight: EventFight) =
@@ -58,7 +60,8 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
useDb { find { (EventRelationTable.fromId eq group.id.value) and (EventRelationTable.fromType eq FromType.GROUP) }.toList() } useDb { find { (EventRelationTable.fromId eq group.id.value) and (EventRelationTable.fromType eq FromType.GROUP) }.toList() }
@JvmStatic @JvmStatic
fun create(fight: EventFight, fightTeam: FightTeam, fromType: FromType, fromId: Int, fromPlace: Int) = useDb { fun create(fight: EventFight, fightTeam: FightTeam, fromType: FromType, fromId: Int, fromPlace: Int) =
useDb {
new { new {
this.fightEntityId = fight.id this.fightEntityId = fight.id
this.fightTeam = fightTeam this.fightTeam = fightTeam
@@ -100,30 +103,39 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
var fromPlace by EventRelationTable.fromPlace var fromPlace by EventRelationTable.fromPlace
private set private set
fun getId() = id.value fun getId() =
fun setUpdateTeam(team: FightTeam) = useDb { id.value
fun setUpdateTeam(team: FightTeam) =
useDb {
fightTeam = team fightTeam = team
} }
fun setFromFight(fight: EventFight, place: Int) = useDb { fun setFromFight(fight: EventFight, place: Int) =
useDb {
fromType = FromType.FIGHT fromType = FromType.FIGHT
fromId = fight.id.value fromId = fight.id.value
fromPlace = place fromPlace = place
} }
fun setFromGroup(group: EventGroup, place: Int) = useDb { fun setFromGroup(group: EventGroup, place: Int) =
useDb {
fromType = FromType.GROUP fromType = FromType.GROUP
fromId = group.id.value fromId = group.id.value
fromPlace = place fromPlace = place
} }
fun getAdvancingTeam(): Team? = useDb { when(fromType) { fun getAdvancingTeam(): Team? =
useDb {
when (fromType) {
FromType.FIGHT -> if (fromPlace == 0) fromFight?.winner else fromFight?.losser FromType.FIGHT -> if (fromPlace == 0) fromFight?.winner else fromFight?.losser
FromType.GROUP -> fromGroup?.calculatePoints()?.toList()?.sortedBy { (_, v) -> v }?.reversed()?.elementAt(fromPlace)?.first FromType.GROUP -> fromGroup?.calculatePoints()?.toList()?.sortedBy { (_, v) -> v }?.reversed()?.elementAt(fromPlace)?.first
} } }
}
fun apply(): Boolean { fun apply(): Boolean {
val team = getAdvancingTeam() ?: return false val team = getAdvancingTeam()
?: return false
useDb { useDb {
when (fightTeam) { when (fightTeam) {
@@ -135,7 +147,8 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
return true return true
} }
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
+18 -9
View File
@@ -50,7 +50,8 @@ object FightTable : IntIdTable("Fight", "FightId") {
class Fight(id: EntityID<Int>) : IntEntity(id) { class Fight(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Fight>(FightTable) { companion object : IntEntityClass<Fight>(FightTable) {
@JvmStatic @JvmStatic
fun getById(id: Int) = useDb { get(id) } fun getById(id: Int) =
useDb { get(id) }
@JvmStatic @JvmStatic
fun create( fun create(
@@ -64,7 +65,8 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
redschem: Int?, redschem: Int?,
win: Int, win: Int,
wincondition: String wincondition: String
): Int = useDb { ): Int =
useDb {
FightTable.insertAndGetId { FightTable.insertAndGetId {
it[FightTable.gamemode] = gamemode it[FightTable.gamemode] = gamemode
it[FightTable.server] = server it[FightTable.server] = server
@@ -80,7 +82,8 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun getPage(page: Int, pageSize: Int): List<Fight> = useDb { fun getPage(page: Int, pageSize: Int): List<Fight> =
useDb {
val fights = all().orderBy(FightTable.startTime to SortOrder.DESC).limit(pageSize).offset((pageSize * page).toLong()) val fights = all().orderBy(FightTable.startTime to SortOrder.DESC).limit(pageSize).offset((pageSize * page).toLong())
val fightPlayer = FightPlayer.batchGet(fights.map { it.id.value }) val fightPlayer = FightPlayer.batchGet(fights.map { it.id.value })
@@ -93,7 +96,8 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun markReplayAvailable(id: Int) = useDb { fun markReplayAvailable(id: Int) =
useDb {
FightTable.update({ FightTable.id eq id }) { FightTable.update({ FightTable.id eq id }) {
it[replayAvailable] = true it[replayAvailable] = true
} }
@@ -131,12 +135,16 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
} else { } else {
false false
} }
} ?: false }
?: false
} }
} }
fun replayExists() = schemType != null && replayAvailable fun replayExists() =
fun replayAllowed() = replayAllowed schemType != null && replayAvailable
fun replayAllowed() =
replayAllowed
lateinit var bluePlayers: List<FightPlayer> lateinit var bluePlayers: List<FightPlayer>
lateinit var redPlayers: List<FightPlayer> lateinit var redPlayers: List<FightPlayer>
@@ -146,11 +154,12 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
val red = mutableListOf<FightPlayer>() val red = mutableListOf<FightPlayer>()
for (player in fightPlayers.filter { it.fightID == id.value }) { for (player in fightPlayers.filter { it.fightID == id.value }) {
if (player.team == 1) if (player.team == 1) {
blue.add(player) blue.add(player)
else } else {
red.add(player) red.add(player)
} }
}
bluePlayers = blue bluePlayers = blue
redPlayers = red redPlayers = red
@@ -52,7 +52,8 @@ class FightPlayer(id: EntityID<CompositeID>) : CompositeEntity(id) {
kit: String, kit: String,
kills: Int, kills: Int,
out: Boolean out: Boolean
) = useDb { ) =
useDb {
FightPlayerTable.insertIgnore { FightPlayerTable.insertIgnore {
it[this.fightId] = fightId it[this.fightId] = fightId
it[this.userId] = userId it[this.userId] = userId
@@ -64,7 +65,8 @@ class FightPlayer(id: EntityID<CompositeID>) : CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun batchGet(fightIds: List<Int>) = useDb { fun batchGet(fightIds: List<Int>) =
useDb {
find { FightPlayerTable.fightId inList fightIds.toList() }.toList() find { FightPlayerTable.fightId inList fightIds.toList() }.toList()
} }
} }
@@ -76,5 +78,6 @@ class FightPlayer(id: EntityID<CompositeID>) : CompositeEntity(id) {
val kills by FightPlayerTable.kills val kills by FightPlayerTable.kills
val out by FightPlayerTable.out val out by FightPlayerTable.out
fun isOut() = out fun isOut() =
out
} }
@@ -984,8 +984,7 @@ public final class GameModeConfig<M, W> {
public String hasMap(String map) { public String hasMap(String map) {
for (String m : Server.Maps) { for (String m : Server.Maps) {
if (m.equalsIgnoreCase(map)) if (m.equalsIgnoreCase(map)) return m;
return m;
} }
return null; return null;
} }
@@ -996,8 +995,7 @@ public final class GameModeConfig<M, W> {
public String convertToRealMapName(String map) { public String convertToRealMapName(String map) {
for (String m : Server.Maps) { for (String m : Server.Maps) {
if (m.equalsIgnoreCase(map)) if (m.equalsIgnoreCase(map)) return m;
return m;
} }
return null; return null;
} }
@@ -47,17 +47,20 @@ class IgnoreSystem(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<IgnoreSystem>(IgnoreSystemTable) { companion object : CompositeEntityClass<IgnoreSystem>(IgnoreSystemTable) {
@JvmStatic @JvmStatic
fun isIgnored(ignorer: UUID, ignored: UUID) = useDb { isIgnored(SteamwarUser.get(ignorer)!!, SteamwarUser.get(ignored)!!) } fun isIgnored(ignorer: UUID, ignored: UUID) =
useDb { isIgnored(SteamwarUser.get(ignorer)!!, SteamwarUser.get(ignored)!!) }
@JvmStatic @JvmStatic
fun isIgnored(ignorer: SteamwarUser, ignored: SteamwarUser) = useDb { fun isIgnored(ignorer: SteamwarUser, ignored: SteamwarUser) =
useDb {
find { find {
(IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id) (IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id)
}.firstOrNull() != null }.firstOrNull() != null
} }
@JvmStatic @JvmStatic
fun ignore(ignorer: SteamwarUser, ignored: SteamwarUser) = useDb { fun ignore(ignorer: SteamwarUser, ignored: SteamwarUser) =
useDb {
new { new {
this.ignorer = ignorer.id this.ignorer = ignorer.id
this.ignored = ignored.id this.ignored = ignored.id
@@ -65,7 +68,8 @@ class IgnoreSystem(id: EntityID<CompositeID>) : CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun unIgnore(ignorer: SteamwarUser, ignored: SteamwarUser) = useDb { fun unIgnore(ignorer: SteamwarUser, ignored: SteamwarUser) =
useDb {
find { find {
(IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id) (IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id)
}.firstOrNull()?.delete() }.firstOrNull()?.delete()
@@ -48,28 +48,33 @@ object LeaderboardTable : CompositeIdTable("Leaderboard") {
class Leaderboard(id: EntityID<CompositeID>) : CompositeEntity(id) { class Leaderboard(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<Leaderboard>(LeaderboardTable) { companion object : CompositeEntityClass<Leaderboard>(LeaderboardTable) {
@JvmStatic @JvmStatic
fun getLeaderboard(name: String) = useDb { fun getLeaderboard(name: String) =
useDb {
find { LeaderboardTable.name eq name }.orderBy(LeaderboardTable.time to SortOrder.ASC).limit(5).toList() find { LeaderboardTable.name eq name }.orderBy(LeaderboardTable.time to SortOrder.ASC).limit(5).toList()
} }
@JvmStatic @JvmStatic
fun getPlayerTime(user: SteamwarUser, name: String) = useDb { fun getPlayerTime(user: SteamwarUser, name: String) =
useDb {
find { (LeaderboardTable.userId eq user.id.value) and (LeaderboardTable.name eq name) }.firstOrNull() find { (LeaderboardTable.userId eq user.id.value) and (LeaderboardTable.name eq name) }.firstOrNull()
} }
@JvmStatic @JvmStatic
fun getPlayerPlacement(user: SteamwarUser, name: String) = useDb { fun getPlayerPlacement(user: SteamwarUser, name: String) =
useDb {
LeaderboardTable.select(LeaderboardTable.time.count()) LeaderboardTable.select(LeaderboardTable.time.count())
.where { .where {
(LeaderboardTable.name eq name) and (LeaderboardTable.time lessSubQuery LeaderboardTable.select( (LeaderboardTable.name eq name) and (LeaderboardTable.time lessSubQuery LeaderboardTable.select(
LeaderboardTable.time LeaderboardTable.time
).where { (LeaderboardTable.userId eq user.id.value) and (LeaderboardTable.name eq name) }) ).where { (LeaderboardTable.userId eq user.id.value) and (LeaderboardTable.name eq name) })
} }
.firstOrNull()?.get(LeaderboardTable.time.count())?.toInt() ?: Int.MAX_VALUE .firstOrNull()?.get(LeaderboardTable.time.count())?.toInt()
?: Int.MAX_VALUE
} }
@JvmStatic @JvmStatic
fun upsert(userId: Int, name: String, time: Long, bestTime: Boolean) = useDb { fun upsert(userId: Int, name: String, time: Long, bestTime: Boolean) =
useDb {
LeaderboardTable.upsert( LeaderboardTable.upsert(
onUpdateExclude = listOf(LeaderboardTable.updatedAt, LeaderboardTable.userId, LeaderboardTable.name) onUpdateExclude = listOf(LeaderboardTable.updatedAt, LeaderboardTable.userId, LeaderboardTable.name)
) { ) {
+10 -5
View File
@@ -38,13 +38,16 @@ object ModTable : CompositeIdTable("Mods") {
class Mod(id: EntityID<CompositeID>) : CompositeEntity(id) { class Mod(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<Mod>(ModTable) { companion object : CompositeEntityClass<Mod>(ModTable) {
@JvmStatic @JvmStatic
fun get(modName: String, platform: Platform) = useDb { fun get(modName: String, platform: Platform) =
useDb {
find { ModTable.platform eq platform and (ModTable.modName eq modName) }.firstOrNull() find { ModTable.platform eq platform and (ModTable.modName eq modName) }.firstOrNull()
} }
@JvmStatic @JvmStatic
fun getOrCreate(modName: String, platform: Platform) = useDb { fun getOrCreate(modName: String, platform: Platform) =
get(modName, platform) ?: new { useDb {
get(modName, platform)
?: new {
this.platform = platform this.platform = platform
this.modName = modName this.modName = modName
this.type = ModType.UNKLASSIFIED this.type = ModType.UNKLASSIFIED
@@ -52,7 +55,8 @@ class Mod(id: EntityID<CompositeID>) : CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun getAllModsFiltered(page: Int, elementsPerPage: Int, filter: ModType) = useDb { fun getAllModsFiltered(page: Int, elementsPerPage: Int, filter: ModType) =
useDb {
find { ModTable.modeType eq filter }.limit(elementsPerPage).offset((elementsPerPage * page).toLong()) find { ModTable.modeType eq filter }.limit(elementsPerPage).offset((elementsPerPage * page).toLong())
.orderBy( .orderBy(
ModTable.modName to SortOrder.DESC ModTable.modName to SortOrder.DESC
@@ -60,7 +64,8 @@ class Mod(id: EntityID<CompositeID>) : CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun findFirstMod() = useDb { fun findFirstMod() =
useDb {
find { ModTable.modeType eq ModType.UNKLASSIFIED }.limit(1).firstOrNull() find { ModTable.modeType eq ModType.UNKLASSIFIED }.limit(1).firstOrNull()
} }
} }
+14 -7
View File
@@ -55,27 +55,32 @@ class NodeData(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<NodeData>(NodeDataTable) { companion object : CompositeEntityClass<NodeData>(NodeDataTable) {
@JvmStatic @JvmStatic
fun getLatest(node: SchematicNode) = useDb { fun getLatest(node: SchematicNode) =
useDb {
find { (NodeDataTable.nodeId eq node.nodeId) }.orderBy(NodeDataTable.createdAt to SortOrder.DESC).firstOrNull() find { (NodeDataTable.nodeId eq node.nodeId) }.orderBy(NodeDataTable.createdAt to SortOrder.DESC).firstOrNull()
} }
@JvmStatic @JvmStatic
fun get(node: SchematicNode) = useDb { fun get(node: SchematicNode) =
useDb {
find { (NodeDataTable.nodeId eq node.nodeId) }.orderBy(NodeDataTable.createdAt to SortOrder.ASC).toList() find { (NodeDataTable.nodeId eq node.nodeId) }.orderBy(NodeDataTable.createdAt to SortOrder.ASC).toList()
} }
@JvmStatic @JvmStatic
fun get(node: SchematicNode, revision: Int) = useDb { fun get(node: SchematicNode, revision: Int) =
useDb {
find { NodeDataTable.nodeId eq node.nodeId }.orderBy(NodeDataTable.createdAt to SortOrder.ASC).toList().get(revision - 1) find { NodeDataTable.nodeId eq node.nodeId }.orderBy(NodeDataTable.createdAt to SortOrder.ASC).toList().get(revision - 1)
} }
@JvmStatic @JvmStatic
fun getRevisions(node: SchematicNode) = useDb { fun getRevisions(node: SchematicNode) =
useDb {
count(NodeDataTable.nodeId eq node.nodeId).toInt() count(NodeDataTable.nodeId eq node.nodeId).toInt()
} }
@JvmStatic @JvmStatic
fun saveFromStream(node: SchematicNode, blob: InputStream, format: SchematicFormat) = useDb { fun saveFromStream(node: SchematicNode, blob: InputStream, format: SchematicFormat) =
useDb {
NodeDataTable.insert { NodeDataTable.insert {
it[NodeDataTable.nodeId] = EntityID(node.getId(), SchematicNodeTable) it[NodeDataTable.nodeId] = EntityID(node.getId(), SchematicNodeTable)
it[NodeDataTable.nodeFormat] = format it[NodeDataTable.nodeFormat] = format
@@ -84,11 +89,13 @@ class NodeData(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
} }
fun schemData(decompress: Boolean) = useDb { fun schemData(decompress: Boolean) =
useDb {
schemData.inputStream.let { if (decompress) GZIPInputStream(it) else it } schemData.inputStream.let { if (decompress) GZIPInputStream(it) else it }
} }
override fun delete() = useDb { super.delete() } override fun delete() =
useDb { super.delete() }
enum class SchematicFormat(val fileEnding: String) { enum class SchematicFormat(val fileEnding: String) {
MCEDIT(".schematic"), MCEDIT(".schematic"),
@@ -44,8 +44,7 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
@JvmStatic @JvmStatic
fun getLink(schem: SchematicNode): String { fun getLink(schem: SchematicNode): String {
if (schem.isDir()) if (schem.isDir()) throw IllegalArgumentException("Cannot get link for directory")
throw IllegalArgumentException("Cannot get link for directory")
val digest = MessageDigest.getInstance("SHA-1") val digest = MessageDigest.getInstance("SHA-1")
digest.update("${Instant.now()}${schem.owner}${schem.nodeId}".toByteArray()) digest.update("${Instant.now()}${schem.owner}${schem.nodeId}".toByteArray())
@@ -53,7 +52,8 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
useDb { useDb {
findByIdAndUpdate(schem.id.value) { findByIdAndUpdate(schem.id.value) {
it.link = hash it.link = hash
} ?: new { }
?: new {
nodeId = schem.id.value nodeId = schem.id.value
link = hash link = hash
} }
@@ -62,7 +62,8 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun get(link: String) = useDb { fun get(link: String) =
useDb {
find { NodeDownloadTable.link eq link }.firstOrNull() find { NodeDownloadTable.link eq link }.firstOrNull()
} }
} }
@@ -71,7 +72,8 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
var link by NodeDownloadTable.link var link by NodeDownloadTable.link
var timestamp by NodeDownloadTable.timestamp.transform({ it.toInstant() }, { Timestamp.from(it) }) var timestamp by NodeDownloadTable.timestamp.transform({ it.toInstant() }, { Timestamp.from(it) })
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
} }
@@ -48,44 +48,54 @@ object NodeMemberTable : CompositeIdTable("NodeMember") {
class NodeMember(id: EntityID<CompositeID>) : CompositeEntity(id) { class NodeMember(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<NodeMember>(NodeMemberTable) { companion object : CompositeEntityClass<NodeMember>(NodeMemberTable) {
@JvmStatic @JvmStatic
fun createNodeMember(node: Int, member: Int): NodeMember = useDb { fun createNodeMember(node: Int, member: Int): NodeMember =
useDb {
NodeMemberTable.insertIgnore { NodeMemberTable.insertIgnore {
it[this.node] = EntityID(node, SchematicNodeTable) it[this.node] = EntityID(node, SchematicNodeTable)
it[this.userId] = EntityID(member, SteamwarUserTable) it[this.userId] = EntityID(member, SteamwarUserTable)
} }
getNodeMember(node, member) ?: throw IllegalStateException("NodeMember not created") getNodeMember(node, member)
?: throw IllegalStateException("NodeMember not created")
} }
@JvmStatic @JvmStatic
fun createNodeMember(node: Int, member: Int, parent: SchematicNode): NodeMember = useDb { fun createNodeMember(node: Int, member: Int, parent: SchematicNode): NodeMember =
useDb {
if (!parent.isDir()) throw IllegalStateException("Parent must be a directory") if (!parent.isDir()) throw IllegalStateException("Parent must be a directory")
NodeMemberTable.insertIgnore { NodeMemberTable.insertIgnore {
it[this.node] = EntityID(node, SchematicNodeTable) it[this.node] = EntityID(node, SchematicNodeTable)
it[this.userId] = EntityID(member, SteamwarUserTable) it[this.userId] = EntityID(member, SteamwarUserTable)
it[NodeMemberTable.parentNode] = parent.getId() it[NodeMemberTable.parentNode] = parent.getId()
} }
getNodeMember(node, member) ?: throw IllegalStateException("NodeMember not created") getNodeMember(node, member)
?: throw IllegalStateException("NodeMember not created")
} }
@JvmStatic @JvmStatic
fun createNodeMember(node: Int, member: SteamwarUser) = createNodeMember(node, member.id.value) fun createNodeMember(node: Int, member: SteamwarUser) =
createNodeMember(node, member.id.value)
@JvmStatic @JvmStatic
fun getNodeMember(node: Int, member: Int) = useDb { fun getNodeMember(node: Int, member: Int) =
useDb {
find { (NodeMemberTable.node eq node) and (NodeMemberTable.userId eq member) }.firstOrNull() find { (NodeMemberTable.node eq node) and (NodeMemberTable.userId eq member) }.firstOrNull()
} }
@JvmStatic @JvmStatic
fun getNodeMember(node: Int, member: SteamwarUser) = getNodeMember(node, member.id.value) fun getNodeMember(node: Int, member: SteamwarUser) =
getNodeMember(node, member.id.value)
@JvmStatic @JvmStatic
fun getNodeMembers(node: Int) = useDb { find { NodeMemberTable.node eq node }.toSet() } fun getNodeMembers(node: Int) =
useDb { find { NodeMemberTable.node eq node }.toSet() }
@JvmStatic @JvmStatic
fun getSchematics(member: Int) = useDb { find { NodeMemberTable.userId eq member }.toSet() } fun getSchematics(member: Int) =
useDb { find { NodeMemberTable.userId eq member }.toSet() }
@JvmStatic @JvmStatic
fun init() = Unit fun init() =
Unit
} }
val node by NodeMemberTable.node.transform({ EntityID(it, SchematicNodeTable) }, { it.value }) val node by NodeMemberTable.node.transform({ EntityID(it, SchematicNodeTable) }, { it.value })
@@ -95,11 +105,13 @@ class NodeMember(id: EntityID<CompositeID>) : CompositeEntity(id) {
{ Optional.ofNullable(it?.value) }) { Optional.ofNullable(it?.value) })
private set private set
fun setParentId(id: Int?) = useDb { fun setParentId(id: Int?) =
useDb {
parent = Optional.ofNullable(id) parent = Optional.ofNullable(id)
} }
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
} }
@@ -47,13 +47,15 @@ object PersonalKitTable: CompositeIdTable("PersonalKit") {
class InternalKit(id: EntityID<CompositeID>) : CompositeEntity(id) { class InternalKit(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<InternalKit>(PersonalKitTable) { companion object : CompositeEntityClass<InternalKit>(PersonalKitTable) {
@JvmStatic @JvmStatic
fun get(userId: Int, gamemode: String) = useDb { fun get(userId: Int, gamemode: String) =
useDb {
find { PersonalKitTable.userId eq userId and (PersonalKitTable.gamemode eq gamemode) } find { PersonalKitTable.userId eq userId and (PersonalKitTable.gamemode eq gamemode) }
.toList() .toList()
} }
@JvmStatic @JvmStatic
fun get(userId: Int, gamemode: String, kitName: String) = useDb { fun get(userId: Int, gamemode: String, kitName: String) =
useDb {
findById(CompositeID { findById(CompositeID {
it[PersonalKitTable.userId] = EntityID(userId, SteamwarUserTable) it[PersonalKitTable.userId] = EntityID(userId, SteamwarUserTable)
it[PersonalKitTable.gamemode] = gamemode it[PersonalKitTable.gamemode] = gamemode
@@ -62,7 +64,8 @@ class InternalKit(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun create(userId: Int, gamemode: String, kitName: String, rawInventory: String, rawArmor: String) = useDb { fun create(userId: Int, gamemode: String, kitName: String, rawInventory: String, rawArmor: String) =
useDb {
new( new(
CompositeID { CompositeID {
it[PersonalKitTable.userId] = EntityID(userId, SteamwarUserTable) it[PersonalKitTable.userId] = EntityID(userId, SteamwarUserTable)
@@ -77,7 +80,8 @@ class InternalKit(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun getKitInUse(userId: Int, gamemode: String) = useDb { fun getKitInUse(userId: Int, gamemode: String) =
useDb {
find { PersonalKitTable.userId eq userId and (PersonalKitTable.gamemode eq gamemode) and (PersonalKitTable.inUse eq true) } find { PersonalKitTable.userId eq userId and (PersonalKitTable.gamemode eq gamemode) and (PersonalKitTable.inUse eq true) }
.firstOrNull() .firstOrNull()
} }
@@ -108,14 +112,16 @@ class InternalKit(id: EntityID<CompositeID>): CompositeEntity(id) {
get() = rawArmor get() = rawArmor
set(value) = useDb { rawArmor = value } set(value) = useDb { rawArmor = value }
fun setDefault() = useDb { fun setDefault() =
useDb {
find { PersonalKitTable.userId eq userID and (PersonalKitTable.gamemode eq gameMode) and (PersonalKitTable.inUse eq true) } find { PersonalKitTable.userId eq userID and (PersonalKitTable.gamemode eq gameMode) and (PersonalKitTable.inUse eq true) }
.filter { it.id.value != this@InternalKit.id.value } .filter { it.id.value != this@InternalKit.id.value }
.forEach { it.inUse = false } .forEach { it.inUse = false }
inUse = true inUse = true
} }
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
} }
@@ -52,13 +52,15 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
val PERMA_TIME: Timestamp = Timestamp.from(Instant.ofEpochSecond(946674800)) val PERMA_TIME: Timestamp = Timestamp.from(Instant.ofEpochSecond(946674800))
@JvmStatic @JvmStatic
fun getPunsihmentOfPlayer(user: Int, type: PunishmentType) = useDb { fun getPunsihmentOfPlayer(user: Int, type: PunishmentType) =
useDb {
find { (PunishmentTable.userId eq user) and (PunishmentTable.type eq type) }.orderBy(PunishmentTable.id to SortOrder.DESC) find { (PunishmentTable.userId eq user) and (PunishmentTable.type eq type) }.orderBy(PunishmentTable.id to SortOrder.DESC)
.firstOrNull() .firstOrNull()
} }
@JvmStatic @JvmStatic
fun getPunishmentsOfPlayer(user: Int) = useDb { fun getPunishmentsOfPlayer(user: Int) =
useDb {
find { find {
PunishmentTable.id inSubQuery PunishmentTable.select(PunishmentTable.id.max()) PunishmentTable.id inSubQuery PunishmentTable.select(PunishmentTable.id.max())
.where { PunishmentTable.userId eq user }.groupBy( .where { PunishmentTable.userId eq user }.groupBy(
@@ -68,13 +70,16 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun getAllPunishmentsOfPlayer(user: Int) = useDb { fun getAllPunishmentsOfPlayer(user: Int) =
useDb {
find { PunishmentTable.userId eq user }.orderBy(PunishmentTable.id to SortOrder.DESC).toList() find { PunishmentTable.userId eq user }.orderBy(PunishmentTable.id to SortOrder.DESC).toList()
} }
@JvmStatic @JvmStatic
fun isPunished(user: SteamwarUser, type: PunishmentType, callback: Consumer<Punishment>): Boolean = useDb { fun isPunished(user: SteamwarUser, type: PunishmentType, callback: Consumer<Punishment>): Boolean =
val punishment = getPunsihmentOfPlayer(user.id.value, type) ?: return@useDb false useDb {
val punishment = getPunsihmentOfPlayer(user.id.value, type)
?: return@useDb false
if (punishment.isCurrent()) { if (punishment.isCurrent()) {
callback.accept(punishment) callback.accept(punishment)
@@ -92,7 +97,8 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
reason: String, reason: String,
endTime: Timestamp, endTime: Timestamp,
perma: Boolean perma: Boolean
) = useDb { ) =
useDb {
new { new {
this.userId = user this.userId = user
this.punisher = executor this.punisher = executor
@@ -120,9 +126,11 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
var reason by PunishmentTable.reason var reason by PunishmentTable.reason
private set private set
fun isPerma() = perma fun isPerma() =
perma
fun isCurrent() = perma || endTime.after(Date()) fun isCurrent() =
perma || endTime.after(Date())
enum class PunishmentType( enum class PunishmentType(
val teamMessage: String?, val teamMessage: String?,
@@ -185,6 +193,7 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
), ),
Note("NOTE_TEAM", null, null, null, null, UserPerm.PUNISHMENTS, true); Note("NOTE_TEAM", null, null, null, null, UserPerm.PUNISHMENTS, true);
fun isMulti() = multi fun isMulti() =
multi
} }
} }
@@ -43,7 +43,8 @@ object RefereeTable: CompositeIdTable("Referee") {
class Referee(id: EntityID<CompositeID>) : CompositeEntity(id) { class Referee(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<Referee>(RefereeTable) { companion object : CompositeEntityClass<Referee>(RefereeTable) {
@JvmStatic @JvmStatic
fun add(eventId: Int, userId: Int) = useDb { fun add(eventId: Int, userId: Int) =
useDb {
new { new {
this.eventID = eventId this.eventID = eventId
this.userID = userId this.userID = userId
@@ -51,12 +52,14 @@ class Referee(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun remove(eventId: Int, userId: Int) = useDb { fun remove(eventId: Int, userId: Int) =
useDb {
find { (RefereeTable.eventId eq eventId) and (RefereeTable.userId eq userId) }.firstOrNull()?.delete() find { (RefereeTable.eventId eq eventId) and (RefereeTable.userId eq userId) }.firstOrNull()?.delete()
} }
@JvmStatic @JvmStatic
fun get(event: Int) = useDb { fun get(event: Int) =
useDb {
find { RefereeTable.eventId eq event }.map { it.userID }.toSet() find { RefereeTable.eventId eq event }.map { it.userID }.toSet()
} }
} }
@@ -40,10 +40,12 @@ class SWException {
val serverName = File(cwd).name val serverName = File(cwd).name
@JvmStatic @JvmStatic
fun init() = Unit fun init() =
Unit
@JvmStatic @JvmStatic
fun log(message: String, stacktrace: String) = useDb { fun log(message: String, stacktrace: String) =
useDb {
ExceptionTable.insert { ExceptionTable.insert {
it[ExceptionTable.server] = serverName it[ExceptionTable.server] = serverName
it[ExceptionTable.message] = generateMessage(message) it[ExceptionTable.message] = generateMessage(message)
@@ -54,7 +56,8 @@ class SWException {
} }
@JvmStatic @JvmStatic
fun logGetId(message: String, stacktrace: String) = useDb { fun logGetId(message: String, stacktrace: String) =
useDb {
ExceptionTable.insertAndGetId { ExceptionTable.insertAndGetId {
it[ExceptionTable.server] = serverName it[ExceptionTable.server] = serverName
it[ExceptionTable.message] = generateMessage(message) it[ExceptionTable.message] = generateMessage(message)
@@ -58,12 +58,15 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
val tabCache = mutableMapOf<Int, MutableMap<String, List<String>>>() val tabCache = mutableMapOf<Int, MutableMap<String, List<String>>>()
@JvmStatic @JvmStatic
fun clear() = tabCache.clear() fun clear() =
tabCache.clear()
private fun List<SchematicNode>.mapToIds(): Map<Int, SchematicNode> = this.associateBy { it.nodeId } private fun List<SchematicNode>.mapToIds(): Map<Int, SchematicNode> =
this.associateBy { it.nodeId }
@JvmStatic @JvmStatic
fun getAll(user: SteamwarUser) = fromSql( fun getAll(user: SteamwarUser) =
fromSql(
"WITH RECURSIVE Nodes AS (SELECT NodeId, ParentId as ParentNode FROM NodeMember WHERE UserId = ? UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?), RSN AS ( SELECT NodeId, ParentNode FROM Nodes UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN, RSN WHERE SN.ParentNode = RSN.NodeId ) SELECT SN.* FROM RSN INNER JOIN SchematicNode SN ON RSN.NodeId = SN.NodeId", "WITH RECURSIVE Nodes AS (SELECT NodeId, ParentId as ParentNode FROM NodeMember WHERE UserId = ? UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?), RSN AS ( SELECT NodeId, ParentNode FROM Nodes UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN, RSN WHERE SN.ParentNode = RSN.NodeId ) SELECT SN.* FROM RSN INNER JOIN SchematicNode SN ON RSN.NodeId = SN.NodeId",
listOf( listOf(
IntegerColumnType() to user.getId(), IntegerColumnType() to user.getId(),
@@ -73,10 +76,12 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
) )
@JvmStatic @JvmStatic
fun getAllMap(user: SteamwarUser) = getAll(user).mapToIds() fun getAllMap(user: SteamwarUser) =
getAll(user).mapToIds()
@JvmStatic @JvmStatic
fun list(user: SteamwarUser, schematicId: Int?) = fromSql( fun list(user: SteamwarUser, schematicId: Int?) =
fromSql(
"SELECT SchematicNode.NodeId, NodeOwner, NodeName, NM.ParentId AS ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode INNER JOIN NodeMember NM on SchematicNode.NodeId = NM.NodeId WHERE NM.ParentId <=> ? AND NM.UserId = ? UNION ALL SELECT SchematicNode.NodeId, NodeOwner, NodeName, ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode WHERE (? IS NULL AND ParentNode IS NULL AND NodeOwner = ?) OR (? IS NOT NULL AND ParentNode = ?) ORDER BY NodeName", "SELECT SchematicNode.NodeId, NodeOwner, NodeName, NM.ParentId AS ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode INNER JOIN NodeMember NM on SchematicNode.NodeId = NM.NodeId WHERE NM.ParentId <=> ? AND NM.UserId = ? UNION ALL SELECT SchematicNode.NodeId, NodeOwner, NodeName, ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode WHERE (? IS NULL AND ParentNode IS NULL AND NodeOwner = ?) OR (? IS NOT NULL AND ParentNode = ?) ORDER BY NodeName",
listOf( listOf(
IntegerColumnType() to schematicId, IntegerColumnType() to schematicId,
@@ -89,7 +94,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
) )
@JvmStatic @JvmStatic
fun byParentName(user: SteamwarUser, schematicId: Int?, name: String) = fromSql( fun byParentName(user: SteamwarUser, schematicId: Int?, name: String) =
fromSql(
"SELECT SchematicNode.NodeId, NodeOwner, NodeName, NM.ParentId AS ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode INNER JOIN NodeMember NM on SchematicNode.NodeId = NM.NodeId WHERE NM.ParentId <=> ? AND NM.UserId = ? AND SchematicNode.NodeName = ? UNION ALL SELECT SchematicNode.NodeId, NodeOwner, NodeName, ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode WHERE ((? IS NULL AND ParentNode IS NULL AND NodeOwner = ?) OR (? IS NOT NULL AND ParentNode = ?)) AND NodeName = ?", "SELECT SchematicNode.NodeId, NodeOwner, NodeName, NM.ParentId AS ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode INNER JOIN NodeMember NM on SchematicNode.NodeId = NM.NodeId WHERE NM.ParentId <=> ? AND NM.UserId = ? AND SchematicNode.NodeName = ? UNION ALL SELECT SchematicNode.NodeId, NodeOwner, NodeName, ParentNode, LastUpdate, NodeItem, NodeType, NodeRank, Config FROM SchematicNode WHERE ((? IS NULL AND ParentNode IS NULL AND NodeOwner = ?) OR (? IS NOT NULL AND ParentNode = ?)) AND NodeName = ?",
listOf( listOf(
IntegerColumnType() to schematicId, IntegerColumnType() to schematicId,
@@ -104,7 +110,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
).firstOrNull() ).firstOrNull()
@JvmStatic @JvmStatic
fun accessibleByUserType(user: SteamwarUser, type: SchematicType) = fromSql( fun accessibleByUserType(user: SteamwarUser, type: SchematicType) =
fromSql(
"WITH RECURSIVE Nodes AS (SELECT NodeId, ParentId as ParentNode FROM NodeMember WHERE UserId = ? UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?), RSN AS ( SELECT NodeId, ParentNode FROM Nodes UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN, RSN WHERE SN.ParentNode = RSN.NodeId ) SELECT SN.*, ? AS EffectiveOwner FROM RSN INNER JOIN SchematicNode SN ON RSN.NodeId = SN.NodeId WHERE NodeType = ?", "WITH RECURSIVE Nodes AS (SELECT NodeId, ParentId as ParentNode FROM NodeMember WHERE UserId = ? UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?), RSN AS ( SELECT NodeId, ParentNode FROM Nodes UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN, RSN WHERE SN.ParentNode = RSN.NodeId ) SELECT SN.*, ? AS EffectiveOwner FROM RSN INNER JOIN SchematicNode SN ON RSN.NodeId = SN.NodeId WHERE NodeType = ?",
listOf( listOf(
IntegerColumnType() to user.getId(), IntegerColumnType() to user.getId(),
@@ -119,7 +126,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
accessibleByUserType(user, type).mapToIds() accessibleByUserType(user, type).mapToIds()
@JvmStatic @JvmStatic
fun schematicAccessibleForUser(user: SteamwarUser, schematicId: Int?) = fromSql( fun schematicAccessibleForUser(user: SteamwarUser, schematicId: Int?) =
fromSql(
"WITH RECURSIVE Nodes AS (SELECT NodeId, ParentId as ParentNode FROM NodeMember WHERE UserId = ? UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?), RSN AS ( SELECT NodeId, ParentNode FROM Nodes UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN, RSN WHERE SN.ParentNode = RSN.NodeId ) SELECT SN.*, ? AS EffectiveOwner FROM RSN INNER JOIN SchematicNode SN ON RSN.NodeId = SN.NodeId WHERE SN.NodeId = ?", "WITH RECURSIVE Nodes AS (SELECT NodeId, ParentId as ParentNode FROM NodeMember WHERE UserId = ? UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?), RSN AS ( SELECT NodeId, ParentNode FROM Nodes UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN, RSN WHERE SN.ParentNode = RSN.NodeId ) SELECT SN.*, ? AS EffectiveOwner FROM RSN INNER JOIN SchematicNode SN ON RSN.NodeId = SN.NodeId WHERE SN.NodeId = ?",
listOf( listOf(
IntegerColumnType() to user.getId(), IntegerColumnType() to user.getId(),
@@ -131,7 +139,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
).isNotEmpty() ).isNotEmpty()
@JvmStatic @JvmStatic
fun accessibleByUserTypeParent(user: SteamwarUser, type: SchematicType, parentId: Int?) = fromSql( fun accessibleByUserTypeParent(user: SteamwarUser, type: SchematicType, parentId: Int?) =
fromSql(
"WITH RECURSIVE RSASN AS(WITH RECURSIVE RSAN AS (WITH RSANH AS (WITH RECURSIVE RSA AS (SELECT SN.NodeId, NM.ParentId FROM SchematicNode SN LEFT JOIN NodeMember NM on SN.NodeId = NM.NodeId WHERE NM.UserId = ? UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN INNER JOIN RSA ON RSA.NodeId = SN.ParentNode) SELECT * FROM RSA UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?) SELECT * FROM RSANH UNION SELECT SN.NodeId, SN.ParentNode FROM RSANH JOIN SchematicNode SN ON SN.ParentNode = RSANH.NodeId) SELECT RSAN.NodeId, RSAN.ParentId FROM RSAN JOIN SchematicNode SN ON SN.NodeId = RSAN.NodeId WHERE NodeType = ? UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN JOIN RSASN ON SN.NodeId = RSASN.ParentId) SELECT SN.*, ? as EffectiveOwner, RSASN.ParentId AS ParentNode FROM RSASN JOIN SchematicNode SN ON SN.NodeId = RSASN.NodeId WHERE RSASN.ParentId <=> ? ORDER BY NodeName", "WITH RECURSIVE RSASN AS(WITH RECURSIVE RSAN AS (WITH RSANH AS (WITH RECURSIVE RSA AS (SELECT SN.NodeId, NM.ParentId FROM SchematicNode SN LEFT JOIN NodeMember NM on SN.NodeId = NM.NodeId WHERE NM.UserId = ? UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN INNER JOIN RSA ON RSA.NodeId = SN.ParentNode) SELECT * FROM RSA UNION SELECT NodeId, ParentNode FROM SchematicNode WHERE NodeOwner = ?) SELECT * FROM RSANH UNION SELECT SN.NodeId, SN.ParentNode FROM RSANH JOIN SchematicNode SN ON SN.ParentNode = RSANH.NodeId) SELECT RSAN.NodeId, RSAN.ParentId FROM RSAN JOIN SchematicNode SN ON SN.NodeId = RSAN.NodeId WHERE NodeType = ? UNION SELECT SN.NodeId, SN.ParentNode FROM SchematicNode SN JOIN RSASN ON SN.NodeId = RSASN.ParentId) SELECT SN.*, ? as EffectiveOwner, RSASN.ParentId AS ParentNode FROM RSASN JOIN SchematicNode SN ON SN.NodeId = RSASN.NodeId WHERE RSASN.ParentId <=> ? ORDER BY NodeName",
listOf( listOf(
IntegerColumnType() to user.getId(), IntegerColumnType() to user.getId(),
@@ -144,12 +153,14 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
@JvmStatic @JvmStatic
@Deprecated("Use byId") @Deprecated("Use byId")
fun byIdAndUser(ignored: SteamwarUser, id: Int) = useDb { fun byIdAndUser(ignored: SteamwarUser, id: Int) =
useDb {
findById(id) findById(id)
} }
@JvmStatic @JvmStatic
fun parentsOfNode(user: SteamwarUser, id: Int) = fromSql( fun parentsOfNode(user: SteamwarUser, id: Int) =
fromSql(
""" """
WITH RECURSIVE WITH RECURSIVE
ESN_R AS ( ESN_R AS (
@@ -242,7 +253,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
) )
@JvmStatic @JvmStatic
fun createSchematic(owner: Int, name: String, parent: Int?) = createSchematicNode( fun createSchematic(owner: Int, name: String, parent: Int?) =
createSchematicNode(
owner, name, parent, owner, name, parent,
SchematicType.Normal.toDB(), "" SchematicType.Normal.toDB(), ""
) )
@@ -252,7 +264,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
createSchematicNode(owner, name, parent, null, "") createSchematicNode(owner, name, parent, null, "")
@JvmStatic @JvmStatic
fun createSchematicNode(owner: Int, name: String, parent: Int?, type: String?, item: String) = useDb { fun createSchematicNode(owner: Int, name: String, parent: Int?, type: String?, item: String) =
useDb {
val id = SchematicNodeTable.insertAndGetId { val id = SchematicNodeTable.insertAndGetId {
it[this.owner] = EntityID(owner, SteamwarUserTable) it[this.owner] = EntityID(owner, SteamwarUserTable)
it[this.name] = name it[this.name] = name
@@ -261,14 +274,17 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
it[this.item] = item it[this.item] = item
it[this.type] = type it[this.type] = type
} }
return@useDb findById(id) ?: throw IllegalStateException("SchematicNode $id not found") return@useDb findById(id)
?: throw IllegalStateException("SchematicNode $id not found")
} }
@JvmStatic @JvmStatic
fun byId(id: Int) = useDb { findById(id) } fun byId(id: Int) =
useDb { findById(id) }
@JvmStatic @JvmStatic
fun getSchematicNode(owner: Int, name: String, parent: Int?) = useDb { fun getSchematicNode(owner: Int, name: String, parent: Int?) =
useDb {
find { (SchematicNodeTable.owner eq owner) and (SchematicNodeTable.name eq name) and (SchematicNodeTable.parent eq parent) }.firstOrNull() find { (SchematicNodeTable.owner eq owner) and (SchematicNodeTable.name eq name) and (SchematicNodeTable.parent eq parent) }.firstOrNull()
} }
@@ -277,37 +293,44 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
getSchematicNode(owner, name, parent.nodeId) getSchematicNode(owner, name, parent.nodeId)
@JvmStatic @JvmStatic
fun getSchematicNodeInNode(parent: Int?) = useDb { fun getSchematicNodeInNode(parent: Int?) =
useDb {
find { (SchematicNodeTable.parent eq parent) }.orderBy(SchematicNodeTable.name to SortOrder.ASC).toList() find { (SchematicNodeTable.parent eq parent) }.orderBy(SchematicNodeTable.name to SortOrder.ASC).toList()
} }
@JvmStatic @JvmStatic
fun getSchematicNodeInNode(parent: SchematicNode) = getSchematicNodeInNode(parent.nodeId) fun getSchematicNodeInNode(parent: SchematicNode) =
getSchematicNodeInNode(parent.nodeId)
@JvmStatic @JvmStatic
fun getSchematicNode(name: String, parent: Int?) = useDb { fun getSchematicNode(name: String, parent: Int?) =
useDb {
find { (SchematicNodeTable.name eq name) and (SchematicNodeTable.parent eq parent) }.firstOrNull() find { (SchematicNodeTable.name eq name) and (SchematicNodeTable.parent eq parent) }.firstOrNull()
} }
@JvmStatic @JvmStatic
fun getSchematicNode(id: Int) = byId(id) fun getSchematicNode(id: Int) =
byId(id)
@JvmStatic @JvmStatic
fun getAllAccessibleSchematicsOfType(user: Int, type: String) = fun getAllAccessibleSchematicsOfType(user: Int, type: String) =
accessibleByUserType(SteamwarUser.byId(user)!!, SchematicType.fromDB(type)!!) accessibleByUserType(SteamwarUser.byId(user)!!, SchematicType.fromDB(type)!!)
@JvmStatic @JvmStatic
fun getAllSchematicsAccessibleByUser(user: Int) = getAll(SteamwarUser.byId(user)!!) fun getAllSchematicsAccessibleByUser(user: Int) =
getAll(SteamwarUser.byId(user)!!)
@JvmStatic @JvmStatic
fun getAllSchematicsOfType(owner: Int, type: String) = useDb { fun getAllSchematicsOfType(owner: Int, type: String) =
useDb {
find { (SchematicNodeTable.owner eq owner) and (SchematicNodeTable.type eq type) }.orderBy( find { (SchematicNodeTable.owner eq owner) and (SchematicNodeTable.type eq type) }.orderBy(
SchematicNodeTable.name to SortOrder.ASC SchematicNodeTable.name to SortOrder.ASC
).toList() ).toList()
} }
@JvmStatic @JvmStatic
fun getAllSchematicsOfType(type: SchematicType) = useDb { fun getAllSchematicsOfType(type: SchematicType) =
useDb {
find { (SchematicNodeTable.type eq type.toDB()) }.orderBy(SchematicNodeTable.name to SortOrder.ASC).toList() find { (SchematicNodeTable.type eq type.toDB()) }.orderBy(SchematicNodeTable.name to SortOrder.ASC).toList()
} }
@@ -354,7 +377,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun invalidSchemName(layers: Array<String>) = layers.any { fun invalidSchemName(layers: Array<String>) =
layers.any {
it.isEmpty() || FORBIDDEN_CHARS.any { c -> c in it } || FORBIDDEN_NAMES.any { n -> n == it.lowercase() } it.isEmpty() || FORBIDDEN_CHARS.any { c -> c in it } || FORBIDDEN_NAMES.any { n -> n == it.lowercase() }
} }
@@ -372,7 +396,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
val list = mutableListOf<String>() val list = mutableListOf<String>()
if (s.contains("/")) { if (s.contains("/")) {
val preTab = s.take(s.lastIndexOf("/") + 1) val preTab = s.take(s.lastIndexOf("/") + 1)
val pa = getNodeFromPath(user, preTab) ?: return mutableListOf() val pa = getNodeFromPath(user, preTab)
?: return mutableListOf()
val nodes: List<SchematicNode> = list(user, pa.getId()) val nodes: List<SchematicNode> = list(user, pa.getId())
val br = pa.generateBreadcrumbs(user) val br = pa.generateBreadcrumbs(user)
nodes.forEach(Consumer { node: SchematicNode? -> list.add((if (sws) "/" else "") + br + node!!.name + (if (node.isDir()) "/" else "")) }) nodes.forEach(Consumer { node: SchematicNode? -> list.add((if (sws) "/" else "") + br + node!!.name + (if (node.isDir()) "/" else "")) })
@@ -416,16 +441,24 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
} }
private var nodeType by SchematicNodeTable.type private var nodeType by SchematicNodeTable.type
var schemtype: SchematicType var schemtype: SchematicType
get() = checkDir { SchematicType.fromDB(nodeType!!) ?: SchematicType.Normal } get() = checkDir {
SchematicType.fromDB(nodeType!!)
?: SchematicType.Normal
}
set(value) = checkDir { useDb { nodeType = value.toDB() } } set(value) = checkDir { useDb { nodeType = value.toDB() } }
var config by SchematicNodeTable.config var config by SchematicNodeTable.config
val members: Set<NodeMember> by lazy { NodeMember.getNodeMembers(nodeId) } val members: Set<NodeMember> by lazy { NodeMember.getNodeMembers(nodeId) }
private lateinit var breadcrumbs: String private lateinit var breadcrumbs: String
fun getFileEnding(): String = checkDir { NodeData.getLatest(this)!!.nodeFormat.fileEnding } fun getFileEnding(): String =
fun getId() = nodeId checkDir { NodeData.getLatest(this)!!.nodeFormat.fileEnding }
fun isDir() = nodeType == null
fun getId() =
nodeId
fun isDir() =
nodeType == null
private fun <T> checkDir(block: () -> T): T { private fun <T> checkDir(block: () -> T): T {
if (isDir()) { if (isDir()) {
@@ -435,17 +468,29 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
return block() return block()
} }
fun replaceColor() = getConfig(ConfigFlags.REPLACE_COLOR) fun replaceColor() =
fun setReplaceColor(value: Boolean) = setConfig(ConfigFlags.REPLACE_COLOR, value) getConfig(ConfigFlags.REPLACE_COLOR)
fun allowReplay() = getConfig(ConfigFlags.ALLOW_REPLAY) fun setReplaceColor(value: Boolean) =
fun setAllowReplay(value: Boolean) = setConfig(ConfigFlags.ALLOW_REPLAY, value) setConfig(ConfigFlags.REPLACE_COLOR, value)
fun isPrepared() = getConfig(ConfigFlags.IS_PREPARED) fun allowReplay() =
fun setPrepared(value: Boolean) = setConfig(ConfigFlags.IS_PREPARED, value) getConfig(ConfigFlags.ALLOW_REPLAY)
fun getConfig(flag: ConfigFlags) = config and (1 shl flag.ordinal) != 0 fun setAllowReplay(value: Boolean) =
fun setConfig(flag: ConfigFlags, value: Boolean) = useDb { setConfig(ConfigFlags.ALLOW_REPLAY, value)
fun isPrepared() =
getConfig(ConfigFlags.IS_PREPARED)
fun setPrepared(value: Boolean) =
setConfig(ConfigFlags.IS_PREPARED, value)
fun getConfig(flag: ConfigFlags) =
config and (1 shl flag.ordinal) != 0
fun setConfig(flag: ConfigFlags, value: Boolean) =
useDb {
config = if (value) { config = if (value) {
config or (1 shl flag.ordinal) config or (1 shl flag.ordinal)
} else { } else {
@@ -453,11 +498,13 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
} }
} }
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
override fun hashCode() = nodeId override fun hashCode() =
nodeId
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (other !is SchematicNode) return false if (other !is SchematicNode) return false
@@ -471,7 +518,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
return breadcrumbs return breadcrumbs
} }
fun generateBreadcrumbs(split: String, user: SteamwarUser): String = useDb { fun generateBreadcrumbs(split: String, user: SteamwarUser): String =
useDb {
val builder: StringBuilder = StringBuilder(name) val builder: StringBuilder = StringBuilder(name)
if (isDir()) { if (isDir()) {
builder.append(split) builder.append(split)
@@ -481,7 +529,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
currentNode = currentNode currentNode = currentNode
.let { .let {
NodeMember.getNodeMember(it.nodeId, user.getId()) NodeMember.getNodeMember(it.nodeId, user.getId())
?.parent?.orElse(null) ?: it.parent ?.parent?.orElse(null)
?: it.parent
} }
?.let { findById(it) } ?.let { findById(it) }
?.also { ?.also {
@@ -491,7 +540,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
return@useDb builder.toString() return@useDb builder.toString()
} }
fun generateBreadcrumbsMap(user: SteamwarUser): List<Pair<String, Int>> = useDb { fun generateBreadcrumbsMap(user: SteamwarUser): List<Pair<String, Int>> =
useDb {
val map = mutableListOf<Pair<String, Int>>() val map = mutableListOf<Pair<String, Int>>()
var currentNode: SchematicNode? = this@SchematicNode var currentNode: SchematicNode? = this@SchematicNode
while (currentNode != null) { while (currentNode != null) {
@@ -501,14 +551,16 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
} }
.let { .let {
NodeMember.getNodeMember(it.nodeId, user.getId()) NodeMember.getNodeMember(it.nodeId, user.getId())
?.parent?.orElse(null) ?: it.parent ?.parent?.orElse(null)
?: it.parent
} }
?.let { findById(it) } ?.let { findById(it) }
} }
return@useDb map return@useDb map
} }
fun accessibleByUser(user: SteamwarUser) = schematicAccessibleForUser(user, nodeId) fun accessibleByUser(user: SteamwarUser) =
schematicAccessibleForUser(user, nodeId)
enum class ConfigFlags { enum class ConfigFlags {
REPLACE_COLOR, REPLACE_COLOR,
+13 -6
View File
@@ -40,15 +40,18 @@ object ScriptTable: IntIdTable("Script") {
class Script(id: EntityID<Int>) : IntEntity(id) { class Script(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Script>(ScriptTable) { companion object : IntEntityClass<Script>(ScriptTable) {
@JvmStatic @JvmStatic
fun byId(id: Int) = useDb { findById(id) } fun byId(id: Int) =
useDb { findById(id) }
@JvmStatic @JvmStatic
fun get(user: SteamwarUser, name: String) = useDb { fun get(user: SteamwarUser, name: String) =
useDb {
find { ScriptTable.userId eq user.id and (ScriptTable.name eq name) }.firstOrNull() find { ScriptTable.userId eq user.id and (ScriptTable.name eq name) }.firstOrNull()
} }
@JvmStatic @JvmStatic
fun create(user: SteamwarUser, name: String, code: String) = useDb { fun create(user: SteamwarUser, name: String, code: String) =
useDb {
new { new {
this.userId = user.id.value this.userId = user.id.value
this.scriptName = name this.scriptName = name
@@ -57,12 +60,15 @@ class Script(id: EntityID<Int>) : IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun list(user: SteamwarUser) = useDb { fun list(user: SteamwarUser) =
useDb {
find { ScriptTable.userId eq user.id }.toList() find { ScriptTable.userId eq user.id }.toList()
} }
} }
fun getId() = id.value fun getId() =
id.value
var userId by ScriptTable.userId.transform({ EntityID(it, SteamwarUserTable) }, { it.value }) var userId by ScriptTable.userId.transform({ EntityID(it, SteamwarUserTable) }, { it.value })
private var scriptName by ScriptTable.name private var scriptName by ScriptTable.name
private var scriptCode by ScriptTable.code private var scriptCode by ScriptTable.code
@@ -75,5 +81,6 @@ class Script(id: EntityID<Int>) : IntEntity(id) {
get() = scriptCode get() = scriptCode
set(value) = useDb { scriptCode = value } set(value) = useDb { scriptCode = value }
override fun delete() = useDb { super.delete() } override fun delete() =
useDb { super.delete() }
} }
@@ -35,7 +35,8 @@ object SessionTable: Table("Session") {
object Session { object Session {
@JvmStatic @JvmStatic
fun insertSession(userId: Int, startTime: Timestamp) = useDb { fun insertSession(userId: Int, startTime: Timestamp) =
useDb {
SessionTable.insert { SessionTable.insert {
it[SessionTable.userId] = EntityID(userId, SteamwarUserTable) it[SessionTable.userId] = EntityID(userId, SteamwarUserTable)
it[SessionTable.startTime] = startTime.toInstant() it[SessionTable.startTime] = startTime.toInstant()
@@ -77,16 +77,24 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun byId(id: Int) = byId[id] ?: useDb { findById(id)?.also { cache(it) } } fun byId(id: Int) =
byId[id]
?: useDb { findById(id)?.also { cache(it) } }
@JvmStatic @JvmStatic
fun get(uuid: UUID) = byUUID[uuid] ?: useDb { find { SteamwarUserTable.uuid eq uuid.toString() }.firstOrNull()?.also { cache(it) } } fun get(uuid: UUID) =
byUUID[uuid]
?: useDb { find { SteamwarUserTable.uuid eq uuid.toString() }.firstOrNull()?.also { cache(it) } }
@JvmStatic @JvmStatic
fun get(discordId: Long) = byDiscordId[discordId] ?: useDb { find { SteamwarUserTable.discordId eq discordId }.firstOrNull()?.also { cache(it) } } fun get(discordId: Long) =
byDiscordId[discordId]
?: useDb { find { SteamwarUserTable.discordId eq discordId }.firstOrNull()?.also { cache(it) } }
@JvmStatic @JvmStatic
fun get(username: String) = byUsername[username] ?: useDb { find { SteamwarUserTable.username eq username }.firstOrNull()?.also { cache(it) } } fun get(username: String) =
byUsername[username]
?: useDb { find { SteamwarUserTable.username eq username }.firstOrNull()?.also { cache(it) } }
private fun cache(user: SteamwarUser) { private fun cache(user: SteamwarUser) {
byId[user.getId()] = user byId[user.getId()] = user
@@ -116,27 +124,33 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
} }
newPlayer.accept(uuid) newPlayer.accept(uuid)
get(uuid) ?: error("User $uuid not found after creation!") get(uuid)
?: error("User $uuid not found after creation!")
} }
} }
@JvmStatic @JvmStatic
fun getUsersWithPerm(perm: UserPerm) = useDb { fun getUsersWithPerm(perm: UserPerm) =
useDb {
UserPermTable.join(SteamwarUserTable, JoinType.INNER, UserPermTable.user, SteamwarUserTable.id) UserPermTable.join(SteamwarUserTable, JoinType.INNER, UserPermTable.user, SteamwarUserTable.id)
.select(SteamwarUserTable.fields).where { UserPermTable.perm eq perm }.map { wrapRow(it) } .select(SteamwarUserTable.fields).where { UserPermTable.perm eq perm }.map { wrapRow(it) }
} }
@JvmStatic @JvmStatic
fun getServerTeam() = useDb { listOf( fun getServerTeam() =
useDb {
listOf(
getUsersWithPerm(UserPerm.PREFIX_ADMIN), getUsersWithPerm(UserPerm.PREFIX_ADMIN),
getUsersWithPerm(UserPerm.PREFIX_DEVELOPER), getUsersWithPerm(UserPerm.PREFIX_DEVELOPER),
getUsersWithPerm(UserPerm.PREFIX_MODERATOR), getUsersWithPerm(UserPerm.PREFIX_MODERATOR),
getUsersWithPerm(UserPerm.PREFIX_SUPPORTER), getUsersWithPerm(UserPerm.PREFIX_SUPPORTER),
getUsersWithPerm(UserPerm.PREFIX_BUILDER), getUsersWithPerm(UserPerm.PREFIX_BUILDER),
).flatten() } ).flatten()
}
@JvmStatic @JvmStatic
fun getTeam(teamId: Int) = useDb { fun getTeam(teamId: Int) =
useDb {
find { SteamwarUserTable.team eq teamId }.toList() find { SteamwarUserTable.team eq teamId }.toList()
} }
@@ -167,10 +181,15 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
set(value) = useDb { set(value) = useDb {
leaderInternal = value leaderInternal = value
} }
fun isLeader() = leader
fun isLeader() =
leader
var locale: Locale by SteamwarUserTable.locale var locale: Locale by SteamwarUserTable.locale
.transform({ it.toLanguageTag() }, { it?.let { Locale.forLanguageTag(it) } ?: Locale.ENGLISH }) .transform({ it.toLanguageTag() }, {
it?.let { Locale.forLanguageTag(it) }
?: Locale.ENGLISH
})
var manualLocale by SteamwarUserTable.manualLocale var manualLocale by SteamwarUserTable.manualLocale
var bedrock by SteamwarUserTable.bedrock var bedrock by SteamwarUserTable.bedrock
private var passwordInternal by SteamwarUserTable.password private var passwordInternal by SteamwarUserTable.password
@@ -200,13 +219,22 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
private val punishments by lazy { Punishment.getPunishmentsOfPlayer(id.value) } private val punishments by lazy { Punishment.getPunishmentsOfPlayer(id.value) }
private val perms by lazy { UserPerm.getPerms(id.value) } private val perms by lazy { UserPerm.getPerms(id.value) }
private val prefix by lazy { perms.firstOrNull { UserPerm.prefixes.containsKey(it) }?.let { UserPerm.prefixes[it]} ?: UserPerm.emptyPrefix } private val prefix by lazy {
perms.firstOrNull { UserPerm.prefixes.containsKey(it) }?.let { UserPerm.prefixes[it] }
?: UserPerm.emptyPrefix
}
fun getUUID(): UUID = uuid fun getUUID(): UUID =
fun getId() = id.value uuid
fun getPunishment(punishment: Punishment.PunishmentType) = punishments[punishment] fun getId() =
fun isPunished(punishment: Punishment.PunishmentType) = getPunishment(punishment) id.value
fun getPunishment(punishment: Punishment.PunishmentType) =
punishments[punishment]
fun isPunished(punishment: Punishment.PunishmentType) =
getPunishment(punishment)
?.let { ?.let {
if (!it.isCurrent()) { if (!it.isCurrent()) {
if (punishment == Punishment.PunishmentType.Ban) { if (punishment == Punishment.PunishmentType.Ban) {
@@ -217,39 +245,54 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
} }
return@let true return@let true
} ?: false }
?: false
fun hasPerm(perm: UserPerm) = perms.contains(perm) fun hasPerm(perm: UserPerm) =
fun perms() = perms perms.contains(perm)
fun prefix() = prefix
fun getOnlinetime() = useDb { fun perms() =
perms
fun prefix() =
prefix
fun getOnlinetime() =
useDb {
exec("SELECT SUM(UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime)) as Playtime FROM Session WHERE UserID = ${this@SteamwarUser.id.value}") { rs -> exec("SELECT SUM(UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime)) as Playtime FROM Session WHERE UserID = ${this@SteamwarUser.id.value}") { rs ->
return@exec if (rs.next()) { return@exec if (rs.next()) {
rs.getBigDecimal("Playtime").toDouble() rs.getBigDecimal("Playtime").toDouble()
} else { } else {
0.0 0.0
} }
} ?: 0.0 }
?: 0.0
} }
fun getFirstjoin() = useDb { fun getFirstjoin() =
useDb {
exec("SELECT MIN(StartTime) AS FirstJoin FROM Session WHERE UserID = ${this@SteamwarUser.id.value}") { rs -> exec("SELECT MIN(StartTime) AS FirstJoin FROM Session WHERE UserID = ${this@SteamwarUser.id.value}") { rs ->
return@exec if (rs.next()) { return@exec if (rs.next()) {
rs.getTimestamp("FirstJoin") rs.getTimestamp("FirstJoin")
} else { null } } else {
null
}
} }
} }
fun getLastOnline() = useDb { fun getLastOnline() =
useDb {
exec("SELECT MAX(EndTime) AS LastOnline FROM Session WHERE UserID = ${this@SteamwarUser.id.value}") { rs -> exec("SELECT MAX(EndTime) AS LastOnline FROM Session WHERE UserID = ${this@SteamwarUser.id.value}") { rs ->
return@exec if (rs.next()) { return@exec if (rs.next()) {
rs.getTimestamp("LastOnline") rs.getTimestamp("LastOnline")
} else { null } } else {
null
}
} }
} }
fun punish(punishment: Punishment.PunishmentType, time: Timestamp, reason: String, from: Int, perma: Boolean) = useDb { fun punish(punishment: Punishment.PunishmentType, time: Timestamp, reason: String, from: Int, perma: Boolean) =
useDb {
punishments.remove(punishment) punishments.remove(punishment)
punishments[punishment] = Punishment.createPunishment(this@SteamwarUser.id.value, from, punishment, reason, time, perma) punishments[punishment] = Punishment.createPunishment(this@SteamwarUser.id.value, from, punishment, reason, time, perma)
} }
@@ -282,7 +325,8 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
return hash.contentEquals(generateHash(password, salt)) return hash.contentEquals(generateHash(password, salt))
} }
fun hasPassword() = password != null fun hasPassword() =
password != null
fun generateHash(password: String, salt: ByteArray): ByteArray = fun generateHash(password: String, salt: ByteArray): ByteArray =
PBEKeySpec(password.toCharArray(), salt, 65536, 512).let { factory.generateSecret(it).encoded } PBEKeySpec(password.toCharArray(), salt, 65536, 512).let { factory.generateSecret(it).encoded }
+15 -7
View File
@@ -39,19 +39,24 @@ class Team(id: EntityID<Int>) : IntEntity(id) {
private val teamCache = mutableMapOf<Int, Team>() private val teamCache = mutableMapOf<Int, Team>()
@JvmStatic @JvmStatic
fun clear() = synchronized(teamCache) { teamCache.clear() } fun clear() =
synchronized(teamCache) { teamCache.clear() }
@JvmStatic @JvmStatic
fun byId(id: Int) = synchronized(teamCache) { teamCache.computeIfAbsent(id) { useDb { Team[id] } } } fun byId(id: Int) =
synchronized(teamCache) { teamCache.computeIfAbsent(id) { useDb { Team[id] } } }
@JvmStatic @JvmStatic
fun get(name: String) = useDb { find { (TeamTable.name.lowerCase() eq name.lowercase() or (TeamTable.kuerzel.lowerCase() eq name.lowercase())) and not(TeamTable.deleted) }.firstOrNull() } fun get(name: String) =
useDb { find { (TeamTable.name.lowerCase() eq name.lowercase() or (TeamTable.kuerzel.lowerCase() eq name.lowercase())) and not(TeamTable.deleted) }.firstOrNull() }
@JvmStatic @JvmStatic
fun getAll() = useDb { find { not(TeamTable.deleted) }.toList() } fun getAll() =
useDb { find { not(TeamTable.deleted) }.toList() }
@JvmStatic @JvmStatic
fun create(kuerzel: String, name: String) = useDb { fun create(kuerzel: String, name: String) =
useDb {
new { new {
this.kuerzel = kuerzel this.kuerzel = kuerzel
this.name = name this.name = name
@@ -67,8 +72,11 @@ class Team(id: EntityID<Int>) : IntEntity(id) {
private set private set
val members by lazy { useDb { SteamwarUserTable.select(SteamwarUserTable.id).where { SteamwarUserTable.team eq teamId }.map { it[SteamwarUserTable.id].value } } } val members by lazy { useDb { SteamwarUserTable.select(SteamwarUserTable.id).where { SteamwarUserTable.team eq teamId }.map { it[SteamwarUserTable.id].value } } }
fun size() = useDb { SteamwarUser.find { SteamwarUserTable.team eq teamId }.count().toInt() } fun size() =
fun disband(user: SteamwarUser) = useDb { useDb { SteamwarUser.find { SteamwarUserTable.team eq teamId }.count().toInt() }
fun disband(user: SteamwarUser) =
useDb {
user.team = 0 user.team = 0
deleted = true deleted = true
teamCache.remove(teamId) teamCache.remove(teamId)
@@ -47,12 +47,14 @@ object TeamTeilnahmeTable : CompositeIdTable("TeamTeilnahme") {
class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) { class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<TeamTeilnahme>(TeamTeilnahmeTable) { companion object : CompositeEntityClass<TeamTeilnahme>(TeamTeilnahmeTable) {
@JvmStatic @JvmStatic
fun nimmtTeil(teamId: Int, eventId: Int) = useDb { fun nimmtTeil(teamId: Int, eventId: Int) =
useDb {
find { (TeamTeilnahmeTable.teamId eq teamId) and (TeamTeilnahmeTable.eventId eq eventId) }.firstOrNull() != null find { (TeamTeilnahmeTable.teamId eq teamId) and (TeamTeilnahmeTable.eventId eq eventId) }.firstOrNull() != null
} }
@JvmStatic @JvmStatic
fun teilnehmen(teamId: Int, eventId: Int) = useDb { fun teilnehmen(teamId: Int, eventId: Int) =
useDb {
TeamTeilnahmeTable.insertIgnore { TeamTeilnahmeTable.insertIgnore {
it[TeamTeilnahmeTable.teamId] = teamId it[TeamTeilnahmeTable.teamId] = teamId
it[TeamTeilnahmeTable.eventId] = eventId it[TeamTeilnahmeTable.eventId] = eventId
@@ -60,12 +62,14 @@ class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun notTeilnehmen(teamId: Int, eventId: Int) = useDb { fun notTeilnehmen(teamId: Int, eventId: Int) =
useDb {
TeamTeilnahmeTable.deleteWhere { (TeamTeilnahmeTable.teamId eq teamId) and (TeamTeilnahmeTable.eventId eq eventId) } TeamTeilnahmeTable.deleteWhere { (TeamTeilnahmeTable.teamId eq teamId) and (TeamTeilnahmeTable.eventId eq eventId) }
} }
@JvmStatic @JvmStatic
fun deleteFuture(teamId: Int) = useDb { fun deleteFuture(teamId: Int) =
useDb {
exec( exec(
"DELETE t FROM TeamTeilnahme t INNER JOIN Event e ON t.EventID = e.EventID WHERE t.TeamID = ? AND e.Start > NOW()", "DELETE t FROM TeamTeilnahme t INNER JOIN Event e ON t.EventID = e.EventID WHERE t.TeamID = ? AND e.Start > NOW()",
args = listOf(IntegerColumnType() to teamId) args = listOf(IntegerColumnType() to teamId)
@@ -73,17 +77,20 @@ class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun getTeams(eventId: Int) = useDb { fun getTeams(eventId: Int) =
useDb {
find { TeamTeilnahmeTable.eventId eq eventId }.map { Team.byId(it.teamId.value) }.toSet() find { TeamTeilnahmeTable.eventId eq eventId }.map { Team.byId(it.teamId.value) }.toSet()
} }
@JvmStatic @JvmStatic
fun getEvents(teamId: Int) = useDb { fun getEvents(teamId: Int) =
useDb {
find { TeamTeilnahmeTable.teamId eq teamId }.map { Event.byId(it.eventId.value) }.toSet() find { TeamTeilnahmeTable.teamId eq teamId }.map { Event.byId(it.eventId.value) }.toSet()
} }
@JvmStatic @JvmStatic
fun getPlacement(team: Team, event: Event) = useDb { fun getPlacement(team: Team, event: Event) =
useDb {
get(CompositeID { get(CompositeID {
it[TeamTeilnahmeTable.teamId] = team.id it[TeamTeilnahmeTable.teamId] = team.id
it[TeamTeilnahmeTable.eventId] = event.id it[TeamTeilnahmeTable.eventId] = event.id
+10 -5
View File
@@ -41,7 +41,8 @@ object TokenTable: IntIdTable("Token") {
class Token(id: EntityID<Int>) : IntEntity(id) { class Token(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Token>(TokenTable) { companion object : IntEntityClass<Token>(TokenTable) {
private fun getHash(code: String) = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-512").digest(code.toByteArray())) private fun getHash(code: String) =
Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-512").digest(code.toByteArray()))
@JvmStatic @JvmStatic
fun createToken(name: String, owner: SteamwarUser): String { fun createToken(name: String, owner: SteamwarUser): String {
@@ -65,15 +66,18 @@ class Token(id: EntityID<Int>): IntEntity(id) {
} }
@JvmStatic @JvmStatic
fun getTokenByCode(code: String) = get(getHash(code)) fun getTokenByCode(code: String) =
get(getHash(code))
@JvmStatic @JvmStatic
fun get(hash: String) = useDb { fun get(hash: String) =
useDb {
find { TokenTable.hash eq hash }.firstOrNull() find { TokenTable.hash eq hash }.firstOrNull()
} }
@JvmStatic @JvmStatic
fun listUser(user: SteamwarUser) = useDb { fun listUser(user: SteamwarUser) =
useDb {
find { TokenTable.owner eq user.id }.toList() find { TokenTable.owner eq user.id }.toList()
} }
} }
@@ -87,7 +91,8 @@ class Token(id: EntityID<Int>): IntEntity(id) {
var hash by TokenTable.hash var hash by TokenTable.hash
private set private set
override fun delete() = useDb { override fun delete() =
useDb {
super.delete() super.delete()
} }
} }
@@ -49,15 +49,18 @@ class UserConfig(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<UserConfig>(UserConfigTable) { companion object : CompositeEntityClass<UserConfig>(UserConfigTable) {
@JvmStatic @JvmStatic
fun getConfig(userId: Int, config: String) = useDb { fun getConfig(userId: Int, config: String) =
useDb {
find { (UserConfigTable.userId eq userId) and (UserConfigTable.config eq config) }.firstOrNull()?.value find { (UserConfigTable.userId eq userId) and (UserConfigTable.config eq config) }.firstOrNull()?.value
} }
@JvmStatic @JvmStatic
fun getConfig(user: UUID, config: String) = getConfig(SteamwarUser.get(user)!!.id.value, config) fun getConfig(user: UUID, config: String) =
getConfig(SteamwarUser.get(user)!!.id.value, config)
@JvmStatic @JvmStatic
fun updatePlayerConfig(id: Int, config: String, value: String?) = useDb { fun updatePlayerConfig(id: Int, config: String, value: String?) =
useDb {
if (value == null) { if (value == null) {
removePlayerConfig(id, config) removePlayerConfig(id, config)
} else { } else {
@@ -70,14 +73,17 @@ class UserConfig(id: EntityID<CompositeID>): CompositeEntity(id) {
} }
@JvmStatic @JvmStatic
fun updatePlayerConfig(user: UUID, config: String, value: String?) = updatePlayerConfig(SteamwarUser.get(user)!!.id.value, config, value) fun updatePlayerConfig(user: UUID, config: String, value: String?) =
updatePlayerConfig(SteamwarUser.get(user)!!.id.value, config, value)
@JvmStatic @JvmStatic
fun removePlayerConfig(id: Int, config: String) = useDb { fun removePlayerConfig(id: Int, config: String) =
useDb {
find { (UserConfigTable.userId eq id) and (UserConfigTable.config eq config) }.firstOrNull()?.delete() find { (UserConfigTable.userId eq id) and (UserConfigTable.config eq config) }.firstOrNull()?.delete()
} }
@JvmStatic @JvmStatic
fun removePlayerConfig(user: UUID, config: String) = removePlayerConfig(SteamwarUser.get(user)!!.id.value, config) fun removePlayerConfig(user: UUID, config: String) =
removePlayerConfig(SteamwarUser.get(user)!!.id.value, config)
} }
} }
@@ -57,6 +57,7 @@ enum class UserPerm {
companion object { companion object {
@JvmField @JvmField
val emptyPrefix = Prefix("§7", "") val emptyPrefix = Prefix("§7", "")
@JvmField @JvmField
val prefixes = mapOf( val prefixes = mapOf(
PREFIX_NONE to emptyPrefix, PREFIX_NONE to emptyPrefix,
@@ -70,12 +71,14 @@ enum class UserPerm {
) )
@JvmStatic @JvmStatic
fun getPerms(id: Int) = useDb { fun getPerms(id: Int) =
useDb {
UserPermTable.selectAll().where { UserPermTable.user eq id }.map { it[UserPermTable.perm] }.toSet() UserPermTable.selectAll().where { UserPermTable.user eq id }.map { it[UserPermTable.perm] }.toSet()
} }
@JvmStatic @JvmStatic
fun addPerm(user: SteamwarUser, perm: UserPerm) = useDb { fun addPerm(user: SteamwarUser, perm: UserPerm) =
useDb {
UserPermTable.insert { UserPermTable.insert {
it[UserPermTable.user] = user.getId() it[UserPermTable.user] = user.getId()
it[UserPermTable.perm] = perm it[UserPermTable.perm] = perm
@@ -83,7 +86,8 @@ enum class UserPerm {
} }
@JvmStatic @JvmStatic
fun removePerm(user: SteamwarUser, perm: UserPerm) = useDb { fun removePerm(user: SteamwarUser, perm: UserPerm) =
useDb {
UserPermTable.deleteWhere { UserPermTable.deleteWhere {
(UserPermTable.user eq user.getId()) and (UserPermTable.perm eq perm) (UserPermTable.user eq user.getId()) and (UserPermTable.perm eq perm)
} }
@@ -68,7 +68,8 @@ object KotlinDatabase {
fun <T> useDb(statement: JdbcTransaction.() -> T): T { fun <T> useDb(statement: JdbcTransaction.() -> T): T {
KotlinDatabase.ensureConnected() KotlinDatabase.ensureConnected()
return TransactionManager.currentOrNull()?.statement() ?: transaction(KotlinDatabase.db) { return TransactionManager.currentOrNull()?.statement()
?: transaction(KotlinDatabase.db) {
statement() statement()
} }
} }
@@ -77,12 +78,14 @@ fun <T : IntEntity> IntEntityClass<T>.fromSql(
@Language("MySQL") stmt: String, @Language("MySQL") stmt: String,
args: List<Pair<ColumnType<*>, Any?>>, args: List<Pair<ColumnType<*>, Any?>>,
fieldIndex: Map<Expression<*>, Int> fieldIndex: Map<Expression<*>, Int>
): List<T> = useDb { ): List<T> =
useDb {
exec(stmt, explicitStatementType = StatementType.SELECT, args = args) { exec(stmt, explicitStatementType = StatementType.SELECT, args = args) {
val list = mutableListOf<T>() val list = mutableListOf<T>()
while (it.next()) { while (it.next()) {
list.add(wrapRow(ResultRow.create(JdbcResult(it), fieldIndex))) list.add(wrapRow(ResultRow.create(JdbcResult(it), fieldIndex)))
} }
list list
} ?: listOf() }
?: listOf()
} }
@@ -32,19 +32,23 @@ import java.sql.SQLException
data class Statement(val statement: String) { data class Statement(val statement: String) {
companion object { companion object {
@JvmStatic @JvmStatic
fun closeAll() = KotlinDatabase.close() fun closeAll() =
KotlinDatabase.close()
@JvmStatic @JvmStatic
fun productionDatabase() = TransactionManager.defaultDatabase?.name == "production" fun productionDatabase() =
TransactionManager.defaultDatabase?.name == "production"
} }
fun <T> select(user: ResultSetUser<T>, vararg args: Any): T? = useDb { fun <T> select(user: ResultSetUser<T>, vararg args: Any): T? =
useDb {
exec(statement, args = args.map { getArgType(it) }) { exec(statement, args = args.map { getArgType(it) }) {
user.use(it) user.use(it)
} }
} }
private fun getArgType(obj: Any) = when(obj) { private fun getArgType(obj: Any) =
when (obj) {
is String -> VarCharColumnType() to obj is String -> VarCharColumnType() to obj
is Int -> IntegerColumnType() to obj is Int -> IntegerColumnType() to obj
is Long -> LongColumnType() to obj is Long -> LongColumnType() to obj
@@ -40,7 +40,8 @@ import java.util.logging.Level;
public class Config { public class Config {
private Config(){} private Config() {
}
public static final World world = Bukkit.getWorlds().get(0); public static final World world = Bukkit.getWorlds().get(0);
@@ -265,14 +266,16 @@ public class Config {
String blueLeader = System.getProperty("blueLeader", null); String blueLeader = System.getProperty("blueLeader", null);
String redLeader = System.getProperty("redLeader", null); String redLeader = System.getProperty("redLeader", null);
if(blueLeader != null) if (blueLeader != null) {
BlueLeader = UUID.fromString(blueLeader); BlueLeader = UUID.fromString(blueLeader);
else } else {
BlueLeader = null; BlueLeader = null;
if(redLeader != null) }
if (redLeader != null) {
RedLeader = UUID.fromString(redLeader); RedLeader = UUID.fromString(redLeader);
else } else {
RedLeader = null; RedLeader = null;
}
if (CheckSchemID != 0) { if (CheckSchemID != 0) {
mode = ArenaMode.CHECK; mode = ArenaMode.CHECK;
@@ -292,9 +295,11 @@ public class Config {
public static boolean test() { public static boolean test() {
return ArenaMode.Test.contains(mode); return ArenaMode.Test.contains(mode);
} }
public static boolean replayserver() { public static boolean replayserver() {
return ReplayID < 0; return ReplayID < 0;
} }
public static boolean blueNegZ() { public static boolean blueNegZ() {
return BlueToRedZ > 0; return BlueToRedZ > 0;
} }
@@ -65,6 +65,7 @@ public abstract class AI {
public static final double INTERACTION_RANGE = 5.0; public static final double INTERACTION_RANGE = 5.0;
private static final Map<UUID, AI> ais = new HashMap<>(); private static final Map<UUID, AI> ais = new HashMap<>();
public static void printPos() { public static void printPos() {
ais.values().forEach(ai -> ai.chat(ai.entity.isValid() + " " + ai.entity.isDead() + " " + ai.entity.getLocation())); ais.values().forEach(ai -> ai.chat(ai.entity.isValid() + " " + ai.entity.isDead() + " " + ai.entity.getLocation()));
} }
@@ -98,11 +99,13 @@ public abstract class AI {
ais.put(entity.getUniqueId(), this); ais.put(entity.getUniqueId(), this);
team.addMember(entity, user); team.addMember(entity, user);
if(FightState.Schem.contains(FightState.getFightState())) if (FightState.Schem.contains(FightState.getFightState())) {
Bukkit.getScheduler().runTask(FightSystem.getPlugin(), () -> schematic(team.getClipboard())); Bukkit.getScheduler().runTask(FightSystem.getPlugin(), () -> schematic(team.getClipboard()));
} }
}
public abstract SchematicNode chooseSchematic(); public abstract SchematicNode chooseSchematic();
public abstract void schematic(Clipboard clipboard); public abstract void schematic(Clipboard clipboard);
public boolean acceptJoinRequest(JoinRequest.Enquirer enquirer, FightTeam team) { public boolean acceptJoinRequest(JoinRequest.Enquirer enquirer, FightTeam team) {
@@ -112,20 +115,13 @@ public abstract class AI {
protected abstract void plan(); protected abstract void plan();
public void stop() { public void stop() {
if(!entity.isDead()) if (!entity.isDead()) entity.remove();
entity.remove(); if (!task.isCancelled()) task.cancel();
if(!task.isCancelled())
task.cancel();
} }
public void setReady() { public void setReady() {
if(FightState.getFightState() != FightState.POST_SCHEM_SETUP) if (FightState.getFightState() != FightState.POST_SCHEM_SETUP) return;
return; if (team.getLeader().getEntity() != entity) return;
if(team.getLeader().getEntity() != entity)
return;
team.setReady(true); team.setReady(true);
} }
@@ -137,19 +133,20 @@ public abstract class AI {
public Vector getPosition() { public Vector getPosition() {
Location location = entity.getLocation(); Location location = entity.getLocation();
Region extend = team.getExtendRegion(); Region extend = team.getExtendRegion();
if(Fight.getUnrotated() == team) if (Fight.getUnrotated() == team) {
return new Vector( return new Vector(
location.getX() - extend.getMinX(), location.getX() - extend.getMinX(),
location.getY() - team.getSchemRegion().getMinY(), location.getY() - team.getSchemRegion().getMinY(),
location.getZ() - extend.getMinZ() location.getZ() - extend.getMinZ()
); );
else } else {
return new Vector( return new Vector(
extend.getMaxX() - location.getX(), extend.getMaxX() - location.getX(),
location.getY() - team.getSchemRegion().getMinY(), location.getY() - team.getSchemRegion().getMinY(),
extend.getMaxZ() - location.getZ() extend.getMaxZ() - location.getZ()
); );
} }
}
public Material getBlock(Vector pos) { public Material getBlock(Vector pos) {
queue.add(new Action(1)); queue.add(new Action(1));
@@ -165,8 +162,7 @@ public abstract class AI {
queue.add(new Action(1) { queue.add(new Action(1) {
@Override @Override
public void run() { public void run() {
if(FightState.getFightState() != FightState.RUNNING) if (FightState.getFightState() != FightState.RUNNING) return;
return;
Location location = translate(pos); Location location = translate(pos);
if (interactionDistanceViolation(location)) { if (interactionDistanceViolation(location)) {
@@ -175,8 +171,7 @@ public abstract class AI {
} }
Block block = location.getBlock(); Block block = location.getBlock();
if(block.getType() == Material.AIR) if (block.getType() == Material.AIR) block.setType(Material.TNT);
block.setType(Material.TNT);
} }
}); });
} }
@@ -201,8 +196,7 @@ public abstract class AI {
@Override @Override
public void run() { public void run() {
Location location = translate(pos); Location location = translate(pos);
if (interactionDistanceViolation(location)) if (interactionDistanceViolation(location)) return;
return;
Block block = location.getBlock(); Block block = location.getBlock();
BlockData data = block.getBlockData(); BlockData data = block.getBlockData();
if (data instanceof Repeater) { if (data instanceof Repeater) {
@@ -236,8 +230,9 @@ public abstract class AI {
if (!team.getFightPlayer(entity).canEntern() && !team.getExtendRegion().inRegion(target)) if (!team.getFightPlayer(entity).canEntern() && !team.getExtendRegion().inRegion(target))
return; return;
if(!entity.teleport(target, PlayerTeleportEvent.TeleportCause.PLUGIN)) if (!entity.teleport(target, PlayerTeleportEvent.TeleportCause.PLUGIN)) {
FightSystem.getPlugin().getLogger().log(Level.INFO, "Entity not teleported: " + entity.isValid()); FightSystem.getPlugin().getLogger().log(Level.INFO, "Entity not teleported: " + entity.isValid());
}
GlobalRecorder.getInstance().entityMoves(entity); GlobalRecorder.getInstance().entityMoves(entity);
} }
@@ -266,12 +261,10 @@ public abstract class AI {
boolean isPowered = powerable.isPowered(); boolean isPowered = powerable.isPowered();
if (type.name().endsWith("BUTTON")) { if (type.name().endsWith("BUTTON")) {
if(isPowered) if (isPowered) return;
return;
Bukkit.getScheduler().runTaskLater(FightSystem.getPlugin(), () -> { Bukkit.getScheduler().runTaskLater(FightSystem.getPlugin(), () -> {
if(!block.getType().name().endsWith("BUTTON")) if (!block.getType().name().endsWith("BUTTON")) return;
return;
powerable.setPowered(false); powerable.setPowered(false);
block.setBlockData(powerable); block.setBlockData(powerable);
@@ -315,20 +308,19 @@ public abstract class AI {
} }
} }
if(!queue.isEmpty() && --queue.peek().delay == 0) if (!queue.isEmpty() && --queue.peek().delay == 0) queue.poll().run();
queue.poll().run();
} }
public Location translate(Vector pos) { public Location translate(Vector pos) {
Region extend = team.getExtendRegion(); Region extend = team.getExtendRegion();
if(Fight.getUnrotated() == team) if (Fight.getUnrotated() == team) {
return new Location( return new Location(
Config.world, Config.world,
pos.getX() + extend.getMinX(), pos.getX() + extend.getMinX(),
pos.getY() + team.getSchemRegion().getMinY(), pos.getY() + team.getSchemRegion().getMinY(),
pos.getZ() + extend.getMinZ() pos.getZ() + extend.getMinZ()
); );
else } else {
return new Location( return new Location(
Config.world, Config.world,
extend.getMaxX() - pos.getX(), extend.getMaxX() - pos.getX(),
@@ -336,13 +328,16 @@ public abstract class AI {
extend.getMaxZ() - pos.getZ() extend.getMaxZ() - pos.getZ()
); );
} }
}
private static class Action { private static class Action {
private int delay; private int delay;
public Action(int delay) { public Action(int delay) {
this.delay = delay; this.delay = delay;
} }
public void run() {} public void run() {
}
} }
} }
@@ -52,7 +52,6 @@ public class DummyAI extends AI {
@Override @Override
protected void plan() { protected void plan() {
if(FightState.getFightState() == FightState.POST_SCHEM_SETUP) if (FightState.getFightState() == FightState.POST_SCHEM_SETUP) setReady();
setReady();
} }
} }

Some files were not shown because too many files have changed in this diff Show More