1901 lines
73 KiB
JavaScript
1901 lines
73 KiB
JavaScript
const MODULE_ID = "dragonroll-foundry";
|
|
const SETTING_BRIDGE_URL = "bridgeUrl";
|
|
const SETTING_PUSH_TOKEN = "pushToken";
|
|
const SETTING_BRIDGE_CONFIG = "bridgeConfig";
|
|
const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl";
|
|
const SETTING_LINK_CODE = "linkCode";
|
|
const SETTING_LINK_URL = "linkUrl";
|
|
const SETTING_PAIRING_STATUS = "pairingStatus";
|
|
const SETTING_SYNC_TOKEN = "syncToken";
|
|
const SETTING_AUTO_SYNC = "autoSync";
|
|
// How often a world asks Dragonroll whether its sign-up link has been answered.
|
|
const LINK_POLL_MS = 5000;
|
|
let syncTimeout;
|
|
let syncInProgress = false;
|
|
let syncRequested = false;
|
|
let askingForLink = false;
|
|
let checkingLink = false;
|
|
let updatingLinkSetting = false;
|
|
// Marks a pairing Dragonroll honoured once and no longer accepts: the campaign
|
|
// unlinked this world, so the token this client holds is dead.
|
|
const PAIRING_REVOKED = "revoked";
|
|
let updatingPairingStatus = false;
|
|
let linkedCampaignName = "";
|
|
let linkProblem = "";
|
|
let actorSyncTimeout;
|
|
let characterSyncRetryTimeout;
|
|
let characterSyncRunning = false;
|
|
let actorSyncErrorLogged = false;
|
|
const syncingActorIds = new Set();
|
|
const queuedActorChanges = new Map();
|
|
let itemSyncTimeout;
|
|
let itemSyncRunning = false;
|
|
let itemSyncErrorLogged = false;
|
|
let folderSyncTimeout;
|
|
let folderSyncRunning = false;
|
|
const syncingItemIds = new Set();
|
|
const syncingFolderIds = new Set();
|
|
const queuedItemChanges = new Map();
|
|
// The lighting of the scene being played: queued while the GM drags walls about, and written back into
|
|
// the world from the campaign on a timer.
|
|
let sceneLightingTimeout;
|
|
let sceneLightingRunning = false;
|
|
let sceneLightingErrorLogged = false;
|
|
const syncingLightIds = new Set();
|
|
|
|
function getCollectionContents(collection, collectionName) {
|
|
if (!collection) {
|
|
throw new Error(`Foundry ${collectionName} collection is not available yet.`);
|
|
}
|
|
|
|
return collection.contents;
|
|
}
|
|
|
|
function toPlainData(document) {
|
|
return document?.toObject() ?? null;
|
|
}
|
|
|
|
const api = Object.freeze({
|
|
/** Return metadata for the currently loaded world. */
|
|
getWorld() {
|
|
if (!game.world) return null;
|
|
|
|
return {
|
|
id: game.world.id,
|
|
title: game.world.title,
|
|
system: game.system.id,
|
|
url: window.location.origin,
|
|
};
|
|
},
|
|
|
|
/** Return plain data snapshots for all Actor documents in the active world. */
|
|
getActors() {
|
|
return getCollectionContents(game.actors, "actor").map(toPlainData);
|
|
},
|
|
|
|
/** Return plain data snapshots for Actors whose system type is `character`. */
|
|
getCharacters() {
|
|
return getCollectionContents(game.actors, "actor")
|
|
.filter((actor) => actor.type === "character")
|
|
.map(toPlainData);
|
|
},
|
|
|
|
/** Return one Actor snapshot, or null when its id is not in the active world. */
|
|
getActor(actorId) {
|
|
return toPlainData(game.actors?.get(actorId));
|
|
},
|
|
|
|
/** Return plain data snapshots for world-level Item documents. */
|
|
getItems() {
|
|
return getCollectionContents(game.items, "item").map(toPlainData);
|
|
},
|
|
|
|
/** Return one world-level Item snapshot, or null when its id is not in the active world. */
|
|
getItem(itemId) {
|
|
return toPlainData(game.items?.get(itemId));
|
|
},
|
|
|
|
/** Return embedded Item snapshots belonging to an Actor, or null if the Actor is missing. */
|
|
getActorItems(actorId) {
|
|
const actor = game.actors?.get(actorId);
|
|
if (!actor) return null;
|
|
|
|
return getCollectionContents(actor.items, "actor item").map(toPlainData);
|
|
},
|
|
});
|
|
|
|
Hooks.once("init", () => {
|
|
game.settings.register(MODULE_ID, SETTING_BRIDGE_URL, {
|
|
name: "Legacy bridge URL",
|
|
scope: "client",
|
|
config: false,
|
|
type: String,
|
|
default: "",
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_PUSH_TOKEN, {
|
|
name: "Legacy bridge publish token",
|
|
scope: "client",
|
|
config: false,
|
|
type: String,
|
|
default: "",
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_BRIDGE_CONFIG, {
|
|
name: "Bridge configuration",
|
|
scope: "client",
|
|
config: false,
|
|
type: Object,
|
|
default: {},
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_SYNC_TOKEN, {
|
|
name: "Character sync token",
|
|
scope: "client",
|
|
config: false,
|
|
type: String,
|
|
default: "",
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_DRAGONROLL_API_URL, {
|
|
name: "Dragonroll Endpoint",
|
|
hint: "The Dragonroll server URL. The API path is added automatically.",
|
|
scope: "client",
|
|
config: true,
|
|
type: String,
|
|
default: "https://dragonroll.aranroig.com",
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_LINK_CODE, {
|
|
name: "Dragonroll Connection Link Code",
|
|
scope: "client",
|
|
config: false,
|
|
type: String,
|
|
default: "",
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_LINK_URL, {
|
|
name: "Dragonroll Connection Link",
|
|
scope: "client",
|
|
config: false,
|
|
type: String,
|
|
default: "",
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_PAIRING_STATUS, {
|
|
name: "Dragonroll Pairing Status",
|
|
hint: "Whether this world is connected to a Dragonroll campaign. The module keeps this text up to date: it asks Dragonroll for a sign-up link, and whoever opens that link picks the campaign. There is nothing to set here.",
|
|
scope: "client",
|
|
config: true,
|
|
type: String,
|
|
default: "",
|
|
onChange: handlePairingStatusChange,
|
|
});
|
|
|
|
game.settings.register(MODULE_ID, SETTING_AUTO_SYNC, {
|
|
name: "Dragonroll Auto-sync",
|
|
hint: "Keep the linked Dragonroll campaign in step with this world as its actors and items change. Turn this off to stop synchronizing; the actor directory's Dragonroll: Force Sync entry then sends an actor over only when you ask for it.",
|
|
scope: "client",
|
|
config: true,
|
|
type: Boolean,
|
|
default: true,
|
|
onChange: handleAutoSyncChange,
|
|
});
|
|
|
|
const module = game.modules.get(MODULE_ID);
|
|
if (!module) {
|
|
console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`);
|
|
return;
|
|
}
|
|
|
|
module.api = api;
|
|
console.info(`${MODULE_ID} | Public API registered.`);
|
|
});
|
|
|
|
function dragonrollEndpoint(path) {
|
|
const endpoint = game.settings.get(MODULE_ID, SETTING_DRAGONROLL_API_URL)?.trim();
|
|
if (!endpoint) throw new Error("Set the Dragonroll endpoint in the Dragonroll Foundry module settings first.");
|
|
|
|
const apiBase = new URL(endpoint);
|
|
const basePath = apiBase.pathname.replace(/\/+$/, "");
|
|
const isLocalBackend = ["localhost", "127.0.0.1", "[::1]"].includes(apiBase.hostname)
|
|
&& apiBase.port === "5000";
|
|
const hasApiPath = basePath.endsWith("/api");
|
|
apiBase.pathname = `${hasApiPath || isLocalBackend ? basePath : `${basePath}/api`}/`;
|
|
apiBase.search = "";
|
|
apiBase.hash = "";
|
|
return new URL(path.replace(/^\/+/, ""), apiBase);
|
|
}
|
|
|
|
async function postDragonroll(path, body, token = "") {
|
|
const headers = { "Content-Type": "application/json" };
|
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
const response = await fetch(dragonrollEndpoint(path), {
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify(body),
|
|
});
|
|
const result = await response.json();
|
|
if (!response.ok || result.status !== "ok") {
|
|
throw new Error(result.msg || `Dragonroll returned HTTP ${response.status}.`);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async function getDragonroll(path, token) {
|
|
const response = await fetch(dragonrollEndpoint(path), {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
const result = await response.json();
|
|
if (!response.ok || result.status !== "ok") {
|
|
throw new Error(result.msg || `Dragonroll returned HTTP ${response.status}.`);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// --- Connecting a world ----------------------------------------------------
|
|
// A world does not paste a code into its settings any more: it asks Dragonroll
|
|
// for the same sign-up link every service gets, the GM opens it and picks the
|
|
// campaign this world may work on. That link then hands the world its token.
|
|
|
|
function worldLinkRequest() {
|
|
const world = api.getWorld();
|
|
return {
|
|
service: "foundry",
|
|
target: {
|
|
id: world.id,
|
|
name: world.title,
|
|
user: game.user?.name || "",
|
|
meta: { system: world.system, url: world.url },
|
|
},
|
|
};
|
|
}
|
|
|
|
async function setLink(code, url) {
|
|
updatingLinkSetting = true;
|
|
try {
|
|
await game.settings.set(MODULE_ID, SETTING_LINK_CODE, code);
|
|
await game.settings.set(MODULE_ID, SETTING_LINK_URL, url);
|
|
} finally {
|
|
updatingLinkSetting = false;
|
|
}
|
|
}
|
|
|
|
async function requestDragonrollLink() {
|
|
if (askingForLink || !game.user?.isGM || !game.world) return;
|
|
askingForLink = true;
|
|
try {
|
|
const result = await postDragonroll("link/start", worldLinkRequest());
|
|
linkProblem = "";
|
|
await setLink(String(result.code || ""), String(result.linkUrl || ""));
|
|
ui.notifications?.info(`Open this link to pick the Dragonroll campaign for this world: ${result.linkUrl}`);
|
|
} catch (error) {
|
|
console.error(`${MODULE_ID} | Could not get a Dragonroll connection link.`, error);
|
|
linkProblem = error.message;
|
|
} finally {
|
|
askingForLink = false;
|
|
await setPairingStatus(pairingStatusText());
|
|
}
|
|
}
|
|
|
|
// What a link leaves this client with once a campaign has been picked: the token
|
|
// its sync runs on, and the bridge settings that came with it.
|
|
async function applyDragonrollLink(result) {
|
|
let syncTokenStored = false;
|
|
if (result.syncToken) {
|
|
try {
|
|
await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, result.syncToken);
|
|
syncTokenStored = true;
|
|
} catch (error) {
|
|
console.error(`${MODULE_ID} | Could not save the character sync token.`, error);
|
|
}
|
|
}
|
|
if (result.bridgeConfig?.url && result.bridgeConfig?.pushToken) {
|
|
try {
|
|
await game.settings.set(MODULE_ID, SETTING_BRIDGE_CONFIG, result.bridgeConfig);
|
|
} catch (error) {
|
|
console.error(`${MODULE_ID} | Could not save the bridge configuration.`, error);
|
|
ui.notifications?.warn("This world was linked, but its bridge settings could not be saved on this client.");
|
|
}
|
|
}
|
|
|
|
linkedCampaignName = String(result.campaign?.name || "").trim();
|
|
await setLink("", "");
|
|
if (syncTokenStored) {
|
|
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
|
|
scheduleSnapshotSync(0);
|
|
setTimeout(initializeCharacterSync, 0);
|
|
setTimeout(reconcileDragonrollItems, 2000);
|
|
} else {
|
|
// Without a token this client cannot sync, and only a fresh link gives one.
|
|
linkProblem = "this client could not save the token it was given";
|
|
ui.notifications?.warn("This world is linked to a Dragonroll campaign, but character sync is unavailable. Update Dragonroll and link the world again.");
|
|
}
|
|
}
|
|
|
|
// Where the sign-up link stands: still waiting for the GM to pick a campaign,
|
|
// finished and handing its token over, or gone, in which case there is a new
|
|
// link to show instead of a world that quietly stops trying.
|
|
async function advanceDragonrollLink() {
|
|
if (askingForLink || checkingLink || !game.user?.isGM || !game.world || getSyncToken()) return;
|
|
const code = game.settings.get(MODULE_ID, SETTING_LINK_CODE)?.trim();
|
|
if (!code) return requestDragonrollLink();
|
|
|
|
checkingLink = true;
|
|
try {
|
|
const result = await postDragonroll("link/pickup", { code });
|
|
if (result.state === "pending") return;
|
|
if (result.state === "linked") await applyDragonrollLink(result);
|
|
else if (result.state === "revoked") {
|
|
linkProblem = PAIRING_REVOKED;
|
|
await setLink("", "");
|
|
} else {
|
|
await setLink("", "");
|
|
await requestDragonrollLink();
|
|
}
|
|
} catch (error) {
|
|
// Dragonroll may be restarting: the next check asks again.
|
|
console.warn(`${MODULE_ID} | Could not check the Dragonroll connection link.`, error);
|
|
} finally {
|
|
checkingLink = false;
|
|
await setPairingStatus(pairingStatusText());
|
|
}
|
|
}
|
|
|
|
// --- Pairing status --------------------------------------------------------
|
|
// The pairing status is the sentence the module settings show. Everything in it
|
|
// comes from this client plus what Dragonroll last said about its token, so it
|
|
// reads correctly from the first frame and is corrected by refreshPairingStatus.
|
|
|
|
function pairingStatusText() {
|
|
const link = game.settings.get(MODULE_ID, SETTING_LINK_URL)?.trim();
|
|
if (linkProblem === PAIRING_REVOKED) {
|
|
return link
|
|
? `Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Open ${link} to pick a campaign again.`
|
|
: "Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Its settings will show a link to pick one again.";
|
|
}
|
|
if (getSyncToken()) {
|
|
return linkedCampaignName
|
|
? `Connected to the Dragonroll campaign "${linkedCampaignName}".`
|
|
: "Connected to a Dragonroll campaign.";
|
|
}
|
|
if (linkProblem) return `Not connected: Dragonroll did not answer this world's link (${linkProblem})`;
|
|
if (link) {
|
|
return `Not connected yet: open ${link} in a browser, sign in and pick the campaign for this world.`;
|
|
}
|
|
return "Not connected to a Dragonroll campaign. Set the Dragonroll Endpoint in these settings, then reload this world to get a sign-up link.";
|
|
}
|
|
|
|
async function setPairingStatus(text) {
|
|
if (game.settings.get(MODULE_ID, SETTING_PAIRING_STATUS) === text) return;
|
|
updatingPairingStatus = true;
|
|
try {
|
|
await game.settings.set(MODULE_ID, SETTING_PAIRING_STATUS, text);
|
|
} catch (error) {
|
|
console.warn(`${MODULE_ID} | Could not store the Dragonroll pairing status.`, error);
|
|
} finally {
|
|
updatingPairingStatus = false;
|
|
}
|
|
}
|
|
|
|
// Nothing is configured here: anything typed into the status is replaced by the
|
|
// status the module actually has.
|
|
function handlePairingStatusChange() {
|
|
if (updatingPairingStatus) return;
|
|
setPairingStatus(pairingStatusText());
|
|
}
|
|
|
|
// A token in this client only proves the world was paired once. Ask Dragonroll
|
|
// which campaign that token belongs to, and hear back when the campaign has
|
|
// unlinked this world again in the meantime.
|
|
async function refreshPairingStatus() {
|
|
const token = getSyncToken();
|
|
if (!token) {
|
|
linkedCampaignName = "";
|
|
await setPairingStatus(pairingStatusText());
|
|
return;
|
|
}
|
|
try {
|
|
const result = await getDragonroll("foundry/sync/status", token);
|
|
linkedCampaignName = String(result.campaign?.name || "").trim();
|
|
if (linkProblem === PAIRING_REVOKED) linkProblem = "";
|
|
} catch (error) {
|
|
// An unauthorized token is a campaign that unlinked this world. Any other
|
|
// failure (an unreachable Dragonroll, or one old enough to have no status
|
|
// route) says nothing about the pairing, so keep showing what we know.
|
|
if (error.message === "unauthorized") {
|
|
linkProblem = PAIRING_REVOKED;
|
|
linkedCampaignName = "";
|
|
// The dead token is dropped so the world stops pushing to a campaign that
|
|
// no longer wants it, and its link check asks for a sign-up link again.
|
|
await game.settings.set(MODULE_ID, SETTING_SYNC_TOKEN, "");
|
|
ui.notifications?.warn("This world is no longer linked to its Dragonroll campaign. Its settings show the link to pick one again.");
|
|
}
|
|
}
|
|
await setPairingStatus(pairingStatusText());
|
|
}
|
|
|
|
function scheduleSnapshotSync(delay = 500) {
|
|
clearTimeout(syncTimeout);
|
|
syncTimeout = setTimeout(publishSnapshot, delay);
|
|
}
|
|
|
|
function getBridgeConfig() {
|
|
const configured = game.settings.get(MODULE_ID, SETTING_BRIDGE_CONFIG);
|
|
if (configured?.url?.trim() && configured?.pushToken?.trim()) return configured;
|
|
|
|
const legacy = {
|
|
url: game.settings.get(MODULE_ID, SETTING_BRIDGE_URL)?.trim(),
|
|
pushToken: game.settings.get(MODULE_ID, SETTING_PUSH_TOKEN)?.trim(),
|
|
};
|
|
return legacy.url && legacy.pushToken ? legacy : null;
|
|
}
|
|
|
|
function getSyncToken() {
|
|
return game.settings.get(MODULE_ID, SETTING_SYNC_TOKEN)?.trim() || "";
|
|
}
|
|
|
|
// Autosync is what the module has always done: every Foundry create, update and
|
|
// delete pushes to Dragonroll, and both sides reconcile on a timer. When it is
|
|
// off, nothing syncs on its own and only a forced actor sync reaches Dragonroll.
|
|
function isAutoSyncEnabled() {
|
|
return game.settings.get(MODULE_ID, SETTING_AUTO_SYNC) !== false;
|
|
}
|
|
|
|
function handleAutoSyncChange(value) {
|
|
if (value === false) {
|
|
clearTimeout(actorSyncTimeout);
|
|
clearTimeout(itemSyncTimeout);
|
|
clearTimeout(folderSyncTimeout);
|
|
clearTimeout(sceneLightingTimeout);
|
|
return;
|
|
}
|
|
if (!game.user?.isGM || !getSyncToken()) return;
|
|
|
|
// Switching it back on converges both sides again, then the changes queued
|
|
// while autosync was off are pushed so this world's state wins over them.
|
|
initializeCharacterSync();
|
|
reconcileDragonrollItems();
|
|
queueFoundryItemFolders(400);
|
|
// The lighting of the scene the campaign mirrors converges too: a wall or a lamp moved while
|
|
// autosync was off is the world's, and the campaign's own lights are written back into the scene.
|
|
queueSceneLightingChange(400);
|
|
reconcileDragonrollSceneLighting();
|
|
if (queuedActorChanges.size) {
|
|
clearTimeout(actorSyncTimeout);
|
|
actorSyncTimeout = setTimeout(flushActorChanges, 400);
|
|
}
|
|
if (queuedItemChanges.size) {
|
|
clearTimeout(itemSyncTimeout);
|
|
itemSyncTimeout = setTimeout(flushItemChanges, 400);
|
|
}
|
|
}
|
|
|
|
function dragonrollActorId(actor) {
|
|
return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || "";
|
|
}
|
|
|
|
function serializeFoundryActor(actor) {
|
|
const data = {
|
|
...toPlainData(actor),
|
|
// Embedded items go through serializeFoundryItem so their icons become
|
|
// absolute URLs too: Dragonroll renders them outside of Foundry.
|
|
items: (actor.items?.contents?.map(serializeFoundryItem) || []).filter(Boolean),
|
|
};
|
|
if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) {
|
|
data.img = new URL(data.img, window.location.origin).toString();
|
|
}
|
|
// Tools and languages travel by their names: what the actor holds are proficiency
|
|
// keys (and, since the third release of the system, language documents), which mean
|
|
// nothing to a sheet outside Foundry.
|
|
const names = { tools: foundryTraitNames(actor, "tools"), languages: foundryTraitNames(actor, "languages") };
|
|
if (names.tools || names.languages) data.dragonroll = { ...names };
|
|
return data;
|
|
}
|
|
|
|
// A proficiency list of `system.traits`: its keys resolved to the labels CONFIG gives
|
|
// them, plus whatever the GM typed as a proficiency of their own. `null` for an actor
|
|
// that has no such list, an empty array for one that has none of that kind. Dragonroll
|
|
// names its lists in full, while the world keeps its tools under `system.traits.tool`
|
|
// and its languages under `system.traits.languages`.
|
|
const TRAIT_FIELDS = { tools: "tool", languages: "languages" };
|
|
|
|
function foundryTraitNames(actor, kind) {
|
|
if (game.system?.id !== "dnd5e") return null;
|
|
const trait = actor.system?.traits?.[TRAIT_FIELDS[kind] ?? kind];
|
|
if (!trait || typeof trait !== "object") return null;
|
|
|
|
const names = (Array.isArray(trait.value) ? trait.value : [])
|
|
.map((key) => foundryProficiencyLabel(kind, key))
|
|
.filter(Boolean);
|
|
for (const custom of String(trait.custom ?? "").split(",")) {
|
|
const name = custom.trim();
|
|
if (name) names.push(name);
|
|
}
|
|
return [...new Set(names)];
|
|
}
|
|
|
|
function foundryProficiencyLabel(kind, key) {
|
|
if (typeof key !== "string" || !key) return "";
|
|
|
|
const entry = CONFIG.DND5E?.[kind === "languages" ? "languages" : "tools"]?.[key];
|
|
const label = entry?.label ?? entry?.name;
|
|
if (label) return String(label);
|
|
// A language the world added itself stands as a document of its own rather than in
|
|
// the system's config.
|
|
const document = kind === "languages" ? game.items?.get?.(key) : null;
|
|
if (document?.name) return String(document.name);
|
|
// The key beats dropping a proficiency the character really has.
|
|
return key;
|
|
}
|
|
|
|
function isSupportedCharacterActor(actor) {
|
|
const savedType = actor.getFlag?.(MODULE_ID, "actorType") || actor.flags?.[MODULE_ID]?.actorType;
|
|
return ["character", "npc", "creature"].includes(savedType || actor.type);
|
|
}
|
|
|
|
// Embedded documents the world owns outright (Syndria98/dragonroll#89): a feat is a trait
|
|
// and a race is a species — they reach the campaign through its traits and species fields,
|
|
// never through its inventory. Dragonroll must neither mark them as its own nor delete one
|
|
// when it writes the character, and an older campaign still holding such a row in its
|
|
// inventory must be let to write it out of the campaign without the document going with it.
|
|
const WORLD_OWNED_EMBEDDED_TYPES = new Set(["feat", "race", "species", "status", "spellbook", "language"]);
|
|
|
|
async function markActorItemsAsSynced(actor) {
|
|
const updates = actor.items.contents
|
|
.filter((item) => !item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type))
|
|
.map((item) => ({
|
|
_id: item.id,
|
|
[`flags.${MODULE_ID}.syncedItem`]: true,
|
|
}));
|
|
if (updates.length) {
|
|
await withActorSyncSuppressed(actor, () => actor.updateEmbeddedDocuments("Item", updates));
|
|
}
|
|
}
|
|
|
|
async function withActorSyncSuppressed(actor, callback) {
|
|
if (!actor?.id) return callback();
|
|
syncingActorIds.add(actor.id);
|
|
try {
|
|
return await callback();
|
|
} finally {
|
|
syncingActorIds.delete(actor.id);
|
|
}
|
|
}
|
|
|
|
async function setDragonrollActorId(actor, actorId) {
|
|
if (!actor || !actorId) return;
|
|
await withActorSyncSuppressed(actor, () => actor.update({
|
|
[`flags.${MODULE_ID}.actorId`]: String(actorId),
|
|
[`flags.${MODULE_ID}.syncMutation`]: false,
|
|
}));
|
|
}
|
|
|
|
function reportActorSyncError(error) {
|
|
if (actorSyncErrorLogged) return;
|
|
actorSyncErrorLogged = true;
|
|
console.warn(`${MODULE_ID} | Character sync failed and will retry.`, error);
|
|
}
|
|
|
|
async function pushFoundryActors(actors, fullSync = false) {
|
|
const token = getSyncToken();
|
|
if (!token || !game.user?.isGM || !game.world || (!actors.length && !fullSync)) return;
|
|
if (game.system.id !== "dnd5e") {
|
|
throw new Error("Character sync currently requires the D&D 5e Foundry system.");
|
|
}
|
|
const supportedActors = actors.filter(isSupportedCharacterActor);
|
|
|
|
for (const actor of supportedActors) await markActorItemsAsSynced(actor);
|
|
const result = await postDragonroll("foundry/sync/snapshot", {
|
|
worldId: game.world.id,
|
|
actors: supportedActors.map(serializeFoundryActor),
|
|
// The world item directory is what the campaign lists as its items
|
|
// (Syndria98/dragonroll#67); the gear a character carries travels inside that
|
|
// actor's snapshot as its inventory, not as campaign items.
|
|
items: getWorldItemSnapshots(),
|
|
// The folder tree those world items stand in (see worldItemFolderSnapshots).
|
|
folders: worldItemFolderSnapshots(),
|
|
fullSync,
|
|
}, token);
|
|
|
|
for (const mapping of result.actors || []) {
|
|
const actor = game.actors.get(mapping.foundryActorId);
|
|
if (actor && dragonrollActorId(actor) !== mapping.actorId) {
|
|
await setDragonrollActorId(actor, mapping.actorId);
|
|
}
|
|
}
|
|
await rememberItemMappings(result.items);
|
|
actorSyncErrorLogged = false;
|
|
}
|
|
|
|
async function deleteDragonrollActor(foundryActorId) {
|
|
const token = getSyncToken();
|
|
if (!token || !game.world || !foundryActorId) return;
|
|
await postDragonroll("foundry/sync/delete", {
|
|
worldId: game.world.id,
|
|
foundryActorId,
|
|
}, token);
|
|
}
|
|
|
|
// Sending actors on purpose, whether or not autosync is on: this is the push the
|
|
// GM asks for. It upserts those actors only, so unlike a full snapshot it never
|
|
// prunes anything else the campaign holds.
|
|
async function forceSyncActorsToDragonroll(actors) {
|
|
if (!game.user?.isGM || !game.world || !actors.length) return;
|
|
if (!getSyncToken()) {
|
|
ui.notifications?.warn("Link this world to a Dragonroll campaign before syncing actors to it.");
|
|
return;
|
|
}
|
|
|
|
const supported = actors.filter(isSupportedCharacterActor);
|
|
const refused = actors.filter((actor) => !supported.includes(actor));
|
|
if (refused.length) {
|
|
ui.notifications?.warn(`${refused.map((actor) => actor.name).join(", ")} ${refused.length === 1 ? "is" : "are"} not a character, NPC or creature: Dragonroll does not import ${refused.length === 1 ? "it" : "them"}.`);
|
|
}
|
|
if (!supported.length) return;
|
|
|
|
try {
|
|
await pushFoundryActors(supported);
|
|
ui.notifications?.info(supported.length === 1
|
|
? `${supported[0].name} was sent to the Dragonroll campaign.`
|
|
: `${supported.length} actors were sent to the Dragonroll campaign.`);
|
|
} catch (error) {
|
|
console.error(`${MODULE_ID} | Could not force sync the selected actors.`, error);
|
|
ui.notifications?.error(`Dragonroll sync failed: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
function queueActorChange(kind, actor) {
|
|
if (!actor || !game.user?.isGM || !getSyncToken()) return;
|
|
if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return;
|
|
|
|
queuedActorChanges.set(actor.id, { kind, actor });
|
|
clearTimeout(actorSyncTimeout);
|
|
actorSyncTimeout = setTimeout(flushActorChanges, 400);
|
|
}
|
|
async function flushActorChanges() {
|
|
// Autosync may have been switched off while changes were queued: keep them
|
|
// waiting so turning it back on still sends them.
|
|
if (!isAutoSyncEnabled()) return;
|
|
const changes = [...queuedActorChanges.values()];
|
|
queuedActorChanges.clear();
|
|
const deleted = changes.filter((change) => change.kind === "delete");
|
|
const changed = changes.filter((change) => change.kind !== "delete");
|
|
|
|
try {
|
|
for (const change of deleted) await deleteDragonrollActor(change.actor.id);
|
|
await pushFoundryActors(changed.map((change) => change.actor));
|
|
} catch (error) {
|
|
reportActorSyncError(error);
|
|
for (const change of changes) queuedActorChanges.set(change.actor.id, change);
|
|
clearTimeout(actorSyncTimeout);
|
|
actorSyncTimeout = setTimeout(flushActorChanges, 5000);
|
|
}
|
|
}
|
|
|
|
// --- 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;
|
|
}
|
|
|
|
// --- Item folders ------------------------------------------------------------
|
|
// Dragonroll mirrors the folders the world's item directory is grouped into, so its
|
|
// item list reads like Foundry's. `game.folders` also holds the folders an actor
|
|
// keeps for its own inventory: those hang off the actor instead of the world, and
|
|
// the campaign has no use for them, so only folders rooted in the world go over.
|
|
|
|
// The folder a folder is nested in, or null when it is not nested in a folder.
|
|
function itemFolderParent(folder) {
|
|
const parent = typeof folder.parent === "string" ? game.folders?.get(folder.parent) : folder.parent;
|
|
return parent?.documentName === "Folder" ? parent : null;
|
|
}
|
|
|
|
// Whether a folder belongs to the world's item directory: its whole ancestry has
|
|
// to be folders, ending in one that nothing is above.
|
|
function isWorldItemFolder(folder, seen = new Set()) {
|
|
if (folder.type !== "Item" || seen.has(folder.id)) return false;
|
|
seen.add(folder.id);
|
|
const rawParent = folder.parent;
|
|
const rawParentId = typeof rawParent === "string" ? rawParent : rawParent?.id;
|
|
if (!rawParentId) return true;
|
|
const parent = typeof rawParent === "string" ? game.folders?.get(rawParentId) : rawParent;
|
|
if (parent?.documentName !== "Folder") return false;
|
|
return isWorldItemFolder(parent, seen);
|
|
}
|
|
|
|
// A Foundry folder's colour, or null for one the GM left uncoloured. Null travels as null:
|
|
// it tells Dragonroll to take a colour off the folder it was given before, whereas a module
|
|
// that says nothing about colours at all leaves the campaign's own choice alone.
|
|
function itemFolderColor(folder) {
|
|
const color = typeof folder?.color === "string" ? folder.color.trim() : "";
|
|
return color || null;
|
|
}
|
|
|
|
function worldItemFolderSnapshots() {
|
|
return (game.folders?.contents || [])
|
|
.filter((folder) => isWorldItemFolder(folder))
|
|
.map((folder) => ({
|
|
id: folder.id,
|
|
name: folder.name,
|
|
parent: itemFolderParent(folder)?.id || null,
|
|
color: itemFolderColor(folder),
|
|
}));
|
|
}
|
|
|
|
// A world item travels with the folder it stands in, so Dragonroll can file it the
|
|
// same way; `""` says the world keeps it at the root of the item directory. Items
|
|
// embedded in an actor use serializeFoundryItem instead: their folders are the
|
|
// actor's own, and the campaign's item list is deduplicated by name anyway.
|
|
function serializeFoundryWorldItem(item) {
|
|
const data = serializeFoundryItem(item);
|
|
if (!data) return null;
|
|
|
|
data.dragonroll = { ...data.dragonroll, folder: worldItemFolderId(item) };
|
|
return data;
|
|
}
|
|
|
|
// The folder id an item data carries is either the id or the Folder document
|
|
// itself, depending on the Foundry version.
|
|
function worldItemFolderId(item) {
|
|
const folder = item?.folder;
|
|
if (!folder) return "";
|
|
if (typeof folder === "string") return game.folders?.get(folder)?.documentName === "Folder" ? folder : "";
|
|
return folder.documentName === "Folder" ? String(folder.id || "") : "";
|
|
}
|
|
|
|
function getWorldItemSnapshots() {
|
|
return (game.items?.contents || []).map(serializeFoundryWorldItem).filter(Boolean);
|
|
}
|
|
|
|
// --- Folder colours ----------------------------------------------------------
|
|
// Colouring a folder is the one thing about the tree the campaign gets to do on its
|
|
// own: the world owns what the folders are called and how they nest, and Dragonroll
|
|
// owns the colour its user picks for one. So the colour travels back with the folder
|
|
// list the item reconcile reads, and lands on the world's folder — marked, like every
|
|
// Dragonroll write, so the world does not echo it straight back to the campaign.
|
|
|
|
async function withFolderSyncSuppressed(folder, callback) {
|
|
if (!folder?.id) return callback();
|
|
syncingFolderIds.add(folder.id);
|
|
try {
|
|
return await callback();
|
|
} finally {
|
|
syncingFolderIds.delete(folder.id);
|
|
}
|
|
}
|
|
|
|
async function applyDragonrollFolderColors(entries) {
|
|
for (const entry of entries || []) {
|
|
const folder = entry?.foundryFolderId ? game.folders?.get(entry.foundryFolderId) : null;
|
|
// Only the world's item directories: a Dragonroll folder the world has no document
|
|
// for is the campaign's business alone, and making one there is not ours to do.
|
|
if (!folder || folder.documentName !== "Folder" || !isWorldItemFolder(folder)) continue;
|
|
const color = entry.color || null;
|
|
if (itemFolderColor(folder) === color) continue;
|
|
await withFolderSyncSuppressed(folder, () => folder.update({ color }));
|
|
}
|
|
}
|
|
|
|
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(serializeFoundryWorldItem).filter(Boolean),
|
|
// The folder tree goes along, so an item that moved into or out of a folder
|
|
// arrives with the folder it names.
|
|
folders: worldItemFolderSnapshots(),
|
|
}, 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);
|
|
}
|
|
|
|
// A folder the GM made, renamed or nested has to reach the campaign even though no
|
|
// item changed, so the tree goes over on its own without pushing the items in it.
|
|
function queueFoundryItemFolders(delay = 400) {
|
|
clearTimeout(folderSyncTimeout);
|
|
folderSyncTimeout = setTimeout(pushFoundryItemFolders, delay);
|
|
}
|
|
|
|
async function pushFoundryItemFolders() {
|
|
// Autosync off: folder changes wait, like the item edits do.
|
|
if (!isAutoSyncEnabled()) return;
|
|
const token = getSyncToken();
|
|
if (!token || !game.user?.isGM || !game.world || folderSyncRunning) return;
|
|
folderSyncRunning = true;
|
|
try {
|
|
await postDragonroll("foundry/sync/item-snapshot", {
|
|
worldId: game.world.id,
|
|
items: [],
|
|
folders: worldItemFolderSnapshots(),
|
|
}, token);
|
|
itemSyncErrorLogged = false;
|
|
} catch (error) {
|
|
reportItemSyncError(error);
|
|
queueFoundryItemFolders(5000);
|
|
} finally {
|
|
folderSyncRunning = false;
|
|
}
|
|
}
|
|
|
|
async function flushItemChanges() {
|
|
// Autosync off: the queued edits wait here, like the actor changes do.
|
|
if (!isAutoSyncEnabled()) return;
|
|
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,
|
|
img: getDragonrollImageUrl(entry.image) || undefined,
|
|
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) {
|
|
const updates = {
|
|
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 || "",
|
|
};
|
|
// An icon the campaign picked in Dragonroll travels back to Foundry; no icon
|
|
// there means leave the world's own choice alone, not erase it.
|
|
const image = getDragonrollImageUrl(entry.image);
|
|
if (image) updates.img = image;
|
|
return updates;
|
|
}
|
|
|
|
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 || !isAutoSyncEnabled()) return;
|
|
itemSyncRunning = true;
|
|
try {
|
|
const result = await getDragonroll("foundry/sync/items", token);
|
|
// The folder colours are applied first, and whatever system this world runs: a
|
|
// colour is the same on every one of them, while writing an item is what needs D&D 5e.
|
|
await applyDragonrollFolderColors(result.folders);
|
|
if (game.system.id !== "dnd5e") {
|
|
throw new Error("Item sync currently requires the D&D 5e Foundry system.");
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
|
|
// --- Scene lighting ------------------------------------------------------------
|
|
// The lights of the scene being played, and the walls that stop them, travel to the Dragonroll map
|
|
// mirroring that scene; the lights the campaign places on that map travel back into the scene as
|
|
// ambient lights. Lighting belongs to a world the same way whatever system it runs, so unlike the
|
|
// actors and the items this asks for no particular one.
|
|
//
|
|
// Foundry measures a scene in canvas pixels (its background image as it is drawn) and a light's reach
|
|
// in the scene's distance units; Dragonroll measures both in pixels of the map image and of its grid.
|
|
// So a scene goes over as pixels of its own background image, and comes back through the grid cell,
|
|
// which is the one unit the two share.
|
|
|
|
// The canvas of the scene being played. `canvas` is a global only where a scene has been drawn, and
|
|
// only in a game client at that, so it is asked for the way the module asks for any global it cannot
|
|
// be sure of.
|
|
function foundryCanvas() {
|
|
return typeof canvas === "undefined" ? null : canvas;
|
|
}
|
|
|
|
// The scene whose lighting travels: the one being played. Foundry loads the walls and lights of a scene
|
|
// when it draws it, so nothing else of the world's is at hand to send.
|
|
function currentScene() {
|
|
return foundryCanvas()?.scene ?? game.scenes?.active ?? game.scenes?.current ?? null;
|
|
}
|
|
|
|
// A scene's embedded documents of one kind. Which collection holds them has moved about between Foundry
|
|
// versions, so each way is tried, best first, and only documents of the kind asked for are taken.
|
|
function sceneDocuments(scene, kind) {
|
|
if (!scene) return [];
|
|
for (const candidate of [
|
|
scene.getEmbeddedCollection?.(kind)?.contents,
|
|
scene[kind === "Wall" ? "walls" : "lighting"]?.contents,
|
|
scene.embedded?.[kind]?.contents,
|
|
scene.embeddedContents,
|
|
]) {
|
|
if (!Array.isArray(candidate)) continue;
|
|
return candidate.filter((document) => document?.documentName === kind);
|
|
}
|
|
return [];
|
|
}
|
|
|
|
function findSceneDocument(scene, kind, id) {
|
|
return sceneDocuments(scene, kind).find((document) => String(document.id) === String(id)) ?? null;
|
|
}
|
|
|
|
// Scene canvas pixels → pixels of the scene's background image at the size it has on disk, which is
|
|
// what a Dragonroll map is measured in. `dimensions.sceneRatio` is the scale that image is drawn at.
|
|
function sceneImageScale() {
|
|
const ratio = Number(foundryCanvas()?.dimensions?.sceneRatio);
|
|
return Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
|
|
}
|
|
|
|
function toSceneImagePixels(value) {
|
|
const number = Number(value);
|
|
return Number.isFinite(number) ? Math.round(number / sceneImageScale()) : 0;
|
|
}
|
|
|
|
// How wide one of the scene's cells is, in its image pixels.
|
|
function sceneImageGrid(scene) {
|
|
const grid = Number(scene?.grid ?? foundryCanvas()?.dimensions?.grid);
|
|
return Number.isFinite(grid) && grid > 0 ? Math.round(grid) : 50;
|
|
}
|
|
|
|
function sceneGridDistance(scene) {
|
|
const distance = Number(scene?.gridDistance);
|
|
return Number.isFinite(distance) && distance > 0 ? distance : 5;
|
|
}
|
|
|
|
// A light's reach, which Foundry measures in the scene's distance units, as pixels of its image: so
|
|
// many cells, at the scene's own pixels per cell.
|
|
function lightReachToImagePixels(value, scene) {
|
|
const reach = Number(value);
|
|
if (!Number.isFinite(reach) || reach <= 0) return 0;
|
|
return Math.round((reach / sceneGridDistance(scene)) * sceneImageGrid(scene));
|
|
}
|
|
|
|
// A colour of a Foundry light as its document writes it: a hex string, or a number in the versions
|
|
// that stored one that way. Empty for a light with no tint of its own.
|
|
function sceneLightColor(color) {
|
|
if (typeof color === "string") return /^#[0-9a-f]{3,8}$/i.test(color.trim()) ? color.trim().toLowerCase() : "";
|
|
if (Number.isFinite(color) && color > 0) return `#${Math.round(color).toString(16).padStart(6, "0")}`;
|
|
return "";
|
|
}
|
|
|
|
// Foundry's wall kinds and restrictions: a wall that lets the players see through it lights whatever
|
|
// it is drawn over, a wall only sensing shapes what a sensor reaches and lets light through, and a
|
|
// door left open lets the light through along with whoever opened it.
|
|
const WALL_KIND_SENSES = "sense";
|
|
const WALL_MOVEMENT_OPEN = 2;
|
|
const WALL_RESTRICTION_BLOCK = 2;
|
|
|
|
function blocksSceneLight(wall) {
|
|
if (String(wall?.wall ?? "walls") === WALL_KIND_SENSES) return false;
|
|
if (Number(wall?.move) === WALL_MOVEMENT_OPEN) return false;
|
|
return Number(wall?.sight) === WALL_RESTRICTION_BLOCK || Number(wall?.light) === WALL_RESTRICTION_BLOCK;
|
|
}
|
|
|
|
function serializeSceneLight(light, scene) {
|
|
const config = light?.config ?? {};
|
|
return {
|
|
id: String(light.id),
|
|
x: toSceneImagePixels(light.x),
|
|
y: toSceneImagePixels(light.y),
|
|
radius: lightReachToImagePixels(config.dim, scene),
|
|
bright: lightReachToImagePixels(config.bright, scene),
|
|
color: sceneLightColor(config.color),
|
|
};
|
|
}
|
|
|
|
function serializeSceneWall(wall) {
|
|
const corner = wall?.c ?? {};
|
|
return {
|
|
id: String(wall.id),
|
|
x1: toSceneImagePixels(corner.x),
|
|
y1: toSceneImagePixels(corner.y),
|
|
x2: toSceneImagePixels(corner.x2),
|
|
y2: toSceneImagePixels(corner.y2),
|
|
};
|
|
}
|
|
|
|
function sceneLightingMeta(scene) {
|
|
return {
|
|
id: scene.id,
|
|
title: String(scene.title ?? scene.name ?? ""),
|
|
grid: sceneImageGrid(scene),
|
|
gridDistance: sceneGridDistance(scene),
|
|
image: sceneBackgroundImage(scene),
|
|
};
|
|
}
|
|
|
|
// The scene's own artwork, as an address a campaign outside the world can read — the same as every
|
|
// other image the module sends (see serializeFoundryActor).
|
|
function sceneBackgroundImage(scene) {
|
|
const image = scene?.texture?.src ?? scene?.img ?? "";
|
|
if (typeof image !== "string" || !image || /^(https?:|data:|\/\/)/i.test(image)) return image || "";
|
|
return new URL(image, window.location.origin).toString();
|
|
}
|
|
|
|
// What a scene is lit by, whole. A scene with neither lights nor walls is worth sending for what it
|
|
// takes off the campaign; it is the campaign's own business whether that is worth a map of.
|
|
function sceneLightingSnapshot(scene) {
|
|
const target = scene ?? currentScene();
|
|
if (!target) return null;
|
|
return {
|
|
scene: sceneLightingMeta(target),
|
|
lights: sceneDocuments(target, "AmbientLight").map((light) => serializeSceneLight(light, target)),
|
|
walls: sceneDocuments(target, "Wall").filter(blocksSceneLight).map(serializeSceneWall),
|
|
};
|
|
}
|
|
|
|
async function pushSceneLighting() {
|
|
const token = getSyncToken();
|
|
if (!token || !game.user?.isGM || !game.world) return;
|
|
const snapshot = sceneLightingSnapshot();
|
|
if (!snapshot) return;
|
|
|
|
await postDragonroll("foundry/sync/scene", { worldId: game.world.id, ...snapshot }, token);
|
|
}
|
|
|
|
function queueSceneLightingChange(delay = 400) {
|
|
clearTimeout(sceneLightingTimeout);
|
|
sceneLightingTimeout = setTimeout(flushSceneLighting, delay);
|
|
}
|
|
|
|
async function flushSceneLighting() {
|
|
// Autosync off: the lighting edits wait with the actor and item ones, so turning it back on sends them.
|
|
if (!isAutoSyncEnabled()) return;
|
|
try {
|
|
await pushSceneLighting();
|
|
sceneLightingErrorLogged = false;
|
|
} catch (error) {
|
|
if (!sceneLightingErrorLogged) {
|
|
sceneLightingErrorLogged = true;
|
|
console.warn(`${MODULE_ID} | Scene lighting sync failed and will retry.`, error);
|
|
}
|
|
queueSceneLightingChange(5000);
|
|
}
|
|
}
|
|
|
|
// Writing into the world from the campaign is marked the same way every other Dragonroll write is, so
|
|
// the world does not echo it straight back to the campaign.
|
|
function dragonrollLightId(light) {
|
|
return light.getFlag?.(MODULE_ID, "lightId") || light.flags?.[MODULE_ID]?.lightId || "";
|
|
}
|
|
|
|
function isSceneLightingMutation(document) {
|
|
return document?.flags?.[MODULE_ID]?.syncMutation === true || syncingLightIds.has(document?.id);
|
|
}
|
|
|
|
async function withLightSyncSuppressed(light, callback) {
|
|
if (!light?.id) return callback();
|
|
syncingLightIds.add(light.id);
|
|
try {
|
|
return await callback();
|
|
} finally {
|
|
syncingLightIds.delete(light.id);
|
|
}
|
|
}
|
|
|
|
// How many canvas pixels one pixel of the campaign's map is worth in the scene being written to: cells
|
|
// first, then the cell as the world's canvas draws it.
|
|
function mapPixelsToSceneCanvas(value, mirror) {
|
|
const cell = Number(mirror?.gridSize) || sceneImageGrid(currentScene());
|
|
const gridPixels = Number(foundryCanvas()?.dimensions?.gridPixels) || sceneImageGrid(currentScene()) * sceneImageScale();
|
|
const number = Number(value);
|
|
if (!Number.isFinite(number)) return 0;
|
|
return Math.round((number / Math.max(1, cell)) * gridPixels);
|
|
}
|
|
|
|
// A reach of the campaign's map, in its pixels, as so many of the scene's distance units. `scale` is
|
|
// how much distance one cell of the map stands for, which is what Foundry measures a light in.
|
|
function mapPixelsToSceneDistance(value, mirror) {
|
|
const cell = Number(mirror?.gridSize) || sceneImageGrid(currentScene());
|
|
const perCell = Number(mirror?.scale) || sceneGridDistance(currentScene());
|
|
const number = Number(value);
|
|
if (!Number.isFinite(number) || number <= 0) return 0;
|
|
return Math.round(((number / Math.max(1, cell)) * perCell * 100)) / 100;
|
|
}
|
|
|
|
function sceneLightUpdateData(entry, mirror) {
|
|
return {
|
|
x: mapPixelsToSceneCanvas(entry.x, mirror),
|
|
y: mapPixelsToSceneCanvas(entry.y, mirror),
|
|
"config.dim": mapPixelsToSceneDistance(entry.radius, mirror),
|
|
"config.bright": mapPixelsToSceneDistance(entry.bright, mirror),
|
|
"config.color": entry.color || null,
|
|
};
|
|
}
|
|
|
|
// Whether a light of the world already says what the campaign's light says — within a pixel, and within
|
|
// a hundredth of a distance unit. Writing a light that is already where it belongs is how a sync would
|
|
// never come to rest: the two sides measure in different units and round differently doing it.
|
|
function sceneLightMatches(light, entry, mirror) {
|
|
const updates = sceneLightUpdateData(entry, mirror);
|
|
const near = (foundry, wanted, tolerance) => Math.abs(Number(foundry ?? 0) - Number(wanted ?? 0)) <= tolerance;
|
|
return near(light.x, updates.x, 1)
|
|
&& near(light.y, updates.y, 1)
|
|
&& near(light.config?.radius?.dim, updates["config.dim"], 0.01)
|
|
&& near(light.config?.radius?.bright, updates["config.bright"], 0.01)
|
|
&& sceneLightColor(light.config?.color) === String(entry.color ?? "").toLowerCase();
|
|
}
|
|
|
|
async function mapDragonrollSceneLight(mapId, lightId, foundryLightId) {
|
|
const token = getSyncToken();
|
|
return postDragonroll("foundry/sync/map-scene-light", {
|
|
worldId: game.world.id,
|
|
map: String(mapId),
|
|
light: String(lightId),
|
|
foundryLightId: String(foundryLightId),
|
|
}, token);
|
|
}
|
|
|
|
function makeSceneLightData(entry, mirror) {
|
|
return {
|
|
name: String(mirror?.name || "Dragonroll") + " light",
|
|
hidden: false,
|
|
x: mapPixelsToSceneCanvas(entry.x, mirror),
|
|
y: mapPixelsToSceneCanvas(entry.y, mirror),
|
|
config: {
|
|
alpha: 1,
|
|
dim: mapPixelsToSceneDistance(entry.radius, mirror),
|
|
bright: mapPixelsToSceneDistance(entry.bright, mirror),
|
|
color: entry.color || null,
|
|
},
|
|
flags: { [MODULE_ID]: { lightId: String(entry._id), syncMutation: true } },
|
|
};
|
|
}
|
|
|
|
async function createSceneLightFromDragonroll(scene, entry, mirror) {
|
|
const LightDocument = CONFIG.AmbientLight?.documentClass ?? (typeof AmbientLight === "undefined" ? null : AmbientLight);
|
|
if (!LightDocument?.create) return null;
|
|
const created = await LightDocument.create(makeSceneLightData(entry, mirror), { parent: scene });
|
|
const light = Array.isArray(created) ? created[0] : created;
|
|
if (!light) return null;
|
|
|
|
await withLightSyncSuppressed(light, async () => {
|
|
await light.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
|
|
});
|
|
await mapDragonrollSceneLight(mirror._id, entry._id, light.id);
|
|
return light;
|
|
}
|
|
|
|
async function applyDragonrollSceneLight(light, entry, mirror) {
|
|
const retag = dragonrollLightId(light) !== String(entry._id)
|
|
? { [`flags.${MODULE_ID}.lightId`]: String(entry._id) }
|
|
: null;
|
|
// Already where the campaign says it is: nothing is written, which is what keeps this from
|
|
// rewriting the world's lighting every few seconds for the rest of the evening.
|
|
if (sceneLightMatches(light, entry, mirror)) {
|
|
if (retag) await light.update(retag);
|
|
return;
|
|
}
|
|
|
|
await withLightSyncSuppressed(light, async () => {
|
|
await light.update(sceneLightUpdateData(entry, mirror));
|
|
if (retag) await light.update(retag);
|
|
});
|
|
}
|
|
|
|
// Which of the campaign's maps the scene being played mirrors: the one that says it does, failing that
|
|
// a map of the same name — the same courtesy the item sync offers a hand-written row, and refused the
|
|
// moment two maps of that name leave it a guess.
|
|
function sceneMirrorMap(scenes, scene) {
|
|
const rows = Array.isArray(scenes) ? scenes : [];
|
|
const mapped = rows.find((row) => row.foundrySceneId && String(row.foundrySceneId) === String(scene.id));
|
|
if (mapped) return mapped;
|
|
|
|
const title = String(scene.title ?? scene.name ?? "").trim();
|
|
if (!title) return null;
|
|
const namesakes = rows.filter((row) => !row.foundrySceneId && String(row.name ?? "").trim() === title);
|
|
return namesakes.length === 1 ? namesakes[0] : null;
|
|
}
|
|
|
|
async function reconcileDragonrollSceneLighting() {
|
|
const token = getSyncToken();
|
|
if (!token || !game.user?.isGM || !game.world || sceneLightingRunning || !isAutoSyncEnabled()) return;
|
|
const scene = currentScene();
|
|
if (!scene) return;
|
|
sceneLightingRunning = true;
|
|
try {
|
|
const result = await getDragonroll("foundry/sync/scenes", token);
|
|
const mirror = sceneMirrorMap(result.scenes, scene);
|
|
if (!mirror) return;
|
|
|
|
const entries = Array.isArray(mirror.lights) ? mirror.lights : [];
|
|
const wanted = new Set(entries.map((entry) => String(entry._id)));
|
|
const localByRemoteId = new Map(sceneDocuments(scene, "AmbientLight")
|
|
.map((light) => [String(dragonrollLightId(light)), light])
|
|
.filter(([lightId]) => lightId));
|
|
const retained = new Set();
|
|
|
|
for (const entry of entries) {
|
|
let light = entry.foundryLightId ? findSceneDocument(scene, "AmbientLight", entry.foundryLightId) : null;
|
|
if (!light) light = localByRemoteId.get(String(entry._id));
|
|
if (light) {
|
|
retained.add(light.id);
|
|
await applyDragonrollSceneLight(light, entry, mirror);
|
|
if (!entry.foundryLightId) await mapDragonrollSceneLight(mirror._id, entry._id, light.id);
|
|
} else if (entry.foundryLightId) {
|
|
// A light of another world's scene, or one the campaign read from a scene that is not this one:
|
|
// its own scene owns it, so cloning it here would light the room twice.
|
|
continue;
|
|
} else {
|
|
const created = await createSceneLightFromDragonroll(scene, entry, mirror);
|
|
if (created) retained.add(created.id);
|
|
}
|
|
}
|
|
|
|
// A light the campaign put out is taken out of the world along with it — only one the world was
|
|
// told it wrote, never a lamp the GM lit themselves.
|
|
for (const light of sceneDocuments(scene, "AmbientLight")) {
|
|
const lightId = dragonrollLightId(light);
|
|
if (!lightId || retained.has(light.id) || wanted.has(String(lightId))) continue;
|
|
await withLightSyncSuppressed(light, () => light.delete());
|
|
}
|
|
sceneLightingErrorLogged = false;
|
|
} catch (error) {
|
|
if (!sceneLightingErrorLogged) {
|
|
sceneLightingErrorLogged = true;
|
|
console.warn(`${MODULE_ID} | Scene lighting reconcile failed and will retry.`, error);
|
|
}
|
|
} finally {
|
|
sceneLightingRunning = false;
|
|
}
|
|
}
|
|
|
|
function getDragonrollImageUrl(image) {
|
|
if (!image) return "";
|
|
if (/^(https?:|data:|\/\/)/i.test(image)) return image;
|
|
|
|
const endpoint = new URL(game.settings.get(MODULE_ID, SETTING_DRAGONROLL_API_URL));
|
|
const basePath = endpoint.pathname.replace(/\/+$/, "");
|
|
endpoint.pathname = `${basePath.endsWith("/api") ? basePath : `${basePath}/api`}/public/${encodeURIComponent(image)}`;
|
|
endpoint.search = "";
|
|
endpoint.hash = "";
|
|
return endpoint.toString();
|
|
}
|
|
|
|
function makeFoundryCharacterData(entry) {
|
|
const stats = entry.abilityScores || {};
|
|
const items = [];
|
|
if (entry.className) items.push({ name: entry.className, type: "class", system: { levels: Number(entry.level) || 1 } });
|
|
if (entry.subclass) items.push({ name: entry.subclass, type: "subclass" });
|
|
if (entry.background) items.push({ name: entry.background, type: "background" });
|
|
for (const name of String(entry.spells || "").split("\n").map((value) => value.trim()).filter(Boolean)) {
|
|
items.push({ name, type: "spell" });
|
|
}
|
|
for (const item of entry.inventory || []) {
|
|
if (!item.name?.trim()) continue;
|
|
items.push({
|
|
name: item.name.trim(),
|
|
type: "loot",
|
|
system: { quantity: Number(item.quantity) || 1, weight: { value: Number(item.weight) || 0 } },
|
|
});
|
|
}
|
|
|
|
return {
|
|
name: entry.name,
|
|
type: entry.type === "character" ? "character" : "npc",
|
|
img: getDragonrollImageUrl(entry.image) || undefined,
|
|
system: {
|
|
// `details.race` and `details.background` are left out on purpose: they reference
|
|
// embedded items and are linked once the actor stands with its items made.
|
|
details: {
|
|
level: Number(entry.level) || 1,
|
|
biography: { value: entry.description || "" },
|
|
cr: entry.challengeRating || "",
|
|
},
|
|
abilities: Object.fromEntries(["str", "dex", "con", "int", "wis", "cha"].map((key) => [
|
|
key,
|
|
{ value: Number(stats[key]) || 10 },
|
|
])),
|
|
attributes: {
|
|
ac: { value: Number(entry.armorClass) || 10 },
|
|
movement: { walk: Number(entry.speed) || 30 },
|
|
},
|
|
},
|
|
items,
|
|
flags: { [MODULE_ID]: {
|
|
actorId: String(entry._id),
|
|
actorType: entry.type,
|
|
traits: entry.traits || "",
|
|
proficiencies: entry.proficiencies || "",
|
|
syncMutation: true,
|
|
} },
|
|
};
|
|
}
|
|
|
|
function documentValue(document, path) {
|
|
return path.split(".").reduce((value, key) => value?.[key], document);
|
|
}
|
|
|
|
function characterUpdateData(entry) {
|
|
const stats = entry.abilityScores || {};
|
|
const updates = {
|
|
name: entry.name,
|
|
img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg",
|
|
"system.details.level": Number(entry.level) || 1,
|
|
"system.details.biography.value": entry.description || "",
|
|
"system.details.cr": entry.challengeRating || "",
|
|
[`flags.${MODULE_ID}.traits`]: entry.traits || "",
|
|
[`flags.${MODULE_ID}.proficiencies`]: entry.proficiencies || "",
|
|
"system.attributes.ac.value": Number(entry.armorClass) || 10,
|
|
"system.attributes.movement.walk": Number(entry.speed) || 30,
|
|
};
|
|
for (const key of ["str", "dex", "con", "int", "wis", "cha"]) {
|
|
updates[`system.abilities.${key}.value`] = Number(stats[key]) || 10;
|
|
}
|
|
return updates;
|
|
}
|
|
|
|
// `system.details.background` and `system.details.race` are LocalDocumentFields in
|
|
// D&D 5e: they hold the id of an item embedded in the actor, never its name. A name
|
|
// written into one is a reference that resolves to nothing, and adding that item in
|
|
// Foundry then fails, so each of these follows the actor's own item for it instead.
|
|
const EMBEDDED_DETAILS = [
|
|
// Dragonroll owns the background item it lists, so its reference follows it always and
|
|
// a background taken off in the campaign leaves no reference behind.
|
|
{ field: "background", path: "system.details.background", types: ["background"], clearWhenMissing: true },
|
|
// The species item belongs to the world: point at it when it carries the name, and
|
|
// leave the reference to the GM when it does not.
|
|
{ field: "species", path: "system.details.race", types: ["race", "species"] },
|
|
];
|
|
|
|
function localDocumentId(value) {
|
|
// The field resolves to the referenced document when it can and to the stored id
|
|
// when the document is gone (its `fallback` option).
|
|
if (typeof value === "string") return value;
|
|
return value?._id || "";
|
|
}
|
|
|
|
function embeddedDetailReferenceData(actor, entry) {
|
|
const updates = {};
|
|
for (const detail of EMBEDDED_DETAILS) {
|
|
const wanted = String(entry[detail.field] || "").trim();
|
|
const item = wanted
|
|
? actor.items?.contents?.find((candidate) => detail.types.includes(candidate.type) && candidate.name === wanted)
|
|
: null;
|
|
const reference = item?.id || "";
|
|
if (!reference && !detail.clearWhenMissing) continue;
|
|
if (localDocumentId(documentValue(actor, detail.path)) !== reference) updates[detail.path] = reference;
|
|
}
|
|
return updates;
|
|
}
|
|
|
|
async function reconcileEmbeddedItems(actor, entry) {
|
|
const desired = [];
|
|
if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } });
|
|
if (entry.subclass) desired.push({ type: "subclass", name: entry.subclass });
|
|
if (entry.background) desired.push({ type: "background", name: entry.background });
|
|
for (const name of String(entry.spells || "").split("\n").map((value) => value.trim()).filter(Boolean)) {
|
|
desired.push({ type: "spell", name });
|
|
}
|
|
for (const item of entry.inventory || []) {
|
|
if (item.name?.trim()) desired.push({
|
|
type: "loot",
|
|
name: item.name.trim(),
|
|
system: { quantity: Number(item.quantity) || 1, weight: { value: Number(item.weight) || 0 } },
|
|
});
|
|
}
|
|
|
|
const retainedIds = new Set();
|
|
for (const wanted of desired) {
|
|
const existing = actor.items.contents.find((item) => item.name === wanted.name
|
|
&& item.type === wanted.type && item.getFlag?.(MODULE_ID, "syncedItem"))
|
|
|| actor.items.contents.find((item) => item.name === wanted.name
|
|
&& item.getFlag?.(MODULE_ID, "syncedItem") && !WORLD_OWNED_EMBEDDED_TYPES.has(item.type));
|
|
// A carried row holding the name of one of the world's own trait or species documents
|
|
// — a trait a campaign that synced before #89 still has in its inventory — stands in
|
|
// the world as that document: no loot is made after its name, and the document itself
|
|
// is let be. Writing it out of the campaign is the campaign's to do, keeping it is the world's.
|
|
if (!existing && wanted.type === "loot") {
|
|
const worldOwned = actor.items.contents.find((item) => item.name === wanted.name
|
|
&& WORLD_OWNED_EMBEDDED_TYPES.has(item.type));
|
|
if (worldOwned) {
|
|
retainedIds.add(worldOwned.id);
|
|
continue;
|
|
}
|
|
}
|
|
if (existing) {
|
|
retainedIds.add(existing.id);
|
|
const update = { _id: existing.id };
|
|
const expected = { name: wanted.name };
|
|
if (wanted.system?.levels !== undefined) expected["system.levels"] = wanted.system.levels;
|
|
if (wanted.system?.quantity !== undefined) expected["system.quantity"] = wanted.system.quantity;
|
|
if (wanted.system?.weight?.value !== undefined) expected["system.weight.value"] = wanted.system.weight.value;
|
|
let changed = false;
|
|
for (const [key, value] of Object.entries(expected)) {
|
|
if (documentValue(existing, key) !== value) {
|
|
update[key] = value;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (changed) await actor.updateEmbeddedDocuments("Item", [update]);
|
|
} else {
|
|
const created = await actor.createEmbeddedDocuments("Item", [{
|
|
...wanted,
|
|
flags: { [MODULE_ID]: { syncedItem: true } },
|
|
}]);
|
|
for (const item of created) retainedIds.add(item.id);
|
|
}
|
|
}
|
|
|
|
const staleItemIds = actor.items.contents
|
|
.filter((item) => item.getFlag?.(MODULE_ID, "syncedItem") && !retainedIds.has(item.id)
|
|
&& !WORLD_OWNED_EMBEDDED_TYPES.has(item.type))
|
|
.map((item) => item.id);
|
|
if (staleItemIds.length) await actor.deleteEmbeddedDocuments("Item", staleItemIds);
|
|
}
|
|
|
|
async function applyDragonrollCharacter(actor, entry) {
|
|
const updates = characterUpdateData(entry);
|
|
const changed = Object.entries(updates).some(([key, value]) => documentValue(actor, key) !== value);
|
|
await withActorSyncSuppressed(actor, async () => {
|
|
if (changed) await actor.update(updates);
|
|
await reconcileEmbeddedItems(actor, entry);
|
|
// The item references are written after the reconcile that makes the items they point at.
|
|
const references = embeddedDetailReferenceData(actor, entry);
|
|
if (Object.keys(references).length) await actor.update(references);
|
|
if (dragonrollActorId(actor) !== String(entry._id)
|
|
|| actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) {
|
|
await actor.update({
|
|
[`flags.${MODULE_ID}.actorId`]: String(entry._id),
|
|
[`flags.${MODULE_ID}.actorType`]: entry.type,
|
|
});
|
|
}
|
|
});
|
|
}
|
|
|
|
async function mapDragonrollActor(actorId, foundryActorId) {
|
|
const token = getSyncToken();
|
|
return postDragonroll("foundry/sync/map", {
|
|
worldId: game.world.id,
|
|
actorId: String(actorId),
|
|
foundryActorId: String(foundryActorId),
|
|
}, token);
|
|
}
|
|
|
|
async function createFoundryCharacter(entry) {
|
|
if (game.system.id !== "dnd5e") {
|
|
throw new Error("Character sync currently requires the D&D 5e Foundry system.");
|
|
}
|
|
const actor = await Actor.create(makeFoundryCharacterData(entry), { renderSheet: false });
|
|
if (!actor) return;
|
|
|
|
await withActorSyncSuppressed(actor, async () => {
|
|
await actor.update({
|
|
// The actor was made with its items, so its background and species references
|
|
// can point at them right away.
|
|
...embeddedDetailReferenceData(actor, entry),
|
|
[`flags.${MODULE_ID}.syncMutation`]: false,
|
|
});
|
|
});
|
|
await mapDragonrollActor(entry._id, actor.id);
|
|
}
|
|
|
|
async function reconcileDragonrollCharacters() {
|
|
const token = getSyncToken();
|
|
if (!token || !game.user?.isGM || !game.world || characterSyncRunning || !isAutoSyncEnabled()) return;
|
|
characterSyncRunning = true;
|
|
try {
|
|
if (game.system.id !== "dnd5e") {
|
|
throw new Error("Character sync currently requires the D&D 5e Foundry system.");
|
|
}
|
|
const result = await getDragonroll("foundry/sync/characters", token);
|
|
const remoteActors = result.actors || [];
|
|
const remoteById = new Map(remoteActors.map((actor) => [String(actor._id), actor]));
|
|
const localByRemoteId = new Map(game.actors.contents
|
|
.map((actor) => [String(dragonrollActorId(actor)), actor])
|
|
.filter(([actorId]) => actorId));
|
|
const retainedFoundryIds = new Set();
|
|
|
|
for (const entry of remoteActors) {
|
|
let actor = entry.foundryActorId ? game.actors.get(entry.foundryActorId) : null;
|
|
if (!actor) actor = localByRemoteId.get(String(entry._id));
|
|
if (actor) {
|
|
retainedFoundryIds.add(actor.id);
|
|
await applyDragonrollCharacter(actor, entry);
|
|
if (!entry.foundryActorId) await mapDragonrollActor(entry._id, actor.id);
|
|
} else {
|
|
await createFoundryCharacter(entry);
|
|
}
|
|
}
|
|
|
|
for (const actor of game.actors.contents) {
|
|
const actorId = dragonrollActorId(actor);
|
|
if (!actorId || retainedFoundryIds.has(actor.id) || remoteById.has(String(actorId))) continue;
|
|
await withActorSyncSuppressed(actor, () => actor.delete());
|
|
}
|
|
actorSyncErrorLogged = false;
|
|
} catch (error) {
|
|
reportActorSyncError(error);
|
|
} finally {
|
|
characterSyncRunning = false;
|
|
}
|
|
}
|
|
|
|
// Both sides converge on a timer that only runs while the world is open, so a
|
|
// round that could not reach Dragonroll is asked for again in a while instead of
|
|
// leaving the campaign with whatever it happened to receive.
|
|
function scheduleDragonrollCharacterSync(delay = 15000) {
|
|
clearTimeout(characterSyncRetryTimeout);
|
|
characterSyncRetryTimeout = setTimeout(reconcileDragonrollCharacters, delay);
|
|
}
|
|
|
|
async function initializeCharacterSync() {
|
|
if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return;
|
|
try {
|
|
await pushFoundryActors(game.actors.contents, true);
|
|
await reconcileDragonrollCharacters();
|
|
} catch (error) {
|
|
reportActorSyncError(error);
|
|
scheduleDragonrollCharacterSync(15000);
|
|
}
|
|
}
|
|
|
|
function queueFoundryActorChange(kind, actor) {
|
|
if (kind !== "delete" && (actor.flags?.[MODULE_ID]?.syncMutation || syncingActorIds.has(actor.id))) return;
|
|
queueActorChange(kind, actor);
|
|
}
|
|
|
|
async function publishSnapshot() {
|
|
if (!game.user?.isGM || !game.world) return;
|
|
if (syncInProgress) {
|
|
syncRequested = true;
|
|
return;
|
|
}
|
|
|
|
const bridgeConfig = getBridgeConfig();
|
|
if (!bridgeConfig) return;
|
|
|
|
syncInProgress = true;
|
|
try {
|
|
const actorItems = Object.fromEntries(
|
|
game.actors.contents.map((actor) => [
|
|
actor.id,
|
|
actor.items.contents.map(toPlainData),
|
|
]),
|
|
);
|
|
|
|
const response = await fetch(new URL("internal/snapshot", `${bridgeConfig.url.replace(/\/+$/, "")}/`), {
|
|
method: "POST",
|
|
headers: {
|
|
"Authorization": `Bearer ${bridgeConfig.pushToken}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
world: api.getWorld(),
|
|
actors: api.getActors(),
|
|
items: api.getItems(),
|
|
actorItems,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Bridge returned HTTP ${response.status}.`);
|
|
}
|
|
} catch (error) {
|
|
console.error(`${MODULE_ID} | Could not publish the world snapshot.`, error);
|
|
scheduleSnapshotSync(15000);
|
|
} finally {
|
|
syncInProgress = false;
|
|
if (syncRequested) {
|
|
syncRequested = false;
|
|
scheduleSnapshotSync();
|
|
}
|
|
}
|
|
}
|
|
|
|
async function publishHeartbeat() {
|
|
if (!game.user?.isGM || !game.world) return;
|
|
|
|
const bridgeConfig = getBridgeConfig();
|
|
if (!bridgeConfig) return;
|
|
|
|
try {
|
|
const response = await fetch(new URL("internal/heartbeat", `${bridgeConfig.url.replace(/\/+$/, "")}/`), {
|
|
method: "POST",
|
|
headers: {
|
|
"Authorization": `Bearer ${bridgeConfig.pushToken}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({ worldId: game.world.id }),
|
|
});
|
|
|
|
if (response.status === 409 || response.status === 503) {
|
|
scheduleSnapshotSync(0);
|
|
return;
|
|
}
|
|
if (!response.ok) throw new Error(`Bridge returned HTTP ${response.status}.`);
|
|
} catch (error) {
|
|
console.warn(`${MODULE_ID} | Bridge heartbeat failed.`, error);
|
|
scheduleSnapshotSync(15000);
|
|
}
|
|
}
|
|
|
|
Hooks.once("ready", () => {
|
|
advanceDragonrollLink().then(refreshPairingStatus);
|
|
// While this world has no campaign, its sign-up link is what the GM has to
|
|
// work with: keep showing it and keep asking whether it has been answered.
|
|
setInterval(() => {
|
|
if (getSyncToken()) return;
|
|
advanceDragonrollLink();
|
|
}, LINK_POLL_MS);
|
|
setInterval(refreshPairingStatus, 60000);
|
|
scheduleSnapshotSync(0);
|
|
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);
|
|
// The scene being played is lit once its canvas is drawn: send what lights it, and write back the
|
|
// lights the campaign has placed on the map mirroring it.
|
|
queueSceneLightingChange(3000);
|
|
setInterval(reconcileDragonrollSceneLighting, 5000);
|
|
|
|
for (const event of [
|
|
"createActor", "updateActor", "deleteActor",
|
|
"createItem", "updateItem", "deleteItem",
|
|
"createFolder", "updateFolder", "deleteFolder",
|
|
"createAmbientLight", "updateAmbientLight", "deleteAmbientLight",
|
|
"createWall", "updateWall", "deleteWall",
|
|
]) {
|
|
Hooks.on(event, (document) => {
|
|
scheduleSnapshotSync();
|
|
const isDelete = event.startsWith("delete");
|
|
|
|
if (document.documentName === "Actor") {
|
|
queueFoundryActorChange(isDelete ? "delete" : "upsert", document);
|
|
return;
|
|
}
|
|
// A wall the GM draws or a lamp they move changes how the scene reads, so the whole of its
|
|
// lighting goes over. A light Dragonroll has just written into the scene is not the GM's doing.
|
|
if (document.documentName === "AmbientLight" || document.documentName === "Wall") {
|
|
if (isSceneLightingMutation(document)) return;
|
|
queueSceneLightingChange();
|
|
return;
|
|
}
|
|
// An item folder the GM made, renamed or nested changes the tree the campaign
|
|
// mirrors; nothing about the items themselves changed, so only the tree goes.
|
|
// A colour Dragonroll has just written into the folder is not the GM changing it.
|
|
if (document.documentName === "Folder") {
|
|
if (syncingFolderIds.has(document.id)) return;
|
|
if (document.type === "Item" && isWorldItemFolder(document)) queueFoundryItemFolders();
|
|
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);
|
|
});
|
|
}
|
|
});
|
|
|
|
// Moving to another scene changes which of the world's lighting the campaign mirrors: what lights the
|
|
// new scene is sent, and the lights the campaign placed on its map are written back into it. A canvas
|
|
// is not worth reading the moment it is initialised, so both are asked for a little later.
|
|
Hooks.on("canvasInit", () => {
|
|
if (!game.user?.isGM || !getSyncToken()) return;
|
|
queueSceneLightingChange(1200);
|
|
setTimeout(reconcileDragonrollSceneLighting, 1500);
|
|
});
|
|
|
|
// A GM sends selected actors to Dragonroll from the actor directory's context
|
|
// menu. This works with autosync on and off: it is the one push done on purpose.
|
|
Hooks.on("getActorDirectoryEntryContext", (html, options) => {
|
|
if (!game.user?.isGM || !getSyncToken()) return;
|
|
|
|
options.push({
|
|
name: "Dragonroll: Force Sync",
|
|
icon: '<i class="fa-solid fa-rotate"></i>',
|
|
// Array.from: the selected entries are jQuery in Foundry 12 and a plain
|
|
// array afterwards, and both are array-like.
|
|
callback: (entries) => forceSyncActorsToDragonroll(
|
|
Array.from(entries || [])
|
|
.map((entry) => game.actors?.get(entry.dataset?.actorId))
|
|
.filter(Boolean),
|
|
),
|
|
});
|
|
});
|