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/cron/cron.go b/cron/cron.go index a5cf2de..657d101 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, + checkEnnoblements := trackDuration(log, h.checkEnnoblements, "checkEnnoblements") + checkBotServers := trackDuration(log, h.checkBotServers, "checkBotServers") + deleteClosedTribalWarsServers := trackDuration(log, h.deleteClosedTribalWarsServers, "deleteClosedTribalWarsServers") - updateBotStatus := sharedutils.TrackExecutionTime(log, h.updateBotStatus, "updateBotStatus") + 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..14f1d38 100644 --- a/cron/ennoblements.go +++ b/cron/ennoblements.go @@ -1,13 +1,14 @@ package cron import ( + "github.com/tribalwarshelp/shared/tw/twmodel" + "github.com/tribalwarshelp/dcbot/utils" - shared_models "github.com/tribalwarshelp/shared/models" ) -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 diff --git a/cron/handler.go b/cron/handler.go index c728738..a990eb5 100644 --- a/cron/handler.go +++ b/cron/handler.go @@ -3,16 +3,17 @@ 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/golang-sdk/sdk" "github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/group" @@ -20,7 +21,6 @@ import ( "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,36 +83,36 @@ 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 { @@ -156,26 +156,26 @@ func (h *handler) checkEnnoblements() { } log.Info("checkEnnoblements: loaded ennoblements") - 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 := utils.FindVersionByCode(versions, twmodel.VersionCodeFromServerKey(obs.Server)) if ok && version != nil && version.Host != "" { - if group.LostVillagesChannelID != "" { - for _, ennoblement := range ennoblements.getLostVillagesByTribe(observation.TribeID) { + if g.LostVillagesChannelID != "" { + for _, ennoblement := range enblmnts.getLostVillagesByTribe(obs.TribeID) { if !utils.IsPlayerTribeNil(ennoblement.NewOwner) && - group.Observations.Contains(observation.Server, ennoblement.NewOwner.Tribe.ID) { + 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) { + if g.ConqueredVillagesChannelID != "" { + for _, ennoblement := range enblmnts.getConqueredVillagesByTribe(obs.TribeID, g.ShowInternals) { isInTheSameGroup := !utils.IsPlayerTribeNil(ennoblement.OldOwner) && - group.Observations.Contains(observation.Server, ennoblement.OldOwner.Tribe.ID) - if (!group.ShowInternals && isInTheSameGroup) || - (!group.ShowEnnobledBarbarians && isBarbarian(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) } } @@ -282,9 +282,9 @@ func (h *handler) deleteClosedTribalWarsServers() { WithField("servers", servers). Info("deleteClosedTribalWarsServers: 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()) @@ -294,9 +294,9 @@ func (h *handler) deleteClosedTribalWarsServers() { 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 { diff --git a/cron/helpers.go b/cron/helpers.go index ed1a1b3..f27bfcf 100644 --- a/cron/helpers.go +++ b/cron/helpers.go @@ -1,10 +1,29 @@ package cron import ( + "github.com/sirupsen/logrus" + "github.com/tribalwarshelp/shared/tw/twmodel" + "time" + "github.com/tribalwarshelp/dcbot/utils" - shared_models "github.com/tribalwarshelp/shared/models" ) -func isBarbarian(p *shared_models.Player) bool { +func isBarbarian(p *twmodel.Player) bool { return utils.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..b1d7d35 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" ) 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 } @@ -55,23 +56,23 @@ func newMessage(cfg newMessageConfig) checkEnnoblementsMsg { } if !utils.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) { 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) { 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) { 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) { 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/discord/coords_translation.go b/discord/coords_translation.go index 1075604..30b7156 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/golang-sdk/sdk" + "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" ) 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) { 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) { 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..fc1c72e 100644 --- a/discord/discord.go +++ b/discord/discord.go @@ -6,13 +6,15 @@ import ( "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" ) @@ -231,18 +233,18 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre splitted := strings.Split(m.Content, " ") args := splitted[1:] - server := &models.Server{ + 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]) @@ -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..c433d12 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" ) const ( @@ -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 { @@ -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 := utils.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, diff --git a/discord/public_commands.go b/discord/public_commands.go index 822cd05..5c657cb 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" @@ -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..6f8769d 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,9 @@ 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/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 +14,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..e10128b 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,8 @@ package main import ( + "github.com/Kichiyaki/appmode" + "github.com/Kichiyaki/goutil/envutil" "log" "os" "os/signal" @@ -16,13 +18,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 +37,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 +51,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 +72,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,14 +97,15 @@ 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))), @@ -122,24 +120,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/models/observation.go b/models/observation.go index 1b074a6..c5b5342 100644 --- a/models/observation.go +++ b/models/observation.go @@ -1,23 +1,23 @@ package models import ( + "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 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/utils/find_version_by_code.go b/utils/find_version_by_code.go index 9d244f9..63fe64d 100644 --- a/utils/find_version_by_code.go +++ b/utils/find_version_by_code.go @@ -1,9 +1,9 @@ package utils -import "github.com/tribalwarshelp/shared/models" +import "github.com/tribalwarshelp/shared/tw/twmodel" -func FindVersionByCode(versions []*models.Version, code models.VersionCode) *models.Version { - v := &models.Version{} +func FindVersionByCode(versions []*twmodel.Version, code twmodel.VersionCode) *twmodel.Version { + var v *twmodel.Version for _, version := range versions { if version.Code == code { v = version diff --git a/utils/tribalwars.go b/utils/tribalwars.go index fb55833..ffd085d 100644 --- a/utils/tribalwars.go +++ b/utils/tribalwars.go @@ -1,17 +1,17 @@ package utils import ( - "github.com/tribalwarshelp/shared/models" + "github.com/tribalwarshelp/shared/tw/twmodel" ) -func IsPlayerNil(player *models.Player) bool { +func IsPlayerNil(player *twmodel.Player) bool { return player == nil } -func IsPlayerTribeNil(player *models.Player) bool { +func IsPlayerTribeNil(player *twmodel.Player) bool { return IsPlayerNil(player) || player.Tribe == nil } -func IsVillageNil(village *models.Village) bool { +func IsVillageNil(village *twmodel.Village) bool { return village == nil }