1 Commits

Author SHA1 Message Date
caeff595da Obsidian plugin 2026-10-14 14:47:27 +02:00
16 changed files with 581 additions and 803 deletions

View File

@@ -12,10 +12,8 @@ dice widgets, shared markdown, sounds). It is a two-app monorepo:
- `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth. CommonJS. - `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth. CommonJS.
- `frontend/` — **Nuxt 4 / Vue 3** client (Composition API, `<script setup>`), SCSS, axios, marked, mitt, motion. - `frontend/` — **Nuxt 4 / Vue 3** client (Composition API, `<script setup>`), SCSS, axios, marked, mitt, motion.
There is **no** database seeding, no ORM migrations, no linter/formatter config, no Pinia/Vuex, and no There is **no** database seeding, no ORM migrations, no test suite, no linter/formatter config, no
Vue Router pages (see §5.1 — the UI is a window manager, not routed pages). The only automated tests Pinia/Vuex, and no Vue Router pages (see §5.1 — the UI is a window manager, not routed pages).
are `tests/*.test.js` (`npm test`, Node's built-in runner), which exercise the Foundry module's sync
logic against stubbed Foundry globals.
Git: default branch `master`, hosted on a self-hosted Gitea (`git.aranroig.com/BinarySandia04/Dragonroll`). Git: default branch `master`, hosted on a self-hosted Gitea (`git.aranroig.com/BinarySandia04/Dragonroll`).
CI (`.gitea/workflows/deploy.yml`) builds two Docker images on every push to `master`, pushes them to CI (`.gitea/workflows/deploy.yml`) builds two Docker images on every push to `master`, pushes them to
@@ -28,12 +26,12 @@ CI (`.gitea/workflows/deploy.yml`) builds two Docker images on every push to `ma
dragonroll/ dragonroll/
├── backend/ Express API (CommonJS, entry: src/index.js) ├── backend/ Express API (CommonJS, entry: src/index.js)
├── frontend/ Nuxt 4 app (entry: app/app.vue) ├── frontend/ Nuxt 4 app (entry: app/app.vue)
├── obsidian-plugin/ Plain JavaScript Obsidian plugin for campaign note import/push
├── docker-compose.yml nginx :3000 -> frontend :3000, /api -> backend :5000 ├── docker-compose.yml nginx :3000 -> frontend :3000, /api -> backend :5000
├── nginx.conf reverse proxy rules for the compose stack ├── nginx.conf reverse proxy rules for the compose stack
├── ecosystem.config.js PM2 config (stale: runs `npm start`, which does not exist — see §9) ├── ecosystem.config.js PM2 config (stale: runs `npm start`, which does not exist — see §9)
├── .gitea/workflows/deploy.yml ├── .gitea/workflows/deploy.yml
├── static/media/ README logo images only ├── static/media/ README logo images only
├── tests/ `node --test` tests (Foundry module sync toggle)
├── package.json root: only `concurrently`, used by `npm run dev` ├── package.json root: only `concurrently`, used by `npm run dev`
└── README.md install/run instructions are STALE (see §9) └── README.md install/run instructions are STALE (see §9)
``` ```
@@ -52,13 +50,10 @@ npm --prefix backend run dev # backend only
npm --prefix frontend run dev # frontend only npm --prefix frontend run dev # frontend only
npm --prefix frontend run build # nuxt build --dotenv .env.production npm --prefix frontend run build # nuxt build --dotenv .env.production
npm --prefix frontend run preview npm --prefix frontend run preview
npm test # node --test tests/ (Foundry module sync logic, no dependencies)
``` ```
There is no `start` script in either package and no lint command. There is no `start` script in either package, no test command, and no lint command.
Verification = run the dev server and exercise the flow (`/api/test` returns a JSON hello); Verification = run the dev server and exercise the flow (`/api/test` returns a JSON hello).
`npm test` covers the Foundry character/item sync toggle and per-actor force sync.
### Environment files ### Environment files
@@ -189,7 +184,8 @@ Fetch the file from `/api/public/<filename>`.
`GET /api/campaign/list` → `{status:'ok',campaigns}` `GET /api/campaign/list` → `{status:'ok',campaigns}`
`GET /api/campaign/retrieve/:id` → `{status:'ok',campaign}` (401 when no `req.user.id`) `GET /api/campaign/retrieve/:id` → `{status:'ok',campaign}` (401 when no `req.user.id`)
`GET /api/note/list?campaign=` → `{status:'ok', folders, notes}` — notes with `folder: null` (roots) `GET /api/note/list?campaign=` → `{status:'ok', folders, notes}` — notes with `folder: null` (roots);
folder entries include `parentFolder` so clients can rebuild nested folder paths
`GET /api/note/subfolder/list?campaign=&folder=` → `{status:'ok', subfolders, notes}` `GET /api/note/subfolder/list?campaign=&folder=` → `{status:'ok', subfolders, notes}`
`POST /api/note/create` — `{title*,content,campaign*,folder?}` (folder validated against campaign) `POST /api/note/create` — `{title*,content,campaign*,folder?}` (folder validated against campaign)
`POST /api/note/update` — `{id*, title?, content?, folder?, color?}` — partial, ownership checked `POST /api/note/update` — `{id*, title?, content?, folder?, color?}` — partial, ownership checked
@@ -239,7 +235,6 @@ not `Campaign.foundryWorldId` (`syncCampaign` / `requestMatchesWorld`). CORS is
| `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted | | `POST /sync/item-delete` | `{worldId, foundryItemId}` — a world item was deleted |
| `GET /sync/characters` | Actors the module applies back into Foundry | | `GET /sync/characters` | Actors the module applies back into Foundry |
| `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) | | `GET /sync/items` | Items the module applies back into Foundry (creates world items for Dragonroll-authored ones) |
| `GET /sync/status` | The campaign a sync token belongs to; the module shows it in its **Dragonroll Pairing Status** setting and treats `unauthorized` as the campaign having unlinked the world |
| `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document | | `POST /sync/map` / `POST /sync/map-item` | Store the id mapping after the module creates a document |
| `POST /sync/delete` | `{worldId, foundryActorId}` | | `POST /sync/delete` | `{worldId, foundryActorId}` |
@@ -255,13 +250,6 @@ Rules worth knowing before editing this:
which the sync skips. which the sync skips.
- **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events - **`fullSync` preserves Dragonroll edits** (only new rows are overwritten); live Foundry events
overwrite. Item pruning requires the full snapshot, since only it sees world items and actor copies. overwrite. Item pruning requires the full snapshot, since only it sees world items and actor copies.
- **Autosync is a Foundry-side switch** (`autoSync` client setting, on by default): when off, the
module queues no CRUD push, runs no periodic reconcile and sends no startup snapshot; the actor
directory's `Dragonroll: Force Sync` entry still pushes the selected actors as an upsert
(`fullSync:false`, so it never prunes). The read-only bridge snapshot is not gated by it.
- **`pairingStatus` is a setting the module writes, not the GM**: the module settings sentence about
whether this world is connected comes from the stored sync token plus the answer from
`/sync/status` (checked at world start and every minute), and anything typed into it is replaced.
- `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`. - `Actor.inventory` stays a flattened copy of the actor's embedded items; it is not linked to `Item`.
- `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only - `GET /api/foundry/*` (`routes/foundry.js`) is unrelated: a JWT-protected proxy over the read-only
bridge, only useful when `FOUNDRY_API_URL` is configured. bridge, only useful when `FOUNDRY_API_URL` is configured.
@@ -477,6 +465,23 @@ script; `WindowDefinitions` stores raw keys (`title: 'windows.login'`) and `Wind
configured (`nuxt.config.ts`, `langDir: 'locales/'`, `vueI18n: './i18n.config.ts'`) but its locale files configured (`nuxt.config.ts`, `langDir: 'locales/'`, `vueI18n: './i18n.config.ts'`) but its locale files
(`locales/en.json` etc.) are empty `{}` — the custom plugin is what components actually consume. (`locales/en.json` etc.) are empty `{}` — the custom plugin is what components actually consume.
### 5.9 Obsidian plugin
`obsidian-plugin/` is a plain JavaScript community plugin; copy `main.js` and `manifest.json` into
`<vault>/.obsidian/plugins/dragonroll-sync/` (details in its README). It signs in through
`POST /api/user/login`, saves the 48-hour JWT token in plugin data, and does not save the password.
The user selects a campaign from `GET /api/campaign/list`.
- **Import or refresh campaign notes** reads `/api/note/list` plus `/api/note/subfolder/list` and
creates/updates Markdown files under `Dragonroll/<Campaign>/`, preserving Dragonroll's folder tree.
- **Push active note to Dragonroll** creates a root campaign note or updates the note linked in its
frontmatter.
- `dragonrollId`, `dragonrollCampaign`, and `dragonrollTitle` frontmatter properties link imported
notes. They are omitted from content sent to Dragonroll. Per-note signatures detect local edits;
imports preserve modified local files, and push is explicit.
The plugin uses Obsidian's `requestUrl` helper, so the request path does not depend on browser CORS.
## 6. Conventions ## 6. Conventions
- **Backend**: CommonJS `require`/`module.exports`; files in `services/` are shared infra, `routes/` - **Backend**: CommonJS `require`/`module.exports`; files in `services/` are shared infra, `routes/`

View File

@@ -24,6 +24,7 @@ Dragonroll is an open source connector for role-playing games.
- Play music during physical campaings - Play music during physical campaings
- Plan different encounters - Plan different encounters
- Manage different items and spells - Manage different items and spells
- Import and edit campaign notes in Obsidian with the [Dragonroll Sync plugin](obsidian-plugin/README.md)
- And so much more! - And so much more!
## Installation 🛠️ ## Installation 🛠️
@@ -55,7 +56,6 @@ if you want to start the development environments
- Dragonroll <-> Foundry integration - Dragonroll <-> Foundry integration
- Dragonroll <-> Discord Bot integration - Dragonroll <-> Discord Bot integration
- Dragonroll <-> Obsidian integration
What to sync: What to sync:

View File

@@ -225,7 +225,6 @@ router.post('/link/complete', linkRateLimit, async (req, res) => {
res.set('Cache-Control', 'no-store'); res.set('Cache-Control', 'no-store');
res.json({ res.json({
status: 'ok', status: 'ok',
campaign: { id: campaign.id, name: campaign.name },
world: { id: world.worldId, title: world.worldTitle, system: world.system }, world: { id: world.worldId, title: world.worldTitle, system: world.system },
syncToken, syncToken,
bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null bridgeConfig: bridgeUrl && pushToken ? { url: bridgeUrl, pushToken } : null
@@ -237,26 +236,6 @@ router.post('/link/complete', linkRateLimit, async (req, res) => {
} }
}); });
// The Foundry module shows this in its settings: the sync token alone only proves
// a link was made once, so the module asks which campaign it belongs to and hears
// back nothing but `unauthorized` once that campaign unlinks the world again.
router.get('/sync/status', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
res.set('Cache-Control', 'no-store');
res.json({
status: 'ok',
campaign: { id: campaign.id, name: campaign.name },
worldId: campaign.foundryWorldId
});
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/sync/snapshot', async (req, res) => { router.post('/sync/snapshot', async (req, res) => {
try { try {
const campaign = await syncCampaign(req, res); const campaign = await syncCampaign(req, res);

View File

@@ -19,7 +19,7 @@ router.get('/list', async (req, res) => {
if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' }); if (!hasAccess) return res.json({ status: 'error', msg: 'unauthorized' });
const folders = await Folder.find({ campaign }) const folders = await Folder.find({ campaign })
.select('_id name date color') .select('_id name parentFolder date color')
.sort({ date: -1 }) .sort({ date: -1 })
.lean(); .lean();

View File

@@ -41,14 +41,6 @@ For a local backend, use `http://localhost:5000`; the module omits `/api` and th
the local pairing route at its root. Character synchronization works without the optional snapshot the local pairing route at its root. Character synchronization works without the optional snapshot
bridge. Configure that bridge only if you also need the read-only world snapshot API described below. bridge. Configure that bridge only if you also need the read-only world snapshot API described below.
**Dragonroll Pairing Status** in the module settings always says whether this browser holds a pairing
and, once Dragonroll has answered `GET /api/foundry/sync/status`, which campaign the world is
connected to. It is written by the module, not by the GM: it appears as not connected until the world
is paired, names the campaign after a pairing or a check on world start and every minute afterwards,
gives the reason when a pairing code can never be redeemed, and says the world is no longer linked
once the campaign unlinks it. Because both the pairing code and the sync token are client settings,
another browser of the same world reads as not paired.
The campaign settings show the linked world's title and system. A Foundry world can be linked to The campaign settings show the linked world's title and system. A Foundry world can be linked to
only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry only one campaign at a time. The pairing endpoint accepts cross-origin requests from the Foundry
client and uses the one-time code instead of a Dragonroll login token. client and uses the one-time code instead of a Dragonroll login token.
@@ -61,25 +53,6 @@ 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 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. 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 ### Items
The campaign's Item list is synchronized with the world's gear, both ways: The campaign's Item list is synchronized with the world's gear, both ways:
@@ -111,7 +84,6 @@ The module calls these Dragonroll routes with the campaign sync token (no Dragon
| `POST /api/foundry/sync/item-delete` | A world item was deleted | | `POST /api/foundry/sync/item-delete` | A world item was deleted |
| `GET /api/foundry/sync/characters` | Characters to apply back in Foundry | | `GET /api/foundry/sync/characters` | Characters to apply back in Foundry |
| `GET /api/foundry/sync/items` | Items to apply back in Foundry | | `GET /api/foundry/sync/items` | Items to apply back in Foundry |
| `GET /api/foundry/sync/status` | The campaign this world's token belongs to, for the module's pairing status |
| `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document | | `POST /api/foundry/sync/map` / `map-item` | Store an id mapping after creating a document |
| `POST /api/foundry/sync/delete` | An actor was deleted | | `POST /api/foundry/sync/delete` | An actor was deleted |

View File

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

View File

@@ -4,9 +4,7 @@ const SETTING_PUSH_TOKEN = "pushToken";
const SETTING_BRIDGE_CONFIG = "bridgeConfig"; const SETTING_BRIDGE_CONFIG = "bridgeConfig";
const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl"; const SETTING_DRAGONROLL_API_URL = "dragonrollApiUrl";
const SETTING_LINK_CODE = "linkCode"; const SETTING_LINK_CODE = "linkCode";
const SETTING_PAIRING_STATUS = "pairingStatus";
const SETTING_SYNC_TOKEN = "syncToken"; const SETTING_SYNC_TOKEN = "syncToken";
const SETTING_AUTO_SYNC = "autoSync";
let syncTimeout; let syncTimeout;
let syncInProgress = false; let syncInProgress = false;
let syncRequested = false; let syncRequested = false;
@@ -17,12 +15,6 @@ const FATAL_LINK_ERRORS = new Set([
"foundry.errors.link-expired", "foundry.errors.link-expired",
"foundry.errors.world-already-linked", "foundry.errors.world-already-linked",
]); ]);
// 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 actorSyncTimeout; let actorSyncTimeout;
let characterSyncRunning = false; let characterSyncRunning = false;
let actorSyncErrorLogged = false; let actorSyncErrorLogged = false;
@@ -147,26 +139,6 @@ Hooks.once("init", () => {
onChange: handleLinkCodeChange, 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.",
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); const module = game.modules.get(MODULE_ID);
if (!module) { if (!module) {
console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`); console.warn(`${MODULE_ID} | Could not register the public API: module was not found.`);
@@ -238,9 +210,6 @@ async function setLinkCode(value) {
function handleLinkCodeChange(value) { function handleLinkCodeChange(value) {
if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return; if (updatingLinkCodeSetting || handlingLinkCode || !value?.trim()) return;
linkRetriesDisabled = false; linkRetriesDisabled = false;
// A code typed by hand supersedes whatever went wrong with the last one.
pairingProblem = "";
setPairingStatus(pairingStatusText());
completeDragonrollCampaignLink(value.trim()); completeDragonrollCampaignLink(value.trim());
} }
@@ -277,19 +246,13 @@ async function completeDragonrollCampaignLink(code, options = {}) {
scheduleSnapshotSync(0); scheduleSnapshotSync(0);
setTimeout(initializeCharacterSync, 0); setTimeout(initializeCharacterSync, 0);
setTimeout(reconcileDragonrollItems, 2000); setTimeout(reconcileDragonrollItems, 2000);
linkedCampaignName = String(result.campaign?.name || "").trim();
ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign."); ui.notifications?.info("This Foundry world is now linked to the Dragonroll campaign.");
await setPairingStatus(pairingStatusText());
} catch (error) { } catch (error) {
console.error(`${MODULE_ID} | Could not complete the campaign link.`, error); console.error(`${MODULE_ID} | Could not complete the campaign link.`, error);
// Expired or already-used codes will never redeem, so stop the background // Expired or already-used codes will never redeem, so stop the background
// retry; any error keeps retrying (the Dragonroll server may be restarting). // retry; any error keeps retrying (the Dragonroll server may be restarting).
linkRetriesDisabled = FATAL_LINK_ERRORS.has(error.message); 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)); if (notifyOnError) ui.notifications?.error(linkErrorMessage(error));
await setPairingStatus(pairingStatusText());
} finally { } finally {
handlingLinkCode = false; handlingLinkCode = false;
} }
@@ -304,69 +267,6 @@ async function resumePendingDragonrollLink(options = {}) {
if (code) await completeDragonrollCampaignLink(code, options); if (code) await completeDragonrollCampaignLink(code, options);
} }
// --- 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() {
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.";
}
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.";
}
return "Not connected to a Dragonroll campaign. Paste a pairing code from that campaign's settings to link this world.";
}
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 (pairingProblem === PAIRING_REVOKED) pairingProblem = "";
} 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;
}
await setPairingStatus(pairingStatusText());
}
function scheduleSnapshotSync(delay = 500) { function scheduleSnapshotSync(delay = 500) {
clearTimeout(syncTimeout); clearTimeout(syncTimeout);
syncTimeout = setTimeout(publishSnapshot, delay); syncTimeout = setTimeout(publishSnapshot, delay);
@@ -387,35 +287,6 @@ function getSyncToken() {
return game.settings.get(MODULE_ID, SETTING_SYNC_TOKEN)?.trim() || ""; 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) { function dragonrollActorId(actor) {
return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || ""; return actor.getFlag?.(MODULE_ID, "actorId") || actor.flags?.[MODULE_ID]?.actorId || "";
} }
@@ -509,34 +380,6 @@ async function deleteDragonrollActor(foundryActorId) {
}, token); }, 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) { function queueActorChange(kind, actor) {
if (!actor || !game.user?.isGM || !getSyncToken()) return; if (!actor || !game.user?.isGM || !getSyncToken()) return;
if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return; if (syncingActorIds.has(actor.id) || actor.flags?.[MODULE_ID]?.syncMutation) return;
@@ -546,9 +389,6 @@ function queueActorChange(kind, actor) {
actorSyncTimeout = setTimeout(flushActorChanges, 400); actorSyncTimeout = setTimeout(flushActorChanges, 400);
} }
async function flushActorChanges() { 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()]; const changes = [...queuedActorChanges.values()];
queuedActorChanges.clear(); queuedActorChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete"); const deleted = changes.filter((change) => change.kind === "delete");
@@ -678,8 +518,6 @@ function queueFoundryItemChange(kind, item) {
} }
async function flushItemChanges() { async function flushItemChanges() {
// Autosync off: the queued edits wait here, like the actor changes do.
if (!isAutoSyncEnabled()) return;
const changes = [...queuedItemChanges.values()]; const changes = [...queuedItemChanges.values()];
queuedItemChanges.clear(); queuedItemChanges.clear();
const deleted = changes.filter((change) => change.kind === "delete"); const deleted = changes.filter((change) => change.kind === "delete");
@@ -778,7 +616,7 @@ async function createFoundryWorldItem(entry) {
async function reconcileDragonrollItems() { async function reconcileDragonrollItems() {
const token = getSyncToken(); const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || itemSyncRunning || !isAutoSyncEnabled()) return; if (!token || !game.user?.isGM || !game.world || itemSyncRunning) return;
itemSyncRunning = true; itemSyncRunning = true;
try { try {
if (game.system.id !== "dnd5e") { if (game.system.id !== "dnd5e") {
@@ -1009,7 +847,7 @@ async function createFoundryCharacter(entry) {
async function reconcileDragonrollCharacters() { async function reconcileDragonrollCharacters() {
const token = getSyncToken(); const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || characterSyncRunning || !isAutoSyncEnabled()) return; if (!token || !game.user?.isGM || !game.world || characterSyncRunning) return;
characterSyncRunning = true; characterSyncRunning = true;
try { try {
if (game.system.id !== "dnd5e") { if (game.system.id !== "dnd5e") {
@@ -1049,7 +887,7 @@ async function reconcileDragonrollCharacters() {
} }
async function initializeCharacterSync() { async function initializeCharacterSync() {
if (!getSyncToken() || !game.user?.isGM || !game.world || !isAutoSyncEnabled()) return; if (!getSyncToken() || !game.user?.isGM || !game.world) return;
try { try {
await pushFoundryActors(game.actors.contents, true); await pushFoundryActors(game.actors.contents, true);
await reconcileDragonrollCharacters(); await reconcileDragonrollCharacters();
@@ -1140,12 +978,11 @@ async function publishHeartbeat() {
} }
Hooks.once("ready", () => { Hooks.once("ready", () => {
resumePendingDragonrollLink().then(refreshPairingStatus); resumePendingDragonrollLink();
setInterval(() => { setInterval(() => {
if (linkRetriesDisabled) return; if (linkRetriesDisabled) return;
resumePendingDragonrollLink({ notifyOnError: false }); resumePendingDragonrollLink({ notifyOnError: false });
}, 60000); }, 60000);
setInterval(refreshPairingStatus, 60000);
scheduleSnapshotSync(0); scheduleSnapshotSync(0);
setInterval(publishHeartbeat, 60000); setInterval(publishHeartbeat, 60000);
setTimeout(initializeCharacterSync, 1000); setTimeout(initializeCharacterSync, 1000);
@@ -1179,21 +1016,3 @@ 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),
),
});
});

View File

@@ -17,7 +17,6 @@
"saved": "S'ha desat la configuració de la campanya.", "saved": "S'ha desat la configuració de la campanya.",
"linked": "S'ha enllaçat el món de Foundry amb aquesta campanya.", "linked": "S'ha enllaçat el món de Foundry amb aquesta campanya.",
"unlinked": "S'ha desenllaçat el món de Foundry d'aquesta campanya.", "unlinked": "S'ha desenllaçat el món de Foundry d'aquesta campanya.",
"copy-code": "Copia el codi",
"code-copied": "S'ha copiat el codi d'enllaç.", "code-copied": "S'ha copiat el codi d'enllaç.",
"saving": "Desant...", "saving": "Desant...",
"errors": { "errors": {

View File

@@ -21,7 +21,6 @@
"saved": "Campaign settings saved.", "saved": "Campaign settings saved.",
"linked": "Foundry world linked to this campaign.", "linked": "Foundry world linked to this campaign.",
"unlinked": "Foundry world unlinked from this campaign.", "unlinked": "Foundry world unlinked from this campaign.",
"copy-code": "Copy code",
"code-copied": "Pairing code copied.", "code-copied": "Pairing code copied.",
"saving": "Saving...", "saving": "Saving...",
"errors": { "errors": {

View File

@@ -17,7 +17,6 @@
"saved": "Se han guardado los ajustes de la campaña.", "saved": "Se han guardado los ajustes de la campaña.",
"linked": "El mundo de Foundry se ha vinculado a esta campaña.", "linked": "El mundo de Foundry se ha vinculado a esta campaña.",
"unlinked": "Se ha desvinculado el mundo de Foundry de esta campaña.", "unlinked": "Se ha desvinculado el mundo de Foundry de esta campaña.",
"copy-code": "Copiar código",
"code-copied": "Código de vinculación copiado.", "code-copied": "Código de vinculación copiado.",
"saving": "Guardando...", "saving": "Guardando...",
"errors": { "errors": {

43
obsidian-plugin/README.md Normal file
View File

@@ -0,0 +1,43 @@
# Dragonroll Sync for Obsidian
An Obsidian community plugin that imports notes from a Dragonroll campaign and pushes the active
Markdown note back to Dragonroll.
## Install from this repository
Copy `main.js` and `manifest.json` into:
```text
<vault>/.obsidian/plugins/dragonroll-sync/
```
Then enable **Dragonroll Sync** in Obsidian's Community Plugins settings. The plugin is plain
JavaScript and does not need a build step.
## Connect your account
Open **Settings → Community plugins → Dragonroll Sync**, enter the Dragonroll API URL and sign in
with your Dragonroll username/email and password. The default API URL is
`https://dragonroll.aranroig.com/api`; a local server can use `http://localhost:5000/api`.
Choose a campaign after signing in. The plugin saves the Dragonroll session token in this vault;
Dragonroll sessions expire after 48 hours. The password is not saved.
## Commands
- **Import or refresh campaign notes** fetches all campaign notes, including notes inside nested
Dragonroll folders, into `Dragonroll/<Campaign>/`. Imported notes keep their folder hierarchy.
- **Push active note to Dragonroll** creates the active Markdown note as a root campaign note, or
updates its linked Dragonroll note. A note linked to a different campaign cannot be pushed while
another campaign is selected.
The import command adds `dragonrollId`, `dragonrollCampaign`, and `dragonrollTitle` properties to
each imported note's frontmatter. These properties link the local file to its remote record and are
omitted from the Markdown content sent back to Dragonroll. Pushing a new local note adds those
properties as well.
Import protects local edits. It updates a linked note only when the local copy still matches the
last imported/pushed version. If the local copy changed, or both copies changed since the last sync,
the plugin keeps the local file and reports it for review. Push is explicit and updates Dragonroll
with the active note's current title and content.
This is an explicit import/push workflow; it does not sync in the background or delete notes.

497
obsidian-plugin/main.js Normal file
View File

@@ -0,0 +1,497 @@
const {
Notice,
Plugin,
PluginSettingTab,
Setting,
normalizePath,
requestUrl,
} = require('obsidian');
const DEFAULT_SETTINGS = {
apiBaseUrl: 'https://dragonroll.aranroig.com/api',
token: '',
campaignId: '',
snapshots: {},
};
const NOTE_ID_PROPERTY = 'dragonrollId';
const CAMPAIGN_PROPERTY = 'dragonrollCampaign';
const REMOTE_TITLE_PROPERTY = 'dragonrollTitle';
module.exports = class DragonrollSyncPlugin extends Plugin {
async onload() {
await this.loadSettings();
this.status = this.addStatusBarItem();
this.updateStatus();
this.addRibbonIcon('refresh-cw', 'Import Dragonroll campaign notes', () => this.importCampaignNotes());
this.addCommand({
id: 'import-campaign-notes',
name: 'Import or refresh campaign notes',
callback: () => this.importCampaignNotes(),
});
this.addCommand({
id: 'push-active-note',
name: 'Push active note to Dragonroll',
checkCallback: (checking) => {
const file = this.app.workspace.getActiveFile();
if (!file || file.extension !== 'md') return false;
if (!checking) void this.pushActiveNote();
return true;
},
});
this.addSettingTab(new DragonrollSettingTab(this.app, this));
if (this.settings.token && this.settings.campaignId) {
this.status.setText('Dragonroll: ready');
}
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
if (!this.settings.snapshots || typeof this.settings.snapshots !== 'object') {
this.settings.snapshots = {};
}
}
async saveSettings() {
await this.saveData(this.settings);
this.updateStatus();
}
updateStatus() {
if (!this.status) return;
if (!this.settings.token) this.status.setText('Dragonroll: signed out');
else if (!this.settings.campaignId) this.status.setText('Dragonroll: choose campaign');
else this.status.setText('Dragonroll: ready');
}
apiBaseUrl() {
let url = String(this.settings.apiBaseUrl || '').trim().replace(/\/+$/, '');
if (!url) throw new Error('Enter the Dragonroll API URL in settings.');
if (!/\/api$/i.test(url)) url += '/api';
return url;
}
async request(path, { method = 'GET', body, authenticated = true } = {}) {
const headers = { Accept: 'application/json' };
if (authenticated && this.settings.token) {
headers.Authorization = `Bearer ${this.settings.token}`;
}
if (body !== undefined) headers['Content-Type'] = 'application/json';
let response;
try {
response = await requestUrl({
url: `${this.apiBaseUrl()}${path}`,
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
throw: false,
});
} catch (error) {
throw new Error(`Could not reach Dragonroll: ${error.message || error}`);
}
let data;
try {
data = response.json;
} catch {
throw new Error(`Dragonroll returned an unreadable response (HTTP ${response.status}).`);
}
if (response.status < 200 || response.status >= 300 || data?.status !== 'ok') {
const message = data?.msg || `HTTP ${response.status}`;
if (response.status === 401 || message === 'unauthorized') {
throw new Error('Dragonroll rejected this session. Sign in again in plugin settings.');
}
throw new Error(`Dragonroll: ${message}`);
}
return data;
}
async login(usermail, password) {
const data = await this.request('/user/login', {
method: 'POST',
body: { usermail, password },
authenticated: false,
});
this.settings.token = data.token;
this.settings.campaignId = '';
await this.saveSettings();
return this.getCampaigns();
}
async getCampaigns() {
const data = await this.request('/campaign/list');
return data.campaigns || [];
}
async selectedCampaign() {
if (!this.settings.token) throw new Error('Sign in to Dragonroll in plugin settings first.');
if (!this.settings.campaignId) throw new Error('Choose a campaign in plugin settings first.');
const campaigns = await this.getCampaigns();
const campaign = campaigns.find((item) => String(item._id) === String(this.settings.campaignId));
if (!campaign) throw new Error('The selected campaign is unavailable. Choose a campaign in settings.');
return campaign;
}
async fetchCampaignNotes(campaignId) {
const root = await this.request(`/note/list?campaign=${encodeURIComponent(campaignId)}`);
const folders = root.folders || [];
const folderById = new Map(folders.map((folder) => [String(folder._id), folder]));
const pathCache = new Map();
const folderPath = (folderId, visiting = new Set()) => {
const id = String(folderId || '');
if (!id || !folderById.has(id)) return [];
if (pathCache.has(id)) return pathCache.get(id);
if (visiting.has(id)) return [];
const folder = folderById.get(id);
const nextVisiting = new Set(visiting);
nextVisiting.add(id);
const parent = folder.parentFolder ? String(folder.parentFolder) : '';
const path = [...folderPath(parent, nextVisiting), safeSegment(folder.name, 'Folder')];
pathCache.set(id, path);
return path;
};
const nestedResults = await Promise.all(folders.map(async (folder) => {
const data = await this.request(
`/note/subfolder/list?campaign=${encodeURIComponent(campaignId)}&folder=${encodeURIComponent(folder._id)}`
);
return (data.notes || []).map((note) => ({ note, folders: folderPath(folder._id) }));
}));
const notes = (root.notes || []).map((note) => ({ note, folders: [] }));
for (const result of nestedResults) notes.push(...result);
return notes;
}
async importCampaignNotes() {
try {
const campaign = await this.selectedCampaign();
const notes = await this.fetchCampaignNotes(campaign._id);
const existingById = await this.findFilesByDragonrollId();
const baseFolder = normalizePath(`Dragonroll/${safeSegment(campaign.name, 'Campaign')}`);
let created = 0;
let updated = 0;
let unchanged = 0;
let protectedNotes = 0;
for (const entry of notes) {
const remote = entry.note;
const id = String(remote._id);
const title = String(remote.title || 'Untitled');
const content = String(remote.content || '');
const remoteSignature = await signature(title, content);
const file = existingById.get(id);
if (!file) {
const targetFolder = normalizePath([baseFolder, ...entry.folders].join('/'));
await this.ensureFolder(targetFolder);
const path = await this.availableMarkdownPath(targetFolder, title, id);
const newFile = await this.app.vault.create(path, content);
await this.setNoteIdentity(newFile, id, campaign._id, title);
this.settings.snapshots[id] = remoteSignature;
created += 1;
continue;
}
const localContent = await this.app.vault.read(file);
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter || {};
const storedTitle = frontmatter[REMOTE_TITLE_PROPERTY];
const localTitle = storedTitle && safeSegment(storedTitle, 'Untitled') === file.basename
? String(storedTitle)
: file.basename;
const localSignature = await signature(localTitle, stripPluginMetadata(localContent));
const baseline = this.settings.snapshots[id];
if (!baseline) {
if (localSignature === remoteSignature) {
this.settings.snapshots[id] = remoteSignature;
unchanged += 1;
} else {
protectedNotes += 1;
}
continue;
}
const localChanged = localSignature !== baseline;
const remoteChanged = remoteSignature !== baseline;
if (localChanged && remoteChanged) {
protectedNotes += 1;
continue;
}
if (localChanged) {
protectedNotes += 1;
continue;
}
if (!remoteChanged) {
unchanged += 1;
continue;
}
await this.app.vault.modify(file, content);
await this.setNoteIdentity(file, id, campaign._id, title);
const renamed = await this.renameImportedFile(file, title, id);
this.settings.snapshots[id] = remoteSignature;
updated += 1;
if (renamed) existingById.set(id, renamed);
}
await this.saveSettings();
const details = protectedNotes ? `; ${protectedNotes} local edit(s) kept for review` : '';
new Notice(`Dragonroll import: ${created} added, ${updated} updated, ${unchanged} unchanged${details}.`);
} catch (error) {
new Notice(error.message || 'Could not import Dragonroll notes.');
}
}
async pushActiveNote() {
try {
const campaign = await this.selectedCampaign();
const file = this.app.workspace.getActiveFile();
if (!file || file.extension !== 'md') throw new Error('Open a Markdown note to push it.');
const cache = this.app.metadataCache.getFileCache(file);
const frontmatter = cache?.frontmatter || {};
const linkedCampaign = frontmatter[CAMPAIGN_PROPERTY];
const noteId = frontmatter[NOTE_ID_PROPERTY];
if (noteId && String(linkedCampaign || '') !== String(campaign._id)) {
throw new Error('This note is linked to another Dragonroll campaign. Select that campaign to push it.');
}
const markdown = stripPluginMetadata(await this.app.vault.read(file));
let remote;
if (noteId) {
const data = await this.request('/note/update', {
method: 'POST',
body: { id: String(noteId), title: file.basename, content: markdown },
});
remote = data.note;
} else {
const data = await this.request('/note/create', {
method: 'POST',
body: { title: file.basename, content: markdown, campaign: campaign._id },
});
remote = data.note;
}
const id = String(remote._id || noteId);
await this.setNoteIdentity(file, id, campaign._id, file.basename);
this.settings.snapshots[id] = await signature(file.basename, markdown);
await this.saveSettings();
new Notice(`Pushed “${file.basename}” to Dragonroll.`);
} catch (error) {
new Notice(error.message || 'Could not push this note to Dragonroll.');
}
}
async findFilesByDragonrollId() {
const result = new Map();
for (const file of this.app.vault.getMarkdownFiles()) {
const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
const id = frontmatter?.[NOTE_ID_PROPERTY];
if (id && !result.has(String(id))) result.set(String(id), file);
}
return result;
}
async setNoteIdentity(file, noteId, campaignId, title) {
await this.app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter[NOTE_ID_PROPERTY] = String(noteId);
frontmatter[CAMPAIGN_PROPERTY] = String(campaignId);
frontmatter[REMOTE_TITLE_PROPERTY] = String(title || file.basename);
});
}
async ensureFolder(path) {
const normalized = normalizePath(path);
if (!normalized || normalized === '.') return;
const parts = normalized.split('/');
let current = '';
for (const part of parts) {
current = current ? `${current}/${part}` : part;
if (!this.app.vault.getAbstractFileByPath(current)) {
await this.app.vault.createFolder(current);
}
}
}
async availableMarkdownPath(folder, title, noteId) {
const base = safeSegment(title, 'Untitled');
let path = normalizePath(`${folder}/${base}.md`);
if (!this.app.vault.getAbstractFileByPath(path)) return path;
const suffix = String(noteId).slice(-6);
path = normalizePath(`${folder}/${base} (${suffix}).md`);
let counter = 2;
while (this.app.vault.getAbstractFileByPath(path)) {
path = normalizePath(`${folder}/${base} (${suffix}-${counter}).md`);
counter += 1;
}
return path;
}
async renameImportedFile(file, title, noteId) {
const parent = file.parent?.path || '';
const base = safeSegment(title, 'Untitled');
let targetPath = normalizePath(parent ? `${parent}/${base}.md` : `${base}.md`);
if (targetPath === file.path) return file;
if (this.app.vault.getAbstractFileByPath(targetPath)) {
targetPath = await this.availableMarkdownPath(parent || '.', title, noteId);
}
await this.app.fileManager.renameFile(file, targetPath);
return this.app.vault.getAbstractFileByPath(targetPath);
}
};
class DragonrollSettingTab extends PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
this.campaigns = [];
this.loginName = '';
this.password = '';
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Dragonroll Sync' });
containerEl.createEl('p', {
text: 'Sign in with your Dragonroll account, choose a campaign, then use the import and push commands. Your password is used only to sign in; the 48-hour session token is stored in this vault.',
});
new Setting(containerEl)
.setName('Dragonroll API URL')
.setDesc('Use the server address, with or without /api.')
.addText((text) => text
.setPlaceholder('https://dragonroll.aranroig.com/api')
.setValue(this.plugin.settings.apiBaseUrl)
.onChange(async (value) => {
const previous = this.plugin.settings.apiBaseUrl.trim().replace(/\/+$/, '');
const next = value.trim().replace(/\/+$/, '');
if (previous !== next) {
this.plugin.settings.token = '';
this.plugin.settings.campaignId = '';
this.campaigns = [];
}
this.plugin.settings.apiBaseUrl = value.trim();
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Username or email')
.addText((text) => text
.setPlaceholder('Dragonroll username or email')
.onChange((value) => { this.loginName = value.trim(); }));
new Setting(containerEl)
.setName('Password')
.addText((text) => {
text.inputEl.type = 'password';
text.inputEl.autocomplete = 'off';
text.onChange((value) => { this.password = value; });
});
new Setting(containerEl)
.setName(this.plugin.settings.token ? 'Session' : 'Sign in')
.setDesc(this.plugin.settings.token ? 'The stored session expires after 48 hours.' : 'Password is not saved by this plugin.')
.addButton((button) => button
.setButtonText('Sign in')
.setCta()
.onClick(async () => {
if (!this.loginName || !this.password) {
new Notice('Enter your Dragonroll username/email and password.');
return;
}
button.setDisabled(true);
try {
this.campaigns = await this.plugin.login(this.loginName, this.password);
this.password = '';
this.display();
new Notice(`Signed in. Found ${this.campaigns.length} campaign(s).`);
} catch (error) {
new Notice(error.message || 'Could not sign in to Dragonroll.');
} finally {
button.setDisabled(false);
}
}));
if (this.plugin.settings.token) {
new Setting(containerEl)
.setName('Campaign')
.setDesc('The campaign used by import and push commands.')
.addDropdown((dropdown) => {
dropdown.addOption('', 'Choose a campaign');
for (const campaign of this.campaigns) {
dropdown.addOption(String(campaign._id), campaign.name);
}
dropdown.setValue(this.plugin.settings.campaignId || '');
dropdown.onChange(async (value) => {
this.plugin.settings.campaignId = value;
await this.plugin.saveSettings();
});
})
.addButton((button) => button
.setButtonText('Load campaigns')
.onClick(async () => {
button.setDisabled(true);
try {
this.campaigns = await this.plugin.getCampaigns();
this.display();
new Notice(`Loaded ${this.campaigns.length} campaign(s).`);
} catch (error) {
new Notice(error.message || 'Could not load campaigns.');
} finally {
button.setDisabled(false);
}
}));
new Setting(containerEl)
.setName('Sign out')
.setDesc('Remove the saved Dragonroll session from this vault.')
.addButton((button) => button
.setButtonText('Sign out')
.onClick(async () => {
this.plugin.settings.token = '';
this.plugin.settings.campaignId = '';
await this.plugin.saveSettings();
this.display();
}));
}
}
}
function safeSegment(value, fallback) {
const safe = String(value || '')
.replace(/[\\\/:*?"<>|#^\[\]]/g, '-')
.replace(/[. ]+$/g, '')
.trim();
return safe || fallback;
}
function stripPluginMetadata(markdown) {
const text = String(markdown || '');
const match = text.match(/^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/);
if (!match) return text;
const keptLines = match[2].split(/\r?\n/).filter((line) =>
!/^(dragonrollId|dragonrollCampaign|dragonrollTitle):\s*/.test(line)
);
const frontmatter = keptLines.join('\n').trim();
const body = text.slice(match[0].length);
return frontmatter ? `---\n${frontmatter}\n---\n${body}` : body;
}
async function signature(title, content) {
const value = `${title}\u0000${String(content).replace(/\r\n/g, '\n')}`;
if (globalThis.crypto?.subtle) {
const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
}
let hash = 2166136261;
for (let index = 0; index < value.length; index += 1) {
hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
}
return (hash >>> 0).toString(16);
}

