PluginManager.java 6.29 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
6
import emu.grasscutter.server.event.Event;
import emu.grasscutter.server.event.EventHandler;
import emu.grasscutter.server.event.Listener;
KingRainbow44's avatar
KingRainbow44 committed
7
import emu.grasscutter.utils.Utils;
KingRainbow44's avatar
KingRainbow44 committed
8
import org.reflections.Reflections;
KingRainbow44's avatar
KingRainbow44 committed
9
10
11

import java.io.File;
import java.io.InputStreamReader;
KingRainbow44's avatar
KingRainbow44 committed
12
import java.lang.reflect.Method;
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
 * 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 Map<Plugin, List<Listener>> listeners = new HashMap<>();
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();
KingRainbow44's avatar
KingRainbow44 committed
50
51
52
53
54
55
56
        
        plugins.forEach(plugin -> {
            try {
                URL url = plugin.toURI().toURL();
                try (URLClassLoader loader = new URLClassLoader(new URL[]{url})) {
                    URL configFile = loader.findResource("plugin.json");
                    InputStreamReader fileReader = new InputStreamReader(configFile.openStream());
muhammadeko's avatar
muhammadeko committed
57

KingRainbow44's avatar
KingRainbow44 committed
58
59
60
61
62
63
                    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
64
65
66
67
68

                    JarFile jarFile = new JarFile(plugin);
                    Enumeration<JarEntry> entries = jarFile.entries();
                    while(entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
muhammadeko's avatar
muhammadeko committed
69
                        if(entry.isDirectory() || !entry.getName().endsWith(".class") || entry.getName().contains("module-info")) continue;
muhammadeko's avatar
muhammadeko committed
70
71
72
                        String className = entry.getName().replace(".class", "").replace("/", ".");
                        Class<?> clazz = loader.loadClass(className);
                    }
KingRainbow44's avatar
KingRainbow44 committed
73
74
                    
                    Class<?> pluginClass = loader.loadClass(pluginConfig.mainClass);
KingRainbow44's avatar
KingRainbow44 committed
75
76
                    Plugin pluginInstance = (Plugin) pluginClass.getDeclaredConstructor().newInstance();
                    this.loadPlugin(pluginInstance, PluginIdentifier.fromPluginConfig(pluginConfig));
KingRainbow44's avatar
KingRainbow44 committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
                    
                    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.
     */
KingRainbow44's avatar
KingRainbow44 committed
92
93
94
95
96
97
98
99
100
101
102
    private void loadPlugin(Plugin plugin, PluginIdentifier identifier) {
        Grasscutter.getLogger().info("Loading plugin: " + identifier.name);
        
        // Add the plugin's identifier.
        try {
            Class<Plugin> pluginClass = Plugin.class;
            Method method = pluginClass.getDeclaredMethod("initializePlugin", PluginIdentifier.class);
            method.setAccessible(true); method.invoke(plugin, identifier); method.setAccessible(false);
        } catch (Exception ignored) {
            Grasscutter.getLogger().warn("Failed to add plugin identifier: " + identifier.name);
        }
KingRainbow44's avatar
KingRainbow44 committed
103
104
        
        // Add the plugin to the list of loaded plugins.
KingRainbow44's avatar
KingRainbow44 committed
105
        this.plugins.put(identifier.name, plugin);
KingRainbow44's avatar
KingRainbow44 committed
106
107
108
109
110
111
112
113
        // Call the plugin's onLoad method.
        plugin.onLoad();
    }

    /**
     * Enables all registered plugins.
     */
    public void enablePlugins() {
KingRainbow44's avatar
KingRainbow44 committed
114
115
116
117
        this.plugins.forEach((name, plugin) -> {
            Grasscutter.getLogger().info("Enabling plugin: " + name);
            plugin.onEnable();
        });
KingRainbow44's avatar
KingRainbow44 committed
118
119
120
121
122
123
    }
    
    /**
     * Disables all registered plugins.
     */
    public void disablePlugins() {
KingRainbow44's avatar
KingRainbow44 committed
124
125
126
127
        this.plugins.forEach((name, plugin) -> {
            Grasscutter.getLogger().info("Disabling plugin: " + name);
            plugin.onDisable();
        });
KingRainbow44's avatar
KingRainbow44 committed
128
    }
KingRainbow44's avatar
KingRainbow44 committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

    /**
     * Registers a plugin's event listener.
     * @param plugin The plugin instance.
     * @param listener The event listener.
     */
    public void registerListener(Plugin plugin, Listener listener) {
        this.listeners.computeIfAbsent(plugin, k -> new ArrayList<>()).add(listener);
    }
    
    /**
     * Invoke the provided event on all registered event listeners.
     * @param event The event to invoke.
     */
    public void invokeEvent(Event event) {
        this.listeners.values().stream()
                .flatMap(Collection::stream)
                .forEach(listener -> this.invokeOnListener(listener, event));
    }
    
    /**
     * Attempts to invoke the event on the provided listener.
     */
    private void invokeOnListener(Listener listener, Event event) {
        try {
            Class<?> listenerClass = listener.getClass();
            Method[] methods = listenerClass.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(EventHandler.class)) return;
                if(!method.getParameterTypes()[0].isAssignableFrom(event.getClass())) return;
                method.invoke(listener, event);
            }
        } catch (Exception ignored) { }
    }
KingRainbow44's avatar
KingRainbow44 committed
163
}