package online.astradev.packs; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; /** Server-local configuration, deliberately never synchronized to clients. */ public final class PackConfig { public static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public boolean enabled = true; public Build build = new Build(); public Hosting hosting = new Hosting(); public Delivery delivery = new Delivery(); public Messages messages = new Messages(); public static final class Build { public String storageDirectory = "astrapacks"; public List sources = new ArrayList<>(List.of("astrapacks/contents")); public boolean scanModJars = true; public boolean onStartup = true; public boolean resendAfterBuild = true; public String description = "AstraDev — общий серверный ресурспак"; public String conflictPolicy = "error"; public int maxFileMiB = 32; public int maxTotalMiB = 256; public int maxFiles = 50000; } public static final class Hosting { public String mode = "simple_self_host"; public String publicAddress = "auto"; public String bindAddress = "0.0.0.0"; public int port = 8163; public String externalUrl = ""; public boolean blockNonGameRequests = true; public int maxDownloadsPerIp = 5; public int maxConcurrentDownloads = 32; public int maxSpeedMiBPerSecond = 30; public int tokenLifetimeSeconds = 600; } public static final class Delivery { public boolean sendOnJoin = true; public boolean required = true; public boolean kickOnFailure = true; public int timeoutSeconds = 120; public int retries = 1; public boolean logStatus = true; } public static final class Messages { public String prompt = "&6Привет, {player}!\\n&fДля игры на сервере необходим ресурспак AstraDev.\\n&aНажми «Продолжить», чтобы загрузить его."; public String declined = "&cДля входа необходимо принять ресурспак сервера.\\n&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись снова."; public String failed = "&cНе удалось загрузить ресурспак сервера.\\n&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи администрации."; public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова."; public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже."; public String loaded = "&aРесурспак AstraDev загружен."; } public static PackConfig load(Path path) throws IOException { if (!Files.exists(path)) { PackFiles.atomicWrite(path, (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8)); } try { PackConfig config = JSON.fromJson(Files.readString(path), PackConfig.class); if (config == null) throw new IllegalArgumentException("Empty config"); config.validate(); return config; } catch (RuntimeException e) { throw new IOException("Invalid " + path + ": " + e.getMessage(), e); } } public void validate() { Objects.requireNonNull(build); Objects.requireNonNull(hosting); Objects.requireNonNull(delivery); Objects.requireNonNull(messages); if (!Set.of("simple_self_host", "self_host", "no_host").contains(hosting.mode)) throw new IllegalArgumentException("hosting.mode: simple_self_host, self_host or no_host"); if (!Set.of("error", "last_wins").contains(build.conflictPolicy)) throw new IllegalArgumentException("build.conflictPolicy: error or last_wins"); if (build.storageDirectory.isBlank() || build.sources == null || build.sources.stream().anyMatch(s -> s == null || s.isBlank())) throw new IllegalArgumentException("Invalid build paths"); Objects.requireNonNull(build.description); range(build.maxFileMiB, 1, 128, "maxFileMiB"); range(build.maxTotalMiB, build.maxFileMiB, 1024, "maxTotalMiB"); range(build.maxFiles, 1, 200000, "maxFiles"); range(hosting.port, 1, 65535, "port"); range(hosting.maxDownloadsPerIp, 1, 100, "maxDownloadsPerIp"); range(hosting.maxConcurrentDownloads, 1, 256, "maxConcurrentDownloads"); range(hosting.maxSpeedMiBPerSecond, 1, 1024, "maxSpeedMiBPerSecond"); range(hosting.tokenLifetimeSeconds, 30, 86400, "tokenLifetimeSeconds"); range(delivery.timeoutSeconds, 10, 3600, "timeoutSeconds"); range(delivery.retries, 0, 5, "retries"); if (enabled && delivery.required && !delivery.sendOnJoin) throw new IllegalArgumentException("required needs sendOnJoin=true"); if (!hosting.publicAddress.equals("auto") && validateUrl(hosting.publicAddress).getQuery() != null) throw new IllegalArgumentException("hosting.publicAddress must not contain query parameters"); if (!hosting.mode.equals("no_host") && hosting.tokenLifetimeSeconds < delivery.timeoutSeconds) throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds"); if (hosting.mode.equals("no_host") && enabled && delivery.sendOnJoin) validateUrl(hosting.externalUrl); for (String s : List.of(messages.prompt, messages.declined, messages.failed, messages.timeout, messages.unavailable, messages.loaded)) if (s.length() > 8192) throw new IllegalArgumentException("Message exceeds 8192 characters"); } public static URI validateUrl(String value) { URI uri = URI.create(value); if (!("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) || uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null) throw new IllegalArgumentException("Expected a direct http(s) URL: " + value); return uri; } private static void range(int n, int min, int max, String key) { if (n < min || n > max) throw new IllegalArgumentException(key + " must be " + min + ".." + max); } public Path storage(Path root) { return root.resolve(build.storageDirectory).toAbsolutePath().normalize(); } }