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
|
|
|
|
2021-05-04 16:18:15 +00:00
|
|
|
"git.birbmc.com/canopeas/database"
|
2021-02-22 18:27:49 +00:00
|
|
|
|
2021-05-05 03:24:39 +00:00
|
|
|
"git.birbmc.com/Etzelia/go-serverapi"
|
2021-02-22 18:27:49 +00:00
|
|
|
"go.jolheiser.com/beaver"
|
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() {
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|