Grasscutter.java 10.8 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;
4Benj_'s avatar
4Benj_ committed
9
10
import emu.grasscutter.command.DefaultPermissionHandler;
import emu.grasscutter.command.PermissionHandler;
Melledy's avatar
Melledy committed
11
12
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.stamina.StaminaManager;
KingRainbow44's avatar
KingRainbow44 committed
13
import emu.grasscutter.plugin.PluginManager;
KingRainbow44's avatar
KingRainbow44 committed
14
import emu.grasscutter.plugin.api.ServerHook;
15
import emu.grasscutter.scripts.ScriptLoader;
16
17
import emu.grasscutter.server.http.HttpServer;
import emu.grasscutter.server.http.dispatch.DispatchHandler;
18
import emu.grasscutter.server.http.handlers.*;
19
import emu.grasscutter.server.http.dispatch.RegionHandler;
2bllw8's avatar
2bllw8 committed
20
import emu.grasscutter.server.http.documentation.DocumentationServerHandler;
21
import emu.grasscutter.utils.ConfigContainer;
KingRainbow44's avatar
KingRainbow44 committed
22
import emu.grasscutter.utils.Utils;
23
24
25
26
27
28
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
29
import org.reflections.Reflections;
Melledy's avatar
Melledy committed
30
31
32
33
34
35
36
37
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;
38
import emu.grasscutter.utils.Language;
Melledy's avatar
Melledy committed
39
40
41
42
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.Crypto;

43
44
import javax.annotation.Nullable;

45
import static emu.grasscutter.utils.Language.translate;
46
import static emu.grasscutter.Configuration.*;
47

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

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

57
	private static int day; // Current day of week.
Secretboy's avatar
Secretboy committed
58

59
	private static HttpServer httpServer;
Melledy's avatar
Melledy committed
60
	private static GameServer gameServer;
KingRainbow44's avatar
KingRainbow44 committed
61
	private static PluginManager pluginManager;
62
	private static AuthenticationSystem authenticationSystem;
4Benj_'s avatar
4Benj_ committed
63
	private static PermissionHandler permissionHandler;
Secretboy's avatar
Secretboy committed
64

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

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

77
		// Load translation files.
方块君's avatar
方块君 committed
78
		Grasscutter.loadLanguage();
Secretboy's avatar
Secretboy committed
79

KingRainbow44's avatar
KingRainbow44 committed
80
81
82
		// Check server structure.
		Utils.startupCheck();
	}
Secretboy's avatar
Secretboy committed
83

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

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

180
181
182
183
184
185
186
187
188
189
190
191
192
	/*
	 * 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.
	 */

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

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

230
231
232
233
	/*
	 * Getters for the various server components.
	 */
	
234
	public static ConfigContainer getConfig() {
KingRainbow44's avatar
KingRainbow44 committed
235
236
237
		return config;
	}

方块君's avatar
方块君 committed
238
239
240
241
	public static Language getLanguage() {
		return language;
	}

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

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

KingRainbow44's avatar
KingRainbow44 committed
250
251
252
253
	public static Logger getLogger() {
		return log;
	}

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
	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
274
275
276
277
	public static Gson getGsonFactory() {
		return gson;
	}

278
279
	public static HttpServer getHttpServer() {
		return httpServer;
KingRainbow44's avatar
KingRainbow44 committed
280
281
282
283
284
	}

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

KingRainbow44's avatar
KingRainbow44 committed
286
287
288
	public static PluginManager getPluginManager() {
		return pluginManager;
	}
289
290
291
292
	
	public static AuthenticationSystem getAuthenticationSystem() {
		return authenticationSystem;
	}
Secretboy's avatar
Secretboy committed
293

4Benj_'s avatar
4Benj_ committed
294
295
296
297
	public static PermissionHandler getPermissionHandler() {
		return permissionHandler;
	}

298
299
300
301
302
303
304
305
	public static int getCurrentDayOfWeek() {
		return day;
	}
	
	/*
	 * Utility methods.
	 */
	
306
307
308
309
310
	public static void updateDayOfWeek() {
		Calendar calendar = Calendar.getInstance();
		day = calendar.get(Calendar.DAY_OF_WEEK); 
	}

311
312
313
314
315
316
317
318
319
320
	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;
321
		while (config.server.game.enableConsole) {
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
			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);
			}
		}
347
	}
Secretboy's avatar
Secretboy committed
348

349
350
351
352
353
354
355
356
	/**
	 * Sets the authentication system for the server.
	 * @param authenticationSystem The authentication system to use.
	 */
	public static void setAuthenticationSystem(AuthenticationSystem authenticationSystem) {
		Grasscutter.authenticationSystem = authenticationSystem;
	}

4Benj_'s avatar
4Benj_ committed
357
358
359
360
361
362
363
364
	/**
	 * Sets the permission handler for the server.
	 * @param permissionHandler The permission handler to use.
	 */
	public static void setPermissionHandler(PermissionHandler permissionHandler) {
		Grasscutter.permissionHandler = permissionHandler;
	}

365
366
367
368
	/*
	 * Enums for the configuration.
	 */
	
369
370
371
	public enum ServerRunMode {
		HYBRID, DISPATCH_ONLY, GAME_ONLY
	}
Secretboy's avatar
Secretboy committed
372

373
374
375
	public enum ServerDebugMode {
		ALL, MISSING, NONE
	}
Melledy's avatar
Melledy committed
376
}