-
Notifications
You must be signed in to change notification settings - Fork 1
/
apiserver.go
203 lines (182 loc) · 4.72 KB
/
apiserver.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
197
198
199
200
201
202
203
package server
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/eternnoir/gbf-bike/bike"
"github.com/gorilla/websocket"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
var log = logrus.WithFields(logrus.Fields{
"system": "GBF-Bike",
"module": "APIServer",
})
var (
ErrConvertTimeout = errors.New("Can not convert timeout value")
)
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
)
var welcomeInfo = map[string]interface{}{
"welcome": "Welcome use gbf bike.",
"desc": "GBF captains need a bike. `gbf-bike` helps captain find raid's room id from twitter.",
"usage": "https://github.com/eternnoir/gbf-bike",
"version": "1.9487",
}
var DefaultTimeout = "5"
func NewApi(port string) *ApiServer {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{echo.GET},
}))
return &ApiServer{hs: e, revChanList: make(map[chan (*bike.BattleInfo)]bool), port: port}
}
type ApiServer struct {
hs *echo.Echo
port string
revChanList map[chan (*bike.BattleInfo)]bool
}
func (api *ApiServer) Start() error {
e := api.hs
e.GET("/", api.welcome)
e.GET("/query", api.query)
e.GET("/ws", api.webSocket)
e.Logger.Fatal(e.Start(":" + api.port))
return nil
}
func (api *ApiServer) NewBattleInfo(battleInfo *bike.BattleInfo) error {
log.Debugf("%#v", battleInfo)
for infoCh, alive := range api.revChanList {
if !alive {
delete(api.revChanList, infoCh)
continue
}
go fireBattleInfo(infoCh, battleInfo)
}
return nil
}
func fireBattleInfo(ch chan *bike.BattleInfo, battleInfo *bike.BattleInfo) {
defer func() {
if r := recover(); r != nil {
log.Errorf("Recovery in %#v. ", r)
}
}()
select {
case ch <- battleInfo:
log.Debugf("Push battle info to channel %#v", battleInfo)
}
}
func (api *ApiServer) welcome(c echo.Context) error {
return c.JSON(http.StatusOK, welcomeInfo)
}
func (api *ApiServer) query(c echo.Context) error {
// Get team and member from the query string
level := c.QueryParam("level")
mobs := c.QueryParam("mobs")
timeoutStr := c.QueryParam("timeout")
if timeoutStr == "" {
timeoutStr = DefaultTimeout
}
timeout, err := convertTimeout(timeoutStr)
if err != nil {
return ErrConvertTimeout
}
recCh := make(chan (*bike.BattleInfo))
api.revChanList[recCh] = true
stopCh := make(chan bool)
defer close(recCh)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(timeout))
defer cancel()
result := api.pushBattleToList(ctx, level, mobs, recCh, stopCh)
return c.JSON(http.StatusOK, result)
}
func (api *ApiServer) webSocket(c echo.Context) error {
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
log.Error(err.Error())
return err
}
defer ws.Close()
level := convertStringMap(c.QueryParam("level"))
mobs := convertStringMap(c.QueryParam("mobs"))
recCh := make(chan (*bike.BattleInfo))
defer func() {
close(recCh)
api.revChanList[recCh] = false
}()
api.revChanList[recCh] = true
for {
mission := <-recCh
if isWantedMission(level, mobs, mission) {
err := ws.WriteJSON(mission)
if err != nil {
log.Errorf("WebSocket write error. %s", err.Error())
return err
}
}
}
}
func (api *ApiServer) pushBattleToList(ctx context.Context, level, mobs string, ch chan (*bike.BattleInfo), stopCh chan bool) []*bike.BattleInfo {
list := make([]*bike.BattleInfo, 0)
mobMap := convertStringMap(mobs)
levelMap := convertStringMap(level)
for {
select {
case <-ctx.Done():
api.revChanList[ch] = false
return list
case bi := <-ch:
if isWantedMission(levelMap, mobMap, bi) {
log.Debug("Push BattleInfo to list")
list = append(list, bi)
}
}
}
}
func isWantedMission(levels, mobs map[string]struct{}, info *bike.BattleInfo) bool {
return isWantedLevel(levels, info) && isWantedMob(mobs, info)
}
func isWantedMob(mobs map[string]struct{}, info *bike.BattleInfo) bool {
if len(mobs) == 0 {
return true
}
_, ok := mobs[info.MobName]
return ok
}
func isWantedLevel(levels map[string]struct{}, info *bike.BattleInfo) bool {
if len(levels) == 0 {
return true
}
_, ok := levels[info.Level]
return ok
}
func convertStringMap(mobstr string) map[string]struct{} {
if mobstr == "" {
return make(map[string]struct{})
}
moblist := strings.Split(mobstr, ",")
ret := make(map[string]struct{})
for _, mobname := range moblist {
ret[mobname] = struct{}{}
}
return ret
}
func convertTimeout(timeout string) (int64, error) {
i, err := strconv.Atoi(timeout)
if err != nil {
return int64(0), err
}
return int64(i), nil
}