From a39dc5e4c67ab2172bf824a7a790b1cd667c2ab3 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Fri, 25 Aug 2023 13:14:23 +0200 Subject: [PATCH] [templating] Add `b64urldec` and `b64urlenc` functions Signed-off-by: Knut Ahlers --- docs/content/configuration/templating.md | 26 +++++++++++++++++++++++ internal/template/strings/strings.go | 27 ++++++++++++++++++++++++ plugins_core.go | 2 ++ 3 files changed, 55 insertions(+) create mode 100644 internal/template/strings/strings.go diff --git a/docs/content/configuration/templating.md b/docs/content/configuration/templating.md index b4a1335..015acd7 100644 --- a/docs/content/configuration/templating.md +++ b/docs/content/configuration/templating.md @@ -47,6 +47,32 @@ Example: < @tester please refrain from BSG ``` +### `b64urldec` + +Decodes the input using base64 URL-encoding (like `b64dec` but using `URLEncoding` instead of `StdEncoding`) + +Syntax: `b64urldec ` + +Example: + +``` +# {{ b64urldec "bXlzdHJpbmc=" }} +< mystring +``` + +### `b64urlenc` + +Encodes the input using base64 URL-encoding (like `b64enc` but using `URLEncoding` instead of `StdEncoding`) + +Syntax: `b64urlenc ` + +Example: + +``` +# {{ b64urlenc "mystring" }} +< bXlzdHJpbmc= +``` + ### `botHasBadge` Checks whether bot has the given badge in the current channel diff --git a/internal/template/strings/strings.go b/internal/template/strings/strings.go new file mode 100644 index 0000000..b43a870 --- /dev/null +++ b/internal/template/strings/strings.go @@ -0,0 +1,27 @@ +package strings + +import ( + "encoding/base64" + + "github.com/pkg/errors" + + "github.com/Luzifer/twitch-bot/v3/plugins" +) + +func Register(args plugins.RegistrationArguments) error { + args.RegisterTemplateFunction("b64urlenc", plugins.GenericTemplateFunctionGetter(base64URLEncode)) + args.RegisterTemplateFunction("b64urldec", plugins.GenericTemplateFunctionGetter(base64URLDecode)) + return nil +} + +func base64URLEncode(v string) string { + return base64.URLEncoding.EncodeToString([]byte(v)) +} + +func base64URLDecode(v string) (string, error) { + data, err := base64.URLEncoding.DecodeString(v) + if err != nil { + return "", errors.Wrap(err, "decoding string") + } + return string(data), nil +} diff --git a/plugins_core.go b/plugins_core.go index 353af84..69f8294 100644 --- a/plugins_core.go +++ b/plugins_core.go @@ -46,6 +46,7 @@ import ( "github.com/Luzifer/twitch-bot/v3/internal/template/numeric" "github.com/Luzifer/twitch-bot/v3/internal/template/random" "github.com/Luzifer/twitch-bot/v3/internal/template/slice" + "github.com/Luzifer/twitch-bot/v3/internal/template/strings" "github.com/Luzifer/twitch-bot/v3/internal/template/subscriber" "github.com/Luzifer/twitch-bot/v3/pkg/database" "github.com/Luzifer/twitch-bot/v3/pkg/twitch" @@ -90,6 +91,7 @@ var ( numeric.Register, random.Register, slice.Register, + strings.Register, subscriber.Register, // API-only modules