Skip to content

Commit 72ed129

Browse files
committed
🔥 ✨ 优化 setutime
1 parent fa973a9 commit 72ed129

File tree

1 file changed

+104
-92
lines changed

1 file changed

+104
-92
lines changed

plugin_setutime/setu_geter.go

Lines changed: 104 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
package setutime
33

44
import (
5+
"errors"
56
"fmt"
67
"strconv"
78
"strings"
@@ -26,43 +27,24 @@ import (
2627

2728
// Pools 图片缓冲池
2829
type imgpool struct {
29-
Lock sync.Mutex
30-
DB *sql.Sqlite
31-
Path string
32-
Group int64
33-
List []string
34-
Max int
35-
Pool map[string][]*pixiv.Illust
36-
Form int64
30+
lock sync.Mutex
31+
db *sql.Sqlite
32+
path string
33+
max int
34+
pool map[string][]*pixiv.Illust
3735
}
3836

39-
// NewPoolsCache 返回一个缓冲池对象
40-
func newPools() *imgpool {
41-
cache := &imgpool{
42-
DB: &sql.Sqlite{DBPath: "data/SetuTime/SetuTime.db"},
43-
Path: pixiv.CacheDir,
44-
Group: 0,
45-
List: []string{"涩图", "二次元", "风景", "车万"}, // 可以自己加类别,得自己加图片进数据库
46-
Max: 10,
47-
Pool: map[string][]*pixiv.Illust{},
48-
Form: 0,
49-
}
50-
// 如果数据库不存在则下载
51-
_, _ = fileutil.GetLazyData(cache.DB.DBPath, false, false)
52-
for i := range cache.List {
53-
if err := cache.DB.Create(cache.List[i], &pixiv.Illust{}); err != nil {
54-
panic(err)
55-
}
37+
func (i *imgpool) list() (l []string) {
38+
var err error
39+
l, err = i.db.ListTables()
40+
if err != nil {
41+
l = []string{"涩图", "二次元", "风景", "车万"}
5642
}
57-
return cache
43+
return l
5844
}
5945

60-
var (
61-
pool *imgpool
62-
limit = rate.NewManager(time.Minute*1, 5)
63-
)
64-
6546
func init() { // 插件主体
47+
limit := rate.NewManager(time.Minute*1, 5)
6648
engine := control.Register("setutime", order.PrioSetuTime, &control.Options{
6749
DisableOnDefault: false,
6850
Help: "涩图\n" +
@@ -72,29 +54,35 @@ func init() { // 插件主体
7254
"- >setu status",
7355
})
7456
process.SleepAbout1sTo2s()
75-
pool = newPools()
76-
engine.OnRegex(`^来份(.*)$`, rule.FirstValueInList(pool.List)).SetBlock(true).
57+
pool := func() *imgpool {
58+
cache := &imgpool{
59+
db: &sql.Sqlite{DBPath: "data/SetuTime/SetuTime.db"},
60+
path: pixiv.CacheDir,
61+
max: 10,
62+
pool: map[string][]*pixiv.Illust{},
63+
}
64+
// 如果数据库不存在则下载
65+
_, _ = fileutil.GetLazyData(cache.db.DBPath, false, false)
66+
err := cache.db.Open()
67+
if err != nil {
68+
panic(err)
69+
}
70+
for _, imgtype := range cache.list() {
71+
if err := cache.db.Create(imgtype, &pixiv.Illust{}); err != nil {
72+
panic(err)
73+
}
74+
}
75+
return cache
76+
}()
77+
engine.OnRegex(`^来份(.*)$`, rule.FirstValueInList(pool.list())).SetBlock(true).
7778
Handle(func(ctx *zero.Ctx) {
7879
if !limit.Load(ctx.Event.UserID).Acquire() {
7980
ctx.SendChain(message.Text("请稍后重试0x0..."))
8081
return
8182
}
8283
var imgtype = ctx.State["regex_matched"].([]string)[1]
8384
// 补充池子
84-
go func() {
85-
times := math.Min(pool.Max-pool.size(imgtype), 2)
86-
for i := 0; i < times; i++ {
87-
illust := &pixiv.Illust{}
88-
// 查询出一张图片
89-
if err := pool.DB.Pick(imgtype, illust); err != nil {
90-
ctx.SendChain(message.Text("ERROR: ", err))
91-
continue
92-
}
93-
// 向缓冲池添加一张图片
94-
pool.push(ctx, imgtype, illust)
95-
process.SleepAbout1sTo2s()
96-
}
97-
}()
85+
go pool.fill(ctx, imgtype)
9886
// 如果没有缓存,阻塞10秒
9987
if pool.size(imgtype) == 0 {
10088
ctx.SendChain(message.Text("INFO: 正在填充弹药......"))
@@ -105,50 +93,33 @@ func init() { // 插件主体
10593
}
10694
}
10795
// 从缓冲池里抽一张
108-
if id := ctx.SendChain(message.Image(file(pool.pop(imgtype)))); id.ID() == 0 {
96+
if id := ctx.SendChain(message.Image(pool.popfile(imgtype))); id.ID() == 0 {
10997
ctx.SendChain(message.Text("ERROR: 可能被风控了"))
11098
}
11199
})
112100

113-
engine.OnRegex(`^添加(.*?)(\d+)$`, rule.FirstValueInList(pool.List), zero.SuperUserPermission).SetBlock(true).
101+
engine.OnRegex(`^添加(.*?)(\d+)$`, zero.SuperUserPermission).SetBlock(true).
114102
Handle(func(ctx *zero.Ctx) {
115103
var (
116104
imgtype = ctx.State["regex_matched"].([]string)[1]
117105
id, _ = strconv.ParseInt(ctx.State["regex_matched"].([]string)[2], 10, 64)
118106
)
119-
ctx.SendChain(message.Text("少女祈祷中......"))
120-
// 查询P站插图信息
121-
illust, err := pixiv.Works(id)
107+
err := pool.add(ctx, imgtype, id)
122108
if err != nil {
123-
ctx.SendChain(message.Text("ERROR: ", err))
124-
return
125-
}
126-
// 下载插画
127-
if _, err := illust.DownloadToCache(0, strconv.FormatInt(id, 10)+"_p0"); err != nil {
128-
ctx.SendChain(message.Text("ERROR: ", err))
129-
return
130-
}
131-
// 发送到发送者
132-
if id := ctx.SendChain(message.Image(file(illust))); id.ID() == 0 {
133-
ctx.SendChain(message.Text("ERROR: 可能被风控,发送失败"))
109+
ctx.SendChain(message.Text("ERROR:", err))
134110
return
135111
}
136-
// 添加插画到对应的数据库table
137-
if err := pool.DB.Insert(imgtype, illust); err != nil {
138-
ctx.SendChain(message.Text("ERROR: ", err))
139-
return
140-
}
141-
ctx.SendChain(message.Text("添加成功"))
112+
ctx.SendChain(message.Text("成功向分类", imgtype, "添加图片", id))
142113
})
143114

144-
engine.OnRegex(`^删除(.*?)(\d+)$`, rule.FirstValueInList(pool.List), zero.SuperUserPermission).SetBlock(true).
115+
engine.OnRegex(`^删除(.*?)(\d+)$`, rule.FirstValueInList(pool.list()), zero.SuperUserPermission).SetBlock(true).
145116
Handle(func(ctx *zero.Ctx) {
146117
var (
147118
imgtype = ctx.State["regex_matched"].([]string)[1]
148119
id, _ = strconv.ParseInt(ctx.State["regex_matched"].([]string)[2], 10, 64)
149120
)
150121
// 查询数据库
151-
if err := pool.DB.Del(imgtype, fmt.Sprintf("WHERE pid=%d", id)); err != nil {
122+
if err := pool.remove(imgtype, id); err != nil {
152123
ctx.SendChain(message.Text("ERROR: ", err))
153124
return
154125
}
@@ -159,13 +130,13 @@ func init() { // 插件主体
159130
engine.OnFullMatchGroup([]string{">setu status"}).SetBlock(true).
160131
Handle(func(ctx *zero.Ctx) {
161132
state := []string{"[SetuTime]"}
162-
for i := range pool.List {
163-
num, err := pool.DB.Count(pool.List[i])
133+
for _, imgtype := range pool.list() {
134+
num, err := pool.db.Count(imgtype)
164135
if err != nil {
165136
num = 0
166137
}
167138
state = append(state, "\n")
168-
state = append(state, pool.List[i])
139+
state = append(state, imgtype)
169140
state = append(state, ": ")
170141
state = append(state, fmt.Sprintf("%d", num))
171142
}
@@ -175,16 +146,9 @@ func init() { // 插件主体
175146

176147
// size 返回缓冲池指定类型的现有大小
177148
func (p *imgpool) size(imgtype string) int {
178-
return len(p.Pool[imgtype])
149+
return len(p.pool[imgtype])
179150
}
180151

181-
/*
182-
// isFull 返回缓冲池指定类型是否已满
183-
func (p *imgpool) isFull(imgtype string) bool {
184-
return len(p.Pool[imgtype]) >= p.Max
185-
}*/
186-
187-
// push 向缓冲池插入一张图片
188152
func (p *imgpool) push(ctx *zero.Ctx, imgtype string, illust *pixiv.Illust) {
189153
u := illust.ImageUrls[0]
190154
n := u[strings.LastIndex(u, "/")+1 : len(u)-4]
@@ -199,31 +163,30 @@ func (p *imgpool) push(ctx *zero.Ctx, imgtype string, illust *pixiv.Illust) {
199163
m.SetFile(fileutil.BOTPATH + "/" + f)
200164
_, _ = m.Push(ctxext.SendToSelf(ctx), ctxext.GetMessage(ctx))
201165
}
202-
p.Lock.Lock()
203-
p.Pool[imgtype] = append(p.Pool[imgtype], illust)
204-
p.Lock.Unlock()
166+
p.lock.Lock()
167+
p.pool[imgtype] = append(p.pool[imgtype], illust)
168+
p.lock.Unlock()
205169
}
206170

207-
// Push 在缓冲池拿出一张图片
208171
func (p *imgpool) pop(imgtype string) (illust *pixiv.Illust) {
209-
p.Lock.Lock()
210-
defer p.Lock.Unlock()
172+
p.lock.Lock()
173+
defer p.lock.Unlock()
211174
if p.size(imgtype) == 0 {
212175
return
213176
}
214-
illust = p.Pool[imgtype][0]
215-
p.Pool[imgtype] = p.Pool[imgtype][1:]
177+
illust = p.pool[imgtype][0]
178+
p.pool[imgtype] = p.pool[imgtype][1:]
216179
return
217180
}
218181

219-
func file(i *pixiv.Illust) string {
182+
func (p *imgpool) file(i *pixiv.Illust) string {
220183
u := i.ImageUrls[0]
221184
m, err := imagepool.GetImage(u[strings.LastIndex(u, "/")+1 : len(u)-4])
222185
if err == nil {
223186
return m.String()
224187
}
225188
filename := fmt.Sprint(i.Pid) + "_p0"
226-
filepath := fileutil.BOTPATH + `/` + pool.Path + filename
189+
filepath := fileutil.BOTPATH + `/` + p.path + filename
227190
if fileutil.IsExist(filepath + ".jpg") {
228191
return `file:///` + filepath + ".jpg"
229192
}
@@ -235,3 +198,52 @@ func file(i *pixiv.Illust) string {
235198
}
236199
return ""
237200
}
201+
202+
func (p *imgpool) popfile(imgtype string) string {
203+
return p.file(p.pop(imgtype))
204+
}
205+
206+
// fill 补充池子
207+
func (p *imgpool) fill(ctx *zero.Ctx, imgtype string) {
208+
times := math.Min(p.max-p.size(imgtype), 2)
209+
for i := 0; i < times; i++ {
210+
illust := &pixiv.Illust{}
211+
// 查询出一张图片
212+
if err := p.db.Pick(imgtype, illust); err != nil {
213+
ctx.SendChain(message.Text("ERROR: ", err))
214+
continue
215+
}
216+
// 向缓冲池添加一张图片
217+
p.push(ctx, imgtype, illust)
218+
process.SleepAbout1sTo2s()
219+
}
220+
}
221+
222+
func (p *imgpool) add(ctx *zero.Ctx, imgtype string, id int64) error {
223+
if err := p.db.Create(imgtype, &pixiv.Illust{}); err != nil {
224+
return err
225+
}
226+
ctx.SendChain(message.Text("少女祈祷中......"))
227+
// 查询P站插图信息
228+
illust, err := pixiv.Works(id)
229+
if err != nil {
230+
return err
231+
}
232+
// 下载插画
233+
if _, err := illust.DownloadToCache(0, strconv.FormatInt(id, 10)+"_p0"); err != nil {
234+
return err
235+
}
236+
// 发送到发送者
237+
if id := ctx.SendChain(message.Image(p.file(illust))); id.ID() == 0 {
238+
return errors.New("可能被风控,发送失败")
239+
}
240+
// 添加插画到对应的数据库table
241+
if err := p.db.Insert(imgtype, illust); err != nil {
242+
return err
243+
}
244+
return nil
245+
}
246+
247+
func (p *imgpool) remove(imgtype string, id int64) error {
248+
return p.db.Del(imgtype, fmt.Sprintf("WHERE pid=%d", id))
249+
}

0 commit comments

Comments
 (0)