diff --git a/README.md b/README.md index 4e8b7e5..41293e8 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Players keep the official, unmodified client; the mod runs on the server only. ## Requirements -- ZomboidForge 0.4.0 or newer, Project Zomboid Build 42 (dedicated server) +- ZomboidForge 0.6.0 or newer, Project Zomboid Build 42 (dedicated server) - Steam mode (the default of the ZomboidForge image), which the Workshop download needs - a **Public** Steam Workshop collection: unlisted, friends-only, and private collections are invisible to Steam's Web API @@ -45,10 +45,12 @@ replaces those values at every start anyway. For every item of the collection, Steam's Web API returns its title, tags, and description. -- **Mod IDs** come from description lines such as `Mod ID: Foo` or `ModID = Foo; Bar`. An item - without one stays in `WorkshopItems=` (so the server downloads it) but is left out of `Mods=`, - with a warning; `[items.] mod_ids` supplies it. The same applies to items Steam returns no - details for (private, unlisted, or removed items inside the collection). +- **Mod IDs** come from description lines such as `Mod ID: Foo` or `ModID = Foo; Bar`; IDs may + also be separated by `/`, `or`, or `and`, and a dash between spaces (`Foo - B42 only`) ends + the list. An item without one stays in `WorkshopItems=` (so the server downloads it) but is + left out of `Mods=`, with a warning; `[items.] mod_ids` supplies it. The same applies to + items Steam returns no details for (private, unlisted, or removed items inside the + collection). - **Buckets** decide the load order: `map` (a `Map Folder:` line in the description), `framework` (the Steam tag *Framework*), or `misc`. Buckets load in the order of `[order] buckets`, items within a bucket in collection order. @@ -63,7 +65,7 @@ Values go into the server's `.ini` (`[ini] write`), so `showoptions` and the fil The server always starts. The mod uses, in this order: -1. the collection, resolved live from Steam; +1. the collection, resolved live from Steam (tried a second time after 2 seconds); 2. the last successful resolution of the same collection, cached in the world's `zomboidforge.db`; 3. the values already in the `.ini`. @@ -120,9 +122,9 @@ exclude = true # left out of Mods=, WorkshopItems=, a Problems that do not stop the mod are logged as warnings: `[items]` keys or `priority` entries that match no item, two keys naming the same item (the workshop-id key wins field by -field), Mod IDs named by two items (`Mods=` lists them once), unknown keys. An item that lands -in a bucket missing from `[order] buckets` is an error: the mod then falls back as if Steam -could not be reached. +field), Mod IDs named by two items (`Mods=` lists them once), Mod IDs that differ only in case +(`Mods=` lists both), unknown keys. An item that lands in a bucket missing from +`[order] buckets` is an error: the mod then falls back as if Steam could not be reached. ## While the server runs @@ -131,8 +133,9 @@ change: - how the collection differs from what the server runs: items or Mod IDs added, removed, or in another order, a different `Map=`; -- items that were updated on Steam after the server started. Clients that download the new - version may not be able to join until the server restarts and downloads it too. +- items with a newer version on Steam than the one the server downloaded. Clients that + download the new version may not be able to join until the server restarts and downloads it + too. The mod never restarts the server; changes apply at the next start. @@ -165,7 +168,7 @@ is idle. To try it with a collection, copy `build/mod/lua_mod_automator/` into a directory (or set `zomboidForge.deployDirectory` and run `./gradlew deployMod`) and add a `config.toml` there. -Pushing a tag `v` that matches `version` in `build.gradle.kts` builds the mod and +Pushing a tag `v` that matches `version` in `settings.gradle.kts` builds the mod and publishes it as a release (`.gitea/workflows/release.yml`, `ci/release.sh`). Tags containing `-` (e.g. `v0.2.0-rc.1`) and tags on commits that are not on `master` are built and tested but not released. diff --git a/build.gradle.kts b/build.gradle.kts index e110ea1..e048538 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,15 +1,7 @@ -plugins { - id("dev.overlord.zomboidforge.mod") version "0.4.0" // the plugin's version is the ZomboidForge API version -} - -version = "0.1.0" - +// id, name, version, and entry point: settings.gradle.kts zomboidForge { - id = "lua_mod_automator" - name = "LuaModAutomator" - entrypoint = "dev.overlord.luamodautomator.LuaModAutomatorMod" - game("42") // ServerOptions, GameServer, CommandBase - serverImage = "git.security-command.org/overlord/zomboidforge:0.4.0-pz42.21" + game("42") // ServerOptions, GameServer, SteamWorkshop, CommandBase + serverImage = "git.security-command.org/overlord/zomboidforge:0.6.0-pz42.21" } dependencies { @@ -19,7 +11,7 @@ dependencies { testCompileOnly("org.jetbrains:annotations:26.0.2") // ZomboidForge's config.toml parser and binder, to bind the settings the way the server does. - testImplementation("dev.overlord.zomboidforge:mod-tools:0.4.0") + testImplementation("dev.overlord.zomboidforge:mod-tools:0.6.0") testImplementation(platform("org.junit:junit-bom:6.1.3")) testImplementation("org.junit.jupiter:junit-jupiter") diff --git a/ci/release.sh b/ci/release.sh index 3389a1b..eee03ed 100755 --- a/ci/release.sh +++ b/ci/release.sh @@ -6,7 +6,7 @@ # # A pre-release tag (containing "-", e.g. v0.2.0-rc.1), or a tag on a commit that is not on # master, is built and tested but not released. The tag must match the version in -# build.gradle.kts. +# settings.gradle.kts. # # Usage: # ci/release.sh build downloads the game jar and builds the mod (tests and checkMod included) @@ -63,8 +63,10 @@ run_gradle() { "${REPO_ROOT}/gradlew" --no-daemon --console=plain --project-dir "${REPO_ROOT}" "$@" } -project_version() { - run_gradle --quiet properties --property version | sed --quiet 's/^version: //p' +# Prints the mod's version: the `version = "..."` line of zomboidForge { } in settings.gradle.kts. +# The ZomboidForge plugin does not set Gradle's project version. +mod_version() { + sed --quiet 's/^[[:space:]]*version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "${REPO_ROOT}/settings.gradle.kts" } # Downloads java/projectzomboid.jar of the dedicated server and prints its path. @@ -94,9 +96,12 @@ build() { local project local game_jar="${GAME_JAR:-}" - project="$(project_version)" + project="$(mod_version)" + if [[ -z "${project}" ]]; then + fail "No version line in settings.gradle.kts." + fi if [[ "${project}" != "${version}" ]]; then - fail "The tag '${tag}' does not match the version '${project}' in build.gradle.kts." + fail "The tag '${tag}' does not match the version '${project}' in settings.gradle.kts." fi if [[ -z "${game_jar}" ]]; then diff --git a/settings.gradle.kts b/settings.gradle.kts index 6360a32..dc0b7d8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,15 +1,14 @@ pluginManagement { - repositories { - maven("https://git.security-command.org/api/packages/overlord/maven") - gradlePluginPortal() - } + repositories { maven("https://git.security-command.org/api/packages/overlord/maven") } } -dependencyResolutionManagement { - repositories { - maven("https://git.security-command.org/api/packages/overlord/maven") - mavenCentral() - } +plugins { + id("dev.overlord.zomboidforge") version "0.6.0" // the plugin's version is the ZomboidForge API version } -rootProject.name = "LuaModAutomator" +zomboidForge { + id = "lua_mod_automator" + name = "LuaModAutomator" + version = "0.2.0" + entrypoint = "dev.overlord.luamodautomator.LuaModAutomatorMod" +} diff --git a/src/main/java/dev/overlord/luamodautomator/CollectionCommand.java b/src/main/java/dev/overlord/luamodautomator/CollectionCommand.java index 0d67e47..422b218 100644 --- a/src/main/java/dev/overlord/luamodautomator/CollectionCommand.java +++ b/src/main/java/dev/overlord/luamodautomator/CollectionCommand.java @@ -1,5 +1,7 @@ package dev.overlord.luamodautomator; +import dev.overlord.zomboidforge.api.annotations.RegisterCommand; + import org.jetbrains.annotations.Nullable; import zombie.characters.Capability; @@ -15,7 +17,9 @@ import zombie.core.raknet.UdpConnection; * {@code /collection}: where the running mod list comes from and the result of the last drift * check. {@code /collection check} starts a drift check on the mod thread. Works in the chat, * the server console, and RCON; needs the capability of vanilla's {@code checkModsNeedUpdate}. + * ZomboidForge registers it before {@link LuaModAutomatorMod#onLoad()}. */ +@RegisterCommand @CommandName(name = "collection") @CommandArgs(optional = "(\\S+)") @CommandHelp(helpText = "collection [check]: shows where the mod list comes from and the last drift check; 'check' starts a drift check", shouldTranslated = false) diff --git a/src/main/java/dev/overlord/luamodautomator/CollectionResolver.java b/src/main/java/dev/overlord/luamodautomator/CollectionResolver.java index 5434b80..ce02d42 100644 --- a/src/main/java/dev/overlord/luamodautomator/CollectionResolver.java +++ b/src/main/java/dev/overlord/luamodautomator/CollectionResolver.java @@ -225,27 +225,43 @@ final class CollectionResolver pinned.sort(Comparator.comparingInt(id -> overrides.get(id).position().orElseThrow())); + // All pinned items out first: removing one later would shift those placed before it. + ordered.removeAll(pinned); + for (String id : pinned) { - ordered.remove(id); ordered.add(Math.clamp(overrides.get(id).position().orElseThrow() - 1, 0, ordered.size()), id); } return ordered.stream().map(byId::get).toList(); } + /** + * Warns about Mod IDs named by two items, which {@code Mods=} lists once, and about Mod IDs + * that differ only in case, which it lists as written, since references ignore case but + * Project Zomboid may not. + */ private static void duplicateModIds(List items, List warnings) { - Map first = new HashMap<>(); + Map first = new HashMap<>(); + Map spellings = new HashMap<>(); for (Resolution.Item item : items) { for (String modId : item.modIds()) { - Resolution.Item other = first.putIfAbsent(modId, item); + Resolution.Item other = first.putIfAbsent(modId, item); + String spelling = spellings.putIfAbsent(modId.toLowerCase(Locale.ROOT), modId); if (other != null && other != item) + { warnings.add("Mod ID '" + modId + "' is named by '" + other.title() + "' (" + other.id() + ") and '" + item.title() + "' (" + item.id() + "); Mods= lists it once."); + } + else if (spelling != null && !spelling.equals(modId)) + { + Resolution.Item owner = first.get(spelling); + warnings.add("Mod IDs '" + spelling + "' of '" + owner.title() + "' (" + owner.id() + ") and '" + modId + "' of '" + item.title() + "' (" + item.id() + ") differ only in case; Mods= lists both."); + } } } } diff --git a/src/main/java/dev/overlord/luamodautomator/DescriptionParser.java b/src/main/java/dev/overlord/luamodautomator/DescriptionParser.java index 0df625c..2391ce1 100644 --- a/src/main/java/dev/overlord/luamodautomator/DescriptionParser.java +++ b/src/main/java/dev/overlord/luamodautomator/DescriptionParser.java @@ -3,6 +3,7 @@ package dev.overlord.luamodautomator; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -18,14 +19,23 @@ final class DescriptionParser private static final Pattern MOD_IDS = Pattern.compile("(?im)^\\s*Mod\\s*IDs?\\h*[:=]\\h*(.+)$"); private static final Pattern MAP_LINE = Pattern.compile("(?im)^\\s*Map\\s*Folder\\h*[:=]"); private static final Pattern MAP_FOLDER = Pattern.compile("(?im)^\\s*Map\\s*Folder\\h*[:=]\\h*(.+)$"); - private static final Pattern SEPARATOR = Pattern.compile("[\\s,;]+"); - private static final Pattern MOD_ID = Pattern.compile("[A-Za-z0-9_.\\-]+"); + private static final Pattern COMMENT = Pattern.compile("\\h+[-–—]\\h.*$"); + private static final Pattern SEPARATOR = Pattern.compile("[\\s,;/]+"); + private static final Pattern MOD_ID = Pattern.compile("[A-Za-z0-9_.\\-]*[A-Za-z0-9][A-Za-z0-9_.\\-]*"); + + /** Words between Mod IDs, as in {@code Mod ID: Foo or Foo_Lite}. */ + private static final Set CONJUNCTIONS = Set.of("or", "and"); private DescriptionParser() {} static String stripBbcode(String description) { return DescriptionParser.BBCODE.matcher(description).replaceAll(""); } - /** Every Mod ID of every {@code Mod ID} line, each once, in order of appearance. */ + /** + * Every Mod ID of every {@code Mod ID} line, each once, in order of appearance. Mod IDs are + * separated by spaces, {@code ,}, {@code ;}, {@code /}, {@code or}, or {@code and}; a dash + * between spaces ({@code Foo - B42 only}) starts a comment that ends the line; tokens + * without a letter or digit, or with other characters, are skipped. + */ static List modIds(String description) { Set modIds = new LinkedHashSet<>(); @@ -33,9 +43,11 @@ final class DescriptionParser while (matcher.find()) { - for (String token : DescriptionParser.SEPARATOR.split(matcher.group(1).strip())) + String line = DescriptionParser.COMMENT.matcher(matcher.group(1)).replaceFirst(""); + + for (String token : DescriptionParser.SEPARATOR.split(line.strip())) { - if (DescriptionParser.MOD_ID.matcher(token).matches()) modIds.add(token); + if (DescriptionParser.MOD_ID.matcher(token).matches() && !DescriptionParser.CONJUNCTIONS.contains(token.toLowerCase(Locale.ROOT))) modIds.add(token); } } diff --git a/src/main/java/dev/overlord/luamodautomator/LuaModAutomatorMod.java b/src/main/java/dev/overlord/luamodautomator/LuaModAutomatorMod.java index 3e96849..bd10ec3 100644 --- a/src/main/java/dev/overlord/luamodautomator/LuaModAutomatorMod.java +++ b/src/main/java/dev/overlord/luamodautomator/LuaModAutomatorMod.java @@ -33,23 +33,33 @@ import org.jetbrains.annotations.Nullable; * *

