Obsidian plugin

This commit is contained in:
2026-10-14 14:47:27 +02:00
parent bcd173d133
commit caeff595da
6 changed files with 571 additions and 3 deletions

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);
}