DispatchServer.java 21.8 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
5
6
package emu.grasscutter.server.dispatch;

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

7
import emu.grasscutter.GameConstants;
Melledy's avatar
Melledy committed
8
import emu.grasscutter.Grasscutter;
9
10
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.Grasscutter.ServerRunMode;
Melledy's avatar
Melledy committed
11
12
13
14
15
16
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.net.proto.QueryCurrRegionHttpRspOuterClass.QueryCurrRegionHttpRsp;
import emu.grasscutter.net.proto.QueryRegionListHttpRspOuterClass.QueryRegionListHttpRsp;
import emu.grasscutter.net.proto.RegionInfoOuterClass.RegionInfo;
import emu.grasscutter.net.proto.RegionSimpleInfoOuterClass.RegionSimpleInfo;
17
18
import emu.grasscutter.server.dispatch.authentication.AuthenticationHandler;
import emu.grasscutter.server.dispatch.authentication.DefaultAuthenticationHandler;
19
import emu.grasscutter.server.dispatch.http.GachaRecordHandler;
Jaida Wu's avatar
Jaida Wu committed
20
import emu.grasscutter.server.dispatch.json.*;
Melledy's avatar
Melledy committed
21
import emu.grasscutter.server.dispatch.json.ComboTokenReqJson.LoginTokenData;
KingRainbow44's avatar
KingRainbow44 committed
22
23
import emu.grasscutter.server.event.dispatch.QueryAllRegionsEvent;
import emu.grasscutter.server.event.dispatch.QueryCurrentRegionEvent;
24
import emu.grasscutter.tools.Tools;
Melledy's avatar
Melledy committed
25
import emu.grasscutter.utils.FileUtils;
26
import emu.grasscutter.utils.Utils;
27
import express.Express;
28
import io.javalin.http.staticfiles.Location;
29
30
31
32
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;
Melledy's avatar
Melledy committed
33

Jaida Wu's avatar
Jaida Wu committed
34
35
import java.io.*;
import java.net.URLDecoder;
36
import java.nio.charset.StandardCharsets;
37
import java.util.*;
Melledy's avatar
Melledy committed
38

39
import static emu.grasscutter.utils.Language.translate;
40
import static emu.grasscutter.Configuration.*;
41

KingRainbow44's avatar
KingRainbow44 committed
42
public final class DispatchServer {
Jaida Wu's avatar
Jaida Wu committed
43
44
	public static String query_region_list = "";
	public static String query_cur_region = "";
45

Melledy's avatar
Melledy committed
46
	private final Gson gson;
47
	private final String defaultServerName = "os_usa";
48

Melledy's avatar
Melledy committed
49
	public String regionListBase64;
50
	public Map<String, RegionData> regions;
51
	private AuthenticationHandler authHandler;
52
	private Express httpServer;
53

Melledy's avatar
Melledy committed
54
	public DispatchServer() {
55
		this.regions = new HashMap<>();
Melledy's avatar
Melledy committed
56
		this.gson = new GsonBuilder().create();
57

Melledy's avatar
Melledy committed
58
59
60
		this.loadQueries();
		this.initRegion();
	}
61

62
63
	public Express getServer() {
		return httpServer;
Melledy's avatar
Melledy committed
64
	}
65

66
67
68
	public void setHttpServer(Express httpServer) {
		this.httpServer.stop();
		this.httpServer = httpServer;
69
		this.httpServer.listen(DISPATCH_INFO.bindPort);
70
71
	}

Melledy's avatar
Melledy committed
72
73
74
75
	public Gson getGsonFactory() {
		return gson;
	}

76
77
	public QueryCurrRegionHttpRsp getCurrRegion() {
		// Needs to be fixed by having the game servers connect to the dispatch server.
78
		if (SERVER.runMode == ServerRunMode.HYBRID) {
79
			return regions.get(defaultServerName).parsedRegionQuery;
80
81
		}

82
		Grasscutter.getLogger().warn("[Dispatch] Unsupported run mode for getCurrRegion()");
83
		return null;
Melledy's avatar
Melledy committed
84
	}
85

Melledy's avatar
Melledy committed
86
87
	public void loadQueries() {
		File file;
88

89
		file = new File(DATA("query_region_list.txt"));
Melledy's avatar
Melledy committed
90
91
92
		if (file.exists()) {
			query_region_list = new String(FileUtils.read(file));
		} else {
Jaida Wu's avatar
Jaida Wu committed
93
			Grasscutter.getLogger().warn("[Dispatch] query_region_list not found! Using default region list.");
Melledy's avatar
Melledy committed
94
		}
95

96
		file = new File(DATA("query_cur_region.txt"));
Melledy's avatar
Melledy committed
97
98
99
		if (file.exists()) {
			query_cur_region = new String(FileUtils.read(file));
		} else {
Jaida Wu's avatar
Jaida Wu committed
100
			Grasscutter.getLogger().warn("[Dispatch] query_cur_region not found! Using default current region.");
Melledy's avatar
Melledy committed
101
102
103
104
105
106
107
		}
	}

