diff --git a/Dockerfile b/Dockerfile index 7c9d1eb..459436e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,24 +12,24 @@ RUN go mod download # Copy the source from the current directory to the Working Directory inside the container COPY . . -RUN go build -o dcbot . +RUN go build -o twhelpdcbot . ######## Start a new stage from scratch ####### -FROM alpine:latest +FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ -# Copy the Pre-built binary file from the previous stage +# Copy the Pre-built binary file and translations from the previous stage COPY --from=builder /app/message/translations ./message/translations -COPY --from=builder /app/dcbot . +COPY --from=builder /app/twhelpdcbot . -ENV MODE=production +ENV APP_MODE=production ENV GIN_MODE=release EXPOSE 8080 ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait ./wait RUN chmod +x ./wait -CMD ./wait && ./dcbot \ No newline at end of file +CMD ./wait && ./twhelpdcbot diff --git a/README.md b/README.md index 37cf84c..2798a13 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Features: ## Development -**Required env variables to run this bot:** +**Required ENV variables:** ``` DB_USER=your_pgdb_user diff --git a/cron/cron.go b/cron/cron.go index a5cf2de..1c73297 100644 --- a/cron/cron.go +++ b/cron/cron.go @@ -1,13 +1,11 @@ package cron import ( + "github.com/Kichiyaki/appmode" "time" - sharedutils "github.com/tribalwarshelp/shared/utils" - "github.com/sirupsen/logrus" "github.com/tribalwarshelp/golang-sdk/sdk" - "github.com/tribalwarshelp/shared/mode" "github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/group" @@ -38,12 +36,12 @@ func Attach(c *cron.Cron, cfg Config) { api: cfg.API, status: cfg.Status, } - checkEnnoblements := sharedutils.TrackExecutionTime(log, h.checkEnnoblements, "checkEnnoblements") - checkBotServers := sharedutils.TrackExecutionTime(log, h.checkBotServers, "checkBotServers") - deleteClosedTribalWarsServers := sharedutils.TrackExecutionTime(log, - h.deleteClosedTribalWarsServers, - "deleteClosedTribalWarsServers") - updateBotStatus := sharedutils.TrackExecutionTime(log, h.updateBotStatus, "updateBotStatus") + checkEnnoblements := trackDuration(log, h.checkEnnoblements, "checkEnnoblements") + checkBotServers := trackDuration(log, h.checkBotServers, "checkBotServers") + deleteClosedTribalWarsServers := trackDuration(log, + h.deleteClosedTWServers, + "deleteClosedTWServers") + updateBotStatus := trackDuration(log, h.updateBotStatus, "updateBotStatus") c.AddFunc("@every 1m", checkEnnoblements) c.AddFunc("@every 30m", checkBotServers) c.AddFunc("@every 2h10m", deleteClosedTribalWarsServers) @@ -52,7 +50,7 @@ func Attach(c *cron.Cron, cfg Config) { checkBotServers() deleteClosedTribalWarsServers() updateBotStatus() - if mode.Get() == mode.DevelopmentMode { + if appmode.Equals(appmode.DevelopmentMode) { checkEnnoblements() } }() diff --git a/cron/ennoblements.go b/cron/ennoblements.go index 621f7de..c970cd5 100644 --- a/cron/ennoblements.go +++ b/cron/ennoblements.go @@ -1,13 +1,14 @@ package cron import ( - "github.com/tribalwarshelp/dcbot/utils" - shared_models "github.com/tribalwarshelp/shared/models" + "github.com/tribalwarshelp/shared/tw/twmodel" + + "github.com/tribalwarshelp/dcbot/tw/twutil" ) -type ennoblements []*shared_models.Ennoblement +type ennoblements []*twmodel.Ennoblement -func (e ennoblements) getLastEnnoblement() *shared_models.Ennoblement { +func (e ennoblements) getLastEnnoblement() *twmodel.Ennoblement { length := len(e) if length <= 0 { return nil @@ -18,8 +19,8 @@ func (e ennoblements) getLastEnnoblement() *shared_models.Ennoblement { func (e ennoblements) getLostVillagesByTribe(tribeID int) ennoblements { filtered := ennoblements{} for _, ennoblement := range e { - if (!utils.IsPlayerTribeNil(ennoblement.NewOwner) && ennoblement.NewOwner.Tribe.ID == tribeID) || - utils.IsPlayerTribeNil(ennoblement.OldOwner) || + if (!twutil.IsPlayerTribeNil(ennoblement.NewOwner) && ennoblement.NewOwner.Tribe.ID == tribeID) || + twutil.IsPlayerTribeNil(ennoblement.OldOwner) || ennoblement.OldOwner.Tribe.ID != tribeID { continue } @@ -31,9 +32,9 @@ func (e ennoblements) getLostVillagesByTribe(tribeID int) ennoblements { func (e ennoblements) getConqueredVillagesByTribe(tribeID int, showInternals bool) ennoblements { filtered := ennoblements{} for _, ennoblement := range e { - if utils.IsPlayerTribeNil(ennoblement.NewOwner) || + if twutil.IsPlayerTribeNil(ennoblement.NewOwner) || ennoblement.NewOwner.Tribe.ID != tribeID || - (!showInternals && !utils.IsPlayerTribeNil(ennoblement.OldOwner) && ennoblement.OldOwner.Tribe.ID == tribeID) { + (!showInternals && !twutil.IsPlayerTribeNil(ennoblement.OldOwner) && ennoblement.OldOwner.Tribe.ID == tribeID) { continue } filtered = append(filtered, ennoblement) diff --git a/cron/handler.go b/cron/handler.go index c728738..0fa43d4 100644 --- a/cron/handler.go +++ b/cron/handler.go @@ -3,24 +3,24 @@ package cron import ( "context" "fmt" + "github.com/Kichiyaki/appmode" + "github.com/tribalwarshelp/shared/tw/twmodel" "time" - "github.com/tribalwarshelp/shared/tw" - "github.com/nicksnyder/go-i18n/v2/i18n" - "github.com/tribalwarshelp/dcbot/message" "github.com/pkg/errors" - "github.com/tribalwarshelp/shared/mode" - shared_models "github.com/tribalwarshelp/shared/models" + + "github.com/tribalwarshelp/dcbot/message" + "github.com/tribalwarshelp/dcbot/tw/twutil" + + "github.com/tribalwarshelp/golang-sdk/sdk" "github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/group" "github.com/tribalwarshelp/dcbot/models" "github.com/tribalwarshelp/dcbot/observation" "github.com/tribalwarshelp/dcbot/server" - "github.com/tribalwarshelp/dcbot/utils" - "github.com/tribalwarshelp/golang-sdk/sdk" ) type handler struct { @@ -42,13 +42,13 @@ func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, e query := "" - for _, server := range servers { - lastEnnoblementAt, ok := h.lastEnnoblementAt[server] + for _, s := range servers { + lastEnnoblementAt, ok := h.lastEnnoblementAt[s] if !ok { lastEnnoblementAt = time.Now().Add(-1 * time.Minute) - h.lastEnnoblementAt[server] = lastEnnoblementAt + h.lastEnnoblementAt[s] = lastEnnoblementAt } - if mode.Get() == mode.DevelopmentMode { + if appmode.Equals(appmode.DevelopmentMode) { lastEnnoblementAt = time.Now().Add(-1 * time.Hour * 2) } lastEnnoblementAtJSON, err := lastEnnoblementAt.MarshalJSON() @@ -62,8 +62,8 @@ func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, e ennobledAt } } - `, server, - server, + `, s, + s, string(lastEnnoblementAtJSON), sdk.EnnoblementInclude{ NewOwner: true, @@ -83,40 +83,40 @@ func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, e return m, errors.Wrap(err, "loadEnnoblements") } - for server, singleServerResp := range resp { + for s, singleServerResp := range resp { if singleServerResp == nil { continue } - m[server] = ennoblements(singleServerResp.Items) - lastEnnoblement := m[server].getLastEnnoblement() + m[s] = singleServerResp.Items + lastEnnoblement := m[s].getLastEnnoblement() if lastEnnoblement != nil { - h.lastEnnoblementAt[server] = lastEnnoblement.EnnobledAt + h.lastEnnoblementAt[s] = lastEnnoblement.EnnobledAt } } return m, nil } -func (h *handler) loadVersions(servers []string) ([]*shared_models.Version, error) { - versionCodes := []shared_models.VersionCode{} - cache := make(map[shared_models.VersionCode]bool) - for _, server := range servers { - languageTag := tw.VersionCodeFromServerKey(server) - if languageTag.IsValid() && !cache[languageTag] { - cache[languageTag] = true - versionCodes = append(versionCodes, languageTag) +func (h *handler) loadVersions(servers []string) ([]*twmodel.Version, error) { + var versionCodes []twmodel.VersionCode + cache := make(map[twmodel.VersionCode]bool) + for _, s := range servers { + versionCode := twmodel.VersionCodeFromServerKey(s) + if versionCode.IsValid() && !cache[versionCode] { + cache[versionCode] = true + versionCodes = append(versionCodes, versionCode) } } if len(versionCodes) == 0 { - return []*shared_models.Version{}, nil + return []*twmodel.Version{}, nil } - versionList, err := h.api.Version.Browse(0, 0, []string{"code ASC"}, &shared_models.VersionFilter{ + versionList, err := h.api.Version.Browse(0, 0, []string{"code ASC"}, &twmodel.VersionFilter{ Code: versionCodes, }) if err != nil { - return nil, errors.Wrap(err, "cannot load versions") + return nil, errors.Wrap(err, "couldn't load versions") } return versionList.Items, nil @@ -130,7 +130,7 @@ func (h *handler) checkEnnoblements() { } log. WithField("servers", servers). - Info("checkEnnoblements: loaded servers") + Info("checkEnnoblements: servers have been loaded") groups, total, err := h.groupRepo.Fetch(context.Background(), nil) if err != nil { @@ -139,7 +139,7 @@ func (h *handler) checkEnnoblements() { } log. WithField("numberOfGroups", total). - Info("checkEnnoblements: loaded groups") + Info("checkEnnoblements: groups have been loaded") versions, err := h.loadVersions(servers) if err != nil { @@ -148,34 +148,34 @@ func (h *handler) checkEnnoblements() { } log. WithField("numberOfVersions", len(versions)). - Info("checkEnnoblements: loaded versions") + Info("checkEnnoblements: versions have been loaded") ennoblementsByServerKey, err := h.loadEnnoblements(servers) if err != nil { log.Errorln("checkEnnoblements:", err) } - log.Info("checkEnnoblements: loaded ennoblements") + log.Info("checkEnnoblements: ennoblements have been loaded") - for _, group := range groups { - if group.ConqueredVillagesChannelID == "" && group.LostVillagesChannelID == "" { + for _, g := range groups { + if g.ConqueredVillagesChannelID == "" && g.LostVillagesChannelID == "" { continue } - localizer := message.NewLocalizer(group.Server.Lang) + localizer := message.NewLocalizer(g.Server.Lang) lostVillagesMsg := &discord.MessageEmbed{} conqueredVillagesMsg := &discord.MessageEmbed{} - for _, observation := range group.Observations { - ennoblements, ok := ennoblementsByServerKey[observation.Server] - version := utils.FindVersionByCode(versions, tw.VersionCodeFromServerKey(observation.Server)) + for _, obs := range g.Observations { + enblmnts, ok := ennoblementsByServerKey[obs.Server] + version := twutil.FindVersionByCode(versions, twmodel.VersionCodeFromServerKey(obs.Server)) if ok && version != nil && version.Host != "" { - if group.LostVillagesChannelID != "" { - for _, ennoblement := range ennoblements.getLostVillagesByTribe(observation.TribeID) { - if !utils.IsPlayerTribeNil(ennoblement.NewOwner) && - group.Observations.Contains(observation.Server, ennoblement.NewOwner.Tribe.ID) { + if g.LostVillagesChannelID != "" { + for _, ennoblement := range enblmnts.getLostVillagesByTribe(obs.TribeID) { + if !twutil.IsPlayerTribeNil(ennoblement.NewOwner) && + g.Observations.Contains(obs.Server, ennoblement.NewOwner.Tribe.ID) { continue } newMsgDataConfig := newMessageConfig{ host: version.Host, - server: observation.Server, + server: obs.Server, ennoblement: ennoblement, t: messageTypeLost, localizer: localizer, @@ -184,18 +184,18 @@ func (h *handler) checkEnnoblements() { } } - if group.ConqueredVillagesChannelID != "" { - for _, ennoblement := range ennoblements.getConqueredVillagesByTribe(observation.TribeID, group.ShowInternals) { - isInTheSameGroup := !utils.IsPlayerTribeNil(ennoblement.OldOwner) && - group.Observations.Contains(observation.Server, ennoblement.OldOwner.Tribe.ID) - if (!group.ShowInternals && isInTheSameGroup) || - (!group.ShowEnnobledBarbarians && isBarbarian(ennoblement.OldOwner)) { + if g.ConqueredVillagesChannelID != "" { + for _, ennoblement := range enblmnts.getConqueredVillagesByTribe(obs.TribeID, g.ShowInternals) { + isInTheSameGroup := !twutil.IsPlayerTribeNil(ennoblement.OldOwner) && + g.Observations.Contains(obs.Server, ennoblement.OldOwner.Tribe.ID) + if (!g.ShowInternals && isInTheSameGroup) || + (!g.ShowEnnobledBarbarians && isBarbarian(ennoblement.OldOwner)) { continue } newMsgDataConfig := newMessageConfig{ host: version.Host, - server: observation.Server, + server: obs.Server, ennoblement: ennoblement, t: messageTypeConquer, localizer: localizer, @@ -207,13 +207,13 @@ func (h *handler) checkEnnoblements() { } timestamp := time.Now().Format(time.RFC3339) - if group.ConqueredVillagesChannelID != "" && !conqueredVillagesMsg.IsEmpty() { + if g.ConqueredVillagesChannelID != "" && !conqueredVillagesMsg.IsEmpty() { title := localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.CronConqueredVillagesTitle, DefaultMessage: message.FallbackMsg(message.CronConqueredVillagesTitle, "Conquered villages"), }) - go h.discord.SendEmbed(group.ConqueredVillagesChannelID, + go h.discord.SendEmbed(g.ConqueredVillagesChannelID, discord. NewEmbed(). SetTitle(title). @@ -223,13 +223,13 @@ func (h *handler) checkEnnoblements() { MessageEmbed) } - if group.LostVillagesChannelID != "" && !lostVillagesMsg.IsEmpty() { + if g.LostVillagesChannelID != "" && !lostVillagesMsg.IsEmpty() { title := localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.CronLostVillagesTitle, DefaultMessage: message.FallbackMsg(message.CronLostVillagesTitle, "Lost villages"), }) - go h.discord.SendEmbed(group.LostVillagesChannelID, + go h.discord.SendEmbed(g.LostVillagesChannelID, discord. NewEmbed(). SetTitle(title). @@ -251,10 +251,10 @@ func (h *handler) checkBotServers() { WithField("numberOfServers", total). Info("checkBotServers: loaded servers") - idsToDelete := []string{} - for _, server := range servers { - if isGuildMember, _ := h.discord.IsGuildMember(server.ID); !isGuildMember { - idsToDelete = append(idsToDelete, server.ID) + var idsToDelete []string + for _, s := range servers { + if isGuildMember, _ := h.discord.IsGuildMember(s.ID); !isGuildMember { + idsToDelete = append(idsToDelete, s.ID) } } @@ -267,36 +267,36 @@ func (h *handler) checkBotServers() { } else { log. WithField("numberOfDeletedServers", len(deleted)). - Info("checkBotServers: deleted servers") + Info("checkBotServers: some of the servers have been deleted") } } } -func (h *handler) deleteClosedTribalWarsServers() { +func (h *handler) deleteClosedTWServers() { servers, err := h.observationRepo.FetchServers(context.Background()) if err != nil { - log.Error("deleteClosedTribalWarsServers: " + err.Error()) + log.Error("deleteClosedTWServers: " + err.Error()) return } log. WithField("servers", servers). - Info("deleteClosedTribalWarsServers: loaded servers") + Info("deleteClosedTWServers: loaded servers") - list, err := h.api.Server.Browse(0, 0, []string{"key ASC"}, &shared_models.ServerFilter{ + list, err := h.api.Server.Browse(0, 0, []string{"key ASC"}, &twmodel.ServerFilter{ Key: servers, - Status: []shared_models.ServerStatus{shared_models.ServerStatusClosed}, + Status: []twmodel.ServerStatus{twmodel.ServerStatusClosed}, }, nil) if err != nil { - log.Errorln("deleteClosedTribalWarsServers: " + err.Error()) + log.Errorln("deleteClosedTWServers: " + err.Error()) return } if list == nil || list.Items == nil { return } - keys := []string{} - for _, server := range list.Items { - keys = append(keys, server.Key) + var keys []string + for _, s := range list.Items { + keys = append(keys, s.Key) } if len(keys) > 0 { @@ -304,11 +304,11 @@ func (h *handler) deleteClosedTribalWarsServers() { Server: keys, }) if err != nil { - log.Errorln("deleteClosedTribalWarsServers: " + err.Error()) + log.Errorln("deleteClosedTWServers: " + err.Error()) } else { log. WithField("numberOfDeletedObservations", len(deleted)). - Infof("deleteClosedTribalWarsServers: deleted observations") + Infof("deleteClosedTWServers: some of the observations have been deleted") } } } diff --git a/cron/helpers.go b/cron/helpers.go index ed1a1b3..a608dbb 100644 --- a/cron/helpers.go +++ b/cron/helpers.go @@ -1,10 +1,29 @@ package cron import ( - "github.com/tribalwarshelp/dcbot/utils" - shared_models "github.com/tribalwarshelp/shared/models" + "github.com/sirupsen/logrus" + "github.com/tribalwarshelp/shared/tw/twmodel" + "time" + + "github.com/tribalwarshelp/dcbot/tw/twutil" ) -func isBarbarian(p *shared_models.Player) bool { - return utils.IsPlayerNil(p) || p.ID == 0 +func isBarbarian(p *twmodel.Player) bool { + return twutil.IsPlayerNil(p) || p.ID == 0 +} + +func trackDuration(log *logrus.Entry, fn func(), fnName string) func() { + return func() { + now := time.Now() + log := log.WithField("fnName", fnName) + log.Infof("'%s' has been called", fnName) + + fn() + + duration := time.Since(now) + log. + WithField("duration", duration.Nanoseconds()). + WithField("durationPretty", duration.String()). + Infof("'%s' finished executing", fnName) + } } diff --git a/cron/message.go b/cron/message.go index f35869a..1ec3b6d 100644 --- a/cron/message.go +++ b/cron/message.go @@ -2,11 +2,12 @@ package cron import ( "github.com/nicksnyder/go-i18n/v2/i18n" + "github.com/tribalwarshelp/shared/tw/twmodel" + "github.com/tribalwarshelp/shared/tw/twurlbuilder" + "github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/message" - "github.com/tribalwarshelp/dcbot/utils" - shared_models "github.com/tribalwarshelp/shared/models" - "github.com/tribalwarshelp/shared/tw" + "github.com/tribalwarshelp/dcbot/tw/twutil" ) type messageType string @@ -38,7 +39,7 @@ type newMessageConfig struct { t messageType host string server string - ennoblement *shared_models.Ennoblement + ennoblement *twmodel.Ennoblement localizer *i18n.Localizer } @@ -53,25 +54,25 @@ func newMessage(cfg newMessageConfig) checkEnnoblementsMsg { newOwnerTribeTag: "-", localizer: cfg.localizer, } - if !utils.IsVillageNil(cfg.ennoblement.Village) { + if !twutil.IsVillageNil(cfg.ennoblement.Village) { data.village = cfg.ennoblement.Village.FullName() - data.villageURL = tw.BuildVillageURL(cfg.server, cfg.host, cfg.ennoblement.Village.ID) + data.villageURL = twurlbuilder.BuildVillageURL(cfg.server, cfg.host, cfg.ennoblement.Village.ID) } - if !utils.IsPlayerNil(cfg.ennoblement.OldOwner) { + if !twutil.IsPlayerNil(cfg.ennoblement.OldOwner) { data.oldOwnerName = cfg.ennoblement.OldOwner.Name - data.oldOwnerURL = tw.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.ID) + data.oldOwnerURL = twurlbuilder.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.ID) } - if !utils.IsPlayerTribeNil(cfg.ennoblement.OldOwner) { + if !twutil.IsPlayerTribeNil(cfg.ennoblement.OldOwner) { data.oldOwnerTribeTag = cfg.ennoblement.OldOwner.Tribe.Tag - data.oldOwnerTribeURL = tw.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.Tribe.ID) + data.oldOwnerTribeURL = twurlbuilder.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.Tribe.ID) } - if !utils.IsPlayerNil(cfg.ennoblement.NewOwner) { + if !twutil.IsPlayerNil(cfg.ennoblement.NewOwner) { data.newOwnerName = cfg.ennoblement.NewOwner.Name - data.newOwnerURL = tw.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.ID) + data.newOwnerURL = twurlbuilder.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.ID) } - if !utils.IsPlayerTribeNil(cfg.ennoblement.NewOwner) { + if !twutil.IsPlayerTribeNil(cfg.ennoblement.NewOwner) { data.newOwnerTribeTag = cfg.ennoblement.NewOwner.Tribe.Tag - data.newOwnerTribeURL = tw.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.Tribe.ID) + data.newOwnerTribeURL = twurlbuilder.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.Tribe.ID) } return data diff --git a/dev.sh b/dev.sh deleted file mode 100755 index 16b66ca..0000000 --- a/dev.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -export MODE=development -go run main.go \ No newline at end of file diff --git a/discord/coords_translation.go b/discord/coords_translation.go index 1075604..7c99030 100644 --- a/discord/coords_translation.go +++ b/discord/coords_translation.go @@ -2,15 +2,16 @@ package discord import ( "context" + "github.com/tribalwarshelp/shared/tw/twmodel" + "github.com/tribalwarshelp/shared/tw/twurlbuilder" "regexp" "github.com/bwmarrin/discordgo" "github.com/nicksnyder/go-i18n/v2/i18n" - "github.com/tribalwarshelp/dcbot/message" - "github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/golang-sdk/sdk" - "github.com/tribalwarshelp/shared/models" - "github.com/tribalwarshelp/shared/tw" + + "github.com/tribalwarshelp/dcbot/message" + "github.com/tribalwarshelp/dcbot/tw/twutil" ) const ( @@ -86,7 +87,7 @@ func (s *Session) translateCoords(ctx *commandCtx, m *discordgo.MessageCreate) { coords := coordsRegex.FindAllString(m.Content, -1) coordsLen := len(coords) if coordsLen > 0 { - version, err := s.cfg.API.Version.Read(tw.VersionCodeFromServerKey(ctx.server.CoordsTranslation)) + version, err := s.cfg.API.Version.Read(twmodel.VersionCodeFromServerKey(ctx.server.CoordsTranslation)) if err != nil || version == nil { return } @@ -97,7 +98,7 @@ func (s *Session) translateCoords(ctx *commandCtx, m *discordgo.MessageCreate) { 0, 0, []string{}, - &models.VillageFilter{ + &twmodel.VillageFilter{ XY: coords, }, &sdk.VillageInclude{ @@ -105,25 +106,26 @@ func (s *Session) translateCoords(ctx *commandCtx, m *discordgo.MessageCreate) { PlayerInclude: sdk.PlayerInclude{ Tribe: true, }, - }) - if err != nil || list == nil || list.Items == nil || len(list.Items) <= 0 { + }, + ) + if err != nil || list == nil || list.Items == nil { return } msg := &MessageEmbed{} for _, village := range list.Items { - villageURL := tw.BuildVillageURL(ctx.server.CoordsTranslation, version.Host, village.ID) + villageURL := twurlbuilder.BuildVillageURL(ctx.server.CoordsTranslation, version.Host, village.ID) playerName := "-" playerURL := "" - if !utils.IsPlayerNil(village.Player) { + if !twutil.IsPlayerNil(village.Player) { playerName = village.Player.Name - playerURL = tw.BuildPlayerURL(ctx.server.CoordsTranslation, version.Host, village.Player.ID) + playerURL = twurlbuilder.BuildPlayerURL(ctx.server.CoordsTranslation, version.Host, village.Player.ID) } tribeName := "-" tribeURL := "" - if !utils.IsPlayerTribeNil(village.Player) { + if !twutil.IsPlayerTribeNil(village.Player) { tribeName = village.Player.Tribe.Name - tribeURL = tw.BuildTribeURL(ctx.server.CoordsTranslation, version.Host, village.Player.Tribe.ID) + tribeURL = twurlbuilder.BuildTribeURL(ctx.server.CoordsTranslation, version.Host, village.Player.Tribe.ID) } msg.Append(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ diff --git a/discord/discord.go b/discord/discord.go index ec90444..2c1510b 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -2,17 +2,19 @@ package discord import ( "context" - "fmt" + "github.com/pkg/errors" "strings" "github.com/sirupsen/logrus" + "github.com/tribalwarshelp/dcbot/message" + "github.com/tribalwarshelp/golang-sdk/sdk" + "github.com/tribalwarshelp/dcbot/group" "github.com/tribalwarshelp/dcbot/models" "github.com/tribalwarshelp/dcbot/observation" "github.com/tribalwarshelp/dcbot/server" - "github.com/tribalwarshelp/golang-sdk/sdk" "github.com/bwmarrin/discordgo" ) @@ -145,7 +147,7 @@ func (s *Session) init() error { err := s.dg.Open() if err != nil { - return fmt.Errorf("error opening ws connection: %s", err.Error()) + return errors.Wrap(err, "error opening ws connection") } if err := s.UpdateStatus(s.cfg.Status); err != nil { @@ -174,7 +176,7 @@ func (s *Session) SendEmbed(channelID string, message *discordgo.MessageEmbed) e baseNumberOfCharacters += len(message.Footer.Text) } - splittedFields := [][]*discordgo.MessageEmbedField{} + var splittedFields [][]*discordgo.MessageEmbedField characters := baseNumberOfCharacters fromIndex := 0 fieldsLen := len(fields) @@ -229,23 +231,23 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre return } - splitted := strings.Split(m.Content, " ") - args := splitted[1:] - server := &models.Server{ + parts := strings.Split(m.Content, " ") + args := parts[1:] + svr := &models.Server{ ID: m.GuildID, Lang: message.GetDefaultLanguage().String(), } - if server.ID != "" { - if err := s.cfg.ServerRepository.Store(context.Background(), server); err != nil { + if svr.ID != "" { + if err := s.cfg.ServerRepository.Store(context.Background(), svr); err != nil { return } } ctx := &commandCtx{ - server: server, - localizer: message.NewLocalizer(server.Lang), + server: svr, + localizer: message.NewLocalizer(svr.Lang), } - cmd := Command(splitted[0]) + cmd := Command(parts[0]) h := s.handlers.find(cmd) if h != nil { if h.requireAdmPermissions { @@ -259,14 +261,14 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre } log. WithFields(logrus.Fields{ - "serverID": server.ID, - "lang": server.Lang, + "serverID": svr.ID, + "lang": svr.Lang, "command": cmd, "args": args, "authorID": m.Author.ID, "authorUsername": m.Author.Username, }). - Info("handleNewMessage: Executing command") + Info("handleNewMessage: Executing command...") h.fn(ctx, m, args...) return } diff --git a/discord/observations.go b/discord/observations.go index 42a383f..6fe24ea 100644 --- a/discord/observations.go +++ b/discord/observations.go @@ -3,18 +3,19 @@ package discord import ( "context" "fmt" + "github.com/tribalwarshelp/shared/tw/twmodel" + "github.com/tribalwarshelp/shared/tw/twurlbuilder" "strconv" "strings" "github.com/tribalwarshelp/golang-sdk/sdk" - "github.com/tribalwarshelp/shared/tw" "github.com/bwmarrin/discordgo" "github.com/nicksnyder/go-i18n/v2/i18n" + "github.com/tribalwarshelp/dcbot/message" "github.com/tribalwarshelp/dcbot/models" - "github.com/tribalwarshelp/dcbot/utils" - shared_models "github.com/tribalwarshelp/shared/models" + "github.com/tribalwarshelp/dcbot/tw/twutil" ) const ( @@ -180,7 +181,7 @@ func (s *Session) handleConqueredVillagesCommand(ctx *commandCtx, m *discordgo.M m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpConqueredVillages, DefaultMessage: message.FallbackMsg(message.HelpConqueredVillages, - "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about conquered village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications."), + "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about conquered village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications."), TemplateData: map[string]interface{}{ "Command": ConqueredVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), @@ -226,7 +227,7 @@ func (s *Session) handleConqueredVillagesCommand(ctx *commandCtx, m *discordgo.M ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.ConqueredVillagesSuccess, DefaultMessage: message.FallbackMsg(message.ConqueredVillagesSuccess, - "{{.Mention}} Channel changed successfully."), + "{{.Mention}} The channel has been successfully set."), TemplateData: map[string]interface{}{ "Mention": m.Author.Mention(), }, @@ -302,7 +303,7 @@ func (s *Session) handleLostVillagesCommand(ctx *commandCtx, m *discordgo.Messag m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpLostVillages, DefaultMessage: message.FallbackMsg(message.HelpLostVillages, - "**{{.Command}}** [group id from {{.GroupsCommand}}] changes the channel on which notifications about lost village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications."), + "**{{.Command}}** [group id from {{.GroupsCommand}}] sets the channel on which notifications about lost village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications."), TemplateData: map[string]interface{}{ "Command": LostVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), @@ -349,7 +350,7 @@ func (s *Session) handleLostVillagesCommand(ctx *commandCtx, m *discordgo.Messag ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.LostVillagesSuccess, DefaultMessage: message.FallbackMsg(message.LostVillagesSuccess, - "{{.Mention}} Channel changed successfully."), + "{{.Mention}} The channel has been successfully set."), TemplateData: map[string]interface{}{ "Mention": m.Author.Mention(), }, @@ -476,7 +477,7 @@ func (s *Session) handleObserveCommand(ctx *commandCtx, m *discordgo.MessageCrea })) return } - if server.Status == shared_models.ServerStatusClosed { + if server.Status == twmodel.ServerStatusClosed { s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.ObserveServerIsClosed, @@ -488,12 +489,12 @@ func (s *Session) handleObserveCommand(ctx *commandCtx, m *discordgo.MessageCrea return } - var tribe *shared_models.Tribe + var tribe *twmodel.Tribe if tribeID > 0 { tribe, err = s.cfg.API.Tribe.Read(server.Key, tribeID) } else { list := &sdk.TribeList{} - list, err = s.cfg.API.Tribe.Browse(server.Key, 1, 0, []string{}, &shared_models.TribeFilter{ + list, err = s.cfg.API.Tribe.Browse(server.Key, 1, 0, []string{}, &twmodel.TribeFilter{ Tag: []string{tribeTag}, }) if list != nil && list.Items != nil && len(list.Items) > 0 { @@ -548,7 +549,7 @@ func (s *Session) handleObserveCommand(ctx *commandCtx, m *discordgo.MessageCrea s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.ObserveSuccess, - DefaultMessage: message.FallbackMsg(message.ObserveSuccess, "{{.Mention}} Added."), + DefaultMessage: message.FallbackMsg(message.ObserveSuccess, "{{.Mention}} The tribe has been added to the group."), TemplateData: map[string]interface{}{ "Mention": m.Author.Mention(), }, @@ -619,7 +620,7 @@ func (s *Session) handleDeleteObservationCommand(ctx *commandCtx, m *discordgo.M s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.DeleteObservationSuccess, - DefaultMessage: message.FallbackMsg(message.DeleteObservationSuccess, "{{.Mention}} Deleted."), + DefaultMessage: message.FallbackMsg(message.DeleteObservationSuccess, "{{.Mention}} The tribe has been removed from the group."), TemplateData: map[string]interface{}{ "Mention": m.Author.Mention(), }, @@ -687,10 +688,10 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag } tribeIDsByServer := make(map[string][]int) - versionCodes := []shared_models.VersionCode{} + versionCodes := []twmodel.VersionCode{} for _, observation := range observations { tribeIDsByServer[observation.Server] = append(tribeIDsByServer[observation.Server], observation.TribeID) - currentCode := tw.VersionCodeFromServerKey(observation.Server) + currentCode := twmodel.VersionCodeFromServerKey(observation.Server) unique := true for _, code := range versionCodes { if code == currentCode { @@ -703,7 +704,7 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag } } for server, tribeIDs := range tribeIDsByServer { - list, err := s.cfg.API.Tribe.Browse(server, 0, 0, []string{}, &shared_models.TribeFilter{ + list, err := s.cfg.API.Tribe.Browse(server, 0, 0, []string{}, &twmodel.TribeFilter{ ID: tribeIDs, }) if err != nil { @@ -727,7 +728,7 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag } } } - versionList, err := s.cfg.API.Version.Browse(0, 0, []string{}, &shared_models.VersionFilter{ + versionList, err := s.cfg.API.Version.Browse(0, 0, []string{}, &twmodel.VersionFilter{ Code: versionCodes, }) @@ -740,10 +741,10 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag if observation.Tribe != nil { tag = observation.Tribe.Tag } - version := utils.FindVersionByCode(versionList.Items, tw.VersionCodeFromServerKey(observation.Server)) + version := twutil.FindVersionByCode(versionList.Items, twmodel.VersionCodeFromServerKey(observation.Server)) tribeURL := "" if version != nil { - tribeURL = tw.BuildTribeURL(observation.Server, version.Host, observation.TribeID) + tribeURL = twurlbuilder.BuildTribeURL(observation.Server, version.Host, observation.TribeID) } msg.Append(fmt.Sprintf("**%d** | %d - %s - %s\n", i+1, observation.ID, observation.Server, @@ -969,7 +970,7 @@ func (s *Session) handleShowInternalsCommand(ctx *commandCtx, m *discordgo.Messa ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.ShowInternalsSuccess2, DefaultMessage: message.FallbackMsg(message.ShowInternalsSuccess2, - "{{.Mention}} Enabled notifications about internals."), + "{{.Mention}} Notifications about internals have been enabled."), TemplateData: map[string]interface{}{ "Mention": m.Author.Mention(), }, diff --git a/discord/public_commands.go b/discord/public_commands.go index 822cd05..2f3b6ea 100644 --- a/discord/public_commands.go +++ b/discord/public_commands.go @@ -2,6 +2,8 @@ package discord import ( "fmt" + "github.com/tribalwarshelp/shared/tw/twmodel" + "github.com/tribalwarshelp/shared/tw/twurlbuilder" "math" "strconv" "strings" @@ -9,8 +11,6 @@ import ( "github.com/tribalwarshelp/dcbot/message" "github.com/nicksnyder/go-i18n/v2/i18n" - shared_models "github.com/tribalwarshelp/shared/models" - "github.com/tribalwarshelp/shared/tw" "github.com/bwmarrin/discordgo" "github.com/dustin/go-humanize" @@ -163,7 +163,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpConqueredVillages, DefaultMessage: message.FallbackMsg(message.HelpConqueredVillages, - "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about conquered village will show. IMPORTANT! Call this command on the channel you want to display these notifications."), + "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about conquered village will be displayed. IMPORTANT! Call this command on the channel you want to display these notifications."), TemplateData: map[string]interface{}{ "Command": ConqueredVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), @@ -191,7 +191,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpLostVillages, DefaultMessage: message.FallbackMsg(message.HelpLostVillages, - "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about lost village will show. IMPORTANT! Call this command on the channel you want to display these notifications."), + "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about lost village will be displayed. IMPORTANT! Call this command on the channel you want to display these notifications."), TemplateData: map[string]interface{}{ "Command": LostVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), @@ -200,7 +200,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpDisableLostVillages, DefaultMessage: message.FallbackMsg(message.HelpDisableLostVillages, - "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about lost village will show. IMPORTANT! Call this command on the channel you want to display these notifications."), + "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about lost village will be displayed. IMPORTANT! Call this command on the channel you want to display these notifications."), TemplateData: map[string]interface{}{ "Command": DisableLostVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), @@ -255,7 +255,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate, SetURL("https://dcbot.tribalwarshelp.com/"). SetDescription(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpDescription, - DefaultMessage: message.FallbackMsg(message.HelpDescription, "Commands offered by bot"), + DefaultMessage: message.FallbackMsg(message.HelpDescription, "Command list"), })). AddField(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ MessageID: message.HelpForAllUsers, @@ -291,8 +291,8 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate })) return } - ids := []int{} - tags := []string{} + var ids []int + var tags []string for _, arg := range args[3:argsLength] { trimmed := strings.TrimSpace(arg) if trimmed == "" { @@ -319,10 +319,10 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate exists := true limit := 10 offset := (page - 1) * limit - filter := &shared_models.PlayerFilter{ + filter := &twmodel.PlayerFilter{ Exists: &exists, - TribeFilter: &shared_models.TribeFilter{ - Or: &shared_models.TribeFilterOr{ + TribeFilter: &twmodel.TribeFilter{ + Or: &twmodel.TribeFilterOr{ ID: ids, Tag: tags, }, @@ -414,7 +414,7 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate return } - code := tw.VersionCodeFromServerKey(server) + code := twmodel.VersionCodeFromServerKey(server) version, err := s.cfg.API.Version.Read(code) if err != nil || version == nil { s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ @@ -458,7 +458,7 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate tribeURL := "-" if player.Tribe != nil { tribeTag = player.Tribe.Tag - tribeURL = tw.BuildTribeURL(server, version.Host, player.Tribe.ID) + tribeURL = twurlbuilder.BuildTribeURL(server, version.Host, player.Tribe.ID) } msg.Append(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ @@ -468,7 +468,7 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate TemplateData: map[string]interface{}{ "Index": offset + i + 1, "PlayerName": player.Name, - "PlayerURL": tw.BuildPlayerURL(server, version.Host, player.ID), + "PlayerURL": twurlbuilder.BuildPlayerURL(server, version.Host, player.ID), "TribeTag": tribeTag, "TribeURL": tribeURL, "Rank": rank, diff --git a/go.mod b/go.mod index 3ee782c..e48407a 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,10 @@ module github.com/tribalwarshelp/dcbot go 1.16 require ( + github.com/Kichiyaki/appmode v0.0.0-20210502105643-0a26207c548d github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9 + github.com/Kichiyaki/gopgutil/v10 v10.0.0-20210505093434-655fa2df248f + github.com/Kichiyaki/goutil v0.0.0-20210504132659-3d843a787db7 github.com/bwmarrin/discordgo v0.22.0 github.com/dustin/go-humanize v1.0.0 github.com/go-pg/pg/v10 v10.9.1 @@ -12,7 +15,7 @@ require ( github.com/pkg/errors v0.9.1 github.com/robfig/cron/v3 v3.0.1 github.com/sirupsen/logrus v1.8.1 - github.com/tribalwarshelp/golang-sdk v0.0.0-20210423190639-622eeb3ee870 - github.com/tribalwarshelp/shared v0.0.0-20210423190057-03d8445d35dc + github.com/tribalwarshelp/golang-sdk v0.0.0-20210505172651-7dc458534a8c + github.com/tribalwarshelp/shared v0.0.0-20210505172413-bf85190fd66d golang.org/x/text v0.3.3 ) diff --git a/go.sum b/go.sum index 038791e..45e7b3b 100644 --- a/go.sum +++ b/go.sum @@ -2,10 +2,16 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT github.com/BurntSushi/toml v0.3.0/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210423175217-c83fa01c60d7 h1:7IdSzhdupqm4AC3UDH9b5gdCDE2SlX6qkVC0zwqAuLA= -github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210423175217-c83fa01c60d7/go.mod h1:ADHVWnGlWcRn1aGthuh7I1Lrn6zzsjkVJju151dXyDw= +github.com/Kichiyaki/appmode v0.0.0-20210502105643-0a26207c548d h1:ApX13STtfJc2YPH5D2JnBa6+4AM2vt7a81so/MPr/bA= +github.com/Kichiyaki/appmode v0.0.0-20210502105643-0a26207c548d/go.mod h1:41p1KTy/fiVocPnJR2h/iXh2NvWWVBdNoZrN8TWVXUI= github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9 h1:S/08K0AD4bXYeSPJKei8ZbumDy1JNARZsgYbNZgr9Tk= github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9/go.mod h1:ADHVWnGlWcRn1aGthuh7I1Lrn6zzsjkVJju151dXyDw= +github.com/Kichiyaki/go-php-serialize v0.0.0-20200601110855-47b6982acf83/go.mod h1:+iGkf5HfOVeRVd9K7qQDucIl+/Kt3MyenMa90b/O/c4= +github.com/Kichiyaki/gopgutil/v10 v10.0.0-20210505093434-655fa2df248f h1:/kJmv8B59cMHdTmsko0RyAOeRC9WpsQPDmLtRXOAU6c= +github.com/Kichiyaki/gopgutil/v10 v10.0.0-20210505093434-655fa2df248f/go.mod h1:MSAEhr8oeK+Rhjhqyl31/8/AI88thYky80OyD8mheDA= +github.com/Kichiyaki/goutil v0.0.0-20210502095630-318d17091eab/go.mod h1:+HhI932Xb0xrCodNcCv5GPiCjLYhDxWhCtlEqMIJhB4= +github.com/Kichiyaki/goutil v0.0.0-20210504132659-3d843a787db7 h1:OU3ZA5H8fHTzaYIw9UBfH3gtWRL0XmnczlhH3E2PjV4= +github.com/Kichiyaki/goutil v0.0.0-20210504132659-3d843a787db7/go.mod h1:+HhI932Xb0xrCodNcCv5GPiCjLYhDxWhCtlEqMIJhB4= github.com/Kichiyaki/gqlgen-client v0.0.0-20200604145848-274796c104f4 h1:QiOarkkKHdFYI+0m6F1H3rRzP6DqJsKJVLirGXEHGSU= github.com/Kichiyaki/gqlgen-client v0.0.0-20200604145848-274796c104f4/go.mod h1:weCVl47ZANyeX60sdsSl0bWHf8HWXyVFmlGHHCR/i5M= github.com/bwmarrin/discordgo v0.22.0 h1:uBxY1HmlVCsW1IuaPjpCGT6A2DBwRn0nvOguQIxDdFM= @@ -78,7 +84,6 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -90,10 +95,10 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs= -github.com/tribalwarshelp/golang-sdk v0.0.0-20210423190639-622eeb3ee870 h1:OHkmBk+KoVL/GEJqi9qpxuga6C0NOC8faam1wE74YWA= -github.com/tribalwarshelp/golang-sdk v0.0.0-20210423190639-622eeb3ee870/go.mod h1:OJSOBFIytm2cxZZh4B0x2ucJWQ0vlVu9T61hDrnwJaw= -github.com/tribalwarshelp/shared v0.0.0-20210423190057-03d8445d35dc h1:giWPsD/6WTOrQl9KT5AXrrf3KLkHSGuNpWa2CyyaM6w= -github.com/tribalwarshelp/shared v0.0.0-20210423190057-03d8445d35dc/go.mod h1:CDQvesBYmSyGDl5X37xfa+ub55ZbikrHDuIZ4AcfM8I= +github.com/tribalwarshelp/golang-sdk v0.0.0-20210505172651-7dc458534a8c h1:Ip4C8G6zjdHnsHeyuajb5BZeRrls/Ym14Vww8e9jGLM= +github.com/tribalwarshelp/golang-sdk v0.0.0-20210505172651-7dc458534a8c/go.mod h1:0VNYCWHFE5Szvd/b5RpnhtHdvYwR/6XfB/iFjgPTAtY= +github.com/tribalwarshelp/shared v0.0.0-20210505172413-bf85190fd66d h1:aMlYOsJbYwKqHx7wAt526eIutV1Q5EnYK6b7lOzvPmk= +github.com/tribalwarshelp/shared v0.0.0-20210505172413-bf85190fd66d/go.mod h1:GBnSKQrxL8Nmi3MViIzZVbyP9+ugd28gWArsSvw1iVU= github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ= github.com/vmihailenco/msgpack/v5 v5.3.0/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= diff --git a/group/repository/group_pg_repo.go b/group/repository/group_pg_repo.go index ae9cc22..adf4f14 100644 --- a/group/repository/group_pg_repo.go +++ b/group/repository/group_pg_repo.go @@ -20,7 +20,7 @@ func NewPgRepo(db *pg.DB) (group.Repository, error) { IfNotExists: true, FKConstraints: true, }); err != nil { - return nil, errors.Wrap(err, "cannot create 'groups' table") + return nil, errors.Wrap(err, "couldn't create the 'groups' table") } return &pgRepo{db}, nil } @@ -52,11 +52,11 @@ func (repo *pgRepo) Update(ctx context.Context, group *models.Group) error { } func (repo *pgRepo) GetByID(ctx context.Context, id int) (*models.Group, error) { - group := &models.Group{ + g := &models.Group{ ID: id, } if err := repo. - Model(group). + Model(g). WherePK(). Returning("*"). Relation("Observations"). @@ -64,12 +64,12 @@ func (repo *pgRepo) GetByID(ctx context.Context, id int) (*models.Group, error) Select(); err != nil { return nil, err } - return group, nil + return g, nil } func (repo *pgRepo) Fetch(ctx context.Context, f *models.GroupFilter) ([]*models.Group, int, error) { var err error - data := []*models.Group{} + var data []*models.Group query := repo.Model(&data).Relation("Server").Relation("Observations").Context(ctx) if f != nil { @@ -88,7 +88,7 @@ func (repo *pgRepo) Fetch(ctx context.Context, f *models.GroupFilter) ([]*models } func (repo *pgRepo) Delete(ctx context.Context, f *models.GroupFilter) ([]*models.Group, error) { - data := []*models.Group{} + var data []*models.Group query := repo.Model(&data).Context(ctx) if f != nil { diff --git a/main.go b/main.go index a8fda6c..bf34a61 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,8 @@ package main import ( - "log" + "github.com/Kichiyaki/appmode" + "github.com/Kichiyaki/goutil/envutil" "os" "os/signal" "path" @@ -16,13 +17,11 @@ import ( _cron "github.com/tribalwarshelp/dcbot/cron" "github.com/tribalwarshelp/dcbot/discord" - group_repository "github.com/tribalwarshelp/dcbot/group/repository" - observation_repository "github.com/tribalwarshelp/dcbot/observation/repository" - server_repository "github.com/tribalwarshelp/dcbot/server/repository" + grouprepository "github.com/tribalwarshelp/dcbot/group/repository" + observationrepository "github.com/tribalwarshelp/dcbot/observation/repository" + serverepository "github.com/tribalwarshelp/dcbot/server/repository" - "github.com/tribalwarshelp/shared/mode" - - gopglogrusquerylogger "github.com/Kichiyaki/go-pg-logrus-query-logger/v10" + "github.com/Kichiyaki/go-pg-logrus-query-logger/v10" "github.com/go-pg/pg/v10" "github.com/joho/godotenv" "github.com/robfig/cron/v3" @@ -37,7 +36,7 @@ var status = "tribalwarshelp.com | " + discord.HelpCommand.WithPrefix(commandPre func init() { os.Setenv("TZ", "UTC") - if mode.Get() == mode.DevelopmentMode { + if appmode.Equals(appmode.DevelopmentMode) { godotenv.Load(".env.local") } @@ -51,17 +50,14 @@ func main() { } dirWithMessages := path.Join(dir, "message", "translations") if err := message.LoadMessages(dirWithMessages); err != nil { - logrus.Fatal(err) + logrus.WithField("dir", dirWithMessages).Fatal(err) } - logrus.WithField("dir", dirWithMessages). - WithField("languages", message.LanguageTags()). - Info("Loaded messages") db := pg.Connect(&pg.Options{ - User: os.Getenv("DB_USER"), - Password: os.Getenv("DB_PASSWORD"), - Database: os.Getenv("DB_NAME"), - Addr: os.Getenv("DB_HOST") + ":" + os.Getenv("DB_PORT"), + User: envutil.GetenvString("DB_USER"), + Password: envutil.GetenvString("DB_PASSWORD"), + Database: envutil.GetenvString("DB_NAME"), + Addr: envutil.GetenvString("DB_HOST") + ":" + os.Getenv("DB_PORT"), }) defer func() { if err := db.Close(); err != nil { @@ -75,23 +71,23 @@ func main() { }) } - serverRepo, err := server_repository.NewPgRepo(db) + serverRepo, err := serverepository.NewPgRepo(db) if err != nil { logrus.Fatal(err) } - groupRepo, err := group_repository.NewPgRepo(db) + groupRepo, err := grouprepository.NewPgRepo(db) if err != nil { logrus.Fatal(err) } - observationRepo, err := observation_repository.NewPgRepo(db) + observationRepo, err := observationrepository.NewPgRepo(db) if err != nil { logrus.Fatal(err) } - api := sdk.New(os.Getenv("API_URL")) + api := sdk.New(envutil.GetenvString("API_URL")) sess, err := discord.New(discord.SessionConfig{ - Token: os.Getenv("BOT_TOKEN"), + Token: envutil.GetenvString("BOT_TOKEN"), CommandPrefix: commandPrefix, Status: status, ObservationRepository: observationRepo, @@ -100,18 +96,23 @@ func main() { API: api, }) if err != nil { - logrus.Fatal(err) + logrus. + WithFields(logrus.Fields{ + "api": envutil.GetenvString("API_URL"), + "commandPrefix": commandPrefix, + "status": status, + }). + Fatal(err) } defer sess.Close() - logrus.WithFields(logrus.Fields{ - "api": os.Getenv("API_URL"), - "commandPrefix": commandPrefix, - "status": status, - }).Info("The Discord session has been initialized") - c := cron.New(cron.WithChain( - cron.SkipIfStillRunning(cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))), - )) + c := cron.New( + cron.WithChain( + cron.SkipIfStillRunning( + cron.PrintfLogger(logrus.StandardLogger()), + ), + ), + ) _cron.Attach(c, _cron.Config{ ServerRepo: serverRepo, ObservationRepo: observationRepo, @@ -122,24 +123,23 @@ func main() { }) c.Start() defer c.Stop() - logrus.Info("Started the cron scheduler") - logrus.Info("Bot is running!") + logrus.Info("The bot is up and running!") channel := make(chan os.Signal, 1) signal.Notify(channel, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGINT) <-channel - logrus.Info("shutting down") + logrus.Info("shutting down...") } func setupLogger() { - if mode.Get() == mode.DevelopmentMode { + if appmode.Equals(appmode.DevelopmentMode) { logrus.SetLevel(logrus.DebugLevel) } timestampFormat := "2006-01-02 15:04:05" - if mode.Get() == mode.ProductionMode { + if appmode.Equals(appmode.ProductionMode) { customFormatter := new(logrus.JSONFormatter) customFormatter.TimestampFormat = timestampFormat logrus.SetFormatter(customFormatter) diff --git a/message/translations/active.en.json b/message/translations/active.en.json index 1700518..e6fb578 100644 --- a/message/translations/active.en.json +++ b/message/translations/active.en.json @@ -1,6 +1,6 @@ { "help.title": "Help", - "help.description": "Commands offered by the bot.", + "help.description": "Command list", "help.footer": "", "help.forAllUsers": "For everyone", "help.forAdmins": "For admins", @@ -17,9 +17,9 @@ "help.observe": "**{{.Command}}** [group id from {{.GroupsCommand}}] [server] [tribe id or tribe tag] - adds a tribe to the observation group.", "help.observations": "**{{.Command}}** [group id from {{.GroupsCommand}}] - shows a list of monitored tribes added to this group.", "help.deleteobservation": "**{{.Command}}** [group id from {{.GroupsCommand}}] [id from {{.ObservationsCommand}}] - removes a tribe from the observation group.", - "help.conqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about conquered village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications.", + "help.conqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about conquered village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications.", "help.disableconqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disables notifications about conquered villages.", - "help.lostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about lost village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications.", + "help.lostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about lost village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications.", "help.disablelostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disables notifications about lost villages.", "help.changelanguage": "**{{.Command}}** [{{.Languages}}] - changes language.", "help.showinternals": "**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about in-group/in-tribe conquering.", @@ -49,7 +49,7 @@ "conqueredVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "conqueredVillages.groupNotFound": "{{.Mention}} Group not found.", - "conqueredVillages.success": "{{.Mention}} Channel changed successfully.", + "conqueredVillages.success": "{{.Mention}} The channel has been successfully set.", "disableConqueredVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "disableConqueredVillages.groupNotFound": "{{.Mention}} Group not found.", @@ -57,7 +57,7 @@ "lostVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "lostVillages.groupNotFound": "{{.Mention}} Group not found.", - "lostVillages.success": "{{.Mention}} Channel changed successfully.", + "lostVillages.success": "{{.Mention}} The channel has been successfully set.", "disableLostVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "disableLostVillages.groupNotFound": "{{.Mention}} Group not found.", @@ -70,12 +70,12 @@ "observe.groupNotFound": "{{.Mention}} Group not found.", "observe.tribeNotFound": "{{.Mention}} Tribe not found.", "observe.observationLimitHasBeenReached": "{{.Mention}} The observation limit for this group has been reached ({{.Total}}/{{.Limit}}).", - "observe.success": "{{.Mention}} Added.", + "observe.success": "{{.Mention}} The tribe has been added to the group.", "deleteObservation.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.", "deleteObservation.invalidObservationID": "{{.Mention}} The observation ID must be a number greater than 0.", "deleteObservation.groupNotFound": "{{.Mention}} Group not found.", - "deleteObservation.success": "{{.Mention}} Deleted.", + "deleteObservation.success": "{{.Mention}} The tribe has been removed from the group.", "observations.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.", "observations.groupNotFound": "{{.Mention}} Group not found.", @@ -92,7 +92,7 @@ "showInternals.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.", "showInternals.groupNotFound": "{{.Mention}} Group not found.", "showInternals.success_1": "{{.Mention}} Notifications about internals will no longer show up.", - "showInternals.success_2": "{{.Mention}} Enabled notifications about internals.", + "showInternals.success_2": "{{.Mention}} Notifications about internals have been enabled.", "coordsTranslation.title": "Villages", "coordsTranslation.message": "{{.Village}} owned by {{.Player}} (Tribe: {{.Tribe}}).", diff --git a/message/translations/active.pl.json b/message/translations/active.pl.json index 84e13ab..3960be6 100644 --- a/message/translations/active.pl.json +++ b/message/translations/active.pl.json @@ -1,6 +1,6 @@ { "help.title": "Pomoc", - "help.description": "Komendy oferowane przez bota.", + "help.description": "Lista komend", "help.footer": "", "help.forAllUsers": "Dla wszystkich", "help.forAdmins": "Dla adminów", @@ -17,9 +17,9 @@ "help.observe": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] [serwer] [id lub skrót plemienia] - dodaje plemię do grupy.", "help.observations": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - pokazuje plemiona należące do wybranej grupy.", "help.deleteobservation": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] [id from {{.ObservationsCommand}}] - usuwa plemię z grupy.", - "help.conqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - zmienia kanał na którym będą się pojawiać informację o podbitych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.", + "help.conqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - ustawia kanał na którym będą się pojawiać informację o podbitych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.", "help.disableconqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - wyłącza powiadomienia o podbitych wioskach w danej grupie.", - "help.lostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - zmienia kanał na którym będą się pojawiać informację o straconych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.", + "help.lostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - ustawia kanał na którym będą się pojawiać informację o straconych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.", "help.disablelostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - wyłącza powiadomienia o straconych wioskach w danej grupie.", "help.changelanguage": "**{{.Command}}** [{{.Languages}}] - zmień język bota.", "help.showinternals": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - włącza/wyłącza notyfikacje o podbiciach plemion należących do jednej grupy.", @@ -49,7 +49,7 @@ "conqueredVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "conqueredVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", - "conqueredVillages.success": "{{.Mention}} Kanał został pomyślnie zmieniony.", + "conqueredVillages.success": "{{.Mention}} Kanał został pomyślnie ustawiony.", "disableConqueredVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "disableConqueredVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", @@ -57,7 +57,7 @@ "lostVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "lostVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", - "lostVillages.success": "{{.Mention}} Kanał został pomyślnie zmieniony.", + "lostVillages.success": "{{.Mention}} Kanał został pomyślnie ustawiony.", "disableLostVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "disableLostVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", @@ -70,12 +70,12 @@ "observe.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "observe.tribeNotFound": "{{.Mention}} Plemię nie zostało znalezione.", "observe.observationLimitHasBeenReached": "{{.Mention}} Limit obserwacji dla grupy został osiągnięty ({{.Total}}/{{.Limit}}).", - "observe.success": "{{.Mention}} Dodano.", + "observe.success": "{{.Mention}} Dodano plemię do obserwowanych.", "deleteObservation.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "deleteObservation.invalidObservationID": "{{.Mention}} ID obserwacji musi być liczbą większą od 0.", "deleteObservation.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", - "deleteObservation.success": "{{.Mention}} Usunięto.", + "deleteObservation.success": "{{.Mention}} Usunięto plemię z grupy.", "observations.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "observations.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", @@ -109,5 +109,5 @@ "pagination.labelDisplayedPage": "Strona: {{.Page}} z {{.MaxPage}}", - "internalServerError": "{{.Mention}} Wewnętrzny błąd serwera, prosimy spróbować później." + "internalServerError": "{{.Mention}} Wewnętrzny błąd serwera, prosimy spróbować później." } diff --git a/models/group.go b/models/group.go index 10b0345..3b2ca92 100644 --- a/models/group.go +++ b/models/group.go @@ -1,6 +1,7 @@ package models import ( + "github.com/Kichiyaki/gopgutil/v10" "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" ) @@ -22,20 +23,16 @@ type GroupFilter struct { DefaultFilter } -func (f *GroupFilter) ApplyWithPrefix(prefix string) func(q *orm.Query) (*orm.Query, error) { - return func(q *orm.Query) (*orm.Query, error) { - if len(f.ID) > 0 { - column := addPrefixToColumnName("id", prefix) - q = q.Where(column+" = ANY(?)", pg.Array(f.ID)) - } - if len(f.ServerID) > 0 { - column := addPrefixToColumnName("server_id", prefix) - q = q.Where(column+" = ANY(?)", pg.Array(f.ServerID)) - } - return f.DefaultFilter.Apply(q) +func (f *GroupFilter) ApplyWithAlias(q *orm.Query, prefix string) (*orm.Query, error) { + if len(f.ID) > 0 { + q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("id", prefix), pg.Array(f.ID)) } + if len(f.ServerID) > 0 { + q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("server_id", prefix), pg.Array(f.ServerID)) + } + return f.DefaultFilter.Apply(q) } func (f *GroupFilter) Apply(q *orm.Query) (*orm.Query, error) { - return f.ApplyWithPrefix("group")(q) + return f.ApplyWithAlias(q, "group") } diff --git a/models/helpers.go b/models/helpers.go deleted file mode 100644 index e3f9f2f..0000000 --- a/models/helpers.go +++ /dev/null @@ -1,16 +0,0 @@ -package models - -import "strings" - -func addPrefixToColumnName(column, prefix string) string { - if prefix != "" && !strings.HasPrefix(column, prefix+".") { - column = wrapStringInDoubleQuotes(prefix) + "." + wrapStringInDoubleQuotes(column) - } else { - column = wrapStringInDoubleQuotes(column) - } - return column -} - -func wrapStringInDoubleQuotes(str string) string { - return `"` + str + `"` -} diff --git a/models/observation.go b/models/observation.go index 1b074a6..f959c13 100644 --- a/models/observation.go +++ b/models/observation.go @@ -1,23 +1,24 @@ package models import ( + "github.com/Kichiyaki/gopgutil/v10" + "github.com/tribalwarshelp/shared/tw/twmodel" "time" "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" - shared_models "github.com/tribalwarshelp/shared/models" ) type Observation struct { tableName struct{} `pg:",alias:observation"` - ID int `json:"id" gqlgen:"id"` - Server string `pg:"unique:group_1,use_zero" json:"server" gqlgen:"server"` - TribeID int `pg:"unique:group_1,use_zero" json:"tribeID" gqlgen:"tribeID"` - Tribe *shared_models.Tribe `pg:"-"` - GroupID int `pg:"on_delete:CASCADE,unique:group_1,use_zero" json:"groupID" gqlgen:"groupID"` - Group *Group `json:"group,omitempty" gqlgen:"group" pg:"rel:has-one"` - CreatedAt time.Time `pg:"default:now()" json:"createdAt" gqlgen:"createdAt" xml:"createdAt"` + ID int `json:"id" gqlgen:"id"` + Server string `pg:"unique:group_1,use_zero" json:"server" gqlgen:"server"` + TribeID int `pg:"unique:group_1,use_zero" json:"tribeID" gqlgen:"tribeID"` + Tribe *twmodel.Tribe `pg:"-"` + GroupID int `pg:"on_delete:CASCADE,unique:group_1,use_zero" json:"groupID" gqlgen:"groupID"` + Group *Group `json:"group,omitempty" gqlgen:"group" pg:"rel:has-one"` + CreatedAt time.Time `pg:"default:now()" json:"createdAt" gqlgen:"createdAt" xml:"createdAt"` } type Observations []*Observation @@ -38,24 +39,19 @@ type ObservationFilter struct { DefaultFilter } -func (f *ObservationFilter) ApplyWithPrefix(prefix string) func(q *orm.Query) (*orm.Query, error) { - return func(q *orm.Query) (*orm.Query, error) { - if len(f.ID) > 0 { - column := addPrefixToColumnName("id", prefix) - q = q.Where(column+" = ANY(?)", pg.Array(f.ID)) - } - if len(f.Server) > 0 { - column := addPrefixToColumnName("server", prefix) - q = q.Where(column+" = ANY(?)", pg.Array(f.Server)) - } - if len(f.GroupID) > 0 { - column := addPrefixToColumnName("group_id", prefix) - q = q.Where(column+" = ANY(?)", pg.Array(f.GroupID)) - } - return f.DefaultFilter.Apply(q) +func (f *ObservationFilter) ApplyWithAlias(q *orm.Query, alias string) (*orm.Query, error) { + if len(f.ID) > 0 { + q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("id", alias), pg.Array(f.ID)) } + if len(f.Server) > 0 { + q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("server", alias), pg.Array(f.Server)) + } + if len(f.GroupID) > 0 { + q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("group_id", alias), pg.Array(f.GroupID)) + } + return f.DefaultFilter.Apply(q) } func (f *ObservationFilter) Apply(q *orm.Query) (*orm.Query, error) { - return f.ApplyWithPrefix("observation")(q) + return f.ApplyWithAlias(q, "observation") } diff --git a/models/server.go b/models/server.go index 2a99bf5..b0014d8 100644 --- a/models/server.go +++ b/models/server.go @@ -1,6 +1,7 @@ package models import ( + "github.com/Kichiyaki/gopgutil/v10" "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" ) @@ -19,16 +20,13 @@ type ServerFilter struct { DefaultFilter } -func (f *ServerFilter) ApplyWithPrefix(prefix string) func(q *orm.Query) (*orm.Query, error) { - return func(q *orm.Query) (*orm.Query, error) { - if len(f.ID) > 0 { - column := addPrefixToColumnName("id", prefix) - q = q.Where(column+" = ANY(?)", pg.Array(f.ID)) - } - return f.DefaultFilter.Apply(q) +func (f *ServerFilter) ApplyWithAlias(q *orm.Query, alias string) (*orm.Query, error) { + if len(f.ID) > 0 { + q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("id", alias), pg.Array(f.ID)) } + return f.DefaultFilter.Apply(q) } func (f *ServerFilter) Apply(q *orm.Query) (*orm.Query, error) { - return f.ApplyWithPrefix("server")(q) + return f.ApplyWithAlias(q, "server") } diff --git a/observation/repository/observation_pg_repo.go b/observation/repository/pg_repository.go similarity index 91% rename from observation/repository/observation_pg_repo.go rename to observation/repository/pg_repository.go index 34ae7e4..27a9e4b 100644 --- a/observation/repository/observation_pg_repo.go +++ b/observation/repository/pg_repository.go @@ -20,7 +20,7 @@ func NewPgRepo(db *pg.DB) (observation.Repository, error) { IfNotExists: true, FKConstraints: true, }); err != nil { - return nil, errors.Wrap(err, "cannot create 'observations' table") + return nil, errors.Wrap(err, "couldn't create the 'observations' table") } return &pgRepo{db}, nil } @@ -53,7 +53,7 @@ func (repo *pgRepo) Update(ctx context.Context, observation *models.Observation) func (repo *pgRepo) Fetch(ctx context.Context, f *models.ObservationFilter) ([]*models.Observation, int, error) { var err error - data := []*models.Observation{} + var data []*models.Observation query := repo.Model(&data).Context(ctx) if f != nil { @@ -72,10 +72,9 @@ func (repo *pgRepo) Fetch(ctx context.Context, f *models.ObservationFilter) ([]* } func (repo *pgRepo) FetchServers(ctx context.Context) ([]string, error) { - data := []*models.Observation{} - res := []string{} + var res []string err := repo. - Model(&data). + Model(&models.Observation{}). Column("server"). Context(ctx). Group("server"). @@ -85,7 +84,7 @@ func (repo *pgRepo) FetchServers(ctx context.Context) ([]string, error) { } func (repo *pgRepo) Delete(ctx context.Context, f *models.ObservationFilter) ([]*models.Observation, error) { - data := []*models.Observation{} + var data []*models.Observation query := repo.Model(&data).Context(ctx) if f != nil { diff --git a/server/repository/server_pg_repo.go b/server/repository/server_pg_repo.go index ddf0f0a..68f09e5 100644 --- a/server/repository/server_pg_repo.go +++ b/server/repository/server_pg_repo.go @@ -19,7 +19,7 @@ func NewPgRepo(db *pg.DB) (server.Repository, error) { if err := db.Model((*models.Server)(nil)).CreateTable(&orm.CreateTableOptions{ IfNotExists: true, }); err != nil { - return nil, errors.Wrap(err, "cannot create 'servers' table") + return nil, errors.Wrap(err, "couldn't create the 'servers' table") } return &pgRepo{db}, nil } @@ -51,7 +51,7 @@ func (repo *pgRepo) Update(ctx context.Context, server *models.Server) error { func (repo *pgRepo) Fetch(ctx context.Context, f *models.ServerFilter) ([]*models.Server, int, error) { var err error - data := []*models.Server{} + var data []*models.Server query := repo.Model(&data).Context(ctx).Relation("Groups") if f != nil { @@ -70,7 +70,7 @@ func (repo *pgRepo) Fetch(ctx context.Context, f *models.ServerFilter) ([]*model } func (repo *pgRepo) Delete(ctx context.Context, f *models.ServerFilter) ([]*models.Server, error) { - data := []*models.Server{} + var data []*models.Server query := repo.Model(&data).Context(ctx) if f != nil { diff --git a/tw/twutil/find_version_by_code.go b/tw/twutil/find_version_by_code.go new file mode 100644 index 0000000..652e2b0 --- /dev/null +++ b/tw/twutil/find_version_by_code.go @@ -0,0 +1,14 @@ +package twutil + +import "github.com/tribalwarshelp/shared/tw/twmodel" + +func FindVersionByCode(versions []*twmodel.Version, code twmodel.VersionCode) *twmodel.Version { + var v *twmodel.Version + for _, version := range versions { + if version.Code == code { + v = version + break + } + } + return v +} diff --git a/tw/twutil/tribalwars.go b/tw/twutil/tribalwars.go new file mode 100644 index 0000000..bfbe8d4 --- /dev/null +++ b/tw/twutil/tribalwars.go @@ -0,0 +1,17 @@ +package twutil + +import ( + "github.com/tribalwarshelp/shared/tw/twmodel" +) + +func IsPlayerNil(player *twmodel.Player) bool { + return player == nil +} + +func IsPlayerTribeNil(player *twmodel.Player) bool { + return IsPlayerNil(player) || player.Tribe == nil +} + +func IsVillageNil(village *twmodel.Village) bool { + return village == nil +} diff --git a/utils/find_version_by_code.go b/utils/find_version_by_code.go deleted file mode 100644 index 9d244f9..0000000 --- a/utils/find_version_by_code.go +++ /dev/null @@ -1,14 +0,0 @@ -package utils - -import "github.com/tribalwarshelp/shared/models" - -func FindVersionByCode(versions []*models.Version, code models.VersionCode) *models.Version { - v := &models.Version{} - for _, version := range versions { - if version.Code == code { - v = version - break - } - } - return v -} diff --git a/utils/tribalwars.go b/utils/tribalwars.go deleted file mode 100644 index fb55833..0000000 --- a/utils/tribalwars.go +++ /dev/null @@ -1,17 +0,0 @@ -package utils - -import ( - "github.com/tribalwarshelp/shared/models" -) - -func IsPlayerNil(player *models.Player) bool { - return player == nil -} - -func IsPlayerTribeNil(player *models.Player) bool { - return IsPlayerNil(player) || player.Tribe == nil -} - -func IsVillageNil(village *models.Village) bool { - return village == nil -}