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

@@ -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;