Grasscutter.java 12.7 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter;

3
4
5
import ch.qos.logback.classic.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
6
7
import emu.grasscutter.auth.AuthenticationSystem;
import emu.grasscutter.auth.DefaultAuthentication;
Jaida Wu's avatar
Jaida Wu committed
8
import emu.grasscutter.command.CommandMap;
4Benj_'s avatar
4Benj_ committed
9
10
import emu.grasscutter.command.DefaultPermissionHandler;
import emu.grasscutter.command.PermissionHandler;
GanyusLeftHorn's avatar
GanyusLeftHorn committed
11
import emu.grasscutter.game.dungeons.challenge.DungeonChallenge;
12
13
import emu.grasscutter.data.ResourceLoader;
import emu.grasscutter.database.DatabaseManager;
Melledy's avatar
Melledy committed
14
15
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
KingRainbow44's avatar
KingRainbow44 committed
16
import emu.grasscutter.plugin.PluginManager;
KingRainbow44's avatar
KingRainbow44 committed
17
import emu.grasscutter.plugin.api.ServerHook;
18
import emu.grasscutter.scripts.ScriptLoader;
19
import emu.grasscutter.server.game.GameServer;
20
21
22
import emu.grasscutter.server.http.HttpServer;
import emu.grasscutter.server.http.dispatch.DispatchHandler;
import emu.grasscutter.server.http.dispatch.RegionHandler;
2bllw8's avatar
2bllw8 committed
23
import emu.grasscutter.server.http.documentation.DocumentationServerHandler;
24
25
26
27
28
import emu.grasscutter.server.http.handlers.AnnouncementsHandler;
import emu.grasscutter.server.http.handlers.GachaHandler;
import emu.grasscutter.server.http.handlers.GenericHandler;
import emu.grasscutter.server.http.handlers.LogHandler;
import emu.grasscutter.tools.Tools;
29
import emu.grasscutter.utils.ConfigContainer;
30
31
import emu.grasscutter.utils.Crypto;
import emu.grasscutter.utils.Language;
KingRainbow44's avatar
KingRainbow44 committed
32
import emu.grasscutter.utils.Utils;
33
34
35
36
37
38
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
Melledy's avatar
Melledy committed
39
import org.reflections.Reflections;
Melledy's avatar
Melledy committed
40
41
import org.slf4j.LoggerFactory;

42
import javax.annotation.Nullable;
43
44
import java.io.*;
import java.util.Calendar;
45

46
47
import static emu.grasscutter.Configuration.DATA;
import static emu.grasscutter.Configuration.SERVER;
48
49
import static emu.grasscutter.utils.Language.translate;

KingRainbow44's avatar
KingRainbow44 committed
50
public final class Grasscutter {
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    private static final Logger log = (Logger) LoggerFactory.getLogger(Grasscutter.class);
    private static LineReader consoleLineReader = null;

    private static Language language;

    private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    public static final File configFile = new File("./config.json");

    private static int day; // Current day of week.

    private static HttpServer httpServer;
    private static GameServer gameServer;
    private static PluginManager pluginManager;
    private static AuthenticationSystem authenticationSystem;
    private static PermissionHandler permissionHandler;

    public static final Reflections reflector = new Reflections("emu.grasscutter");
    public static ConfigContainer config;

    static {
        // Declare logback configuration.
        System.setProperty("logback.configurationFile", "src/main/resources/logback.xml");

        // Load server configuration.
        Grasscutter.loadConfig();
        // Attempt to update configuration.
        ConfigContainer.updateConfig();

        // Load translation files.
        Grasscutter.loadLanguage();

        // Check server structure.
        Utils.startupCheck();
    }

    public static void main(String[] args) throws Exception {
        Crypto.loadKeys(); // Load keys from buffers.

        // Parse arguments.
        boolean exitEarly = false;
        for (String arg : args) {
            switch (arg.toLowerCase()) {
                case "-handbook" -> {
                    Tools.createGmHandbook();
                    exitEarly = true;
                }
                case "-gachamap" -> {
                    Tools.createGachaMapping(DATA("gacha_mappings.js"));
                    exitEarly = true;
                }
                case "-version" -> {
                    System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH);
                    exitEarly = true;
                }
            }
        }

