Skip to content

Commit

Permalink
feat: move templates manager to class (#85)
Browse files Browse the repository at this point in the history
* feat: move templates manager to class

* chore: fixed linting

* chore: added tests for templates manager

* chore: fixed linting
  • Loading branch information
freak12techno authored May 11, 2024
1 parent a03e92d commit aa15dc7
Show file tree
Hide file tree
Showing 11 changed files with 247 additions and 128 deletions.
13 changes: 5 additions & 8 deletions pkg/reporters/telegram/add_mute.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package telegram

import (
"bytes"

tele "gopkg.in/telebot.v3"
)

Expand All @@ -19,12 +17,11 @@ func (reporter *Reporter) HandleAddMute(c tele.Context) error {

reporter.MutesManager.AddMute(mute)

template, _ := reporter.GetTemplate("mute_added")
var buffer bytes.Buffer
if err := template.Execute(&buffer, mute); err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering mute_added template")
return err
templateRendered, renderErr := reporter.TemplatesManager.Render("mute_added", mute)
if renderErr != nil {
reporter.Logger.Error().Err(renderErr).Msg("Error rendering template")
return reporter.BotReply(c, "Error rendering template")
}

return reporter.BotReply(c, buffer.String())
return reporter.BotReply(c, templateRendered)
}
13 changes: 5 additions & 8 deletions pkg/reporters/telegram/help.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package telegram

import (
"bytes"

tele "gopkg.in/telebot.v3"
)

Expand All @@ -12,12 +10,11 @@ func (reporter *Reporter) HandleHelp(c tele.Context) error {
Str("text", c.Text()).
Msg("Got help query")

template, _ := reporter.GetTemplate("help")
var buffer bytes.Buffer
if err := template.Execute(&buffer, reporter.Version); err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering help template")
return err
template, err := reporter.TemplatesManager.Render("help", reporter.Version)
if err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering template")
return reporter.BotReply(c, "Error rendering template")
}

return reporter.BotReply(c, buffer.String())
return reporter.BotReply(c, template)
}
12 changes: 5 additions & 7 deletions pkg/reporters/telegram/list_mutes.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package telegram

import (
"bytes"
mutes "main/pkg/mutes"
"main/pkg/utils"

Expand All @@ -18,12 +17,11 @@ func (reporter *Reporter) HandleListMutes(c tele.Context) error {
return !m.IsExpired()
})

template, _ := reporter.GetTemplate("mutes")
var buffer bytes.Buffer
if err := template.Execute(&buffer, filteredMutes); err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering votes template")
return err
template, err := reporter.TemplatesManager.Render("mutes", filteredMutes)
if err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering template")
return reporter.BotReply(c, "Error rendering template")
}

return reporter.BotReply(c, buffer.String())
return reporter.BotReply(c, template)
}
12 changes: 5 additions & 7 deletions pkg/reporters/telegram/list_proposals.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package telegram

import (
"bytes"
statePkg "main/pkg/state"

tele "gopkg.in/telebot.v3"
Expand All @@ -16,12 +15,11 @@ func (reporter *Reporter) HandleProposals(c tele.Context) error {
state := reporter.StateGenerator.GetState(statePkg.NewState())
renderedState := state.ToRenderedState()

template, _ := reporter.GetTemplate("proposals")
var buffer bytes.Buffer
if err := template.Execute(&buffer, renderedState); err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering proposals template")
return err
template, err := reporter.TemplatesManager.Render("proposals", renderedState)
if err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering template")
return reporter.BotReply(c, "Error rendering template")
}

return reporter.BotReply(c, buffer.String())
return reporter.BotReply(c, template)
}
17 changes: 4 additions & 13 deletions pkg/reporters/telegram/params.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package telegram

import (
"bytes"
"fmt"

tele "gopkg.in/telebot.v3"
Expand All @@ -18,19 +17,11 @@ func (reporter *Reporter) HandleParams(c tele.Context) error {
return reporter.BotReply(c, fmt.Sprintf("Error getting chain params: %s", err))
}

template, err := reporter.GetTemplate("params")
template, err := reporter.TemplatesManager.Render("params", params)
if err != nil {
reporter.Logger.Error().
Err(err).
Msg("Error rendering params template")
return reporter.BotReply(c, "Error rendering params template")
reporter.Logger.Error().Err(err).Msg("Error rendering template")
return reporter.BotReply(c, "Error rendering template")
}

var buffer bytes.Buffer
if err := template.Execute(&buffer, params); err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering params template")
return err
}

