PluginManager.java 5.68 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.*;
KingRainbow44's avatar
KingRainbow44 committed
16
17
18
19
20
21

/**
 * Manages the server's plugins & the event system.
 */
public final class PluginManager {
    private final Map<String, Plugin> plugins = new HashMap<>();
KingRainbow44's avatar
KingRainbow44 committed
22
    private final Map<Plugin, List<Listener>> listeners = new HashMap<>();
KingRainbow44's avatar
KingRainbow44 committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    
    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
47
                .toList();
KingRainbow44's avatar
KingRainbow44 committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
        
        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());
                    
                    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;
                    }
                    
                    Class<?> pluginClass = loader.loadClass(pluginConfig.mainClass);
KingRainbow44's avatar
KingRainbow44 committed
64
65
                    Plugin pluginInstance = (Plugin) pluginClass.getDeclaredConstructor().newInstance();
                    this.loadPlugin(pluginInstance, PluginIdentifier.fromPluginConfig(pluginConfig));
KingRainbow44's avatar
KingRainbow44 committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
                    
                    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
81
82
83
84
85
86
87
88
89
90
91
    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
92
93
        
        // Add the plugin to the list of loaded plugins.
KingRainbow44's avatar
KingRainbow44 committed
94
        this.plugins.put(identifier.name, plugin);
KingRainbow44's avatar
KingRainbow44 committed
95
96
97
98
99
100
101
102
        // Call the plugin's onLoad method.
        plugin.onLoad();
    }

    /**
     * Enables all registered plugins.
     */
    public void enablePlugins() {
KingRainbow44's avatar
KingRainbow44 committed
103
104
105
106
        this.plugins.forEach((name, plugin) -> {
            Grasscutter.getLogger().info("Enabling plugin: " + name);
            plugin.onEnable();
        });
KingRainbow44's avatar
KingRainbow44 committed
107
108
109
110
111
112
    }
    
    /**
     * Disables all registered plugins.
     */
    public void disablePlugins() {
KingRainbow44's avatar
KingRainbow44 committed
113
114
115
116
        this.plugins.forEach((name, plugin) -> {
            Grasscutter.getLogger().info("Disabling plugin: " + name);
            plugin.onDisable();
        });
KingRainbow44's avatar
KingRainbow44 committed
117
    }
KingRainbow44's avatar
KingRainbow44 committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

    /**
     * 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
152
}