Fix issue #19: Add unified campaign sync

This commit is contained in:
Gitea OpenCode Agent
2026-10-14 14:07:52 +00:00
parent 9d9738b2b4
commit 0a8452b3c8
22 changed files with 1469 additions and 921 deletions

View File

@@ -4,25 +4,24 @@ 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 handlingLinkCode = false;
let updatingLinkCodeSetting = false;
let linkRetriesDisabled = false;
const FATAL_LINK_ERRORS = new Set([
"foundry.errors.link-expired",
"foundry.errors.world-already-linked",
]);
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 pairingProblem = "";
let linkProblem = "";
let actorSyncTimeout;
let characterSyncRunning = false;
let actorSyncErrorLogged = false;
@@ -138,18 +137,24 @@ Hooks.once("init", () => {
});
game.settings.register(MODULE_ID, SETTING_LINK_CODE, {
name: "Dragonroll Campaign Pairing Code",
hint: "Paste a pairing code created in Dragonroll campaign settings.",
name: "Dragonroll Connection Link Code",
scope: "client",
config: true,
config: false,
type: String,
default: "",
});
game.settings.register(MODULE_ID, SETTING_LINK_URL, {
name: "Dragonroll Connection Link",
scope: "client",
config: false,
type: String,
default: "",
onChange: handleLinkCodeChange,
});
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 and the pairing lives in the browser of whoever linked the world: there is nothing to set here.",
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,
@@ -218,90 +223,113 @@ async function getDragonroll(path, token) {
return result;
}
function linkErrorMessage(error) {
const messages = {
"foundry.errors.link-expired": "The pairing code is invalid, expired, or already used.",
"foundry.errors.world-already-linked": "This Foundry world is already linked to another campaign.",
// --- 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 },
},
};
return messages[error.message] || error.message;
}
async function setLinkCode(value) {
updatingLinkCodeSetting = true;
async function setLink(code, url) {
updatingLinkSetting = true;
try {
await game.settings.set(MODULE_ID, SETTING_LINK_CODE, value);
await game.settings.set(MODULE_ID, SETTING_LINK_CODE, code);
await game.settings.set(MODULE_ID, SETTING_LINK_URL, url);
} finally {
updatingLinkCodeSetting = false;
updatingLinkSetting = false;
}
}
function handleLinkCodeChange(value) {
if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return;
linkRetriesDisabled = false;
// A code typed by hand supersedes whatever went wrong with the last one.
pairingProblem = "";
setPairingStatus(pairingStatusText());
completeDragonrollCampaignLink(value.trim());
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());
}
}
async function completeDragonrollCampaignLink(code, options = {}) {
if (handlingLinkCode) return;
handlingLinkCode = true;
const notifyOnError = options.notifyOnError !== false;
try {
if (!game.user?.isGM || !game.world) throw new Error("Open the world as a GM to link it.");
const result = await postDragonroll("foundry/link/complete", { code, world: api.getWorld() });
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);
}
// 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("The world was linked, but its bridge settings could not be saved on this client.");
}
}
// Keep an unprocessed pairing code in the setting when its sync token could
// not be saved, so the retry below can complete the link again.
if (syncTokenStored || !result.syncToken) await setLinkCode("");
if (!syncTokenStored) {
ui.notifications?.warn("The world was linked, but character sync is unavailable. Update Dragonroll and link the world again.");
}
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);
linkedCampaignName = String(result.campaign?.name || "").trim();
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
await setPairingStatus(pairingStatusText());
} catch (error) {
console.error(`${MODULE_ID} | Could not complete the campaign link.`, error);
// Expired or already-used codes will never redeem, so stop the background
// retry; any error keeps retrying (the Dragonroll server may be restarting).
linkRetriesDisabled = FATAL_LINK_ERRORS.has(error.message);
// Only a code that can never be redeemed belongs in the status: while the
// retry is still running, waiting for Dragonroll is the honest text.
if (linkRetriesDisabled) pairingProblem = linkErrorMessage(error);
if (notifyOnError) ui.notifications?.error(linkErrorMessage(error));
await setPairingStatus(pairingStatusText());
} finally {
handlingLinkCode = false;
} 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.");
}
}
// A pairing code entered while the Dragonroll server was unreachable (or just
// before Foundry restarted) stays in the setting; redeem it on world start so
// the connection survives restarts without typing the code in again.
async function resumePendingDragonrollLink(options = {}) {
if (handlingLinkCode || !game.user?.isGM || !game.world) return;
// 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) await completeDragonrollCampaignLink(code, options);
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 --------------------------------------------------------
@@ -310,19 +338,22 @@ async function resumePendingDragonrollLink(options = {}) {
// reads correctly from the first frame and is corrected by refreshPairingStatus.
function pairingStatusText() {
if (pairingProblem === PAIRING_REVOKED) {
return "Not connected: this world is no longer linked to the Dragonroll campaign it was paired with. Create a new pairing code there to link it again.";
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 (pairingProblem) return `Not connected: Dragonroll did not accept that pairing code (${pairingProblem})`;
if (game.settings.get(MODULE_ID, SETTING_LINK_CODE)?.trim()) {
return "Not connected yet: waiting for Dragonroll to accept this pairing code.";
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. Paste a pairing code from that campaign's settings to link 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) {
@@ -357,12 +388,19 @@ async function refreshPairingStatus() {
try {
const result = await getDragonroll("foundry/sync/status", token);
linkedCampaignName = String(result.campaign?.name || "").trim();
if (pairingProblem === PAIRING_REVOKED) pairingProblem = "";
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") pairingProblem = PAIRING_REVOKED;
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());
}
@@ -1140,11 +1178,13 @@ async function publishHeartbeat() {
}
Hooks.once("ready", () => {
resumePendingDragonrollLink().then(refreshPairingStatus);
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 (linkRetriesDisabled) return;
resumePendingDragonrollLink({ notifyOnError: false });
}, 60000);
if (getSyncToken()) return;
advanceDragonrollLink();
}, LINK_POLL_MS);
setInterval(refreshPairingStatus, 60000);
scheduleSnapshotSync(0);
setInterval(publishHeartbeat, 60000);