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

3
import java.io.*;
4
import java.util.Calendar;
Melledy's avatar
Melledy committed
5

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;
Melledy's avatar
Melledy committed
9
10
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
KingRainbow44's avatar
KingRainbow44 committed
11
import emu.grasscutter.plugin.PluginManager;
KingRainbow44's avatar
KingRainbow44 committed
12
import emu.grasscutter.plugin.api.ServerHook;
13
import emu.grasscutter.scripts.ScriptLoader;
14
15
import emu.grasscutter.server.http.HttpServer;
import emu.grasscutter.server.http.dispatch.DispatchHandler;
16
import emu.grasscutter.server.http.handlers.*;
17
import emu.grasscutter.server.http.dispatch.RegionHandler;
2bllw8's avatar
2bllw8 committed
18
import emu.grasscutter.server.http.documentation.DocumentationServerHandler;
19
import emu.grasscutter.utils.ConfigContainer;
KingRainbow44's avatar
KingRainbow44 committed
20
import emu.grasscutter.utils.Utils;
21
22
23
24
25
26
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
27
import org.reflections.Reflections;
Melledy's avatar
Melledy committed
28
29
30
31
32
33
34
35
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import ch.qos.logback.classic.Logger;
import emu.grasscutter.data.ResourceLoader;
import emu.grasscutter.database.DatabaseManager;
36
import emu.grasscutter.utils.Language;
Melledy's avatar
Melledy committed
37
38
39
40
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.Crypto;

41
42
import javax.annotation.Nullable;

43
import static emu.grasscutter.utils.Language.translate;
44
import static emu.grasscutter.Configuration.*;
45

KingRainbow44's avatar
KingRainbow44 committed
46
47
public final class Grasscutter {
	private static final Logger log = (Logger) LoggerFactory.getLogger(Grasscutter.class);
48
	private static LineReader consoleLineReader = null;
49
	
方块君's avatar
方块君 committed
50
	private static Language language;
51

KingRainbow44's avatar
KingRainbow44 committed
52
	private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
53
	public static final File configFile = new File("./config.json");
Secretboy's avatar
Secretboy committed
54

55
	private static int day; // Current day of week.
Secretboy's avatar
Secretboy committed
56

57
	private static HttpServer httpServer;
Melledy's avatar
Melledy committed
58
	private static GameServer gameServer;
KingRainbow44's avatar
KingRainbow44 committed
59
	private static PluginManager pluginManager;
60
	private static AuthenticationSystem authenticationSystem;
Secretboy's avatar
Secretboy committed
61

KingRainbow44's avatar
KingRainbow44 committed
62
	public static final Reflections reflector = new Reflections("emu.grasscutter");
63
	public static ConfigContainer config;
Magix's avatar
Magix committed
64
  
KingRainbow44's avatar
KingRainbow44 committed
65
	static {
Melledy's avatar
Melledy committed
66
67
		// Declare logback configuration.
		System.setProperty("logback.configurationFile", "src/main/resources/logback.xml");
Secretboy's avatar
Secretboy committed
68

Melledy's avatar
Melledy committed
69
		// Load server configuration.
70
		Grasscutter.loadConfig();
71
		// Attempt to update configuration.
72
		ConfigContainer.updateConfig();
方块君's avatar
方块君 committed
73

74
		// Load translation files.
方块君's avatar
方块君 committed
75
		Grasscutter.loadLanguage();
Secretboy's avatar
Secretboy committed
76

KingRainbow44's avatar
KingRainbow44 committed
77
78
79
		// Check server structure.
		Utils.startupCheck();
	}
Secretboy's avatar
Secretboy committed
80

81
82
83
  	public static void main(String[] args) throws Exception {
		Crypto.loadKeys(); // Load keys from buffers.
	
84
		// Parse arguments.
KingRainbow44's avatar
KingRainbow44 committed
85
		boolean exitEarly = false;
Melledy's avatar
Melledy committed
86
87
		for (String arg : args) {
			switch (arg.toLowerCase()) {
KingRainbow44's avatar
KingRainbow44 committed
88
				case "-handbook" -> {
KingRainbow44's avatar
KingRainbow44 committed
89
					Tools.createGmHandbook(); exitEarly = true;
KingRainbow44's avatar
KingRainbow44 committed
90
				}
91
				case "-gachamap" -> {
92
					Tools.createGachaMapping(DATA("gacha_mappings.js")); exitEarly = true;
93
				}
94
				case "-version" -> {
mingjun97's avatar
mingjun97 committed
95
					System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH); exitEarly = true;
96
				}
Melledy's avatar
Melledy committed
97
			}
KingRainbow44's avatar
KingRainbow44 committed
98
99
100
101
		} 
		
