forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
premium.go
300 lines (242 loc) · 7.88 KB
/
premium.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package premium
import (
"context"
"database/sql"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/premium/models"
"github.com/mediocregopher/radix.v3"
"github.com/pkg/errors"
"github.com/volatiletech/null"
"github.com/volatiletech/sqlboiler/boil"
"github.com/volatiletech/sqlboiler/queries/qm"
"time"
)
const (
// Hash
// Key: guild id's
// Value: the user id's providing the premium status
RedisKeyPremiumGuilds = "premium_activated_guilds"
RedisKeyPremiumGuildsTmp = "premium_activated_guilds_tmp"
)
type Plugin struct {
}
func (p *Plugin) Name() string {
return "premium"
}
func RegisterPlugin() {
common.RegisterPlugin(&Plugin{})
for _, v := range PremiumSources {
v.Init()
}
}
// IsGuildPremium return true if the provided guild has the premium status provided to it by a user
func IsGuildPremium(guildID int64) (bool, error) {
var premium bool
err := common.RedisPool.Do(radix.FlatCmd(&premium, "HEXISTS", RedisKeyPremiumGuilds, guildID))
return premium, errors.WithMessage(err, "IsGuildPremium")
}
// UserPremiumSlots returns all slots for a user
func UserPremiumSlots(ctx context.Context, userID int64) (slots []*models.PremiumSlot, err error) {
slots, err = models.PremiumSlots(qm.Where("user_id = ?", userID), qm.OrderBy("id desc")).AllG(ctx)
return
}
var (
PremiumSources []PremiumSource
ErrSlotNotFound = errors.New("premium slot not found")
ErrGuildAlreadyPremium = errors.New("guild already assigned premium from another slot")
)
type PremiumSource interface {
Init()
Names() (human string, idname string)
}
func RegisterPremiumSource(source PremiumSource) {
PremiumSources = append(PremiumSources, source)
}
func SlotExpired(ctx context.Context, slot *models.PremiumSlot) error {
err := DetachSlotFromGuild(ctx, slot.ID, slot.UserID)
if err != nil {
return errors.WithMessage(err, "Detach")
}
// Attempt migrating the guild attached to the epxired slot to the next available slot the owner of the slot has
tx, err := common.PQ.BeginTx(ctx, nil)
if err != nil {
return errors.WithMessage(err, "BeginTX")
}
availableSlot, err := models.PremiumSlots(qm.Where("user_id = ? AND guild_id IS NULL and permanent = true", slot.UserID), qm.For("UPDATE")).One(ctx, tx)
if err != nil {
tx.Rollback()
// If there's no available slots to migrate the guild to, not much can be done
if errors.Cause(err) == sql.ErrNoRows {
return nil
}
return errors.WithMessage(err, "models.PremiumSlots")
}
availableSlot.AttachedAt = null.TimeFrom(time.Now())
availableSlot.GuildID = slot.GuildID
_, err = availableSlot.Update(ctx, tx, boil.Whitelist("attached_at", "guild_id"))
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "Update")
}
err = tx.Commit()
if err != nil {
return errors.WithMessage(err, "Commit")
}
err = common.RedisPool.Do(radix.FlatCmd(nil, "HSET", RedisKeyPremiumGuilds, slot.GuildID.Int64, slot.UserID))
return errors.WithMessage(err, "HSET")
}
// RemovePremiumSlots removes the specifues premium slots and attempts to migrate to other permanent available ones
// THIS SHOULD BE USED INSIDE A TRANSACTION ONLY, AS OTHERWISE RACE CONDITIONS BE UPON THEE
func RemovePremiumSlots(ctx context.Context, exec boil.ContextExecutor, userID int64, slotsToRemove []int64) error {
userSlots, err := models.PremiumSlots(qm.Where("user_id = ?", userID), qm.OrderBy("id desc"), qm.For("UPDATE")).All(ctx, exec)
if err != nil {
return errors.WithMessage(err, "models.PremiumSlots")
}
// Find the remainign free slots after the removal of the specified slots
remainingFreeSlots := make([]*models.PremiumSlot, 0)
for _, slot := range userSlots {
if slot.GuildID.Valid || !slot.Permanent || SlotDurationLeft(slot) <= 0 {
continue
}
for _, v := range slotsToRemove {
if v == slot.ID {
continue
}
}
remainingFreeSlots = append(remainingFreeSlots, slot)
}
freeSlotsUsed := 0
// Do the removal and migration
for _, removing := range slotsToRemove {
// Find the model first
var slot *models.PremiumSlot
for _, v := range userSlots {
if v.ID == removing {
slot = v
break
}
}
if slot == nil {
continue
}
if slot.GuildID.Valid && freeSlotsUsed < len(remainingFreeSlots) {
// We can migrate it
remainingFreeSlots[freeSlotsUsed].GuildID = slot.GuildID
remainingFreeSlots[freeSlotsUsed].AttachedAt = null.TimeFrom(time.Now())
freeSlotsUsed++
}
_, err = slot.Delete(ctx, exec)
if err != nil {
return errors.WithMessage(err, "slot.Delete")
}
}
// Update all the slots we migrated to
for i := 0; i < freeSlotsUsed; i++ {
_, err = remainingFreeSlots[i].Update(ctx, exec, boil.Whitelist("guild_id", "attached_at"))
if err != nil {
return errors.WithMessage(err, "remainingFreeSlots.Update")
}
}
return nil
}
func CreatePremiumSlot(ctx context.Context, exec boil.ContextExecutor, userID int64, source, title, message string, sourceSlotID int64, duration time.Duration) (*models.PremiumSlot, error) {
slot := &models.PremiumSlot{
UserID: userID,
Source: source,
SourceID: sourceSlotID,
Title: title,
Message: message,
FullDuration: int64(duration),
Permanent: duration <= 0,
DurationRemaining: int64(duration),
}
err := slot.Insert(ctx, exec, boil.Infer())
return slot, err
}
func FindSource(sourceID string) PremiumSource {
for _, v := range PremiumSources {
if _, id := v.Names(); id == sourceID {
return v
}
}
return nil
}
func SlotDurationLeft(slot *models.PremiumSlot) (duration time.Duration) {
if slot.Permanent {
return 0xfffffffffffffff
}
duration = time.Duration(slot.DurationRemaining)
if slot.GuildID.Valid {
duration -= time.Since(slot.AttachedAt.Time)
}
return duration
}
func AttachSlotToGuild(ctx context.Context, slotID int64, userID int64, guildID int64) error {
tx, err := common.PQ.BeginTx(ctx, nil)
if err != nil {
return errors.WithMessage(err, "BeginTX")
}
_, err = tx.Exec("LOCK TABLE premium_slots IN EXCLUSIVE MODE")
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "Lock")
}
// Check if this guild is used in another slot
n, err := models.PremiumSlots(qm.Where("guild_id = ?", guildID)).Count(ctx, tx)
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "PremiumSlots.Count")
}
if n > 0 {
tx.Rollback()
return ErrGuildAlreadyPremium
}
n, err = models.PremiumSlots(qm.Where("id = ? AND user_id = ? AND guild_id IS NULL AND (permanent OR duration_remaining > 0)", slotID, userID)).UpdateAll(
ctx, tx, models.M{"guild_id": null.Int64From(guildID), "attached_at": time.Now()})
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "UpdateAll")
}
if n < 1 {
tx.Rollback()
return ErrSlotNotFound
}
err = tx.Commit()
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "Commit")
}
err = common.RedisPool.Do(radix.FlatCmd(nil, "HSET", RedisKeyPremiumGuilds, guildID, userID))
return errors.WithMessage(err, "Hset.RedisKeyPremiumGuilds")
}
func DetachSlotFromGuild(ctx context.Context, slotID int64, userID int64) error {
tx, err := common.PQ.BeginTx(ctx, nil)
if err != nil {
return errors.WithMessage(err, "BeginTX")
}
slot, err := models.PremiumSlots(qm.Where("id = ? AND user_id = ?", slotID, userID), qm.For("UPDATE")).One(ctx, tx)
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "PremiumSlots.One")
}
if slot == nil {
tx.Rollback()
return ErrSlotNotFound
}
oldGuildID := slot.GuildID.Int64
// Update the duration before we reset the guild_id to null
slot.DurationRemaining = int64(SlotDurationLeft(slot))
slot.GuildID = null.Int64{}
slot.AttachedAt = null.Time{}
_, err = slot.Update(ctx, tx, boil.Infer())
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "Update")
}
err = tx.Commit()
if err != nil {
errors.WithMessage(err, "Commit")
}
err = common.RedisPool.Do(radix.FlatCmd(nil, "HDEL", RedisKeyPremiumGuilds, oldGuildID))
return errors.WithMessage(err, "HDEL.RedisKeyPremiumGuilds")
}