	private void initRegion() {
		try {
			byte[] decoded = Base64.getDecoder().decode(query_region_list);
			QueryRegionListHttpRsp rl = QueryRegionListHttpRsp.parseFrom(decoded);
108

Melledy's avatar
Melledy committed
109
110
			byte[] decoded2 = Base64.getDecoder().decode(query_cur_region);
			QueryCurrRegionHttpRsp regionQuery = QueryCurrRegionHttpRsp.parseFrom(decoded2);
111

KingRainbow44's avatar
KingRainbow44 committed
112
			List<RegionSimpleInfo> servers = new ArrayList<>();
113
114
			List<String> usedNames = new ArrayList<>(); // List to check for potential naming conflicts.
			if (SERVER.runMode == ServerRunMode.HYBRID) { // Automatically add the game server if in hybrid mode.
115
116
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName("os_usa")
117
						.setTitle(DISPATCH_INFO.defaultName)
118
						.setType("DEV_PUBLIC")
119
						.setDispatchUrl(
120
121
122
								"http" + (DISPATCH_ENCRYPTION.useEncryption ? "s" : "") + "://"
										+ lr(DISPATCH_INFO.accessAddress, DISPATCH_INFO.bindAddress) + ":"
										+ lr(DISPATCH_INFO.accessPort, DISPATCH_INFO.bindPort)
123
										+ "/query_cur_region/" + defaultServerName)
124
125
126
127
128
						.build();
				usedNames.add(defaultServerName);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
mingjun97's avatar
mingjun97 committed
129
130
						.setGateserverIp(lr(GAME_INFO.accessAddress, GAME_INFO.bindAddress))
						.setGateserverPort(lr(GAME_INFO.accessPort, GAME_INFO.bindPort))
131
						.setSecretKey(ByteString.copyFrom(FileUtils.read(KEYS_FOLDER + "/dispatchSeed.bin")))
132
133
134
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
135
136
				regions.put(defaultServerName, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
137

138
139
140
			} else if (DISPATCH_INFO.regions.length == 0) {
				Grasscutter.getLogger().error("[Dispatch] There are no game servers available. Exiting due to unplayable state.");
				System.exit(1);
141
142
			}

143
			for (var regionInfo : DISPATCH_INFO.regions) {
144
				if (usedNames.contains(regionInfo.Name)) {
145
146
147
148
149
150
151
					Grasscutter.getLogger().error("Region name already in use.");
					continue;
				}
				RegionSimpleInfo server = RegionSimpleInfo.newBuilder()
						.setName(regionInfo.Name)
						.setTitle(regionInfo.Title)
						.setType("DEV_PUBLIC")
152
						.setDispatchUrl(
153
154
155
156
								"http" + (DISPATCH_ENCRYPTION.useEncryption ? "s" : "") + "://"
										+ lr(DISPATCH_INFO.accessAddress, DISPATCH_INFO.bindAddress) + ":" 
										+ lr(DISPATCH_INFO.accessPort, DISPATCH_INFO.bindPort) 
										+ "/query_cur_region/" + regionInfo.Name)
157
158
159
160
161
						.build();
				usedNames.add(regionInfo.Name);
				servers.add(server);

				RegionInfo serverRegion = regionQuery.getRegionInfo().toBuilder()
162
163
						.setGateserverIp(regionInfo.Ip)
						.setGateserverPort(regionInfo.Port)
164
						.setSecretKey(ByteString
165
								.copyFrom(FileUtils.read(KEYS_FOLDER + "/dispatchSeed.bin")))
166
167
168
						.build();

				QueryCurrRegionHttpRsp parsedRegionQuery = regionQuery.toBuilder().setRegionInfo(serverRegion).build();
169
170
				regions.put(regionInfo.Name, new RegionData(parsedRegionQuery,
						Base64.getEncoder().encodeToString(parsedRegionQuery.toByteString().toByteArray())));
171
172
			}

Melledy's avatar
Melledy committed
173
			QueryRegionListHttpRsp regionList = QueryRegionListHttpRsp.newBuilder()
174
					.addAllRegionList(servers)
175
176
177
178
					.setClientSecretKey(rl.getClientSecretKey())
					.setClientCustomConfigEncrypted(rl.getClientCustomConfigEncrypted())
					.setEnableLoginPc(true)
					.build();
Melledy's avatar
Melledy committed
179
180

			this.regionListBase64 = Base64.getEncoder().encodeToString(regionList.toByteString().toByteArray());
181
182
		} catch (Exception exception) {
			Grasscutter.getLogger().error("[Dispatch] Error while initializing region info!", exception);
Melledy's avatar
Melledy committed
183
184
185
186
		}
	}

	public void start() throws Exception {
187
188
189
190
191
		httpServer = new Express(config -> {
			config.server(() -> {
				Server server = new Server();
				ServerConnector serverConnector;

192
				if(DISPATCH_ENCRYPTION.useEncryption) {
193
					SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
194
					File keystoreFile = new File(DISPATCH_ENCRYPTION.keystore);
195
196
197
198

					if(keystoreFile.exists()) {
						try {
							sslContextFactory.setKeyStorePath(keystoreFile.getPath());
199
							sslContextFactory.setKeyStorePassword(DISPATCH_ENCRYPTION.keystorePassword);
200
201
						} catch (Exception e) {
							e.printStackTrace();
202
							Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.password_error"));
203
204
205
206

							try {
								sslContextFactory.setKeyStorePath(keystoreFile.getPath());
								sslContextFactory.setKeyStorePassword("123456");
207
								Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.default_password"));
208
							} catch (Exception e2) {
209
								Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.general_error"));
210
211
212
213
214
215
								e2.printStackTrace();
							}
						}

						serverConnector = new ServerConnector(server, sslContextFactory);
					} else {
216
						Grasscutter.getLogger().warn(translate("messages.dispatch.keystore.no_keystore_error"));
217
						DISPATCH_ENCRYPTION.useEncryption = false;
218
219

						serverConnector = new ServerConnector(server);
220
					}
221
222
				} else {
					serverConnector = new ServerConnector(server);
223
				}
224

225
				serverConnector.setPort(DISPATCH_INFO.bindPort);
226
227
228
229
				server.setConnectors(new Connector[]{serverConnector});
				return server;
			});

230
231
			config.enforceSsl = DISPATCH_ENCRYPTION.useEncryption;
			if(SERVER.debugLevel == ServerDebugMode.ALL) {
232
				config.enableDevLogging();
233
			}
234
235
236
237
238
			
			if (DISPATCH_POLICIES.cors.enabled) {
				var corsPolicy = DISPATCH_POLICIES.cors;
				if (corsPolicy.allowedOrigins.length > 0) 
					config.enableCorsForOrigin(corsPolicy.allowedOrigins);
239
240
				else config.enableCorsForAllOrigins();
			}
241
		});
242
		httpServer.get("/", (req, res) -> res.send("<!doctype html><html><head><meta charset=\"utf8\"></head><body>" + translate("messages.status.welcome") + "</body></html>"));
Jaida Wu's avatar
Jaida Wu committed
243

244
		httpServer.raw().error(404, ctx -> {
245
			if(SERVER.debugLevel == ServerDebugMode.MISSING) {
246
				Grasscutter.getLogger().info(translate("messages.dispatch.unhandled_request_error", ctx.method(), ctx.url()));
247
248
			}
			ctx.contentType("text/html");
249
			ctx.result("<!doctype html><html><head><meta charset=\"utf8\"></head><body><img src=\"https://http.cat/404\" /></body></html>"); // I'm like 70% sure this won't break anything.
250
		});
251

252
253
254
255
256
257
258
259
260
261
		// Authentication Handler
		// These routes are so that authentication routes are always the same no matter what auth system is used.
		httpServer.get("/authentication/type", (req, res) -> {
			res.send(this.getAuthHandler().getClass().getName());
		});

		httpServer.post("/authentication/login", (req, res) -> this.getAuthHandler().handleLogin(req, res));
		httpServer.post("/authentication/register", (req, res) -> this.getAuthHandler().handleRegister(req, res));
		httpServer.post("/authentication/change_password", (req, res) -> this.getAuthHandler().handleChangePassword(req, res));

262
263
264
265
266
267
268
269
270
		// Server Status
		httpServer.get("/status/server", (req, res) -> {

			int playerCount = Grasscutter.getGameServer().getPlayers().size();
			String version = GameConstants.VERSION;

			res.send("{\"retcode\":0,\"status\":{\"playerCount\":" + playerCount + ",\"version\":\"" + version + "\"}}");
		});

Melledy's avatar
Melledy committed
271
		// Dispatch
272
		httpServer.get("/query_region_list", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
273
			// Log
274
			Grasscutter.getLogger().info(String.format("[Dispatch] Client %s request: query_region_list", req.ip()));
Jaida Wu's avatar
Jaida Wu committed
275

276
277
278
			// Invoke event.
			QueryAllRegionsEvent event = new QueryAllRegionsEvent(regionListBase64); event.call();
			// Respond with event result.
279
			res.send(event.getRegionList());
Melledy's avatar
Melledy committed
280
		});
281

282
283
284
285
286
287
288
289
290
291
		httpServer.get("/query_cur_region/:id", (req, res) -> {
			String regionName = req.params("id");
			// Log
			Grasscutter.getLogger().info(
					String.format("Client %s request: query_cur_region/%s", req.ip(), regionName));
			// Create a response form the request query parameters
			String response = "CAESGE5vdCBGb3VuZCB2ZXJzaW9uIGNvbmZpZw==";
			if (req.query().values().size() > 0) {
				response = regions.get(regionName).Base64;
			}
292

293
294
295
296
297
298
299
			// Invoke event.
			QueryCurrentRegionEvent event = new QueryCurrentRegionEvent(response); event.call();
			// Respond with event result.
			res.send(event.getRegionInfo());
		});

		// Login
300

301
		httpServer.post("/hk4e_global/mdk/shield/api/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
302
303
304
			// Get post data
			LoginAccountRequestJson requestData = null;
			try {
305
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
306
				requestData = getGsonFactory().fromJson(body, LoginAccountRequestJson.class);
307
			} catch (Exception ignored) { }
308

KingRainbow44's avatar
KingRainbow44 committed
309
310
311
312
			// Create response json
			if (requestData == null) {
				return;
			}
313
			Grasscutter.getLogger().info(translate("messages.dispatch.account.login_attempt", req.ip()));
314

315
			res.send(this.getAuthHandler().handleGameLogin(req, requestData));
Melledy's avatar
Melledy committed
316
		});
317

Melledy's avatar
Melledy committed
318
		// Login via token
319
		httpServer.post("/hk4e_global/mdk/shield/api/verify", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
320
321
322
			// Get post data
			LoginTokenRequestJson requestData = null;
			try {
323
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
324
				requestData = getGsonFactory().fromJson(body, LoginTokenRequestJson.class);
325
326
			} catch (Exception ignored) {
			}
327

KingRainbow44's avatar
KingRainbow44 committed
328
329
330
331
332
			// Create response json
			if (requestData == null) {
				return;
			}
			LoginResultJson responseData = new LoginResultJson();
KingRainbow44's avatar
KingRainbow44 committed
333
			Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_attempt", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
334
335
336

			// Login
			Account account = DatabaseHelper.getAccountById(requestData.uid);
337

KingRainbow44's avatar
KingRainbow44 committed
338
339
340
			// Test
			if (account == null || !account.getSessionKey().equals(requestData.token)) {
				responseData.retcode = -111;
341
				responseData.message = translate("messages.dispatch.account.account_cache_error");
Jaida Wu's avatar
Jaida Wu committed
342

343
				Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_error", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
344
345
346
347
348
			} else {
				responseData.message = "OK";
				responseData.data.account.uid = requestData.uid;
				responseData.data.account.token = requestData.token;
				responseData.data.account.email = account.getEmail();
Jaida Wu's avatar
Jaida Wu committed
349

350
				Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_success", req.ip(), requestData.uid));
KingRainbow44's avatar
KingRainbow44 committed
351
			}
Jaida Wu's avatar
Jaida Wu committed
352

353
			res.send(responseData);
Melledy's avatar
Melledy committed
354
		});
