2020-12-21 00:32:39 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-12-24 14:59:11 +00:00
|
|
|
"crypto/sha256"
|
|
|
|
"fmt"
|
2020-12-21 00:32:39 +00:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var timerStore = newTimer()
|
|
|
|
|
|
|
|
type timer struct {
|
|
|
|
timers map[string]time.Time
|
|
|
|
lock *sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func newTimer() *timer {
|
|
|
|
return &timer{
|
|
|
|
timers: map[string]time.Time{},
|
|
|
|
lock: new(sync.RWMutex),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *timer) Add(id string) {
|
|
|
|
t.lock.Lock()
|
|
|
|
defer t.lock.Unlock()
|
|
|
|
|
|
|
|
t.timers[id] = time.Now()
|
|
|
|
}
|
|
|
|
|
2020-12-24 14:59:11 +00:00
|
|
|
func (t *timer) AddPermit(channel, username string) {
|
|
|
|
t.Add(t.getPermitTimerKey(channel, username))
|
|
|
|
}
|
|
|
|
|
2020-12-21 00:32:39 +00:00
|
|
|
func (t *timer) Has(id string, validity time.Duration) bool {
|
|
|
|
t.lock.RLock()
|
|
|
|
defer t.lock.RUnlock()
|
|
|
|
|
|
|
|
return time.Since(t.timers[id]) < validity
|
|
|
|
}
|
|
|
|
|
2020-12-24 14:59:11 +00:00
|
|
|
func (t *timer) HasPermit(channel, username string) bool {
|
|
|
|
return t.Has(t.getPermitTimerKey(channel, username), config.PermitTimeout)
|
2020-12-21 00:32:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t timer) NormalizeUsername(username string) string {
|
|
|
|
return strings.ToLower(strings.TrimLeft(username, "@"))
|
|
|
|
}
|
2020-12-24 14:59:11 +00:00
|
|
|
|
|
|
|
func (t timer) getPermitTimerKey(channel, username string) string {
|
|
|
|
h := sha256.New()
|
|
|
|
fmt.Fprintf(h, "%s:%s", channel, t.NormalizeUsername(username))
|
|
|
|
return fmt.Sprintf("sha256:%x", h.Sum(nil))
|
|
|
|
}
|