From 951437248eb1ce980f06188c087947775a07182f Mon Sep 17 00:00:00 2001 From: Mariano Cavallo Date: Sat, 1 Jul 2023 11:37:56 +0200 Subject: [PATCH] feat: Add macro migration --- src/constants.js | 2 ++ src/lib/MacroMigration.js | 41 +++++++++++++++++++++++++++++++++++++++ src/module.mjs | 6 ++++++ 3 files changed, 49 insertions(+) create mode 100644 src/lib/MacroMigration.js diff --git a/src/constants.js b/src/constants.js index b1a780c..997fcaf 100644 --- a/src/constants.js +++ b/src/constants.js @@ -2,6 +2,8 @@ export const MODULE = { NAME: 'Random Target', ID: 'random-target', NAMESPACE: 'randomTarget', + MACRO_COMPENDIUM: 'random-target-macros', + MACRO_ID: 'oIVhNA8Po9HpYdJc', }; export const SETTING_IDS = { diff --git a/src/lib/MacroMigration.js b/src/lib/MacroMigration.js new file mode 100644 index 0000000..d7d867d --- /dev/null +++ b/src/lib/MacroMigration.js @@ -0,0 +1,41 @@ +import { MODULE } from '../constants.js'; + +export class MacroMigration { + constructor() { + this.compendiumId = `${MODULE.ID}.${MODULE.MACRO_COMPENDIUM}`; + this.macroSourceId = `Compendium.${this.compendiumId}.Macro.${MODULE.MACRO_ID}`; + } + + _getGameMacros() { + return Array.from(game.macros).filter(macro => macro._source?.flags?.core?.sourceId === this.macroSourceId); + } + + async _getLatestCompendiumVersionCommand() { + const compendiumMacros = await game.packs.get(this.compendiumId).getDocuments(); + const latestMacro = compendiumMacros.find(macro => macro._id === MODULE.MACRO_ID); + + if (!latestMacro) { + return null; + } + + return latestMacro.command; + } + + async run() { + const gameMacros = this._getGameMacros(); + + if (gameMacros.length === 0) { + return; + } + + const latestCommand = await this._getLatestCompendiumVersionCommand(); + + if (!latestCommand) { + return; + } + + gameMacros.forEach(macro => { + macro.command = latestCommand; + }); + } +} diff --git a/src/module.mjs b/src/module.mjs index 20852b9..2acac60 100644 --- a/src/module.mjs +++ b/src/module.mjs @@ -1,5 +1,6 @@ import { run } from './apps/RandomTarget.js'; import { MODULE } from './constants.js'; +import { MacroMigration } from './lib/MacroMigration.js'; import { registerSettings, saveSetting } from './settings.js'; Hooks.once('init', function () { @@ -11,3 +12,8 @@ Hooks.once('init', function () { settings: initialSettings, }; }); + +Hooks.once('ready', function () { + const migration = new MacroMigration(); + migration.run(); +});