Fix issue #8: Sync toggle on foundry

This commit is contained in:
Gitea OpenCode Agent
2026-10-13 23:02:43 +00:00
parent af76cf1050
commit 7d19a22a4b
6 changed files with 439 additions and 9 deletions

View File

@@ -53,6 +53,25 @@ 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.
### Auto-sync, and sending one actor on purpose
**Dragonroll Auto-sync** in the module settings (on by default) is what keeps the campaign and this
world in step: actors and world items the GM creates, updates or deletes are sent to Dragonroll, and
both sides reconcile every few seconds. Turn it off to stop synchronizing altogether — nothing is
sent to the campaign, and Dragonroll stops rewriting those documents in Foundry, so the campaign
keeps whatever it already holds. Turn it back on to reconcile both sides again; the Foundry edits
queued while it was off are sent as the world catches up.
With autosync off — or any time a single character needs to cross over right now — right-click an
actor (or several selected ones) in the Foundry actor directory and pick **Dragonroll: Force Sync**.
Those actors, together with the gear carried inside them, are pushed to the campaign immediately even
when autosync is off. It is an upsert only: it never prunes the campaign's other actors, which a full
snapshot does and a forced sync never claims to. Actors Dragonroll does not import (anything that is
not a character, NPC or creature) are refused with a notification.
The optional read-only snapshot bridge is not affected: it keeps publishing the world snapshot behind
`/api/foundry/*`, which is never written into the campaign.
### Items
The campaign's Item list is synchronized with the world's gear, both ways:

View File

@@ -2,7 +2,7 @@
"id": "dragonroll-foundry",
"title": "Dragonroll Foundry API",
"description": "Links a Foundry world to a Dragonroll campaign and exposes a client-side API for world data.",
"version": "0.3.0",
"version": "0.4.0",
"library": true,
"compatibility": {
"minimum": "12",

View File

@@ -5,6 +5,7 @@ const SETTING_BRIDGE_CONFIG = "bridgeConfig";
const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl";
const SETTING_LINK_CODE = "linkCode";
const SETTING_SYNC_TOKEN = "syncToken";
const SETTING_AUTO_SYNC = "autoSync";
let syncTimeout;
let syncInProgress = false;
let syncRequested = false;
@@ -139,6 +140,16 @@ Hooks.once("init", () => {
onChange: handleLinkCodeChange,
});
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.`);
@@ -287,6 +298,35 @@ 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);
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();
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 || "";
}
@@ -380,6 +420,34 @@ async function deleteDragonrollActor(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;
@@ -389,6 +457,9 @@ function queueActorChange(kind, actor) {
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");
@@ -518,6 +589,8 @@ function queueFoundryItemChange(kind, item) {
}
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");
@@ -616,7 +689,7 @@ async function createFoundryWorldItem(entry) {
async function reconcileDragonrollItems() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return;
if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return;
itemSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
@@ -847,7 +920,7 @@ async function createFoundryCharacter(entry) {
async function reconcileDragonrollCharacters() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || characterSyncRunning) return;
if (!token || !game.user?.isGM || !game.world || characterSyncRunning || !isAutoSyncEnabled()) return;
characterSyncRunning = true;
try {
if (game.system.id !== "dnd5e") {
@@ -887,7 +960,7 @@ async function reconcileDragonrollCharacters() {
}
async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world) return;
if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return;
try {
await pushFoundryActors(game.actors.contents, true);
await reconcileDragonrollCharacters();
@@ -1016,3 +1089,21 @@ Hooks.once("ready", () => {
});
}
});
// 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),
),
});
});