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

@@ -84,6 +84,7 @@ app.use(checkAuth);
// ROUTES WITH AUTH
app.use('/api/campaign', require('./routes/campaign'));
app.use('/api/note', require('./routes/note'));
app.use('/api/media', require('./routes/media'));
app.use('/api/folder', require('./routes/folder'));
app.use('/api/actor', require('./routes/actor'));
app.use('/api/item', require('./routes/item'));

View File

@@ -39,15 +39,7 @@ const MapSchema = new Schema({
ref: 'Folder',
default: null
},
// The Foundry scene this map mirrors, set by the scene sync only
// (see routes/foundry-link.js). Only the picture and the grid follow the world.
foundrySceneId: { type: String },
date: { type: Date, default: Date.now }
});
MapSchema.index(
{ campaign: 1, foundrySceneId: 1 },
{ unique: true, partialFilterExpression: { foundrySceneId: { $type: 'string' } } }
);
module.exports = mongoose.model('Map', MapSchema);

View File

@@ -0,0 +1,23 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// A media file of a campaign's note tree: an image, a sound, a video or a document uploaded to
// src/uploads and listed in the sidebar beside the notes. It holds no content of its own, only the
// name it shows under, the file it points at and the note folder it stands in.
const MediaSchema = new Schema({
name: { type: String, required: true },
file: { type: String, required: true },
mimeType: { type: String, required: true },
campaign: {
type: Schema.Types.ObjectId,
ref: 'Campaign',
required: true
},
folder: {
type: Schema.Types.ObjectId,
ref: 'Folder'
},
date: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Media', MediaSchema);

View File

@@ -14,17 +14,7 @@ const NoteSchema = new Schema({
ref: 'Folder'
},
color: { type: String },
// The journal page this note is written as in the linked Foundry world: a page
// of the journal of this note's folder (root notes: "Dragonroll") whose rows
// carry this note's id in their `dragonroll-foundry.noteId` flag (see the
// module's notes sync).
foundryPageId: { type: String },
date: { type: Date, default: Date.now }
});
NoteSchema.index(
{ campaign: 1, foundryPageId: 1 },
{ unique: true, partialFilterExpression: { foundryPageId: { $type: 'string' } } }
);
module.exports = mongoose.model('Note', NoteSchema);

View File

@@ -6,6 +6,7 @@ const Actor = require('../models/Actor');
const Folder = require('../models/Folder');
const Map = require('../models/Map');
const Note = require('../models/Note');
const Media = require('../models/Media');
const Item = require('../models/Item');
async function userOwnsCampaign(campaignId, userId) {
@@ -99,6 +100,10 @@ router.post('/delete', async (req, res) => {
{ folder: folderId },
{ $set: { folder: null, date: Date.now() } }
);
await Media.updateMany(
{ folder: folderId },
{ $set: { folder: null, date: Date.now() } }
);
await Actor.updateMany(
{ folder: folderId },
{ $set: { folder: null } }

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.

View File

@@ -0,0 +1,88 @@
const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();
const Campaign = require('../models/Campaign');
const Folder = require('../models/Folder');
const Media = require('../models/Media');
const upload = require('../services/storage');
const uploadDir = path.join(__dirname, '..', 'uploads');
async function userOwnsCampaign(campaignId, userId) {
const campaign = await Campaign.findOne({ _id: campaignId, createdBy: userId }).lean();
return Boolean(campaign);
}
// Media stands in the note tree, so its folders are the note folders and nothing else.
async function noteFolderFor(folderId, campaignId) {
if (folderId === null || folderId === undefined || folderId === '') return true;
return Folder.belongsToSection(folderId, campaignId, 'note');
}
router.post('/upload', upload.single('file'), async (req, res) => {
try {
const { campaign, folder } = req.body;
if (!campaign || !req.file) return res.json({ status: 'error', msg: 'errors.missing-data' });
if (!(await userOwnsCampaign(campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
if (!(await noteFolderFor(folder, campaign))) return res.json({ status: 'error', msg: 'errors.notfound' });
const media = new Media({
name: (req.body.name || req.file.originalname).trim(),
file: req.file.filename,
mimeType: req.file.mimetype,
campaign,
folder: folder || null
});
await media.save();
res.json({ status: 'ok', media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// Moving a media row to another folder of the note tree, the way a note is moved.
router.post('/update', async (req, res) => {
try {
const { id, folder } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const media = await Media.findById(id);
if (!media) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(media.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
if (!(await noteFolderFor(folder, media.campaign))) return res.json({ status: 'error', msg: 'errors.notfound' });
media.folder = folder || null;
await media.save();
res.json({ status: 'ok', media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/delete', async (req, res) => {
try {
const { id } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const media = await Media.findById(id);
if (!media) return res.json({ status: 'error', msg: 'errors.notfound' });
// Unlike a note, a media row can be checked before it is deleted: the file belongs to the
// campaign it is asked from, so this route never drops another campaign's upload.
if (!(await userOwnsCampaign(media.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
await Media.deleteOne({ _id: media._id });
fs.unlink(path.join(uploadDir, media.file), () => {});
res.json({ status: 'ok' });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router;

View File

@@ -3,6 +3,7 @@ const router = express.Router();
const Campaign = require('../models/Campaign');
const Note = require('../models/Note');
const Media = require('../models/Media');
const Folder = require('../models/Folder');
const Map = require('../models/Map');
@@ -31,7 +32,13 @@ router.get('/list', async (req, res) => {
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', folders, notes: rootNotes });
// The media files standing beside the notes at the root of the tree.
const media = await Media.find({ campaign, folder: null })
.select('_id name file mimeType date')
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', folders, notes: rootNotes, media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
@@ -60,7 +67,12 @@ router.get('/subfolder/list', async (req, res) => {
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', subfolders, notes });
const media = await Media.find({ campaign, folder })
.select('_id name file mimeType date')
.sort({ date: -1 })
.lean();
res.json({ status: 'ok', subfolders, notes, media });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });

View File

@@ -1,49 +0,0 @@
const { numberOr, asText } = require('./foundry-fields');
// A Foundry scene is one of the campaign's maps (Syndria98/dragonroll#99): its background
// picture and the grid laid over it travel to Dragonroll. Everything else a scene holds —
// its padding, its lighting, the tokens standing on it — belongs to the world's table, and
// so does what one of its cells stands for (`gridDistance` with its units): the campaign
// sets its own scale and keeps it.
// The scene's background picture: `background.src` since Foundry V13, plain `img` before.
function sceneImage(scene) {
return asText(scene?.background?.src).trim() || asText(scene?.img).trim();
}
// How many pixels of the picture one grid cell covers. Foundry keeps it under `grid.size`
// since V13 and under plain `grid` before; 50 px is its own default cell size, and
// Dragonroll's is the same, so a scene that says nothing gets the grid it draws.
function sceneGridSize(scene) {
const size = numberOr(scene?.grid?.size ?? scene?.grid, 0);
return size >= 1 ? Math.round(size) : 50;
}
// Where that grid starts on the picture. A world shifts it with the core flags of its own
// (`flags.core.shiftX` / `.shiftY`, what it uses to line a hexagonal grid up); one that says
// nothing has its grid at the corner of the picture. The scene's padding is blank canvas
// *outside* the picture, so it is no part of the grid the campaign lays on the picture itself.
function sceneGridOffset(scene, axis) {
return Math.round(numberOr(scene?.flags?.core?.[`shift${axis}`], 0));
}
// Returns null for a scene that is not a map: one with no name, or with no background
// picture. A Dragonroll map without a picture is an empty viewer, so those scenes stay in
// the world — their id is still listed by the snapshot that carries them, so nothing of the
// campaign is pruned because of one.
function foundrySceneToMapData(scene) {
const name = asText(scene?.name).trim();
const image = sceneImage(scene);
if (!name || !image) return null;
return {
name,
// The module sends Foundry's picture as an absolute URL, like actors do.
image,
gridSize: sceneGridSize(scene),
offsetX: sceneGridOffset(scene, 'X'),
offsetY: sceneGridOffset(scene, 'Y')
};
}
module.exports = { foundrySceneToMapData };