84 lines
1.5 KiB
Go
84 lines
1.5 KiB
Go
package discord
|
|
|
|
import (
|
|
r "math/rand"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.canopymc.net/Etzelia/canopeas/database"
|
|
|
|
"git.birbmc.com/Etzelia/go-serverapi"
|
|
"go.jolheiser.com/beaver"
|
|
)
|
|
|
|
type rateLimit struct {
|
|
rate time.Duration
|
|
next time.Time
|
|
}
|
|
|
|
func NewRateLimit(rate time.Duration) *rateLimit {
|
|
return &rateLimit{
|
|
rate: rate,
|
|
next: time.Now(),
|
|
}
|
|
}
|
|
|
|
func (r *rateLimit) Try() bool {
|
|
now := time.Now()
|
|
if now.After(r.next) {
|
|
r.next = now.Add(r.rate)
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
var rand = r.New(r.NewSource(time.Now().Unix()))
|
|
|
|
func random(list []string) string {
|
|
size := len(list)
|
|
if size == 0 {
|
|
return ""
|
|
} else if size == 1 {
|
|
return list[0]
|
|
}
|
|
idx := rand.Intn(size)
|
|
return list[idx]
|
|
}
|
|
|
|
type unbanSchedule struct {
|
|
db *database.Database
|
|
sapi *serverapi.Client
|
|
}
|
|
|
|
func (u *unbanSchedule) Run() {
|
|
u.check()
|
|
ticker := time.NewTicker(time.Minute * 5)
|
|
for {
|
|
<-ticker.C
|
|
u.check()
|
|
}
|
|
}
|
|
|
|
func (u *unbanSchedule) check() {
|
|
beaver.Debug("Running unban schedule")
|
|
now := time.Now()
|
|
for _, record := range u.db.ListUnbans() {
|
|
if now.After(record.Expiration) {
|
|
beaver.Infof("Unbanning %s", record.Username)
|
|
unban := serverapi.Unban{
|
|
Target: record.Username,
|
|
}
|
|
status, err := u.sapi.Unban(unban)
|
|
if err != nil {
|
|
beaver.Error(err)
|
|
}
|
|
if status != http.StatusOK {
|
|
beaver.Errorf("ServerAPI returned status %d when trying to ban %s", status, record.Username)
|
|
}
|
|
if err := u.db.RemoveUnban(record.Username); err != nil {
|
|
beaver.Errorf("could not remove unban for %s in database", record.Username)
|
|
}
|
|
}
|
|
}
|
|
}
|