This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user