Skip to content

Commit

Permalink
update dependencies & add metadata refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
topi314 committed Feb 16, 2023
1 parent a4f3510 commit bc1b6ce
Show file tree
Hide file tree
Showing 8 changed files with 275 additions and 64 deletions.
76 changes: 74 additions & 2 deletions butler/butler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import (
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"

"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo-butler/db"
"github.com/disgoorg/disgo-butler/mod_mail"
"github.com/disgoorg/disgo/bot"
"github.com/disgoorg/disgo/cache"
"github.com/disgoorg/disgo/discord"
Expand All @@ -28,6 +28,9 @@ import (
"github.com/hhhapz/doc"
"github.com/hhhapz/doc/godocs"
gopiston "github.com/milindmadhukar/go-piston"

"github.com/disgoorg/disgo-butler/db"
"github.com/disgoorg/disgo-butler/mod_mail"
)

func New(logger log.Logger, version string, config Config) *Butler {
Expand Down Expand Up @@ -148,6 +151,10 @@ func (b *Butler) StartAndBlock() {
b.Logger.Errorf("Failed to start http server: %s", err)
}

contributorCtx, contributorCancel := context.WithCancel(context.Background())
defer contributorCancel()
go b.RefreshContributorRoles(contributorCtx)

defer func() {
b.Logger.Info("Shutting down...")
b.Client.Close(context.TODO())
Expand All @@ -173,3 +180,68 @@ func (b *Butler) OnReady(_ *events.Ready) {
b.Logger.Errorf("Failed to set presence: %s", err)
}
}

func (b *Butler) RefreshContributorRoles(ctx context.Context) {
for {
select {
case <-time.After(time.Hour):
b.Logger.Info("Refreshing contributor roles...")
if err := b.UpdateContributorRoles(); err != nil {
b.Logger.Errorf("Failed to update contributor roles: %s", err)
}
case <-ctx.Done():
return
}
}
}

func (b *Butler) UpdateContributorRoles() error {
contributors, err := b.DB.GetAllContributors()
if err != nil {
return err
}

contributorRepos := map[string][]*github.Contributor{}
for _, repo := range b.Config.ContributorRepos {
values := strings.SplitN(repo, "/", 2)
githubContributors, _, err := b.GitHubClient.Repositories.ListContributors(context.TODO(), values[0], values[1], nil)
if err != nil {
return err
}
contributorRepos[repo] = githubContributors
}

for _, contributor := range contributors {
metadata, err := b.GetContributorMetadata(contributor.Username, contributorRepos)
if err != nil {
b.Logger.Errorf("Failed to get contributor metadata for %s: %s", contributor.Username, err)
continue
}

session := newSession(contributor)
if _, err = b.OAuth2.UpdateApplicationRoleConnection(session, b.Client.ApplicationID(), discord.ApplicationRoleConnectionUpdate{
Metadata: &metadata,
}); err != nil {
b.Logger.Errorf("Failed to update contributor roles: %s", err)
}
}

return nil
}

func (b *Butler) GetContributorMetadata(username string, contributorRepos map[string][]*github.Contributor) (map[string]string, error) {
metadata := make(map[string]string)
for repo, contributors := range contributorRepos {
for _, contributor := range contributors {
if contributor.GetLogin() == username {
contributions := 0
if contributor.Contributions != nil {
contributions = *contributor.Contributions
}
metadata[strings.ReplaceAll(repo, "/", "_")+"_contributions"] = strconv.Itoa(contributions)
break
}
}
}
return metadata, nil
}
54 changes: 54 additions & 0 deletions butler/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package butler

import (
"time"

"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/oauth2"

"github.com/disgoorg/disgo-butler/db"
)

var _ oauth2.Session = (*Session)(nil)

func newSession(contributor db.Contributor) Session {
return Session{
accessToken: contributor.AccessToken,
refreshToken: contributor.RefreshToken,
scopes: contributor.Scopes,
tokenType: discord.TokenType(contributor.TokenType),
expiration: contributor.Expiration,
}
}

type Session struct {
accessToken string
refreshToken string
scopes []discord.OAuth2Scope
tokenType discord.TokenType
expiration time.Time
}

func (s Session) AccessToken() string {
return s.accessToken
}

func (s Session) RefreshToken() string {
return s.refreshToken
}

func (s Session) Scopes() []discord.OAuth2Scope {
return s.scopes
}

func (s Session) TokenType() discord.TokenType {
return s.tokenType
}

func (s Session) Expiration() time.Time {
return s.expiration
}

func (s Session) Webhook() *discord.IncomingWebhook {
return nil
}
67 changes: 34 additions & 33 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package main
import (
"flag"

"github.com/disgoorg/disgo-butler/butler"
"github.com/disgoorg/disgo-butler/commands"
"github.com/disgoorg/disgo-butler/components"
"github.com/disgoorg/disgo-butler/routes"
"github.com/disgoorg/disgo/handler"
"github.com/disgoorg/log"
"github.com/disgoorg/snowflake/v2"
"github.com/go-chi/chi/v5"

"github.com/disgoorg/disgo-butler/butler"
"github.com/disgoorg/disgo-butler/commands"
"github.com/disgoorg/disgo-butler/components"
"github.com/disgoorg/disgo-butler/routes"
)

const version = "development"
Expand Down Expand Up @@ -49,47 +50,47 @@ func main() {
cr := handler.New()
cr.Route("/config", func(cr handler.Router) {
cr.Route("/aliases", func(cr handler.Router) {
cr.HandleCommand("/add", commands.HandleAliasesAdd(b))
cr.HandleCommand("/remove", commands.HandleAliasesRemove(b))
cr.HandleCommand("/list", commands.HandleAliasesList(b))
cr.Command("/add", commands.HandleAliasesAdd(b))
cr.Command("/remove", commands.HandleAliasesRemove(b))
cr.Command("/list", commands.HandleAliasesList(b))
})
cr.Route("/releases", func(cr handler.Router) {
cr.HandleCommand("/add", commands.HandleReleasesAdd(b))
cr.HandleCommand("/remove", commands.HandleReleasesRemove(b))
cr.HandleCommand("/list", commands.HandleReleasesList(b))
cr.Command("/add", commands.HandleReleasesAdd(b))
cr.Command("/remove", commands.HandleReleasesRemove(b))
cr.Command("/list", commands.HandleReleasesList(b))
})
cr.Route("/contributor-repos", func(cr handler.Router) {
cr.HandleCommand("/add", commands.HandleContributorReposAdd(b))
cr.HandleCommand("/remove", commands.HandleContributorReposRemove(b))
cr.HandleCommand("/list", commands.HandleContributorReposList(b))
cr.Command("/add", commands.HandleContributorReposAdd(b))
cr.Command("/remove", commands.HandleContributorReposRemove(b))
cr.Command("/list", commands.HandleContributorReposList(b))
})
})
cr.Route("/docs", func(cr handler.Router) {
cr.HandleCommand("/", commands.HandleDocs(b))
cr.HandleAutocomplete("/", commands.HandleDocsAutocomplete(b))
cr.Command("/", commands.HandleDocs(b))
cr.Autocomplete("/", commands.HandleDocsAutocomplete(b))
})
cr.HandleComponent("docs_action", components.HandleDocsAction(b))
cr.HandleComponent("eval/rerun/{message_id}", components.HandleEvalRerunAction(b))
cr.HandleComponent("eval/delete", components.HandleEvalDeleteAction)
cr.HandleCommand("/eval", commands.HandleEval(b))
cr.HandleCommand("/info", commands.HandleInfo(b))
cr.HandleCommand("/ping", commands.HandlePing)
cr.Component("docs_action", components.HandleDocsAction(b))
cr.Component("eval/rerun/{message_id}", components.HandleEvalRerunAction(b))
cr.Component("eval/delete", components.HandleEvalDeleteAction)
cr.Command("/eval", commands.HandleEval(b))
cr.Command("/info", commands.HandleInfo(b))
cr.Command("/ping", commands.HandlePing)
cr.Route("/tag", func(cr handler.Router) {
cr.HandleCommand("/", commands.HandleTag(b))
cr.HandleAutocomplete("/", commands.HandleTagListAutoComplete(b, false))
cr.Command("/", commands.HandleTag(b))
cr.Autocomplete("/", commands.HandleTagListAutoComplete(b, false))
})
cr.Route("/tags", func(cr handler.Router) {
cr.HandleCommand("/create", commands.HandleCreateTag(b))
cr.HandleCommand("/edit", commands.HandleEditTag(b))
cr.HandleCommand("/delete", commands.HandleDeleteTag(b))
cr.HandleCommand("/info", commands.HandleTagInfo(b))
cr.HandleCommand("/list", commands.HandleListTags(b))
cr.HandleAutocomplete("/edit", commands.HandleTagListAutoComplete(b, true))
cr.HandleAutocomplete("/delete", commands.HandleTagListAutoComplete(b, true))
cr.HandleAutocomplete("/info", commands.HandleTagListAutoComplete(b, false))
cr.HandleAutocomplete("/list", commands.HandleTagListAutoComplete(b, false))
cr.Command("/create", commands.HandleCreateTag(b))
cr.Command("/edit", commands.HandleEditTag(b))
cr.Command("/delete", commands.HandleDeleteTag(b))
cr.Command("/info", commands.HandleTagInfo(b))
cr.Command("/list", commands.HandleListTags(b))
cr.Autocomplete("/edit", commands.HandleTagListAutoComplete(b, true))
cr.Autocomplete("/delete", commands.HandleTagListAutoComplete(b, true))
cr.Autocomplete("/info", commands.HandleTagListAutoComplete(b, false))
cr.Autocomplete("/list", commands.HandleTagListAutoComplete(b, false))
})
cr.HandleCommand("/close-ticket", commands.HandleCloseTicket(b))
cr.Command("/close-ticket", commands.HandleCloseTicket(b))
b.SetupBot(cr)
b.SetupDB(*shouldSyncDBTables)
b.RegisterLinkedRoles()
Expand Down
53 changes: 53 additions & 0 deletions db/contributors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package db

import (
"context"
"time"

"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/oauth2"
)

type Contributor struct {
Username string `bun:"username,pk"`
AccessToken string `bun:"access_token,notnull"`
RefreshToken string `bun:"refresh_token,notnull"`
Scopes []discord.OAuth2Scope `bun:"scopes,notnull"`
TokenType discord.TokenType `bun:"token_type,notnull"`
Expiration time.Time `bun:"expiration,notnull"`
}

type ContributorsDB interface {
GetAllContributors() ([]Contributor, error)
AddContributor(username string, session oauth2.Session) error
DeleteContributor(username string) error
}

func (s *sqlDB) GetAllContributors() (contributors []Contributor, err error) {
err = s.db.NewSelect().
Model(&contributors).
Scan(context.TODO())
return
}

func (s *sqlDB) AddContributor(username string, session oauth2.Session) (err error) {
_, err = s.db.NewInsert().
Model(&Contributor{
Username: username,
AccessToken: session.AccessToken(),
RefreshToken: session.RefreshToken(),
Scopes: session.Scopes(),
TokenType: session.TokenType(),
Expiration: session.Expiration(),
}).
Exec(context.TODO())
return
}

func (s *sqlDB) DeleteContributor(username string) (err error) {
_, err = s.db.NewDelete().
Model(&Contributor{}).
Where("username = ?", username).
Exec(context.TODO())
return
}
4 changes: 4 additions & 0 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,17 @@ func SetupDatabase(shouldSyncDBTables bool, config Config) (DB, error) {
if _, err := db.NewCreateTable().Model((*Tag)(nil)).Exec(context.TODO()); err != nil {
return nil, err
}
if _, err := db.NewCreateTable().Model((*Contributor)(nil)).Exec(context.TODO()); err != nil {
return nil, err
}
}

return &sqlDB{db: db}, nil
}

type DB interface {
TagsDB
ContributorsDB
Close()
}

Expand Down
28 changes: 14 additions & 14 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,39 @@ module github.com/disgoorg/disgo-butler
go 1.18

require (
github.com/disgoorg/disgo v0.14.2-0.20230103162111-29c995c348d1
github.com/disgoorg/disgo v0.15.1
github.com/disgoorg/json v1.0.0
github.com/disgoorg/log v1.2.0
github.com/disgoorg/paginator v0.0.0-20230104145353-f988d828ede9
github.com/disgoorg/snowflake/v2 v2.0.1
github.com/go-chi/chi/v5 v5.0.7
github.com/go-chi/chi/v5 v5.0.8
github.com/google/go-github/v44 v44.1.0
github.com/hhhapz/doc v0.5.1
github.com/lithammer/fuzzysearch v1.1.5
github.com/milindmadhukar/go-piston v0.0.0-20211122120254-64da61081d05
github.com/uptrace/bun v1.1.8
github.com/uptrace/bun/dialect/pgdialect v1.1.8
github.com/uptrace/bun/driver/pgdriver v1.1.8
github.com/uptrace/bun/extra/bundebug v1.1.8
golang.org/x/exp v0.0.0-20220914170420-dc92f8653013
github.com/uptrace/bun v1.1.11
github.com/uptrace/bun/dialect/pgdialect v1.1.11
github.com/uptrace/bun/driver/pgdriver v1.1.11
github.com/uptrace/bun/extra/bundebug v1.1.11
golang.org/x/exp v0.0.0-20230213192124-5e25df0256eb
)

require (
github.com/PuerkitoBio/goquery v1.8.0 // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/fatih/color v1.13.0 // indirect
github.com/fatih/color v1.14.1 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/sasha-s/go-csync v0.0.0-20210812194225-61421b77c44b // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 // indirect
golang.org/x/net v0.0.0-20220909164309-bea034e7d591 // indirect
golang.org/x/sys v0.0.0-20220913175220-63ea55921009 // indirect
golang.org/x/text v0.3.7 // indirect
mellium.im/sasl v0.3.0 // indirect
golang.org/x/crypto v0.6.0 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
mellium.im/sasl v0.3.1 // indirect
)
Loading

0 comments on commit bc1b6ce

Please sign in to comment.