        // Exit early if argument sets it.
        if (exitEarly) System.exit(0);

        // Initialize server.
        Grasscutter.getLogger().info(translate("messages.status.starting"));
        Grasscutter.getLogger().info(translate("messages.status.game_version", GameConstants.VERSION));
        Grasscutter.getLogger().info(translate("messages.status.version", BuildConfig.VERSION, BuildConfig.GIT_HASH));

        // Load all resources.
        Grasscutter.updateDayOfWeek();
        ResourceLoader.loadAll();
        ScriptLoader.init();

        // Initialize database.
        DatabaseManager.initialize();

        // Initialize the default systems.
        authenticationSystem = new DefaultAuthentication();
        permissionHandler = new DefaultPermissionHandler();

        // Create server instances.
        httpServer = new HttpServer();
        gameServer = new GameServer();
        // Create a server hook instance with both servers.
        new ServerHook(gameServer, httpServer);

        // Create plugin manager instance.
        pluginManager = new PluginManager();
        // Add HTTP routes after loading plugins.
        httpServer.addRouter(HttpServer.UnhandledRequestRouter.class);
        httpServer.addRouter(HttpServer.DefaultRequestRouter.class);
        httpServer.addRouter(RegionHandler.class);
        httpServer.addRouter(LogHandler.class);
        httpServer.addRouter(GenericHandler.class);
        httpServer.addRouter(AnnouncementsHandler.class);
        httpServer.addRouter(DispatchHandler.class);
        httpServer.addRouter(GachaHandler.class);
        httpServer.addRouter(DocumentationServerHandler.class);

        // Start servers.
        var runMode = SERVER.runMode;
        if (runMode == ServerRunMode.HYBRID) {
            httpServer.start();
            gameServer.start();
        } else if (runMode == ServerRunMode.DISPATCH_ONLY) {
            httpServer.start();
        } else if (runMode == ServerRunMode.GAME_ONLY) {
            gameServer.start();
        } else {
            getLogger().error(translate("messages.status.run_mode_error", runMode));
            getLogger().error(translate("messages.status.run_mode_help"));
            getLogger().error(translate("messages.status.shutdown"));
            System.exit(1);
        }

        // Enable all plugins.
        pluginManager.enablePlugins();

        // Hook into shutdown event.
        Runtime.getRuntime().addShutdownHook(new Thread(Grasscutter::onShutdown));

        // Open console.
        startConsole();
    }

    /**
     * Server shutdown event.
     */
    private static void onShutdown() {
        // Disable all plugins.
        if(pluginManager != null)
            pluginManager.disablePlugins();
    }

    /*
     * Methods for the language system component.
     */

    public static void loadLanguage() {
        var locale = config.language.language;
        language = Language.getLanguage(Utils.getLanguageCode(locale));
    }

    /*
     * Methods for the configuration system component.
     */

    /**
     * Attempts to load the configuration from a file.
     */
    public static void loadConfig() {
        // Check if config.json exists. If not, we generate a new config.
        if (!configFile.exists()) {
            getLogger().info("config.json could not be found. Generating a default configuration ...");
            config = new ConfigContainer();
            Grasscutter.saveConfig(config);
            return;
        }

        // If the file already exists, we attempt to load it.
        try (FileReader file = new FileReader(configFile)) {
            config = gson.fromJson(file, ConfigContainer.class);
        } catch (Exception exception) {
            getLogger().error("There was an error while trying to load the configuration from config.json. Please make sure that there are no syntax errors. If you want to start with a default configuration, delete your existing config.json.");
            System.exit(1);
        }
    }

    /**
     * Saves the provided server configuration.
     *
     * @param config The configuration to save, or null for a new one.
     */
    public static void saveConfig(@Nullable ConfigContainer config) {
        if (config == null) config = new ConfigContainer();

        try (FileWriter file = new FileWriter(configFile)) {
            file.write(gson.toJson(config));
        } catch (IOException ignored) {
            Grasscutter.getLogger().error("Unable to write to config file.");
        } catch (Exception e) {
            Grasscutter.getLogger().error("Unable to save config file.", e);
        }
    }

    /*
     * Getters for the various server components.
     */

    public static ConfigContainer getConfig() {
        return config;
    }

    public static Language getLanguage() {
        return language;
    }

    public static void setLanguage(Language language) {
Secretboy's avatar
Secretboy committed
246
        Grasscutter.language = language;
247
    }
