vegapokerbot/internal/handler/fsmwizard/base.go

89 lines
2.2 KiB
Go

package fsmwizard
import (
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/db/model"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/iface"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/util"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/locale"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/pkg/fsm"
"github.com/mymmrac/telego"
"golang.org/x/text/language"
"strings"
)
type Wizard struct {
UserID int64
ChatID int64
TGChat telego.Chat
User *model.User
Chat *model.Chat
Loc locale.Localizer
Data telego.Update
KeyClick util.Payload
IsMaster bool
}
type State struct {
fsm.State[Wizard]
App iface.App
}
func newBase(app iface.App) State {
return State{App: app}
}
func (s State) Localizer(langCode ...string) locale.Localizer {
lang := language.English.String()
if len(langCode) > 0 {
lang = langCode[0]
} else {
if s.Payload != nil && s.Payload.User != nil {
lang = s.Payload.User.Language
} else if s.Payload != nil && s.Payload.UserID > 0 {
user, _ := s.App.DB().ForUser().ByTelegramID(s.Payload.UserID)
if user != nil && user.Language != "" {
lang = user.Language
}
}
}
if s.Payload != nil && s.Payload.Loc != nil && (len(langCode) == 0 || s.hasLocalizerWithLocale(lang)) {
return s.Payload.Loc
}
lang = strings.ToLower(lang)
if len(lang) > 2 {
lang = lang[:2]
}
switch lang {
case "en", "ru":
return s.App.Localizer(lang)
default:
return s.App.Localizer("en")
}
}
func (s State) hasLocalizerWithLocale(lang string) bool {
if s.Payload.Loc == nil {
return false
}
return s.Payload.Loc.Tag().String() == lang
}
func (s State) LogError(err error) {
if err == nil {
return
}
if s.App.Conf().Debug {
s.App.Log().Errorf("handler error: %s, payload: %#v", err, s.Payload)
return
}
s.App.Log().Errorf("handler error: %s, user id: %d, chat id: %d", err, s.Payload.UserID, s.Payload.ChatID)
}
func (s State) Move(mc fsm.MachineControls[Wizard], stateID fsm.StateID, pl *Wizard) {
s.LogError(mc.Move(stateID, pl))
}
func (s State) MoveForHandle(mc fsm.MachineControls[Wizard], stateID fsm.StateID, pl *Wizard) {
s.LogError(mc.MoveForHandle(stateID, pl))
}