View File

@@ -0,0 +1,9 @@
{
"id": "dragonroll-sync",
"name": "Dragonroll Sync",
"version": "1.0.0",
"minAppVersion": "1.5.0",
"description": "Import Dragonroll campaign notes into Obsidian and push edits back.",
"author": "Dragonroll",
"isDesktopOnly": false
}

View File

@@ -3,7 +3,6 @@
"concurrently": "^9.2.1" "concurrently": "^9.2.1"
}, },
"scripts": { "scripts": {
"dev": "concurrently -k -n BACKEND,FRONTEND,DISCORD-BOT,FOUNDRY -c blue,green,yellow,magenta \"DEBUG=* npm --prefix backend run dev\" \"npm --prefix frontend run dev\" \"npm --prefix discord-bot start\" \"node scripts/run-foundry.js\"", "dev": "concurrently -k -n BACKEND,FRONTEND,DISCORD-BOT,FOUNDRY -c blue,green,yellow,magenta \"DEBUG=* npm --prefix backend run dev\" \"npm --prefix frontend run dev\" \"npm --prefix discord-bot start\" \"node scripts/run-foundry.js\""
"test": "node --test tests/"
} }
} }

View File

@@ -1,230 +0,0 @@
// Tests for the pairing status the Dragonroll Foundry module shows in its
// settings (Syndria98/dragonroll#17). Like foundry-sync-toggle.test.js, the module
// script runs inside a `node:vm` context of stubbed Foundry globals; here each
// test also decides what Dragonroll answers, because the status is that answer
// plus what this client holds (its sync token and any pairing code).
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const MODULE_ID = "dragonroll-foundry";
const MODULE_SOURCE = fs.readFileSync(
path.join(__dirname, "..", "dragonroll-foundry", "scripts", "api.js"),
"utf8",
);
const LINKED_CAMPAIGN = { id: "campaign-1", name: "Curse of Strahd" };
// The stub starts as a world that finished pairing (`syncToken: ""` is one that
// never did). `answers` maps a route fragment to the JSON Dragonroll replies
// with; a route that is not listed answers `{status:"ok"}`, and one mapped to
// null answers HTML, like a Dragonroll old enough not to have that route at all.
function makeStubWorld({ syncToken = "sync-token-1", linkCode = "", answers = {} } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
notifications: [],
};
const settingsStore = {
autoSync: true,
syncToken,
linkCode,
dragonrollApiUrl: "http://backend.test:5000",
};
const sandbox = {
console: { log() {}, info() {}, warn() {}, error() {} },
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: {
notifications: {
info: (text) => state.notifications.push(["info", text]),
warn: (text) => state.notifications.push(["warn", text]),
error: (text) => state.notifications.push(["error", text]),
},
},
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) {
const handlers = state.hooks.get(name) || [];
handlers.push(fn);
state.hooks.set(name, handlers);
},
},
// The pairing status never waits on a timer: it is written when the world is
// ready and whenever a pairing attempt answers, so dropping these keeps the
// snapshot and reconcile loops out of these tests.
setTimeout: () => 0,
clearTimeout: () => {},
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({
href,
method: options.method,
authorization: options.headers?.Authorization || "",
});
const route = Object.keys(answers).find((fragment) => href.includes(fragment));
const payload = route ? answers[route] : { status: "ok" };
if (payload === null) {
return { ok: false, status: 404, json: async () => { throw new SyntaxError("Unexpected token < in JSON."); } };
}
return { ok: true, status: 200, json: async () => payload };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: [], get: () => null },
items: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(MODULE_SOURCE, sandbox);
state.game = sandbox.game;
state.status = () => settingsStore.pairingStatus;
state.statusRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync/status"));
// The module's own awaits run in the vm's promise intrinsics, so a few turns of
// the event loop are what it takes for a written status to be observable.
state.settle = async () => {
for (let round = 0; round < 10; round += 1) await new Promise((resolve) => setImmediate(resolve));
};
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await state.settle();
};
state.configure = async (key, value) => {
await sandbox.game.settings.set(MODULE_ID, key, value);
await state.settle();
};
state.start = async () => {
await state.fire("init");
await state.fire("ready");
return state;
};
return state;
}
test("the pairing status is a setting the module configures", async () => {
const world = await makeStubWorld().start();
const setting = world.registered.get("pairingStatus");
assert.equal(setting.config, true, "the pairing status appears in the module settings");
assert.equal(setting.type.name, "String", "the pairing status is a sentence");
assert.equal(setting.scope, "client", "the pairing status belongs to this client, like the token it comes from");
});
test("a world that was never paired says it is not connected", async () => {
const world = await makeStubWorld({ syncToken: "" }).start();
assert.match(world.status(), /^Not connected/, "an unpaired world says so plainly");
assert.match(world.status(), /Dragonroll campaign/, "and names what it is not connected to");
assert.deepEqual(world.statusRequests(), [], "there is nothing to verify without a sync token");
});
test("a paired world names the Dragonroll campaign it is connected to", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } },
}).start();
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
assert.equal(world.statusRequests()[0].authorization, "Bearer sync-token-1", "the campaign is asked with the sync token");
});
test("a campaign that unlinked this world stops being reported as connected", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "error", msg: "unauthorized" } },
}).start();
assert.match(world.status(), /^Not connected/);
assert.match(world.status(), /no longer linked/);
});
test("an unreachable Dragonroll keeps the pairing this client already knows", async () => {
const world = await makeStubWorld({ answers: { "foundry/sync/status": null } }).start();
assert.equal(world.status(), "Connected to a Dragonroll campaign.",
"a Dragonroll without the status route says nothing, so the token speaks");
});
test("a code that cannot be redeemed explains why the world is not connected", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: { "foundry/link/complete": { status: "error", msg: "foundry.errors.link-expired" } },
});
await world.start();
await world.configure("linkCode", "AN-EXPIRED-CODE");
assert.match(world.status(), /^Not connected/);
assert.match(world.status(), /pairing code is invalid, expired, or already used/);
});
test("a code still waiting on Dragonroll says the pairing is not finished", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: { "foundry/link/complete": { status: "error", msg: "errors.internal" } },
});
await world.start();
await world.configure("linkCode", "A-CODE-TO-RETRY");
assert.equal(world.status(), "Not connected yet: waiting for Dragonroll to accept this pairing code.");
});
test("redeeming a pairing code connects the world to its campaign", async () => {
const world = await makeStubWorld({
syncToken: "",
answers: {
"foundry/link/complete": { status: "ok", campaign: LINKED_CAMPAIGN, syncToken: "sync-token-2" },
},
});
await world.start();
await world.configure("linkCode", "A-FRESH-CODE");
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
assert.equal(world.game.settings.get(MODULE_ID, "linkCode"), "", "a redeemed code is not kept");
});
test("whatever is typed into the status is replaced by the real one", async () => {
const world = await makeStubWorld({
answers: { "foundry/sync/status": { status: "ok", campaign: LINKED_CAMPAIGN, worldId: "world-1" } },
});
await world.start();
await world.configure("pairingStatus", "My own status text");
assert.equal(world.status(), `Connected to the Dragonroll campaign "${LINKED_CAMPAIGN.name}".`);
});

