Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: report guild role #1370

Merged
merged 1 commit into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions pkg/entities/guild.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"time"

"github.com/bwmarrin/discordgo"
Expand All @@ -15,6 +16,7 @@ import (
baseerrs "github.com/defipod/mochi/pkg/model/errors"
"github.com/defipod/mochi/pkg/request"
"github.com/defipod/mochi/pkg/response"
"github.com/defipod/mochi/pkg/util"
)

func (e *Entity) CreateGuild(guild request.CreateGuildRequest) error {
Expand Down Expand Up @@ -352,3 +354,62 @@ func (e *Entity) ValidateUser(ids []string, guildId string) ([]string, error) {

return res, nil
}

func (e *Entity) GuildReportRoles(guildId string) (*response.GuildReportRoles, error) {
guildInfo, err := e.svc.Discord.GuildWithCounts(guildId)
if err != nil {
e.log.Errorf(err, "[entity.Statistic] cannot get guild info from Discord")
return nil, err
}

// Discord API not count number of members in each role
// - need to get all guild member to see what roles they have and count
// - only allow 1000 members per request, so need to loop until all members are counted
after := ""
limit := 1000
countRole := make(map[string]int64, 0)

for {
guildMembers, err := e.discord.GuildMembers(guildId, after, limit)
if err != nil {
return nil, err
}
for _, member := range guildMembers {
for _, role := range member.Roles {
_, ok := countRole[role]
if !ok {
countRole[role] = 1
} else {
countRole[role] = countRole[role] + 1
}

}
}

if len(guildMembers) < limit {
break
}
after = guildMembers[len(guildMembers)-1].User.ID
}

// mapping to response
guildReportRoles := make([]response.GuildReportRoleDetail, 0)
for _, role := range guildInfo.Roles {
if role.ID != guildId {
// change percentage: temp random value until implement database logic
rand.Seed(time.Now().UnixNano())
changePercentage := util.RandFloats(0.0, 100.0)
guildReportRoles = append(guildReportRoles, response.GuildReportRoleDetail{
Id: role.ID,
Name: role.Name,
NrOfMember: countRole[role.ID],
ChangePercentage: changePercentage,
})
}
}

return &response.GuildReportRoles{
LastUpdated: time.Now(),
Roles: guildReportRoles,
}, nil
}
18 changes: 18 additions & 0 deletions pkg/handler/guild/guild.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,21 @@ func (h *Handler) CreateGuild(c *gin.Context) {

c.JSON(http.StatusOK, response.CreateResponse(response.ResponseMessage{Message: "OK"}, nil, nil, nil))
}

func (h *Handler) GuildReportRoles(c *gin.Context) {
var req request.GuildRequest
if err := c.ShouldBindUri(&req); err != nil {
h.log.Fields(logger.Fields{"req": req}).Error(err, "[handler.Statistic] - failed to read query")
c.JSON(http.StatusBadRequest, response.CreateResponse[any](nil, nil, errors.New("invalid request"), nil))
return
}

resp, err := h.entities.GuildReportRoles(req.GuildId)
if err != nil {
h.log.Fields(logger.Fields{"req": req}).Error(err, "[handler.Statistic] - failed to statistic")
c.JSON(http.StatusInternalServerError, response.CreateResponse[any](nil, nil, err, nil))
return
}

c.JSON(http.StatusOK, response.CreateResponse(resp, nil, nil, nil))
}
2 changes: 2 additions & 0 deletions pkg/handler/guild/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@ type IHandler interface {
UpdateGuild(c *gin.Context)
GetGuildRoles(c *gin.Context)
ValidateUser(c *gin.Context)
// report
GuildReportRoles(c *gin.Context)
}
4 changes: 4 additions & 0 deletions pkg/request/guild.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ type ValidateUserRequest struct {
Ids string `form:"ids"`
GuildId string `form:"guild_id"`
}

type GuildRequest struct {
GuildId string `uri:"guild_id" binding:"required"`
}
14 changes: 14 additions & 0 deletions pkg/response/guild.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package response

import (
"time"

"github.com/bwmarrin/discordgo"

"github.com/defipod/mochi/pkg/model"
Expand Down Expand Up @@ -36,3 +38,15 @@ type DiscordGuildResponse struct {
type ListMyGuildsResponse struct {
Data []DiscordGuildResponse `json:"data"`
}

type GuildReportRoles struct {
Roles []GuildReportRoleDetail `json:"roles"`
LastUpdated time.Time `json:"last_updated"`
}

type GuildReportRoleDetail struct {
Id string `json:"id"`
Name string `json:"name"`
NrOfMember int64 `json:"nr_of_member"`
ChangePercentage float64 `json:"change_percentage"`
}
5 changes: 5 additions & 0 deletions pkg/routes/v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ func NewRoutes(r *gin.Engine, h *handler.Handler, cfg config.Config) {
guildGroup.GET("/user-managed", middleware.AuthGuard(cfg), h.Guild.ListMyGuilds)
guildGroup.PUT("/:guild_id", h.Guild.UpdateGuild)
guildGroup.GET("/validate-user", h.Guild.ValidateUser)

reportGuildGroup := guildGroup.Group("/:guild_id/report")
{
reportGuildGroup.GET("/roles", h.Guild.GuildReportRoles)
}
}

profileGroup := v1.Group("/profiles")
Expand Down
10 changes: 10 additions & 0 deletions pkg/service/discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ func (d *Discord) GetGuildEmojis() ([]*discordgo.Emoji, error) {
return emojis, nil
}

func (d *Discord) GuildWithCounts(guildId string) (*discordgo.Guild, error) {
guild, err := d.session.GuildWithCounts(guildId)
if err != nil {
d.log.Errorf(err, "[discord.GuildWithCounts] - failed to get guild with counts: %s", guildId)
return nil, err
}

return guild, nil
}

func (d *Discord) NotifyNewGuild(guildID string, count int) error {
// get new guild info
guild, err := d.session.Guild(guildID)
Expand Down
15 changes: 15 additions & 0 deletions pkg/service/discord/mocks/service.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/service/discord/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type Service interface {
GetGuildMembers(guildID string) ([]*discordgo.Member, error)
GetGuild(guildID string) (*discordgo.Guild, error)
GetGuildRoles(guildID string) ([]*model.DiscordGuildRole, error)
GuildWithCounts(guildId string) (*discordgo.Guild, error)

// User
GetUser(userID string) (*discordgo.User, error)
Expand Down
4 changes: 4 additions & 0 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -883,3 +883,7 @@ func ValidateFileMarkdown(s string) bool {

return matched
}

func RandFloats(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
Loading