PluginManager.java 7.19 KB
Newer Older
KingRainbow44's avatar
KingRainbow44 committed
1
2
3
package emu.grasscutter.plugin;

import emu.grasscutter.Grasscutter;
KingRainbow44's avatar
KingRainbow44 committed
4
5
import emu.grasscutter.server.event.Event;
import emu.grasscutter.server.event.EventHandler;
6
import emu.grasscutter.server.event.HandlerPriority;
KingRainbow44's avatar
KingRainbow44 committed
7
8
9
10
import emu.grasscutter.utils.Utils;

import java.io.File;
import java.io.InputStreamReader;
KingRainbow44's avatar
KingRainbow44 committed
11
import java.lang.reflect.Method;
12
import java.net.MalformedURLException;
KingRainbow44's avatar
KingRainbow44 committed
13
14
import java.net.URL;
import java.net.URLClassLoader;
KingRainbow44's avatar
KingRainbow44 committed
15
import java.util.*;
muhammadeko's avatar
muhammadeko committed
16
17
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
KingRainbow44's avatar
KingRainbow44 committed
18
19

/**
KingRainbow44's avatar
KingRainbow44 committed
20
 * Manages the server's plugins and the event system.
KingRainbow44's avatar
KingRainbow44 committed
21
22
23
 */
public final class PluginManager {
    private final Map<String, Plugin> plugins = new HashMap<>();
KingRainbow44's avatar
KingRainbow44 committed
24
    private final List<EventHandler<? extends Event>> listeners = new LinkedList<>();
KingRainbow44's avatar
KingRainbow44 committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    
    public PluginManager() {
        this.loadPlugins(); // Load all plugins from the plugins directory.
    }

    /**
     * Loads plugins from the config-specified directory.
     */
    private void loadPlugins() {
        String directory = Grasscutter.getConfig().PLUGINS_FOLDER;
        File pluginsDir = new File(Utils.toFilePath(directory));
        if(!pluginsDir.exists() && !pluginsDir.mkdirs()) {
            Grasscutter.getLogger().error("Failed to create plugins directory: " + pluginsDir.getAbsolutePath());
            return;
        }
        
        File[] files = pluginsDir.listFiles();
        if(files == null) {
            // The directory is empty, there aren't any plugins to load.
            return;
        }
        
        List<File> plugins = Arrays.stream(files)
                .filter(file -> file.getName().endsWith(".jar"))
KingRainbow44's avatar
KingRainbow44 committed
49
                .toList();
50
51
52
53
54

        URL[] pluginNames = new URL[plugins.size()];
        plugins.forEach(plugin -> {
            try {
                pluginNames[plugins.indexOf(plugin)] = plugin.toURI().toURL();
Magix's avatar
Magix committed
55
56
            } catch (MalformedURLException exception) {
                Grasscutter.getLogger().warn("Unable to load plugin.", exception);
57
58
59
60
61
            }
        });

        URLClassLoader classLoader = new URLClassLoader(pluginNames);

KingRainbow44's avatar
KingRainbow44 committed
62
63
64
65
        plugins.forEach(plugin -> {
            try {
                URL url = plugin.toURI().toURL();
                try (URLClassLoader loader = new URLClassLoader(new URL[]{url})) {
66
                    URL configFile = loader.findResource("plugin.json"); // Find the plugin.json file for each plugin.
KingRainbow44's avatar
KingRainbow44 committed
67
                    InputStreamReader fileReader = new InputStreamReader(configFile.openStream());
muhammadeko's avatar
muhammadeko committed
68

KingRainbow44's avatar
KingRainbow44 committed
69
70
71
72
73
74
                    PluginConfig pluginConfig = Grasscutter.getGsonFactory().fromJson(fileReader, PluginConfig.class);
                    if(!pluginConfig.validate()) {
                        Utils.logObject(pluginConfig);
                        Grasscutter.getLogger().warn("Plugin " + plugin.getName() + " has an invalid config file.");
                        return;
                    }
muhammadeko's avatar
muhammadeko committed
75
76
77
78
79

                    JarFile jarFile = new JarFile(plugin);
                    Enumeration<JarEntry> entries = jarFile.entries();
                    while(entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
muhammadeko's avatar
muhammadeko committed
80
                        if(entry.isDirectory() || !entry.getName().endsWith(".class") || entry.getName().contains("module-info")) continue;
muhammadeko's avatar
muhammadeko committed
81
                        String className = entry.getName().replace(".class", "").replace("/", ".");
Magix's avatar
Magix committed
82
                        classLoader.loadClass(className); // Use the same class loader for ALL plugins.
muhammadeko's avatar
muhammadeko committed
83
                    }
KingRainbow44's avatar
KingRainbow44 committed
84
                    
85
                    Class<?> pluginClass = classLoader.loadClass(pluginConfig.mainClass);
KingRainbow44's avatar
KingRainbow44 committed
86
                    Plugin pluginInstance = (Plugin) pluginClass.getDeclaredConstructor().newInstance();
87
                    this.loadPlugin(pluginInstance, PluginIdentifier.fromPluginConfig(pluginConfig), loader);
KingRainbow44's avatar
KingRainbow44 committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
                    
                    fileReader.close(); // Close the file reader.
                } catch (ClassNotFoundException ignored) {
                    Grasscutter.getLogger().warn("Plugin " + plugin.getName() + " has an invalid main class.");
                }
            } catch (Exception exception) {
                Grasscutter.getLogger().error("Failed to load plugin: " + plugin.getName(), exception);
            }
        });
    }

