Grasscutter.java 8.06 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

Jaida Wu's avatar
Jaida Wu committed
6
import emu.grasscutter.command.CommandMap;
KingRainbow44's avatar
KingRainbow44 committed
7
import emu.grasscutter.plugin.PluginManager;
KingRainbow44's avatar
KingRainbow44 committed
8
import emu.grasscutter.plugin.api.ServerHook;
9
import emu.grasscutter.scripts.ScriptLoader;
10
import emu.grasscutter.utils.ConfigContainer;
KingRainbow44's avatar
KingRainbow44 committed
11
import emu.grasscutter.utils.Utils;
12
13
14
15
16
17
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
18
import org.reflections.Reflections;
Melledy's avatar
Melledy committed
19
20
21
22
23
24
25
26
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;
27
import emu.grasscutter.utils.Language;
Melledy's avatar
Melledy committed
28
29
30
31
import emu.grasscutter.server.dispatch.DispatchServer;
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.Crypto;
32
import emu.grasscutter.BuildConfig;
Melledy's avatar
Melledy committed
33

34
35
import javax.annotation.Nullable;

36
import static emu.grasscutter.utils.Language.translate;
37
import static emu.grasscutter.Configuration.*;
38

KingRainbow44's avatar
KingRainbow44 committed
39
40
public final class Grasscutter {
	private static final Logger log = (Logger) LoggerFactory.getLogger(Grasscutter.class);
41
	private static LineReader consoleLineReader = null;
42
	
方块君's avatar
方块君 committed
43
	private static Language language;
44

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

48
	private static int day; // Current day of week.
Secretboy's avatar
Secretboy committed
49

Melledy's avatar
Melledy committed
50
51
	private static DispatchServer dispatchServer;
	private static GameServer gameServer;
KingRainbow44's avatar
KingRainbow44 committed
52
	private static PluginManager pluginManager;
Secretboy's avatar
Secretboy committed
53

KingRainbow44's avatar
KingRainbow44 committed
54
	public static final Reflections reflector = new Reflections("emu.grasscutter");
55
	public static ConfigContainer config;
Magix's avatar
Magix committed
56
  
KingRainbow44's avatar
KingRainbow44 committed
57
	static {
Melledy's avatar
Melledy committed
58
59
		// Declare logback configuration.
		System.setProperty("logback.configurationFile", "src/main/resources/logback.xml");
Secretboy's avatar
Secretboy committed
60

Melledy's avatar
Melledy committed
61
		// Load server configuration.
62
		Grasscutter.loadConfig();
63
		// Attempt to update configuration.
64
		ConfigContainer.updateConfig();
方块君's avatar
方块君 committed
65

66
		// Load translation files.
方块君's avatar
方块君 committed
67
		Grasscutter.loadLanguage();
Secretboy's avatar
Secretboy committed
68

KingRainbow44's avatar
KingRainbow44 committed
69
70
71
		// Check server structure.
		Utils.startupCheck();
	}
Secretboy's avatar
Secretboy committed
72

73
74
75
  	public static void main(String[] args) throws Exception {
		Crypto.loadKeys(); // Load keys from buffers.
	
76
		// Parse arguments.
KingRainbow44's avatar
KingRainbow44 committed
77
		boolean exitEarly = false;
Melledy's avatar
Melledy committed
78
79
		for (String arg : args) {
			switch (arg.toLowerCase()) {
KingRainbow44's avatar
KingRainbow44 committed
80
				case "-handbook" -> {
KingRainbow44's avatar
KingRainbow44 committed
81
					Tools.createGmHandbook(); exitEarly = true;
KingRainbow44's avatar
KingRainbow44 committed
82
				}
83
				case "-gachamap" -> {
84
					Tools.createGachaMapping(DATA("gacha_mappings.js")); exitEarly = true;
85
				}
86
87
88
				case "-version" -> {
					System.out.println("Grasscutter version: " + BuildConfig.VERSION + "\nGit Hash: " + BuildConfig.GIT_HASH); exitEarly = true;
				}
Melledy's avatar
Melledy committed
89
			}
KingRainbow44's avatar
KingRainbow44 committed
90
91
92
93
		} 
		
		// Exit early if argument sets it.
		if(exitEarly) System.exit(0);
94
	
KingRainbow44's avatar
KingRainbow44 committed
95
		// Initialize server.
96
		Grasscutter.getLogger().info(translate("messages.status.starting"));
97
	
KingRainbow44's avatar
KingRainbow44 committed
98
		// Load all resources.
99
		Grasscutter.updateDayOfWeek();
Melledy's avatar
Melledy committed
100
		ResourceLoader.loadAll();
101
		ScriptLoader.init();
102
	
KingRainbow44's avatar
KingRainbow44 committed
103
		// Initialize database.
Melledy's avatar
Melledy committed
104
		DatabaseManager.initialize();
105
	
KingRainbow44's avatar
KingRainbow44 committed
106
107
		// Create server instances.
		dispatchServer = new DispatchServer();
108
		gameServer = new GameServer();
KingRainbow44's avatar
KingRainbow44 committed
109
110
		// Create a server hook instance with both servers.
		new ServerHook(gameServer, dispatchServer);
111
112
		// Create plugin manager instance.
		pluginManager = new PluginManager();
113
	
KingRainbow44's avatar
KingRainbow44 committed
114
		// Start servers.
115
116
		var runMode = SERVER.runMode;
		if (runMode == ServerRunMode.HYBRID) {
117
118
			dispatchServer.start();
			gameServer.start();
119
		} else if (runMode == ServerRunMode.DISPATCH_ONLY) {
120
			dispatchServer.start();
121
		} else if (runMode == ServerRunMode.GAME_ONLY) {
122
123
			gameServer.start();
		} else {
124
			getLogger().error(translate("messages.status.run_mode_error", runMode));
125
126
			getLogger().error(translate("messages.status.run_mode_help"));
			getLogger().error(translate("messages.status.shutdown"));
127
128
			System.exit(1);
		}
129
	
KingRainbow44's avatar
KingRainbow44 committed
130
131
		// Enable all plugins.
		pluginManager.enablePlugins();
132
	
KingRainbow44's avatar
KingRainbow44 committed
133
134
		// Hook into shutdown event.
		Runtime.getRuntime().addShutdownHook(new Thread(Grasscutter::onShutdown));
135
	
136
137
		// Open console.
		startConsole();
138
 	}
KingRainbow44's avatar
KingRainbow44 committed
139
140
141
142
143
144
145
146

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

148
149
150
	/**
	 * Attempts to load the configuration from a file.
	 */
151
	public static void loadConfig() {
Melledy's avatar
Melledy committed
152
		try (FileReader file = new FileReader(configFile)) {
153
154
155
156
157
158
			config = gson.fromJson(file, ConfigContainer.class);
		} catch (Exception exception) {
			Grasscutter.saveConfig(null);
			config = new ConfigContainer();
		} catch (Error error) {
			// Occurred probably from an outdated config file.
159
			Grasscutter.saveConfig(null);
160
			config = new ConfigContainer();
Melledy's avatar
Melledy committed
161
162
		}
	}
方块君's avatar
方块君 committed
163
164

