forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
91 lines (76 loc) · 2.3 KB
/
monitor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package premium
import (
"context"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/premium/models"
"github.com/mediocregopher/radix.v3"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/volatiletech/sqlboiler/queries/qm"
"strconv"
"time"
)
func runMonitor() {
ticker := time.NewTicker(time.Second * 30)
time.Sleep(time.Second * 3)
err := checkExpiredSlots(context.Background())
if err != nil {
logrus.WithError(err).Error("Failed checking for expired premium slots")
}
checkedExpiredSlots := false
for {
<-ticker.C
if checkedExpiredSlots {
err := updatePremiumServers(context.Background())
if err != nil {
logrus.WithError(err).Error("Failed updating premium servers")
}
checkedExpiredSlots = false
} else {
err := checkExpiredSlots(context.Background())
if err != nil {
logrus.WithError(err).Error("Failed checking for expired premium slots")
}
checkedExpiredSlots = true
}
}
}
// Updates ALL premiun slots from ALL sources
func checkExpiredSlots(ctx context.Context) error {
timedSlots, err := models.PremiumSlots(qm.Where("permanent = false"), qm.Where("guild_id IS NOT NULL")).AllG(ctx)
if err != nil {
return errors.WithMessage(err, "models.PremiumSlots")
}
for _, v := range timedSlots {
if SlotDurationLeft(v) <= 0 {
err := SlotExpired(ctx, v)
if err != nil {
logrus.WithError(err).WithField("slot", v.ID).Error("Failed expiring premium slot")
}
}
}
return nil
}
func updatePremiumServers(ctx context.Context) error {
slots, err := models.PremiumSlots(qm.Where("guild_id IS NOT NULL")).AllG(ctx)
if err != nil {
return errors.WithMessage(err, "models.PremiumSlots")
}
if len(slots) < 1 {
// Fast path
err = common.RedisPool.Do(radix.Cmd(nil, "DEL", RedisKeyPremiumGuilds))
return errors.WithMessage(err, "do.Del")
}
rCmd := []string{RedisKeyPremiumGuildsTmp}
for _, slot := range slots {
strGID := strconv.FormatInt(slot.GuildID.Int64, 10)
strUserID := strconv.FormatInt(slot.UserID, 10)
rCmd = append(rCmd, strGID, strUserID)
}
err = common.RedisPool.Do(radix.Pipeline(
radix.Cmd(nil, "DEL", RedisKeyPremiumGuildsTmp),
radix.Cmd(nil, "HMSET", rCmd...),
radix.Cmd(nil, "RENAME", RedisKeyPremiumGuildsTmp, RedisKeyPremiumGuilds),
))
return errors.WithMessage(err, "radix.Pipeline")
}