		// Exit early if argument sets it.
		if(exitEarly) System.exit(0);
102
	
KingRainbow44's avatar
KingRainbow44 committed
103
		// Initialize server.
104
		Grasscutter.getLogger().info(translate("messages.status.starting"));
105
106
		Grasscutter.getLogger().info(translate("messages.status.game_version", GameConstants.VERSION));
		Grasscutter.getLogger().info(translate("messages.status.version", BuildConfig.VERSION, BuildConfig.GIT_HASH));
107
	
KingRainbow44's avatar
KingRainbow44 committed
108
		// Load all resources.
109
		Grasscutter.updateDayOfWeek();
Melledy's avatar
Melledy committed
110
		ResourceLoader.loadAll();
111
		ScriptLoader.init();
112
		EnergyManager.initialize();
113
	
KingRainbow44's avatar
KingRainbow44 committed
114
		// Initialize database.
Melledy's avatar
Melledy committed
115
		DatabaseManager.initialize();
116
117
118
		
		// Initialize the default authentication system.
		authenticationSystem = new DefaultAuthentication();
119
	
KingRainbow44's avatar
KingRainbow44 committed
120
		// Create server instances.
121
		httpServer = new HttpServer();
122
		gameServer = new GameServer();
KingRainbow44's avatar
KingRainbow44 committed
123
		// Create a server hook instance with both servers.
124
		new ServerHook(gameServer, httpServer);
125
		
126
127
		// Create plugin manager instance.
		pluginManager = new PluginManager();
128
129
130
131
132
133
134
135
		// 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);
136
		httpServer.addRouter(GachaHandler.class);
2bllw8's avatar
2bllw8 committed
137
		httpServer.addRouter(DocumentationServerHandler.class);
138
		
gentlespoon's avatar
gentlespoon committed
139
140
		// TODO: find a better place?
		StaminaManager.initialize();
141
	
KingRainbow44's avatar
KingRainbow44 committed
142
		// Start servers.
143
144
		var runMode = SERVER.runMode;
		if (runMode == ServerRunMode.HYBRID) {
145
			httpServer.start();
146
			gameServer.start();
147
		} else if (runMode == ServerRunMode.DISPATCH_ONLY) {
148
			httpServer.start();
149
		} else if (runMode == ServerRunMode.GAME_ONLY) {
150
151
			gameServer.start();
		} else {
152
			getLogger().error(translate("messages.status.run_mode_error", runMode));
153
154
			getLogger().error(translate("messages.status.run_mode_help"));
			getLogger().error(translate("messages.status.shutdown"));
155
156
			System.exit(1);
		}
157
	
KingRainbow44's avatar
KingRainbow44 committed
158
159
		// Enable all plugins.
		pluginManager.enablePlugins();
160
	
KingRainbow44's avatar
KingRainbow44 committed
161
162
		// Hook into shutdown event.
		Runtime.getRuntime().addShutdownHook(new Thread(Grasscutter::onShutdown));
163
	
164
165
		// Open console.
		startConsole();
166
 	}
KingRainbow44's avatar
KingRainbow44 committed
167
168
169
170
171
172
173
174

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

176
177
178
179
180
181
182
183
184
185
186
187
188
	/*
	 * 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.
	 */

189
190
191
	/**
	 * Attempts to load the configuration from a file.
	 */
