1 Commits

Author SHA1 Message Date
caeff595da Obsidian plugin 2026-10-14 14:47:27 +02:00
6 changed files with 571 additions and 3 deletions

View File

@@ -26,6 +26,7 @@ CI (`.gitea/workflows/deploy.yml`) builds two Docker images on every push to `ma
dragonroll/
├── backend/ Express API (CommonJS, entry: src/index.js)
├── 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
├── nginx.conf reverse proxy rules for the compose stack
├── ecosystem.config.js PM2 config (stale: runs `npm start`, which does not exist — see §9)
@@ -183,7 +184,8 @@ Fetch the file from `/api/public/<filename>`.
`GET /api/campaign/list` → `{status:'ok',campaigns}`
`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}`
`POST /api/note/create` — `{title*,content,campaign*,folder?}` (folder validated against campaign)
`POST /api/note/update` — `{id*, title?, content?, folder?, color?}` — partial, ownership checked
@@ -463,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
(`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
- **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
- Plan different encounters
- 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!
## Installation 🛠️
@@ -55,7 +56,6 @@ if you want to start the development environments
- Dragonroll <-> Foundry integration
- Dragonroll <-> Discord Bot integration
- Dragonroll <-> Obsidian integration
What to sync:

View File

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

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
}