forked from TruthHun/BookStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsign.go
More file actions
269 lines (238 loc) · 6.63 KB
/
sign.go
File metadata and controls
269 lines (238 loc) · 6.63 KB
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
package models
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
// 会员签到表
type Sign struct {
Id int
Uid int `orm:"index"` // 签到的用户id
Day int `orm:"index"` // 签到日期,如20200101
Reward int // 奖励的阅读秒数
FromApp bool
CreatedAt time.Time
}
type Rule struct {
BasicReward int
ContinuousReward int
AppReward int
MaxContinuousReward int
}
var (
_rule = &Rule{}
)
const (
signDayLayout = "20060102"
messageSigned = "您今日已签到"
messageNotExistUser = "您的账户不存在"
messageSignInnerErr = "签到失败,内部错误"
)
const (
signCacheDir = "cache/rank/sign"
signCacheFmt = "cache/rank/sign/%v-%v.json"
)
func init() {
if _, err := os.Stat(signCacheDir); err != nil {
err = os.MkdirAll(signCacheDir, os.ModePerm)
if err != nil {
panic(err)
}
}
}
func NewSign() *Sign {
return &Sign{}
}
// 多字段唯一键
func (m *Sign) TableUnique() [][]string {
return [][]string{
[]string{"uid", "day"},
}
}
// 今天是否已签到
func (m *Sign) IsSignToday(uid int) bool {
s := &Sign{}
orm.NewOrm().QueryTable(m).Filter("uid", uid).Filter("day", time.Now().Format(signDayLayout)).One(s, "id")
return s.Id > 0
}
func (m *Sign) LatestSignTime(uid int) (date int) {
s := &Sign{}
err := orm.NewOrm().QueryTable(m).Filter("uid", uid).OrderBy("-id").One(s)
if err != nil {
return
}
return int(s.CreatedAt.Unix())
}
// 是否未断签
func (m *Sign) IsContinuousSign(uid int) bool {
s := &Sign{}
now := time.Now()
yesterday := now.Add(-24 * time.Hour).Format(signDayLayout)
orm.NewOrm().QueryTable(m).Filter("uid", uid).Filter("day", yesterday).One(s)
return s.Id > 0
}
// 执行签到。使用事务
func (m *Sign) Sign(uid int, fromApp bool) (reward int, err error) {
s := &Sign{}
o := orm.NewOrm()
now := time.Now()
day, _ := strconv.Atoi(now.Format(signDayLayout))
// 1. 检测用户有没有签到
o.QueryTable(s).Filter("uid", uid).Filter("day", day).One(s)
if m.IsSignToday(uid) {
err = errors.New(messageSigned)
return
}
isContinuousSign := m.IsContinuousSign(uid) // 昨天有没有断签
// 2. 查询用户签到了多少天
user := NewMember()
cols := []string{"member_id", "total_sign", "total_continuous_sign", "history_total_continuous_sign"}
o.QueryTable(user).Filter("member_id", uid).One(user, cols...)
if user.MemberId < 0 {
err = errors.New(messageNotExistUser)
return
}
// 3. 查询奖励规则
rule := s.GetSignRule()
// 4. 更新用户签到记录、签到天数和连续签到天数
o.Begin()
defer func() {
if err != nil {
beego.Error(err)
err = errors.New(messageSignInnerErr)
o.Rollback()
} else {
o.Commit()
}
}()
user.TotalSign += 1
s.Day = day
s.Uid = uid
s.CreatedAt = now
s.FromApp = fromApp
// 奖励计算
if isContinuousSign { //连续签到
user.TotalContinuousSign += 1
extra := user.TotalContinuousSign * rule.ContinuousReward
if extra >= rule.MaxContinuousReward {
extra = rule.MaxContinuousReward
}
s.Reward = rule.BasicReward + extra
} else { // 未连续签到
user.TotalContinuousSign = 1
s.Reward = rule.BasicReward + rule.ContinuousReward
}
if user.TotalContinuousSign > user.HistoryTotalContinuousSign {
user.HistoryTotalContinuousSign = user.TotalContinuousSign
}
if fromApp {
s.Reward = s.Reward + rule.AppReward
}
if _, err = o.Insert(s); err != nil {
return
}
_, err = o.QueryTable(user).Filter("member_id", user.MemberId).Update(orm.Params{
"total_sign": user.TotalSign,
"total_continuous_sign": user.TotalContinuousSign,
"history_total_continuous_sign": user.HistoryTotalContinuousSign,
})
rt := NewReadingTime()
o.QueryTable(rt).Filter("uid", uid).Filter("day", now.Format(signDayLayout)).One(rt)
if rt.Id > 0 {
rt.Duration += s.Reward
_, err = o.Update(rt)
} else {
rt.Day, _ = strconv.Atoi(now.Format(signDayLayout))
rt.Uid = uid
rt.Duration = s.Reward
_, err = o.Insert(rt)
}
reward = s.Reward
return
}
// 获取签到奖励规则
func (m *Sign) GetSignRule() (r *Rule) {
return _rule
}
// 更新签到奖励规则
func (m *Sign) UpdateSignRule() {
ops := []string{"SIGN_BASIC_REWARD", "SIGN_APP_REWARD", "SIGN_CONTINUOUS_REWARD", "SIGN_CONTINUOUS_MAX_REWARD"}
for _, op := range ops {
num, _ := strconv.Atoi(GetOptionValue(op, ""))
switch op {
case "SIGN_BASIC_REWARD":
_rule.BasicReward = num
case "SIGN_APP_REWARD":
_rule.AppReward = num
case "SIGN_CONTINUOUS_REWARD":
_rule.ContinuousReward = num
case "SIGN_CONTINUOUS_MAX_REWARD":
_rule.MaxContinuousReward = num
}
}
}
func (m *Sign) Sorted(limit int, orderField string, withCache ...bool) (members []Member) {
var b []byte
cache := false
if len(withCache) > 0 {
cache = withCache[0]
}
file := fmt.Sprintf(signCacheFmt, orderField, limit)
if cache {
if info, err := os.Stat(file); err == nil && time.Now().Sub(info.ModTime()).Seconds() <= cacheTime {
// 文件存在,且在缓存时间内
if b, err = ioutil.ReadFile(file); err == nil {
json.Unmarshal(b, &members)
if len(members) > 0 {
return
}
}
}
}
member := NewMember()
o := orm.NewOrm()
fields := []string{"member_id", "account", "nickname", "total_continuous_sign", "total_sign", "total_reading_time", "history_total_continuous_sign"}
o.QueryTable(member).OrderBy("-"+orderField).Limit(limit).All(&members, fields...)
if cache && len(members) > 0 {
b, _ = json.Marshal(members)
ioutil.WriteFile(file, b, os.ModePerm)
}
return
}
func (*Sign) LatestOne(uid int) (s Sign) {
orm.NewOrm().QueryTable(&s).Filter("uid", uid).OrderBy("-id").One(&s)
return
}
func (m *Sign) SortedByPeriod(limit int, prd period, withCache ...bool) (members []Member) {
var b []byte
cache := false
if len(withCache) > 0 {
cache = withCache[0]
}
file := fmt.Sprintf(signCacheFmt, "month-"+prd, limit)
if cache {
if info, err := os.Stat(file); err == nil && time.Now().Sub(info.ModTime()).Seconds() <= cacheTime {
// 文件存在,且在缓存时间内
if b, err = ioutil.ReadFile(file); err == nil {
json.Unmarshal(b, &members)
if len(members) > 0 {
return
}
}
}
}
sqlSort := "SELECT t.uid member_id,count(t.id) total_sign,m.account,m.avatar,m.nickname FROM `md_sign` t left JOIN md_members m on t.uid=m.member_id WHERE t.day>=? and t.day<=? GROUP BY t.uid ORDER BY total_sign desc limit ?"
start, end := getTimeRange(time.Now(), prd)
orm.NewOrm().Raw(sqlSort, start, end, limit).QueryRows(&members)
if cache && len(members) > 0 {
b, _ = json.Marshal(members)
ioutil.WriteFile(file, b, os.ModePerm)
}
return
}