192
	public static void loadConfig() {
193
194
195
196
197
198
199
200
201
		// 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.
Melledy's avatar
Melledy committed
202
		try (FileReader file = new FileReader(configFile)) {
203
204
			config = gson.fromJson(file, ConfigContainer.class);
		} catch (Exception exception) {
205
206
207
			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);
		} 
Melledy's avatar
Melledy committed
208
	}
方块君's avatar
方块君 committed
209

210
211
212
213
	/**
	 * Saves the provided server configuration.
	 * @param config The configuration to save, or null for a new one.
	 */
214
215
	public static void saveConfig(@Nullable ConfigContainer config) {
		if(config == null) config = new ConfigContainer();
216
		
Melledy's avatar
Melledy committed
217
218
		try (FileWriter file = new FileWriter(configFile)) {
			file.write(gson.toJson(config));
219
220
		} catch (IOException ignored) {
			Grasscutter.getLogger().error("Unable to write to config file.");
Melledy's avatar
Melledy committed
221
		} catch (Exception e) {
222
			Grasscutter.getLogger().error("Unable to save config file.", e);
Melledy's avatar
Melledy committed
223
224
		}
	}
Secretboy's avatar
Secretboy committed
225

226
227
228
229
	/*
	 * Getters for the various server components.
	 */
	
230
	public static ConfigContainer getConfig() {
KingRainbow44's avatar
KingRainbow44 committed
231
232
233
		return config;
	}

方块君's avatar
方块君 committed
234
235
236
237
	public static Language getLanguage() {
		return language;
	}

Secretboy's avatar
Secretboy committed
238
239
240
241
242
243
244
245
	public static void setLanguage(Language language) {
        Grasscutter.language = language;
	}

	public static Language getLanguage(String langCode) {
        return Language.getLanguage(langCode);
	}

KingRainbow44's avatar
KingRainbow44 committed
246
247
248
249
	public static Logger getLogger() {
		return log;
	}

250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
	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;
	}

KingRainbow44's avatar
KingRainbow44 committed
270
271
272
273
	public static Gson getGsonFactory() {
		return gson;
	}

274
275
	public static HttpServer getHttpServer() {
		return httpServer;
KingRainbow44's avatar
KingRainbow44 committed
276
277
278
279
280
	}

	public static GameServer getGameServer() {
		return gameServer;
	}
Secretboy's avatar
Secretboy committed
281

KingRainbow44's avatar
KingRainbow44 committed
282
283
284
	public static PluginManager getPluginManager() {
		return pluginManager;
	}
285
286
287
288
	
	public static AuthenticationSystem getAuthenticationSystem() {
		return authenticationSystem;
	}
Secretboy's avatar
Secretboy committed
289

290
291
292
293
294
295
296
297
	public static int getCurrentDayOfWeek() {
		return day;
	}
	
	/*
	 * Utility methods.
	 */
	
298
299
300
301
302
	public static void updateDayOfWeek() {
		Calendar calendar = Calendar.getInstance();
		day = calendar.get(Calendar.DAY_OF_WEEK); 
	}

303
304
305
306
307
308
309
310
311
312
	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;
313
		while (config.server.game.enableConsole) {
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
			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);
			}
		}
339
	}
Secretboy's avatar
Secretboy committed
340

341
342
343
344
345
346
347
348
349
350
351
352
	/**
	 * Sets the authentication system for the server.
	 * @param authenticationSystem The authentication system to use.
	 */
	public static void setAuthenticationSystem(AuthenticationSystem authenticationSystem) {
		Grasscutter.authenticationSystem = authenticationSystem;
	}

	/*
	 * Enums for the configuration.
	 */
	
353
354
355
	public enum ServerRunMode {
		HYBRID, DISPATCH_ONLY, GAME_ONLY
	}
Secretboy's avatar
Secretboy committed
356

357
358
359
	public enum ServerDebugMode {
		ALL, MISSING, NONE
	}
Melledy's avatar
Melledy committed
360
}