diff --git a/AGENTS.md b/AGENTS.md index 8125d8cd..e98c2ef5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,14 +74,21 @@ backend/src/ ├── index.js app bootstrap: dotenv, static uploads, json limits (50mb), │ passport init, CORS, route mounting, listen(5000) ├── db.js connectDB() -> mongoose.connect(process.env.DB_URI) -├── models/ User.js Campaign.js Note.js Folder.js -├── routes/ user.js campaign.js note.js folder.js +├── models/ User.js Campaign.js Note.js Folder.js Actor.js Item.js +│ FoundryLinkRequest.js DiscordLinkRequest.js DiscordGuildLink.js +├── routes/ user.js campaign.js note.js folder.js actor.js item.js +│ foundry-link.js (token sync, mounted BEFORE auth) foundry.js (bridge proxy) +│ discord.js ├── services/ │ ├── keys.js { secret: "putyoursecrethere" } <- JWT secret, hardcoded │ ├── passport.js JwtStrategy: Bearer token -> User.findById(jwt_payload._id) │ ├── middleware.js isAdmin — imported by routes/user.js but applied to no route yet │ ├── rate-limiter.js express-rate-limit: 150 req / 60 min, applied to /user/login and /user/setup -│ └── storage.js multer diskStorage -> backend/src/uploads/, filename `-` +│ ├── storage.js multer diskStorage -> backend/src/uploads/, filename `-` +│ ├── foundry.js requestFoundry(): reads the optional snapshot bridge +│ ├── foundry-fields.js shared asText/numberOr/plainText/stringList for the mappers +│ ├── actor-foundry.js foundryActorToCharacter(): Foundry actor document -> Actor fields +│ └── item-foundry.js foundryItemToItemData(): Foundry item document -> Item fields └── uploads/ created on demand, gitignored, served PUBLICLY at /api/public ``` @@ -94,7 +101,9 @@ backend/src/ `/get-settings`). 3. `checkAuth = passport.authenticate('jwt', { session: false })` — note the **missing declaration** (implicit global). Everything mounted after this is JWT-protected. -4. `/api/campaign`, `/api/note`, `/api/folder`. +4. `/api/campaign`, `/api/note`, `/api/folder`, `/api/actor`, `/api/item` and `/api/foundry` + (the read-only bridge proxy). `routes/foundry-link.js` is deliberately mounted **before** step 3 — + it authenticates with the per-campaign sync token instead of a Dragonroll login (see §4.1). JWT: signed in `POST /api/user/login` with payload `{ _id, username, name, email, admin, settings }`, `expiresIn: 172800` (48h). `req.user` is the Mongoose `User` document, so routes use `req.user.id`. @@ -130,14 +139,18 @@ Ownership is enforced per handler. `settings`, `color`, `description` and `User. ``` User ──< Campaign ──< Note ──?> Folder ──?> Folder (parentFolder, self-ref) └───────< Folder + └───────< Actor (Foundry actors, when linked) + └───────< Item (Foundry gear + hand-made items) ``` | Model | File | Fields | |---|---|---| | `User` | `models/User.js` | `name*`, `username*` (unique), `email*` (unique), `password` (bcrypt hash, 10 salt rounds), `date`, `admin` (bool, default false), `image`, `setupCode`, `settings` (Object) | -| `Campaign` | `models/Campaign.js` | `name*`, `description`, `color`, `createdBy*` → User, `date`, `settings` (Object) | +| `Campaign` | `models/Campaign.js` | `name*`, `description`, `color`, `createdBy*` → User, `date`, `settings` (Object), `foundryWorldId` (unique, sparse), `foundryWorldTitle`, `foundrySystem`, `foundrySyncTokenHash` (`select: false`), `discordGuildId` | | `Note` | `models/Note.js` | `title`, `content` (markdown source string), `campaign*` → Campaign, `folder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` | | `Folder` | `models/Folder.js` | `name*`, `campaign*` → Campaign, `parentFolder` → Folder (null = root), `color` (hex string, sidebar entry background), `date` | +| `Actor` | `models/Actor.js` | `name*`, `type` (`character`\|`npc`\|`creature`), `species`, `className`, `subclass`, `level`, `background`, `challengeRating`, `description`, `image`, `abilityScores{str..cha}`, `armorClass`, `speed`, `proficiencies`, `inventory[{name,quantity,weight}]` (flattened Foundry items, embedded — not `Item` docs), `traits`, `spells` (newline text), `campaign*` → Campaign, `foundryActorId` (unique per campaign), `date` | +| `Item` | `models/Item.js` | `name*`, `category` (`weapon`\|`armor`\|`shield`\|`adventuring-gear`\|`magic-item`\|`consumable`\|`tool`\|`treasure`\|`other`), `rarity` (`common`…`artifact`), `quantity`, `weight`, `properties`, `description`, `campaign*` → Campaign, `foundryItemId` (unique per campaign), `foundryNames` (names Foundry uses for it, keeps dedup stable across a Dragonroll rename), `date` | `*` = required. Notes and folders are ordered by `date: -1` everywhere. @@ -183,6 +196,54 @@ subfolders re-parented to null then deleted. `GET /api/test` — health check. +`GET /api/actor/list?campaign=` → `{status:'ok',actors}` +`POST /api/actor/create` — `{name*,campaign*,type?,species?,className?,subclass?,level?,background?,challengeRating?,description?}` +`POST /api/actor/update` — `{id*, name?, species?, className?, subclass?, level?, abilityScores?, armorClass?, speed?, proficiencies?, inventory?, traits?, spells?, image?}` — partial, ownership checked +`POST /api/actor/upload-image?actor=` — multipart field `image` +`POST /api/actor/delete` — `{id}` + +`GET /api/item/list?campaign=` → `{status:'ok',items}` +`POST /api/item/create` — `{name*,campaign*,category?,rarity?,quantity?,weight?,properties?,description?}` +`POST /api/item/update` — `{id*, name?, category?, rarity?, quantity?, weight?, properties?, description?}` — partial, ownership checked. `''` for `quantity`/`weight` is ignored, like `/item/create`. +`POST /api/item/delete` — `{id}` + +### 4.1 Foundry integration (actors, items) + +`dragonroll-foundry/` holds the Foundry VTT module (`scripts/api.js`, loaded by `module.json`) and an +optional read-only snapshot bridge (`bridge/server.js`). The module talks to Dragonroll with a +per-campaign bearer token, **not** a Dragonroll login: `POST /api/foundry/link/complete` redeems a +pairing code, stores its hash on `Campaign.foundrySyncTokenHash` and hands the plain token to Foundry +once. Every sync route re-reads the campaign from that hash and rejects payloads whose `worldId` is +not `Campaign.foundryWorldId` (`syncCampaign` / `requestMatchesWorld`). CORS is opened for +`/api/foundry/sync*` and `/foundry/link/complete` in `src/index.js`, before the app-wide CORS. +`dragonroll-foundry/README.md` documents pairing, the bridge and its environment variables. + +| Sync route (token) | Meaning | +|---|---| +| `POST /sync/snapshot` | `{worldId, actors[], items[], fullSync}` — upserts actors, world items and every item embedded in those actors; a `fullSync` also deletes actors/items that are gone | +| `POST /sync/item-snapshot` | `{worldId, items[]}` — live world-item edits, upsert only (never prunes) | +| `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted | +| `GET /sync/characters` | Actors the module applies back into Foundry | +| `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) | +| `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document | +| `POST /sync/delete` | `{worldId, foundryActorId}` | + +Rules worth knowing before editing this: + +- **Identity** is `foundryActorId` / `foundryItemId` (unique per campaign, partial index so local + documents can leave it unset). A document carrying the `dragonroll-foundry.actorId` / + `dragonroll-foundry.itemId` flag adopts the matching Dragonroll row. +- **Items are deduplicated by name.** Foundry keeps the same gear once per carrier, so one Dragonroll + `Item` per name: the first document to claim it keeps the mapping, later copies just return it. + `foundryNames` remembers Foundry's names so a Dragonroll rename does not resurrect a duplicate. + `services/item-foundry.js` returns `null` for non-gear types (spells, classes, feats, species…), + which the sync skips. +- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events + overwrite. Item pruning requires the full snapshot, since only it sees world items and actor copies. +- `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`. +- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only + bridge, only useful when `FOUNDRY_API_URL` is configured. + ## 5. Frontend ``` diff --git a/README.md b/README.md index 883fdf79..cfac0933 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ An open-source helper for role-playing games # Dragonroll -Dragonroll is an open source helper for role-playing games. +Dragonroll is an open source connector for role-playing games. ## Features @@ -48,4 +48,21 @@ or ./start-dev.sh ``` -if you want to start the development environments \ No newline at end of file +if you want to start the development environments + + +## TODO + +- Dragonroll <-> Foundry integration +- Dragonroll <-> Discord Bot integration +- Dragonroll <-> Obsidian integration + +What to sync: + +- Actors +- Monsters +- Items +- Notes +- Maps +- Music ? + diff --git a/backend/src/models/Item.js b/backend/src/models/Item.js index 53cd6919..bd0b67fb 100644 --- a/backend/src/models/Item.js +++ b/backend/src/models/Item.js @@ -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); diff --git a/backend/src/routes/foundry-link.js b/backend/src/routes/foundry-link.js index bb33ddc6..77d5fea0 100644 --- a/backend/src/routes/foundry-link.js +++ b/backend/src/routes/foundry-link.js @@ -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; diff --git a/backend/src/routes/item.js b/backend/src/routes/item.js index 8a0f0195..45ff8558 100644 --- a/backend/src/routes/item.js +++ b/backend/src/routes/item.js @@ -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; diff --git a/backend/src/services/actor-foundry.js b/backend/src/services/actor-foundry.js index cffcfb8f..df74af20 100644 --- a/backend/src/services/actor-foundry.js +++ b/backend/src/services/actor-foundry.js @@ -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(//gi, '\n') - .replace(/<\/p\s*>/gi, '\n') - .replace(/<[^>]*>/g, ' ') - .replace(/ /gi, ' ') - .replace(/&/gi, '&') - .replace(/</gi, '<') - .replace(/>/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 { diff --git a/backend/src/services/foundry-fields.js b/backend/src/services/foundry-fields.js new file mode 100644 index 00000000..8366df36 --- /dev/null +++ b/backend/src/services/foundry-fields.js @@ -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(//gi, '\n') + .replace(/<\/p\s*>/gi, '\n') + .replace(/<[^>]*>/g, ' ') + .replace(/ /gi, ' ') + .replace(/&/gi, '&') + .replace(/</gi, '<') + .replace(/>/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 }; diff --git a/backend/src/services/item-foundry.js b/backend/src/services/item-foundry.js new file mode 100644 index 00000000..b1c7205f --- /dev/null +++ b/backend/src/services/item-foundry.js @@ -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 }; diff --git a/dragonroll-foundry/README.md b/dragonroll-foundry/README.md index b1ddea36..798fc1b0 100644 --- a/dragonroll-foundry/README.md +++ b/dragonroll-foundry/README.md @@ -3,7 +3,7 @@ Foundry modules run in the game client, so the module cannot bind an HTTP port on the Foundry host. This integration uses a small companion bridge process on that host: -1. A linked GM client syncs character Actors directly with the Dragonroll campaign. +1. A linked GM client syncs character Actors and world Items directly with the Dragonroll campaign. 2. The module publishes the active world's actor and item snapshot to the optional bridge. 3. The bridge serves authenticated HTTP read endpoints that Dragonroll proxies under `/api/foundry/*`. @@ -45,7 +45,7 @@ The campaign settings show the linked world's title and system. A Foundry world only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry client and uses the one-time code instead of a Dragonroll login token. -## Character synchronization +## Character and item synchronization After linking, the GM client imports Foundry character, NPC, and creature Actors into the campaign. Creates, updates, and deletes sync in either direction; Dragonroll changes are applied in Foundry @@ -53,6 +53,44 @@ within about five seconds. The module currently creates Dragonroll characters in worlds. After updating an already-linked world to a version with character sync, create a fresh pairing code and enter it in Foundry once to issue the sync token. +### Items + +The campaign's Item list is synchronized with the world's gear, both ways: + +- The GM sends the world item directory (`game.items`) with every snapshot, and world items created, + changed or deleted in Foundry are pushed as they happen. Items embedded in a character travel with + that character's snapshot instead. +- Gear is deduplicated by name: the same sword in the world directory and in three characters' + inventories becomes one Dragonroll item. Names Dragonroll renames away from are remembered on the + item (`foundryNames`), so Foundry's copies keep folding into it rather than coming back as a + duplicate. Spells, classes, subclasses, backgrounds, feats and species are not gear and are not + imported. +- Foundry owns the fields it sends (category from the item type, rarity, quantity, weight, weapon + properties, description). An item made by hand in Dragonroll is created in the world's item + directory on the next reconcile, mapped afterwards, and editing it in Dragonroll updates the Foundry + document. +- A full snapshot keeps Dragonroll edits on reconnect; live Foundry edits overwrite. Item removal is + pruned only by a full snapshot, so a live item push never deletes anything. Deleting a synced item in + Dragonroll removes its Foundry world copy on the next reconcile. Items that live only in an actor's + inventory are owned by that actor's snapshot: editing such an item in Dragonroll does not rewrite the + actor's copy. + +The module calls these Dragonroll routes with the campaign sync token (no Dragonroll login): + +| Route | Use | +|---|---| +| `POST /api/foundry/sync/snapshot` | Actors and world items upsert; `fullSync` also prunes | +| `POST /api/foundry/sync/item-snapshot` | Live world item edits, upsert only | +| `POST /api/foundry/sync/item-delete` | A world item was deleted | +| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry | +| `GET /api/foundry/sync/items` | Items to apply back in Foundry | +| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document | +| `POST /api/foundry/sync/delete` | An actor was deleted | + +Foundry documents keep the Dragonroll id in the `dragonroll-foundry.actorId` / `dragonroll-foundry.itemId` +flag, and world items are marked with `dragonroll-foundry.syncMutation` while Dragonroll writes them so +the write is not echoed back. + ## 2. Run the bridge on the Foundry host The bridge uses only Node.js built-in modules and requires Node 18 or newer. Set separate random diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index 8f017026..6096bf55 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -20,6 +20,11 @@ let characterSyncRunning = false; let actorSyncErrorLogged = false; const syncingActorIds = new Set(); const queuedActorChanges = new Map(); +let itemSyncTimeout; +let itemSyncRunning = false; +let itemSyncErrorLogged = false; +const syncingItemIds = new Set(); +const queuedItemChanges = new Map(); function getCollectionContents(collection, collectionName) { if (!collection) { @@ -240,6 +245,7 @@ async function completeDragonrollCampaignLink(code, options = {}) { } scheduleSnapshotSync(0); setTimeout(initializeCharacterSync, 0); + setTimeout(reconcileDragonrollItems, 2000); ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); } catch (error) { console.error(`${MODULE_ID} | Could not complete the campaign link.`, error); @@ -349,6 +355,9 @@ async function pushFoundryActors(actors, fullSync = false) { const result = await postDragonroll("foundry/sync/snapshot", { worldId: game.world.id, actors: supportedActors.map(serializeFoundryActor), + // Dragonroll deduplicates by name, so sending the world directory next to + // the actor copies keeps a single Item per piece of gear. + items: getWorldItemSnapshots(), fullSync, }, token); @@ -358,6 +367,7 @@ async function pushFoundryActors(actors, fullSync = false) { await setDragonrollActorId(actor, mapping.actorId); } } + await rememberItemMappings(result.items); actorSyncErrorLogged = false; } @@ -378,7 +388,6 @@ function queueActorChange(kind, actor) { clearTimeout(actorSyncTimeout); actorSyncTimeout = setTimeout(flushActorChanges, 400); } - async function flushActorChanges() { const changes = [...queuedActorChanges.values()]; queuedActorChanges.clear(); @@ -396,6 +405,269 @@ async function flushActorChanges() { } } +// --- World item sync ------------------------------------------------------- +// Items embedded in an actor travel with that actor's snapshot; the items below +// handle the world-level item directory (game.items) in both directions. + +function itemPropertyLabels(item) { + const values = item.system?.properties?.value; + if (!Array.isArray(values) || !values.length || game.system?.id !== "dnd5e") return []; + + const propertyConfigs = [ + CONFIG.DND5E?.weaponProperties, + CONFIG.DND5E?.armorProperties, + CONFIG.DND5E?.toolProperties, + CONFIG.DND5E?.consumableProperties, + ]; + return values + .map((key) => { + for (const config of propertyConfigs) { + const label = config?.[key]?.label; + if (label) return String(label).toLowerCase(); + } + return typeof key === "string" ? key : ""; + }) + .filter(Boolean); +} + +function serializeFoundryItem(item) { + const data = toPlainData(item); + if (!data) return null; + + if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) { + data.img = new URL(data.img, window.location.origin).toString(); + } + // Dragonroll shows plain property text; send Foundry's own labels when present + // so keys such as "ver" do not end up in its Item list. + const properties = itemPropertyLabels(item); + if (properties.length) data.dragonroll = { properties }; + return data; +} + +function getWorldItemSnapshots() { + return (game.items?.contents || []).map(serializeFoundryItem).filter(Boolean); +} + +function dragonrollItemIdOf(item) { + return item.getFlag?.(MODULE_ID, "itemId") || item.flags?.[MODULE_ID]?.itemId || ""; +} + +async function withItemSyncSuppressed(item, callback) { + if (!item?.id) return callback(); + syncingItemIds.add(item.id); + try { + return await callback(); + } finally { + syncingItemIds.delete(item.id); + } +} + +async function setDragonrollItemId(item, itemId) { + if (!item || !itemId) return; + await withItemSyncSuppressed(item, () => item.update({ + [`flags.${MODULE_ID}.itemId`]: String(itemId), + [`flags.${MODULE_ID}.syncMutation`]: false, + })); +} + +async function rememberItemMappings(mappings) { + for (const mapping of mappings || []) { + const item = game.items?.get(mapping.foundryItemId); + if (item && String(dragonrollItemIdOf(item)) !== String(mapping.itemId)) { + await setDragonrollItemId(item, mapping.itemId); + } + } +} + +function reportItemSyncError(error) { + if (itemSyncErrorLogged) return; + itemSyncErrorLogged = true; + console.warn(`${MODULE_ID} | Item sync failed and will retry.`, error); +} + +// Item pushes are upserts only: the full world snapshot sent with the actors +// owns pruning, because it is the only one that sees every embedded copy. +async function pushFoundryItems(items) { + const token = getSyncToken(); + if (!token || !game.user?.isGM || !game.world || !items.length) return; + + const result = await postDragonroll("foundry/sync/item-snapshot", { + worldId: game.world.id, + items: items.map(serializeFoundryItem).filter(Boolean), + }, token); + await rememberItemMappings(result.items); + itemSyncErrorLogged = false; +} + +async function deleteDragonrollItem(foundryItemId) { + const token = getSyncToken(); + if (!token || !game.world || !foundryItemId) return; + await postDragonroll("foundry/sync/item-delete", { + worldId: game.world.id, + foundryItemId, + }, token); +} + +function queueFoundryItemChange(kind, item) { + if (!item || !game.user?.isGM || !getSyncToken()) return; + if (syncingItemIds.has(item.id) || item.flags?.[MODULE_ID]?.syncMutation) return; + + queuedItemChanges.set(item.id, { kind, item }); + clearTimeout(itemSyncTimeout); + itemSyncTimeout = setTimeout(flushItemChanges, 400); +} + +async function flushItemChanges() { + const changes = [...queuedItemChanges.values()]; + queuedItemChanges.clear(); + const deleted = changes.filter((change) => change.kind === "delete"); + const changed = changes.filter((change) => change.kind !== "delete"); + + try { + for (const change of deleted) await deleteDragonrollItem(change.item.id); + if (changed.length) await pushFoundryItems(changed.map((change) => change.item)); + } catch (error) { + reportItemSyncError(error); + for (const change of changes) queuedItemChanges.set(change.item.id, change); + clearTimeout(itemSyncTimeout); + itemSyncTimeout = setTimeout(flushItemChanges, 5000); + } +} + +const CATEGORY_TO_FOUNDRY_ITEM_TYPE = { + weapon: "weapon", + armor: "equipment", + shield: "equipment", + consumable: "consumable", + tool: "tool", + "adventuring-gear": "loot", + "magic-item": "loot", + treasure: "loot", + other: "loot", +}; + +const RARITY_TO_FOUNDRY_VALUE = { + common: "common", + uncommon: "uncommon", + rare: "rare", + "very-rare": "veryRare", + legendary: "legendary", + artifact: "artifact", +}; + +function makeFoundryItemData(entry) { + const type = CATEGORY_TO_FOUNDRY_ITEM_TYPE[entry.category] || "loot"; + const data = { + name: String(entry.name || "").trim(), + type, + system: { + quantity: Number(entry.quantity) || 1, + weight: Number(entry.weight) || 0, + rarity: RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", + description: { value: entry.description || "" }, + }, + flags: { [MODULE_ID]: { itemId: String(entry._id), syncMutation: true } }, + }; + if (type === "equipment") data.system.armor = { type: entry.category === "shield" ? "shield" : "medium" }; + return data; +} + +function foundryItemUpdateData(entry) { + return { + name: String(entry.name || "").trim(), + "system.quantity": Number(entry.quantity) || 1, + "system.weight": Number(entry.weight) || 0, + "system.rarity": RARITY_TO_FOUNDRY_VALUE[entry.rarity] || "common", + "system.description.value": entry.description || "", + }; +} + +async function applyDragonrollItem(item, entry) { + const updates = foundryItemUpdateData(entry); + const changed = Object.entries(updates).some(([key, value]) => documentValue(item, key) !== value); + await withItemSyncSuppressed(item, async () => { + if (changed) await item.update(updates); + if (dragonrollItemIdOf(item) !== String(entry._id)) { + await item.update({ [`flags.${MODULE_ID}.itemId`]: String(entry._id) }); + } + }); +} + +async function mapDragonrollItem(itemId, foundryItemId) { + const token = getSyncToken(); + return postDragonroll("foundry/sync/map-item", { + worldId: game.world.id, + itemId: String(itemId), + foundryItemId: String(foundryItemId), + }, token); +} + +async function createFoundryWorldItem(entry) { + const data = makeFoundryItemData(entry); + if (!data.name) return; + const item = await Item.create(data); + if (!item) return; + + await withItemSyncSuppressed(item, async () => { + await item.update({ [`flags.${MODULE_ID}.syncMutation`]: false }); + }); + await mapDragonrollItem(entry._id, item.id); +} + +async function reconcileDragonrollItems() { + const token = getSyncToken(); + if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return; + itemSyncRunning = true; + try { + if (game.system.id !== "dnd5e") { + throw new Error("Item sync currently requires the D&D 5e Foundry system."); + } + const result = await getDragonroll("foundry/sync/items", token); + const remoteItems = result.items || []; + const remoteById = new Map(remoteItems.map((entry) => [String(entry._id), entry])); + const localByRemoteId = new Map(game.items.contents + .map((item) => [String(dragonrollItemIdOf(item)), item]) + .filter(([itemId]) => itemId)); + const retainedFoundryIds = new Set(); + + for (const entry of remoteItems) { + let item = entry.foundryItemId ? game.items.get(entry.foundryItemId) : null; + if (!item) item = localByRemoteId.get(String(entry._id)); + if (item) { + retainedFoundryIds.add(item.id); + await applyDragonrollItem(item, entry); + if (!entry.foundryItemId) await mapDragonrollItem(entry._id, item.id); + } else if (entry.foundryItemId) { + // Imported gear that only exists inside an actor's inventory: its actor + // snapshot owns it, so cloning it into the world would duplicate it. + continue; + } else { + // A Dragonroll item named like an unmapped Foundry item maps to that + // document instead of adding a second copy of the same gear. + const sameName = game.items.contents.find((candidate) => candidate.name === String(entry.name).trim() + && !dragonrollItemIdOf(candidate)); + if (sameName) { + retainedFoundryIds.add(sameName.id); + await mapDragonrollItem(entry._id, sameName.id); + } else { + await createFoundryWorldItem(entry); + } + } + } + + for (const item of game.items.contents) { + const itemId = dragonrollItemIdOf(item); + if (!itemId || retainedFoundryIds.has(item.id) || remoteById.has(String(itemId))) continue; + await withItemSyncSuppressed(item, () => item.delete()); + } + itemSyncErrorLogged = false; + } catch (error) { + reportItemSyncError(error); + } finally { + itemSyncRunning = false; + } +} + function getDragonrollImageUrl(image) { if (!image) return ""; if (/^(https?:|data:|\/\/)/i.test(image)) return image; @@ -715,6 +987,10 @@ Hooks.once("ready", () => { setInterval(publishHeartbeat, 60000); setTimeout(initializeCharacterSync, 1000); setInterval(reconcileDragonrollCharacters, 5000); + // Items reconcile after the character snapshot has landed so Dragonroll has + // already seen the world directory when it starts sending its own items back. + setTimeout(reconcileDragonrollItems, 2000); + setInterval(reconcileDragonrollItems, 5000); for (const event of [ "createActor", "updateActor", "deleteActor", @@ -722,10 +998,21 @@ Hooks.once("ready", () => { ]) { Hooks.on(event, (document) => { scheduleSnapshotSync(); - const actor = document.documentName === "Actor" ? document : document.parent; - if (actor?.documentName === "Actor") { - queueFoundryActorChange(event.startsWith("delete") ? "delete" : "upsert", actor); + const isDelete = event.startsWith("delete"); + + if (document.documentName === "Actor") { + queueFoundryActorChange(isDelete ? "delete" : "upsert", document); + return; } + if (document.documentName !== "Item") return; + + // Items embedded in an actor travel with that actor's snapshot: adding or + // removing one only changes the actor, never deletes it. + if (document.parent?.documentName === "Actor") { + queueFoundryActorChange("upsert", document.parent); + return; + } + queueFoundryItemChange(isDelete ? "delete" : "upsert", document); }); } }); diff --git a/frontend/app/components/partials/ContentSidebar.vue b/frontend/app/components/partials/ContentSidebar.vue index 4b574141..03ebe24e 100644 --- a/frontend/app/components/partials/ContentSidebar.vue +++ b/frontend/app/components/partials/ContentSidebar.vue @@ -25,7 +25,7 @@ const isDragOverSidebar = ref(false); const expandedFolderIds = ref([]); const expandedEntryIds = ref([]); const nestedNoteListRef = ref(null); -let actorRefreshInterval; +let entryRefreshInterval; async function handleSidebarDrop(event) { if (activeSection.value !== 'notes') return; @@ -171,17 +171,17 @@ async function fetchCampaignEntries(entityType = activeSection.value, silent = f if (!silent) entriesError.value = response.data.msg ?? t('campaigns.errors.load'); return; } - if (entityType === 'actors') { - const previousById = new Map(actors.value.map((actor) => [actor._id, actor])); - actors.value = response.data.actors; - for (const actor of actors.value) { - const previous = previousById.get(actor._id); - if (previous && JSON.stringify(previous) !== JSON.stringify(actor)) { - emitter.emit('campaign-entry-updated', { entityType: 'actor', entry: actor }); - } + + const kind = entityType === 'actors' ? 'actor' : 'item'; + const list = entityType === 'actors' ? actors : items; + const previousById = new Map(list.value.map((entry) => [entry._id, entry])); + list.value = response.data[entityType]; + // Tell open windows about Foundry changes landing behind them. + for (const entry of list.value) { + const previous = previousById.get(entry._id); + if (previous && JSON.stringify(previous) !== JSON.stringify(entry)) { + emitter.emit('campaign-entry-updated', { entityType: kind, entry }); } - } else { - items.value = response.data.items; } } catch (error) { if (!silent) entriesError.value = t('campaigns.errors.load'); @@ -213,9 +213,25 @@ function itemSummary(item) { return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`; } +function editItem(entry) { + if (!campaignId.value) return; + CreateWindow('create_campaign_entry', { entityType: 'item', campaign: campaignId.value, entry }); +} + function showEntryMenu(entry, entityType) { const collection = entityType === 'actor' ? 'actor' : 'item'; - ShowContextMenu([{ + const menuItems = []; + + // Characters are edited in their sheet; items get the entry window in edit mode. + if (entityType !== 'actor') { + menuItems.push({ + name: t('campaigns.actions.edit'), + icon: '/icons/iconoir/regular/edit.svg', + action: () => { HideContextMenu(); editItem(entry); } + }); + } + + menuItems.push({ name: t('campaigns.actions.delete'), icon: '/icons/iconoir/regular/trash.svg', action: async () => { @@ -227,7 +243,8 @@ function showEntryMenu(entry, entityType) { } } catch (error) {} finally { HideContextMenu(); } } - }]); + }); + ShowContextMenu(menuItems); } function toggleEntryDetails(entryId) { @@ -289,13 +306,16 @@ onMounted(() => { if (campaignId.value) { fetchCampaignNotes(); } - actorRefreshInterval = setInterval(() => { - if (activeSection.value === 'actors' && campaignId.value) fetchCampaignEntries('actors', true); + entryRefreshInterval = setInterval(() => { + // Synced Foundry entries land in the background for both lists. + if ((activeSection.value === 'actors' || activeSection.value === 'items') && campaignId.value) { + fetchCampaignEntries(activeSection.value, true); + } }, 5000); }); onBeforeUnmount(() => { - clearInterval(actorRefreshInterval); + clearInterval(entryRefreshInterval); emitter.off('note-created', handleNoteCreated); emitter.off('note-renamed', handleNoteRenamed); emitter.off('delete-note', handleNoteDeleted); @@ -412,7 +432,10 @@ onBeforeUnmount(() => {
- {{ item.name }} + + {{ item.name }} + {{ t('campaigns.synced') }} +