More things
Some checks failed
Test / test (push) Failing after 5s
Build and Deploy Nuxt / build (push) Successful in 2m3s

This commit is contained in:
2026-11-20 18:59:01 +01:00
parent b83f64ff9e
commit d61659cfdd
51 changed files with 1777 additions and 3817 deletions

View File

@@ -6,13 +6,9 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
// Not `Map`: this route builds plain `Map`s of its own to mirror the world's folder tree.
const MapModel = require('../models/Map');
const Folder = require('../models/Folder');
const Note = require('../models/Note');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const { foundrySceneToMapData } = require('../services/map-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
const serviceLinks = require('../services/service-links');
@@ -245,9 +241,7 @@ async function syncFoundryItemFolders(campaign, folderSources) {
// 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.
// The colour the world shows for the folder arrives here with the tree.
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;
@@ -276,48 +270,6 @@ function resolveFoundryItemFolder(source, folders) {
return folders.get(foundryFolderId.trim())?._id || null;
}
// --- Maps -------------------------------------------------------------------
// A scene of the world becomes one of the campaign's maps (Syndria98/dragonroll#99):
// services/map-foundry.js says what of a scene travels — its background picture and the
// grid laid over it, and nothing else, so the map's pins, its tokens, the folder it
// stands in and what one of its cells means stay the campaign's own.
async function saveFoundryScene(campaign, source, fullSync = false) {
const foundrySceneId = String(source?._id || source?.id || '').trim().slice(0, 120);
const fields = foundrySceneToMapData(source || {});
if (!foundrySceneId || !fields) return null;
resolveWorldAssets(fields, campaign);
let map = await MapModel.findOne({ campaign: campaign._id, foundrySceneId });
const dragonrollMapId = source?.flags?.['dragonroll-foundry']?.mapId;
if (!map && mongoose.isValidObjectId(dragonrollMapId)) {
const flagged = await MapModel.findOne({ _id: dragonrollMapId, campaign: campaign._id });
// Only adopt a flagged map while no other scene owns its mapping.
if (flagged && (!flagged.foundrySceneId || flagged.foundrySceneId === foundrySceneId)) map = flagged;
}
if (!map) {
// The campaign drew this place by hand before the scene of it ever arrived: a scene
// naming the one unmapped map the campaign holds folds into that row instead of
// adding a second copy of the same room.
const sameName = await MapModel.find({
campaign: campaign._id,
name: fields.name,
foundrySceneId: { $exists: false }
}).limit(2);
map = sameName.length === 1 ? sameName[0] : new MapModel({ campaign: campaign._id });
}
map.foundrySceneId = foundrySceneId;
// `created` says whether this row is new, like the actor and item writers answer it.
const created = map.isNew;
// A full snapshot runs when a GM reconnects: the grid the campaign lined up for a map
// it already has survives that. Live scene edits continue to overwrite normally.
if (!fullSync || map.isNew) Object.assign(map, fields);
await map.save();
return { foundrySceneId, mapId: map.id, created };
}
// 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.
@@ -433,41 +385,6 @@ router.post('/sync/delete', async (req, res) => {
}
});
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) => {
@@ -487,218 +404,6 @@ router.post('/sync/item-delete', async (req, res) => {
}
});
// The world's scenes, upserted as the campaign's maps (Syndria98/dragonroll#99). Like a
// world item push, this one prunes only when it is told it carries every scene: that push
// alone sees the whole scene list, so it alone knows which synced maps the world has let go
// of. A map the campaign made by hand has no scene of its own and is never pruned.
router.post('/sync/scenes', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
if (!requestMatchesWorld(campaign, req.body.worldId) || !Array.isArray(req.body.scenes)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const fullSync = req.body.fullSync === true;
const maps = [];
for (const source of req.body.scenes) {
const mapping = await saveFoundryScene(campaign, source, fullSync);
if (mapping) maps.push(mapping);
}
if (fullSync) {
const currentIds = req.body.scenes
.map((source) => String(source?._id || source?.id || '').trim())
.filter(Boolean);
await MapModel.deleteMany({
campaign: campaign._id,
foundrySceneId: { $exists: true, $nin: currentIds }
});
}
res.json({ status: 'ok', maps });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// A scene the world deleted takes its map with it. Only the world says so; deleting a map
// in the campaign leaves the world's scene alone, which is the campaign's own to do.
router.post('/sync/scene-delete', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const foundrySceneId = String(req.body.foundrySceneId || '').trim();
if (!requestMatchesWorld(campaign, req.body.worldId) || !foundrySceneId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
await MapModel.deleteOne({ campaign: campaign._id, foundrySceneId });
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' });
}
});
// --- Note pages ------------------------------------------------------------
// The campaign's notes are read where their authors' table sits: each note
// stands as a page of the journal of the folder it lives in, and root notes share
// the journal the world calls "Dragonroll". Notes are written in Dragonroll, so
// this copy runs one way — the module reads the notes and rewrites their pages;
// nothing of the journal travels back. Its pages keep the note's id in a
// `dragonroll-foundry.noteId` flag, and the note keeps the page's id here, so
// either side recognises the pairing again after a restart.
const NOTE_FOLDER_SEPARATOR = ' / ';
// The path of the folder a note lives in, from the root down: the module names a
// journal after it, so a note in "Sessions / Arc 1" is written into that journal.
// A broken parent chain stops at the first folder seen twice instead of looping.
function noteFolderPath(folderId, foldersById) {
const names = [];
const seen = new Set();
let folder = folderId ? foldersById.get(String(folderId)) : null;
while (folder && !seen.has(String(folder._id))) {
seen.add(String(folder._id));
if (folder.name) names.unshift(String(folder.name));
folder = folder.parentFolder ? foldersById.get(String(folder.parentFolder)) : null;
}
return names.join(NOTE_FOLDER_SEPARATOR);
}
// The note folders of a campaign, keyed by id, for the path of each note.
async function campaignNoteFolders(campaignId) {
const folders = await Folder.find({ campaign: campaignId })
.select('_id name parentFolder')
.lean();
return new Map(folders.map((folder) => [String(folder._id), folder]));
}
// A cheap summary of the campaign's notes for the module's change check: the same
// notes `/sync/notes` would send, folded into one hash, so a world can tell whether
// anything changed without pulling every note's markdown over on every poll. The
// folder path travels in the hash too: renaming or moving a folder moves a note to
// another journal. The page a note is already mapped to is left out — mapping is
// not an edit.
router.get('/sync/notes/revision', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const notes = await Note.find({ campaign: campaign._id })
.select('_id title content folder')
.sort({ _id: 1 })
.lean();
const foldersById = await campaignNoteFolders(campaign._id);
const revision = crypto.createHash('sha256')
.update(notes.map((note) => [
note._id,
note.title ?? '',
note.content ?? '',
note.folder ?? '',
noteFolderPath(note.folder, foldersById),
].join('\u0000')).join('\u0001'))
.digest('hex');
res.json({ status: 'ok', revision });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Every note of the campaign, content included: enough for the module to write
// each one as a page. A note also carries the path of its folder, which names the
// journal the page belongs to; root notes carry an empty path.
router.get('/sync/notes', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const notes = await Note.find({ campaign: campaign._id })
.select('_id title content foundryPageId date folder')
.sort({ date: -1 })
.lean();
const foldersById = await campaignNoteFolders(campaign._id);
res.json({
status: 'ok',
notes: notes.map((note) => ({
...note,
folderPath: noteFolderPath(note.folder, foldersById),
})),
});
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// The page the module made for a note, kept on the note so the next reconcile —
// or a world whose page flags were lost — writes that page instead of a second
// one under the same title.
router.post('/sync/map-note', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { noteId, foundryPageId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !noteId || !foundryPageId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const note = await Note.findOne({ _id: noteId, campaign: campaign._id });
if (!note) return res.json({ status: 'error', msg: 'errors.notfound' });
const existing = await Note.findOne({ campaign: campaign._id, foundryPageId, _id: { $ne: note._id } });
if (existing) return res.json({ status: 'error', msg: 'foundry.errors.note-already-synced' });
note.foundryPageId = String(foundryPageId).trim().slice(0, 120);
await note.save();
res.json({ status: 'ok', note });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// A world letting its campaign go from the module settings: the campaign forgets
// the world and the token this request used stops working, so the world is free
// to pair again — and the campaign's settings stop listing it as connected.