-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
pool.go
111 lines (96 loc) · 1.94 KB
/
pool.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
package local_pool
import (
"errors"
"github.com/Sora233/DDBOT/image_pool"
localutils "github.com/Sora233/DDBOT/utils"
"github.com/Sora233/MiraiGo-Template/utils"
"io/ioutil"
"math/rand"
"os"
"sync"
"time"
)
var logger = utils.GetModuleLogger("local_pool")
type LocalPool struct {
freshMutex *sync.Mutex
imageDir string
imageList []string
}
type Image struct {
Path string
}
func (i *Image) Content() ([]byte, error) {
return ioutil.ReadFile(i.Path)
}
func (pool *LocalPool) Get(opts ...image_pool.OptionFunc) ([]image_pool.Image, error) {
if pool == nil {
return nil, errors.New("pool status down")
}
pool.freshMutex.Lock()
defer pool.freshMutex.Unlock()
if len(pool.imageList) == 0 {
return nil, errors.New("no image")
}
var (
result []image_pool.Image
option = make(image_pool.Option)
num = 1
)
for _, opt := range opts {
opt(option)
}
for k, v := range option {
switch k {
case "num":
_v, ok := v.(int)
if ok {
num = _v
}
}
}
for i := 0; i < num; i++ {
result = append(result, &Image{
Path: pool.imageList[rand.Intn(len(pool.imageList))],
})
}
return result, nil
}
func (pool *LocalPool) RefreshImage() error {
pool.freshMutex.Lock()
defer pool.freshMutex.Unlock()
files, err := localutils.FilePathWalkDir(pool.imageDir)
if err != nil {
return err
} else {
pool.imageList = files
}
return nil
}
func NewLocalPool(path string) (*LocalPool, error) {
if i, err := os.Stat(path); err != nil || i == nil {
return nil, errors.New("invalid path")
}
pool := &LocalPool{
imageDir: path,
freshMutex: new(sync.Mutex),
imageList: make([]string, 0),
}
err := pool.RefreshImage()
if err != nil {
return nil, err
}
go func() {
timer := time.NewTimer(time.Minute)
for {
select {
case <-timer.C:
err := pool.RefreshImage()
if err != nil {
logger.Errorf("local pool refresh failed %v", err)
}
timer.Reset(time.Minute)
}
}
}()
return pool, nil
}