Format code

This commit is contained in:
2026-05-16 23:08:09 +02:00
parent 81dd8045f2
commit d110df924e
562 changed files with 11025 additions and 10059 deletions
@@ -104,7 +104,8 @@ public class BackupCommand extends SWCommand {
List<String> lore = Arrays.asList(BauSystem.MESSAGE.parse("BACKUP_LORE", p));
for (int i = 0; i < backups.size(); 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);
swListEntries.add(new SWListInv.SWListEntry<>(swItem, backup));
}
@@ -50,7 +50,8 @@ public class InventoryFillBauGuiItem extends BauGuiItem {
@Override
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";
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
@@ -104,7 +104,9 @@ public class KillcheckerVisualizer {
Block block = WORLD.getBlockAt(x, y, z);
if (block.getType().isAir()) continue;
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;
Cuboid cuboid = create(block.getType(), x, y, z);
cuboids.add(cuboid);
@@ -283,7 +285,9 @@ public class KillcheckerVisualizer {
}
kill.forEach((point, count) -> {
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();
}
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();
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, () -> {
updateRunnable.run();
swListInv.open();
@@ -363,7 +364,9 @@ public class Loader implements Listener, SWPlayer.Component {
public static int LENGTH = SettingsSorting.values().length;
public abstract Material getMaterial();
public abstract String getName();
public abstract boolean shouldShow(LoaderElement previous, LoaderElement current, LoaderElement next);
}
@@ -26,6 +26,8 @@ import java.util.function.Consumer;
public interface LoaderElement {
SWItem menu(Player player);
void execute(Consumer<Long> delay);
void click(Player player, Runnable backAction);
}
@@ -95,7 +95,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
};
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) -> {
openIndividualSettingsMenu(player, entry, () -> {
updateRunnable.run();
@@ -150,7 +151,9 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
}
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 - 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");
@@ -197,7 +200,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
for (int power = 0; power < 16; power++) {
int finalPowerPosition = power;
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));
if (extraPower.get(index) == power) powerItem.setEnchanted(true);
@@ -210,7 +214,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
}
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);
ticks -= clickType.isShiftClick() ? 5 : 1;
if (ticks < 1) ticks = 1;
@@ -218,7 +223,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
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));
swInventory.setItem(ticksStart + 4, ticksItem.getItemStack(), clickType -> {
SWAnvilInv swAnvilInv = new SWAnvilInv(player, BauSystem.MESSAGE.parse("LOADER_SETTING_TICKS_NAME", player), extraTicks.get(index) + "");
@@ -234,7 +240,8 @@ public abstract class LoaderInteractionElement<T extends Enum<T> & LoaderSetting
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);
ticks += clickType.isShiftClick() ? 5 : 1;
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>> {
int getPos();
SWItem menu(Player player, P parent, int power, long ticks);
default boolean hasPower(P parent) {
return false;
}
default boolean hasTicks(P parent) {
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"));
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;
if (delay < 0) delay = 0;
swInventory.setItem(4, menu(player));
@@ -80,7 +81,8 @@ public class LoaderWait implements LoaderElement {
});
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;
swInventory.setItem(4, menu(player));
});
@@ -146,8 +146,7 @@ public class Loadtimer implements Listener {
if ((stage == Stage.COUNTING || stage == Stage.ACTIVATED)) {
stage = Stage.IGNITION;
ignite = TPSUtils.currentRealTick.get();
if (activate == -1)
activate = TPSUtils.currentRealTick.get();
if (activate == -1) activate = TPSUtils.currentRealTick.get();
if (finishOnActive) {
stage = Stage.END;
print();
@@ -40,17 +40,19 @@ public class LoadtimerCommand extends SWCommand {
public void start(@Validator Player p, TimerMode mode) {
Region r = Region.getRegion(p.getLocation());
if (r.getType().isGlobal()) return;
if (!Loadtimer.hasTimer(r))
if (!Loadtimer.hasTimer(r)) {
Loadtimer.createLoadtimer(r, mode == TimerMode.HALF);
}
}
@Register(value = "stop", description = "LOADTIMER_HELP_STOP")
public void stop(@Validator Player p) {
Region r = Region.getRegion(p.getLocation());
if (r.getType().isGlobal()) return;
if (Loadtimer.hasTimer(r))
if (Loadtimer.hasTimer(r)) {
Loadtimer.getTimer(r).delete();
}
}
public enum TimerMode {
FULL,
@@ -46,8 +46,9 @@ public class LoadtimerGuiItem extends BauGuiItem {
@Override
public ItemStack getItem(Player player) {
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();
}
if (Loadtimer.hasTimer(r)) {
return new SWItem(Material.BOW, BauSystem.MESSAGE.parse("LOADTIMER_GUI_STOP", player)).getItemStack();
} else {
@@ -36,12 +36,16 @@ public class FireListener implements Listener, ScoreboardElement {
@EventHandler
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
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
@@ -47,7 +47,9 @@ public class FreezeListener implements Listener, ScoreboardElement {
@EventHandler
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);
BlockState state = e.getBlock().getState();
Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
@@ -57,7 +59,9 @@ public class FreezeListener implements Listener, ScoreboardElement {
@EventHandler
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);
if (e.getEntityType() == EntityType.TNT) {
Bukkit.getScheduler().runTaskLater(BauSystem.getInstance(), () -> {
@@ -69,7 +73,9 @@ public class FreezeListener implements Listener, ScoreboardElement {
@EventHandler
public void onBlockCanBuild(BlockCanBuildEvent e) {
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) {
e.setBuildable(false);
e.getBlock().setType(Material.TNT, false);
@@ -59,7 +59,9 @@ public class RegionListener implements Listener {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
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)
@@ -36,7 +36,9 @@ public class WaterDestroyListener implements Listener, ScoreboardElement {
@EventHandler
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
@@ -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_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();
});
@@ -82,7 +82,9 @@ public interface LuaLib {
default Class<? extends LuaLib> parent() {
return null;
}
String name();
LuaTable get(Player player);
@AllArgsConstructor
@@ -103,27 +105,33 @@ public interface LuaLib {
try {
consumer.accept(luaValue.toboolean());
return NIL;
} catch (Exception ingored) {}
} catch (Exception ingored) {
}
try {
consumer.accept((long) luaValue.toint());
return NIL;
} catch (Exception ignored) {}
} catch (Exception ignored) {
}
try {
consumer.accept(luaValue.toint());
return NIL;
} catch (Exception ignored) {}
} catch (Exception ignored) {
}
try {
consumer.accept(luaValue.todouble());
return NIL;
} catch (Exception ignored) {}
} catch (Exception ignored) {
}
try {
consumer.accept((float) luaValue.todouble());
return NIL;
} catch (Exception ignored) {}
} catch (Exception ignored) {
}
try {
consumer.accept(luaValue.toString());
return NIL;
} catch (Exception ignored) {}
} catch (Exception ignored) {
}
throw new LuaError("Invalid lua type: " + luaValue.typename());
} catch (Throwable throwable) {
throw new LuaError("Error in '" + name + "' " + throwable.getMessage());
@@ -62,7 +62,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
jsonObject.keySet().forEach(key -> {
GLOBAL_STORAGE.put(key, fromJson(jsonObject.get(key)));
});
} catch (Exception e) {}
} catch (Exception e) {
}
File regionStorageDirectory = new File(storageDirectory, "region");
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_STORAGE.put(region, map);
} catch (Exception e) {}
} catch (Exception e) {
}
}
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())));
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()) {
try {
return LuaValue.valueOf(jsonPrimitive.getAsInt());
} catch (NumberFormatException e) {}
} catch (NumberFormatException e) {
}
try {
return LuaValue.valueOf(jsonPrimitive.getAsDouble());
} catch (NumberFormatException e) {}
} catch (NumberFormatException e) {
}
}
if (jsonPrimitive.isString()) {
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"));
gson.toJson(toJson(GLOBAL_STORAGE), fileWriter);
fileWriter.close();
} catch (IOException e) {}
} catch (IOException e) {
}
File regionStorageDirectory = new File(storageDirectory, "region");
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"));
gson.toJson(toJson(entry.getValue()), fileWriter);
fileWriter.close();
} catch (IOException e) {}
} catch (IOException e) {
}
}
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"));
gson.toJson(toJson(entry.getValue()), fileWriter);
fileWriter.close();
} catch (IOException e) {}
} catch (IOException e) {
}
}
}
@@ -174,13 +182,16 @@ public class StorageLib implements LuaLib, Enable, Disable {
}
try {
return new JsonPrimitive(luaValue.checkboolean());
} catch (Exception e) {}
} catch (Exception e) {
}
try {
return new JsonPrimitive(luaValue.checkint());
} catch (Exception e) {}
} catch (Exception e) {
}
try {
return new JsonPrimitive(luaValue.checkdouble());
} catch (Exception e) {}
} catch (Exception e) {
}
if (luaValue.isstring()) {
return new JsonPrimitive(luaValue.tojstring());
@@ -193,7 +204,8 @@ public class StorageLib implements LuaLib, Enable, Disable {
if (value == null) continue;
try {
jsonObject.add(key.checkjstring(), value);
} catch (Exception e) {}
} catch (Exception e) {
}
}
return jsonObject;
}
@@ -249,7 +261,9 @@ public class StorageLib implements LuaLib, Enable, Disable {
}
}
};
};
}
;
});
storageLib.set("global", global);
@@ -294,7 +308,9 @@ public class StorageLib implements LuaLib, Enable, Disable {
}
}
};
};
}
;
});
storageLib.set("player", playerStorage);
@@ -343,7 +359,9 @@ public class StorageLib implements LuaLib, Enable, Disable {
}
}
};
};
}
;
});
storageLib.set("region", regionStorage);
@@ -26,7 +26,9 @@ import org.bukkit.entity.Player;
public interface BlockDataConfiguration<T extends BlockData> {
void previous();
void next();
SWItem get(Player player);
void apply(T copied, T worldOriginal);
@@ -293,8 +293,9 @@ public class SimulatorCursor implements Listener {
if (!player.isSneaking()) {
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.setZ(pos.getBlockZ() + 0.5);
}
@@ -120,6 +120,10 @@ public abstract class SimulatorElement<T extends SimulatorPhase> {
}
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;
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
public void accept(World 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);
if (!xJump) tnt.setVelocity(tnt.getVelocity().setX(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 (Region.getRegion(event.getEntity().getLocation()) == data.region) {
event.blockList().forEach(block -> {
if (!data.region.getTestblockArea().inRegion(block.getLocation(), true))
if (!data.region.getTestblockArea().inRegion(block.getLocation(), true)) {
return;
}
int component = data.direction.component.apply(block.getLocation().toVector());
destroyedBlocksPerSlice.computeIfAbsent(component, __ -> new HashSet<>())
.add(block.getLocation());
@@ -33,6 +33,7 @@ import java.util.*;
public class LaufbauSettings {
private static Map<Pair<Material, String>, List<BlockBoundingBox>> groupMap = new LinkedHashMap<>();
static {
BlockBoundingBox.elements.forEach(blockBoundingBox -> {
if (blockBoundingBox.getSwItem() == null) return;
@@ -115,12 +116,15 @@ public class LaufbauSettings {
} else {
long count = blockBoundingBoxes.stream().filter(bb -> LaufbauUtils.isDeactivated(p, bb)).count();
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()) {
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);
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;
}
Location location = current.getLocation();
if (current.getPrevious().isPresent()) {
@@ -40,6 +40,7 @@ import java.util.*;
public class Panzern {
private static List<PanzernAlgorithm> panzernAlgorithmList = new ArrayList<>();
public static void add(PanzernAlgorithm panzernAlgorithm) {
panzernAlgorithmList.add(panzernAlgorithm);
}
@@ -144,8 +144,9 @@ public class Trace {
entityServer = new REntityServer();
entityServer.addPlayer(player);
entityServer.setCallback((p, rEntity, entityAction) -> {
if (entityAction != REntityServer.EntityAction.INTERACT)
if (entityAction != REntityServer.EntityAction.INTERACT) {
return;
}
if (rEntity instanceof TraceEntity) {
((TraceEntity) rEntity).printIntoChat(p);
}
@@ -167,8 +168,9 @@ public class Trace {
REntityServer newEntityServer = new REntityServer();
newEntityServer.addPlayer(k);
newEntityServer.setCallback((p, rEntity, entityAction) -> {
if (entityAction != REntityServer.EntityAction.INTERACT)
if (entityAction != REntityServer.EntityAction.INTERACT) {
return;
}
if (rEntity instanceof TraceEntity) {
((TraceEntity) rEntity).printIntoChat(p);
}
@@ -46,12 +46,10 @@ public class TraceManager implements Listener {
}
public void init() {
if (!tracesFolder.exists())
tracesFolder.mkdir();
if (!tracesFolder.exists()) tracesFolder.mkdir();
File[] traceFiles = tracesFolder.listFiles();
if (traceFiles == null)
return;
if (traceFiles == null) return;
boolean hasMetaFiles = false;
for (File traceFile : traceFiles) {
@@ -152,7 +150,8 @@ public class TraceManager implements Listener {
.map(Map.Entry::getKey)
.findFirst()
.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);
trace.hide();
trace.getRecordsSaveFile().delete();
@@ -70,7 +70,9 @@ public class TraceEntity extends RFallingBlockEntity {
* @param player the player the message should be printed for
*/
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);
BauSystem.MESSAGE.sendPrefixless("TNT_CLICK_HEADER", player);
@@ -102,8 +102,7 @@ public abstract class ViewFlag {
}
}
if (!hasMicromotion)
toRemove.add(uniqueRecord);
if (!hasMicromotion) toRemove.add(uniqueRecord);
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<>();
static {
elements.put("-transparent", (search, searchType) -> search.transparent = searchType);
elements.put("-solid", (search, searchType) -> search.solid = searchType);
@@ -282,8 +282,9 @@ public class PistonCalculator implements Listener {
immovableBlocks.add(block.getLocation());
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;
}
if (!movedBlocks.contains(block.getLocation())) toCalc.add(block);
}
}
@@ -60,7 +60,9 @@ public class TNTClickListener extends SWCommand implements Listener {
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (!Permission.BUILD.hasPermission(event.getPlayer())) 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();
if (event.getRightClicked() instanceof TNTPrimed) {
@@ -41,7 +41,8 @@ public class GamemodeBauGuiItem extends BauGuiItem {
@Override
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
@@ -46,7 +46,8 @@ public class KillAllBauGuiItem extends BauGuiItem {
@Override
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
@@ -38,16 +38,19 @@ public class NavWandBauGuiItem extends BauGuiItem {
super(27);
}
@Override public Permission permission() {
@Override
public Permission permission() {
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 -> {
}).getItemStack();
}
@Override public boolean click(ClickType click, Player p) {
@Override
public boolean click(ClickType click, Player p) {
p.performCommand("/wand -n");
p.closeInventory();
return false;
@@ -42,34 +42,37 @@ public class AFKStopperListener implements Listener {
Bukkit.getScheduler().runTaskTimer(BauSystem.getInstance(), () -> {
long currentTime = System.currentTimeMillis();
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));
} else if(currentTime - lastMovementTime > 9*60000)
}
} else if (currentTime - lastMovementTime > 9 * 60000) {
BauSystem.MESSAGE.broadcast("AFK_WARNING_MESSAGE");
}
}, 1200, 1200); //every minute
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Location to = event.getTo();
if (to == null)
return;
if (to == null) return;
Location from = event.getFrom();
if (from.getPitch() != to.getPitch() || from.getYaw() != to.getYaw())
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) {
event.getPlayer().setOp(true);
}
@EventHandler(priority = EventPriority.MONITOR)
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();
}
}
@EventHandler
public void onCRIUWakeup(CRIUWakeupEvent event) {
@@ -105,8 +105,9 @@ public class SignEdit implements Listener {
Bukkit.getScheduler().runTask(BauSystem.getInstance(), () -> {
ServerLevel serverLevel = ((CraftWorld) player.getWorld()).getHandle();
Block signLoc = CraftBlock.at(serverLevel, o.getPos());
if (!signLoc.getType().name().contains("SIGN"))
if (!signLoc.getType().name().contains("SIGN")) {
return;
}
String[] lines = o.getLines();
Sign sign = ((Sign) signLoc.getState());
@@ -32,8 +32,7 @@ public class SignListener implements Listener {
public void onSignChange(SignChangeEvent event) {
for (int i = 0; i <= 3; ++i) {
String line = event.getLine(i);
if (line == null)
continue;
if (line == null) continue;
line = ChatColor.translateAlternateColorCodes('&', line);
event.setLine(i, line);
}
@@ -51,6 +51,7 @@ public class ColorReplaceCommand extends SWCommand {
}
private Set<String> types = new HashSet<>();
{
WorldEditListener.addOtherCommand("//colorreplace");
WorldEditListener.addOtherCommand("//cr");
@@ -218,12 +218,10 @@ public class FlatteningWrapper {
public boolean inWater(org.bukkit.World world, Vector tntPosition) {
Block block = world.getBlockAt(tntPosition.getBlockX(), tntPosition.getBlockY(), tntPosition.getBlockZ());
if (block.getType() == Material.WATER)
return true;
if (block.getType() == Material.WATER) return true;
BlockData data = block.getBlockData();
if (!(data instanceof Waterlogged))
return false;
if (!(data instanceof Waterlogged)) return false;
return ((Waterlogged) data).isWaterlogged();
}
@@ -49,7 +49,9 @@ public class RayTraceUtils {
RRayTraceResult nearestHitResult = null;
double nearestDistanceSq = Double.MAX_VALUE;
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());
if (distanceSq > 100.0) continue;
if (distanceSq < nearestDistanceSq) {
@@ -24,6 +24,7 @@ import org.bukkit.entity.Player;
public interface ScoreboardElement {
ScoreboardGroup getGroup();
int order();
String get(Region region, Player p);
@@ -27,22 +27,29 @@ import org.bukkit.boss.BarStyle;
public interface BauSystemBossbar {
String getTitle();
void setTitle(String title);
double getProgress();
void setProgress(double progress);
BarColor getColor();
void setColor(BarColor color);
BarStyle getStyle();
void setStyle(BarStyle style);
boolean hasFlag(BarFlag flag);
void addFlag(BarFlag flag);
void removeFlag(BarFlag flag);
boolean isVisible();
void setVisible(boolean visible);
Region getRegion();
+52 -12
View File
@@ -2,6 +2,7 @@
---
<!-- TOC -->
* [SteamWar.de - Script System](#steamwarde---script-system)
* [Einleitung](#einleitung)
* [Nutzung mit einer IDE](#nutzung-mit-einer-ide)
@@ -37,32 +38,39 @@
* [Code](#code-3)
* [Inventory](#inventory-1)
* [Code](#code-4)
<!-- TOC -->
## Einleitung
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.
## 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.
Einfach die `sw.def.lua` in denselben Ordner wie das Script legen und die IDE sollte die APIs erkennen.
# Basis-Apis
Es werden folgende Standard-Apis zur Verfügung gestellt:
- [`math`](https://www.lua.org/manual/5.4/manual.html#6.7)
- [`string`](https://www.lua.org/manual/5.4/manual.html#6.4)
- [`table`](https://www.lua.org/manual/5.4/manual.html#6.6)
- [`bit32`](https://www.lua.org/manual/5.2/manual.html#6.7)
# SteamWar.de-Api
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.
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:
- [`player`](#player)
- [`random`](#random)
- [`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 |
### player
Das `player`-Modul stellt Funktionen zur Verfügung, die den Spieler betreffen.
Es gibt folgende Funktionen:
@@ -105,6 +114,7 @@ Es gibt folgende Funktionen:
| `closeInventory` | closeInventory() | Schließe das aktuell geöffnete Inventar des Spielers |
### random
Das `random`-Modul stellt Funktionen zur Verfügung, die Zufallszahlen betreffen.
Es gibt folgende Funktionen:
@@ -119,6 +129,7 @@ Es gibt folgende Funktionen:
| nextBool | nextBool(): Boolean | Gibt true oder false zurück |
### region
Das `region`-Modul stellt Funktion zur Verfügung, die die Region des Spielers betreffen.
Es gibt folgende Funktionen:
@@ -141,6 +152,7 @@ Es gibt folgende weitere Module:
| `trace` | [trace](#trace) |
#### tnt
Das `tnt`-Modul stellt Funktionen zur Verfügung, die den TNT-Modus in der Region des Spielers betreffen.
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 |
| `onlyBuild` | onlyBuild(): Boolean | Gibt zurück, ob der TNT-Modus auf Only-Build ist |
#### trace
Das `trace`-Modul stellt Funktionen zur Verfügung, die den Status des Tracers der Region betreffen.
Es gibt folgende Funktionen:
@@ -164,6 +176,7 @@ Es gibt folgende Funktionen:
| `time` | time(): String | Gibt die Zeit des Tracers zurück |
## server
Das `server`-Modul stellt Funktionen zur Verfügung, die den Server betreffen.
Es gibt folgende Funktionen:
@@ -181,6 +194,7 @@ Es gibt folgende weitere Module:
| `tps` | [tps](#tps) |
#### tps
Das `tps`-Modul stellt Funktionen zur Verfügung, die die TPS des Servers betreffen.
Es gibt folgende Funktionen:
@@ -195,6 +209,7 @@ Es gibt folgende Funktionen:
| `limit` | limit(): Number | Gibt das TPS-Limit zurück |
## storage
Das `storage`-Modul stellt Funktionen zur Verfügung, mit welchen man Werte speichern kann.
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.
Es geht wie folgt:
```lua
keyAccessor = storage.player.accessor("key")
@@ -225,11 +241,12 @@ print(keyAccessor()) -- Gibt den Wert zurück
```
## inventory
Das `inventory`-Modul stellt Funktionen zur Verfügung, um ein Inventar zu öffnen.
Es gibt folgende Funktionen:
| Name | Signature | Beschreibung |
|----------|-----------------------------------|-------------------------------------------------------------------|
|----------|-----------------------------------|--------------------------------------------------------------|
| `create` | create(String, Number): Inventory | Erstellt ein Inventar mit dem Title und der Anzahl an Zeilen |
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
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.
@@ -274,20 +292,28 @@ Es gibt folgende Variablen:
| `events` | Siehe: [Event Type](#eventtypen) |
## 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 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`
- `shift`
- `alt`
- `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
Einige Events sind auch abbrechbar, dazu muss die Funktion `setCancelled()` aufgerufen werden.
| 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 |
### BlockEvent
Das übergebene Objekt an den Handler hat folgende Variablen:
| Name | Beschreibung |
@@ -316,6 +343,7 @@ Das übergebene Objekt an den Handler hat folgende Variablen:
| `type` | Das Material des Blocks |
### InteractEvent
Das übergebene Objekt an den Handler hat folgende Variablen:
| Name | Beschreibung |
@@ -334,8 +362,8 @@ Wenn `hasBlock` wahr ist, gibt es folgende Variablen:
| `blockZ` | Die Z-Koordinate des Blocks |
| `blockFace` | Die Seite des Blocks die geklickt wurde |
### Position
Die Position ist ein Objekt mit folgenden Variablen:
| Name | Beschreibung |
@@ -345,6 +373,7 @@ Die Position ist ein Objekt mit folgenden Variablen:
| `z` | Die Z-Koordinate |
# Instabile APIs
Hier sind einige APIs aufgelistet, die nicht stabil sind und sich jederzeit ändern können.
## _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 |
# Beispiele
## Hello, World!
Ein einfaches Hello, World!-Script.
#### Code
```lua
print("Hello, World!")
```
#### Ausgabe
```
Hello, World!
```
## BauGUI on DoubleSwap
Das Standardskript für das Öffnen des BauGUIs
#### Code
```lua
function handler(event)
exec("gui")
@@ -383,9 +415,11 @@ event(events.DoubleSwap, handler)
```
## SL Command
Ein einfacher Command Redefiner.
#### Code
```lua
function handler(args)
exec("stoplag")
@@ -395,9 +429,11 @@ command("sl", handler)
```
## Paste Hotkey
Ein Hotkey zum Pasten des Clipboard-Inhalts.
#### Code
```lua
function handler(pressed)
if pressed then
@@ -409,11 +445,15 @@ hotkey("ctrl+v", handler)
```
## Inventory
Ein Beispiel für ein Inventar.
#### Code
```lua
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()
```
+213 -81
View File
@@ -26,7 +26,9 @@ inventory = {}
---@param title string
---@param size number
---@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'
@@ -44,66 +46,88 @@ local Inventory = {}
---@param enchanted boolean
---@param amount number
---@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
---@return void
function Inventory.setCloseHandler(handler) end
function Inventory.setCloseHandler(handler)
end
---@return void
function Inventory.open() end
function Inventory.open()
end
player = {}
---@return string
---Get the name of the player.
function player.name() return "" end
function player.name()
return ""
end
---@return void
function player.chat(...) end
function player.chat(...)
end
---@return void
---Send a message to the actionbar of the player.
function player.actionbar(...) end
function player.actionbar(...)
end
---@overload fun(): number
---@param newX number
function player.x(newX) end
function player.x(newX)
end
---@overload fun(): number
---@param newY number
function player.y(newY) end
function player.y(newY)
end
---@overload fun(): number
---@param newZ number
function player.z(newZ) end
function player.z(newZ)
end
---@overload fun(): number
---@param newYaw number
function player.yaw(newYaw) end
function player.yaw(newYaw)
end
---@overload fun(): number
---@param newPitch number
function player.pitch(newPitch) end
function player.pitch(newPitch)
end
---@return boolean
function player.sneaking() return nil end
function player.sneaking()
return nil
end
---@return boolean
function player.sprinting() return nil end
function player.sprinting()
return nil
end
---@overload fun(): number
---@param newSlot number
function player.slot(newSlot) end
function player.slot(newSlot)
end
---@return string
function player.item() return nil end
function player.item()
return nil
end
---@return string
function player.offHandItem() return nil end
function player.offHandItem()
return nil
end
---@return void
function player.closeInventory() end
function player.closeInventory()
end
---@field nextBool fun(): boolean
random = {}
@@ -113,17 +137,23 @@ random = {}
---@param origin number
---@param bound number
---@return number
function random.nextInt(origin, bound) return nil end
function random.nextInt(origin, bound)
return nil
end
---@overload fun(): number
---@overload fun(bound: number): number
---@param origin number
---@param bound number
---@return number
function random.nextDouble(origin, bound) return nil end
function random.nextDouble(origin, bound)
return nil
end
---@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'
@@ -136,52 +166,84 @@ local iregion = {}
region = {}
---@return string
function iregion.name() return nil end
function iregion.name()
return nil
end
---@return RegionType
function iregion.type() return nil end
function iregion.type()
return nil
end
---@return boolean
function iregion.fire() return nil end
function iregion.fire()
return nil
end
---@return boolean
function iregion.freeze() return nil end
function iregion.freeze()
return nil
end
---@return boolean
function iregion.protect() return nil end
function iregion.protect()
return nil
end
---@return string
function iregion.loader() return nil end
function iregion.loader()
return nil
end
---@return Position
function iregion.copyPoint() return nil end
function iregion.copyPoint()
return nil
end
---@return Position
function iregion.minPointBuild() return nil end
function iregion.minPointBuild()
return nil
end
---@return Position
function iregion.maxPointBuild() return nil end
function iregion.maxPointBuild()
return nil
end
---@return Position
function iregion.minPointBuildExtension() return nil end
function iregion.minPointBuildExtension()
return nil
end
---@return Position
function iregion.maxPointBuildExtension() return nil end
function iregion.maxPointBuildExtension()
return nil
end
---@return Position
function iregion.testblockPoint() return nil end
function iregion.testblockPoint()
return nil
end
---@return Position
function iregion.minPointTestblock() return nil end
function iregion.minPointTestblock()
return nil
end
---@return Position
function iregion.maxPointTestblock() return nil end
function iregion.maxPointTestblock()
return nil
end
---@return Position
function iregion.minPointTestblockExtension() return nil end
function iregion.minPointTestblockExtension()
return nil
end
---@return Position
function iregion.maxPointTestblockExtension() return nil end
function iregion.maxPointTestblockExtension()
return nil
end
---@alias TNTMode 'ALLOW' | 'DENY' | 'ONLY_TB'
@@ -189,23 +251,35 @@ function iregion.maxPointTestblockExtension() return nil end
local tnt = {}
---@return TNTMode
function tnt.mode() return nil end
function tnt.mode()
return nil
end
---@return boolean
function tnt.enabled() return nil end
function tnt.enabled()
return nil
end
---@return boolean
function tnt.onlyTb() return nil end
function tnt.onlyTb()
return nil
end
---@return boolean
function tnt.onlyBuild() return nil end
function tnt.onlyBuild()
return nil
end
---@param name string
---@return iregion
function region.get(name) return nil end
function region.get(name)
return nil
end
---@return iregion[]
function region.list() return nil end
function region.list()
return nil
end
---@class tracerLib
tracer = {}
@@ -224,7 +298,9 @@ tracer = {}
---@field getId fun(): string
---@field getRecords fun(): {[number]: {[number]: TraceRecord}}
function tracer.getTraces() return nil end
function tracer.getTraces()
return nil
end
---@class Position
---@field x number
@@ -236,43 +312,65 @@ function tracer.getTraces() return nil end
server = {}
---@return string
function server.time() return nil end
function server.time()
return nil
end
---@return number
function server.ticks() return nil end
function server.ticks()
return nil
end
---@param position Position
---@return string
function getBlockAt(position) return nil end
function getBlockAt(position)
return nil
end
---@param position Position
---@param material string
---@return void
function setBlockAt(position, material) return nil end
function setBlockAt(position, material)
return nil
end
---@class tps
local tps = {}
---@return number
function tps.oneSecond() return nil end
function tps.oneSecond()
return nil
end
---@return number
function tps.tenSecond() return nil end
function tps.tenSecond()
return nil
end
---@return number
function tps.oneMinute() return nil end
function tps.oneMinute()
return nil
end
---@return number
function tps.fiveMinute() return nil end
function tps.fiveMinute()
return nil
end
---@return number
function tps.tenMinute() return nil end
function tps.tenMinute()
return nil
end
---@return number
function tps.current() return nil end
function tps.current()
return nil
end
---@return number
function tps.limit() return nil end
function tps.limit()
return nil
end
---@class storage
---@field global storageLib
@@ -286,24 +384,32 @@ local storageLib = {}
---@param key string
---@return any
function storageLib.get(key) return nil end
function storageLib.get(key)
return nil
end
---@param key string
---@param value any
---@return void
function storageLib.set(key, value) end
function storageLib.set(key, value)
end
---@param key string
---@return boolean
function storageLib.has(key) return nil end
function storageLib.has(key)
return nil
end
---@param key string
---@return void
function storageLib.remove(key) end
function storageLib.remove(key)
end
---@param key string
---@return Accessor
function storageLib.accessor(key) return nil end
function storageLib.accessor(key)
return nil
end
---@class Accessor
---@overload fun(): any
@@ -318,35 +424,46 @@ _worldedit = {}
---@overload fun(pos: Position[]): void
---@return Selection
function _worldedit.selection() return nil end
function _worldedit.selection()
return nil
end
---@param msg string
---@param callback fun(value: string): void
---@return void
function input(msg, callback) end
function input(msg, callback)
end
---@param ticks number
---@param callback fun(): void
---@return void
function delayed(ticks, callback) end
function delayed(ticks, callback)
end
---@param x number
---@param y number
---@param z number
---@return Position
function pos(x, y, z) return nil end
function pos(x, y, z)
return nil
end
---@return void
function exec(...) end
function exec(...)
end
---@param obj any
---@return number
function length(obj) return 0 end
function length(obj)
return 0
end
---@param separator string
---@param table any[]
---@return string
function join(separator, table) return "" end
function join(separator, table)
return ""
end
---@class EventType
---@class events
@@ -364,21 +481,23 @@ function join(separator, table) return "" end
---@field EntityDeath EventType
events = {}
---@param id EventType
---@param handler fun(params: any): void
---@return void
function event(id, handler) end
function event(id, handler)
end
---@param command string
---@param handler fun(params: string[]): void
---@return void
function command(command, handler) end
function command(command, handler)
end
---@param trigger string
---@param handler fun(pressed: boolean): void
---@return void
function hotkey(trigger, handler) end
function hotkey(trigger, handler)
end
---@class bossbar
bossbar = {}
@@ -394,39 +513,52 @@ local BossBar = {}
---@param color BossBarColor
---@param style BossBarStyle
---@return BossBar
function bossbar.create(title, color, style) return nil end
function bossbar.create(title, color, style)
return nil
end
---@return string
---@overload fun(title: string): void
function BossBar.title() end
function BossBar.title()
end
---@return BossBarColor
---@overload fun(color: BossBarColor): void
function BossBar.color() end
function BossBar.color()
end
---@return BossBarStyle
---@overload fun(style: BossBarStyle): void
function BossBar.style() end
function BossBar.style()
end
---@return number
---@overload fun(progress: number): void
function BossBar.progress() end
function BossBar.progress()
end
---@return boolean
---@overload fun(visible: boolean): void
function BossBar.visible() end
function BossBar.visible()
end
---@return boolean
---@param flag BossBarFlag
function BossBar.hasFlag(flag) return nil end
function BossBar.hasFlag(flag)
return nil
end
---@return void
---@param flag BossBarFlag
function BossBar.addFlag(flag) end
function BossBar.addFlag(flag)
end
---@return boolean
---@param flag BossBarFlag
function BossBar.removeFlag(flag) return nil end
function BossBar.removeFlag(flag)
return nil
end
---@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.UserSearchCommand
fun main(args: Array<String>) = SteamWar()
fun main(args: Array<String>) =
SteamWar()
.subcommands(
DatabaseCommand().subcommands(InfoCommand(), ResetCommand()),
UserCommand().subcommands(UserInfoCommand(), UserSearchCommand()),
+2 -1
View File
@@ -12,7 +12,8 @@ class DatabaseCommand: CliktCommand(name = "db") {
val useProduction by option().flag()
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() {
if (!useProduction && db.database == "production") {
+2 -1
View File
@@ -10,7 +10,8 @@ import de.steamwar.db.useDb
class InfoCommand : CliktCommand() {
val db by requireObject<Database>()
override fun run() = useDb {
override fun run() =
useDb {
val tables = execute("SHOW TABLES") { it.getString(1) }
echo(
+2 -1
View File
@@ -13,7 +13,8 @@ import java.io.File
class ResetCommand : CliktCommand() {
val db by requireObject<Database>()
override fun run() = useDb {
override fun run() =
useDb {
val schemaFile = File("/var/Schema.sql")
if (!schemaFile.exists()) {
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>"""
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
@@ -73,12 +74,21 @@ class DevCommand : CliktCommand("dev") {
if (serverDirectory.exists() && serverDirectory.isDirectory) serverDirectory else File(workingDir, 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 {
setLogConfig(args)
val version = findVersion(server) ?: throw CliktError("Unknown Server Version")
val worldFile = world?.absolute()?.toFile() ?: File(serverDir, "devtempworld")
val jarFile = jar?.absolutePath ?: additionalVersions[server]?.let { supportedVersionJars[it] } ?: supportedVersionJars[version]
val version = findVersion(server)
?: throw CliktError("Unknown Server 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")
if (!worldFile.exists()) {
@@ -108,7 +118,8 @@ class DevCommand : CliktCommand("dev") {
try {
devFile.delete()
} catch (_: Exception) { /* ignored */ }
} catch (_: Exception) { /* ignored */
}
}
}
@@ -145,11 +156,15 @@ class DevCommand : CliktCommand("dev") {
"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>) {
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) {
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(),
*args.toTypedArray(),
*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
class UserCommand : CliktCommand("user") {
override fun run() = Unit
override fun help(context: Context): String = "User related commands"
override fun run() =
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") {
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 fun run() = useDb {
override fun run() =
useDb {
val sessions =
SessionTable.selectAll().where { SessionTable.userId eq user.id.value }
.map { it[SessionTable.startTime] to it[SessionTable.endTime] }
@@ -49,7 +53,8 @@ class UserInfoCommand : CliktCommand("info") {
punishments.map {
row(
it.type,
SteamwarUser.byId(it.punisher)?.userName ?: it.punisher,
SteamwarUser.byId(it.punisher)?.userName
?: it.punisher,
it.startTime.toString(),
if (it.perma) "Perma" else it.endTime.toString(),
it.reason
+4 -2
View File
@@ -18,9 +18,11 @@ class UserSearchCommand : CliktCommand("search") {
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 {
joinedOr(
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 }) }
.firstOrNull()
?.let { return@transaction it }
@@ -182,8 +182,9 @@ public abstract class AbstractSWCommand<T> {
if (!checkType(method.getAnnotations(), method.getReturnType(), false, annotation -> {
CommandMetaData.Method methodMetaData = annotation.annotationType().getAnnotation(CommandMetaData.Method.class);
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) -> {
Class<?>[] types = methodMetaData.value();
if (types == null) return true;
@@ -33,7 +33,9 @@ public @interface CommandMetaData {
@Target(ElementType.ANNOTATION_TYPE)
@interface Method {
Class<?>[] value();
int minParameterCount() default 0;
int maxParameterCount() default Integer.MAX_VALUE;
}
@@ -44,6 +46,7 @@ public @interface CommandMetaData {
@Target(ElementType.ANNOTATION_TYPE)
@interface Parameter {
Class<?>[] value() default {};
Class<?> handler() default void.class;
}
@@ -148,7 +148,8 @@ class CommandPart<T> {
List<Object> currentArgs = new ArrayList<>(mappedArgs);
List<Object> varArgs = new ArrayList<>();
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;
varArgs.add(validArgument.value);
}
@@ -162,7 +163,8 @@ class CommandPart<T> {
}
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 (!ignoreAsArgument) {
mappedArgs.add(checkArgumentResult.value);
@@ -138,7 +138,8 @@ public class SubCommand<T> implements Comparable<SubCommand<T>> {
}
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;
}
if (commandPart == null) {
@@ -26,6 +26,7 @@ import java.lang.annotation.*;
@Repeatable(PluginCheck.PluginChecks.class)
public @interface PluginCheck {
Has has() default Has.THIS;
String value();
enum Has {
@@ -73,5 +73,6 @@ public abstract class PacketHandler {
}
@Retention(RetentionPolicy.RUNTIME)
protected @interface Handler {}
protected @interface Handler {
}
}
@@ -22,12 +22,14 @@ package de.steamwar;
import java.lang.reflect.InvocationTargetException;
public class ImplementationProvider {
private ImplementationProvider() {}
private ImplementationProvider() {
}
public static <T> T getImpl(String className) {
try {
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);
}
}
+18 -9
View File
@@ -46,7 +46,8 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
actor: SteamwarUser,
actionType: Type,
text: String = ""
) = useDb {
) =
useDb {
new {
this.time = Instant.now()
this.server = serverName
@@ -58,13 +59,16 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
}
@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
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
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
fun createSensitiveCommand(
@@ -72,13 +76,16 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
serverOwner: SteamwarUser?,
player: SteamwarUser?,
command: String
) = player?.let { create(serverName, serverOwner, it, Type.SENSITIVE_COMMAND, command) }
) =
player?.let { create(serverName, serverOwner, it, Type.SENSITIVE_COMMAND, command) }
@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
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
fun createGuiClick(
@@ -89,7 +96,8 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
clickType: String,
slot: Int,
itemName: String
) = create(
) =
create(
serverName,
serverOwner,
player,
@@ -98,7 +106,8 @@ class AuditLog(id: EntityID<Int>): IntEntity(id) {
)
@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
@@ -48,17 +48,20 @@ class BannedUserIPs(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<BannedUserIPs>(BannedUserIPsTable) {
@JvmStatic
fun get(userId: Int) = useDb {
fun get(userId: Int) =
useDb {
find { BannedUserIPsTable.userId eq userId }.toList()
}
@JvmStatic
fun get(ip: String) = useDb {
fun get(ip: String) =
useDb {
find { BannedUserIPsTable.ip eq ip }.toList()
}
@JvmStatic
fun banIP(userId: Int, ip: String) = useDb {
fun banIP(userId: Int, ip: String) =
useDb {
BannedUserIPsTable.insertIgnore {
it[BannedUserIPsTable.userId] = userId
it[BannedUserIPsTable.ip] = ip
@@ -67,7 +70,8 @@ class BannedUserIPs(id: EntityID<CompositeID>): CompositeEntity(id) {
}
@JvmStatic
fun unbanIPs(userId: Int) = useDb {
fun unbanIPs(userId: Int) =
useDb {
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 ip by BannedUserIPsTable.ip
fun remove() = useDb {
fun remove() =
useDb {
delete()
}
}
@@ -50,19 +50,24 @@ class BauweltMember(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<BauweltMember>(BauweltMemberTable) {
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
fun clear() = cache.clear()
fun clear() =
cache.clear()
@JvmStatic
@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
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 {
it[bauweltId] = ownerId
it[memberId] = newMemberId
@@ -74,21 +79,25 @@ class BauweltMember(id: EntityID<CompositeID>): CompositeEntity(id) {
@JvmStatic
@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) }
}
@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) }
}
@JvmStatic
@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
fun getMembers(bauwelt: Int) = useDb {
fun getMembers(bauwelt: Int) =
useDb {
find { bauweltId eq bauwelt }.toList().also { it.forEach { cache(it) } }
}
}
@@ -119,12 +128,20 @@ class BauweltMember(id: EntityID<CompositeID>): CompositeEntity(id) {
world = value
}
fun isBuild() = build
fun isSupervisor() = world
fun isWorldEdit() = build
fun isWorld() = world
fun isBuild() =
build
fun remove() = useDb {
fun isSupervisor() =
world
fun isWorldEdit() =
build
fun isWorld() =
world
fun remove() =
useDb {
delete()
}
}
@@ -54,7 +54,8 @@ object CheckedSchematicTable: CompositeIdTable("CheckedSchematic") {
class CheckedSchematic(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<CheckedSchematic>(CheckedSchematicTable) {
@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 {
it[this.nodeId] = node.id
it[this.nodeOwner] = EntityID(node.owner, SteamwarUserTable)
@@ -69,17 +70,20 @@ class CheckedSchematic(id: EntityID<CompositeID>): CompositeEntity(id) {
}
@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()
}
@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()
}
@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()
}
}
+21 -10
View File
@@ -48,7 +48,8 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
private var current: Event? = null
@JvmStatic
fun get(): Event? = if (current?.now() == true) {
fun get(): Event? =
if (current?.now() == true) {
current
} else useDb {
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
fun getAll() = useDb { all().toList() }
fun getAll() =
useDb { all().toList() }
@JvmStatic
fun create(name: String, start: Timestamp, end: Timestamp) = useDb {
fun create(name: String, start: Timestamp, end: Timestamp) =
useDb {
EventTable.insertAndGetId {
it[this.name] = name
it[this.deadline] = start.toInstant()
@@ -71,13 +74,16 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
}
@JvmStatic
fun byId(id: Int) = useDb { findById(id) }
fun byId(id: Int) =
useDb { findById(id) }
@JvmStatic
fun get(name: String) = useDb { find { EventTable.name eq name }.firstOrNull() }
fun get(name: String) =
useDb { find { EventTable.name eq name }.firstOrNull() }
@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 })
@@ -96,8 +102,11 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
var publicSchemsOnly by EventTable.publicsOnly
private set
fun publicSchemsOnly() = publicSchemsOnly
fun now() = Instant.now().let { it.isAfter(start.toInstant()) && it.isBefore(end.toInstant()) }
fun publicSchemsOnly() =
publicSchemsOnly
fun now() =
Instant.now().let { it.isAfter(start.toInstant()) && it.isBefore(end.toInstant()) }
fun update(
name: String,
@@ -107,7 +116,8 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
schematicType: SchematicType?,
maxPlayers: Int,
publicSchemsOnly: Boolean
) = useDb {
) =
useDb {
this@Event.eventName = name
this@Event.deadline = deadline
this@Event.start = start
@@ -117,5 +127,6 @@ class Event(id: EntityID<Int>) : IntEntity(id) {
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
fun byId(fightId: Int) = useDb { findById(fightId) }
fun byId(fightId: Int) =
useDb { findById(fightId) }
@JvmStatic
fun byId(group: EventGroup) = useDb {
fun byId(group: EventGroup) =
useDb {
find { EventFightTable.groupId eq group.id }.orderBy(EventFightTable.startTime to SortOrder.DESC).toList()
}
@JvmStatic
fun getLast(group: EventGroup) = useDb {
fun getLast(group: EventGroup) =
useDb {
Optional.ofNullable(
find { EventFightTable.groupId eq group.id }.orderBy(EventFightTable.startTime to SortOrder.DESC)
.firstOrNull()
@@ -68,13 +71,15 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
}
@JvmStatic
fun loadAllComingFights() = useDb {
fun loadAllComingFights() =
useDb {
fights.clear()
fights.addAll(find { EventFightTable.startTime greaterEq Instant.now() }.orderBy(EventFightTable.startTime to SortOrder.ASC))
}
@JvmStatic
fun getEvent(eventId: Int) = useDb {
fun getEvent(eventId: Int) =
useDb {
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,
redTeam: Int,
spectatePort: Int?
) = useDb {
) =
useDb {
get(
EventFightTable.insertAndGetId {
it[eventId] = EntityID(event, EventTable)
@@ -155,16 +161,25 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
val losser: Team?
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 hasFinished() = fight != null || ergebnis != 0
fun setGroup(group: Int?) =
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))
}
override fun hashCode() = fightID
override fun equals(other: Any?) = other is EventFight && other.fightID == fightID
override fun compareTo(other: EventFight): Int = startTime.compareTo(other.startTime)
override fun hashCode() =
fightID
override fun equals(other: Any?) =
other is EventFight && other.fightID == fightID
override fun compareTo(other: EventFight): Int =
startTime.compareTo(other.startTime)
fun update(
startTime: Timestamp,
@@ -173,7 +188,8 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
teamBlue: Int,
teamRed: Int,
spectatePort: Int?
) = useDb {
) =
useDb {
this@EventFight.startTime = startTime
this@EventFight.spielmodus = spielmodus
this@EventFight.map = map
@@ -182,7 +198,8 @@ class EventFight(id: EntityID<Int>) : IntEntity(id), Comparable<EventFight> {
this@EventFight.spectatePort = spectatePort
}
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
}
@@ -44,13 +44,16 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<EventGroup>(EventGroupTable) {
@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
fun byId(groupId: Int) = useDb { Optional.ofNullable(findById(groupId)) }
fun byId(groupId: Int) =
useDb { Optional.ofNullable(findById(groupId)) }
@JvmStatic
fun create(event: Event, name: String, type: EventGroupType) = useDb {
fun create(event: Event, name: String, type: EventGroupType) =
useDb {
new {
this.eventID = event.id.value
this.groupName = name
@@ -97,7 +100,8 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
val dependents by lazy { EventRelation.getGroupRelations(this) }
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
@@ -118,18 +122,22 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
blueTeamAdd += pointsPerWin
redTeamAdd += pointsPerLoss
}
2 -> {
blueTeamAdd += pointsPerLoss
redTeamAdd += pointsPerWin
}
0 -> if (fight.fight != null) {
blueTeamAdd += pointsPerDraw
redTeamAdd += pointsPerDraw
}
}
p[fight.teamBlue] = p[fight.teamBlue]?.plus(blueTeamAdd) ?: blueTeamAdd
p[fight.teamRed] = p[fight.teamRed]?.plus(redTeamAdd) ?: redTeamAdd
p[fight.teamBlue] = p[fight.teamBlue]?.plus(blueTeamAdd)
?: blueTeamAdd
p[fight.teamRed] = p[fight.teamRed]?.plus(redTeamAdd)
?: redTeamAdd
}
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.type = type
this@EventGroup.pointsPerWin = pointsPerWin
@@ -148,7 +158,8 @@ class EventGroup(id: EntityID<Int>) : IntEntity(id) {
this@EventGroup.pointsPerDraw = pointsPerDraw
}
override fun delete() = useDb { super.delete() }
override fun delete() =
useDb { super.delete() }
enum class EventGroupType {
GROUP_STAGE,
@@ -39,7 +39,8 @@ object EventRelationTable : IntIdTable("EventRelation") {
class EventRelation(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<EventRelation>(EventRelationTable) {
@JvmStatic
fun get(event: Event) = useDb {
fun get(event: Event) =
useDb {
EventRelationTable.innerJoin(EventFightTable)
.select(EventRelationTable.columns)
.where { EventFightTable.eventId eq event.id }
@@ -47,7 +48,8 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
}
@JvmStatic
fun byId(id: Int) = useDb { findById(id) }
fun byId(id: Int) =
useDb { findById(id) }
@JvmStatic
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() }
@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 {
this.fightEntityId = fight.id
this.fightTeam = fightTeam
@@ -100,30 +103,39 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
var fromPlace by EventRelationTable.fromPlace
private set
fun getId() = id.value
fun setUpdateTeam(team: FightTeam) = useDb {
fun getId() =
id.value
fun setUpdateTeam(team: FightTeam) =
useDb {
fightTeam = team
}
fun setFromFight(fight: EventFight, place: Int) = useDb {
fun setFromFight(fight: EventFight, place: Int) =
useDb {
fromType = FromType.FIGHT
fromId = fight.id.value
fromPlace = place
}
fun setFromGroup(group: EventGroup, place: Int) = useDb {
fun setFromGroup(group: EventGroup, place: Int) =
useDb {
fromType = FromType.GROUP
fromId = group.id.value
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.GROUP -> fromGroup?.calculatePoints()?.toList()?.sortedBy { (_, v) -> v }?.reversed()?.elementAt(fromPlace)?.first
} }
}
}
fun apply(): Boolean {
val team = getAdvancingTeam() ?: return false
val team = getAdvancingTeam()
?: return false
useDb {
when (fightTeam) {
@@ -135,7 +147,8 @@ class EventRelation(id: EntityID<Int>) : IntEntity(id) {
return true
}
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
+18 -9
View File
@@ -50,7 +50,8 @@ object FightTable : IntIdTable("Fight", "FightId") {
class Fight(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Fight>(FightTable) {
@JvmStatic
fun getById(id: Int) = useDb { get(id) }
fun getById(id: Int) =
useDb { get(id) }
@JvmStatic
fun create(
@@ -64,7 +65,8 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
redschem: Int?,
win: Int,
wincondition: String
): Int = useDb {
): Int =
useDb {
FightTable.insertAndGetId {
it[FightTable.gamemode] = gamemode
it[FightTable.server] = server
@@ -80,7 +82,8 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
}
@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 fightPlayer = FightPlayer.batchGet(fights.map { it.id.value })
@@ -93,7 +96,8 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
}
@JvmStatic
fun markReplayAvailable(id: Int) = useDb {
fun markReplayAvailable(id: Int) =
useDb {
FightTable.update({ FightTable.id eq id }) {
it[replayAvailable] = true
}
@@ -131,12 +135,16 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
} else {
false
}
} ?: false
}
?: false
}
}
fun replayExists() = schemType != null && replayAvailable
fun replayAllowed() = replayAllowed
fun replayExists() =
schemType != null && replayAvailable
fun replayAllowed() =
replayAllowed
lateinit var bluePlayers: List<FightPlayer>
lateinit var redPlayers: List<FightPlayer>
@@ -146,11 +154,12 @@ class Fight(id: EntityID<Int>) : IntEntity(id) {
val red = mutableListOf<FightPlayer>()
for (player in fightPlayers.filter { it.fightID == id.value }) {
if (player.team == 1)
if (player.team == 1) {
blue.add(player)
else
} else {
red.add(player)
}
}
bluePlayers = blue
redPlayers = red
@@ -52,7 +52,8 @@ class FightPlayer(id: EntityID<CompositeID>) : CompositeEntity(id) {
kit: String,
kills: Int,
out: Boolean
) = useDb {
) =
useDb {
FightPlayerTable.insertIgnore {
it[this.fightId] = fightId
it[this.userId] = userId
@@ -64,7 +65,8 @@ class FightPlayer(id: EntityID<CompositeID>) : CompositeEntity(id) {
}
@JvmStatic
fun batchGet(fightIds: List<Int>) = useDb {
fun batchGet(fightIds: List<Int>) =
useDb {
find { FightPlayerTable.fightId inList fightIds.toList() }.toList()
}
}
@@ -76,5 +78,6 @@ class FightPlayer(id: EntityID<CompositeID>) : CompositeEntity(id) {
val kills by FightPlayerTable.kills
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) {
for (String m : Server.Maps) {
if (m.equalsIgnoreCase(map))
return m;
if (m.equalsIgnoreCase(map)) return m;
}
return null;
}
@@ -47,17 +47,20 @@ class IgnoreSystem(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<IgnoreSystem>(IgnoreSystemTable) {
@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
fun isIgnored(ignorer: SteamwarUser, ignored: SteamwarUser) = useDb {
fun isIgnored(ignorer: SteamwarUser, ignored: SteamwarUser) =
useDb {
find {
(IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id)
}.firstOrNull() != null
}
@JvmStatic
fun ignore(ignorer: SteamwarUser, ignored: SteamwarUser) = useDb {
fun ignore(ignorer: SteamwarUser, ignored: SteamwarUser) =
useDb {
new {
this.ignorer = ignorer.id
this.ignored = ignored.id
@@ -65,7 +68,8 @@ class IgnoreSystem(id: EntityID<CompositeID>) : CompositeEntity(id) {
}
@JvmStatic
fun unIgnore(ignorer: SteamwarUser, ignored: SteamwarUser) = useDb {
fun unIgnore(ignorer: SteamwarUser, ignored: SteamwarUser) =
useDb {
find {
(IgnoreSystemTable.ignorer eq ignorer.id) and (IgnoreSystemTable.ignored eq ignored.id)
}.firstOrNull()?.delete()
@@ -48,28 +48,33 @@ object LeaderboardTable : CompositeIdTable("Leaderboard") {
class Leaderboard(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<Leaderboard>(LeaderboardTable) {
@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()
}
@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()
}
@JvmStatic
fun getPlayerPlacement(user: SteamwarUser, name: String) = useDb {
fun getPlayerPlacement(user: SteamwarUser, name: String) =
useDb {
LeaderboardTable.select(LeaderboardTable.time.count())
.where {
(LeaderboardTable.name eq name) and (LeaderboardTable.time lessSubQuery LeaderboardTable.select(
LeaderboardTable.time
).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
fun upsert(userId: Int, name: String, time: Long, bestTime: Boolean) = useDb {
fun upsert(userId: Int, name: String, time: Long, bestTime: Boolean) =
useDb {
LeaderboardTable.upsert(
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) {
companion object : CompositeEntityClass<Mod>(ModTable) {
@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()
}
@JvmStatic
fun getOrCreate(modName: String, platform: Platform) = useDb {
get(modName, platform) ?: new {
fun getOrCreate(modName: String, platform: Platform) =
useDb {
get(modName, platform)
?: new {
this.platform = platform
this.modName = modName
this.type = ModType.UNKLASSIFIED
@@ -52,7 +55,8 @@ class Mod(id: EntityID<CompositeID>) : CompositeEntity(id) {
}
@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())
.orderBy(
ModTable.modName to SortOrder.DESC
@@ -60,7 +64,8 @@ class Mod(id: EntityID<CompositeID>) : CompositeEntity(id) {
}
@JvmStatic
fun findFirstMod() = useDb {
fun findFirstMod() =
useDb {
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) {
@JvmStatic
fun getLatest(node: SchematicNode) = useDb {
fun getLatest(node: SchematicNode) =
useDb {
find { (NodeDataTable.nodeId eq node.nodeId) }.orderBy(NodeDataTable.createdAt to SortOrder.DESC).firstOrNull()
}
@JvmStatic
fun get(node: SchematicNode) = useDb {
fun get(node: SchematicNode) =
useDb {
find { (NodeDataTable.nodeId eq node.nodeId) }.orderBy(NodeDataTable.createdAt to SortOrder.ASC).toList()
}
@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)
}
@JvmStatic
fun getRevisions(node: SchematicNode) = useDb {
fun getRevisions(node: SchematicNode) =
useDb {
count(NodeDataTable.nodeId eq node.nodeId).toInt()
}
@JvmStatic
fun saveFromStream(node: SchematicNode, blob: InputStream, format: SchematicFormat) = useDb {
fun saveFromStream(node: SchematicNode, blob: InputStream, format: SchematicFormat) =
useDb {
NodeDataTable.insert {
it[NodeDataTable.nodeId] = EntityID(node.getId(), SchematicNodeTable)
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 }
}
override fun delete() = useDb { super.delete() }
override fun delete() =
useDb { super.delete() }
enum class SchematicFormat(val fileEnding: String) {
MCEDIT(".schematic"),
@@ -44,8 +44,7 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
@JvmStatic
fun getLink(schem: SchematicNode): String {
if (schem.isDir())
throw IllegalArgumentException("Cannot get link for directory")
if (schem.isDir()) throw IllegalArgumentException("Cannot get link for directory")
val digest = MessageDigest.getInstance("SHA-1")
digest.update("${Instant.now()}${schem.owner}${schem.nodeId}".toByteArray())
@@ -53,7 +52,8 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
useDb {
findByIdAndUpdate(schem.id.value) {
it.link = hash
} ?: new {
}
?: new {
nodeId = schem.id.value
link = hash
}
@@ -62,7 +62,8 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
}
@JvmStatic
fun get(link: String) = useDb {
fun get(link: String) =
useDb {
find { NodeDownloadTable.link eq link }.firstOrNull()
}
}
@@ -71,7 +72,8 @@ class NodeDownload(id: EntityID<Int>) : IntEntity(id) {
var link by NodeDownloadTable.link
var timestamp by NodeDownloadTable.timestamp.transform({ it.toInstant() }, { Timestamp.from(it) })
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
}
@@ -48,44 +48,54 @@ object NodeMemberTable : CompositeIdTable("NodeMember") {
class NodeMember(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<NodeMember>(NodeMemberTable) {
@JvmStatic
fun createNodeMember(node: Int, member: Int): NodeMember = useDb {
fun createNodeMember(node: Int, member: Int): NodeMember =
useDb {
NodeMemberTable.insertIgnore {
it[this.node] = EntityID(node, SchematicNodeTable)
it[this.userId] = EntityID(member, SteamwarUserTable)
}
getNodeMember(node, member) ?: throw IllegalStateException("NodeMember not created")
getNodeMember(node, member)
?: throw IllegalStateException("NodeMember not created")
}
@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")
NodeMemberTable.insertIgnore {
it[this.node] = EntityID(node, SchematicNodeTable)
it[this.userId] = EntityID(member, SteamwarUserTable)
it[NodeMemberTable.parentNode] = parent.getId()
}
getNodeMember(node, member) ?: throw IllegalStateException("NodeMember not created")
getNodeMember(node, member)
?: throw IllegalStateException("NodeMember not created")
}
@JvmStatic
fun createNodeMember(node: Int, member: SteamwarUser) = createNodeMember(node, member.id.value)
fun createNodeMember(node: Int, member: SteamwarUser) =
createNodeMember(node, member.id.value)
@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()
}
@JvmStatic
fun getNodeMember(node: Int, member: SteamwarUser) = getNodeMember(node, member.id.value)
fun getNodeMember(node: Int, member: SteamwarUser) =
getNodeMember(node, member.id.value)
@JvmStatic
fun getNodeMembers(node: Int) = useDb { find { NodeMemberTable.node eq node }.toSet() }
fun getNodeMembers(node: Int) =
useDb { find { NodeMemberTable.node eq node }.toSet() }
@JvmStatic
fun getSchematics(member: Int) = useDb { find { NodeMemberTable.userId eq member }.toSet() }
fun getSchematics(member: Int) =
useDb { find { NodeMemberTable.userId eq member }.toSet() }
@JvmStatic
fun init() = Unit
fun init() =
Unit
}
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) })
private set
fun setParentId(id: Int?) = useDb {
fun setParentId(id: Int?) =
useDb {
parent = Optional.ofNullable(id)
}
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
}
@@ -47,13 +47,15 @@ object PersonalKitTable: CompositeIdTable("PersonalKit") {
class InternalKit(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<InternalKit>(PersonalKitTable) {
@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) }
.toList()
}
@JvmStatic
fun get(userId: Int, gamemode: String, kitName: String) = useDb {
fun get(userId: Int, gamemode: String, kitName: String) =
useDb {
findById(CompositeID {
it[PersonalKitTable.userId] = EntityID(userId, SteamwarUserTable)
it[PersonalKitTable.gamemode] = gamemode
@@ -62,7 +64,8 @@ class InternalKit(id: EntityID<CompositeID>): CompositeEntity(id) {
}
@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(
CompositeID {
it[PersonalKitTable.userId] = EntityID(userId, SteamwarUserTable)
@@ -77,7 +80,8 @@ class InternalKit(id: EntityID<CompositeID>): CompositeEntity(id) {
}
@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) }
.firstOrNull()
}
@@ -108,14 +112,16 @@ class InternalKit(id: EntityID<CompositeID>): CompositeEntity(id) {
get() = rawArmor
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) }
.filter { it.id.value != this@InternalKit.id.value }
.forEach { it.inUse = false }
inUse = true
}
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
}
@@ -52,13 +52,15 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
val PERMA_TIME: Timestamp = Timestamp.from(Instant.ofEpochSecond(946674800))
@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)
.firstOrNull()
}
@JvmStatic
fun getPunishmentsOfPlayer(user: Int) = useDb {
fun getPunishmentsOfPlayer(user: Int) =
useDb {
find {
PunishmentTable.id inSubQuery PunishmentTable.select(PunishmentTable.id.max())
.where { PunishmentTable.userId eq user }.groupBy(
@@ -68,13 +70,16 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
}
@JvmStatic
fun getAllPunishmentsOfPlayer(user: Int) = useDb {
fun getAllPunishmentsOfPlayer(user: Int) =
useDb {
find { PunishmentTable.userId eq user }.orderBy(PunishmentTable.id to SortOrder.DESC).toList()
}
@JvmStatic
fun isPunished(user: SteamwarUser, type: PunishmentType, callback: Consumer<Punishment>): Boolean = useDb {
val punishment = getPunsihmentOfPlayer(user.id.value, type) ?: return@useDb false
fun isPunished(user: SteamwarUser, type: PunishmentType, callback: Consumer<Punishment>): Boolean =
useDb {
val punishment = getPunsihmentOfPlayer(user.id.value, type)
?: return@useDb false
if (punishment.isCurrent()) {
callback.accept(punishment)
@@ -92,7 +97,8 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
reason: String,
endTime: Timestamp,
perma: Boolean
) = useDb {
) =
useDb {
new {
this.userId = user
this.punisher = executor
@@ -120,9 +126,11 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
var reason by PunishmentTable.reason
private set
fun isPerma() = perma
fun isPerma() =
perma
fun isCurrent() = perma || endTime.after(Date())
fun isCurrent() =
perma || endTime.after(Date())
enum class PunishmentType(
val teamMessage: String?,
@@ -185,6 +193,7 @@ class Punishment(id: EntityID<Int>) : IntEntity(id) {
),
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) {
companion object : CompositeEntityClass<Referee>(RefereeTable) {
@JvmStatic
fun add(eventId: Int, userId: Int) = useDb {
fun add(eventId: Int, userId: Int) =
useDb {
new {
this.eventID = eventId
this.userID = userId
@@ -51,12 +52,14 @@ class Referee(id: EntityID<CompositeID>): CompositeEntity(id) {
}
@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()
}
@JvmStatic
fun get(event: Int) = useDb {
fun get(event: Int) =
useDb {
find { RefereeTable.eventId eq event }.map { it.userID }.toSet()
}
}
@@ -40,10 +40,12 @@ class SWException {
val serverName = File(cwd).name
@JvmStatic
fun init() = Unit
fun init() =
Unit
@JvmStatic
fun log(message: String, stacktrace: String) = useDb {
fun log(message: String, stacktrace: String) =
useDb {
ExceptionTable.insert {
it[ExceptionTable.server] = serverName
it[ExceptionTable.message] = generateMessage(message)
@@ -54,7 +56,8 @@ class SWException {
}
@JvmStatic
fun logGetId(message: String, stacktrace: String) = useDb {
fun logGetId(message: String, stacktrace: String) =
useDb {
ExceptionTable.insertAndGetId {
it[ExceptionTable.server] = serverName
it[ExceptionTable.message] = generateMessage(message)
@@ -58,12 +58,15 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
val tabCache = mutableMapOf<Int, MutableMap<String, List<String>>>()
@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
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",
listOf(
IntegerColumnType() to user.getId(),
@@ -73,10 +76,12 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
)
@JvmStatic
fun getAllMap(user: SteamwarUser) = getAll(user).mapToIds()
fun getAllMap(user: SteamwarUser) =
getAll(user).mapToIds()
@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",
listOf(
IntegerColumnType() to schematicId,
@@ -89,7 +94,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
)
@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 = ?",
listOf(
IntegerColumnType() to schematicId,
@@ -104,7 +110,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
).firstOrNull()
@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 = ?",
listOf(
IntegerColumnType() to user.getId(),
@@ -119,7 +126,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
accessibleByUserType(user, type).mapToIds()
@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 = ?",
listOf(
IntegerColumnType() to user.getId(),
@@ -131,7 +139,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
).isNotEmpty()
@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",
listOf(
IntegerColumnType() to user.getId(),
@@ -144,12 +153,14 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
@JvmStatic
@Deprecated("Use byId")
fun byIdAndUser(ignored: SteamwarUser, id: Int) = useDb {
fun byIdAndUser(ignored: SteamwarUser, id: Int) =
useDb {
findById(id)
}
@JvmStatic
fun parentsOfNode(user: SteamwarUser, id: Int) = fromSql(
fun parentsOfNode(user: SteamwarUser, id: Int) =
fromSql(
"""
WITH RECURSIVE
ESN_R AS (
@@ -242,7 +253,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
)
@JvmStatic
fun createSchematic(owner: Int, name: String, parent: Int?) = createSchematicNode(
fun createSchematic(owner: Int, name: String, parent: Int?) =
createSchematicNode(
owner, name, parent,
SchematicType.Normal.toDB(), ""
)
@@ -252,7 +264,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
createSchematicNode(owner, name, parent, null, "")
@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 {
it[this.owner] = EntityID(owner, SteamwarUserTable)
it[this.name] = name
@@ -261,14 +274,17 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
it[this.item] = item
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
fun byId(id: Int) = useDb { findById(id) }
fun byId(id: Int) =
useDb { findById(id) }
@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()
}
@@ -277,37 +293,44 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
getSchematicNode(owner, name, parent.nodeId)
@JvmStatic
fun getSchematicNodeInNode(parent: Int?) = useDb {
fun getSchematicNodeInNode(parent: Int?) =
useDb {
find { (SchematicNodeTable.parent eq parent) }.orderBy(SchematicNodeTable.name to SortOrder.ASC).toList()
}
@JvmStatic
fun getSchematicNodeInNode(parent: SchematicNode) = getSchematicNodeInNode(parent.nodeId)
fun getSchematicNodeInNode(parent: SchematicNode) =
getSchematicNodeInNode(parent.nodeId)
@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()
}
@JvmStatic
fun getSchematicNode(id: Int) = byId(id)
fun getSchematicNode(id: Int) =
byId(id)
@JvmStatic
fun getAllAccessibleSchematicsOfType(user: Int, type: String) =
accessibleByUserType(SteamwarUser.byId(user)!!, SchematicType.fromDB(type)!!)
@JvmStatic
fun getAllSchematicsAccessibleByUser(user: Int) = getAll(SteamwarUser.byId(user)!!)
fun getAllSchematicsAccessibleByUser(user: Int) =
getAll(SteamwarUser.byId(user)!!)
@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(
SchematicNodeTable.name to SortOrder.ASC
).toList()
}
@JvmStatic
fun getAllSchematicsOfType(type: SchematicType) = useDb {
fun getAllSchematicsOfType(type: SchematicType) =
useDb {
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
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() }
}
@@ -372,7 +396,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
val list = mutableListOf<String>()
if (s.contains("/")) {
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 br = pa.generateBreadcrumbs(user)
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
var schemtype: SchematicType
get() = checkDir { SchematicType.fromDB(nodeType!!) ?: SchematicType.Normal }
get() = checkDir {
SchematicType.fromDB(nodeType!!)
?: SchematicType.Normal
}
set(value) = checkDir { useDb { nodeType = value.toDB() } }
var config by SchematicNodeTable.config
val members: Set<NodeMember> by lazy { NodeMember.getNodeMembers(nodeId) }
private lateinit var breadcrumbs: String
fun getFileEnding(): String = checkDir { NodeData.getLatest(this)!!.nodeFormat.fileEnding }
fun getId() = nodeId
fun isDir() = nodeType == null
fun getFileEnding(): String =
checkDir { NodeData.getLatest(this)!!.nodeFormat.fileEnding }
fun getId() =
nodeId
fun isDir() =
nodeType == null
private fun <T> checkDir(block: () -> T): T {
if (isDir()) {
@@ -435,17 +468,29 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
return block()
}
fun replaceColor() = getConfig(ConfigFlags.REPLACE_COLOR)
fun setReplaceColor(value: Boolean) = setConfig(ConfigFlags.REPLACE_COLOR, value)
fun replaceColor() =
getConfig(ConfigFlags.REPLACE_COLOR)
fun allowReplay() = getConfig(ConfigFlags.ALLOW_REPLAY)
fun setAllowReplay(value: Boolean) = setConfig(ConfigFlags.ALLOW_REPLAY, value)
fun setReplaceColor(value: Boolean) =
setConfig(ConfigFlags.REPLACE_COLOR, value)
fun isPrepared() = getConfig(ConfigFlags.IS_PREPARED)
fun setPrepared(value: Boolean) = setConfig(ConfigFlags.IS_PREPARED, value)
fun allowReplay() =
getConfig(ConfigFlags.ALLOW_REPLAY)
fun getConfig(flag: ConfigFlags) = config and (1 shl flag.ordinal) != 0
fun setConfig(flag: ConfigFlags, value: Boolean) = useDb {
fun setAllowReplay(value: Boolean) =
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 or (1 shl flag.ordinal)
} else {
@@ -453,11 +498,13 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
}
}
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
override fun hashCode() = nodeId
override fun hashCode() =
nodeId
override fun equals(other: Any?): Boolean {
if (other !is SchematicNode) return false
@@ -471,7 +518,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
return breadcrumbs
}
fun generateBreadcrumbs(split: String, user: SteamwarUser): String = useDb {
fun generateBreadcrumbs(split: String, user: SteamwarUser): String =
useDb {
val builder: StringBuilder = StringBuilder(name)
if (isDir()) {
builder.append(split)
@@ -481,7 +529,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
currentNode = currentNode
.let {
NodeMember.getNodeMember(it.nodeId, user.getId())
?.parent?.orElse(null) ?: it.parent
?.parent?.orElse(null)
?: it.parent
}
?.let { findById(it) }
?.also {
@@ -491,7 +540,8 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
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>>()
var currentNode: SchematicNode? = this@SchematicNode
while (currentNode != null) {
@@ -501,14 +551,16 @@ class SchematicNode(id: EntityID<Int>) : IntEntity(id) {
}
.let {
NodeMember.getNodeMember(it.nodeId, user.getId())
?.parent?.orElse(null) ?: it.parent
?.parent?.orElse(null)
?: it.parent
}
?.let { findById(it) }
}
return@useDb map
}
fun accessibleByUser(user: SteamwarUser) = schematicAccessibleForUser(user, nodeId)
fun accessibleByUser(user: SteamwarUser) =
schematicAccessibleForUser(user, nodeId)
enum class ConfigFlags {
REPLACE_COLOR,
+13 -6
View File
@@ -40,15 +40,18 @@ object ScriptTable: IntIdTable("Script") {
class Script(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Script>(ScriptTable) {
@JvmStatic
fun byId(id: Int) = useDb { findById(id) }
fun byId(id: Int) =
useDb { findById(id) }
@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()
}
@JvmStatic
fun create(user: SteamwarUser, name: String, code: String) = useDb {
fun create(user: SteamwarUser, name: String, code: String) =
useDb {
new {
this.userId = user.id.value
this.scriptName = name
@@ -57,12 +60,15 @@ class Script(id: EntityID<Int>) : IntEntity(id) {
}
@JvmStatic
fun list(user: SteamwarUser) = useDb {
fun list(user: SteamwarUser) =
useDb {
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 })
private var scriptName by ScriptTable.name
private var scriptCode by ScriptTable.code
@@ -75,5 +81,6 @@ class Script(id: EntityID<Int>) : IntEntity(id) {
get() = scriptCode
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 {
@JvmStatic
fun insertSession(userId: Int, startTime: Timestamp) = useDb {
fun insertSession(userId: Int, startTime: Timestamp) =
useDb {
SessionTable.insert {
it[SessionTable.userId] = EntityID(userId, SteamwarUserTable)
it[SessionTable.startTime] = startTime.toInstant()
@@ -77,16 +77,24 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
}
@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
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
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
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) {
byId[user.getId()] = user
@@ -116,27 +124,33 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
}
newPlayer.accept(uuid)
get(uuid) ?: error("User $uuid not found after creation!")
get(uuid)
?: error("User $uuid not found after creation!")
}
}
@JvmStatic
fun getUsersWithPerm(perm: UserPerm) = useDb {
fun getUsersWithPerm(perm: UserPerm) =
useDb {
UserPermTable.join(SteamwarUserTable, JoinType.INNER, UserPermTable.user, SteamwarUserTable.id)
.select(SteamwarUserTable.fields).where { UserPermTable.perm eq perm }.map { wrapRow(it) }
}
@JvmStatic
fun getServerTeam() = useDb { listOf(
fun getServerTeam() =
useDb {
listOf(
getUsersWithPerm(UserPerm.PREFIX_ADMIN),
getUsersWithPerm(UserPerm.PREFIX_DEVELOPER),
getUsersWithPerm(UserPerm.PREFIX_MODERATOR),
getUsersWithPerm(UserPerm.PREFIX_SUPPORTER),
getUsersWithPerm(UserPerm.PREFIX_BUILDER),
).flatten() }
).flatten()
}
@JvmStatic
fun getTeam(teamId: Int) = useDb {
fun getTeam(teamId: Int) =
useDb {
find { SteamwarUserTable.team eq teamId }.toList()
}
@@ -167,10 +181,15 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
set(value) = useDb {
leaderInternal = value
}
fun isLeader() = leader
fun isLeader() =
leader
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 bedrock by SteamwarUserTable.bedrock
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 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 getId() = id.value
fun getUUID(): UUID =
uuid
fun getPunishment(punishment: Punishment.PunishmentType) = punishments[punishment]
fun isPunished(punishment: Punishment.PunishmentType) = getPunishment(punishment)
fun getId() =
id.value
fun getPunishment(punishment: Punishment.PunishmentType) =
punishments[punishment]
fun isPunished(punishment: Punishment.PunishmentType) =
getPunishment(punishment)
?.let {
if (!it.isCurrent()) {
if (punishment == Punishment.PunishmentType.Ban) {
@@ -217,39 +245,54 @@ class SteamwarUser(id: EntityID<Int>): IntEntity(id) {
}
return@let true
} ?: false
}
?: false
fun hasPerm(perm: UserPerm) = perms.contains(perm)
fun perms() = perms
fun prefix() = prefix
fun hasPerm(perm: UserPerm) =
perms.contains(perm)
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 ->
return@exec if (rs.next()) {
rs.getBigDecimal("Playtime").toDouble()
} else {
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 ->
return@exec if (rs.next()) {
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 ->
return@exec if (rs.next()) {
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[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))
}
fun hasPassword() = password != null
fun hasPassword() =
password != null
fun generateHash(password: String, salt: ByteArray): ByteArray =
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>()
@JvmStatic
fun clear() = synchronized(teamCache) { teamCache.clear() }
fun clear() =
synchronized(teamCache) { teamCache.clear() }
@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
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
fun getAll() = useDb { find { not(TeamTable.deleted) }.toList() }
fun getAll() =
useDb { find { not(TeamTable.deleted) }.toList() }
@JvmStatic
fun create(kuerzel: String, name: String) = useDb {
fun create(kuerzel: String, name: String) =
useDb {
new {
this.kuerzel = kuerzel
this.name = name
@@ -67,8 +72,11 @@ class Team(id: EntityID<Int>) : IntEntity(id) {
private set
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 disband(user: SteamwarUser) = useDb {
fun size() =
useDb { SteamwarUser.find { SteamwarUserTable.team eq teamId }.count().toInt() }
fun disband(user: SteamwarUser) =
useDb {
user.team = 0
deleted = true
teamCache.remove(teamId)
@@ -47,12 +47,14 @@ object TeamTeilnahmeTable : CompositeIdTable("TeamTeilnahme") {
class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<TeamTeilnahme>(TeamTeilnahmeTable) {
@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
}
@JvmStatic
fun teilnehmen(teamId: Int, eventId: Int) = useDb {
fun teilnehmen(teamId: Int, eventId: Int) =
useDb {
TeamTeilnahmeTable.insertIgnore {
it[TeamTeilnahmeTable.teamId] = teamId
it[TeamTeilnahmeTable.eventId] = eventId
@@ -60,12 +62,14 @@ class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) {
}
@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) }
}
@JvmStatic
fun deleteFuture(teamId: Int) = useDb {
fun deleteFuture(teamId: Int) =
useDb {
exec(
"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)
@@ -73,17 +77,20 @@ class TeamTeilnahme(id: EntityID<CompositeID>) : CompositeEntity(id) {
}
@JvmStatic
fun getTeams(eventId: Int) = useDb {
fun getTeams(eventId: Int) =
useDb {
find { TeamTeilnahmeTable.eventId eq eventId }.map { Team.byId(it.teamId.value) }.toSet()
}
@JvmStatic
fun getEvents(teamId: Int) = useDb {
fun getEvents(teamId: Int) =
useDb {
find { TeamTeilnahmeTable.teamId eq teamId }.map { Event.byId(it.eventId.value) }.toSet()
}
@JvmStatic
fun getPlacement(team: Team, event: Event) = useDb {
fun getPlacement(team: Team, event: Event) =
useDb {
get(CompositeID {
it[TeamTeilnahmeTable.teamId] = team.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) {
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
fun createToken(name: String, owner: SteamwarUser): String {
@@ -65,15 +66,18 @@ class Token(id: EntityID<Int>): IntEntity(id) {
}
@JvmStatic
fun getTokenByCode(code: String) = get(getHash(code))
fun getTokenByCode(code: String) =
get(getHash(code))
@JvmStatic
fun get(hash: String) = useDb {
fun get(hash: String) =
useDb {
find { TokenTable.hash eq hash }.firstOrNull()
}
@JvmStatic
fun listUser(user: SteamwarUser) = useDb {
fun listUser(user: SteamwarUser) =
useDb {
find { TokenTable.owner eq user.id }.toList()
}
}
@@ -87,7 +91,8 @@ class Token(id: EntityID<Int>): IntEntity(id) {
var hash by TokenTable.hash
private set
override fun delete() = useDb {
override fun delete() =
useDb {
super.delete()
}
}
@@ -49,15 +49,18 @@ class UserConfig(id: EntityID<CompositeID>): CompositeEntity(id) {
companion object : CompositeEntityClass<UserConfig>(UserConfigTable) {
@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
}
@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
fun updatePlayerConfig(id: Int, config: String, value: String?) = useDb {
fun updatePlayerConfig(id: Int, config: String, value: String?) =
useDb {
if (value == null) {
removePlayerConfig(id, config)
} else {
@@ -70,14 +73,17 @@ class UserConfig(id: EntityID<CompositeID>): CompositeEntity(id) {
}
@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
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()
}
@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 {
@JvmField
val emptyPrefix = Prefix("§7", "")
@JvmField
val prefixes = mapOf(
PREFIX_NONE to emptyPrefix,
@@ -70,12 +71,14 @@ enum class UserPerm {
)
@JvmStatic
fun getPerms(id: Int) = useDb {
fun getPerms(id: Int) =
useDb {
UserPermTable.selectAll().where { UserPermTable.user eq id }.map { it[UserPermTable.perm] }.toSet()
}
@JvmStatic
fun addPerm(user: SteamwarUser, perm: UserPerm) = useDb {
fun addPerm(user: SteamwarUser, perm: UserPerm) =
useDb {
UserPermTable.insert {
it[UserPermTable.user] = user.getId()
it[UserPermTable.perm] = perm
@@ -83,7 +86,8 @@ enum class UserPerm {
}
@JvmStatic
fun removePerm(user: SteamwarUser, perm: UserPerm) = useDb {
fun removePerm(user: SteamwarUser, perm: UserPerm) =
useDb {
UserPermTable.deleteWhere {
(UserPermTable.user eq user.getId()) and (UserPermTable.perm eq perm)
}
@@ -68,7 +68,8 @@ object KotlinDatabase {
fun <T> useDb(statement: JdbcTransaction.() -> T): T {
KotlinDatabase.ensureConnected()
return TransactionManager.currentOrNull()?.statement() ?: transaction(KotlinDatabase.db) {
return TransactionManager.currentOrNull()?.statement()
?: transaction(KotlinDatabase.db) {
statement()
}
}
@@ -77,12 +78,14 @@ fun <T : IntEntity> IntEntityClass<T>.fromSql(
@Language("MySQL") stmt: String,
args: List<Pair<ColumnType<*>, Any?>>,
fieldIndex: Map<Expression<*>, Int>
): List<T> = useDb {
): List<T> =
useDb {
exec(stmt, explicitStatementType = StatementType.SELECT, args = args) {
val list = mutableListOf<T>()
while (it.next()) {
list.add(wrapRow(ResultRow.create(JdbcResult(it), fieldIndex)))
}
list
} ?: listOf()
}
?: listOf()
}
@@ -32,19 +32,23 @@ import java.sql.SQLException
data class Statement(val statement: String) {
companion object {
@JvmStatic
fun closeAll() = KotlinDatabase.close()
fun closeAll() =
KotlinDatabase.close()
@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) }) {
user.use(it)
}
}
private fun getArgType(obj: Any) = when(obj) {
private fun getArgType(obj: Any) =
when (obj) {
is String -> VarCharColumnType() to obj
is Int -> IntegerColumnType() to obj
is Long -> LongColumnType() to obj
@@ -40,7 +40,8 @@ import java.util.logging.Level;
public class Config {
private Config(){}
private Config() {
}
public static final World world = Bukkit.getWorlds().get(0);
@@ -265,14 +266,16 @@ public class Config {
String blueLeader = System.getProperty("blueLeader", null);
String redLeader = System.getProperty("redLeader", null);
if(blueLeader != null)
if (blueLeader != null) {
BlueLeader = UUID.fromString(blueLeader);
else
} else {
BlueLeader = null;
if(redLeader != null)
}
if (redLeader != null) {
RedLeader = UUID.fromString(redLeader);
else
} else {
RedLeader = null;
}
if (CheckSchemID != 0) {
mode = ArenaMode.CHECK;
@@ -292,9 +295,11 @@ public class Config {
public static boolean test() {
return ArenaMode.Test.contains(mode);
}
public static boolean replayserver() {
return ReplayID < 0;
}
public static boolean blueNegZ() {
return BlueToRedZ > 0;
}
@@ -65,6 +65,7 @@ public abstract class AI {
public static final double INTERACTION_RANGE = 5.0;
private static final Map<UUID, AI> ais = new HashMap<>();
public static void printPos() {
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);
team.addMember(entity, user);
if(FightState.Schem.contains(FightState.getFightState()))
if (FightState.Schem.contains(FightState.getFightState())) {
Bukkit.getScheduler().runTask(FightSystem.getPlugin(), () -> schematic(team.getClipboard()));
}
}
public abstract SchematicNode chooseSchematic();
public abstract void schematic(Clipboard clipboard);
public boolean acceptJoinRequest(JoinRequest.Enquirer enquirer, FightTeam team) {
@@ -112,20 +115,13 @@ public abstract class AI {
protected abstract void plan();
public void stop() {
if(!entity.isDead())
entity.remove();
if(!task.isCancelled())
task.cancel();
if (!entity.isDead()) entity.remove();
if (!task.isCancelled()) task.cancel();
}
public void setReady() {
if(FightState.getFightState() != FightState.POST_SCHEM_SETUP)
return;
if(team.getLeader().getEntity() != entity)
return;
if (FightState.getFightState() != FightState.POST_SCHEM_SETUP) return;
if (team.getLeader().getEntity() != entity) return;
team.setReady(true);
}
@@ -165,8 +161,7 @@ public abstract class AI {
queue.add(new Action(1) {
@Override
public void run() {
if(FightState.getFightState() != FightState.RUNNING)
return;
if (FightState.getFightState() != FightState.RUNNING) return;
Location location = translate(pos);
if (interactionDistanceViolation(location)) {
@@ -201,8 +196,7 @@ public abstract class AI {
@Override
public void run() {
Location location = translate(pos);
if (interactionDistanceViolation(location))
return;
if (interactionDistanceViolation(location)) return;
Block block = location.getBlock();
BlockData data = block.getBlockData();
if (data instanceof Repeater) {
@@ -236,8 +230,9 @@ public abstract class AI {
if (!team.getFightPlayer(entity).canEntern() && !team.getExtendRegion().inRegion(target))
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());
}
GlobalRecorder.getInstance().entityMoves(entity);
}
@@ -266,12 +261,10 @@ public abstract class AI {
boolean isPowered = powerable.isPowered();
if (type.name().endsWith("BUTTON")) {
if(isPowered)
return;
if (isPowered) return;
Bukkit.getScheduler().runTaskLater(FightSystem.getPlugin(), () -> {
if(!block.getType().name().endsWith("BUTTON"))
return;
if (!block.getType().name().endsWith("BUTTON")) return;
powerable.setPowered(false);
block.setBlockData(powerable);
@@ -321,14 +314,14 @@ public abstract class AI {
public Location translate(Vector pos) {
Region extend = team.getExtendRegion();
if(Fight.getUnrotated() == team)
if (Fight.getUnrotated() == team) {
return new Location(
Config.world,
pos.getX() + extend.getMinX(),
pos.getY() + team.getSchemRegion().getMinY(),
pos.getZ() + extend.getMinZ()
);
else
} else {
return new Location(
Config.world,
extend.getMaxX() - pos.getX(),
@@ -336,13 +329,16 @@ public abstract class AI {
extend.getMaxZ() - pos.getZ()
);
}
}
private static class Action {
private int delay;
public Action(int delay) {
this.delay = delay;
}
public void run() {}
public void run() {
}
}
}
@@ -52,7 +52,6 @@ public class DummyAI extends AI {
@Override
protected void plan() {
if(FightState.getFightState() == FightState.POST_SCHEM_SETUP)
setReady();
if (FightState.getFightState() == FightState.POST_SCHEM_SETUP) setReady();
}
}
@@ -46,8 +46,7 @@ public class AkCommand implements CommandExecutor {
return false;
}
Player player = (Player) sender;
if(!player.isOp())
return false;
if (!player.isOp()) return false;
if (!SteamwarUser.get(player.getUniqueId()).hasPerm(UserPerm.ADMINISTRATION) && Core.getInstance() != FightSystem.getPlugin()) {
return false;

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