diff --git a/pkg/app_manager.go b/pkg/app_manager.go index 1faae04..62e1dba 100644 --- a/pkg/app_manager.go +++ b/pkg/app_manager.go @@ -11,7 +11,6 @@ import ( "main/pkg/reporters/telegram" snapshotPkg "main/pkg/snapshot" statePkg "main/pkg/state" - templatesPkg "main/pkg/templates" "main/pkg/tendermint" "main/pkg/types" "main/pkg/utils" @@ -54,10 +53,9 @@ func NewAppManager( stateManager := statePkg.NewManager(managerLogger, config, metricsManager, snapshotManager, database) websocketManager := tendermint.NewWebsocketManager(managerLogger, config, metricsManager) - templatesManager := templatesPkg.NewManager(logger) reporters := []reportersPkg.Reporter{ - telegram.NewReporter(config, managerLogger, stateManager, metricsManager, templatesManager), - discord.NewReporter(config, managerLogger, stateManager, metricsManager, templatesManager), + telegram.NewReporter(config, managerLogger, stateManager, metricsManager), + discord.NewReporter(config, managerLogger, stateManager, metricsManager), } return &AppManager{ diff --git a/pkg/reporters/discord/discord.go b/pkg/reporters/discord/discord.go index b4759b5..ccdaf4a 100644 --- a/pkg/reporters/discord/discord.go +++ b/pkg/reporters/discord/discord.go @@ -9,7 +9,6 @@ import ( reportPkg "main/pkg/report" statePkg "main/pkg/state" templatesPkg "main/pkg/templates" - "main/pkg/types" "main/pkg/utils" "strings" "sync" @@ -29,7 +28,7 @@ type Reporter struct { Config *config.ChainConfig Manager *statePkg.Manager MetricsManager *metrics.Manager - TemplatesManager *templatesPkg.Manager + TemplatesManager templatesPkg.Manager Commands map[string]*Command } @@ -38,7 +37,6 @@ func NewReporter( logger zerolog.Logger, manager *statePkg.Manager, metricsManager *metrics.Manager, - templatesManager *templatesPkg.Manager, ) *Reporter { return &Reporter{ Token: chainConfig.DiscordConfig.Token, @@ -48,7 +46,7 @@ func NewReporter( Logger: logger.With().Str("component", "discord_reporter").Logger(), Manager: manager, MetricsManager: metricsManager, - TemplatesManager: templatesManager, + TemplatesManager: templatesPkg.NewManager(logger, constants.DiscordReporterName), Commands: make(map[string]*Command, 0), } } @@ -179,7 +177,7 @@ func (reporter *Reporter) Send(report *reportPkg.Report) error { func (reporter *Reporter) SerializeEntry(rawEntry reportPkg.Entry) string { validator := rawEntry.GetValidator() notifiers := reporter.Manager.GetNotifiersForReporter(validator.OperatorAddress, reporter.Name()) - notifiersSerialized := " " + reporter.SerializeNotifiers(notifiers) + notifiersSerialized := " " + reporter.TemplatesManager.SerializeNotifiers(notifiers) switch entry := rawEntry.(type) { case events.ValidatorGroupChanged: @@ -194,7 +192,7 @@ func (reporter *Reporter) SerializeEntry(rawEntry reportPkg.Entry) string { // a string like "🟑 is skipping blocks (> 1.0%) (XXX till jail) " "**%s %s %s**%s%s", entry.GetEmoji(), - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), entry.GetDescription(), timeToJailStr, notifiersSerialized, @@ -202,37 +200,37 @@ func (reporter *Reporter) SerializeEntry(rawEntry reportPkg.Entry) string { case events.ValidatorJailed: return fmt.Sprintf( "**❌ %s was jailed**%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorUnjailed: return fmt.Sprintf( "**πŸ‘Œ %s was unjailed**%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorInactive: return fmt.Sprintf( "πŸ˜” **%s is now not in the active set**%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorActive: return fmt.Sprintf( "βœ… **%s is now in the active set**%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorTombstoned: return fmt.Sprintf( "**πŸ’€ %s was tombstoned**%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorCreated: return fmt.Sprintf( "**πŸ’‘New validator created: %s**", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), ) default: return fmt.Sprintf("Unsupported event %+v\n", entry) @@ -255,15 +253,3 @@ func (reporter *Reporter) BotRespond(s *discordgo.Session, i *discordgo.Interact func (reporter *Reporter) SerializeDate(date time.Time) string { return date.Format(time.RFC822) } - -func (reporter *Reporter) SerializeLink(link types.Link) string { - return reporter.TemplatesManager.SerializeMarkdownLink(link) -} - -func (reporter *Reporter) SerializeNotifiers(notifiers []*types.Notifier) string { - return reporter.TemplatesManager.SerializeMarkdownNotifiers(notifiers) -} - -func (reporter *Reporter) SerializeNotifier(notifier *types.Notifier) string { - return reporter.TemplatesManager.SerializeMarkdownNotifier(notifier) -} diff --git a/pkg/reporters/discord/help.go b/pkg/reporters/discord/help.go index 2b153b1..fb2d410 100644 --- a/pkg/reporters/discord/help.go +++ b/pkg/reporters/discord/help.go @@ -15,7 +15,7 @@ func (reporter *Reporter) GetHelpCommand() *Command { Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) { reporter.MetricsManager.LogReporterQuery(reporter.Config.Name, constants.DiscordReporterName, "help") - template, err := reporter.TemplatesManager.Render("Help", reporter.Commands, constants.FormatTypeMarkdown) + template, err := reporter.TemplatesManager.Render("Help", reporter.Commands) if err != nil { reporter.Logger.Error().Err(err).Str("template", "help").Msg("Error rendering template") return diff --git a/pkg/reporters/discord/missing.go b/pkg/reporters/discord/missing.go index 0bff82d..674ce8f 100644 --- a/pkg/reporters/discord/missing.go +++ b/pkg/reporters/discord/missing.go @@ -64,7 +64,7 @@ func (reporter *Reporter) GetMissingCommand() *Command { }), } - template, err := reporter.TemplatesManager.Render("Missing", render, constants.FormatTypeMarkdown) + template, err := reporter.TemplatesManager.Render("Missing", render) if err != nil { reporter.Logger.Error().Err(err).Msg("Error rendering missing") return diff --git a/pkg/reporters/discord/notifiers.go b/pkg/reporters/discord/notifiers.go index 939d844..204384e 100644 --- a/pkg/reporters/discord/notifiers.go +++ b/pkg/reporters/discord/notifiers.go @@ -35,7 +35,7 @@ func (reporter *Reporter) GetNotifiersCommand() *Command { template, err := reporter.TemplatesManager.Render("Notifiers", notifierRender{ Entries: entries, Config: reporter.Config, - }, constants.FormatTypeMarkdown) + }) if err != nil { reporter.BotRespond(s, i, "Error rendering notifiers template") return diff --git a/pkg/reporters/discord/params.go b/pkg/reporters/discord/params.go index 9c8720b..0854c95 100644 --- a/pkg/reporters/discord/params.go +++ b/pkg/reporters/discord/params.go @@ -22,7 +22,7 @@ func (reporter *Reporter) GetParamsCommand() *Command { Config: reporter.Config, BlockTime: blockTime, MaxTimeToJail: maxTimeToJail, - }, constants.FormatTypeMarkdown) + }) if err != nil { reporter.Logger.Error().Err(err).Msg("Error rendering params template") return diff --git a/pkg/reporters/discord/status.go b/pkg/reporters/discord/status.go index 561284c..4a8fc92 100644 --- a/pkg/reporters/discord/status.go +++ b/pkg/reporters/discord/status.go @@ -57,24 +57,24 @@ func (reporter *Reporter) GetStatusCommand() *Command { if validator.Jailed { sb.WriteString(fmt.Sprintf( "**%s:** jailed\n", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), )) } else if !validator.Active() { sb.WriteString(fmt.Sprintf( "**%s:** not in the active set\n", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), )) } else { if signatureInfo, err := reporter.Manager.GetValidatorMissedBlocks(validator); err != nil { sb.WriteString(fmt.Sprintf( "**%s:**: error getting validators missed blocks: %s", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), err, )) } else { sb.WriteString(fmt.Sprintf( "**%s:** %d missed blocks (%.2f%%)\n", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), signatureInfo.GetNotSigned(), float64(signatureInfo.GetNotSigned())/float64(reporter.Config.BlocksWindow)*100, )) diff --git a/pkg/reporters/discord/subscribe.go b/pkg/reporters/discord/subscribe.go index 8f8aa9f..b555620 100644 --- a/pkg/reporters/discord/subscribe.go +++ b/pkg/reporters/discord/subscribe.go @@ -59,7 +59,7 @@ func (reporter *Reporter) GetSubscribeCommand() *Command { } validatorLink := reporter.Config.ExplorerConfig.GetValidatorLink(validator) - validatorLinkSerialized := reporter.SerializeLink(validatorLink) + validatorLinkSerialized := reporter.TemplatesManager.SerializeLink(validatorLink) reporter.BotRespond(s, i, fmt.Sprintf( "Subscribed to validator's notifications on %s: %s", diff --git a/pkg/reporters/discord/unsubscribe.go b/pkg/reporters/discord/unsubscribe.go index 55748d9..2b40abc 100644 --- a/pkg/reporters/discord/unsubscribe.go +++ b/pkg/reporters/discord/unsubscribe.go @@ -54,7 +54,7 @@ func (reporter *Reporter) GetUnsubscribeCommand() *Command { } validatorLink := reporter.Config.ExplorerConfig.GetValidatorLink(validator) - validatorLinkSerialized := reporter.SerializeLink(validatorLink) + validatorLinkSerialized := reporter.TemplatesManager.SerializeLink(validatorLink) reporter.BotRespond(s, i, fmt.Sprintf( "Unsubscribed from validator's notifications on %s: %s", diff --git a/pkg/reporters/telegram/help.go b/pkg/reporters/telegram/help.go index 7b13afe..2a7ea46 100644 --- a/pkg/reporters/telegram/help.go +++ b/pkg/reporters/telegram/help.go @@ -14,7 +14,7 @@ func (reporter *Reporter) HandleHelp(c tele.Context) error { reporter.MetricsManager.LogReporterQuery(reporter.Config.Name, constants.TelegramReporterName, "help") - template, err := reporter.TemplatesManager.Render("Help", nil, constants.FormatTypeHTML) + template, err := reporter.TemplatesManager.Render("Help", nil) if err != nil { return err } diff --git a/pkg/reporters/telegram/missing.go b/pkg/reporters/telegram/missing.go index 98cdc9f..206eba8 100644 --- a/pkg/reporters/telegram/missing.go +++ b/pkg/reporters/telegram/missing.go @@ -56,7 +56,7 @@ func (reporter *Reporter) HandleMissingValidators(c tele.Context) error { }), } - template, err := reporter.TemplatesManager.Render("Missing", render, constants.FormatTypeHTML) + template, err := reporter.TemplatesManager.Render("Missing", render) if err != nil { return err } diff --git a/pkg/reporters/telegram/notifiers.go b/pkg/reporters/telegram/notifiers.go index 51b04d8..05dfaaa 100644 --- a/pkg/reporters/telegram/notifiers.go +++ b/pkg/reporters/telegram/notifiers.go @@ -33,7 +33,7 @@ func (reporter *Reporter) HandleNotifiers(c tele.Context) error { template, err := reporter.TemplatesManager.Render("Notifiers", notifierRender{ Entries: entries, Config: reporter.Config, - }, constants.FormatTypeHTML) + }) if err != nil { return err } diff --git a/pkg/reporters/telegram/params.go b/pkg/reporters/telegram/params.go index 8add8f1..924dd8f 100644 --- a/pkg/reporters/telegram/params.go +++ b/pkg/reporters/telegram/params.go @@ -21,7 +21,7 @@ func (reporter *Reporter) HandleParams(c tele.Context) error { Config: reporter.Config, BlockTime: blockTime, MaxTimeToJail: maxTimeToJail, - }, constants.FormatTypeHTML) + }) if err != nil { return err } diff --git a/pkg/reporters/telegram/status.go b/pkg/reporters/telegram/status.go index 673e996..5cfaa17 100644 --- a/pkg/reporters/telegram/status.go +++ b/pkg/reporters/telegram/status.go @@ -46,24 +46,24 @@ func (reporter *Reporter) HandleStatus(c tele.Context) error { if validator.Jailed { sb.WriteString(fmt.Sprintf( "%s: jailed\n", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), )) } else if !validator.Active() { sb.WriteString(fmt.Sprintf( "%s: not in the active set\n", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), )) } else { if signatureInfo, err := reporter.Manager.GetValidatorMissedBlocks(validator); err != nil { sb.WriteString(fmt.Sprintf( "%s:: error getting validators missed blocks: %s", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), err, )) } else { sb.WriteString(fmt.Sprintf( "%s: %d missed blocks (%.2f%%)\n", - reporter.SerializeLink(link), + reporter.TemplatesManager.SerializeLink(link), signatureInfo.GetNotSigned(), float64(signatureInfo.GetNotSigned())/float64(reporter.Config.BlocksWindow)*100, )) diff --git a/pkg/reporters/telegram/subscribe.go b/pkg/reporters/telegram/subscribe.go index b7da5b3..f37f4d4 100644 --- a/pkg/reporters/telegram/subscribe.go +++ b/pkg/reporters/telegram/subscribe.go @@ -56,7 +56,7 @@ func (reporter *Reporter) HandleSubscribe(c tele.Context) error { } validatorLink := reporter.Config.ExplorerConfig.GetValidatorLink(validator) - validatorLinkSerialized := reporter.SerializeLink(validatorLink) + validatorLinkSerialized := reporter.TemplatesManager.SerializeLink(validatorLink) return reporter.BotReply(c, fmt.Sprintf( "Subscribed to validator's notifications on %s: %s", diff --git a/pkg/reporters/telegram/telegram.go b/pkg/reporters/telegram/telegram.go index 3d5f7fd..088e028 100644 --- a/pkg/reporters/telegram/telegram.go +++ b/pkg/reporters/telegram/telegram.go @@ -3,14 +3,12 @@ package telegram import ( "fmt" "html" - "html/template" "main/pkg/constants" "main/pkg/events" "main/pkg/metrics" reportPkg "main/pkg/report" statePkg "main/pkg/state" templatesPkg "main/pkg/templates" - "main/pkg/types" "strings" "time" @@ -32,7 +30,7 @@ type Reporter struct { Config *config.ChainConfig Manager *statePkg.Manager MetricsManager *metrics.Manager - TemplatesManager *templatesPkg.Manager + TemplatesManager templatesPkg.Manager } const ( @@ -44,7 +42,6 @@ func NewReporter( logger zerolog.Logger, manager *statePkg.Manager, metricsManager *metrics.Manager, - templatesManager *templatesPkg.Manager, ) *Reporter { return &Reporter{ Token: chainConfig.TelegramConfig.Token, @@ -54,7 +51,7 @@ func NewReporter( Logger: logger.With().Str("component", "telegram_reporter").Logger(), Manager: manager, MetricsManager: metricsManager, - TemplatesManager: templatesManager, + TemplatesManager: templatesPkg.NewManager(logger, constants.TelegramReporterName), } } @@ -115,7 +112,7 @@ func (reporter *Reporter) Enabled() bool { func (reporter *Reporter) SerializeEntry(rawEntry reportPkg.Entry) string { validator := rawEntry.GetValidator() notifiers := reporter.Manager.GetNotifiersForReporter(validator.OperatorAddress, reporter.Name()) - notifiersSerialized := " " + reporter.SerializeNotifiers(notifiers) + notifiersSerialized := " " + reporter.TemplatesManager.SerializeNotifiers(notifiers) switch entry := rawEntry.(type) { case events.ValidatorGroupChanged: @@ -130,7 +127,7 @@ func (reporter *Reporter) SerializeEntry(rawEntry reportPkg.Entry) string { // a string like "🟑 is skipping blocks (> 1.0%) (XXX till jail) " "%s %s %s%s%s", entry.GetEmoji(), - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), html.EscapeString(entry.GetDescription()), timeToJailStr, notifiersSerialized, @@ -138,37 +135,37 @@ func (reporter *Reporter) SerializeEntry(rawEntry reportPkg.Entry) string { case events.ValidatorJailed: return fmt.Sprintf( "❌ %s was jailed%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorUnjailed: return fmt.Sprintf( "πŸ‘Œ %s was unjailed%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorInactive: return fmt.Sprintf( "πŸ˜” %s is now not in the active set%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorActive: return fmt.Sprintf( "βœ… %s is now in the active set%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorTombstoned: return fmt.Sprintf( "πŸ’€ %s was tombstoned%s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), notifiersSerialized, ) case events.ValidatorCreated: return fmt.Sprintf( "πŸ’‘New validator created: %s", - reporter.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), + reporter.TemplatesManager.SerializeLink(reporter.Config.ExplorerConfig.GetValidatorLink(entry.Validator)), ) default: return fmt.Sprintf("Unsupported event %+v\n", entry) @@ -233,15 +230,3 @@ func (reporter *Reporter) BotReply(c tele.Context, msg string) error { func (reporter *Reporter) SerializeDate(date time.Time) string { return date.Format(time.RFC822) } - -func (reporter *Reporter) SerializeLink(link types.Link) template.HTML { - return reporter.TemplatesManager.SerializeLink(link) -} - -func (reporter *Reporter) SerializeNotifiers(notifiers []*types.Notifier) string { - return reporter.TemplatesManager.SerializeNotifiers(notifiers) -} - -func (reporter *Reporter) SerializeNotifier(notifier *types.Notifier) string { - return reporter.TemplatesManager.SerializeNotifier(notifier) -} diff --git a/pkg/reporters/telegram/unsubscribe.go b/pkg/reporters/telegram/unsubscribe.go index 7b1e888..d9ea652 100644 --- a/pkg/reporters/telegram/unsubscribe.go +++ b/pkg/reporters/telegram/unsubscribe.go @@ -42,7 +42,7 @@ func (reporter *Reporter) HandleUnsubscribe(c tele.Context) error { } validatorLink := reporter.Config.ExplorerConfig.GetValidatorLink(validator) - validatorLinkSerialized := reporter.SerializeLink(validatorLink) + validatorLinkSerialized := reporter.TemplatesManager.SerializeLink(validatorLink) return reporter.BotReply(c, fmt.Sprintf( "Unsubscribed from validator's notifications on %s: %s", diff --git a/pkg/reporters/telegram/validators.go b/pkg/reporters/telegram/validators.go index 016c94b..e852e1f 100644 --- a/pkg/reporters/telegram/validators.go +++ b/pkg/reporters/telegram/validators.go @@ -51,7 +51,7 @@ func (reporter *Reporter) HandleListValidators(c tele.Context) error { }), } - template, err := reporter.TemplatesManager.Render("Missing", render, constants.FormatTypeHTML) + template, err := reporter.TemplatesManager.Render("Missing", render) if err != nil { return err } diff --git a/pkg/templates/markdown.go b/pkg/templates/discord.go similarity index 50% rename from pkg/templates/markdown.go rename to pkg/templates/discord.go index 55acb18..003364a 100644 --- a/pkg/templates/markdown.go +++ b/pkg/templates/discord.go @@ -3,17 +3,33 @@ package templates import ( "bytes" "fmt" + htmlTemplate "html/template" "main/pkg/types" "main/pkg/utils" "main/templates" "strings" "text/template" + "time" + + "github.com/rs/zerolog" ) -func (m *Manager) GetMarkdownTemplate( - name string, - serializers map[string]any, -) (*template.Template, error) { +type DiscordTemplateManager struct { + Logger zerolog.Logger + Templates map[string]interface{} +} + +func NewDiscordTemplateManager(logger zerolog.Logger) *DiscordTemplateManager { + return &DiscordTemplateManager{ + Logger: logger.With(). + Str("component", "templates_manager"). + Str("reporter", "discord"). + Logger(), + Templates: make(map[string]interface{}, 0), + } +} + +func (m *DiscordTemplateManager) GetTemplate(name string) (*template.Template, error) { if cachedTemplate, ok := m.Templates[name]; ok { m.Logger.Trace().Str("type", name).Msg("Using cached template") if convertedTemplate, ok := cachedTemplate.(*template.Template); !ok { @@ -24,14 +40,10 @@ func (m *Manager) GetMarkdownTemplate( } allSerializers := map[string]any{ - "SerializeLink": m.SerializeMarkdownLink, + "SerializeLink": m.SerializeLink, "SerializeDate": m.SerializeDate, - "SerializeNotifier": m.SerializeMarkdownNotifier, - "SerializeNotifiers": m.SerializeMarkdownNotifiers, - } - - for key, serializer := range serializers { - allSerializers[key] = serializer + "SerializeNotifier": m.SerializeNotifier, + "SerializeNotifiers": m.SerializeNotifiers, } m.Logger.Trace().Str("type", name).Msg("Loading template") @@ -48,12 +60,8 @@ func (m *Manager) GetMarkdownTemplate( return t, nil } -func (m *Manager) RenderMarkdown( - templateName string, - data interface{}, - serializers map[string]any, -) (string, error) { - templateToRender, err := m.GetMarkdownTemplate(templateName, serializers) +func (m *DiscordTemplateManager) Render(templateName string, data interface{}) (string, error) { + templateToRender, err := m.GetTemplate(templateName) if err != nil { m.Logger.Error().Err(err).Str("type", templateName).Msg("Error loading template") return "", err @@ -69,22 +77,26 @@ func (m *Manager) RenderMarkdown( return buffer.String(), err } -func (m *Manager) SerializeMarkdownLink(link types.Link) string { +func (m *DiscordTemplateManager) SerializeLink(link types.Link) htmlTemplate.HTML { if link.Href == "" { - return link.Text + return htmlTemplate.HTML(link.Text) } // using <> to prevent auto-embed links, taken from here: // https://support.discord.com/hc/en-us/articles/206342858--How-do-I-disable-auto-embed- - return fmt.Sprintf("[%s](<%s>)", link.Text, link.Href) + return htmlTemplate.HTML(fmt.Sprintf("[%s](<%s>)", link.Text, link.Href)) } -func (m *Manager) SerializeMarkdownNotifiers(notifiers types.Notifiers) string { - notifiersNormalized := utils.Map(notifiers, m.SerializeMarkdownNotifier) +func (m *DiscordTemplateManager) SerializeNotifiers(notifiers types.Notifiers) string { + notifiersNormalized := utils.Map(notifiers, m.SerializeNotifier) return strings.Join(notifiersNormalized, " ") } -func (m *Manager) SerializeMarkdownNotifier(notifier *types.Notifier) string { +func (m *DiscordTemplateManager) SerializeNotifier(notifier *types.Notifier) string { return fmt.Sprintf("<@%s>", notifier.UserID) } + +func (m *DiscordTemplateManager) SerializeDate(date time.Time) string { + return date.Format(time.RFC822) +} diff --git a/pkg/templates/manager.go b/pkg/templates/manager.go index f894ae7..6a29887 100644 --- a/pkg/templates/manager.go +++ b/pkg/templates/manager.go @@ -1,44 +1,32 @@ package templates import ( - "fmt" + "html/template" "main/pkg/constants" + "main/pkg/types" + "time" "github.com/rs/zerolog" ) -type Manager struct { - Logger zerolog.Logger - Templates map[string]interface{} +type Manager interface { + Render(string, interface{}) (string, error) + SerializeLink(link types.Link) template.HTML + SerializeDate(date time.Time) string + SerializeNotifiers(notifiers types.Notifiers) string + SerializeNotifier(notifier *types.Notifier) string } -func NewManager(logger zerolog.Logger) *Manager { - return &Manager{ - Logger: logger.With().Str("component", "templates_manager").Logger(), - Templates: make(map[string]interface{}, 0), - } -} - -func (m *Manager) Render( - templateName string, - data interface{}, - formatType constants.FormatType, -) (string, error) { - return m.RenderWithSerializers(templateName, data, formatType, make(map[string]any, 0)) -} - -func (m *Manager) RenderWithSerializers( - templateName string, - data interface{}, - formatType constants.FormatType, - serializers map[string]any, -) (string, error) { - switch formatType { - case constants.FormatTypeHTML: - return m.RenderHTML(templateName, data, serializers) - case constants.FormatTypeMarkdown: - return m.RenderMarkdown(templateName, data, serializers) +func NewManager(logger zerolog.Logger, reporterType constants.ReporterName) Manager { + switch reporterType { + case constants.TelegramReporterName: + return NewTelegramTemplateManager(logger) + case constants.DiscordReporterName: + return NewDiscordTemplateManager(logger) + case constants.TestReporterName: + fallthrough default: - return "", fmt.Errorf("unknown format type: %s", formatType) + logger.Fatal().Str("type", string(reporterType)).Msg("Unknown reporter type") + return nil } } diff --git a/pkg/templates/html.go b/pkg/templates/telegram.go similarity index 63% rename from pkg/templates/html.go rename to pkg/templates/telegram.go index 9539196..bb14abe 100644 --- a/pkg/templates/html.go +++ b/pkg/templates/telegram.go @@ -9,9 +9,26 @@ import ( "main/templates" "strings" "time" + + "github.com/rs/zerolog" ) -func (m *Manager) GetHTMLTemplate(name string, serializers map[string]any) (*template.Template, error) { +type TelegramTemplateManager struct { + Logger zerolog.Logger + Templates map[string]interface{} +} + +func NewTelegramTemplateManager(logger zerolog.Logger) *TelegramTemplateManager { + return &TelegramTemplateManager{ + Logger: logger.With(). + Str("component", "templates_manager"). + Str("reporter", "telegram"). + Logger(), + Templates: make(map[string]interface{}, 0), + } +} + +func (m *TelegramTemplateManager) GetHTMLTemplate(name string) (*template.Template, error) { if cachedTemplate, ok := m.Templates[name]; ok { m.Logger.Trace().Str("type", name).Msg("Using cached template") if convertedTemplate, ok := cachedTemplate.(*template.Template); !ok { @@ -30,10 +47,6 @@ func (m *Manager) GetHTMLTemplate(name string, serializers map[string]any) (*tem "SerializeNotifiers": m.SerializeNotifiers, } - for key, serializer := range serializers { - allSerializers[key] = serializer - } - t, err := template.New(name+".html"). Funcs(allSerializers). ParseFS(templates.TemplatesFs, "telegram/"+name+".html") @@ -46,12 +59,8 @@ func (m *Manager) GetHTMLTemplate(name string, serializers map[string]any) (*tem return t, nil } -func (m *Manager) RenderHTML( - templateName string, - data interface{}, - serializers map[string]any, -) (string, error) { - templateToRender, err := m.GetHTMLTemplate(templateName, serializers) +func (m *TelegramTemplateManager) Render(templateName string, data interface{}) (string, error) { + templateToRender, err := m.GetHTMLTemplate(templateName) if err != nil { m.Logger.Error().Err(err).Str("type", templateName).Msg("Error loading template") return "", err @@ -67,11 +76,11 @@ func (m *Manager) RenderHTML( return buffer.String(), err } -func (m *Manager) SerializeDate(date time.Time) string { +func (m *TelegramTemplateManager) SerializeDate(date time.Time) string { return date.Format(time.RFC822) } -func (m *Manager) SerializeLink(link types.Link) template.HTML { +func (m *TelegramTemplateManager) SerializeLink(link types.Link) template.HTML { if link.Href == "" { return template.HTML(link.Text) } @@ -79,13 +88,13 @@ func (m *Manager) SerializeLink(link types.Link) template.HTML { return template.HTML(fmt.Sprintf("%s", link.Href, link.Text)) } -func (m *Manager) SerializeNotifiers(notifiers types.Notifiers) string { +func (m *TelegramTemplateManager) SerializeNotifiers(notifiers types.Notifiers) string { notifiersNormalized := utils.Map(notifiers, m.SerializeNotifier) return strings.Join(notifiersNormalized, " ") } -func (m *Manager) SerializeNotifier(notifier *types.Notifier) string { +func (m *TelegramTemplateManager) SerializeNotifier(notifier *types.Notifier) string { if strings.HasPrefix(notifier.UserName, "@") { return notifier.UserName }