Compare commits
4
Commits
v0.1.0-dev
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee4be1a5b6 | ||
|
|
0763730a24 | ||
|
|
389b5b19d7 | ||
|
|
322092729f |
No files matched your search
@@ -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,13 @@ 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.<id>] 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`. A Mod
|
||||
ID may contain spaces (`Mod ID: Nicks Moveable Workstations - Furniture Fix`); `Mods=` then
|
||||
lists it as written, with a warning until `[items.<id>] mod_ids` confirms or corrects it. An
|
||||
item without one stays in `WorkshopItems=` (so the server downloads it) but is left out of
|
||||
`Mods=`, with a warning; `[items.<id>] 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 +66,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 +123,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 +134,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 +169,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<version>` that matches `version` in `build.gradle.kts` builds the mod and
|
||||
Pushing a tag `v<version>` 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.
|
||||
|
||||
+4
-12
@@ -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")
|
||||
|
||||
+10
-5
@@ -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
|
||||
|
||||
+9
-10
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -66,6 +66,16 @@ final class CollectionResolver
|
||||
warnings.add("Steam returns no details for " + item.id() + " (private, unlisted, or removed); it stays in WorkshopItems= but not in Mods=. Set [items." + item.id() + "] mod_ids to load it.");
|
||||
}
|
||||
|
||||
// Mod IDs may contain spaces, but "Mod ID: Foo Bar" may also mean two of them.
|
||||
if (override.modIds().isEmpty())
|
||||
{
|
||||
for (String modId : result.modIds())
|
||||
{
|
||||
if (modId.chars().anyMatch(Character::isWhitespace))
|
||||
warnings.add("'" + result.title() + "' (" + item.id() + ") names the Mod ID '" + modId + "', which contains spaces; Mods= lists it as written. Set [items." + item.id() + "] mod_ids to confirm or correct it.");
|
||||
}
|
||||
}
|
||||
|
||||
if (item.map() && item.mapFolders().isEmpty())
|
||||
warnings.add("'" + result.title() + "' (" + item.id() + ") has a Map Folder line without a folder name; it adds nothing to Map=.");
|
||||
|
||||
@@ -225,28 +235,44 @@ 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<Resolution.Item> items, List<String> warnings)
|
||||
{
|
||||
Map<String, Resolution.Item> first = new HashMap<>();
|
||||
Map<String, String> spellings = new HashMap<>();
|
||||
|
||||
for (Resolution.Item item : items)
|
||||
{
|
||||
for (String modId : item.modIds())
|
||||
{
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,14 +18,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 SEPARATOR = Pattern.compile("[,;]");
|
||||
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
|
||||
|
||||
/** Words of letters, digits, {@code _}, {@code .}, and {@code -}, separated by spaces; with at least one letter or digit. */
|
||||
private static final Pattern MOD_ID = Pattern.compile("(?=.*[A-Za-z0-9])[A-Za-z0-9_.\\-]+(?:\\h+[A-Za-z0-9_.\\-]+)*");
|
||||
|
||||
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 on
|
||||
* one line are separated by {@code ,} or {@code ;}, and may contain spaces
|
||||
* ({@code Nicks Moveable Workstations - Furniture Fix}, as in its {@code mod.info}). A part
|
||||
* with other characters ({@code Foo (B41)}) yields those of its words that are Mod IDs; parts
|
||||
* without a letter or digit yield none.
|
||||
*/
|
||||
static List<String> modIds(String description)
|
||||
{
|
||||
Set<String> modIds = new LinkedHashSet<>();
|
||||
@@ -33,11 +42,22 @@ final class DescriptionParser
|
||||
|
||||
while (matcher.find())
|
||||
{
|
||||
for (String token : DescriptionParser.SEPARATOR.split(matcher.group(1).strip()))
|
||||
for (String part : DescriptionParser.SEPARATOR.split(matcher.group(1)))
|
||||
{
|
||||
String modId = part.strip();
|
||||
|
||||
if (DescriptionParser.MOD_ID.matcher(modId).matches())
|
||||
{
|
||||
modIds.add(modId);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (String token : DescriptionParser.WHITESPACE.split(modId))
|
||||
{
|
||||
if (DescriptionParser.MOD_ID.matcher(token).matches()) modIds.add(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return List.copyOf(modIds);
|
||||
}
|
||||
|
||||
@@ -33,23 +33,33 @@ import org.jetbrains.annotations.Nullable;
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>Threads: game objects ({@code ServerOptions}) on the main thread only, in {@link #onLoad()}
|
||||
* and {@link CollectionCommand}; drift checks on the mod thread.
|
||||
* <p>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 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<String, Long> 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<String> updatedItems(Resolution resolution)
|
||||
{
|
||||
Set<String> running = new HashSet<>(this.running.workshopIds());
|
||||
Map<String, Long> installed = this.installed;
|
||||
List<String> 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();
|
||||
|
||||
@@ -51,10 +51,11 @@ record Resolution(List<Resolution.Item> items, List<Resolution.Item> excluded, L
|
||||
*/
|
||||
List<String> modList()
|
||||
{
|
||||
// Widths start at 1: "%-0s" is not a valid format.
|
||||
List<String> 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)
|
||||
{
|
||||
|
||||
@@ -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<String> 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<List<String>> modIds, Optional<String> title, Optional<String> bucket, Optional<Integer> position, Optional<Boolean> exclude)
|
||||
record Item(Optional<List<String>> modIds, Optional<String> title, Optional<String> bucket, @Min(1) Optional<Integer> position, Optional<Boolean> 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}. */
|
||||
|
||||
@@ -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<String> 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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<String, Long> installedVersions(List<String> ids)
|
||||
{
|
||||
if (!SteamUtils.isSteamModeEnabled()) return Map.of();
|
||||
|
||||
Map<String, Long> 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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
* <p>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
|
||||
*/
|
||||
|
||||
@@ -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<WorkshopItem> 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<String, Settings.Item> 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,28 @@ class CollectionResolverTest
|
||||
assertEquals(1, resolution.warnings().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modIdsDifferingOnlyInCaseAreWarnedAboutAndBothListed() throws ConfigurationException
|
||||
{
|
||||
List<WorkshopItem> 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 modIdWithSpacesIsListedWithAWarningUntilAnOverrideConfirmsIt() throws ConfigurationException
|
||||
{
|
||||
List<WorkshopItem> collection = List.of(CollectionResolverTest.item("3809993153", "Furniture Fix", "Mod ID: Nicks Moveable Workstations - Furniture Fix"));
|
||||
Resolution parsed = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, Map.of());
|
||||
Resolution confirmed = CollectionResolver.resolve(collection, CollectionResolverTest.DEFAULT_ORDER, Map.of("3809993153", CollectionResolverTest.modIds("Nicks Moveable Workstations - Furniture Fix")));
|
||||
|
||||
assertEquals("\\Nicks Moveable Workstations - Furniture Fix", parsed.values(List.of()).mods());
|
||||
assertEquals(List.of("'Furniture Fix' (3809993153) names the Mod ID 'Nicks Moveable Workstations - Furniture Fix', which contains spaces; Mods= lists it as written. Set [items.3809993153] mod_ids to confirm or correct it."), parsed.warnings());
|
||||
assertEquals(List.of(), confirmed.warnings());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapFoldersThenBaseMapEachOnce() throws ConfigurationException
|
||||
{
|
||||
@@ -200,6 +239,15 @@ class CollectionResolverTest
|
||||
), modList);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modListWithAnEmptyTitle() throws ConfigurationException
|
||||
{
|
||||
List<WorkshopItem> collection = List.of(CollectionResolverTest.item("100", "Misc One", "Mod ID: MiscOne"));
|
||||
Map<String, Settings.Item> 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<String> 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); }
|
||||
|
||||
@@ -43,6 +43,25 @@ class DescriptionParserTest
|
||||
assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo (Bar) Bar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modIdsSkipPartsWithoutLetterOrDigit()
|
||||
{
|
||||
assertEquals(List.of("Foo", "Bar"), DescriptionParser.modIds("Mod ID: Foo; --; Bar, ..."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modIdWithSpacesStaysWhole()
|
||||
{
|
||||
// 3809993153: mod.info has id=Nicks Moveable Workstations - Furniture Fix
|
||||
assertEquals(List.of("Nicks Moveable Workstations - Furniture Fix"), DescriptionParser.modIds("Mod id: Nicks Moveable Workstations - Furniture Fix\nid=3809993153"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modIdsWithSpacesSeparatedBySemicolons()
|
||||
{
|
||||
assertEquals(List.of("Foo Bar", "Baz"), DescriptionParser.modIds("Mod IDs: Foo Bar ; Baz"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyModIdLineDoesNotReadTheNextLine()
|
||||
{
|
||||
|
||||
@@ -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}. */
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user