355

Melledy's avatar
Melledy committed
356
		// Exchange for combo token
357
		httpServer.post("/hk4e_global/combo/granter/login/v2/login", (req, res) -> {
KingRainbow44's avatar
KingRainbow44 committed
358
359
360
			// Get post data
			ComboTokenReqJson requestData = null;
			try {
361
				String body = req.ctx().body();
KingRainbow44's avatar
KingRainbow44 committed
362
				requestData = getGsonFactory().fromJson(body, ComboTokenReqJson.class);
363
364
			} catch (Exception ignored) {
			}
365

KingRainbow44's avatar
KingRainbow44 committed
366
367
368
369
			// Create response json
			if (requestData == null || requestData.data == null) {
				return;
			}
370
			LoginTokenData loginData = getGsonFactory().fromJson(requestData.data, LoginTokenData.class); // Get login
371
			// data
KingRainbow44's avatar
KingRainbow44 committed
372
373
374
375
			ComboTokenResJson responseData = new ComboTokenResJson();

			// Login
			Account account = DatabaseHelper.getAccountById(loginData.uid);
376

KingRainbow44's avatar
KingRainbow44 committed
377
378
379
			// Test
			if (account == null || !account.getSessionKey().equals(loginData.token)) {
				responseData.retcode = -201;
380
				responseData.message = translate("messages.dispatch.account.session_key_error");
Jaida Wu's avatar
Jaida Wu committed
381

382
				Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_error", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
383
384
385
386
387
			} else {
				responseData.message = "OK";
				responseData.data.open_id = loginData.uid;
				responseData.data.combo_id = "157795300";
				responseData.data.combo_token = account.generateLoginToken();
Jaida Wu's avatar
Jaida Wu committed
388

389
				Grasscutter.getLogger().info(translate("messages.dispatch.account.combo_token_success", req.ip()));
KingRainbow44's avatar
KingRainbow44 committed
390
			}
Jaida Wu's avatar
Jaida Wu committed
391

392
			res.send(responseData);
Melledy's avatar
Melledy committed
393
		});
