Grasscutter.java 7.77 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
32
import emu.grasscutter.server.dispatch.DispatchServer;
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.Crypto;

33
34
import javax.annotation.Nullable;

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

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

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

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

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

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

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

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

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

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

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

144
145
146
	/**
	 * Attempts to load the configuration from a file.
	 */
147
	public static void loadConfig() {
Melledy's avatar
Melledy committed
148
		try (FileReader file = new FileReader(configFile)) {
149
150
151
152
153
154
			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.
155
			Grasscutter.saveConfig(null);
156
			config = new ConfigContainer();
Melledy's avatar
Melledy committed
157
158
		}
	}
方块君's avatar
方块君 committed
159
160

	public static void loadLanguage() {
161
		var locale = config.language.language;
Secretboy-SMR's avatar
Secretboy-SMR committed
162
        language = Language.getLanguage(Utils.getLanguageCode(locale));
方块君's avatar
方块君 committed
163
	}
Secretboy's avatar
Secretboy committed
164

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

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

188
		getLogger().info(translate("messages.status.done"));
189
190
191
192
193
194
195
196
197
198
199
200
		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
201
				}
202
203
204
205
206
207
208
209
210
211
			} 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
212
				CommandMap.getInstance().invoke(null, null, input);
213
			} catch (Exception e) {
214
				Grasscutter.getLogger().error(translate("messages.game.command_error"), e);
Melledy's avatar
Melledy committed
215
216
217
			}
		}
	}
KingRainbow44's avatar
KingRainbow44 committed
218

219
	public static ConfigContainer getConfig() {
KingRainbow44's avatar
KingRainbow44 committed
220
221
222
		return config;
	}

方块君's avatar
方块君 committed
223
224
225
226
	public static Language getLanguage() {
		return language;
	}

Secretboy's avatar
Secretboy committed
227
228
229
230
231
232
233
234
	public static void setLanguage(Language language) {
        Grasscutter.language = language;
	}

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

KingRainbow44's avatar
KingRainbow44 committed
235
236
237
238
	public static Logger getLogger() {
		return log;
	}

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

	public static DispatchServer getDispatchServer() {
		return dispatchServer;
	}

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

KingRainbow44's avatar
KingRainbow44 committed
271
272
273
	public static PluginManager getPluginManager() {
		return pluginManager;
	}
Secretboy's avatar
Secretboy committed
274

275
276
277
278
279
280
281
282
	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
283

284
285
286
	public enum ServerRunMode {
		HYBRID, DISPATCH_ONLY, GAME_ONLY
	}
Secretboy's avatar
Secretboy committed
287

288
289
290
	public enum ServerDebugMode {
		ALL, MISSING, NONE
	}
Melledy's avatar
Melledy committed
291
}