While the server runs, a drift check resolves the collection again every * {@code [drift] interval_min} minutes and logs how it differs from what the server runs, and - * which items were updated on Steam since startup. Changes take effect at the next restart. + * which items have a newer version on Steam than the server downloaded. Changes take effect at + * the next restart. * - *

Threads: game objects ({@code ServerOptions}) on the main thread only, in {@link #onLoad()} - * and {@link CollectionCommand}; drift checks on the mod thread. + *

Threads: game objects ({@code ServerOptions}, {@code SteamWorkshop}) on the main thread + * only, in {@link #onLoad()}, {@link #onServerStarted()}, and {@link CollectionCommand}; drift + * checks on the mod thread. */ public final class LuaModAutomatorMod extends Mod { - private static final String NO_CHECK = "No drift check yet."; - private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC); + private static final String NO_CHECK = "No drift check yet."; + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC); + private static final Duration RETRY_DELAY = Duration.ofSeconds(2); /** The loaded instance, for {@link CollectionCommand}, which Project Zomboid creates. */ private static volatile @Nullable LuaModAutomatorMod instance; - /** When the server started; the Workshop download comes after this, so later Steam updates are not on the server. */ + /** + * When the mod loaded, before the Workshop download. Stands in for the installed version of + * items Steam does not report (no Steam mode), on the side of reporting updates the server + * may already have downloaded. + */ private final Instant startedAt = Instant.now(); private final AtomicBoolean checkQueued = new AtomicBoolean(); + /** {@link WorkshopAdapter#installedVersions}, set in {@link #onServerStarted()}, after the Workshop download. */ + private volatile Map installed = Map.of(); + // Set in onLoad(), read later. Tasks submitted after onLoad() see these values. private @Nullable Settings settings; private @Nullable String collectionId; @@ -73,7 +83,6 @@ public final class LuaModAutomatorMod extends Mod public void onLoad() { LuaModAutomatorMod.instance = this; - this.commands().register(CollectionCommand.class); this.running = ServerOptionsAdapter.read(); @@ -115,7 +124,7 @@ public final class LuaModAutomatorMod extends Mod try { - Resolution resolution = this.resolve(); + Resolution resolution = this.resolveAtStartup(); ServerValues values = resolution.values(settings.ini().baseMap()); this.logWarnings(resolution.warnings()); @@ -128,10 +137,14 @@ public final class LuaModAutomatorMod extends Mod } catch (SteamException | ConfigurationException e) { - String reason = Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()); - - this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + reason); - this.fallBack(reason.endsWith(".") ? reason.substring(0, reason.length() - 1) : reason); + this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + LuaModAutomatorMod.reason(e) + "."); + this.fallBack(LuaModAutomatorMod.reason(e)); + } + catch (RuntimeException e) + { + // An exception that leaves onLoad() stops the server. + this.logger().log(ERROR, "Cannot resolve collection '" + this.collectionId + "'.", e); + this.fallBack(e.toString()); } this.log(INFO, this.startup); @@ -141,7 +154,18 @@ public final class LuaModAutomatorMod extends Mod public void onServerStarted() { Settings settings = this.settings; - if (settings == null || settings.drift().intervalMin() == 0) return; + if (settings == null) return; + + try + { + this.installed = WorkshopAdapter.installedVersions(this.running.workshopIds()); + } + catch (RuntimeException e) + { + this.logger().log(WARNING, "Cannot read the versions of the installed Workshop items; updates count from the server's start.", e); + } + + if (settings.drift().intervalMin() == 0) return; Duration interval = Duration.ofMinutes(settings.drift().intervalMin()); this.modThread().scheduleWithFixedDelay(this::scheduledCheck, interval, interval); @@ -272,7 +296,7 @@ public final class LuaModAutomatorMod extends Mod this.lastCheck = "Last drift check " + time + ": " + (drift.isEmpty() ? "the collection matches the running mod list." : "the collection differs: " + difference + "; restart the server to apply it.") - + (updated.isEmpty() ? "" : "\nUpdated on Steam since startup: " + String.join(", ", updated) + "; restart the server to load the updates."); + + (updated.isEmpty() ? "" : "\nNewer on Steam than on the server: " + String.join(", ", updated) + "; restart the server to load the updates."); } catch (SteamException | ConfigurationException e) { @@ -294,28 +318,58 @@ public final class LuaModAutomatorMod extends Mod } /** - * Items the server runs that Steam updated after the server started, as {@code 'title' (id)}; - * logs each update once. Mod thread. + * Items the server runs that have a newer version on Steam than the installed one (or, when + * Steam does not report it, than {@link #startedAt}), as {@code 'title' (id)}; logs each + * update once. Mod thread. */ private List updatedItems(Resolution resolution) { - Set running = new HashSet<>(this.running.workshopIds()); - List updated = new ArrayList<>(); + Set running = new HashSet<>(this.running.workshopIds()); + Map installed = this.installed; + List updated = new ArrayList<>(); for (Resolution.Item item : resolution.items()) { - if (!running.contains(item.id()) || item.timeUpdated() <= this.startedAt.getEpochSecond()) continue; + if (!running.contains(item.id()) || item.timeUpdated() <= installed.getOrDefault(item.id(), this.startedAt.getEpochSecond())) continue; String name = "'" + item.title() + "' (" + item.id() + ")"; updated.add(name); if (!Objects.equals(this.reportedUpdates.put(item.id(), item.timeUpdated()), item.timeUpdated())) - this.log(WARNING, name + " was updated on Steam at " + LuaModAutomatorMod.TIME.format(Instant.ofEpochSecond(item.timeUpdated())) + ", after the server started. Restart the server to load the update; clients with the new version may not be able to join until then."); + this.log(WARNING, name + " was updated on Steam at " + LuaModAutomatorMod.TIME.format(Instant.ofEpochSecond(item.timeUpdated())) + ", after the version the server downloaded. Restart the server to load the update; clients with the new version may not be able to join until then."); } return updated; } + /** + * {@link #resolve()}, tried once more after {@link #RETRY_DELAY} when Steam fails. Main + * thread, in {@link #onLoad()}, before the server runs. + */ + private Resolution resolveAtStartup() throws SteamException, ConfigurationException + { + try + { + return this.resolve(); + } + catch (SteamException e) + { + this.log(WARNING, "Cannot resolve collection '" + this.collectionId + "': " + LuaModAutomatorMod.reason(e) + "; retrying in " + LuaModAutomatorMod.RETRY_DELAY.toSeconds() + " seconds."); + + try + { + Thread.sleep(LuaModAutomatorMod.RETRY_DELAY); + } + catch (InterruptedException interrupted) + { + Thread.currentThread().interrupt(); + throw e; + } + + return this.resolve(); + } + } + private Resolution resolve() throws SteamException, ConfigurationException { Settings settings = Objects.requireNonNull(this.settings); @@ -386,6 +440,13 @@ public final class LuaModAutomatorMod extends Mod private void log(System.Logger.Level level, String message) { this.logger().log(level, message); } + /** The message of {@code e}, without a final period. */ + private static String reason(Exception e) + { + String reason = Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()); + return reason.endsWith(".") ? reason.substring(0, reason.length() - 1) : reason; + } + private static String counts(ServerValues values) { return LuaModAutomatorMod.count(values.workshopIds().size(), "Workshop item") + ", " + LuaModAutomatorMod.count(values.modIds().size(), "Mod ID") + ", Map=" + values.map(); diff --git a/src/main/java/dev/overlord/luamodautomator/Resolution.java b/src/main/java/dev/overlord/luamodautomator/Resolution.java index e19542b..bb1e056 100644 --- a/src/main/java/dev/overlord/luamodautomator/Resolution.java +++ b/src/main/java/dev/overlord/luamodautomator/Resolution.java @@ -51,10 +51,11 @@ record Resolution(List items, List excluded, L */ List modList() { + // Widths start at 1: "%-0s" is not a valid format. List lines = new ArrayList<>(); int number = String.valueOf(this.items.size()).length(); - int title = 0; - int modIds = 0; + int title = 1; + int modIds = 1; for (Item item : this.items) { diff --git a/src/main/java/dev/overlord/luamodautomator/Settings.java b/src/main/java/dev/overlord/luamodautomator/Settings.java index 9b92000..afa7bf4 100644 --- a/src/main/java/dev/overlord/luamodautomator/Settings.java +++ b/src/main/java/dev/overlord/luamodautomator/Settings.java @@ -1,5 +1,7 @@ package dev.overlord.luamodautomator; +import dev.overlord.zomboidforge.api.annotations.Min; + import java.util.List; import java.util.Map; import java.util.Optional; @@ -21,22 +23,10 @@ record Settings(String collection, Settings.Ini ini, Settings.Steam steam, Setti record Ini(boolean write, boolean manageMap, List baseMap) {} /** @param timeoutS seconds per Steam Web API request */ - record Steam(int timeoutS) - { - Steam - { - if (timeoutS < 1) throw new IllegalArgumentException("'timeout_s' must be at least 1, found " + timeoutS); - } - } + record Steam(@Min(1) int timeoutS) {} /** @param intervalMin minutes between drift checks while the server runs; 0 turns them off */ - record Drift(int intervalMin) - { - Drift - { - if (intervalMin < 0) throw new IllegalArgumentException("'interval_min' must be 0 or more, found " + intervalMin); - } - } + record Drift(@Min(0) int intervalMin) {} /** * @param buckets the bucket sequence of the load order @@ -53,15 +43,10 @@ record Settings(String collection, Settings.Ini ini, Settings.Steam steam, Setti * @param position 1-based place in the final list, applied after {@code priority} * @param exclude whether the item is left out of {@code Mods=}, {@code WorkshopItems=}, and {@code Map=} */ - record Item(Optional> modIds, Optional title, Optional bucket, Optional position, Optional exclude) + record Item(Optional> modIds, Optional title, Optional bucket, @Min(1) Optional position, Optional exclude) { static final Item NONE = new Item(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); - Item - { - if (position.isPresent() && position.get() < 1) throw new IllegalArgumentException("'position' must be at least 1, found " + position.get()); - } - boolean excluded() { return this.exclude.orElse(false); } /** These overrides, with the fields this item does not set taken from {@code other}. */ diff --git a/src/main/java/dev/overlord/luamodautomator/SteamWorkshopApi.java b/src/main/java/dev/overlord/luamodautomator/SteamWorkshopApi.java index 410e1c9..edaf5d2 100644 --- a/src/main/java/dev/overlord/luamodautomator/SteamWorkshopApi.java +++ b/src/main/java/dev/overlord/luamodautomator/SteamWorkshopApi.java @@ -44,7 +44,8 @@ final class SteamWorkshopApi implements AutoCloseable /** {@code filetype} of a child that is itself a collection. */ private static final int COLLECTION = 2; - private static final Pattern COLLECTION_ID = Pattern.compile("(?:[?&]id=)?(\\d{2,})"); + private static final Pattern ID_PARAMETER = Pattern.compile("[?&]id=(\\d{2,})"); + private static final Pattern BARE_ID = Pattern.compile("\\d{2,}"); private final HttpClient client; private final URI base; @@ -59,11 +60,19 @@ final class SteamWorkshopApi implements AutoCloseable this.userAgent = userAgent; } - /** The collection id in {@code setting}, a collection URL or a bare id. */ + /** + * The collection id in {@code setting}: the {@code id} parameter of a collection URL, which + * may have other numeric parameters such as {@code tscn}, or a bare id. + */ static Optional collectionId(String setting) { - Matcher matcher = SteamWorkshopApi.COLLECTION_ID.matcher(setting.strip()); - return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); + String value = setting.strip(); + Matcher matcher = SteamWorkshopApi.ID_PARAMETER.matcher(value); + + if (matcher.find()) return Optional.of(matcher.group(1)); + if (SteamWorkshopApi.BARE_ID.matcher(value).matches()) return Optional.of(value); + + return Optional.empty(); } /** diff --git a/src/main/java/dev/overlord/luamodautomator/WorkshopAdapter.java b/src/main/java/dev/overlord/luamodautomator/WorkshopAdapter.java new file mode 100644 index 0000000..d140407 --- /dev/null +++ b/src/main/java/dev/overlord/luamodautomator/WorkshopAdapter.java @@ -0,0 +1,50 @@ +package dev.overlord.luamodautomator; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import zombie.core.znet.SteamUtils; +import zombie.core.znet.SteamWorkshop; + +/** + * The versions of the Workshop items installed on the server. Main thread only. + * + *

Steam reports, for an installed item, when the installed version was updated on the + * Workshop; {@code GameServerWorkshopItems} compares it with Steam's {@code time_updated} to + * decide whether an item needs an update (Project Zomboid 42.21). + */ +final class WorkshopAdapter +{ + private WorkshopAdapter() {} + + /** + * For each of {@code ids}, when its installed version was updated on the Workshop, in + * seconds since the epoch. Ids that are not installed or not numeric are left out; all of + * them without Steam mode. + */ + static Map installedVersions(List ids) + { + if (!SteamUtils.isSteamModeEnabled()) return Map.of(); + + Map versions = new HashMap<>(); + + for (String id : ids) + { + long timeUpdated; + + try + { + timeUpdated = SteamWorkshop.instance.GetItemInstallTimeStamp(Long.parseLong(id)); + } + catch (NumberFormatException e) + { + continue; + } + + if (timeUpdated > 0) versions.put(id, timeUpdated); + } + + return Map.copyOf(versions); + } +} diff --git a/src/main/java/dev/overlord/luamodautomator/package-info.java b/src/main/java/dev/overlord/luamodautomator/package-info.java index 310f11d..5127a86 100644 --- a/src/main/java/dev/overlord/luamodautomator/package-info.java +++ b/src/main/java/dev/overlord/luamodautomator/package-info.java @@ -2,10 +2,12 @@ * LuaModAutomator: the server's {@code Mods=}, {@code WorkshopItems=}, and {@code Map=} come * from a public Steam Workshop collection, resolved at every start. * - *

Only {@link dev.overlord.luamodautomator.LuaModAutomatorMod}, - * {@link dev.overlord.luamodautomator.ServerOptionsAdapter}, and - * {@link dev.overlord.luamodautomator.CollectionCommand} use game classes; everything else runs - * without the game. + *

Only + * {@link dev.overlord.luamodautomator.LuaModAutomatorMod}, + * {@link dev.overlord.luamodautomator.ServerOptionsAdapter}, + * {@link dev.overlord.luamodautomator.WorkshopAdapter}, and + * {@link dev.overlord.luamodautomator.CollectionCommand} use game classes; + * everything else runs without the game. * * @noinspection UnstableApiUsage, RedundantSuppression */ diff --git a/src/test/java/dev/overlord/luamodautomator/CollectionResolverTest.java b/src/test/java/dev/overlord/luamodautomator/CollectionResolverTest.java index 3727aec..7b3e821 100644 --- a/src/test/java/dev/overlord/luamodautomator/CollectionResolverTest.java +++ b/src/test/java/dev/overlord/luamodautomator/CollectionResolverTest.java @@ -73,7 +73,24 @@ class CollectionResolverTest Resolution resolution = CollectionResolver.resolve(CollectionResolverTest.COLLECTION, order, items); - assertEquals(List.of("100", "200", "300", "400", "500"), CollectionResolverTest.ids(resolution)); + assertEquals(List.of("100", "300", "200", "400", "500"), CollectionResolverTest.ids(resolution)); + } + + @Test + void pinsKeepTheirPlaceWhenALaterPinStartsAheadOfThem() throws ConfigurationException + { + List collection = List.of( + CollectionResolverTest.item("1", "B", "Mod ID: B"), + CollectionResolverTest.item("2", "X", "Mod ID: X"), + CollectionResolverTest.item("3", "Y", "Mod ID: Y"), + CollectionResolverTest.item("4", "P", "Mod ID: P"), + CollectionResolverTest.item("5", "Z", "Mod ID: Z") + ); + Map items = Map.of("P", CollectionResolverTest.position(3), "B", CollectionResolverTest.position(4)); + + Resolution resolution = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, items); + + assertEquals(List.of("2", "3", "4", "1", "5"), CollectionResolverTest.ids(resolution)); } @Test @@ -169,6 +186,16 @@ class CollectionResolverTest assertEquals(1, resolution.warnings().size()); } + @Test + void modIdsDifferingOnlyInCaseAreWarnedAboutAndBothListed() throws ConfigurationException + { + List collection = List.of(CollectionResolverTest.item("100", "One", "Mod ID: Shared"), CollectionResolverTest.item("200", "Two", "Mod ID: shared")); + Resolution resolution = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, Map.of()); + + assertEquals("\\Shared;\\shared", resolution.values(List.of()).mods()); + assertEquals(List.of("Mod IDs 'Shared' of 'One' (100) and 'shared' of 'Two' (200) differ only in case; Mods= lists both."), resolution.warnings()); + } + @Test void mapFoldersThenBaseMapEachOnce() throws ConfigurationException { @@ -200,6 +227,15 @@ class CollectionResolverTest ), modList); } + @Test + void modListWithAnEmptyTitle() throws ConfigurationException + { + List collection = List.of(CollectionResolverTest.item("100", "Misc One", "Mod ID: MiscOne")); + Map items = Map.of("100", new Settings.Item(Optional.empty(), Optional.of(""), Optional.empty(), Optional.empty(), Optional.empty())); + + assertEquals(List.of("Mod List:", "1. 100 MiscOne"), CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, items).modList()); + } + private static List ids(Resolution resolution) { return resolution.items().stream().map(Resolution.Item::id).toList(); } private static WorkshopItem item(String id, String title, String description) { return WorkshopItem.of(id, title, description, List.of("Build 42"), 0); } diff --git a/src/test/java/dev/overlord/luamodautomator/DescriptionParserTest.java b/src/test/java/dev/overlord/luamodautomator/DescriptionParserTest.java index cc6d163..dd6f485 100644 --- a/src/test/java/dev/overlord/luamodautomator/DescriptionParserTest.java +++ b/src/test/java/dev/overlord/luamodautomator/DescriptionParserTest.java @@ -43,6 +43,30 @@ class DescriptionParserTest assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo (Bar) Bar")); } + @Test + void modIdsSkipTokensWithoutLetterOrDigit() + { + assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo -- Bar ...")); + } + + @Test + void modIdsSeparatedByWords() + { + assertEquals(List.of("Foo", "Foo_Lite", "Bar", "Baz"), DescriptionParser.modIds("Mod ID: Foo or Foo_Lite\nMod IDs: Bar AND Baz")); + } + + @Test + void modIdsSeparatedBySlashes() + { + assertEquals(List.of("Foo", "FooLite"), DescriptionParser.modIds("Mod ID: Foo/FooLite")); + } + + @Test + void spacedDashStartsAComment() + { + assertEquals(List.of("Bar", "Baz-Lite"), DescriptionParser.modIds("Mod ID: Bar - B42 only\nMod ID: Baz-Lite – optional")); + } + @Test void emptyModIdLineDoesNotReadTheNextLine() { diff --git a/src/test/java/dev/overlord/luamodautomator/SettingsTest.java b/src/test/java/dev/overlord/luamodautomator/SettingsTest.java index 2d13514..7b6d8b6 100644 --- a/src/test/java/dev/overlord/luamodautomator/SettingsTest.java +++ b/src/test/java/dev/overlord/luamodautomator/SettingsTest.java @@ -102,13 +102,20 @@ class SettingsTest @Test void invalidValues() { - assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[steam]\ntimeout_s = 0")); - assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[drift]\ninterval_min = -1")); - assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[items.123]\nposition = 0")); assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[items.123]\nmod_ids = \"Foo\"")); assertThrows(IllegalStateException.class, () -> SettingsTest.bind("collection = 123")); } + @Test + void valuesOutOfBoundsAreReportedTogetherWithTheirKeys() + { + String message = assertThrows(IllegalStateException.class, () -> SettingsTest.bind("[steam]\ntimeout_s = 0\n[drift]\ninterval_min = -1\n[items.123]\nposition = 0")).getMessage(); + + assertTrue(message.contains("'steam.timeout_s' must be at least 1, found 0."), message); + assertTrue(message.contains("'drift.interval_min' must be at least 0, found -1."), message); + assertTrue(message.contains("'items.123.position' must be at least 1, found 0."), message); + } + static Settings bind(String overrides) { return SettingsTest.bind(overrides, new CopyOnWriteArrayList<>()); } /** The shipped defaults with {@code overrides} on top, bound like the server binds them; warnings go to {@code warnings}. */ diff --git a/src/test/java/dev/overlord/luamodautomator/SteamWorkshopApiTest.java b/src/test/java/dev/overlord/luamodautomator/SteamWorkshopApiTest.java index 8e6e265..eb7b2aa 100644 --- a/src/test/java/dev/overlord/luamodautomator/SteamWorkshopApiTest.java +++ b/src/test/java/dev/overlord/luamodautomator/SteamWorkshopApiTest.java @@ -73,8 +73,10 @@ class SteamWorkshopApiTest { assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?id=1234567890")); assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?searchtext=&id=1234567890")); + assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?tscn=1712345678&id=1234567890")); assertEquals(Optional.of("1234567890"), SteamWorkshopApi.collectionId(" 1234567890 ")); assertEquals(Optional.empty(), SteamWorkshopApi.collectionId("my collection")); + assertEquals(Optional.empty(), SteamWorkshopApi.collectionId("https://steamcommunity.com/sharedfiles/filedetails/?tscn=1712345678")); } @Test