onEnable: Log an error if NCP is not there or already enabled. Spaces.

This commit is contained in:
asofold 2015-03-22 01:24:18 +01:00
parent 94fd56e66f
commit 21d54b48a4

View File

@ -48,411 +48,420 @@ import fr.neatmonster.nocheatplus.hooks.NCPHookManager;
*/ */
public class CompatNoCheatPlus extends JavaPlugin implements Listener { public class CompatNoCheatPlus extends JavaPlugin implements Listener {
private static CompatNoCheatPlus instance = null; private static CompatNoCheatPlus instance = null;
private final Settings settings = new Settings(); private final Settings settings = new Settings();
/** Hooks registered with cncp */ /** Hooks registered with cncp */
private static final Set<Hook> registeredHooks = new HashSet<Hook>(); private static final Set<Hook> registeredHooks = new HashSet<Hook>();
private final List<Hook> builtinHooks = new LinkedList<Hook>(); private final List<Hook> builtinHooks = new LinkedList<Hook>();
/** /**
* Flag if plugin is enabled. * Flag if plugin is enabled.
*/ */
private static boolean enabled = false; private static boolean enabled = false;
/** /**
* Experimental: static method to enable this plugin, only enables if it is not already enabled. * Experimental: static method to enable this plugin, only enables if it is not already enabled.
* @return * @return
*/ */
public static boolean enableCncp(){ public static boolean enableCncp(){
if (enabled) return true; if (enabled) return true;
return enablePlugin("CompatNoCheatPlus"); return enablePlugin("CompatNoCheatPlus");
} }
/** /**
* Static method to enable a plugin (might also be useful for hooks). * Static method to enable a plugin (might also be useful for hooks).
* @param plgName * @param plgName
* @return * @return
*/ */
public static boolean enablePlugin(String plgName) { public static boolean enablePlugin(String plgName) {
PluginManager pm = Bukkit.getPluginManager(); PluginManager pm = Bukkit.getPluginManager();
Plugin plugin = pm.getPlugin(plgName); Plugin plugin = pm.getPlugin(plgName);
if (plugin == null) return false; if (plugin == null) return false;
if (pm.isPluginEnabled(plugin)) return true; if (pm.isPluginEnabled(plugin)) return true;
pm.enablePlugin(plugin); pm.enablePlugin(plugin);
return true; return true;
} }
/** /**
* Static method to disable a plugin (might also be useful for hooks). * Static method to disable a plugin (might also be useful for hooks).
* @param plgName * @param plgName
* @return * @return
*/ */
public static boolean disablePlugin(String plgName){ public static boolean disablePlugin(String plgName){
PluginManager pm = Bukkit.getPluginManager(); PluginManager pm = Bukkit.getPluginManager();
Plugin plugin = pm.getPlugin(plgName); Plugin plugin = pm.getPlugin(plgName);
if (plugin == null) return false; if (plugin == null) return false;
if (!pm.isPluginEnabled(plugin)) return true; if (!pm.isPluginEnabled(plugin)) return true;
pm.disablePlugin(plugin); pm.disablePlugin(plugin);
return true; return true;
} }
/** /**
* Get the plugin instance. * Get the plugin instance.
* @return * @return
*/ */
public static CompatNoCheatPlus getInstance(){ public static CompatNoCheatPlus getInstance(){
return instance; return instance;
} }
/** /**
* API to add a hook. Adds the hook AND registers listeners if enabled. Also respects the configuration for preventing hooks.<br> * API to add a hook. Adds the hook AND registers listeners if enabled. Also respects the configuration for preventing hooks.<br>
* If you want to not register the listeners use NCPHookManager. * If you want to not register the listeners use NCPHookManager.
* @param hook * @param hook
* @return * @return
*/ */
public static boolean addHook(Hook hook){ public static boolean addHook(Hook hook){
if (Settings.preventAddHooks.contains(hook.getHookName())){ if (Settings.preventAddHooks.contains(hook.getHookName())){
Bukkit.getLogger().info("[cncp] Prevented adding hook: "+hook.getHookName() + " / " + hook.getHookVersion()); Bukkit.getLogger().info("[cncp] Prevented adding hook: "+hook.getHookName() + " / " + hook.getHookVersion());
return false; return false;
} }
registeredHooks.add(hook); registeredHooks.add(hook);
if (enabled) registerListeners(hook); if (enabled) registerListeners(hook);
boolean added = checkAddNCPHook(hook); // Add if plugin is present, otherwise queue for adding. boolean added = checkAddNCPHook(hook); // Add if plugin is present, otherwise queue for adding.
Bukkit.getLogger().info("[cncp] Registered hook"+(added?"":"(NCPHook might get added later)")+": "+hook.getHookName() + " / " + hook.getHookVersion()); Bukkit.getLogger().info("[cncp] Registered hook"+(added?"":"(NCPHook might get added later)")+": "+hook.getHookName() + " / " + hook.getHookVersion());
return true; return true;
} }
/** /**
* If already added to NCP * If already added to NCP
* @param hook * @param hook
* @return * @return
*/ */
private static boolean checkAddNCPHook(Hook hook) { private static boolean checkAddNCPHook(Hook hook) {
PluginManager pm = Bukkit.getPluginManager(); PluginManager pm = Bukkit.getPluginManager();
Plugin plugin = pm.getPlugin("NoCheatPlus"); Plugin plugin = pm.getPlugin("NoCheatPlus");
if (plugin == null || !pm.isPluginEnabled(plugin)) if (plugin == null || !pm.isPluginEnabled(plugin))
return false; return false;
NCPHook ncpHook = hook.getNCPHook(); NCPHook ncpHook = hook.getNCPHook();
if (ncpHook != null) if (ncpHook != null)
NCPHookManager.addHook(hook.getCheckTypes(), ncpHook); NCPHookManager.addHook(hook.getCheckTypes(), ncpHook);
return true; return true;
} }
/** /**
* Conveniently register the listeners, do not use if you add/added the hook with addHook. * Conveniently register the listeners, do not use if you add/added the hook with addHook.
* @param hook * @param hook
* @return * @return
*/ */
public static boolean registerListeners(Hook hook) { public static boolean registerListeners(Hook hook) {
if (!enabled) return false; if (!enabled) return false;
Listener[] listeners = hook.getListeners(); Listener[] listeners = hook.getListeners();
if (listeners != null){ if (listeners != null){
// attempt to register events: // attempt to register events:
PluginManager pm = Bukkit.getPluginManager(); PluginManager pm = Bukkit.getPluginManager();
Plugin plg = pm.getPlugin("CompatNoCheatPlus"); Plugin plg = pm.getPlugin("CompatNoCheatPlus");
if (plg == null) return false; if (plg == null) return false;
for (Listener listener : listeners) { for (Listener listener : listeners) {
pm.registerEvents(listener, plg); pm.registerEvents(listener, plg);
} }
} }
return true; return true;
} }
/** /**
* Called before loading settings, adds available hooks into a list, so they will be able to read config. * Called before loading settings, adds available hooks into a list, so they will be able to read config.
*/ */
private void setupBuiltinHooks() { private void setupBuiltinHooks() {
builtinHooks.clear(); builtinHooks.clear();
// Might-fail hooks: // Might-fail hooks:
// Set speed // Set speed
try{ try{
builtinHooks.add(new me.asofold.bpl.cncp.hooks.generic.HookSetSpeed()); builtinHooks.add(new me.asofold.bpl.cncp.hooks.generic.HookSetSpeed());
} }
catch (Throwable t){} catch (Throwable t){}
// Citizens 2 // Citizens 2
try{ try{
builtinHooks.add(new me.asofold.bpl.cncp.hooks.citizens2.HookCitizens2()); builtinHooks.add(new me.asofold.bpl.cncp.hooks.citizens2.HookCitizens2());
} }
catch (Throwable t){} catch (Throwable t){}
// mcMMO // mcMMO
try{ try{
builtinHooks.add(new me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO()); builtinHooks.add(new me.asofold.bpl.cncp.hooks.mcmmo.HookmcMMO());
} }
catch (Throwable t){} catch (Throwable t){}
// MagicSpells // MagicSpells
try{ try{
builtinHooks.add(new me.asofold.bpl.cncp.hooks.magicspells.HookMagicSpells()); builtinHooks.add(new me.asofold.bpl.cncp.hooks.magicspells.HookMagicSpells());
} }
catch (Throwable t){} catch (Throwable t){}
// Simple generic hooks // Simple generic hooks
for (Hook hook : new Hook[]{ for (Hook hook : new Hook[]{
new HookPlayerClass(), new HookPlayerClass(),
new HookBlockBreak(), new HookBlockBreak(),
new HookBlockPlace(), new HookBlockPlace(),
new HookInstaBreak(), new HookInstaBreak(),
new HookEntityDamageByEntity(), new HookEntityDamageByEntity(),
}){ }){
builtinHooks.add(hook); builtinHooks.add(hook);
} }
} }
/** /**
* Add standard hooks if enabled. * Add standard hooks if enabled.
*/ */
private void addAvailableHooks() { private void addAvailableHooks() {
// Add built in hooks: // Add built in hooks:
for (Hook hook : builtinHooks){ for (Hook hook : builtinHooks){
boolean add = true; boolean add = true;
if (hook instanceof ConfigurableHook){ if (hook instanceof ConfigurableHook){
if (!((ConfigurableHook)hook).isEnabled()) add = false; if (!((ConfigurableHook)hook).isEnabled()) add = false;
} }
if (add){ if (add){
try{ try{
addHook(hook); addHook(hook);
} }
catch (Throwable t){} catch (Throwable t){}
} }
} }
} }
@Override @Override
public void onEnable() { public void onEnable() {
enabled = false; // make sure enabled = false; // make sure
instance = this; instance = this;
// (no cleanup) // (no cleanup)
// Settings: // Settings:
settings.clear(); settings.clear();
setupBuiltinHooks(); setupBuiltinHooks();
loadSettings(); loadSettings();
// Register own listener: // Register own listener:
final PluginManager pm = getServer().getPluginManager(); final PluginManager pm = getServer().getPluginManager();
pm.registerEvents(this, this); pm.registerEvents(this, this);
super.onEnable(); super.onEnable();
// Add Hooks: // Add Hooks:
addAvailableHooks(); // add before enable is set to not yet register listeners. addAvailableHooks(); // add before enable is set to not yet register listeners.
enabled = true; enabled = true;
// register all listeners: // register all listeners:
for (Hook hook : registeredHooks){ for (Hook hook : registeredHooks){
registerListeners(hook); registerListeners(hook);
} }
// Start ticktask 2 // Start ticktask 2
getServer().getScheduler().scheduleSyncRepeatingTask(this, new TickTask2(), 1, 1); getServer().getScheduler().scheduleSyncRepeatingTask(this, new TickTask2(), 1, 1);
// Finished. // Check for the NoCheatPlus plugin.
getLogger().info(getDescription().getFullName() + " is enabled. Some hooks might get registered with NoCheatPlus later on."); Plugin plugin = pm.getPlugin("NoCheatPlus");
} if (plugin == null) {
getLogger().severe("[CompatNoCheatPlus] The NoCheatPlus plugin is not present.");
}
else if (plugin.isEnabled()) {
getLogger().severe("[CompatNoCheatPlus] The NoCheatPlus plugin already is enabled, this might break several hooks.");
}
public boolean loadSettings() { // Finished.
final Set<String> oldForceEnableLater = new LinkedHashSet<String>(); getLogger().info(getDescription().getFullName() + " is enabled. Some hooks might get registered with NoCheatPlus later on.");
oldForceEnableLater.addAll(settings.forceEnableLater); }
// Read and apply config to settings:
File file = new File(getDataFolder() , "cncp.yml"); public boolean loadSettings() {
CompatConfig cfg = new NewConfig(file); final Set<String> oldForceEnableLater = new LinkedHashSet<String>();
cfg.load(); oldForceEnableLater.addAll(settings.forceEnableLater);
boolean changed = false; // Read and apply config to settings:
// General settings: File file = new File(getDataFolder() , "cncp.yml");
if (Settings.addDefaults(cfg)) changed = true; CompatConfig cfg = new NewConfig(file);
settings.fromConfig(cfg); cfg.load();
// Settings for builtin hooks: boolean changed = false;
for (Hook hook : builtinHooks){ // General settings:
if (hook instanceof ConfigurableHook){ if (Settings.addDefaults(cfg)) changed = true;
try{ settings.fromConfig(cfg);
ConfigurableHook cfgHook = (ConfigurableHook) hook; // Settings for builtin hooks:
if (cfgHook.updateConfig(cfg, "hooks.")) changed = true; for (Hook hook : builtinHooks){
cfgHook.applyConfig(cfg, "hooks."); if (hook instanceof ConfigurableHook){
} try{
catch (Throwable t){ ConfigurableHook cfgHook = (ConfigurableHook) hook;
getLogger().severe("[cncp] Hook failed to process config ("+hook.getHookName() +" / " + hook.getHookVersion()+"): " + t.getClass().getSimpleName() + ": "+t.getMessage()); if (cfgHook.updateConfig(cfg, "hooks.")) changed = true;
t.printStackTrace(); cfgHook.applyConfig(cfg, "hooks.");
} }
} catch (Throwable t){
} getLogger().severe("[cncp] Hook failed to process config ("+hook.getHookName() +" / " + hook.getHookVersion()+"): " + t.getClass().getSimpleName() + ": "+t.getMessage());
// save back config if changed: t.printStackTrace();
if (changed) cfg.save(); }
}
}
// save back config if changed:
if (changed) cfg.save();
// Re-enable plugins that were not yet on the list: // Re-enable plugins that were not yet on the list:
Server server = getServer(); Server server = getServer();
Logger logger = server.getLogger(); Logger logger = server.getLogger();
for (String plgName : settings.loadPlugins){ for (String plgName : settings.loadPlugins){
try{ try{
if (CompatNoCheatPlus.enablePlugin(plgName)){ if (CompatNoCheatPlus.enablePlugin(plgName)){
System.out.println("[cncp] Ensured that the following plugin is enabled: " + plgName); System.out.println("[cncp] Ensured that the following plugin is enabled: " + plgName);
} }
} }
catch (Throwable t){ catch (Throwable t){
logger.severe("[cncp] Failed to enable the plugin: " + plgName); logger.severe("[cncp] Failed to enable the plugin: " + plgName);
logger.severe(Utils.toString(t)); logger.severe(Utils.toString(t));
} }
} }
BukkitScheduler sched = server.getScheduler(); BukkitScheduler sched = server.getScheduler();
for (String plgName : settings.forceEnableLater){ for (String plgName : settings.forceEnableLater){
if (!oldForceEnableLater.remove(plgName)) oldForceEnableLater.add(plgName); if (!oldForceEnableLater.remove(plgName)) oldForceEnableLater.add(plgName);
} }
if (!oldForceEnableLater.isEmpty()){ if (!oldForceEnableLater.isEmpty()){
System.out.println("[cncp] Schedule task to re-enable plugins later..."); System.out.println("[cncp] Schedule task to re-enable plugins later...");
sched.scheduleSyncDelayedTask(this, new Runnable() { sched.scheduleSyncDelayedTask(this, new Runnable() {
@Override @Override
public void run() { public void run() {
// (Later maybe re-enabling this plugin could be added.) // (Later maybe re-enabling this plugin could be added.)
// TODO: log levels ! // TODO: log levels !
for (String plgName : oldForceEnableLater){ for (String plgName : oldForceEnableLater){
try{ try{
if (disablePlugin(plgName)){ if (disablePlugin(plgName)){
if (enablePlugin(plgName)) System.out.println("[cncp] Re-enabled plugin: " + plgName); if (enablePlugin(plgName)) System.out.println("[cncp] Re-enabled plugin: " + plgName);
else System.out.println("[cncp] Could not re-enable plugin: "+plgName); else System.out.println("[cncp] Could not re-enable plugin: "+plgName);
} }
else{ else{
System.out.println("[cncp] Could not disable plugin (already disabled?): "+plgName); System.out.println("[cncp] Could not disable plugin (already disabled?): "+plgName);
} }
} }
catch(Throwable t){ catch(Throwable t){
// TODO: maybe log ? // TODO: maybe log ?
} }
} }
} }
}); });
} }
return true; return true;
} }
@Override @Override
public void onDisable() { public void onDisable() {
unregisterNCPHooks(); // Just in case. unregisterNCPHooks(); // Just in case.
enabled = false; enabled = false;
instance = null; // Set last. instance = null; // Set last.
super.onDisable(); super.onDisable();
} }
protected int unregisterNCPHooks() { protected int unregisterNCPHooks() {
// TODO: Clear list here !? Currently done externally... // TODO: Clear list here !? Currently done externally...
int n = 0; int n = 0;
for (Hook hook : registeredHooks) { for (Hook hook : registeredHooks) {
String hookDescr = null; String hookDescr = null;
try { try {
NCPHook ncpHook = hook.getNCPHook(); NCPHook ncpHook = hook.getNCPHook();
if (ncpHook != null){ if (ncpHook != null){
hookDescr = ncpHook.getHookName() + ": " + ncpHook.getHookVersion(); hookDescr = ncpHook.getHookName() + ": " + ncpHook.getHookVersion();
NCPHookManager.removeHook(ncpHook); NCPHookManager.removeHook(ncpHook);
n ++; n ++;
} }
} catch (Throwable e) } catch (Throwable e)
{ {
if (hookDescr != null) { if (hookDescr != null) {
// Some error with removing a hook. // Some error with removing a hook.
getLogger().log(Level.WARNING, "Failed to unregister hook: " + hookDescr, e); getLogger().log(Level.WARNING, "Failed to unregister hook: " + hookDescr, e);
} }
} }
} }
getLogger().info("[cncp] Removed "+n+" registered hooks from NoCheatPlus."); getLogger().info("[cncp] Removed "+n+" registered hooks from NoCheatPlus.");
registeredHooks.clear(); registeredHooks.clear();
return n; return n;
} }
private int registerHooks() { private int registerHooks() {
int n = 0; int n = 0;
for (Hook hook : registeredHooks){ for (Hook hook : registeredHooks){
// TODO: try catch // TODO: try catch
NCPHook ncpHook = hook.getNCPHook(); NCPHook ncpHook = hook.getNCPHook();
if (ncpHook == null) continue; if (ncpHook == null) continue;
NCPHookManager.addHook(hook.getCheckTypes(), ncpHook); NCPHookManager.addHook(hook.getCheckTypes(), ncpHook);
n ++; n ++;
} }
getLogger().info("[cncp] Added "+n+" registered hooks to NoCheatPlus."); getLogger().info("[cncp] Added "+n+" registered hooks to NoCheatPlus.");
return n; return n;
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
void onPluginEnable(PluginEnableEvent event){ void onPluginEnable(PluginEnableEvent event){
Plugin plugin = event.getPlugin(); Plugin plugin = event.getPlugin();
if (!plugin.getName().equals("NoCheatPlus")) { if (!plugin.getName().equals("NoCheatPlus")) {
return; return;
} }
// Register to rmeove hooks when NCP is disabling. // Register to rmeove hooks when NCP is disabling.
NCPAPIProvider.getNoCheatPlusAPI().addComponent(new DisableListener(){ NCPAPIProvider.getNoCheatPlusAPI().addComponent(new DisableListener(){
@Override @Override
public void onDisable() { public void onDisable() {
// Remove all registered cncp hooks: // Remove all registered cncp hooks:
unregisterNCPHooks(); unregisterNCPHooks();
} }
}); });
if (registeredHooks.isEmpty()) { if (registeredHooks.isEmpty()) {
return; return;
} }
registerHooks(); registerHooks();
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[]) * @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/ */
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Permission has already been checked. // Permission has already been checked.
sendInfo(sender); sendInfo(sender);
return true; return true;
} }
/** /**
* Send general version and hooks info. * Send general version and hooks info.
* @param sender * @param sender
*/ */
private void sendInfo(CommandSender sender) { private void sendInfo(CommandSender sender) {
List<String> infos = new LinkedList<String>(); List<String> infos = new LinkedList<String>();
infos.add("---- Version infomation ----"); infos.add("---- Version infomation ----");
// Server // Server
infos.add("#### Server ####"); infos.add("#### Server ####");
infos.add(getServer().getVersion()); infos.add(getServer().getVersion());
// Core plugins (NCP + cncp) // Core plugins (NCP + cncp)
infos.add("#### Core plugins ####"); infos.add("#### Core plugins ####");
infos.add(getDescription().getFullName()); infos.add(getDescription().getFullName());
String temp = getOtherVersion("NoCheatPlus"); String temp = getOtherVersion("NoCheatPlus");
infos.add(temp.isEmpty() ? "NoCheatPlus is missing or not yet enabled." : temp); infos.add(temp.isEmpty() ? "NoCheatPlus is missing or not yet enabled." : temp);
infos.add("#### Typical plugin dependencies ####"); infos.add("#### Typical plugin dependencies ####");
for (String pluginName : new String[]{ for (String pluginName : new String[]{
"mcMMO", "Citizens", "MachinaCraft", "MagicSpells", "mcMMO", "Citizens", "MachinaCraft", "MagicSpells",
// TODO: extend // TODO: extend
}){ }){
temp = getOtherVersion(pluginName); temp = getOtherVersion(pluginName);
if (!temp.isEmpty()) infos.add(temp); if (!temp.isEmpty()) infos.add(temp);
} }
// Hooks // Hooks
infos.add("#### Registered hooks (cncp) ###"); infos.add("#### Registered hooks (cncp) ###");
for (final Hook hook : registeredHooks){ for (final Hook hook : registeredHooks){
temp = hook.getHookName() + ": " + hook.getHookVersion(); temp = hook.getHookName() + ": " + hook.getHookVersion();
if (hook instanceof ConfigurableHook){ if (hook instanceof ConfigurableHook){
temp += ((ConfigurableHook) hook).isEnabled() ? " (enabled)" : " (disabled)"; temp += ((ConfigurableHook) hook).isEnabled() ? " (enabled)" : " (disabled)";
} }
infos.add(temp); infos.add(temp);
} }
// TODO: Registered hooks (ncp) ? // TODO: Registered hooks (ncp) ?
infos.add("#### Registered hooks (ncp) ####"); infos.add("#### Registered hooks (ncp) ####");
for (final NCPHook hook : NCPHookManager.getAllHooks()){ for (final NCPHook hook : NCPHookManager.getAllHooks()){
infos.add(hook.getHookName() + ": " + hook.getHookVersion()); infos.add(hook.getHookName() + ": " + hook.getHookVersion());
} }
final String[] a = new String[infos.size()]; final String[] a = new String[infos.size()];
infos.toArray(a); infos.toArray(a);
sender.sendMessage(a); sender.sendMessage(a);
} }
/** /**
* *
* @param pluginName Empty string or "name: version". * @param pluginName Empty string or "name: version".
*/ */
private String getOtherVersion(String pluginName){ private String getOtherVersion(String pluginName){
Plugin plg = getServer().getPluginManager().getPlugin(pluginName); Plugin plg = getServer().getPluginManager().getPlugin(pluginName);
if (plg == null) return ""; if (plg == null) return "";
PluginDescriptionFile pdf = plg.getDescription(); PluginDescriptionFile pdf = plg.getDescription();
return pdf.getFullName(); return pdf.getFullName();
} }
} }