2020-07-02 20:00:22 +00:00
|
|
|
package discord
|
|
|
|
|
|
|
|
import (
|
2020-07-02 21:52:20 +00:00
|
|
|
r "math/rand"
|
2021-02-22 18:27:49 +00:00
|
|
|
"net/http"
|
2020-07-02 20:00:22 +00:00
|
|
|
"time"
|
2021-02-22 18:27:49 +00:00
|
|
|
|
2022-01-19 19:51:12 +00:00
|
|
|
"github.com/rs/zerolog/log"
|
2021-02-22 18:27:49 +00:00
|
|
|
|
2022-01-19 19:51:12 +00:00
|
|
|
"git.jojodev.com/Minecraft/go-serverapi"
|
|
|
|
|
|
|
|
"git.jojodev.com/Minecraft/canopeas/database"
|
2020-07-02 20:00:22 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2020-07-02 21:52:20 +00:00
|
|
|
|
|
|
|
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]
|
|
|
|
}
|
2021-02-22 18:27:49 +00:00
|
|
|
|
|
|
|
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() {
|
2022-01-19 19:51:12 +00:00
|
|
|
log.Debug().Msg("Running unban schedule")
|
2021-02-22 18:27:49 +00:00
|
|
|
now := time.Now()
|
|
|
|
for _, record := range u.db.ListUnbans() {
|
|
|
|
if now.After(record.Expiration) {
|
2022-01-19 19:51:12 +00:00
|
|
|
log.Info().Msgf("Unbanning %s", record.Username)
|
2021-02-22 18:27:49 +00:00
|
|
|
unban := serverapi.Unban{
|
|
|
|
Target: record.Username,
|
|
|
|
}
|
|
|
|
status, err := u.sapi.Unban(unban)
|
|
|
|
if err != nil {
|
2022-01-19 19:51:12 +00:00
|
|
|
log.Err(err).Msg("")
|
2021-02-22 18:27:49 +00:00
|
|
|
}
|
|
|
|
if status != http.StatusOK {
|
2022-01-19 19:51:12 +00:00
|
|
|
log.Error().Msgf("ServerAPI returned status %d when trying to ban %s", status, record.Username)
|
2021-02-22 18:27:49 +00:00
|
|
|
}
|
|
|
|
if err := u.db.RemoveUnban(record.Username); err != nil {
|
2022-01-19 19:51:12 +00:00
|
|
|
log.Error().Msgf("could not remove unban for %s in database", record.Username)
|
2021-02-22 18:27:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|