462 lines
21 KiB
JavaScript
462 lines
21 KiB
JavaScript
const crypto = require('node:crypto');
|
|
const express = require('express');
|
|
const mongoose = require('mongoose');
|
|
const router = express.Router();
|
|
|
|
const Campaign = require('../models/Campaign');
|
|
const Actor = require('../models/Actor');
|
|
const Item = require('../models/Item');
|
|
const Folder = require('../models/Folder');
|
|
const { foundryActorToCharacter } = require('../services/actor-foundry');
|
|
const { foundryItemToItemData } = require('../services/item-foundry');
|
|
|
|
// 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');
|
|
}
|
|
|
|
function readSyncToken(req) {
|
|
const match = /^Bearer\s+(.+)$/i.exec(req.get('authorization') || '');
|
|
return match?.[1] || '';
|
|
}
|
|
|
|
async function syncCampaign(req, res) {
|
|
const token = readSyncToken(req);
|
|
if (!token) {
|
|
res.json({ status: 'error', msg: 'unauthorized' });
|
|
return null;
|
|
}
|
|
|
|
const campaign = await Campaign.findOne({ foundrySyncTokenHash: codeHash(token) });
|
|
if (!campaign?.foundryWorldId) {
|
|
res.json({ status: 'error', msg: 'unauthorized' });
|
|
return null;
|
|
}
|
|
return campaign;
|
|
}
|
|
|
|
function requestMatchesWorld(campaign, worldId) {
|
|
return typeof worldId === 'string' && worldId === campaign.foundryWorldId;
|
|
}
|
|
|
|
async function saveFoundryActor(campaign, source, fullSync = false) {
|
|
const foundryActorId = String(source?._id || source?.id || '').trim().slice(0, 120);
|
|
const fields = foundryActorToCharacter(source || {});
|
|
if (!foundryActorId || !fields.name) return null;
|
|
|
|
let actor = await Actor.findOne({ campaign: campaign._id, foundryActorId });
|
|
const dragonrollActorId = source?.flags?.['dragonroll-foundry']?.actorId;
|
|
if (!actor && mongoose.isValidObjectId(dragonrollActorId)) {
|
|
actor = await Actor.findOne({ _id: dragonrollActorId, campaign: campaign._id });
|
|
}
|
|
if (!actor) {
|
|
const possibleMatches = await Actor.find({
|
|
campaign: campaign._id,
|
|
name: fields.name,
|
|
foundryActorId: { $exists: false }
|
|
}).limit(2);
|
|
actor = possibleMatches.length === 1
|
|
? possibleMatches[0]
|
|
: new Actor({ campaign: campaign._id });
|
|
}
|
|
actor.foundryActorId = foundryActorId;
|
|
// `created` says whether this row is new: whoever imports a whole world counts
|
|
// the rows it made apart from the ones it only wrote over.
|
|
const created = actor.isNew;
|
|
// A full snapshot runs when a GM reconnects. Preserve existing Dragonroll
|
|
// edits then; live Foundry change events continue to overwrite normally.
|
|
if (!fullSync || actor.isNew) Object.assign(actor, fields);
|
|
await actor.save();
|
|
return { foundryActorId, actorId: actor.id, created };
|
|
}
|
|
|
|
// The campaign's item list mirrors the world's item directory and nothing else
|
|
// (Syndria98/dragonroll#67). The items embedded in an actor are that character's own
|
|
// inventory: they travel with the actor document (see services/actor-foundry.js), so a
|
|
// snapshot feeds Item rows from the world directory (`body.items`) alone and gear a
|
|
// character merely carries stays on its sheet instead of standing in the item list.
|
|
function snapshotItemSources(body) {
|
|
return Array.isArray(body.items) ? body.items : [];
|
|
}
|
|
|
|
async function saveFoundryItem(campaign, source, fullSync = false, folders = null) {
|
|
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) {
|
|
// A world item can share its name with a Dragonroll row the campaign made by
|
|
// hand, or with one it renamed away from. Keep a single item per name so a
|
|
// piece of gear the world sends folds into that row instead of doubling it.
|
|
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;
|
|
// `created` says whether this row is new: whoever imports a whole world counts
|
|
// the rows it made apart from the ones it only wrote over.
|
|
const created = item.isNew;
|
|
if (!fullSync || item.isNew) Object.assign(item, fields);
|
|
// Foundry's own icon is kept on every save, not only when the edits above
|
|
// land: the item window offers it back after the user picked their own.
|
|
if (fields.image) item.foundryImage = fields.image;
|
|
if (!item.foundryNames.includes(fields.name)) {
|
|
item.foundryNames = [...item.foundryNames, fields.name].slice(-MAX_FOUNDRY_NAMES);
|
|
}
|
|
// Which folder of the campaign's item tree the world says this item stands in.
|
|
// `undefined` means the push says nothing about folders — an older module that
|
|
// knows nothing about them — and the item stays where it is. The world owns the
|
|
// folder of its own directory, so a move it reports lands on a full snapshot too
|
|
// and wins over one a campaign made from its item list.
|
|
const folder = resolveFoundryItemFolder(source, folders);
|
|
if (folder !== undefined) item.folder = folder;
|
|
await item.save();
|
|
return { foundryItemId, itemId: item.id, created };
|
|
}
|
|
|
|
async function syncFoundryItems(campaign, sources, fullSync = false, folders = null) {
|
|
const items = [];
|
|
for (const source of sources) {
|
|
const mapping = await saveFoundryItem(campaign, source, fullSync, folders);
|
|
if (mapping) items.push(mapping);
|
|
}
|
|
return items;
|
|
}
|
|
|
|
// --- Item folders ------------------------------------------------------------
|
|
// A Foundry world groups its item directory into folders; the campaign mirrors that
|
|
// tree as Folders of target 'item' so its item list reads like the world's. Every
|
|
// push from a module that knows about folders carries the whole world tree, and
|
|
// names the folder each world item it sends stands in. Only the world's item
|
|
// directory reaches the campaign's item list, so only its folders are mirrored; the
|
|
// inventory folders an actor keeps for itself are none of the item list's business.
|
|
|
|
// The colour a pushed folder carries. `undefined` means the push says nothing about
|
|
// colours — an older module, which knows nothing about them — and the colour the
|
|
// campaign has stays; `null` is the world leaving a folder uncoloured, which takes
|
|
// the campaign's colour off along with it. Anything else is the colour to show.
|
|
function foundryFolderColor(source) {
|
|
if (source?.color === undefined) return undefined;
|
|
const color = typeof source.color === 'string' ? source.color.trim() : '';
|
|
return color || null;
|
|
}
|
|
|
|
// Parents before children, so a folder is mapped before the one nested in it.
|
|
// A folder whose parent is missing, or caught in a cycle, becomes a root.
|
|
function orderFoundryFolderSources(sources) {
|
|
const byId = new Map();
|
|
for (const source of sources) {
|
|
const id = String(source?.id || '').trim().slice(0, 120);
|
|
const name = String(source?.name || '').trim();
|
|
if (!id || !name) continue;
|
|
byId.set(id, {
|
|
id,
|
|
name,
|
|
parent: String(source?.parent || '').trim().slice(0, 120),
|
|
color: foundryFolderColor(source)
|
|
});
|
|
}
|
|
|
|
const ordered = [];
|
|
const placed = new Set();
|
|
const visiting = new Set();
|
|
function place(id) {
|
|
if (!byId.has(id) || placed.has(id) || visiting.has(id)) return;
|
|
visiting.add(id);
|
|
place(byId.get(id).parent);
|
|
visiting.delete(id);
|
|
placed.add(id);
|
|
ordered.push(byId.get(id));
|
|
}
|
|
for (const id of byId.keys()) place(id);
|
|
return ordered;
|
|
}
|
|
|
|
// The campaign folders mirroring the world's item folder tree, keyed by the Foundry
|
|
// folder id so pushing the same tree again neither doubles a folder nor loses the
|
|
// items filed in it. Rows the campaign made for its own items (no foundryFolderId)
|
|
// are left alone: the world does not know them.
|
|
async function syncFoundryItemFolders(campaign, folderSources) {
|
|
const folders = new Map();
|
|
for (const folder of await Folder.find({ campaign: campaign._id, target: 'item' })) {
|
|
if (folder.foundryFolderId) folders.set(String(folder.foundryFolderId), folder);
|
|
}
|
|
|
|
const ordered = orderFoundryFolderSources(folderSources);
|
|
const inTree = new Set(ordered.map((source) => source.id));
|
|
for (const source of ordered) {
|
|
let folder = folders.get(source.id);
|
|
if (!folder) {
|
|
folder = new Folder({
|
|
campaign: campaign._id,
|
|
target: 'item',
|
|
foundryFolderId: source.id,
|
|
name: source.name
|
|
});
|
|
}
|
|
// The world owns this tree, so unlike an item's fields a rename or a move
|
|
// lands whatever kind of push carried it: the whole tree arrives with each.
|
|
folder.name = source.name;
|
|
// Its colour is the one part of the tree the campaign colours too: what the
|
|
// world shows arrives here, and what the campaign picks travels back to the
|
|
// world with the folder list `/sync/items` answers with.
|
|
if (source.color !== undefined) folder.color = source.color;
|
|
const parent = inTree.has(source.parent) ? folders.get(source.parent) : null;
|
|
folder.parentFolder = parent ? parent._id : null;
|
|
await folder.save();
|
|
folders.set(source.id, folder);
|
|
}
|
|
|
|
// Folders the world no longer has go with it, and the items standing in them
|
|
// move to the root instead of pointing at a folder that is not there.
|
|
const staleIds = [...folders.values()]
|
|
.filter((folder) => folder.foundryFolderId && !inTree.has(String(folder.foundryFolderId)))
|
|
.map((folder) => folder._id);
|
|
if (staleIds.length) {
|
|
await Item.updateMany({ campaign: campaign._id, folder: { $in: staleIds } }, { $set: { folder: null } });
|
|
await Folder.deleteMany({ campaign: campaign._id, _id: { $in: staleIds } });
|
|
}
|
|
return folders;
|
|
}
|
|
|
|
// The folder of a pushed item: undefined when the push says nothing about folders,
|
|
// null for the root of the item directory, and the campaign folder otherwise. An
|
|
// id the tree does not know puts the item at the root rather than nowhere.
|
|
function resolveFoundryItemFolder(source, folders) {
|
|
const foundryFolderId = source?.dragonroll?.folder;
|
|
if (!folders || typeof foundryFolderId !== 'string') return undefined;
|
|
return folders.get(foundryFolderId.trim())?._id || null;
|
|
}
|
|
|
|
|
|
// Linking a world to a campaign happens through the sign-up link every service
|
|
// uses (routes/service-link.js); what stays here is the sync that world keeps up
|
|
// with the campaign once that link has handed it its token.
|
|
|
|
// The Foundry module shows this in its settings: the sync token alone only proves
|
|
// a link was made once, so the module asks which campaign it belongs to and hears
|
|
// back nothing but `unauthorized` once that campaign unlinks the world again.
|
|
router.get('/sync/status', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
|
|
res.set('Cache-Control', 'no-store');
|
|
res.json({
|
|
status: 'ok',
|
|
campaign: { id: campaign.id, name: campaign.name },
|
|
worldId: campaign.foundryWorldId
|
|
});
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.post('/sync/snapshot', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
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;
|
|
// A module that knows nothing about item folders sends neither the tree
|
|
// nor the folder of an item, and then nothing here touches the folders.
|
|
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
|
|
const actors = [];
|
|
for (const source of actorSources || []) {
|
|
const mapping = await saveFoundryActor(campaign, source, fullSync);
|
|
if (mapping) actors.push(mapping);
|
|
}
|
|
const itemFolders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
|
|
const items = await syncFoundryItems(campaign, snapshotItemSources(req.body), fullSync, itemFolders);
|
|
|
|
if (fullSync && actorSources) {
|
|
const currentIds = actorSources
|
|
.map((source) => String(source?._id || source?.id || '').trim())
|
|
.filter(Boolean);
|
|
await Actor.deleteMany({
|
|
campaign: campaign._id,
|
|
foundryActorId: { $exists: true, $nin: currentIds }
|
|
});
|
|
}
|
|
// Pruning needs a full snapshot: only that request sees the whole world
|
|
// directory, so it alone knows which synced rows the world has let go of.
|
|
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 items. Removing items that no
|
|
// longer exist is left to the full snapshot sent with the actors. Item folders are
|
|
// the exception: every request carries the world's whole folder tree, so a folder
|
|
// the world dropped is dropped here too, and a push may carry folders only.
|
|
router.post('/sync/item-snapshot', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const folderSources = Array.isArray(req.body.folders) ? req.body.folders : null;
|
|
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.items)) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const folders = folderSources ? await syncFoundryItemFolders(campaign, folderSources) : null;
|
|
res.json({ status: 'ok', items: await syncFoundryItems(campaign, req.body.items, false, folders) });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.post('/sync/delete', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const foundryActorId = String(req.body.foundryActorId || '').trim();
|
|
if (!requestMatchesWorld(campaign, req.body.worldId) || !foundryActorId) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
await Actor.deleteOne({ campaign: campaign._id, foundryActorId });
|
|
res.json({ status: 'ok' });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.get('/sync/characters', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const actors = await Actor.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
|
|
res.json({ status: 'ok', actors });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
router.post('/sync/map', async (req, res) => {
|
|
try {
|
|
const campaign = await syncCampaign(req, res);
|
|
if (!campaign) return;
|
|
const { actorId, foundryActorId, worldId } = req.body;
|
|
if (!requestMatchesWorld(campaign, worldId) || !actorId || !foundryActorId) {
|
|
return res.json({ status: 'error', msg: 'errors.missing-data' });
|
|
}
|
|
|
|
const actor = await Actor.findOne({ _id: actorId, campaign: campaign._id });
|
|
if (!actor) return res.json({ status: 'error', msg: 'errors.notfound' });
|
|
const existing = await Actor.findOne({ campaign: campaign._id, foundryActorId, _id: { $ne: actor._id } });
|
|
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.actor-already-synced' });
|
|
|
|
actor.foundryActorId = String(foundryActorId).trim().slice(0, 120);
|
|
await actor.save();
|
|
res.json({ status: 'ok', actor });
|
|
} catch (err) {
|
|
console.error(err);
|
|
res.json({ status: 'error', msg: 'errors.internal' });
|
|
}
|
|
});
|
|
|
|
// 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' });
|
|
}
|
|
});
|
|
|
|
// The item list the world reconciles against, together with the folders its rows are
|
|
// grouped into — the same shape the campaign's own `/item/list` answers with. The folders
|
|
// travel back for their colour: the world owns the tree's name and nesting, while whoever
|
|
// colours a folder on either side expects to see it coloured on the other.
|
|
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();
|
|
const folders = await Folder.find({ campaign: campaign._id, target: 'item' })
|
|
.select('_id name color foundryFolderId')
|
|
.sort({ name: 1 })
|
|
.lean();
|
|
res.json({ status: 'ok', items, folders });
|
|
} 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;
|
|
// The writers every Foundry document goes through: the sync pushes above, and the
|
|
// force import a campaign asks for from its sidebar (routes/foundry.js). One set of
|
|
// rules decides which campaign row a world document owns, so pulling a world over
|
|
// twice updates its rows instead of doubling them.
|
|
module.exports.saveFoundryActor = saveFoundryActor;
|
|
module.exports.saveFoundryItem = saveFoundryItem;
|