PageRenderTime 29ms CodeModel.GetById 13ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 0ms

/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java

https://gitlab.com/Skull3x/WorldEdit
Java | 307 lines | 248 code | 40 blank | 19 comment | 35 complexity | a8c938c27aa9adca777b87a25feea47c MD5 | raw file
  1/*
  2 * WorldEdit, a Minecraft world manipulation toolkit
  3 * Copyright (C) sk89q <http://www.sk89q.com>
  4 * Copyright (C) WorldEdit team and contributors
  5 *
  6 * This program is free software: you can redistribute it and/or modify it
  7 * under the terms of the GNU Lesser General Public License as published by the
  8 * Free Software Foundation, either version 3 of the License, or
  9 * (at your option) any later version.
 10 *
 11 * This program is distributed in the hope that it will be useful, but WITHOUT
 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 14 * for more details.
 15 *
 16 * You should have received a copy of the GNU Lesser General Public License
 17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 18 */
 19
 20package com.sk89q.wepif;
 21
 22import com.sk89q.util.yaml.YAMLFormat;
 23import com.sk89q.util.yaml.YAMLProcessor;
 24import org.bukkit.OfflinePlayer;
 25import org.bukkit.Server;
 26import org.bukkit.event.EventHandler;
 27import org.bukkit.event.server.PluginDisableEvent;
 28import org.bukkit.event.server.PluginEnableEvent;
 29import org.bukkit.plugin.Plugin;
 30
 31import java.io.File;
 32import java.io.IOException;
 33import java.lang.reflect.Method;
 34import java.util.ArrayList;
 35import java.util.Arrays;
 36import java.util.Iterator;
 37import java.util.List;
 38import java.util.logging.Level;
 39import java.util.logging.Logger;
 40
 41public class PermissionsResolverManager implements PermissionsResolver {
 42
 43    private static final String CONFIG_HEADER = "#\r\n" +
 44            "# WEPIF Configuration File\r\n" +
 45            "#\r\n" +
 46            "# This file handles permissions configuration for every plugin using WEPIF\r\n" +
 47            "#\r\n" +
 48            "# About editing this file:\r\n" +
 49            "# - DO NOT USE TABS. You MUST use spaces or Bukkit will complain. If\r\n" +
 50            "#   you use an editor like Notepad++ (recommended for Windows users), you\r\n" +
 51            "#   must configure it to \"replace tabs with spaces.\" In Notepad++, this can\r\n" +
 52            "#   be changed in Settings > Preferences > Language Menu.\r\n" +
 53            "# - Don't get rid of the indents. They are indented so some entries are\r\n" +
 54            "#   in categories (like \"enforce-single-session\" is in the \"protection\"\r\n" +
 55            "#   category.\r\n" +
 56            "# - If you want to check the format of this file before putting it\r\n" +
 57            "#   into WEPIF, paste it into http://yaml-online-parser.appspot.com/\r\n" +
 58            "#   and see if it gives \"ERROR:\".\r\n" +
 59            "# - Lines starting with # are comments and so they are ignored.\r\n" +
 60            "#\r\n" +
 61            "# About Configuration Permissions\r\n" +
 62            "# - See http://wiki.sk89q.com/wiki/WorldEdit/Permissions/Bukkit\r\n" +
 63            "# - Now with multiworld support (see example)\r\n" +
 64            "\r\n";
 65
 66    private static PermissionsResolverManager instance;
 67
 68    public static void initialize(Plugin plugin) {
 69        if (!isInitialized()) {
 70            instance = new PermissionsResolverManager(plugin);
 71        }
 72    }
 73
 74    public static boolean isInitialized() {
 75        return instance != null;
 76    }
 77
 78    public static PermissionsResolverManager getInstance() {
 79        if (!isInitialized()) {
 80            throw new WEPIFRuntimeException("WEPIF has not yet been initialized!");
 81        }
 82        return instance;
 83    }
 84
 85    private Server server;
 86    private PermissionsResolver permissionResolver;
 87    private YAMLProcessor config;
 88    private Logger logger = Logger.getLogger(getClass().getCanonicalName());
 89    private List<Class<? extends PermissionsResolver>> enabledResolvers = new ArrayList<Class<? extends PermissionsResolver>>();
 90
 91    @SuppressWarnings("unchecked")
 92    protected Class<? extends PermissionsResolver>[] availableResolvers = new Class[] {
 93            PluginPermissionsResolver.class,
 94            PermissionsExResolver.class,
 95            bPermissionsResolver.class,
 96            GroupManagerResolver.class,
 97            NijiPermissionsResolver.class,
 98            DinnerPermsResolver.class,
 99            FlatFilePermissionsResolver.class
100    };
101
102    protected PermissionsResolverManager(Plugin plugin) {
103        this.server = plugin.getServer();
104        (new ServerListener()).register(plugin); // Register the events
105
106        loadConfig(new File("wepif.yml"));
107        findResolver();
108    }
109
110    public void findResolver() {
111        for (Class<? extends PermissionsResolver> resolverClass : enabledResolvers) {
112            try {
113                Method factoryMethod = resolverClass.getMethod("factory", Server.class, YAMLProcessor.class);
114
115                this.permissionResolver = (PermissionsResolver) factoryMethod.invoke(null, this.server, this.config);
116
117                if (this.permissionResolver != null) {
118                    break;
119                }
120            } catch (Throwable e) {
121                logger.log(Level.WARNING, "Error in factory method for " + resolverClass.getSimpleName(), e);
122                continue;
123            }
124        }
125        if (permissionResolver == null) {
126            permissionResolver = new ConfigurationPermissionsResolver(config);
127        }
128        permissionResolver.load();
129        logger.info("WEPIF: " + permissionResolver.getDetectionMessage());
130    }
131
132    public void setPluginPermissionsResolver(Plugin plugin) {
133        if (!(plugin instanceof PermissionsProvider)) {
134            return;
135        }
136
137        permissionResolver = new PluginPermissionsResolver((PermissionsProvider) plugin, plugin);
138        logger.info("WEPIF: " + permissionResolver.getDetectionMessage());
139    }
140
141    @Override
142    public void load() {
143        findResolver();
144    }
145
146    @Override
147    public boolean hasPermission(String name, String permission) {
148        return permissionResolver.hasPermission(name, permission);
149    }
150
151    @Override
152    public boolean hasPermission(String worldName, String name, String permission) {
153        return permissionResolver.hasPermission(worldName, name, permission);
154    }
155
156    @Override
157    public boolean inGroup(String player, String group) {
158        return permissionResolver.inGroup(player, group);
159    }
160
161    @Override
162    public String[] getGroups(String player) {
163        return permissionResolver.getGroups(player);
164    }
165
166    @Override
167    public boolean hasPermission(OfflinePlayer player, String permission) {
168        return permissionResolver.hasPermission(player, permission);
169    }
170
171    @Override
172    public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
173        return permissionResolver.hasPermission(worldName, player, permission);
174    }
175
176    @Override
177    public boolean inGroup(OfflinePlayer player, String group) {
178        return permissionResolver.inGroup(player, group);
179    }
180
181    @Override
182    public String[] getGroups(OfflinePlayer player) {
183        return permissionResolver.getGroups(player);
184    }
185
186    @Override
187    public String getDetectionMessage() {
188        return "Using WEPIF for permissions";
189    }
190
191    private boolean loadConfig(File file) {
192        boolean isUpdated = false;
193        if (!file.exists()) {
194            try {
195                file.createNewFile();
196            } catch (IOException e) {
197                logger.log(Level.WARNING, "Failed to create new configuration file", e);
198            }
199        }
200        config = new YAMLProcessor(file, false, YAMLFormat.EXTENDED);
201        try {
202            config.load();
203        } catch (IOException e) {
204            logger.log(Level.WARNING, "Error loading WEPIF configuration", e);
205        }
206        List<String> keys = config.getKeys(null);
207        config.setHeader(CONFIG_HEADER);
208
209        if (!keys.contains("ignore-nijiperms-bridges")) {
210            config.setProperty("ignore-nijiperms-bridges", true);
211            isUpdated = true;
212        }
213
214        if (!keys.contains("resolvers")) {
215            //List<String> resolverKeys = config.getKeys("resolvers");
216            List<String> resolvers = new ArrayList<String>();
217            for (Class<?> clazz : availableResolvers) {
218                resolvers.add(clazz.getSimpleName());
219            }
220            enabledResolvers.addAll(Arrays.asList(availableResolvers));
221            config.setProperty("resolvers.enabled", resolvers);
222            isUpdated = true;
223        } else {
224            List<String> disabledResolvers = config.getStringList("resolvers.disabled", new ArrayList<String>());
225            List<String> stagedEnabled = config.getStringList("resolvers.enabled", null);
226            for (Iterator<String> i = stagedEnabled.iterator(); i.hasNext();) {
227                String nextName = i.next();
228                Class<?> next = null;
229                try {
230                    next = Class.forName(getClass().getPackage().getName() + "." + nextName);
231                } catch (ClassNotFoundException e) {}
232
233                if (next == null || !PermissionsResolver.class.isAssignableFrom(next)) {
234                    logger.warning("WEPIF: Invalid or unknown class found in enabled resolvers: "
235                            + nextName + ". Moving to disabled resolvers list.");
236                    i.remove();
237                    disabledResolvers.add(nextName);
238                    isUpdated = true;
239                    continue;
240                }
241                enabledResolvers.add(next.asSubclass(PermissionsResolver.class));
242            }
243
244            for (Class<?> clazz : availableResolvers) {
245                if (!stagedEnabled.contains(clazz.getSimpleName()) &&
246                        !disabledResolvers.contains(clazz.getSimpleName())) {
247                    disabledResolvers.add(clazz.getSimpleName());
248                    logger.info("New permissions resolver: "
249                            + clazz.getSimpleName() + " detected. " +
250                            "Added to disabled resolvers list.");
251                    isUpdated = true;
252                }
253            }
254            config.setProperty("resolvers.disabled", disabledResolvers);
255            config.setProperty("resolvers.enabled", stagedEnabled);
256        }
257
258        if (keys.contains("dinner-perms") || keys.contains("dinnerperms")) {
259            config.removeProperty("dinner-perms");
260            config.removeProperty("dinnerperms");
261            isUpdated = true;
262        }
263        if (!keys.contains("permissions")) {
264            ConfigurationPermissionsResolver.generateDefaultPerms(
265                    config.addNode("permissions"));
266            isUpdated = true;
267        }
268        if (isUpdated) {
269            logger.info("WEPIF: Updated config file");
270            config.save();
271        }
272        return isUpdated;
273    }
274
275    public static class MissingPluginException extends Exception {
276    }
277
278    class ServerListener implements org.bukkit.event.Listener {
279        @EventHandler
280        public void onPluginEnable(PluginEnableEvent event) {
281            Plugin plugin = event.getPlugin();
282            String name = plugin.getDescription().getName();
283            if (plugin instanceof PermissionsProvider) {
284                setPluginPermissionsResolver(plugin);
285            } else if ("permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name)
286                    || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) {
287                load();
288            }
289        }
290
291        @EventHandler
292        public void onPluginDisable(PluginDisableEvent event) {
293            String name = event.getPlugin().getDescription().getName();
294
295            if (event.getPlugin() instanceof PermissionsProvider
296                    || "permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name)
297                    || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) {
298                load();
299            }
300        }
301
302        void register(Plugin plugin) {
303            plugin.getServer().getPluginManager().registerEvents(this, plugin);
304        }
305    }
306
307}