394
395
396
397

		// TODO: There are some missing route request types here (You can tell if they are missing if they are .all and not anything else)
		//  When http requests for theses routes are found please remove it from the list in DispatchHttpJsonHandler and update the route request types here

Melledy's avatar
Melledy committed
398
		// Agreement and Protocol
399
400
401
		// hk4e-sdk-os.hoyoverse.com
		httpServer.get("/hk4e_global/mdk/agreement/api/getAgreementInfos", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}"));
		// hk4e-sdk-os.hoyoverse.com
mingjun97's avatar
mingjun97 committed
402
403
		// this could be either GET or POST based on the observation of different clients
		httpServer.all("/hk4e_global/combo/granter/api/compareProtocolVersion", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":true,\"protocol\":{\"id\":0,\"app_id\":4,\"language\":\"en\",\"user_proto\":\"\",\"priv_proto\":\"\",\"major\":7,\"minimum\":0,\"create_time\":\"0\",\"teenager_proto\":\"\",\"third_proto\":\"\"}}}"));
404

Melledy's avatar
Melledy committed
405
		// Game data
406
407
408
409
410
		// hk4e-api-os.hoyoverse.com
		httpServer.all("/common/hk4e_global/announcement/api/getAlertPic", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}"));
		// hk4e-api-os.hoyoverse.com
		httpServer.all("/common/hk4e_global/announcement/api/getAlertAnn", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":true}}"));
		// hk4e-api-os.hoyoverse.com