Secretboy's avatar
Secretboy committed
248

249
    public static Language getLanguage(String langCode) {
Secretboy's avatar
Secretboy committed
250
        return Language.getLanguage(langCode);
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    }

    public static Logger getLogger() {
        return log;
    }

    public static LineReader getConsole() {
        if (consoleLineReader == null) {
            Terminal terminal = null;
            try {
                terminal = TerminalBuilder.builder().jna(true).build();
            } catch (Exception e) {
                try {
                    // Fallback to a dumb jline terminal.
                    terminal = TerminalBuilder.builder().dumb(true).build();
                } catch (Exception ignored) {
                    // When dumb is true, build() never throws.
                }
            }
            consoleLineReader = LineReaderBuilder.builder()
                .terminal(terminal)
                .build();
        }
        return consoleLineReader;
    }

    public static Gson getGsonFactory() {
        return gson;
    }

    public static HttpServer getHttpServer() {
        return httpServer;
    }

    public static GameServer getGameServer() {
        return gameServer;
    }

    public static PluginManager getPluginManager() {
        return pluginManager;
    }

    public static AuthenticationSystem getAuthenticationSystem() {
        return authenticationSystem;
    }

    public static PermissionHandler getPermissionHandler() {
        return permissionHandler;
    }

    public static int getCurrentDayOfWeek() {
        return day;
    }

    /*
     * Utility methods.
     */

    public static void updateDayOfWeek() {
        Calendar calendar = Calendar.getInstance();
        day = calendar.get(Calendar.DAY_OF_WEEK);
    }

    public static void startConsole() {
        // Console should not start in dispatch only mode.
        if (SERVER.runMode == ServerRunMode.DISPATCH_ONLY) {
            getLogger().info(translate("messages.dispatch.no_commands_error"));
            return;
        }

        getLogger().info(translate("messages.status.done"));
        String input = null;
        boolean isLastInterrupted = false;
        while (config.server.game.enableConsole) {
            try {
                input = consoleLineReader.readLine("> ");
            } catch (UserInterruptException e) {
                if (!isLastInterrupted) {
                    isLastInterrupted = true;
                    Grasscutter.getLogger().info("Press Ctrl-C again to shutdown.");
                    continue;
                } else {
                    Runtime.getRuntime().exit(0);
                }
            } catch (EndOfFileException e) {
                Grasscutter.getLogger().info("EOF detected.");
                continue;
            } catch (IOError e) {
                Grasscutter.getLogger().error("An IO error occurred.", e);
                continue;
            }

            isLastInterrupted = false;
            try {
                CommandMap.getInstance().invoke(null, null, input);
            } catch (Exception e) {
                Grasscutter.getLogger().error(translate("messages.game.command_error"), e);
            }
        }
    }

    /**
     * Sets the authentication system for the server.
     *
     * @param authenticationSystem The authentication system to use.
     */
    public static void setAuthenticationSystem(AuthenticationSystem authenticationSystem) {
        Grasscutter.authenticationSystem = authenticationSystem;
    }

    /**
     * Sets the permission handler for the server.
     *
     * @param permissionHandler The permission handler to use.
     */
    public static void setPermissionHandler(PermissionHandler permissionHandler) {
        Grasscutter.permissionHandler = permissionHandler;
    }

    /*
     * Enums for the configuration.
     */

    public enum ServerRunMode {
        HYBRID, DISPATCH_ONLY, GAME_ONLY
    }

    public enum ServerDebugMode {
        ALL, MISSING, NONE
    }
Melledy's avatar
Melledy committed
381
}