PluginManager.java 7.17 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
20
import static emu.grasscutter.Configuration.*;

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

    /**
     * Loads plugins from the config-specified directory.
     */
    private void loadPlugins() {
36
        File pluginsDir = new File(Utils.toFilePath(PLUGINS_FOLDER));
KingRainbow44's avatar
KingRainbow44 committed
37
38
39
40
41
42
43
44
45
46
47
48
49
        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
50
                .toList();
51
52
53
54
55

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

        URLClassLoader classLoader = new URLClassLoader(pluginNames);

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

KingRainbow44's avatar
KingRainbow44 committed
70
71
72
73
74
75
                    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
76
77
78
79
80

                    JarFile jarFile = new JarFile(plugin);
                    Enumeration<JarEntry> entries = jarFile.entries();
                    while(entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
muhammadeko's avatar
muhammadeko committed
81
                        if(entry.isDirectory() || !entry.getName().endsWith(".class") || entry.getName().contains("module-info")) continue;
muhammadeko's avatar
muhammadeko committed
82
                        String className = entry.getName().replace(".class", "").replace("/", ".");
Magix's avatar
Magix committed
83
                        classLoader.loadClass(className); // Use the same class loader for ALL plugins.
muhammadeko's avatar
muhammadeko committed
84
                    }
KingRainbow44's avatar
KingRainbow44 committed
85
                    
86
                    Class<?> pluginClass = classLoader.loadClass(pluginConfig.mainClass);
KingRainbow44's avatar
KingRainbow44 committed
87
                    Plugin pluginInstance = (Plugin) pluginClass.getDeclaredConstructor().newInstance();
88
                    this.loadPlugin(pluginInstance, PluginIdentifier.fromPluginConfig(pluginConfig), loader);
KingRainbow44's avatar
KingRainbow44 committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
                    
                    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.
     */
104
    private void loadPlugin(Plugin plugin, PluginIdentifier identifier, URLClassLoader classLoader) {
KingRainbow44's avatar
KingRainbow44 committed
105
106
107
108
109
        Grasscutter.getLogger().info("Loading plugin: " + identifier.name);
        
        // Add the plugin's identifier.
        try {
            Class<Plugin> pluginClass = Plugin.class;
110
111
            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
112
113
114
        } catch (Exception ignored) {
            Grasscutter.getLogger().warn("Failed to add plugin identifier: " + identifier.name);
        }
KingRainbow44's avatar
KingRainbow44 committed
115
116
        
        // Add the plugin to the list of loaded plugins.
KingRainbow44's avatar
KingRainbow44 committed
117
        this.plugins.put(identifier.name, plugin);
KingRainbow44's avatar
KingRainbow44 committed
118
119
120
121
122
123
124
125
        // Call the plugin's onLoad method.
        plugin.onLoad();
    }

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

    /**
     * Registers a plugin's event listener.
     * @param listener The event listener.
     */
KingRainbow44's avatar
KingRainbow44 committed
146
    public void registerListener(EventHandler<? extends Event> listener) {
147
        this.listeners.add(listener);
KingRainbow44's avatar
KingRainbow44 committed
148
149
150
151
152
153
154
    }
    
    /**
     * 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
155
156
157
158
159
160
161
162
163
164
165
166
167
        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)
168
                .toList().forEach(handler -> this.invokeHandler(event, handler));
KingRainbow44's avatar
KingRainbow44 committed
169
    }
170

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

KingRainbow44's avatar
KingRainbow44 committed
175
    /**
176
177
178
     * 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
179
     */
KingRainbow44's avatar
KingRainbow44 committed
180
181
    @SuppressWarnings("unchecked")
    private <T extends Event> void invokeHandler(Event event, EventHandler<T> handler) {
182
183
        if(!event.isCanceled() ||
                (event.isCanceled() && handler.ignoresCanceled())
KingRainbow44's avatar
KingRainbow44 committed
184
        ) handler.getCallback().consume((T) event);
KingRainbow44's avatar
KingRainbow44 committed
185
    }
Magix's avatar
Magix committed
186
}