forked from unimatrix/web
Merge pull request 'Connect existing Atelier kit menus to v3 metadata renderer' (#334) from dev/kit-atelier-v3 into main
This commit is contained in:
commit
77b62905c8
7 changed files with 348 additions and 1 deletions
|
|
@ -37,5 +37,5 @@ jobs:
|
|||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneKits
|
||||
path: DuneKits/build/libs/DuneKits-3.0.0.jar
|
||||
path: DuneKits/build/libs/*.jar
|
||||
if-no-files-found: error
|
||||
|
|
|
|||
|
|
@ -12,3 +12,12 @@ tasks.withType<JavaCompile> { options.encoding = "UTF-8"; options.release.set(21
|
|||
tasks.processResources { from("../network/server-control/kit-equipment-contract.json") }
|
||||
tasks.test { useJUnitPlatform() }
|
||||
tasks.jar { archiveFileName.set("DuneKits-3.0.0.jar") }
|
||||
|
||||
val compat by sourceSets.creating
|
||||
configurations[compat.compileOnlyConfigurationName].extendsFrom(configurations.compileOnly.get())
|
||||
val compatJar by tasks.registering(Jar::class) {
|
||||
archiveFileName.set("DuneAtelierCompat-3.0.0.jar")
|
||||
from(compat.output)
|
||||
}
|
||||
tasks.jar { dependsOn(compatJar) }
|
||||
sourceSets.test { compileClasspath += compat.output; runtimeClasspath += compat.output }
|
||||
|
|
|
|||
|
|
@ -0,0 +1,136 @@
|
|||
/*
|
||||
* Decompiled with CFR 0.152.
|
||||
*
|
||||
* Could not load the following classes:
|
||||
* com.google.gson.JsonArray
|
||||
* com.google.gson.JsonElement
|
||||
* com.google.gson.JsonObject
|
||||
* com.google.gson.JsonParser
|
||||
*/
|
||||
package com.dunerealms.atelier;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class DeliveryStore {
|
||||
static final List<String> TIERS = List.of("common", "uncommon", "rare", "very_rare", "legendary");
|
||||
|
||||
static String plain(JsonElement value, int limit) {
|
||||
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
|
||||
throw new IllegalArgumentException("Plain text required");
|
||||
}
|
||||
String raw = value.getAsString();
|
||||
String s = raw.strip();
|
||||
if (s.isEmpty() || s.codePointCount(0, s.length()) > limit || raw.chars().anyMatch(c -> c < 32 || c == 127 || c == 60 || c == 62 || c == 167)) {
|
||||
throw new IllegalArgumentException("Invalid design text");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
static Design parse(String json) {
|
||||
if (json == null || json.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 65536) {
|
||||
throw new IllegalArgumentException("Invalid design");
|
||||
}
|
||||
JsonObject o = JsonParser.parseString((String)json).getAsJsonObject();
|
||||
String id = DeliveryStore.plain(o.get("blueprintId"), 36);
|
||||
UUID.fromString(id);
|
||||
String quality = DeliveryStore.plain(o.get("quality"), 16);
|
||||
if (!TIERS.contains(quality)) {
|
||||
throw new IllegalArgumentException("Invalid quality");
|
||||
}
|
||||
String color = DeliveryStore.plain(o.get("color"), 7);
|
||||
if (!color.matches("#[0-9a-fA-F]{6}")) {
|
||||
throw new IllegalArgumentException("Invalid color");
|
||||
}
|
||||
JsonArray lines = o.getAsJsonArray("lore");
|
||||
if (lines == null || lines.size() > 6) {
|
||||
throw new IllegalArgumentException("Invalid lore");
|
||||
}
|
||||
ArrayList<String> lore = new ArrayList<String>();
|
||||
for (JsonElement line : lines) {
|
||||
if (!line.isJsonPrimitive() || !line.getAsJsonPrimitive().isString() || line.getAsString().length()>120 || line.getAsString().chars().anyMatch(v -> v<32 || v==127 || v==60 || v==62 || v==167)) throw new IllegalArgumentException("Invalid lore");
|
||||
lore.add(line.getAsString());
|
||||
}
|
||||
return new Design(id, DeliveryStore.plain(o.get("name"), 64), color, List.copyOf(lore), quality, json);
|
||||
}
|
||||
|
||||
public List<Pending> pending(Connection c, UUID player, boolean queuedOnly) throws SQLException {
|
||||
ArrayList<Pending> rows = new ArrayList<Pending>();
|
||||
try (PreparedStatement q = c.prepareStatement("SELECT id,snapshot_json FROM dune_kit_sales WHERE buyer_uuid=? AND delivered_at IS NULL" + (queuedOnly ? " AND redeem_requested_at IS NOT NULL" : "") + " ORDER BY completed_at,id LIMIT 25");){
|
||||
q.setString(1, player.toString());
|
||||
try (ResultSet r = q.executeQuery();){
|
||||
while (r.next()) {
|
||||
Design d = DeliveryStore.parse(r.getString(2));
|
||||
rows.add(new Pending(r.getString(1), d.name(), d.quality()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
public Design lock(Connection c, UUID player, UUID order) throws SQLException {
|
||||
if (c.getAutoCommit()) {
|
||||
throw new SQLException("Fenced inventory transaction required");
|
||||
}
|
||||
try (PreparedStatement q = c.prepareStatement("SELECT buyer_uuid,snapshot_json,delivered_at FROM dune_kit_sales WHERE id=? FOR UPDATE");){
|
||||
Design design;
|
||||
block14: {
|
||||
q.setString(1, order.toString());
|
||||
ResultSet r = q.executeQuery();
|
||||
try {
|
||||
if (!r.next() || !player.toString().equals(r.getString(1)) || r.getObject(3) != null) {
|
||||
throw new SQLException("Paid item receipt unavailable");
|
||||
}
|
||||
design = DeliveryStore.parse(r.getString(2));
|
||||
if (r == null) break block14;
|
||||
}
|
||||
catch (Throwable throwable) {
|
||||
if (r != null) {
|
||||
try {
|
||||
r.close();
|
||||
}
|
||||
catch (Throwable throwable2) {
|
||||
throwable.addSuppressed(throwable2);
|
||||
}
|
||||
}
|
||||
throw throwable;
|
||||
}
|
||||
r.close();
|
||||
}
|
||||
return design;
|
||||
}
|
||||
}
|
||||
|
||||
public void delivered(Connection c, UUID player, UUID order, long now) throws SQLException {
|
||||
if (c.getAutoCommit()) {
|
||||
throw new SQLException("Fenced inventory transaction required");
|
||||
}
|
||||
try (PreparedStatement q = c.prepareStatement("UPDATE dune_kit_sales SET delivered_at=?,redeem_requested_at=COALESCE(redeem_requested_at,?) WHERE id=? AND buyer_uuid=? AND delivered_at IS NULL");){
|
||||
q.setLong(1, now);
|
||||
q.setLong(2, now);
|
||||
q.setString(3, order.toString());
|
||||
q.setString(4, player.toString());
|
||||
if (q.executeUpdate() != 1) {
|
||||
throw new SQLException("Item receipt already consumed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Design(String id, String name, String color, List<String> lore, String quality, String snapshot) {
|
||||
public Design(String id, String name, String color, List<String> lore, String quality) { this(id,name,color,lore,quality,null); }
|
||||
}
|
||||
|
||||
public record Pending(String id, String name, String quality) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
122
DuneKits/src/compat/java/com/dunerealms/atelier/KitFactory.java
Normal file
122
DuneKits/src/compat/java/com/dunerealms/atelier/KitFactory.java
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
/*
|
||||
* Decompiled with CFR 0.152.
|
||||
*
|
||||
* Could not load the following classes:
|
||||
* net.kyori.adventure.text.Component
|
||||
* net.kyori.adventure.text.TextComponent
|
||||
* net.kyori.adventure.text.format.NamedTextColor
|
||||
* net.kyori.adventure.text.format.TextColor
|
||||
* org.bukkit.Color
|
||||
* org.bukkit.NamespacedKey
|
||||
* org.bukkit.inventory.ItemStack
|
||||
* org.bukkit.inventory.meta.ArmorMeta
|
||||
* org.bukkit.inventory.meta.ItemMeta
|
||||
* org.bukkit.inventory.meta.LeatherArmorMeta
|
||||
* org.bukkit.inventory.meta.trim.ArmorTrim
|
||||
* org.bukkit.persistence.PersistentDataType
|
||||
*/
|
||||
package com.dunerealms.atelier;
|
||||
|
||||
import com.dunerealms.atelier.DeliveryStore;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ArmorMeta;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.inventory.meta.LeatherArmorMeta;
|
||||
import org.bukkit.inventory.meta.trim.ArmorTrim;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
final class KitFactory {
|
||||
KitFactory() {
|
||||
}
|
||||
|
||||
static List<ItemStack> decorate(List<?> base, DeliveryStore.Design d, UUID order) {
|
||||
if (d.snapshot()!=null && com.google.gson.JsonParser.parseString(d.snapshot()).getAsJsonObject().has("equipment")) {
|
||||
org.bukkit.plugin.Plugin plugin=org.bukkit.Bukkit.getPluginManager().getPlugin("DuneKits");
|
||||
if(plugin==null || !plugin.isEnabled()) throw new IllegalStateException("Kit delivery unavailable; receipt retained");
|
||||
try {
|
||||
@SuppressWarnings("unchecked") List<ItemStack> rendered=(List<ItemStack>)plugin.getClass().getMethod("decoratePurchasedKit",String.class,List.class,UUID.class).invoke(plugin,d.snapshot(),base,order);
|
||||
return rendered;
|
||||
} catch (ReflectiveOperationException ex) { throw new IllegalStateException("Kit rendering unavailable; receipt retained",ex); }
|
||||
}
|
||||
if (!DeliveryStore.TIERS.contains(d.quality())) {
|
||||
throw new IllegalArgumentException("Invalid cosmetic rarity");
|
||||
}
|
||||
ArrayList<ItemStack> pieces = new ArrayList<ItemStack>();
|
||||
for (Object value : base) {
|
||||
ItemStack original;
|
||||
if (!(value instanceof ItemStack) || !((original = (ItemStack)value).getItemMeta() instanceof LeatherArmorMeta)) continue;
|
||||
ItemStack copy = original.clone();
|
||||
LeatherArmorMeta meta = (LeatherArmorMeta)copy.getItemMeta();
|
||||
meta.setColor(Color.fromRGB((int)Integer.parseInt(d.color().substring(1), 16)));
|
||||
meta.displayName((Component)Component.text((String)(d.name() + " " + copy.getType().name().replace("LEATHER_", "").toLowerCase(Locale.ROOT)), (TextColor)NamedTextColor.GOLD));
|
||||
String label = Arrays.stream(d.quality().split("_")).map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1)).collect(Collectors.joining(" "));
|
||||
ArrayList<TextComponent> lore = new ArrayList<TextComponent>();
|
||||
lore.add(Component.text((String)("Quality: " + label), (TextColor)NamedTextColor.GREEN));
|
||||
for (String line : d.lore()) {
|
||||
lore.add(Component.text((String)line, (TextColor)NamedTextColor.GRAY));
|
||||
}
|
||||
meta.lore(lore);
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms", "quality"), PersistentDataType.STRING, d.quality());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms", "kit_sale_id"), PersistentDataType.STRING, order.toString());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms", "kit_design_id"), PersistentDataType.STRING, d.id());
|
||||
if(d.snapshot()!=null) meta.getPersistentDataContainer().set(new NamespacedKey("dunekits", "contract_version"), PersistentDataType.INTEGER, 1);
|
||||
copy.setItemMeta((ItemMeta)meta);
|
||||
pieces.add(copy);
|
||||
}
|
||||
if (pieces.size() != 4 || pieces.stream().map(ItemStack::getType).distinct().count() != 4L) {
|
||||
throw new IllegalStateException("Incomplete faction kit");
|
||||
}
|
||||
return pieces;
|
||||
}
|
||||
|
||||
static Object trim(ItemMeta meta) {
|
||||
ArmorTrim armorTrim;
|
||||
if (meta instanceof ArmorMeta) {
|
||||
ArmorMeta armor = (ArmorMeta)meta;
|
||||
armorTrim = armor.getTrim();
|
||||
} else {
|
||||
armorTrim = null;
|
||||
}
|
||||
return armorTrim;
|
||||
}
|
||||
|
||||
static void verify(List<?> base, DeliveryStore.Design d) {
|
||||
List<ItemStack> originals = base.stream().filter(v -> {
|
||||
ItemStack i;
|
||||
return v instanceof ItemStack && (i = (ItemStack)v).getItemMeta() instanceof LeatherArmorMeta;
|
||||
}).map(v -> (ItemStack)v).toList();
|
||||
List<byte[]> before = originals.stream().map(ItemStack::serializeAsBytes).toList();
|
||||
List<ItemStack> made = KitFactory.decorate(base, d, UUID.randomUUID());
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
ItemStack original = originals.get(i);
|
||||
LeatherArmorMeta originalMeta = (LeatherArmorMeta)original.getItemMeta();
|
||||
ItemStack result = made.get(i);
|
||||
LeatherArmorMeta resultMeta = (LeatherArmorMeta)result.getItemMeta();
|
||||
if (!(Arrays.equals(before.get(i), original.serializeAsBytes()) && Objects.equals(originalMeta.getAttributeModifiers(), resultMeta.getAttributeModifiers()) && originalMeta.getEnchants().equals(resultMeta.getEnchants()) && Objects.equals(KitFactory.trim((ItemMeta)originalMeta), KitFactory.trim((ItemMeta)resultMeta)))) {
|
||||
throw new IllegalStateException("Kit decoration changed base combat properties");
|
||||
}
|
||||
for (NamespacedKey tag : originalMeta.getPersistentDataContainer().getKeys()) {
|
||||
String value;
|
||||
if (tag.equals((Object)new NamespacedKey("dunerealms", "quality")) || (value = (String)originalMeta.getPersistentDataContainer().get(tag, PersistentDataType.STRING)) == null || value.equals(resultMeta.getPersistentDataContainer().get(tag, PersistentDataType.STRING))) continue;
|
||||
throw new IllegalStateException("Faction authority changed");
|
||||
}
|
||||
if (d.quality().equals(resultMeta.getPersistentDataContainer().get(new NamespacedKey("dunerealms", "quality"), PersistentDataType.STRING))) continue;
|
||||
throw new IllegalStateException("Quality label mismatch");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -186,6 +186,24 @@ public final class DuneKits extends JavaPlugin implements CommandExecutor, org.b
|
|||
return base;
|
||||
}
|
||||
|
||||
/** Called by the existing Atelier menu inside its original fenced inventory transaction. */
|
||||
public List<ItemStack> decoratePurchasedKit(String raw, List<?> original, UUID order) {
|
||||
JsonObject snapshot=JsonParser.parseString(raw).getAsJsonObject();
|
||||
Map<String,ItemStack> base=new HashMap<>();
|
||||
for(Object value:original) if(value instanceof ItemStack item)
|
||||
for(String slot:KitSpec.SLOTS) if(item.getType().name().endsWith("_"+slot.toUpperCase(Locale.ROOT))) base.put(slot,item);
|
||||
if(base.size()!=4) throw KitSpec.invalid();
|
||||
List<ItemStack> items=KitItemFactory.create(snapshot,base);
|
||||
for(ItemStack item:items){
|
||||
org.bukkit.inventory.meta.ItemMeta meta=item.getItemMeta();
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","kit_sale_id"),org.bukkit.persistence.PersistentDataType.STRING,order.toString());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","kit_design_id"),org.bukkit.persistence.PersistentDataType.STRING,snapshot.get("blueprintId").getAsString());
|
||||
meta.getPersistentDataContainer().set(new NamespacedKey("dunerealms","quality"),org.bukkit.persistence.PersistentDataType.STRING,snapshot.get("quality").getAsString());
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
static String digest(String raw) throws Exception {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(raw.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
package com.dunerealms.atelier;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.util.List;
|
||||
|
||||
class AtelierCompatibilityTest {
|
||||
@Test void oldMenuReceivesTheFullModernSnapshotIncludingBlankLore() {
|
||||
String raw="{\"blueprintId\":\"11111111-1111-4111-8111-111111111111\",\"name\":\"Test suit\",\"quality\":\"rare\",\"color\":\"#bca05b\",\"lore\":[\"Story\",\"\"],\"equipment\":{\"version\":3}}";
|
||||
var design=DeliveryStore.parse(raw);assertEquals(raw,design.snapshot());assertEquals("",design.lore().get(1));
|
||||
}
|
||||
@Test void originalQuestConstructorAndAccessorsRemainBinaryCompatible() {
|
||||
var design=new DeliveryStore.Design("id","Name","#123456",List.of("Lore"),"common");
|
||||
assertEquals("id",design.id());assertEquals("Name",design.name());assertNull(design.snapshot());
|
||||
}
|
||||
}
|
||||
47
network/server-control/install-atelier-compat.py
Normal file
47
network/server-control/install-atelier-compat.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
"""Preserve the existing Atelier menus/quests; adapt only receipt metadata rendering."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
BASELINE = 'b0e640901419eb3e544ae0e60b52867f927341246990a2f5cc67bc1a4dc86bf8'
|
||||
CLASSES = {'com/dunerealms/atelier/' + name + '.class' for name in
|
||||
['DeliveryStore', 'DeliveryStore$Design', 'DeliveryStore$Pending', 'KitFactory']}
|
||||
|
||||
|
||||
def install(artifact, apply=False):
|
||||
target = Path('/opt/dunerealms/lobby/plugins/DuneAtelier-1.0.0.jar')
|
||||
if hashlib.sha256(target.read_bytes()).hexdigest() != BASELINE:
|
||||
raise RuntimeError('Existing Atelier changed; no files replaced')
|
||||
with zipfile.ZipFile(artifact) as patch:
|
||||
entries = {n: patch.read(n) for n in patch.namelist() if not n.endswith('/') and n != 'META-INF/MANIFEST.MF'}
|
||||
if set(entries) != CLASSES or any(not v.startswith(b'\xca\xfe\xba\xbe') for v in entries.values()):
|
||||
raise RuntimeError('Unexpected compatibility artifact')
|
||||
with zipfile.ZipFile(target) as original:
|
||||
descriptor = original.read('plugin.yml').decode()
|
||||
if 'softdepend:' in descriptor or 'version: 1.0.0\n' not in descriptor:
|
||||
raise RuntimeError('Unexpected Atelier descriptor')
|
||||
descriptor = descriptor.replace('version: 1.0.0\n', 'version: 1.0.0-kit3\n') + '\nsoftdepend: [DuneKits]\n'
|
||||
if not apply:
|
||||
print('Plan: four compatibility classes and load order; existing menus, quests and transaction code retained')
|
||||
return
|
||||
temporary = target.with_suffix('.kit-v3-new')
|
||||
try:
|
||||
with zipfile.ZipFile(temporary, 'w', zipfile.ZIP_DEFLATED) as output:
|
||||
for item in original.infolist():
|
||||
output.writestr(item, descriptor.encode() if item.filename == 'plugin.yml' else entries.get(item.filename, original.read(item.filename)))
|
||||
with zipfile.ZipFile(temporary) as check:
|
||||
assert check.testzip() is None
|
||||
assert all(check.read(name) == original.read(name) for name in original.namelist() if name not in CLASSES | {'plugin.yml'})
|
||||
status = target.stat()
|
||||
os.chmod(temporary, status.st_mode & 0o777)
|
||||
os.chown(temporary, status.st_uid, status.st_gid)
|
||||
os.replace(temporary, target)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
print('Installed Atelier metadata compatibility; all other classes are unchanged')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
install(Path(sys.argv[1]), '--apply' in sys.argv)
|
||||
Loading…
Reference in a new issue

Staff