return reporter.BotReply(c, buffer.String())
return reporter.BotReply(c, template)
}
17 changes: 4 additions & 13 deletions pkg/reporters/telegram/tally.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package telegram

import (
"bytes"
"fmt"

tele "gopkg.in/telebot.v3"
Expand All @@ -22,19 +21,11 @@ func (reporter *Reporter) HandleTally(c tele.Context) error {
return reporter.BotReply(c, fmt.Sprintf("Error getting tallies info: %s", err))
}

template, err := reporter.GetTemplate("tally")
template, err := reporter.TemplatesManager.Render("tally", tallies)
if err != nil {
reporter.Logger.Error().
Err(err).
Msg("Error rendering tallies template")
return reporter.BotReply(c, "Error rendering tallies template")
reporter.Logger.Error().Err(err).Msg("Error rendering template")
return reporter.BotReply(c, "Error rendering template")
}

var buffer bytes.Buffer
if err := template.Execute(&buffer, tallies); err != nil {
reporter.Logger.Error().Err(err).Msg("Error rendering votes template")
return err
}

return reporter.BotReply(c, buffer.String())
return reporter.BotReply(c, template)
}
88 changes: 17 additions & 71 deletions pkg/reporters/telegram/telegram.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,34 @@
package telegram

import (
"bytes"
"fmt"
"html/template"
"main/pkg/data"
mutes "main/pkg/mutes"
"main/pkg/report/entry"
"main/pkg/state"
"main/pkg/utils"
"main/pkg/templates"
"strings"
"time"

"main/pkg/reporters"
"main/pkg/types"
"main/templates"

"github.com/rs/zerolog"
tele "gopkg.in/telebot.v3"
)

type Reporter struct {
TelegramToken string
TelegramChat int64
MutesManager *mutes.Manager
StateGenerator *state.Generator
DataManager *data.Manager
TelegramToken string
TelegramChat int64
MutesManager *mutes.Manager
StateGenerator *state.Generator
DataManager *data.Manager
TemplatesManager templates.Manager

TelegramBot *tele.Bot
Logger zerolog.Logger
Templates map[string]*template.Template

Version string
Timezone *time.Location
Version string
}

