Added Save System.

Added Notes System.
This commit is contained in:
Brianna O'Keefe 2019-03-05 00:06:02 -05:00
parent 9a32add117
commit 01d4a1f6c8
25 changed files with 1065 additions and 34 deletions

View File

@ -1,17 +1,28 @@
package com.songoda.ultimatemoderation;
import com.songoda.epicspawners.utils.gui.AbstractGUI;
import com.songoda.ultimatemoderation.command.CommandManager;
import com.songoda.ultimatemoderation.listeners.*;
import com.songoda.ultimatemoderation.punish.AppliedPunishment;
import com.songoda.ultimatemoderation.punish.PunishmentNote;
import com.songoda.ultimatemoderation.punish.PunishmentType;
import com.songoda.ultimatemoderation.punish.player.PlayerPunishData;
import com.songoda.ultimatemoderation.punish.player.PunishmentManager;
import com.songoda.ultimatemoderation.punish.template.Template;
import com.songoda.ultimatemoderation.punish.template.TemplateManager;
import com.songoda.ultimatemoderation.storage.Storage;
import com.songoda.ultimatemoderation.storage.StorageRow;
import com.songoda.ultimatemoderation.storage.types.StorageMysql;
import com.songoda.ultimatemoderation.storage.types.StorageYaml;
import com.songoda.ultimatemoderation.utils.Methods;
import com.songoda.ultimatemoderation.utils.SettingsManager;
import com.songoda.ultimatemoderation.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.UUID;
public class UltimateModeration extends JavaPlugin {
private static CommandSender console = Bukkit.getConsoleSender();
private static UltimateModeration INSTANCE;
@ -23,6 +34,7 @@ public class UltimateModeration extends JavaPlugin {
private PunishmentManager punishmentManager;
private Locale locale;
private Storage storage;
public static UltimateModeration getInstance() {
return INSTANCE;
@ -67,14 +79,18 @@ public class UltimateModeration extends JavaPlugin {
this.references = new References();
//Setup Managers
// Setup Managers
this.templateManager = new TemplateManager();
this.commandManager = new CommandManager(this);
this.punishmentManager = new PunishmentManager();
AbstractGUI.initializeListeners(this);
// Load data
this.checkStorage();
this.loadFromFile();
// Register Listeners
AbstractGUI.initializeListeners(this);
Bukkit.getPluginManager().registerEvents(new CommandListener(this), this);
Bukkit.getPluginManager().registerEvents(new DeathListener(this), this);
Bukkit.getPluginManager().registerEvents(new MoveListener(this), this);
@ -83,16 +99,72 @@ public class UltimateModeration extends JavaPlugin {
Bukkit.getPluginManager().registerEvents(new ChatListener(this), this);
Bukkit.getPluginManager().registerEvents(new LoginListener(this), this);
int timeout = SettingsManager.Setting.AUTOSAVE.getInt() * 60 * 20;
Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> storage.doSave(), timeout, timeout);
}
@Override
public void onDisable() {
storage.doSave();
this.storage.closeConnection();
console.sendMessage(Methods.formatText("&a============================="));
console.sendMessage(Methods.formatText("&7UltimateModeration " + this.getDescription().getVersion() + " by &5Songoda <3!"));
console.sendMessage(Methods.formatText("&7Action: &cDisabling&7..."));
console.sendMessage(Methods.formatText("&a============================="));
}
private void checkStorage() {
if (getConfig().getBoolean("Database.Activate Mysql Support")) {
this.storage = new StorageMysql(this);
} else {
this.storage = new StorageYaml(this);
}
}
private void loadFromFile() {
if (storage.containsGroup("templates")) {
for (StorageRow row : storage.getRowsByGroup("templates")) {
Template template = new Template(PunishmentType.valueOf(row.get("type").asString()),
row.get("duration").asLong(),
row.get("reason").asString(),
UUID.fromString(row.get("creator").asString()),
row.get("name").asString(),
UUID.fromString(row.get("uuid").asString()));
templateManager.addTemplate(template);
}
}
if (storage.containsGroup("punishments")) {
for (StorageRow row : storage.getRowsByGroup("punishments")) {
UUID playerUUID = UUID.fromString(row.get("victim").asString());
AppliedPunishment appliedPunishment = new AppliedPunishment(PunishmentType.valueOf(row.get("type").asString()),
row.get("duration").asLong(),
row.get("reason").asString(),
UUID.fromString(row.get("victim").asString()),
UUID.fromString(row.get("punisher").asString()),
row.get("expiration").asLong(),
playerUUID);
PlayerPunishData playerPunishData = getPunishmentManager().getPlayer(playerUUID);
playerPunishData.addPunishment(appliedPunishment);
playerPunishData.audit();
}
}
if (storage.containsGroup("notes")) {
for (StorageRow row : storage.getRowsByGroup("notes")) {
UUID playerUUID = UUID.fromString(row.get("subject").asString());
PunishmentNote note = new PunishmentNote(UUID.fromString(row.get("uuid").asString()),
row.get("note").asString(),
UUID.fromString(row.get("author").asString()),
UUID.fromString(row.get("subject").asString()),
row.get("creation").asLong());
PlayerPunishData playerPunishData = getPunishmentManager().getPlayer(playerUUID);
playerPunishData.addNotes(note);
}
}
storage.doSave();
}
private void setupConfig() {
settingsManager.updateSettings();
this.getConfig().options().copyDefaults(true);

View File

@ -3,6 +3,7 @@ package com.songoda.ultimatemoderation.command.commands;
import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.command.AbstractCommand;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -18,20 +19,20 @@ public class CommandFreeze extends AbstractCommand {
super(true, true, "Freeze");
}
public static void freeze(Player player, Player sender) {
public static void freeze(OfflinePlayer player, Player sender) {
UltimateModeration instance = UltimateModeration.getInstance();
if (frozen.contains(player.getUniqueId())) {
frozen.remove(player.getUniqueId());
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.remove", player.getDisplayName()));
player.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.alertremove"));
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.remove", player.getPlayer().getDisplayName()));
player.getPlayer().sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.alertremove"));
} else {
frozen.add(player.getUniqueId());
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.add", player.getDisplayName()));
player.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.alertadd"));
sender.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.add", player.getPlayer().getDisplayName()));
player.getPlayer().sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.freeze.alertadd"));
}
}
public static boolean isFrozen(Player player) {
public static boolean isFrozen(OfflinePlayer player) {
return frozen.contains(player.getUniqueId());
}

View File

@ -4,6 +4,7 @@ import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.command.AbstractCommand;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -20,7 +21,7 @@ public class CommandSpy extends AbstractCommand {
super(true, true, "Spy");
}
public static void spy(Player player, Player senderP) {
public static void spy(OfflinePlayer player, Player senderP) {
UltimateModeration instance = UltimateModeration.getInstance();
boolean didVanish = false;
if (!CommandVanish.isVanished(senderP)) {
@ -29,7 +30,7 @@ public class CommandSpy extends AbstractCommand {
}
spying.put(senderP.getUniqueId(), new Spy(senderP.getLocation(), didVanish));
player.addPassenger(senderP);
player.getPlayer().addPassenger(senderP);
senderP.sendMessage(instance.getReferences().getPrefix() + instance.getLocale().getMessage("command.spy.success", player.getName()));
}

View File

@ -5,6 +5,7 @@ import com.songoda.ultimatemoderation.command.commands.CommandFreeze;
import com.songoda.ultimatemoderation.command.commands.CommandSpy;
import com.songoda.ultimatemoderation.utils.gui.AbstractGUI;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
@ -13,9 +14,9 @@ public class GUIModerate extends AbstractGUI {
private final UltimateModeration plugin;
private final Player toModerate;
private final OfflinePlayer toModerate;
public GUIModerate(UltimateModeration plugin, Player toModerate, Player player) {
public GUIModerate(UltimateModeration plugin, OfflinePlayer toModerate, Player player) {
super(player);
this.plugin = plugin;
this.toModerate = toModerate;

View File

@ -0,0 +1,112 @@
package com.songoda.ultimatemoderation.gui;
import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.punish.PunishmentNote;
import com.songoda.ultimatemoderation.utils.AbstractChatConfirm;
import com.songoda.ultimatemoderation.utils.gui.AbstractAnvilGUI;
import com.songoda.ultimatemoderation.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class GUINotesManager extends AbstractGUI {
private final UltimateModeration plugin;
private final OfflinePlayer toModerate;
public GUINotesManager(UltimateModeration plugin, OfflinePlayer toModerate, Player player) {
super(player);
this.plugin = plugin;
this.toModerate = toModerate;
init(plugin.getLocale().getMessage("gui.notes.title", player.getName()), 54);
}
@Override
protected void constructGUI() {
inventory.clear();
createButton(1, Material.ARROW, plugin.getLocale().getMessage("gui.general.previous"));
createButton(3, Material.ARROW, plugin.getLocale().getMessage("gui.general.next"));
createButton(8, Material.OAK_DOOR, plugin.getLocale().getMessage("gui.general.back"));
createButton(6, Material.REDSTONE, plugin.getLocale().getMessage("gui.moderate.create"));
for (int i = 0; i < 9; i++)
createButton(9 + i, Material.GRAY_STAINED_GLASS_PANE, "&1");
List<PunishmentNote> notes = plugin.getPunishmentManager().getPlayer(toModerate).getNotes();
for (int i = 0; i < notes.size(); i++) {
PunishmentNote note = notes.get(i);
String noteStr = note.getNote();
ArrayList<String> lore = new ArrayList<>();
int lastIndex = 0;
for (int n = 0; n < noteStr.length(); n++) {
if (n - lastIndex < 20)
continue;
if (noteStr.charAt(n) == ' ') {
lore.add("&6" +noteStr.substring(lastIndex, n).trim());
lastIndex = n;
}
}
if (lastIndex - noteStr.length() < 20)
lore.add("&6" + noteStr.substring(lastIndex, noteStr.length()).trim());
String name = lore.get(0);
lore.remove(0);
lore.add("");
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
lore.add(plugin.getLocale().getMessage("gui.moderate.createdby", Bukkit.getOfflinePlayer(note.getAuthor()).getName()));
lore.add(plugin.getLocale().getMessage("gui.moderate.createdon", format.format(new Date(note.getCreationDate()))));
lore.add(plugin.getLocale().getMessage("gui.moderate.remove"));
createButton(18 + i, Material.MAP, name, lore);
registerClickable(18 + i, ((player1, inventory1, cursor, slot, type) -> {
plugin.getPunishmentManager().getPlayer(toModerate).removeNote(note);
constructGUI();
resetClickables();
registerClickables();
}));
}
}
@Override
protected void registerClickables() {
registerClickable(8, ((player1, inventory1, cursor, slot, type) ->
new GUIPlayers(plugin, player)));
registerClickable(6, ((player1, inventory1, cursor, slot, type) -> {
player.sendMessage(plugin.getLocale().getMessage("gui.moderate.type"));
new AbstractChatConfirm(player, event -> {
plugin.getPunishmentManager().getPlayer(toModerate).addNotes(new PunishmentNote(event.getMessage(),
player.getUniqueId(), toModerate.getUniqueId(), System.currentTimeMillis()));
constructGUI();
});
}));
}
@Override
protected void registerOnCloses() {
}
}

View File

@ -3,6 +3,7 @@ package com.songoda.ultimatemoderation.gui;
import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.utils.gui.AbstractGUI;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
@ -11,9 +12,9 @@ public class GUIPlayer extends AbstractGUI {
private final UltimateModeration plugin;
private final Player toModerate;
private final OfflinePlayer toModerate;
public GUIPlayer(UltimateModeration plugin, Player toModerate, Player player) {
public GUIPlayer(UltimateModeration plugin, OfflinePlayer toModerate, Player player) {
super(player);
this.plugin = plugin;
this.toModerate = toModerate;
@ -35,7 +36,7 @@ public class GUIPlayer extends AbstractGUI {
createButton(28, Material.ANVIL, plugin.getLocale().getMessage("gui.player.punish"));
createButton(30, Material.DIAMOND_CHESTPLATE, plugin.getLocale().getMessage("gui.player.moderate"));
createButton(32, Material.DIAMOND_SWORD, plugin.getLocale().getMessage("gui.player.punishments"));
createButton(34, Material.STONE, "BUTT");
createButton(34, Material.MAP, plugin.getLocale().getMessage("gui.player.notes"));
}
@Override
@ -55,6 +56,10 @@ public class GUIPlayer extends AbstractGUI {
registerClickable(32, ((player1, inventory1, cursor, slot, type) -> {
new GUIPunishments(plugin, toModerate, player1);
}));
registerClickable(34, ((player1, inventory1, cursor, slot, type) -> {
new GUINotesManager(plugin, toModerate, player1);
}));
}
@Override

View File

@ -9,6 +9,7 @@ import com.songoda.ultimatemoderation.utils.gui.AbstractAnvilGUI;
import com.songoda.ultimatemoderation.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.ItemStack;
@ -20,7 +21,7 @@ import java.util.ArrayList;
public class GUIPunish extends AbstractGUI {
private final UltimateModeration plugin;
private final Player toModerate;
private final OfflinePlayer toModerate;
private Template template;
private boolean justSaved = false;
@ -33,7 +34,7 @@ public class GUIPunish extends AbstractGUI {
private int task;
public GUIPunish(UltimateModeration plugin, Player toModerate, Template template, Player player) {
public GUIPunish(UltimateModeration plugin, OfflinePlayer toModerate, Template template, Player player) {
super(player);
this.plugin = plugin;
this.toModerate = toModerate;
@ -258,7 +259,7 @@ public class GUIPunish extends AbstractGUI {
private void updateTemplate() {
Template template = new Template(this.type, this.duration, this.reason, this.template.getCreator(), this.templateName);
plugin.getTemplateManager().updateTemplate(template);
plugin.getTemplateManager().updateTemplate(this.template.getUUID(), template);
justSaved = true;
if (toModerate == null)
new GUITemplateManager(plugin, player);

View File

@ -8,6 +8,7 @@ import com.songoda.ultimatemoderation.utils.Methods;
import com.songoda.ultimatemoderation.utils.gui.AbstractGUI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.util.ArrayList;
@ -18,12 +19,12 @@ import java.util.UUID;
public class GUIPunishments extends AbstractGUI {
private final UltimateModeration plugin;
private final Player toModerate;
private final OfflinePlayer toModerate;
private Activity currentActivity = Activity.BOTH;
private PunishmentType punishmentType = PunishmentType.ALL;
public GUIPunishments(UltimateModeration plugin, Player toModerate, Player player) {
public GUIPunishments(UltimateModeration plugin, OfflinePlayer toModerate, Player player) {
super(player);
this.plugin = plugin;
this.toModerate = toModerate;

View File

@ -42,7 +42,8 @@ public class GUITemplateManager extends AbstractGUI {
createButton(9 + i, Material.GRAY_STAINED_GLASS_PANE, "&1");
ArrayList<Template> templates = new ArrayList<>(plugin.getTemplateManager().getTemplates().values());
templates.removeIf(template -> template.getPunishmentType() != punishmentType);
if (punishmentType != PunishmentType.ALL)
templates.removeIf(template -> template.getPunishmentType() != punishmentType);
for (int i = 0; i < templates.size(); i++) {
Template template = templates.get(i);
createButton(18 + i, Material.MAP, "&6&l" + template.getTemplateName(),
@ -53,7 +54,7 @@ public class GUITemplateManager extends AbstractGUI {
if (type == ClickType.LEFT) {
new GUIPunish(plugin, null, template, player);
} else if (type == ClickType.RIGHT) {
plugin.getTemplateManager().removeTemplate(template.getTemplateName());
plugin.getTemplateManager().removeTemplate(template.getUUID());
constructGUI();
}
}));

View File

@ -8,6 +8,13 @@ public class AppliedPunishment extends Punishment {
private final UUID punisher;
private long expiration;
public AppliedPunishment(PunishmentType punishmentType, long duration, String reason, UUID victim, UUID punisher, long expiration, UUID uuid) {
super(punishmentType, duration, reason, uuid);
this.victim = victim;
this.punisher = punisher;
this.expiration = expiration;
}
public AppliedPunishment(PunishmentType punishmentType, long duration, String reason, UUID victim, UUID punisher, long expiration) {
super(punishmentType, duration, reason);
this.victim = victim;

View File

@ -7,28 +7,42 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
public class Punishment {
private final UUID uuid;
private final PunishmentType punishmentType;
private final long duration;
private final String reason;
public Punishment(PunishmentType punishmentType, long duration, String reason, UUID uuid) {
this.punishmentType = punishmentType;
this.duration = duration;
this.reason = reason;
this.uuid = uuid;
}
public Punishment(PunishmentType punishmentType, long duration, String reason) {
this.punishmentType = punishmentType;
this.duration = duration;
this.reason = reason;
this.uuid = UUID.randomUUID();
}
public Punishment(PunishmentType punishmentType, String reason) {
this.punishmentType = punishmentType;
this.duration = -1;
this.reason = reason;
this.uuid = UUID.randomUUID();
}
protected Punishment(Punishment punishment) {
this.punishmentType = punishment.getPunishmentType();
this.duration = punishment.getDuration();
this.reason = punishment.getReason();
this.uuid = punishment.getUUID();
}
public void execute(CommandSender punisher, OfflinePlayer victim) {
@ -94,6 +108,10 @@ public class Punishment {
victim.sendMessage(punishSuccess + Methods.formatText("&7."));
}
public UUID getUUID() {
return uuid;
}
public PunishmentType getPunishmentType() {
return this.punishmentType;
}

View File

@ -0,0 +1,49 @@
package com.songoda.ultimatemoderation.punish;
import java.util.UUID;
public class PunishmentNote {
private final UUID uuid;
private final String note;
private final UUID author;
private final UUID subject;
private final long creationDate;
public PunishmentNote(UUID uuid, String note, UUID author, UUID subject, long creationDate) {
this.uuid = uuid;
this.note = note;
this.author = author;
this.subject = subject;
this.creationDate = creationDate;
}
public PunishmentNote(String note, UUID author, UUID subject, long creationDate) {
this.uuid = UUID.randomUUID();
this.note = note;
this.author = author;
this.subject = subject;
this.creationDate = creationDate;
}
public UUID getUUID() {
return uuid;
}
public String getNote() {
return note;
}
public UUID getAuthor() {
return author;
}
public UUID getSubject() {
return subject;
}
public long getCreationDate() {
return creationDate;
}
}

View File

@ -1,5 +1,6 @@
package com.songoda.ultimatemoderation.punish.player;
import com.songoda.ultimatemoderation.punish.PunishmentNote;
import com.songoda.ultimatemoderation.punish.AppliedPunishment;
import com.songoda.ultimatemoderation.punish.PunishmentType;
@ -16,6 +17,8 @@ public class PlayerPunishData {
private final List<AppliedPunishment> activePunishments = new ArrayList<>();
private final List<AppliedPunishment> expiredPunishments = new ArrayList<>();
private final List<PunishmentNote> punishmentNotes = new ArrayList<>();
public PlayerPunishData(UUID player) {
this.player = player;
}
@ -64,7 +67,21 @@ public class PlayerPunishData {
return appliedPunishments;
}
private void audit() {
public List<PunishmentNote> getNotes() {
return new ArrayList<>(punishmentNotes);
}
public PunishmentNote[] addNotes(PunishmentNote... notes) {
this.punishmentNotes.addAll(Arrays.asList(notes));
return notes;
}
public PunishmentNote[] removeNote(PunishmentNote... notes) {
this.punishmentNotes.removeAll(Arrays.asList(notes));
return notes;
}
public void audit() {
audit(false, PunishmentType.ALL);
}

View File

@ -17,6 +17,12 @@ public class Template extends Punishment {
this.templateName = templateName;
}
public Template(PunishmentType punishmentType, long duration, String reason, UUID creator, String templateName, UUID uuid) {
super(punishmentType, duration, reason, uuid);
this.creator = creator;
this.templateName = templateName;
}
public Template(PunishmentType punishmentType, long duration, String reason, UUID creator, String templateName) {
super(punishmentType, duration, reason);
this.creator = creator;

View File

@ -3,33 +3,39 @@ package com.songoda.ultimatemoderation.punish.template;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class TemplateManager {
private static final Map<String, Template> templates = new HashMap<>();
private static final Map<UUID, Template> templates = new HashMap<>();
public Template getTemplate(String name) {
return templates.get(formatName(name));
for (Template template : templates.values()) {
if (formatName(template.getTemplateName()).equals(formatName(name)))
return template;
}
return null;
}
public Template addTemplate(Template template) {
return templates.put(formatName(template.getTemplateName()), template);
return templates.put(template.getUUID(), template);
}
public Template removeTemplate(String name) {
return templates.remove(formatName(name));
public Template removeTemplate(UUID uuid) {
return templates.remove(uuid);
}
public Template updateTemplate(Template template) {
templates.remove(formatName(template.getTemplateName()));
public Template updateTemplate(UUID uuid, Template template) {
templates.remove(uuid);
return addTemplate(template);
}
public Map<String, Template> getTemplates() {
public Map<UUID, Template> getTemplates() {
return Collections.unmodifiableMap(templates);
}
private String formatName(String name) {
if (name == null) return null;
name = name.toUpperCase().trim();
name = name.replace(" ", "_");
return name;

View File

@ -0,0 +1,74 @@
package com.songoda.ultimatemoderation.storage;
import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.punish.AppliedPunishment;
import com.songoda.ultimatemoderation.punish.PunishmentNote;
import com.songoda.ultimatemoderation.punish.player.PlayerPunishData;
import com.songoda.ultimatemoderation.punish.template.Template;
import com.songoda.ultimatemoderation.utils.ConfigWrapper;
import java.util.List;
public abstract class Storage {
protected final UltimateModeration instance;
protected final ConfigWrapper dataFile;
public Storage(UltimateModeration instance) {
this.instance = instance;
this.dataFile = new ConfigWrapper(instance, "", "data.yml");
this.dataFile.createNewFile(null, "UltimateModeration Data File");
this.dataFile.getConfig().options().copyDefaults(true);
this.dataFile.saveConfig();
}
public abstract boolean containsGroup(String group);
public abstract List<StorageRow> getRowsByGroup(String group);
public abstract void prepareSaveItem(String group, StorageItem... items);
public void updateData(UltimateModeration instance) {
// Save game data
for (Template template : instance.getTemplateManager().getTemplates().values()) {
prepareSaveItem("templates", new StorageItem("uuid", template.getUUID().toString()),
new StorageItem("type", template.getPunishmentType().name()),
new StorageItem("duration", template.getDuration()),
new StorageItem("reason", template.getReason()),
new StorageItem("name", template.getTemplateName()),
new StorageItem("creator", template.getCreator().toString()));
}
for (PlayerPunishData playerPunishData : instance.getPunishmentManager().getPunishments().values()) {
List<AppliedPunishment> appliedPunishments = playerPunishData.getActivePunishments();
appliedPunishments.addAll(playerPunishData.getExpiredPunishments());
for (AppliedPunishment appliedPunishment : appliedPunishments) {
prepareSaveItem("punishments", new StorageItem("uuid", appliedPunishment.getUUID().toString()),
new StorageItem("type", appliedPunishment.getPunishmentType().name()),
new StorageItem("duration", appliedPunishment.getDuration()),
new StorageItem("reason", appliedPunishment.getReason()),
new StorageItem("victim", appliedPunishment.getVictim().toString()),
new StorageItem("punisher", appliedPunishment.getPunisher().toString()),
new StorageItem("expiration", appliedPunishment.getExpiration()));
}
List<PunishmentNote> notes = playerPunishData.getNotes();
for (PunishmentNote note : notes) {
prepareSaveItem("notes", new StorageItem("uuid", note.getUUID().toString()),
new StorageItem("note", note.getNote()),
new StorageItem("author", note.getAuthor().toString()),
new StorageItem("subject", note.getSubject().toString()),
new StorageItem("creation", note.getCreationDate()));
}
}
}
public abstract void doSave();
public abstract void save();
public abstract void makeBackup();
public abstract void closeConnection();
}

View File

@ -0,0 +1,64 @@
package com.songoda.ultimatemoderation.storage;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class StorageItem {
private final Object object;
private String key = null;
public StorageItem(Object object) {
this.object = object;
}
public StorageItem(String key, Object object) {
this.key = key;
this.object = object;
}
public StorageItem(String key, List<Material> material) {
String object = "";
for (Material m : material) {
object += m.name() + ";";
}
this.key = key;
this.object = object;
}
public String getKey() {
return key;
}
public String asString() {
if (object == null) return null;
return (String) object;
}
public long asLong() {
if (object == null) return -1;
if (object instanceof Integer) {
return (long)((int)object);
}
return (long) object;
}
public boolean asBoolean() {
if (object == null) return false;
return (boolean) object;
}
public int asInt() {
if (object == null) return 0;
return (int) object;
}
public Object asObject() {
return object;
}
}

View File

@ -0,0 +1,29 @@
package com.songoda.ultimatemoderation.storage;
import java.util.Collections;
import java.util.Map;
public class StorageRow {
private final String key;
private final Map<String, StorageItem> items;
public StorageRow(String key, Map<String, StorageItem> items) {
this.key = key;
this.items = items;
}
public String getKey() {
return key;
}
public Map<String, StorageItem> getItems() {
return Collections.unmodifiableMap(items);
}
public StorageItem get(String key) {
if (!items.containsKey(key) || items.get(key).asObject().toString().equals("")) return new StorageItem(null);
return items.get(key);
}
}

View File

@ -0,0 +1,195 @@
package com.songoda.ultimatemoderation.storage.types;
import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.storage.Storage;
import com.songoda.ultimatemoderation.storage.StorageItem;
import com.songoda.ultimatemoderation.storage.StorageRow;
import com.songoda.ultimatemoderation.utils.MySQLDatabase;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StorageMysql extends Storage {
private static Map<String, StorageItem[]> toSave = new HashMap<>();
private static Map<String, StorageItem[]> lastSave = new HashMap<>();
private MySQLDatabase database;
public StorageMysql(UltimateModeration instance) {
super(instance);
this.database = new MySQLDatabase(instance);
}
@Override
public boolean containsGroup(String group) {
try {
DatabaseMetaData dbm = database.getConnection().getMetaData();
ResultSet rs = dbm.getTables(null, null, instance.getConfig().getString("Database.Prefix") + group, null);
if (rs.next()) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public List<StorageRow> getRowsByGroup(String group) {
List<StorageRow> rows = new ArrayList<>();
try {
ResultSet set = database.getConnection().createStatement().executeQuery(String.format("SELECT * FROM `" + instance.getConfig().getString("Database.Prefix") + "%s`", group));
while (set.next()) {
Map<String, StorageItem> items = new HashMap<>();
String key = set.getString(1);
for (int i = 2; i <= set.getMetaData().getColumnCount(); i++) {
if (set.getObject(i) == null || set.getObject(i) == "") continue;
StorageItem item = new StorageItem(set.getObject(i));
items.put(set.getMetaData().getColumnName(i), item);
}
StorageRow row = new StorageRow(key, items);
rows.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
@Override
public void prepareSaveItem(String group, StorageItem... items) {
toSave.put(group + "]" + items[0].asObject().toString(), items);
}
@Override
public void doSave() {
this.updateData(instance);
if (toSave.isEmpty()) return;
Map<String, StorageItem[]> nextSave = new HashMap<>(toSave);
if (lastSave.isEmpty())
lastSave.putAll(toSave);
this.makeBackup();
this.save();
toSave.clear();
lastSave.clear();
lastSave.putAll(nextSave);
}
@Override
public void save() {
try {
Statement stmt = database.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
last:
for (Map.Entry<String, StorageItem[]> last : lastSave.entrySet()) {
String lastKey = last.getKey().split("]")[0];
String lastValue = last.getValue()[0].asObject().toString();
for (Map.Entry<String, StorageItem[]> to : toSave.entrySet()) {
String toKey = to.getKey().split("]")[0];
if (!toKey.equals(lastKey)
|| !to.getValue()[0].asObject().equals(lastValue)
|| to.getValue().length != last.getValue().length)
continue;
toSave.remove(toKey);
for (int i = 0; i < to.getValue().length - 1; i ++) {
if (to.getValue()[i].asObject() != null
&& !to.getValue()[i].asObject().toString()
.equals(last.getValue()[i].asObject().toString())) {
//Update
StorageItem[] items = to.getValue();
StringBuilder sql = new StringBuilder(String.format("UPDATE `" + instance.getConfig().getString("Database.Prefix") + "%s`", toKey));
sql.append(" SET");
for (StorageItem item : items) {
if (item == null || item.asObject() == null) continue;
String key = item.getKey().split("]")[0];
sql.append(String.format("`%s` = '%s', ", key, item.asObject().toString()));
}
sql = new StringBuilder(sql.substring(0, sql.length() - 2));
sql.append(String.format(" WHERE `%s`='%s'", last.getValue()[0].getKey(), last.getValue()[0].asObject().toString()));
stmt.addBatch(sql.toString());
continue last;
}
}
// Already up to date.
continue last;
}
//Was not found delete.
StringBuilder sql = new StringBuilder(String.format("DELETE FROM `" + instance.getConfig().getString("Database.Prefix") + "%s`", lastKey));
sql.append(String.format(" WHERE `%s`='%s'", last.getValue()[0].getKey(), last.getValue()[0].asObject().toString()));
stmt.addBatch(sql.toString());
}
for (Map.Entry<String, StorageItem[]> to : toSave.entrySet()) {
String toKey = to.getKey().split("]")[0];
//Add
StorageItem[] items = to.getValue();
StringBuilder sql = new StringBuilder(String.format("INSERT INTO `" + instance.getConfig().getString("Database.Prefix") + "%s`", toKey));
sql.append(" (");
for (StorageItem item : items) {
if (item == null || item.asObject() == null) continue;
String key = item.getKey().split("]")[0];
sql.append(String.format("`%s`, ", key));
}
sql = new StringBuilder(sql.substring(0, sql.length() - 2));
sql.append(") VALUES (");
for (StorageItem item : items) {
if (item == null || item.asObject() == null) continue;
sql.append(String.format("'%s', ", item.asObject().toString()));
}
sql = new StringBuilder(sql.substring(0, sql.length() - 2));
sql.append(");");
stmt.addBatch(sql.toString());
}
stmt.executeBatch();
toSave.clear();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void makeBackup() {
}
@Override
public void closeConnection() {
try {
database.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,131 @@
package com.songoda.ultimatemoderation.storage.types;
import com.songoda.ultimatemoderation.UltimateModeration;
import com.songoda.ultimatemoderation.storage.Storage;
import com.songoda.ultimatemoderation.storage.StorageItem;
import com.songoda.ultimatemoderation.storage.StorageRow;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemorySection;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class StorageYaml extends Storage {
private static final Map<String, Object> toSave = new HashMap<>();
private static final Map<String, Object> lastSave = new HashMap<>();
public StorageYaml(UltimateModeration instance) {
super(instance);
}
@Override
public boolean containsGroup(String group) {
return dataFile.getConfig().contains("data." + group);
}
@Override
public List<StorageRow> getRowsByGroup(String group) {
List<StorageRow> rows = new ArrayList<>();
ConfigurationSection currentSection = dataFile.getConfig().getConfigurationSection("data." + group);
for (String key : currentSection.getKeys(false)) {
Map<String, StorageItem> items = new HashMap<>();
ConfigurationSection currentSection2 = dataFile.getConfig().getConfigurationSection("data." + group + "." + key);
for (String key2 : currentSection2.getKeys(false)) {
String path = "data." + group + "." + key + "." + key2;
items.put(key2, new StorageItem(dataFile.getConfig().get(path) instanceof MemorySection
? convertToInLineList(path) : dataFile.getConfig().get(path)));
}
if (items.isEmpty()) continue;
StorageRow row = new StorageRow(key, items);
rows.add(row);
}
return rows;
}
private String convertToInLineList(String path) {
StringBuilder converted = new StringBuilder();
for (String key : dataFile.getConfig().getConfigurationSection(path).getKeys(false)) {
converted.append(key).append(":").append(dataFile.getConfig().getInt(path + "." + key)).append(";");
}
return converted.toString();
}
@Override
public void prepareSaveItem(String group, StorageItem... items) {
for (StorageItem item : items) {
if (item == null || item.asObject() == null) continue;
toSave.put("data." + group + "." + items[0].asString() + "." + item.getKey(), item.asObject());
}
}
@Override
public void doSave() {
this.updateData(instance);
if (toSave.isEmpty()) return;
Map<String, Object> nextSave = new HashMap<>(toSave);
if (lastSave.isEmpty())
lastSave.putAll(toSave);
this.makeBackup();
this.save();
toSave.clear();
lastSave.clear();
lastSave.putAll(nextSave);
}
@Override
public void save() {
try {
for (Map.Entry<String, Object> entry : lastSave.entrySet()) {
if (toSave.containsKey(entry.getKey())) {
Object newValue = toSave.get(entry.getKey());
if (!entry.getValue().equals(newValue)) {
dataFile.getConfig().set(entry.getKey(), entry.getValue());
}
toSave.remove(newValue);
} else {
dataFile.getConfig().set(entry.getKey(), null);
}
}
for (Map.Entry<String, Object> entry : toSave.entrySet()) {
dataFile.getConfig().set(entry.getKey(), entry.getValue());
}
dataFile.saveConfig();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
@Override
public void makeBackup() {
File data = new File(instance.getDataFolder(), "data.yml");
File dataClone = new File(instance.getDataFolder(), "data-backup-" + System.currentTimeMillis() + ".yml");
try {
FileUtils.copyFile(data, dataClone);
} catch (IOException e) {
e.printStackTrace();
}
Deque<File> backups = new ArrayDeque<>();
for (File file : Objects.requireNonNull(instance.getDataFolder().listFiles())) {
if (file.getName().toLowerCase().contains("data-backup")) {
backups.add(file);
}
}
if (backups.size() > 3) {
backups.getFirst().delete();
}
}
@Override
public void closeConnection() {
dataFile.saveConfig();
}
}

View File

@ -0,0 +1,95 @@
package com.songoda.ultimatemoderation.utils;
import com.songoda.ultimatemoderation.UltimateModeration;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class AbstractChatConfirm implements Listener {
private static final List<UUID> registered = new ArrayList<>();
private Inventory inventory;
private final Player player;
private final ChatConfirmHandler handler;
public AbstractChatConfirm(Player player, ChatConfirmHandler hander) {
this.player = player;
this.handler = hander;
this.inventory = player.getOpenInventory() == null ? null : player.getOpenInventory().getTopInventory();
player.closeInventory();
initializeListeners(UltimateModeration.getInstance());
registered.add(player.getUniqueId());
}
private static boolean listenersInitialized = false;
public void initializeListeners(JavaPlugin plugin) {
if (listenersInitialized) return;
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onChat(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
if (!AbstractChatConfirm.isRegistered(player)) return;
AbstractChatConfirm.unregister(player);
event.setCancelled(true);
ChatConfirmEvent chatConfirmEvent = new ChatConfirmEvent(player, event.getMessage());
handler.onChat(chatConfirmEvent);
if (inventory != null) player.openInventory(inventory);
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
AbstractChatConfirm.unregister(event.getPlayer());
}
}, plugin);
listenersInitialized = true;
}
public static boolean isRegistered(Player player) {
return registered.contains(player.getUniqueId());
}
public static boolean unregister(Player player) {
return registered.remove(player.getUniqueId());
}
public interface ChatConfirmHandler {
void onChat(ChatConfirmEvent event);
}
public class ChatConfirmEvent {
private final Player player;
private final String message;
public ChatConfirmEvent(Player player, String message) {
this.player = player;
this.message = message;
}
public Player getPlayer() {
return player;
}
public String getMessage() {
return message;
}
}
}

View File

@ -0,0 +1,67 @@
package com.songoda.ultimatemoderation.utils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
/**
* ConfigWrapper made by @clip
*/
public class ConfigWrapper {
private final JavaPlugin plugin;
private final String folderName, fileName;
private FileConfiguration config;
private File configFile;
public ConfigWrapper(final JavaPlugin instance, final String folderName, final String fileName) {
this.plugin = instance;
this.folderName = folderName;
this.fileName = fileName;
}
public void createNewFile(final String message, final String header) {
reloadConfig();
saveConfig();
loadConfig(header);
if (message != null) {
plugin.getLogger().info(message);
}
}
public FileConfiguration getConfig() {
if (config == null) {
reloadConfig();
}
return config;
}
public void loadConfig(final String header) {
config.options().header(header);
config.options().copyDefaults(true);
saveConfig();
}
public void reloadConfig() {
if (configFile == null) {
configFile = new File(plugin.getDataFolder() + folderName, fileName);
}
config = YamlConfiguration.loadConfiguration(configFile);
}
public void saveConfig() {
if (config == null || configFile == null) {
return;
}
try {
getConfig().save(configFile);
} catch (final IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex);
}
}
}

View File

@ -0,0 +1,60 @@
package com.songoda.ultimatemoderation.utils;
import com.songoda.ultimatemoderation.UltimateModeration;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLDatabase {
private final UltimateModeration instance;
private Connection connection;
public MySQLDatabase(UltimateModeration instance) {
this.instance = instance;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" + instance.getConfig().getString("Database.IP") + ":" + instance.getConfig().getString("Database.Port") + "/" + instance.getConfig().getString("Database.Database Name") + "?autoReconnect=true&useSSL=false";
this.connection = DriverManager.getConnection(url, instance.getConfig().getString("Database.Username"), instance.getConfig().getString("Database.Password"));
createTables();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Database connection failed.");
}
}
private void createTables() {
/*
try {
connection.createStatement().execute("CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "spawners` (\n" +
"\t`location` TEXT NULL,\n" +
"\t`stacks` TEXT NULL,\n" +
"\t`spawns` INT NULL,\n" +
"\t`placedby` TEXT NULL\n" +
")");
connection.createStatement().execute("CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "boosts` (\n" +
"\t`endtime` TEXT NULL,\n" +
"\t`boosttype` TEXT NULL,\n" +
"\t`data` TEXT NULL,\n" +
"\t`amount` INT NULL\n" +
")");
connection.createStatement().execute("CREATE TABLE IF NOT EXISTS `" + instance.getConfig().getString("Database.Prefix") + "players` (\n" +
"\t`uuid` TEXT NULL,\n" +
"\t`entitykills` TEXT NULL\n" +
")");
} catch (SQLException e) {
e.printStackTrace();
}
*/
}
public Connection getConnection() {
return connection;
}
}

View File

@ -175,10 +175,20 @@ public class SettingsManager implements Listener {
BLOCKED_COMMANDS("Main.Blocked Commands", Arrays.asList("Fly", "Op", "Plugins", "Pl")),
AUTOSAVE("Main.Auto Save Interval In Seconds", 15),
GLASS_TYPE_1("Interfaces.Glass Type 1", 7),
GLASS_TYPE_2("Interfaces.Glass Type 2", 11),
GLASS_TYPE_3("Interfaces.Glass Type 3", 3),
DATABASE_SUPPORT("Database.Activate Mysql Support", false),
DATABASE_IP("Database.IP", "127.0.0.1"),
DATABASE_PORT("Database.Port", 3306),
DATABASE_NAME("Database.Database Name", "UltimateModeration"),
DATABASE_PREFIX("Database.Prefix", "UM-"),
DATABASE_USERNAME("Database.Username", "PUT_USERNAME_HERE"),
DATABASE_PASSWORD("Database.Password", "PUT_PASSWORD_HERE"),
DOWNLOAD_FILES("System.Download Needed Data Files", true),
LANGUGE_MODE("System.Language Mode", "en_US");

View File

@ -78,9 +78,11 @@ gui.templateselector.click = "&7Click to select this template."
gui.templatemanager.title = "&8Templates"
gui.templatemanager.create = "&6&lCreate Template"
gui.templatemanager.leftclick = "&7Left-Click to"
gui.templatemanager.leftclick = "&7Left-Click to edit."
gui.templatemanager.rightclick = "&7Right-Click to destroy."
gui.notes.title = "&8%toModerate% > Notes"
gui.punishments.title = "&8%toModerate% > Punish"
gui.punishments.reason = "&6Reason"
gui.punishments.duration = "&6Initial Duration"
@ -126,5 +128,11 @@ gui.player.title = "&8Players > %toModerate%"
gui.player.punish = "&6&lPunish"
gui.player.moderate = "&b&lModerate"
gui.player.punishments = "&c&lPunishments"
gui.player.notes = "&a&lNotes"
gui.moderate.title = "&8%toModerate% > Moderate"
gui.moderate.title = "&8%toModerate% > Moderate"
gui.moderate.create = "&6Create Note"
gui.moderate.remove = "&cClick to remove"
gui.moderate.type = "Type in your note."
gui.moderate.createdon = "&7Created on &6%time%&7."
gui.moderate.createdby = "&7Created by &6%player%&7."