Skip to content

Commit

Permalink
Config automatic updates COMPLETE! (3)
Browse files Browse the repository at this point in the history
  • Loading branch information
Spazzinq authored May 19, 2019
1 parent e5a48f7 commit 2d1cc94
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,14 @@ static void send(Player p, String msg) {
iChatBaseComponentClass.cast(chatSerializerClass.getDeclaredMethod("a", String.class).invoke(
chatSerializerClass, "{\"text\": \"" + msg + "\"}")), (byte) 2);
} else {
Object chatComponentText = Class.forName("net.minecraft.server." + nms + ".ChatComponentText")
.getConstructor(new Class<?>[]{String.class}).newInstance(msg);
Object chatComponentText = Class.forName("net.minecraft.server." + nms + ".ChatComponentText").getConstructor(new Class<?>[]{String.class}).newInstance(msg);
Class<?> iChatBaseComponentClass = Class.forName("net.minecraft.server." + nms + ".IChatBaseComponent");
try {
Class<?> chatMessageTypeClass = Class.forName("net.minecraft.server." + nms + ".ChatMessageType");
Object chatMessageType = null;
for (Object obj : chatMessageTypeClass.getEnumConstants()) if (obj.toString().equals("GAME_INFO")) chatMessageType = obj;
packet = packetPlayOutChatClass.getConstructor(new Class<?>[]{iChatBaseComponentClass, chatMessageTypeClass})
.newInstance(chatComponentText, chatMessageType);
} catch (ClassNotFoundException e) { packet = packetPlayOutChatClass.getConstructor(new Class<?>[]{iChatBaseComponentClass, byte.class})
.newInstance(chatComponentText, (byte) 2); }
packet = packetPlayOutChatClass.getConstructor(new Class<?>[]{iChatBaseComponentClass, chatMessageTypeClass}).newInstance(chatComponentText, chatMessageType);
} catch (ClassNotFoundException e) { packet = packetPlayOutChatClass.getConstructor(new Class<?>[]{iChatBaseComponentClass, byte.class}).newInstance(chatComponentText, (byte) 2); }
}
Object craftPlayerHandle = craftPlayerClass.getDeclaredMethod("getHandle").invoke(craftPlayerClass.cast(p));
Object playerConnection = craftPlayerHandle.getClass().getDeclaredField("playerConnection").get(craftPlayerHandle);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ else if (args[0].equalsIgnoreCase("support")) {
if (Config.support) {
msg(s, "&e&lFlightControl &eWarning &7» &fLive support enables Spazzinq to check debug information on why flight is disabled. " +
"You can disable support at any time by repeating the command, and the access only lasts until you restart FlightControl/the server.");
if (spazzinq != null) if (spazzinq.isOnline()) msg(spazzinq, "&c&lFlightControl &7» &c" + s.getName() + " has requested support.");
if (spazzinq != null && spazzinq.isOnline()) msg(spazzinq, "&c&lFlightControl &7» &c" + s.getName() + " has requested support.");
}
}
else if (args[0].equalsIgnoreCase("debug"))
Expand Down
27 changes: 10 additions & 17 deletions FlightControl/src/main/java/org/Spazzinq/FlightControl/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ final class Config {
private static File dTrailF;
private static FileConfiguration dTrailC;

// TODO get rid of this --------------------------------------vvv
// TODO get rid of this ----------------------------vvv
static boolean command, support, worldBL, regionBL, fac,
useCombat, ownTown, townyWar, cancelFall,
vanishBypass, trail, actionBar, everyEnable;
Expand Down Expand Up @@ -107,25 +107,18 @@ void reloadConfig() {
}

private void updateConfig() {
addDefault("settings");
addDefault("worlds");
addDefault("regions");
addDefault("factions");
addDefault("towny");
if (!c.isConfigurationSection("towny")) {
c.addDefault("towny.enable_own_town", false);
c.addDefault("towny.disable_during_war", false);
boolean cheanged = false;
if (!c.isConfigurationSection("towny")) {
c.addSection("trail", "towny:");
c.addSubsections("towny", Arrays.asList("disable_during_war: false", "enable_own_town: false"));
cheanged = true;
}
addDefault("trail");
addDefault("sounds");
if (!c.isBoolean("sounds.every_enable")) c.addDefault("sounds.every_enable", false);
addDefault("messages");

c.options().copyDefaults(true);
if (!c.isBoolean("sounds.every_enable")) {
c.addSubsection("sounds","every_enable: false"); cheanged = true;
}
if (cheanged) save();
}

private void addDefault(String cs) { if (c.isConfigurationSection(cs)) c.addDefault(cs, ""); }

static void defaultPerms(String suffix) {
if (pm.getPermission("flightcontrol.fly." + suffix) == null)
pm.addPermission(new Permission("flightcontrol.fly." + suffix, PermissionDefault.FALSE));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ public void onEnable() {
return true;
});

boolean is13 = getServer().getVersion().contains("1.13");
boolean is13 = getServer().getVersion().contains("1.13") || getServer().getVersion().contains("1.14");
// Remember, if you initialize on declaration it doesn't wait for the softdepends first...
plot = pm.isPluginEnabled("PlotSquared") ? (is13 ? new NewSquared() : new OldSquared()) : new Plot();
regions = pm.isPluginEnabled("WorldGuard") ? (is13 ? new Regions13() : new Regions8()) : new Regions();
fac = pm.isPluginEnabled("Factions") ? (pm.isPluginEnabled("MassiveCore") ? new Massive() : new UUIDSavage()) : new Factions();
particles = is13 ? new Particles13() : (getServer().getVersion().contains("Spigot") ? new Particles8() : null);
particles = is13 ? new Particles13() : new Particles8();

if (pm.isPluginEnabled("CombatLogX")) combat = new LogX();
else if (pm.isPluginEnabled("CombatTagPlus")) combat = new TagPlus(((CombatTagPlus) pm.getPlugin("CombatTagPlus")).getTagManager());
Expand Down Expand Up @@ -131,6 +131,7 @@ void check(Player p, Location l) {
else if (enable && !disable) canEnable(p);
} else if (!p.getAllowFlight()) canEnable(p);
}

private Eval eval(Player p, Location l) {
String world = l.getWorld().getName();
String region = regions.region(l);
Expand All @@ -141,7 +142,7 @@ private Eval eval(Player p, Location l) {
|| p.hasPermission("flightcontrol.fly." + world)
|| region != null && p.hasPermission("flightcontrol.fly." + world + "." + region)
|| worlds.enable() || regions.enable()
|| (Config.ownTown || p.hasPermission("flightcontrol.owntown")) && towny.ownTown(p) && (!Config.townyWar || !towny.wartime()),
|| (Config.ownTown || p.hasPermission("flightcontrol.owntown")) && towny.ownTown(p) && !(Config.townyWar && towny.wartime()),
disable = combat.tagged(p) || categories.disable()
|| plot.dFlight(world, l.getBlockX(), l.getBlockY(), l.getBlockZ())
|| p.hasPermission("flightcontrol.nofly." + world)
Expand Down Expand Up @@ -192,6 +193,7 @@ private void disableFlight(Player p) {
new BukkitRunnable() { public void run() { fall.remove(p); } }.runTaskLater(this, 300); }
p.setAllowFlight(false);
p.setFlying(false);
Listener.trailRemove(p);
Sound.play(p, Config.dSound);
msg(p, Config.dFlight, Config.actionBar);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

final class Listener implements org.bukkit.event.Listener {
private FlightControl pl;
private HashMap<Player, BukkitTask> partTasks = new HashMap<>();
private static HashMap<Player, BukkitTask> partTasks = new HashMap<>();

Listener(FlightControl i) { pl = i; Bukkit.getPluginManager().registerEvents(this, i); }

Expand All @@ -57,22 +57,25 @@ public void run() {
}
}.runTaskTimerAsynchronously(pl, 0, 3));
}
// TODO Remove trail on disableFlight
static void trailRemove(Player p) {
BukkitTask task = partTasks.remove(p);
if (task != null) task.cancel();
}

// Fly particles
@EventHandler private void onFly(PlayerToggleFlightEvent e) {
Player p = e.getPlayer();
if (e.isFlying()) {
if (Config.everyEnable) Sound.play(p, Config.eSound);
trailCheck(p);
}
else {
BukkitTask task = partTasks.remove(p);
if (task != null) task.cancel();
}
else trailRemove(p);
}

// Check fly status
@EventHandler(priority = EventPriority.HIGHEST) private void onMove(PlayerMoveEvent e) { pl.check(e.getPlayer(), e.getTo()); }
@EventHandler private void onLeave(PlayerQuitEvent e) { BukkitTask task = partTasks.remove(e.getPlayer()); if (task != null) task.cancel(); }
@EventHandler private void onLeave(PlayerQuitEvent e) { trailRemove(e.getPlayer()); }
@EventHandler private void onJoin(PlayerJoinEvent e) {
Player p = e.getPlayer(); pl.check(p);
if (p.isFlying()) new BukkitRunnable() { public void run() { trailCheck(p); } }.runTask(pl);
Expand All @@ -83,7 +86,7 @@ public void run() {
pl.check(p);
// TODO Only check fly commands/Move spectator back to trailCheck
if (p.isFlying() && !partTasks.containsKey(p)) new BukkitRunnable() { public void run() { trailCheck(p); } }.runTask(pl);
else if ((!p.isFlying() || p.getGameMode() == GameMode.SPECTATOR) && partTasks.containsKey(p)) { BukkitTask task = partTasks.remove(e.getPlayer()); if (task != null) task.cancel(); }
else if ((!p.isFlying() || p.getGameMode() == GameMode.SPECTATOR) && partTasks.containsKey(p)) trailRemove(p);
} }.runTask(pl);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,15 @@
import org.yaml.snakeyaml.representer.Representer;

import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Rewritten to ignore Bukkit "headers" in saveToString & loadFromString
public class CommentedConfig extends YamlConfiguration {
private HashMap<String, String> comments;
private HashMap<String, String> comments, addSection = new HashMap<>();
private HashMap<String, List<String>> addSubsection = new HashMap<>();
private final Yaml yaml;

public CommentedConfig() {
Expand All @@ -53,12 +56,15 @@ public CommentedConfig() {
public CommentedConfig(File f, InputStream is) throws IOException, InvalidConfigurationException { this(); load(f); loadComments(is); }

public HashMap<String, String> comments() { return comments; }
public void addSection(String relativeKey, String key) { addSection.put(relativeKey, key); }
public void addSubsections(String relativeKey, List<String> key) { addSubsection.put(relativeKey, key); }
public void addSubsection(String relativeKey, String key) { addSubsection.put(relativeKey, Collections.singletonList(key)); }

public void save(File f) throws IOException {
if (f != null) {
//noinspection UnstableApiUsage
Files.createParentDirs(f);
try (FileWriter writer = new FileWriter(f)) { writer.write(insertComments(saveToString())); }
try (FileWriter writer = new FileWriter(f)) { writer.write(insertComments(insertSubKeys(insertKeys(saveToString())))); }
}
}

Expand All @@ -76,6 +82,7 @@ private String strFromIS(InputStream is) throws IOException {
private String insertComments(String config) {
String[] lines = config.split("\n");
StringBuilder newConf = new StringBuilder(config);
// config index
String key = ""; int i = 0, depth = 0;

for (String line : lines) {
Expand All @@ -89,8 +96,10 @@ private String insertComments(String config) {
// same depth -> "lol.xd" | shallower by 1 -> "lol" | by 2 -> ""
// (add key on later)
int back = (depth - nDepth) / 2 + 1;
// Back the key down
for (int j = 0; j < back; j++) if (!key.isEmpty()) key = key.contains(".") ? key.substring(0, key.lastIndexOf(".")) : "";
}
// Add the key up
key = key.concat((key.isEmpty() ? "" : ".") + localKey);
depth = nDepth;
// Add comment(s)
Expand All @@ -100,13 +109,82 @@ private String insertComments(String config) {
c = c.substring(0, c.length() - depth);
newConf.insert(newConf.indexOf(line, i), c);
// Set location to continue from
i = newConf.indexOf("\n", i + c.length()) + 1;
i += c.length();
}
}
i += line.length();
}
return newConf.toString() + (comments.getOrDefault("footer", ""));
}

// BEFORE
// TODO Fix temporary solution for main keys (Stop copy pasting code)
private String insertKeys(String config) {
String[] lines = config.split("\n");
StringBuilder newConf = new StringBuilder(config);
String key = ""; int i = 0, depth = 0;

for (String line : lines) {
if (!line.contains("#") && (line.contains(": ") || line.endsWith(":"))) {
String localKey = line.replaceAll("\\s+", "").split(":")[0];
String spaces = leadSpaces(line); int nDepth = spaces.length();

if (depth >= nDepth) {
int back = (depth - nDepth) / 2 + 1;
for (int j = 0; j < back; j++) if (!key.isEmpty()) key = key.contains(".") ? key.substring(0, key.lastIndexOf(".")) : "";
}
key = key.concat((key.isEmpty() ? "" : ".") + localKey);
depth = nDepth;

if (addSection.containsKey(key)) {
String k = spaces + addSection.get(key).replaceAll("\n", "\n" + spaces);
k = k.substring(0, k.length() - depth) + "\n";
// Insert BEFORE
newConf.insert(newConf.indexOf(line, i), k);
i += k.length();
}

}
i += line.length();
}
return newConf.toString();
}

// AFTER
private String insertSubKeys(String config) {
String[] lines = config.split("\n");
StringBuilder newConf = new StringBuilder(config);
String key = ""; int i = 0, depth = 0;

for (String line : lines) {
if (!line.contains("#") && (line.contains(": ") || line.endsWith(":"))) {
String localKey = line.replaceAll("\\s+", "").split(":")[0];
String spaces = leadSpaces(line); int nDepth = spaces.length();

if (depth >= nDepth) {
int back = (depth - nDepth) / 2 + 1;
for (int j = 0; j < back; j++) if (!key.isEmpty()) key = key.contains(".") ? key.substring(0, key.lastIndexOf(".")) : "";
}
key = key.concat((key.isEmpty() ? "" : ".") + localKey);
depth = nDepth;

int length = 0;

if (addSubsection.containsKey(key))
for (String section : addSubsection.get(key)) {
String k = spaces + " " + section.replaceAll("\n", "\n" + spaces + " ");
k = "\n" + k.substring(0, k.length() - depth);
// Insert AFTER
newConf.insert(newConf.indexOf(line, i) + line.length(), k);
length += k.length();
}
i += length;
}
i += line.length();
}
return newConf.toString();
}

// TODO Does this work for comments on the same line as content? (lol: # example)
private void loadComments(String config) {
comments = new HashMap<>();
Expand Down Expand Up @@ -136,7 +214,7 @@ else if (line.contains(": ") || line.endsWith(":")) {
}
public HashMap<String, String> loadComments(InputStream is) throws IOException { loadComments(strFromIS(is)); return comments; }
@Override public void load(File f) throws IOException, InvalidConfigurationException { load(new FileInputStream(f)); }
@SuppressWarnings("deprecation") @Override public void load(InputStream is) throws InvalidConfigurationException, IOException { loadFromString(strFromIS(is)); }
@SuppressWarnings("deprecation") public void load(InputStream is) throws InvalidConfigurationException, IOException { loadFromString(strFromIS(is)); }

@Override public String saveToString() {
String dump = yaml.dump(getValues(false));
Expand Down
3 changes: 3 additions & 0 deletions FlightControl/src/main/resources/plugin.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ permissions:
flightcontrol.flyall:
description: Ability to fly in all regions
default: false
flightcontrol.owntown:
description: Ability to fly in own town
default: false
flightcontrol.admin:
description: Access to FlightControl commands
default: op
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
<packaging>pom</packaging>
<version>${revision}</version>

<properties><revision>2.7</revision></properties>
<properties><revision>3</revision></properties>

<modules>
<module>FlightControl</module>
Expand Down
9 changes: 8 additions & 1 deletion v13/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,18 @@
<artifactId>v13</artifactId>
<version>SNAPSHOT</version>

<repositories>
<repository>
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>

<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<version>1.14.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class Particles13 implements org.Spazzinq.FlightControl.Multiversion.Part

public void play(Location loc) {
// amnt x y z
//noinspection ConstantConditions
loc.getWorld().spawnParticle(particle, loc, 1, 0, 0, 0, extra, o);
}
public void setParticle(String s) {
Expand Down

0 comments on commit 2d1cc94

Please sign in to comment.