twitch-bot/timers.go

61 lines
1.4 KiB
Go
Raw Normal View History

2020-12-21 00:32:39 +00:00
package main
import (
"crypto/sha256"
"fmt"
2020-12-21 00:32:39 +00:00
"strings"
"time"
)
type timerType uint8
const (
timerTypePermit timerType = iota
timerTypeCooldown
)
2020-12-21 00:32:39 +00:00
var timerStore = newTimer()
type timerEntry struct {
Kind timerType `json:"kind"`
Time time.Time `json:"time"`
}
type timer struct{}
2020-12-21 00:32:39 +00:00
func newTimer() *timer {
return &timer{}
2020-12-21 00:32:39 +00:00
}
// Cooldown timer
2020-12-21 00:32:39 +00:00
func (t *timer) AddCooldown(tt timerType, limiter, ruleID string, expiry time.Time) {
store.SetTimer(timerTypeCooldown, t.getCooldownTimerKey(tt, limiter, ruleID), expiry)
2020-12-21 00:32:39 +00:00
}
func (t *timer) InCooldown(tt timerType, limiter, ruleID string) bool {
return store.HasTimer(t.getCooldownTimerKey(tt, limiter, ruleID))
}
func (timer) getCooldownTimerKey(tt timerType, limiter, ruleID string) string {
h := sha256.New()
fmt.Fprintf(h, "%d:%s:%s", tt, limiter, ruleID)
return fmt.Sprintf("sha256:%x", h.Sum(nil))
2020-12-21 00:32:39 +00:00
}
// Permit timer
func (t *timer) AddPermit(channel, username string) {
store.SetTimer(timerTypePermit, t.getPermitTimerKey(channel, username), time.Now().Add(config.PermitTimeout))
2020-12-21 00:32:39 +00:00
}
func (t *timer) HasPermit(channel, username string) bool {
return store.HasTimer(t.getPermitTimerKey(channel, username))
2020-12-21 00:32:39 +00:00
}
func (timer) getPermitTimerKey(channel, username string) string {
h := sha256.New()
fmt.Fprintf(h, "%d:%s:%s", timerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@")))
return fmt.Sprintf("sha256:%x", h.Sum(nil))
}