View File

@@ -1,312 +0,0 @@
// Tests for the Dragonroll Foundry module's sync toggle and per-actor force sync
// (Syndria98/dragonroll#8). The module is a Foundry client script with no module
// wrapper, so it is loaded into a `node:vm` context holding stubbed Foundry
// globals (`game`, `Hooks`, `ui`, `fetch`) with fake timers: that makes every
// queued push, retry and reconcile observable without a running Foundry VTT.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const MODULE_ID = "dragonroll-foundry";
const MODULE_SOURCE = fs.readFileSync(
path.join(__dirname, "..", "dragonroll-foundry", "scripts", "api.js"),
"utf8",
);
function stubDocument(id, name, extra = {}) {
return {
id,
name,
flags: {},
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(data) {
for (const [key, value] of Object.entries(data)) {
const parts = key.split(".");
const last = parts.pop();
let target = this;
for (const part of parts) target = target[part] ??= {};
target[last] = value;
}
return this;
},
toObject() {
return {
_id: this.id,
name: this.name,
type: this.type,
img: "icons/svg/mystery-man.svg",
flags: this.flags,
...(this.system ? { system: this.system } : {}),
};
},
...extra,
};
}
function makeWorldItem(id, name) {
return stubDocument(id, name, {
documentName: "Item",
type: "weapon",
parent: null,
system: { properties: { value: [] }, quantity: 1, weight: 3, rarity: "common" },
});
}
function makeStubWorld({ autoSync = true } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
notifications: [],
timers: new Map(),
nextTimerId: 1,
};
const actors = [
stubDocument("actor-1", "Thalia", { documentName: "Actor", type: "character", items: { contents: [] } }),
stubDocument("actor-2", "Grunt", { documentName: "Actor", type: "npc", items: { contents: [] } }),
];
const settingsStore = {
autoSync,
syncToken: "sync-token-1",
dragonrollApiUrl: "http://backend.test:5000",
};
const sandbox = {
console: { log() {}, info() {}, warn() {}, error() {} },
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: {
notifications: {
info: (text) => state.notifications.push(["info", text]),
warn: (text) => state.notifications.push(["warn", text]),
error: (text) => state.notifications.push(["error", text]),
},
},
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) {
const handlers = state.hooks.get(name) || [];
handlers.push(fn);
state.hooks.set(name, handlers);
},
},
// Fake timers: the module debounces and retries with setTimeout, so the tests
// decide when those callbacks run instead of waiting on the wall clock.
setTimeout: (fn, delay = 0) => {
const id = state.nextTimerId++;
state.timers.set(id, { fn, delay });
return id;
},
clearTimeout: (id) => state.timers.delete(id),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
state.requests.push({
href: String(url),
method: options.method,
body: options.body ? JSON.parse(options.body) : null,
});
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Actor: { async create() { return null; } },
Item: { async create() { return null; } },
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (id) => actors.find((actor) => actor.id === id) },
items: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(MODULE_SOURCE, sandbox);
state.game = sandbox.game;
state.actor = (id) => actors.find((document) => document.id === id);
// Sync pushes only: the pairing status read lives under the same prefix, and it
// tells nothing about what the world sent.
state.syncRequests = () => state.requests.filter((request) => request.href.includes("foundry/sync")
&& !request.href.includes("foundry/sync/status"));
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
async function drain() {
await new Promise((resolve) => setImmediate(resolve));
}
state.linkedSetup = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
state.requests.length = 0;
return state;
};
return state;
}
async function forceSyncActors(world, ...actorIds) {
const options = [];
await world.fire("getActorDirectoryEntryContext", null, options);
const entry = options.find((option) => option.name === "Dragonroll: Force Sync");
assert.ok(entry, "Dragonroll: Force Sync is offered in the actor directory context menu");
await entry.callback(actorIds.map((actorId) => ({ dataset: { actorId } })));
await world.runTimers();
}
test("auto-sync is a module setting that is on by default", async () => {
const world = makeStubWorld();
await world.fire("init");
const setting = world.registered.get("autoSync");
assert.equal(setting.default, true, "autosync is on by default");
assert.equal(setting.config, true, "autosync appears in the module settings");
assert.equal(world.game.settings.get(MODULE_ID, "autoSync"), true);
});
test("autosync on: Foundry CRUD events keep syncing with Dragonroll", async () => {
const world = await makeStubWorld().linkedSetup();
await world.fire("updateActor", world.actor("actor-1"));
await world.runTimers();
const pushes = world.syncRequests();
assert.equal(pushes.length, 1);
assert.equal(pushes[0].body.actors[0]._id, "actor-1");
});
test("autosync off: CRUD requests stop syncing", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await world.fire("updateActor", world.actor("actor-1"));
await world.fire("deleteActor", world.actor("actor-2"));
await world.fire("createItem", makeWorldItem("item-1", "Longsword"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
test("edits made while autosync is off are delivered when it is turned back on", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await world.fire("updateActor", world.actor("actor-1"));
await world.fire("createItem", makeWorldItem("item-1", "Longsword"));
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
await world.game.settings.set(MODULE_ID, "autoSync", true);
await world.runTimers();
const pushes = world.syncRequests();
assert.ok(pushes.some((request) => request.body?.fullSync === false
&& request.body.actors?.some((actor) => actor._id === "actor-1")),
"the actor edit queued while autosync was off is sent");
assert.ok(pushes.some((request) => request.href.includes("foundry/sync/item-snapshot")
&& request.body.items.some((item) => item._id === "item-1")),
"the item edit queued while autosync was off is sent");
});
test("autosync off at world start: no snapshot and no reconcile", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
});
test("force sync sends selected actors to Dragonroll even with autosync off", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await forceSyncActors(world, "actor-2");
const pushes = world.syncRequests();
assert.equal(pushes.length, 1);
assert.equal(pushes[0].body.fullSync, false, "a forced actor never prunes the campaign");
assert.deepEqual(pushes[0].body.actors.map((actor) => actor._id), ["actor-2"]);
assert.deepEqual(world.notifications.filter(([kind]) => kind !== "info"), []);
});
test("force sync sends every selected actor in one push", async () => {
const world = await makeStubWorld().linkedSetup();
await world.game.settings.set(MODULE_ID, "autoSync", false);
await forceSyncActors(world, "actor-1", "actor-2");
const pushes = world.syncRequests();
assert.equal(pushes.length, 1);
assert.deepEqual(pushes[0].body.actors.map((actor) => actor._id), ["actor-1", "actor-2"]);
});
test("force sync also works while autosync is on", async () => {
const world = await makeStubWorld().linkedSetup();
await forceSyncActors(world, "actor-1");
assert.deepEqual(world.syncRequests()[0]?.body.actors.map((actor) => actor._id), ["actor-1"]);
});
test("force sync refuses an actor Dragonroll does not import", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
const cart = stubDocument("actor-3", "Cart", { documentName: "Actor", type: "vehicle", items: { contents: [] } });
world.game.actors.contents.push(cart);
await forceSyncActors(world, "actor-3");
assert.deepEqual(world.syncRequests(), []);
assert.ok(world.notifications.some(([kind, text]) => kind === "warn" && text.includes("Cart")));
});
test("turning autosync back on reconciles both sides again", async () => {
const world = makeStubWorld({ autoSync: false });
await world.fire("init");
await world.fire("ready");
await world.runTimers();
assert.deepEqual(world.syncRequests(), []);
await world.game.settings.set(MODULE_ID, "autoSync", true);
await world.runTimers();
assert.ok(world.syncRequests().some((request) => request.body?.fullSync === true),
"the world sends its full snapshot again");
assert.ok(world.requests.some((request) => request.href.includes("foundry/sync/characters")),
"Dragonroll documents are applied back into the world");
});