BaiSugar's avatar
BaiSugar committed
411
		httpServer.all("/common/hk4e_global/announcement/api/getAnnList", new AnnouncementHandler());
412
		// hk4e-api-os-static.hoyoverse.com
BaiSugar's avatar
BaiSugar committed
413
		httpServer.all("/common/hk4e_global/announcement/api/getAnnContent", new AnnouncementHandler());
414
415
416
		// hk4e-sdk-os.hoyoverse.com
		httpServer.all("/hk4e_global/mdk/shopwindow/shopwindow/listPriceTier", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"suggest_currency\":\"USD\",\"tiers\":[]}}"));

Melledy's avatar
Melledy committed
417
		// Captcha
418
419
420
		// api-account-os.hoyoverse.com
		httpServer.post("/account/risky/api/check", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}"));

421
		// Config
422
423
424
425
426
		// sdk-os-static.hoyoverse.com
		httpServer.get("/combo/box/api/config/sdk/combo", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"disable_email_bind_skip\":\"false\",\"email_bind_remind_interval\":\"7\",\"email_bind_remind\":\"true\"}}}"));
		// hk4e-sdk-os-static.hoyoverse.com
		httpServer.get("/hk4e_global/combo/granter/api/getConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"https://webstatic-sea.hoyoverse.com/hk4e/announcement/index.html?sdk_presentation_style=fullscreen\\u0026sdk_screen_transparent=true\\u0026game_biz=hk4e_global\\u0026auth_appid=announcement\\u0026game=hk4e#/\",\"push_alias_type\":2,\"disable_ysdk_guard\":false,\"enable_announce_pic_popup\":true}}"));
		// hk4e-sdk-os-static.hoyoverse.com
Magix's avatar
Magix committed
427
		httpServer.get("/hk4e_global/mdk/shield/api/loadConfig", new DispatchHttpJsonHandler("{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":6,\"game_key\":\"hk4e_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"原神海外\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{\"tw\":\"\",\"fb\":\"\"},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}}}}"));
Melledy's avatar
Melledy committed
428
		// Test api?
429
		// abtest-api-data-sg.hoyoverse.com
Benjamin Elsdon's avatar
Benjamin Elsdon committed
430
		httpServer.post("/data_abtest_api/config/experiment/list", new DispatchHttpJsonHandler("{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6036_99\",\"version\":\"1\",\"configs\":{\"cardType\":\"old\"}}]}"));
431
432
433
434

		// log-upload-os.mihoyo.com
		httpServer.all("/log/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}"));
		httpServer.all("/sdk/upload", new DispatchHttpJsonHandler("{\"code\":0}"));
435
		httpServer.post("/sdk/dataUpload", new DispatchHttpJsonHandler("{\"code\":0}"));
436
437
		// /perf/config/verify?device_id=xxx&platform=x&name=xxx
		httpServer.all("/perf/config/verify", new DispatchHttpJsonHandler("{\"code\":0}"));
438

Melledy's avatar
Melledy committed
439
		// Logging servers
440
		// overseauspider.yuanshen.com
441
		httpServer.all("/log", new ClientLogHandler());
442
		// log-upload-os.mihoyo.com
443
		httpServer.all("/crash/dataUpload", new ClientLogHandler());
Jaida Wu's avatar
Jaida Wu committed
444

mingjun97's avatar
mingjun97 committed
445
446
447
		// webstatic-sea.hoyoverse.com
		httpServer.get("/admin/mi18n/plat_oversea/m202003048/m202003048-version.json", new DispatchHttpJsonHandler("{\"version\":51}"));

448
		// gacha record.
449
		String gachaMappingsPath = Utils.toFilePath(DATA("/gacha_mappings.js"));
450
		// TODO: Only serve the html page and have a subsequent request to fetch the gacha data.
451
		httpServer.get("/gacha", new GachaRecordHandler());
452
453
454
455
456
		if(!(new File(gachaMappingsPath).exists())) {
			Tools.createGachaMapping(gachaMappingsPath);
		}

		httpServer.raw().config.addSinglePageRoot("/gacha/mappings", gachaMappingsPath, Location.EXTERNAL);
Jaida Wu's avatar
Jaida Wu committed
457

458
459
		// static file support for plugins
		httpServer.raw().config.precompressStaticFiles = false; // If this isn't set to false, files such as images may appear corrupted when serving static files
460

461
		httpServer.listen(DISPATCH_INFO.bindPort);
462
		Grasscutter.getLogger().info(translate("messages.dispatch.port_bind", Integer.toString(httpServer.raw().port())));
Melledy's avatar
Melledy committed
463
	}
