Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add base64Encode handlebars helper #4925

Merged
merged 3 commits into from
Sep 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/main/java/net/rptools/maptool/util/HandlebarsUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -95,6 +99,29 @@ protected URL getResource(String location) throws IOException {
}
}

private static enum MapToolHelpers implements Helper<Object> {
/**
* Turns the textual form of the value into a base64-encoded string. For example:
*
* <pre>
* &lt;script type="application/json;base64" id="jsonProperty"&gt;
* {{ base64Encode properties[0].value }}
* &lt;/script&gt;
* &lt;script type="application/javascript"&gt;
* const jsonProperty = JSON.parse(atob(document.getElementById("jsonProperty").innerText));
* &lt;/script&gt;
* </pre>
*/
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.
*
Expand All @@ -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) {
Expand Down
Loading