forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquota.go
95 lines (81 loc) · 2.47 KB
/
quota.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
package auth
import (
"chat/channel"
"chat/globals"
"database/sql"
)
func (u *User) CreateInitialQuota(db *sql.DB) bool {
_, err := globals.ExecDb(db, `
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?)
`, u.GetID(db), channel.SystemInstance.GetInitialQuota(), 0.)
return err == nil
}
func (u *User) GetQuota(db *sql.DB) float32 {
var quota float32
if err := globals.QueryRowDb(db, "SELECT quota FROM quota WHERE user_id = ?", u.GetID(db)).Scan("a); err != nil {
return 0.
}
return quota
}
func (u *User) GetUsedQuota(db *sql.DB) float32 {
var quota float32
if err := globals.QueryRowDb(db, "SELECT used FROM quota WHERE user_id = ?", u.GetID(db)).Scan("a); err != nil {
return 0.
}
return quota
}
func (u *User) SetQuota(db *sql.DB, quota float32) bool {
_, err := globals.ExecDb(db, `
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quota = ?
`, u.GetID(db), quota, 0., quota)
return err == nil
}
func (u *User) SetUsedQuota(db *sql.DB, used float32) bool {
_, err := globals.ExecDb(db, `
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE used = ?
`, u.GetID(db), 0., used, used)
return err == nil
}
func (u *User) IncreaseQuota(db *sql.DB, quota float32) bool {
_, err := globals.ExecDb(db, `
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quota = quota + ?
`, u.GetID(db), quota, 0., quota)
return err == nil
}
func (u *User) IncreaseUsedQuota(db *sql.DB, used float32) bool {
_, err := globals.ExecDb(db, `
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE used = used + ?
`, u.GetID(db), 0., used, used)
return err == nil
}
func (u *User) DecreaseQuota(db *sql.DB, quota float32) bool {
_, err := globals.ExecDb(db, `
INSERT INTO quota (user_id, quota, used) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE quota = quota - ?
`, u.GetID(db), quota, 0., quota)
return err == nil
}
func (u *User) UseQuota(db *sql.DB, quota float32) bool {
if quota == 0 {
return true
}
if !u.DecreaseQuota(db, quota) {
return false
}
return u.IncreaseUsedQuota(db, quota)
}
func (u *User) PayedQuota(db *sql.DB, quota float32) bool {
if quota == 0 {
return true
}
current := u.GetQuota(db)
if quota > current {
return false
}
if !u.DecreaseQuota(db, quota) {
return false
}
return u.IncreaseUsedQuota(db, quota)
}
func (u *User) PayedQuotaAsAmount(db *sql.DB, amount float32) bool {
return u.PayedQuota(db, amount*10)
}