const (
Expand All @@ -49,15 +45,14 @@ func NewTelegramReporter(
timezone *time.Location,
) *Reporter {
return &Reporter{
TelegramToken: config.TelegramToken,
TelegramChat: config.TelegramChat,
MutesManager: mutesManager,
StateGenerator: stateGenerator,
DataManager: dataManager,
Logger: logger.With().Str("component", "telegram_reporter").Logger(),
Templates: make(map[string]*template.Template, 0),
Version: version,
Timezone: timezone,
TelegramToken: config.TelegramToken,
TelegramChat: config.TelegramChat,
MutesManager: mutesManager,
StateGenerator: stateGenerator,
DataManager: dataManager,
Logger: logger.With().Str("component", "telegram_reporter").Logger(),
TemplatesManager: templates.NewTelegramTemplatesManager(logger, timezone),
Version: version,
}
}

Expand Down Expand Up @@ -95,45 +90,8 @@ func (reporter *Reporter) Enabled() bool {
return reporter.TelegramToken != "" && reporter.TelegramChat != 0
}

func (reporter *Reporter) GetTemplate(tmlpType string) (*template.Template, error) {
if cachedTemplate, ok := reporter.Templates[tmlpType]; ok {
reporter.Logger.Trace().Str("type", tmlpType).Msg("Using cached template")
return cachedTemplate, nil
}

reporter.Logger.Trace().Str("type", tmlpType).Msg("Loading template")

filename := tmlpType + ".html"

t, err := template.New(filename).Funcs(template.FuncMap{
"SerializeLink": reporter.SerializeLink,
"SerializeDate": reporter.SerializeDate,
"FormatDuration": utils.FormatDuration,
}).ParseFS(templates.TemplatesFs, "telegram/"+filename)
if err != nil {
return nil, err
}

reporter.Templates[tmlpType] = t

return t, nil
}

func (reporter *Reporter) SerializeReportEntry(e entry.ReportEntry) (string, error) {
parsedTemplate, err := reporter.GetTemplate(e.Name())
if err != nil {
reporter.Logger.Error().Err(err).Str("type", e.Name()).Msg("Error loading template")
return "", err
}

var buffer bytes.Buffer
err = parsedTemplate.Execute(&buffer, e)
if err != nil {
reporter.Logger.Error().Err(err).Str("type", e.Name()).Msg("Error rendering template")
return "", err
}

return buffer.String(), nil
return reporter.TemplatesManager.Render(e.Name(), e)
}

func (reporter *Reporter) SendReport(report reporters.Report) error {
Expand Down Expand Up @@ -247,15 +205,3 @@ func ParseMuteOptions(query string, c tele.Context) (*mutes.Mute, string) {

return mute, ""
}

func (reporter *Reporter) SerializeLink(link types.Link) template.HTML {
if link.Href != "" {
return template.HTML(fmt.Sprintf("<a href='%s'>%s</a>", link.Href, link.Name))
}

return template.HTML(link.Name)
}

func (reporter *Reporter) SerializeDate(date time.Time) string {
return date.In(reporter.Timezone).Format(time.RFC1123)
}
5 changes: 5 additions & 0 deletions pkg/templates/manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package templates

type Manager interface {
Render(templateName string, data interface{}) (string, error)
}
88 changes: 88 additions & 0 deletions pkg/templates/telegram.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package templates

import (
"bytes"
"fmt"
"html/template"
"main/pkg/types"
"main/pkg/utils"
"main/templates"
"time"

"github.com/rs/zerolog"
)

type TelegramTemplatesManager struct {
Templates map[string]*template.Template
Logger zerolog.Logger
Timezone *time.Location
}

func NewTelegramTemplatesManager(
logger *zerolog.Logger,
timezone *time.Location,
) *TelegramTemplatesManager {
return &TelegramTemplatesManager{
Templates: map[string]*template.Template{},
Logger: logger.With().Str("component", "telegram_templates_manager").Logger(),
Timezone: timezone,
}
}

func (m *TelegramTemplatesManager) Render(templateName string, data interface{}) (string, error) {
templateToRender, err := m.GetTemplate(templateName)
if err != nil {
m.Logger.Error().
Err(err).
Str("name", templateName).
Msg("Error getting template")
return "", err
}

var buffer bytes.Buffer
if err := templateToRender.Execute(&buffer, data); err != nil {
m.Logger.Error().
Err(err).
Str("name", templateName).
Msg("Error rendering template")
return "", err
}

return buffer.String(), nil
}

func (m *TelegramTemplatesManager) GetTemplate(templateName string) (*template.Template, error) {
if cachedTemplate, ok := m.Templates[templateName]; ok {
m.Logger.Trace().Str("type", templateName).Msg("Using cached template")
return cachedTemplate, nil
}

m.Logger.Trace().Str("type", templateName).Msg("Loading template")

filename := templateName + ".html"

t, err := template.New(filename).Funcs(template.FuncMap{
"SerializeLink": m.SerializeLink,
"SerializeDate": m.SerializeDate,
"FormatDuration": utils.FormatDuration,
}).ParseFS(templates.TemplatesFs, "telegram/"+filename)
if err != nil {
return nil, err
}

m.Templates[templateName] = t

return t, nil
}

func (m *TelegramTemplatesManager) SerializeLink(link types.Link) template.HTML {
if link.Href != "" {
return template.HTML(fmt.Sprintf("<a href='%s'>%s</a>", link.Href, link.Name))
}

return template.HTML(link.Name)
}

func (m *TelegramTemplatesManager) SerializeDate(date time.Time) string {
return date.In(m.Timezone).Format(time.RFC1123)
}
Loading

0 comments on commit aa15dc7

Please sign in to comment.