464

Melledy's avatar
Melledy committed
465
	private Map<String, String> parseQueryString(String qs) {
Jaida Wu's avatar
Jaida Wu committed
466
		Map<String, String> result = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
467
		if (qs == null) {
Jaida Wu's avatar
Jaida Wu committed
468
			return result;
Jaida Wu's avatar
Jaida Wu committed
469
		}
Jaida Wu's avatar
Jaida Wu committed
470
471
472
473

		int last = 0, next, l = qs.length();
		while (last < l) {
			next = qs.indexOf('&', last);
Jaida Wu's avatar
Jaida Wu committed
474
			if (next == -1) {
Jaida Wu's avatar
Jaida Wu committed
475
				next = l;
Jaida Wu's avatar
Jaida Wu committed
476
			}
Jaida Wu's avatar
Jaida Wu committed
477
478
479

			if (next > last) {
				int eqPos = qs.indexOf('=', last);
480
481
482
483
484
				if (eqPos < 0 || eqPos > next) {
					result.put(URLDecoder.decode(qs.substring(last, next), StandardCharsets.UTF_8), "");
				} else {
					result.put(URLDecoder.decode(qs.substring(last, eqPos), StandardCharsets.UTF_8),
							URLDecoder.decode(qs.substring(eqPos + 1, next), StandardCharsets.UTF_8));
Jaida Wu's avatar
Jaida Wu committed
485
486
487
488
489
				}
			}
			last = next + 1;
		}
		return result;
Melledy's avatar
Melledy committed
490
	}
491

492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
	public AuthenticationHandler getAuthHandler() {
		if(authHandler == null) {
			return new DefaultAuthenticationHandler();
		}
		return authHandler;
	}

	public boolean registerAuthHandler(AuthenticationHandler authHandler) {
		if(this.authHandler != null) {
			Grasscutter.getLogger().error(String.format("[Dispatch] Unable to register '%s' authentication handler. \n" +
					"The '%s' authentication handler has already been registered", authHandler.getClass().getName(), this.authHandler.getClass().getName()));
			return false;
		}
		this.authHandler = authHandler;
		return true;
	}

	public void resetAuthHandler() {
		this.authHandler = null;
	}

513
514
515
516
517
518
519
520
	public static class RegionData {
		QueryCurrRegionHttpRsp parsedRegionQuery;
		String Base64;

		public RegionData(QueryCurrRegionHttpRsp prq, String b64) {
			this.parsedRegionQuery = prq;
			this.Base64 = b64;
		}
521
522
523
524
525
526
527
528

		public QueryCurrRegionHttpRsp getParsedRegionQuery() {
			return parsedRegionQuery;
		}

		public String getBase64() {
			return Base64;
		}
529
	}
Melledy's avatar
Melledy committed
530
}