plugin development

master
yun 2024-08-19 18:39:07 +02:00
parent bfa0145644
commit cf1aee7da1
4 changed files with 2438 additions and 72 deletions

553
main.ts
View File

@ -1,25 +1,474 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import * as Handlebars from 'handlebars';
import { App, Vault, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, TAbstractFile } from 'obsidian';
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
interface P2HLOSettings {
userToken: string;
campaignToken: string;
notesFolder: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
const DEFAULT_SETTINGS: P2HLOSettings = {
userToken: '',
campaignToken: '',
notesFolder: '/'
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
const toolName = "p2hlo-bridge"
const SYMBOLS = {
FREE: "⭓",
ACTION1: "⬻",
ACTION2: "⬺",
ACTION3: "⬽",
REACTION: "⬲"
}
const Endpoints = {
'acquire-access-token' : "https://api.herolab.online/v1/access/acquire-access-token",
'get-stage': "https://api.herolab.online/v1/campaign/get-stage",
'get-bulk': "https://api.herolab.online/v1/character/get-bulk"
}
interface convertReturn {
output: string;
name: string;
}
export default class P2HLO extends Plugin {
settings: P2HLOSettings;
private byPrefixCode(obj: object, prefix: string) {
return obj[Object.keys(obj).find( predicate => predicate.startsWith(prefix))]
}
private filterKeysByPrefixCode(obj: object, prefix: string) {
const keys = [...Object.keys(obj).filter( predicate => predicate.startsWith(prefix))]
return keys.map (key => {
return {
...obj[key]
}
})
}
private prefixNumber(n: number) {
if (n < 0) {
return `-${n}`
} else if (n > 0) {
return `+${n}`
} else {
return "+0"
}
}
private hloTextToMarkdown(str: string) {
return str.replace(/\{b\}/gi, "**").replace(/\{\/b\}/gi, "**").replace(/\{br\}\{br\}/gi, "{br}").replace(/\{br\}/gi, "\\n")
}
convert(json: Object): convertReturn|null {
const actor = this.byPrefixCode(json, "actor");
const name = actor["name"];
if (actor == undefined) {
console.error("\tskipping unknown")
return null
}
const characterData = actor["gameValues"];
const gameStatistics = actor["items"];
const perception = this.byPrefixCode(gameStatistics, "Perception");
const actions = this.filterKeysByPrefixCode(gameStatistics, "ab")
const skills = this.filterKeysByPrefixCode(gameStatistics,"sk")
const feats = this.filterKeysByPrefixCode(gameStatistics,"ft")
const armorClass = this.byPrefixCode(gameStatistics, "ac")
const clazz = this.filterKeysByPrefixCode(gameStatistics, "cl")
const gear = this.filterKeysByPrefixCode(gameStatistics,"gr")
const alchemicalItems = this.filterKeysByPrefixCode(gameStatistics,"ai")
const ancestry = this.byPrefixCode(gameStatistics, "an")
const languages = this.filterKeysByPrefixCode(gameStatistics,"ln")
const naturalWeapons = this.filterKeysByPrefixCode(gameStatistics,"nw")
const resources = this.filterKeysByPrefixCode(gameStatistics,"rv")
const savingThrows = this.filterKeysByPrefixCode(gameStatistics,"sv")
const weapons = this.filterKeysByPrefixCode(gameStatistics,"wp")
const focusSpells = this.filterKeysByPrefixCode(gameStatistics, "fs")
const spells = this.filterKeysByPrefixCode(gameStatistics, "sp")
// gathering done, now we print
const src = `
\`\`\`statblock
columns: 2
forcecolumns: true
layout: Basic Pathfinder 2e Layout
modifier: {{perception}}
hp: {{hp}}
ac: {{ac}}
name: "{{character_name}}"
size: {{size}}
level: {{classes}}
trait_03: "Player"
trait_04: "{{ancestry}}"
languages: "{{#languages}}{{this}}, {{/languages}}; "
perception:
- name: "Perception"
- desc: "Perception {{perception}}"
skills:
- name: "Skills"
- desc: "{{#skills}}__{{name}}__: {{mod}} (1d20{{mod}}); {{/skills}}"
abilitiyMods: [{{str}}, {{con}}, {{dex}}, {{int}}, {{cha}}, {{wis}}]
abilities_top:
{{#feats}}
- name: "[[{{link}}|{{name}}]]"
desc: "{{actions}} {{desc}}"
{{/feats}}
abilities_bot:
{{#actions}}
- name: "[[{{link}}|{{name}}]]"
desc: "{{actions}} {{desc}}"
{{/actions}}
armorclass:
- name: AC
desc: "{{ac}}; __Fort__: {{fortitude}} (1d20{{fortitude}}); __Ref__: {{reflex}} (1d20{{reflex}}); __Will__: {{will}} (1d20{{will}})"
speed: "{{speeds}}"
attacks:
{{#weapons}}
- name: "[[{{link}}|{{name}}]]"
desc: "{{actions}} {{desc}}"
{{/weapons}}
\`\`\`
### Spells
{{#spells}}
- [[{{link}}|{{name}}]]
{{/spells}}
### Inventory
*Items* in containers takes three actions to retrieve.
{{#items}}
- {{name}}
{{/items}}
`
const template = Handlebars.compile(src)
const data = {
character_name: name,
size: characterData["actSpace"],
classes: characterData["actClassText"],
ancestry: ancestry?.name ?? "",
languages: languages.map(predicate => predicate.name),
hp: this.byPrefixCode(gameStatistics, "rvHitPoints").rvCurrent,
perception: this.prefixNumber(perception.stNet),
ac: armorClass.stNet,
str: this.prefixNumber(this.byPrefixCode(gameStatistics, "asStr").stAbScModifier),
con: this.prefixNumber(this.byPrefixCode(gameStatistics, "asCon").stAbScModifier),
dex: this.prefixNumber(this.byPrefixCode(gameStatistics, "asDex").stAbScModifier),
int: this.prefixNumber(this.byPrefixCode(gameStatistics, "asInt").stAbScModifier),
cha: this.prefixNumber(this.byPrefixCode(gameStatistics, "asCha").stAbScModifier),
wis: this.prefixNumber(this.byPrefixCode(gameStatistics, "asWis").stAbScModifier),
fortitude: this.prefixNumber(this.byPrefixCode(gameStatistics, "svFortitude").stNet),
reflex: this.prefixNumber(this.byPrefixCode(gameStatistics, "svReflex").stNet),
will: this.prefixNumber(this.byPrefixCode(gameStatistics, "svWill").stNet),
skills: skills.map( predicate => {
return {
name: predicate.name,
mod: this.prefixNumber(predicate.stNet),
level: predicate.ProfLevel,
}
}).filter(predicate => predicate.mod != "+0"),
feats: feats.map( predicate => {
let desc = ""
let name = ""
let link = ""
let actionpoints = ""
if (predicate.name.split("(").length > 1) {
name = predicate.name.split("(")[0].trim()
} else {
name = predicate.name
}
if (predicate.useInPlay) {
desc = predicate.useInPlay
} else if (predicate.name.split("(").length > 1) {
desc = predicate.name.split("(")[1].split(")")[0]
}
link = `compendium/feats/${name.trim().replace(/\ /g, "-")}`
if (predicate.actions) {
actionpoints = predicate.actions
actionpoints = actionpoints.replace("Action1", SYMBOLS.ACTION1)
actionpoints = actionpoints.replace("Action2", SYMBOLS.ACTION2)
actionpoints = actionpoints.replace("Action3", SYMBOLS.ACTION3)
actionpoints = actionpoints.replace("Reaction", SYMBOLS.REACTION)
actionpoints = actionpoints.replace("Free", SYMBOLS.FREE)
}
return {
name: name,
desc: this.hloTextToMarkdown(desc),
actions: actionpoints,
link: link,
}
}),
actions: actions.map(predicate => {
let desc = ""
let name = ""
let actionpoints = ""
let link = ""
if (predicate.name.split("(").length > 1) {
name = predicate.name.split("(")[0].trim()
} else {
name = predicate.name
}
if (predicate.useInPlay) {
desc = predicate.useInPlay
} else if (predicate.name.split("(").length > 1) {
desc = predicate.name.split("(")[1].split(")")[0]
}
link = `rules/actions/${name.trim().replace(/\ /g, "-")}`
if (predicate.actions) {
actionpoints = predicate.actions
actionpoints = actionpoints.replace("Action1", SYMBOLS.ACTION1)
actionpoints = actionpoints.replace("Action2", SYMBOLS.ACTION2)
actionpoints = actionpoints.replace("Action3", SYMBOLS.ACTION3)
actionpoints = actionpoints.replace("Reaction", SYMBOLS.REACTION)
actionpoints = actionpoints.replace("Free", SYMBOLS.FREE)
}
return {
name: name,
desc: this.hloTextToMarkdown(desc),
actions: actionpoints,
link: link
}
}),
weapons: [...weapons, ...naturalWeapons].map(predciate => {
return {
name: predciate.name,
desc: this.hloTextToMarkdown(predciate.useInPlay),
actions: SYMBOLS.ACTION1,
link: `compendium/equipment/items/${predciate.name}`
}
}),
items: [...alchemicalItems, ...gear].map(predicate => {
let itemName = predicate.name
console.log(predicate.items)
if (predicate.items) {
console.log(predicate.items, Object.values(predicate.items))
itemName += "("
itemName += Object.values(predicate.items).map(predicate2 => "*" + predicate2.name + "*").join(", ")
itemName += ")"
}
itemName = itemName.replace(/&#x27;/g, "'")
return {
name: itemName
}
}),
spells: [...focusSpells, ...spells].map(predicate => {
let actionpoints = ""
if (predicate.actions) {
actionpoints = predicate.actions
actionpoints = actionpoints.replace("Action1", SYMBOLS.ACTION1)
actionpoints = actionpoints.replace("Action2", SYMBOLS.ACTION2)
actionpoints = actionpoints.replace("Action3", SYMBOLS.ACTION3)
actionpoints = actionpoints.replace("Reaction", SYMBOLS.REACTION)
actionpoints = actionpoints.replace("Free", SYMBOLS.FREE)
}
let desc = ""
if (predicate.useInPlay) {
desc = this.hloTextToMarkdown(predicate.useInPlay)
}
let link = `compendium/spells/${predicate.name.trim()}`
link = link.split(" (")[0]
link = link.replace(/\ /g, "-")
let level = predicate.spLevelBase
return {
name: predicate.name,
actions: actionpoints,
link,
level,
desc,
}
}) ,
speeds : this.byPrefixCode(gameStatistics, "mvSpeed")?.stNet ?? 0,
}
const output = template(data)
return {
output,
name
}
}
async fetchAccessToken() {
const { accessToken } = await fetch(Endpoints['acquire-access-token'], {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({
refreshToken: this.settings.userToken,
toolName,
lifespan: 0
})
}).then( response => response.json() )
return accessToken
}
async fetchStage(accessToken: String): Promise<String[]> {
return new Promise( async (resolve, reject) => {
if (accessToken) {
const {wait, castList} = await fetch(Endpoints['get-stage'], {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({
accessToken: accessToken,
campaignToken: this.settings.campaignToken
})
}).then( response => response.json() )
if (wait != 0) {
await new Promise( resolve1 => setTimeout( resolve1, wait))
}
resolve(castList as String[])
}
reject()
})
}
async fetchCharacters(accessToken: String, castList: String[]): Promise<Object[]> {
return new Promise( async (resolve, reject) => {
if (accessToken && castList.length > 0) {
const individualCharacters: any = castList.map( castId => {
return {
elementToken: this.settings.campaignToken,
castId: castId
}
})
const {wait, characters} = await fetch(Endpoints['get-bulk'], {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({
elementToken: this.settings.campaignToken,
accessToken: accessToken,
characters: individualCharacters
})
}).then( response => response.json() )
if (wait != 0) {
await new Promise( resolve1 => setTimeout( resolve1, wait))
}
resolve(characters)
}
reject()
})
}
async preflightTest() {
if (this.settings.userToken == '' || this.settings.campaignToken == '') {
return false
}
return true
}
async performTask() {
if (await this.preflightTest()) {
const accessToken = await this.fetchAccessToken()
const castMember = await this.fetchStage(accessToken)
console.log(castMember)
if (castMember.length == 0) {
new Notice("No Castmember found on Stage. Did you forgot to start a session?")
return
}
const characters = await this.fetchCharacters(accessToken, castMember)
console.log(characters)
try {
const folder = this.app.vault.getFolderByPath(this.settings.notesFolder)
await this.app.vault.trash(folder as TAbstractFile, true)
} catch (e) {
console.log(e)
}
try {
await this.app.vault.createFolder(this.settings.notesFolder)
} catch (e) {
}
for (let character of characters) {
const result = this.convert(character.export.actors)
if (result != null) {
try {
await this.app.vault.create(`${this.settings.notesFolder}/${result.name}.md`, result.output)
} catch (e) {
const file = this.app.vault.getFileByPath(`/${this.settings.notesFolder}/${result.name}.md`)
if (file) {
await this.app.vault.modify(file, result.output)
} else {
console.error(file)
}
}
}
}
new Notice("Import completed")
}
}
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
const ribbonIconEl = this.addRibbonIcon('dice', 'Sync Stage', async (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
await this.performTask()
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
@ -30,41 +479,13 @@ export default class MyPlugin extends Plugin {
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
id: 'sync-herolabonline-stage',
name: 'Sync Stage',
callback: () => {
new SampleModal(this.app).open();
this.preflightTest()
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
@ -91,26 +512,10 @@ export default class MyPlugin extends Plugin {
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
plugin: P2HLO;
constructor(app: App, plugin: MyPlugin) {
constructor(app: App, plugin: P2HLO) {
super(app, plugin);
this.plugin = plugin;
}
@ -121,14 +526,34 @@ class SampleSettingTab extends PluginSettingTab {
containerEl.empty();
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.setName('User Token')
.setDesc('enter your user token from your herolab.online apprentice or higher account')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.setPlaceholder('User Token')
.setValue(this.plugin.settings.userToken)
.onChange(async (value) => {
this.plugin.settings.mySetting = value;
this.plugin.settings.userToken = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Campaign Token')
.setDesc('enter the Element Token of your Campaign you want to get the characters from')
.addText(text => text
.setPlaceholder('element token')
.setValue(this.plugin.settings.campaignToken)
.onChange(async (value) => {
this.plugin.settings.campaignToken = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Character note folder')
.setDesc('enter the path where the character notes should be placed in')
.addText(text => text
.setPlaceholder('/')
.setValue(this.plugin.settings.notesFolder)
.onChange(async (value) => {
this.plugin.settings.notesFolder = value;
await this.plugin.saveSettings();
}));
}
}

View File

@ -1,11 +1,11 @@
{
"id": "sample-plugin",
"name": "Sample Plugin",
"id": "pf2e-herolab-bridge",
"name": "Pf2e Herolab Bridge",
"version": "1.0.0",
"minAppVersion": "0.15.0",
"description": "Demonstrates some of the capabilities of the Obsidian API.",
"author": "Obsidian",
"authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing",
"description": "Allows to keep pathfinder 2e characters in a campaign synchronised",
"author": "org.macniel",
"authorUrl": "",
"fundingUrl": "",
"isDesktopOnly": false
}

1938
package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{
"name": "obsidian-sample-plugin",
"name": "obsidian-pf2e-herolab-bridge",
"version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"description": "a pathfinder 2e herolab bridge to sync player characters",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
@ -20,5 +20,8 @@
"obsidian": "latest",
"tslib": "2.4.0",
"typescript": "4.7.4"
},
"dependencies": {
"handlebars": "^4.7.8"
}
}