Things
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m6s

This commit is contained in:
2026-10-13 22:50:51 +02:00
parent 50828af674
commit af76cf1050
18 changed files with 847 additions and 86 deletions

View File

@@ -22,7 +22,17 @@ const ItemSchema = new Schema({
ref: 'Campaign',
required: true
},
foundryItemId: { type: String },
// Names Foundry uses for this item. Dragonroll may rename it, and the copies
// Foundry keeps sending still have to fold into this row instead of
// creating a second item under their original name.
foundryNames: { type: [String], default: [] },
date: { type: Date, default: Date.now }
});
ItemSchema.index(
{ campaign: 1, foundryItemId: 1 },
{ unique: true, partialFilterExpression: { foundryItemId: { $type: 'string' } } }
);
module.exports = mongoose.model('Item', ItemSchema);

View File

@@ -6,11 +6,16 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
const FoundryLinkRequest = require('../models/FoundryLinkRequest');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const linkRateLimit = rateLimit({ windowMs: 15 * 60 * 1000, max: 20 });
// Upper bound for the Foundry names remembered per synced item (see Item model).
const MAX_FOUNDRY_NAMES = 20;
function codeHash(code) {
return crypto.createHash('sha256').update(String(code ?? '').trim()).digest('hex');
}
@@ -67,6 +72,63 @@ async function saveFoundryActor(campaign, source, fullSync = false) {
return { foundryActorId, actorId: actor.id };
}
// A snapshot carries world-level items plus the items embedded in every actor it
// sends. World items are listed first so they own a name before its copies.
function snapshotItemSources(body) {
const sources = [];
if (Array.isArray(body.items)) sources.push(...body.items);
if (Array.isArray(body.actors)) {
for (const actor of body.actors) {
if (Array.isArray(actor?.items)) sources.push(...actor.items);
}
}
return sources;
}
async function saveFoundryItem(campaign, source, fullSync = false) {
const foundryItemId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundryItemToItemData(source || {});
if (!foundryItemId || !fields) return null;
let item = await Item.findOne({ campaign: campaign._id, foundryItemId });
const dragonrollItemId = source?.flags?.['dragonroll-foundry']?.itemId;
if (!item && mongoose.isValidObjectId(dragonrollItemId)) {
const flagged = await Item.findOne({ _id: dragonrollItemId, campaign: campaign._id });
// Only adopt a flagged item while no other Foundry document owns its mapping.
if (flagged && (!flagged.foundryItemId || flagged.foundryItemId === foundryItemId)) item = flagged;
}
if (!item) {
// The same gear exists more than once in Foundry: once in the world
// directory and once inside each actor carrying it. Keep a single
// Dragonroll item per name so inventories do not flood the Item list.
const sameName = await Item.find({
campaign: campaign._id,
$or: [{ name: fields.name }, { foundryNames: fields.name }]
}).limit(4);
const represented = sameName.find((candidate) => candidate.foundryItemId);
if (represented) return { foundryItemId, itemId: represented.id };
const unclaimed = sameName.filter((candidate) => !candidate.foundryItemId);
item = unclaimed.length === 1 ? unclaimed[0] : new Item({ campaign: campaign._id, name: fields.name });
}
item.foundryItemId = foundryItemId;
if (!fullSync || item.isNew) Object.assign(item, fields);
if (!item.foundryNames.includes(fields.name)) {
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
}
await item.save();
return { foundryItemId, itemId: item.id };
}
async function syncFoundryItems(campaign, sources, fullSync = false) {
const items = [];
for (const source of sources) {
const mapping = await saveFoundryItem(campaign, source, fullSync);
if (mapping) items.push(mapping);
}
return items;
}
function readWorld(body) {
const world = body?.world;
if (!world || typeof world.id !== 'string' || !world.id.trim()) return null;
@@ -178,17 +240,22 @@ router.post('/sync/snapshot', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.actors)) {
const actorSources = Array.isArray(req.body.actors) ? req.body.actors : null;
const itemSources = Array.isArray(req.body.items) ? req.body.items : null;
if (!requestMatchesWorld(campaign, req.body.worldId) || (!actorSources && !itemSources)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const fullSync = req.body.fullSync === true;
const actors = [];
for (const source of req.body.actors) {
const mapping = await saveFoundryActor(campaign, source, req.body.fullSync === true);
for (const source of actorSources || []) {
const mapping = await saveFoundryActor(campaign, source, fullSync);
if (mapping) actors.push(mapping);
}
if (req.body.fullSync === true) {
const currentIds = req.body.actors
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync);
if (fullSync && actorSources) {
const currentIds = actorSources
.map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean);
await Actor.deleteMany({
@@ -196,7 +263,35 @@ router.post('/sync/snapshot', async (req, res) => {
foundryActorId: { $exists: true, $nin: currentIds }
});
}
res.json({ status: 'ok', actors });
// Pruning needs a full snapshot: only that request sees the world
// directory and every actor's copies at the same time.
if (fullSync && itemSources) {
const currentIds = snapshotItemSources(req.body)
.map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean);
await Item.deleteMany({
campaign: campaign._id,
foundryItemId: { $exists: true, $nin: currentIds }
});
}
res.json({ status: 'ok', actors, items });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Live Foundry item edits: upserts only, never prunes. Removing items that no
// longer exist is left to the full snapshot sent with the actors.
router.post('/sync/item-snapshot', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
@@ -255,4 +350,58 @@ router.post('/sync/map', async (req, res) => {
}
});
// Only world-level Foundry items reach this route: an item dropped by an actor
// still exists in the world, and its actor snapshot overwrites the inventory.
router.post('/sync/item-delete', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const foundryItemId = String(req.body.foundryItemId || '').trim();
if (!requestMatchesWorld(campaign, req.body.worldId) || !foundryItemId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
await Item.deleteOne({ campaign: campaign._id, foundryItemId });
res.json({ status: 'ok' });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.get('/sync/items', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const items = await Item.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
res.json({ status: 'ok', items });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/sync/map-item', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { itemId, foundryItemId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !itemId || !foundryItemId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const item = await Item.findOne({ _id: itemId, campaign: campaign._id });
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
const existing = await Item.findOne({ campaign: campaign._id, foundryItemId, _id: { $ne: item._id } });
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.item-already-synced' });
item.foundryItemId = String(foundryItemId).trim().slice(0, 120);
await item.save();
res.json({ status: 'ok', item });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router;

View File

@@ -42,6 +42,31 @@ router.post('/create', async (req, res) => {
}
});
router.post('/update', async (req, res) => {
try {
const { id, name, category, rarity, quantity, weight, properties, description } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const item = await Item.findById(id);
if (!item) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(item.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
if (name !== undefined) item.name = String(name).trim();
if (category !== undefined) item.category = category;
if (rarity !== undefined) item.rarity = rarity;
if (quantity !== undefined && quantity !== '') item.quantity = Number(quantity);
if (weight !== undefined && weight !== '') item.weight = Number(weight);
if (properties !== undefined) item.properties = properties;
if (description !== undefined) item.description = description;
await item.save();
res.json({ status: 'ok', item });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/delete', async (req, res) => {
try {
const { id } = req.body;

View File

@@ -1,30 +1,4 @@
function numberOr(value, fallback) {
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
function asText(value) {
return typeof value === 'string' ? value : '';
}
function plainText(value) {
return asText(value)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p\s*>/gi, '\n')
.replace(/<[^>]*>/g, ' ')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/\s+\n/g, '\n')
.trim();
}
function traitList(value) {
if (Array.isArray(value)) return value.map(asText).filter(Boolean);
if (typeof value === 'string') return [value];
return [];
}
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
function foundryActorToCharacter(foundryActor) {
const system = foundryActor.system || {};
@@ -40,10 +14,10 @@ function foundryActorToCharacter(foundryActor) {
const savedDragonrollFields = foundryActor.flags?.['dragonroll-foundry'] || {};
const savedDragonrollType = savedDragonrollFields.actorType;
const foundryProficiencies = [
...traitList(traits.languages?.value),
...traitList(traits.armor?.value),
...traitList(traits.weapon?.value),
...traitList(traits.tool?.value)
...stringList(traits.languages?.value),
...stringList(traits.armor?.value),
...stringList(traits.weapon?.value),
...stringList(traits.tool?.value)
].join(', ');
return {

View File

@@ -0,0 +1,32 @@
// Small helpers shared by the Foundry -> Dragonroll document mappers
// (services/actor-foundry.js and services/item-foundry.js).
function numberOr(value, fallback) {
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
function asText(value) {
return typeof value === 'string' ? value : '';
}
function plainText(value) {
return asText(value)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p\s*>/gi, '\n')
.replace(/<[^>]*>/g, ' ')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/\s+\n/g, '\n')
.trim();
}
function stringList(value) {
if (Array.isArray(value)) return value.map(asText).filter(Boolean);
if (typeof value === 'string') return [value];
return [];
}
module.exports = { numberOr, asText, plainText, stringList };

View File

@@ -0,0 +1,108 @@
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
// Foundry item types that are gear, mapped to a Dragonroll Item category.
// `equipment` is resolved into armor / shield from its armor type.
const CATEGORY_BY_FOUNDRY_TYPE = {
weapon: 'weapon',
equipment: 'equipment',
consumable: 'consumable',
tool: 'tool',
container: 'adventuring-gear',
loot: 'treasure',
// Item types from older D&D 5e system releases.
ammo: 'weapon',
potion: 'consumable',
poison: 'consumable',
scroll: 'consumable',
trinket: 'magic-item',
backpack: 'adventuring-gear'
};
// Foundry item types that are not gear: they never become Dragonroll items.
const NON_GEAR_FOUNDRY_TYPES = new Set([
'spell', 'class', 'subclass', 'background', 'feat', 'race', 'species', 'status', 'spellbook', 'language'
]);
// Item categories the Dragonroll Item model accepts.
const CATEGORIES = ['weapon', 'armor', 'shield', 'adventuring-gear', 'magic-item', 'consumable', 'tool', 'treasure', 'other'];
const RARITY_BY_FOUNDRY_VALUE = {
common: 'common',
uncommon: 'uncommon',
rare: 'rare',
'very-rare': 'very-rare',
veryrare: 'very-rare',
'very rare': 'very-rare',
legendary: 'legendary',
artifact: 'artifact'
};
// Fallback labels for weapon properties when the Foundry client did not send the
// ones from its own CONFIG (see serializeFoundryItem in the module).
const WEAPON_PROPERTY_LABELS = {
amm: 'ammunition',
fin: 'finesse',
foc: 'focus',
hvy: 'heavy',
lrp: 'long range',
lod: 'loading',
nid: 'noisy',
rch: 'reach',
rel: 'reload',
ret: 'retractable',
slo: 'slow firing',
thr: 'thrown',
thv: 'thrown',
two: 'two-handed',
ver: 'versatile'
};
function foundryItemRarity(foundryItem) {
const rarity = asText(foundryItem.system?.rarity).toLowerCase().trim();
return RARITY_BY_FOUNDRY_VALUE[rarity] || 'common';
}
// Returns null for Foundry documents that are not gear so the sync can skip them.
function foundryItemCategory(foundryItem, rarity) {
const type = asText(foundryItem.type).toLowerCase().trim();
if (NON_GEAR_FOUNDRY_TYPES.has(type)) return null;
if (type === 'equipment') {
return asText(foundryItem.system?.armor?.type).toLowerCase() === 'shield' ? 'shield' : 'armor';
}
const category = CATEGORY_BY_FOUNDRY_TYPE[type];
if (CATEGORIES.includes(category)) return category;
// Systems the module does not know about still get a usable Dragonroll item.
return rarity === 'common' ? 'other' : 'magic-item';
}
function foundryItemProperties(foundryItem) {
const provided = stringList(foundryItem.dragonroll?.properties);
if (provided.length) return provided.join(', ');
const properties = stringList(foundryItem.system?.properties?.value ?? foundryItem.system?.properties);
return properties.map((property) => {
const key = property.toLowerCase();
return Object.hasOwn(WEAPON_PROPERTY_LABELS, key) ? WEAPON_PROPERTY_LABELS[key] : property;
}).join(', ');
}
function foundryItemToItemData(foundryItem) {
const system = foundryItem.system || {};
const name = asText(foundryItem.name).trim();
const rarity = foundryItemRarity(foundryItem);
const category = foundryItemCategory(foundryItem, rarity);
if (!name || !category) return null;
return {
name,
category,
rarity,
quantity: Math.max(1, Math.trunc(numberOr(system.quantity, 1))),
weight: Math.max(0, numberOr(system.weight?.value ?? system.weight, 0)),
properties: foundryItemProperties(foundryItem),
description: plainText(system.description?.value ?? system.description)
};
}
module.exports = { foundryItemToItemData };