    /**
     * Load the specified plugin.
     * @param plugin The plugin instance.
     */
103
    private void loadPlugin(Plugin plugin, PluginIdentifier identifier, URLClassLoader classLoader) {
KingRainbow44's avatar
KingRainbow44 committed
104
105
106
107
108
        Grasscutter.getLogger().info("Loading plugin: " + identifier.name);
        
        // Add the plugin's identifier.
        try {
            Class<Plugin> pluginClass = Plugin.class;
109
110
            Method method = pluginClass.getDeclaredMethod("initializePlugin", PluginIdentifier.class, URLClassLoader.class);
            method.setAccessible(true); method.invoke(plugin, identifier, classLoader); method.setAccessible(false);
KingRainbow44's avatar
KingRainbow44 committed
111
112
113
        } catch (Exception ignored) {
            Grasscutter.getLogger().warn("Failed to add plugin identifier: " + identifier.name);
        }
KingRainbow44's avatar
KingRainbow44 committed
114
115
        
        // Add the plugin to the list of loaded plugins.
KingRainbow44's avatar
KingRainbow44 committed
116
        this.plugins.put(identifier.name, plugin);
KingRainbow44's avatar
KingRainbow44 committed
117
118
119
120
121
122
123
124
        // Call the plugin's onLoad method.
        plugin.onLoad();
    }

    /**
     * Enables all registered plugins.
     */
    public void enablePlugins() {
KingRainbow44's avatar
KingRainbow44 committed
125
126
127
128
        this.plugins.forEach((name, plugin) -> {
            Grasscutter.getLogger().info("Enabling plugin: " + name);
            plugin.onEnable();
        });
KingRainbow44's avatar
KingRainbow44 committed
129
130
131
132
133
134
    }
    
    /**
     * Disables all registered plugins.
     */
    public void disablePlugins() {
KingRainbow44's avatar
KingRainbow44 committed
135
136
137
138
        this.plugins.forEach((name, plugin) -> {
            Grasscutter.getLogger().info("Disabling plugin: " + name);
            plugin.onDisable();
        });
KingRainbow44's avatar
KingRainbow44 committed
139
    }
KingRainbow44's avatar
KingRainbow44 committed
140
141
142
143
144

    /**
     * Registers a plugin's event listener.
     * @param listener The event listener.
     */
KingRainbow44's avatar
KingRainbow44 committed
145
    public void registerListener(EventHandler<? extends Event> listener) {
146
        this.listeners.add(listener);
KingRainbow44's avatar
KingRainbow44 committed
147
148
149
150
151
152
153
    }
    
    /**
     * Invoke the provided event on all registered event listeners.
     * @param event The event to invoke.
     */
    public void invokeEvent(Event event) {
KingRainbow44's avatar
KingRainbow44 committed
154
155
156
157
158
159
160
161
162
163
164
165
166
        EnumSet.allOf(HandlerPriority.class)
                .forEach(priority -> this.checkAndFilter(event, priority));
    }

    /**
     * Check an event to handlers for the priority.
     * @param event The event being called.
     * @param priority The priority to call for.
     */
    private void checkAndFilter(Event event, HandlerPriority priority) {
        this.listeners.stream()
                .filter(handler -> handler.handles().isInstance(event))
                .filter(handler -> handler.getPriority() == priority)
167
                .toList().forEach(handler -> this.invokeHandler(event, handler));
KingRainbow44's avatar
KingRainbow44 committed
168
    }
169

170
171
172
173
    public Plugin getPlugin(String name) {
        return this.plugins.get(name);
    }

KingRainbow44's avatar
KingRainbow44 committed
174
    /**
175
176
177
     * Performs logic checks then invokes the provided event handler.
     * @param event The event passed through to the handler.
     * @param handler The handler to invoke.
KingRainbow44's avatar
KingRainbow44 committed
178
     */
KingRainbow44's avatar
KingRainbow44 committed
179
180
    @SuppressWarnings("unchecked")
    private <T extends Event> void invokeHandler(Event event, EventHandler<T> handler) {
181
182
        if(!event.isCanceled() ||
                (event.isCanceled() && handler.ignoresCanceled())
KingRainbow44's avatar
KingRainbow44 committed
183
        ) handler.getCallback().consume((T) event);
KingRainbow44's avatar
KingRainbow44 committed
184
    }
Magix's avatar
Magix committed
185
}