-
Notifications
You must be signed in to change notification settings - Fork 927
/
codepremiumsource.go
196 lines (160 loc) · 4.87 KB
/
codepremiumsource.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
package premium
//go:generate sqlboiler psql
import (
"context"
"crypto/rand"
"database/sql"
"encoding/base32"
"fmt"
"time"
"emperror.dev/errors"
"github.com/botlabs-gg/yagpdb/v2/bot"
"github.com/botlabs-gg/yagpdb/v2/commands"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/lib/dcmd"
"github.com/botlabs-gg/yagpdb/v2/premium/models"
"github.com/botlabs-gg/yagpdb/v2/stdcommands/util"
"github.com/lib/pq"
"github.com/volatiletech/null/v8"
"github.com/volatiletech/sqlboiler/v4/boil"
"github.com/volatiletech/sqlboiler/v4/queries/qm"
)
var (
ErrCodeExpired = errors.New("Code expired")
ErrCodeNotFound = errors.New("Code not found")
)
func init() {
RegisterPremiumSource(&CodePremiumSource{})
}
type CodePremiumSource struct{}
func (ps *CodePremiumSource) Init() {
}
func (ps *CodePremiumSource) Names() (human string, idname string) {
return "Redeemed code", "code"
}
func RedeemCode(ctx context.Context, code string, userID int64) error {
tx, err := common.PQ.BeginTx(ctx, nil)
if err != nil {
return errors.WithMessage(err, "BeginTX")
}
// Query for the code model
c, err := models.PremiumCodes(qm.Where("code = ? AND user_id IS NULL", code), qm.For("UPDATE")).One(ctx, tx)
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "models.PremiumCodes")
}
// model found, with no user attached, create the slot for it
slot, err := CreatePremiumSlot(ctx, tx, userID, "code", "Redeemed code", c.Message, c.ID, time.Duration(c.Duration), PremiumTierPremium)
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "CreatePremiumSlot")
}
// Update the code fields
c.UserID = null.Int64From(userID)
c.UsedAt = null.TimeFrom(time.Now())
c.SlotID = null.Int64From(slot.ID)
_, err = c.Update(ctx, tx, boil.Infer())
if err != nil {
tx.Rollback()
return errors.WithMessage(err, "Update")
}
err = tx.Commit()
return errors.WithMessage(err, "Commit")
}
func LookupCode(ctx context.Context, code string) (*models.PremiumCode, error) {
c, err := models.PremiumCodes(qm.Where("code = ?", code)).OneG(ctx)
if err != nil {
if err == sql.ErrNoRows {
return nil, ErrCodeNotFound
}
return nil, errors.WithMessage(err, "models.PremiumCodes")
}
return c, nil
}
var (
ErrCodeCollision = errors.New("Code collision")
)
// TryRetryGenerateCode attempts to generate codes, if it enocunters a key collision it retries, returns on all other cases
func TryRetryGenerateCode(ctx context.Context, message string, duration time.Duration) (*models.PremiumCode, error) {
for {
code, err := GenerateCode(ctx, message, duration)
if err != nil && err == ErrCodeCollision {
logger.WithError(err).Error("Code collision!")
continue
}
return code, err
}
}
// GenerateCode generates a redeemable premium code with the specified duration (-1 for permanent) and message
func GenerateCode(ctx context.Context, message string, duration time.Duration) (*models.PremiumCode, error) {
key := make([]byte, 16)
_, err := rand.Read(key)
if err != nil {
return nil, errors.WithMessage(err, "GenerateCode")
}
encoded := encodeKey(key)
model := &models.PremiumCode{
Code: encoded,
Message: message,
Permanent: duration == -1,
Duration: int64(duration),
}
err = model.InsertG(ctx, boil.Infer())
if err != nil {
if cast, ok := errors.Cause(err).(*pq.Error); ok {
if cast.Code == "23505" {
return nil, ErrCodeCollision
}
}
}
return model, err
}
var keyEncoder = base32.StdEncoding.WithPadding(base32.NoPadding)
func encodeKey(rawKey []byte) string {
str := keyEncoder.EncodeToString(rawKey)
output := ""
for i, r := range str {
if i%6 == 0 && i != 0 {
output += "-"
}
output += string(r)
}
return output
}
var cmdGenerateCode = &commands.YAGCommand{
CmdCategory: commands.CategoryDebug,
HideFromCommandsPage: true,
Name: "generatepremiumcode",
Aliases: []string{"gpc"},
Description: "Generates premium codes. Bot Owner Only",
HideFromHelp: true,
RequiredArgs: 3,
RunInDM: true,
Arguments: []*dcmd.ArgDef{
{Name: "Duration", Type: &commands.DurationArg{}},
{Name: "NumCodes", Type: dcmd.Int},
{Name: "Message", Type: dcmd.String},
},
RunFunc: util.RequireOwner(func(data *dcmd.Data) (interface{}, error) {
numKeys := data.Args[1].Int()
duration := data.Args[0].Value.(time.Duration)
codes := make([]string, 0, numKeys)
if duration <= 0 {
duration = -1
}
for i := 0; i < numKeys; i++ {
code, err := TryRetryGenerateCode(data.Context(), data.Args[2].Str(), duration)
if err != nil {
return nil, err
}
codes = append(codes, code.Code)
}
dm := fmt.Sprintf("Duration: `%s`, Permanent: `%t`, Message: `%s`\n```\n", duration.String(), duration == -1, data.Args[2].Str())
for _, v := range codes {
dm += v + "\n"
}
dm += "```"
bot.SendDM(data.Author.ID, dm)
return "Check yer dms", nil
}),
}