	public static void loadLanguage() {
165
		var locale = config.language.language;
Secretboy-SMR's avatar
Secretboy-SMR committed
166
        language = Language.getLanguage(Utils.getLanguageCode(locale));
方块君's avatar
方块君 committed
167
	}
Secretboy's avatar
Secretboy committed
168

169
170
171
172
	/**
	 * Saves the provided server configuration.
	 * @param config The configuration to save, or null for a new one.
	 */
173
174
	public static void saveConfig(@Nullable ConfigContainer config) {
		if(config == null) config = new ConfigContainer();
175
		
Melledy's avatar
Melledy committed
176
177
		try (FileWriter file = new FileWriter(configFile)) {
			file.write(gson.toJson(config));
178
179
		} catch (IOException ignored) {
			Grasscutter.getLogger().error("Unable to write to config file.");
Melledy's avatar
Melledy committed
180
		} catch (Exception e) {
181
			Grasscutter.getLogger().error("Unable to save config file.", e);
Melledy's avatar
Melledy committed
182
183
		}
	}
Secretboy's avatar
Secretboy committed
184

Melledy's avatar
Melledy committed
185
	public static void startConsole() {
186
		// Console should not start in dispatch only mode.
187
		if (SERVER.runMode == ServerRunMode.DISPATCH_ONLY) {
188
			getLogger().info(translate("messages.dispatch.no_commands_error"));
189
190
191
			return;
		}

192
		getLogger().info(translate("messages.status.done"));
193
		getLogger().info(translate("messages.status.version", BuildConfig.VERSION, BuildConfig.GIT_HASH));
194
195
196
197
198
199
200
201
202
203
204
205
		String input = null;
		boolean isLastInterrupted = false;
		while (true) {
			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);
Melledy's avatar
Melledy committed
206
				}
207
208
209
210
211
212
213
214
215
216
			} catch (EndOfFileException e) {
				Grasscutter.getLogger().info("EOF detected.");
				continue;
			} catch (IOError e) {
				Grasscutter.getLogger().error("An IO error occurred.", e);
				continue;
			}

			isLastInterrupted = false;
			try {
AnimeGitB's avatar
AnimeGitB committed
217
				CommandMap.getInstance().invoke(null, null, input);
218
			} catch (Exception e) {
219
				Grasscutter.getLogger().error(translate("messages.game.command_error"), e);
Melledy's avatar
Melledy committed
220
221
222
			}
		}
	}
KingRainbow44's avatar
KingRainbow44 committed
223

224
	public static ConfigContainer getConfig() {
KingRainbow44's avatar
KingRainbow44 committed
225
226
227
		return config;
	}

方块君's avatar
方块君 committed
228
229
230
231
	public static Language getLanguage() {
		return language;
	}

Secretboy's avatar
Secretboy committed
232
233
234
235
236
237
238
239
	public static void setLanguage(Language language) {
        Grasscutter.language = language;
	}

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

KingRainbow44's avatar
KingRainbow44 committed
240
241
242
243
	public static Logger getLogger() {
		return log;
	}

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
	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
264
265
266
267
268
269
270
271
272
273
274
	public static Gson getGsonFactory() {
		return gson;
	}

	public static DispatchServer getDispatchServer() {
		return dispatchServer;
	}

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

KingRainbow44's avatar
KingRainbow44 committed
276
277
278
	public static PluginManager getPluginManager() {
		return pluginManager;
	}
Secretboy's avatar
Secretboy committed
279

280
281
282
283
284
285
286
287
	public static void updateDayOfWeek() {
		Calendar calendar = Calendar.getInstance();
		day = calendar.get(Calendar.DAY_OF_WEEK); 
	}

	public static int getCurrentDayOfWeek() {
		return day;
	}
Secretboy's avatar
Secretboy committed
288

289
290
291
	public enum ServerRunMode {
		HYBRID, DISPATCH_ONLY, GAME_ONLY
	}
Secretboy's avatar
Secretboy committed
292

293
294
295
	public enum ServerDebugMode {
		ALL, MISSING, NONE
	}
Melledy's avatar
Melledy committed
296
}