From adfd931af823b3cee24b8b4f542c262001fd0381 Mon Sep 17 00:00:00 2001 From: Richard Maw Date: Sun, 15 Sep 2024 12:18:25 +0100 Subject: [PATCH] Add base64Encode handlebars helper This is intended to pair with the browser atob function so no base64Decode is provided, but should be equivalent to the mtscript base64Encode if data has already been encoded into the token's properties. --- .../rptools/maptool/util/HandlebarsUtil.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/main/java/net/rptools/maptool/util/HandlebarsUtil.java b/src/main/java/net/rptools/maptool/util/HandlebarsUtil.java index 77be2a0061..a9293948e7 100644 --- a/src/main/java/net/rptools/maptool/util/HandlebarsUtil.java +++ b/src/main/java/net/rptools/maptool/util/HandlebarsUtil.java @@ -16,6 +16,8 @@ import com.github.jknack.handlebars.Context; import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Helper; +import com.github.jknack.handlebars.Options; import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.context.JavaBeanValueResolver; import com.github.jknack.handlebars.helper.AssignHelper; @@ -29,8 +31,10 @@ import java.io.File; import java.io.IOException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Arrays; +import java.util.Base64; import net.rptools.maptool.model.Token; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -95,6 +99,29 @@ protected URL getResource(String location) throws IOException { } } + private static enum MapToolHelpers implements Helper { + /** + * Turns the textual form of the value into a base64-encoded string. For example: + * + *
+     * <script type="application/json;base64" id="jsonProperty">
+     *   {{ base64Encode properties[0].value }}
+     * </script>
+     * <script type="application/javascript">
+     * const jsonProperty = JSON.parse(atob(document.getElementById("jsonProperty").innerText));
+     * </script>
+     * 
+ */ + base64Encode { + @Override + public Object apply(final Object context, final Options options) { + byte[] message = context.toString().getBytes(StandardCharsets.UTF_8); + + return new Handlebars.SafeString(Base64.getUrlEncoder().encodeToString(message)); + } + } + } + /** * Creates a new instance of the utility class. * @@ -111,6 +138,7 @@ private HandlebarsUtil(String stringTemplate, TemplateLoader loader) throws IOEx NumberHelper.register(handlebars); handlebars.registerHelper(AssignHelper.NAME, AssignHelper.INSTANCE); handlebars.registerHelper(IncludeHelper.NAME, IncludeHelper.INSTANCE); + Arrays.stream(MapToolHelpers.values()).forEach(h -> handlebars.registerHelper(h.name(), h)); template = handlebars.compileInline(stringTemplate); } catch (IOException e) {