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
270
271
272
273
274
|
/*
Package longpoll implements Bots Long Poll API.
See more https://vk.com/dev/bots_longpoll
*/
package longpoll // import "github.com/SevereCloud/vksdk/v2/longpoll-bot"
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"github.com/SevereCloud/vksdk/v2"
"github.com/SevereCloud/vksdk/v2/api"
"github.com/SevereCloud/vksdk/v2/events"
"github.com/SevereCloud/vksdk/v2/internal"
)
// Response struct.
type Response struct {
Ts string `json:"ts"`
Updates []events.GroupEvent `json:"updates"`
Failed int `json:"failed"`
}
// LongPoll struct.
type LongPoll struct {
GroupID int
Server string
Key string
Ts string
Wait int
VK *api.VK
Client *http.Client
cancel context.CancelFunc
funcFullResponseList []func(Response)
events.FuncList
}
// NewLongPoll returns a new LongPoll.
//
// The LongPoll will use the http.DefaultClient.
// This means that if the http.DefaultClient is modified by other components
// of your application the modifications will be picked up by the SDK as well.
func NewLongPoll(vk *api.VK, groupID int) (*LongPoll, error) {
lp := &LongPoll{
VK: vk,
GroupID: groupID,
Wait: 25,
Client: http.DefaultClient,
}
lp.FuncList = *events.NewFuncList()
err := lp.updateServer(true)
return lp, err
}
// NewLongPollCommunity returns a new LongPoll for community token.
//
// The LongPoll will use the http.DefaultClient.
// This means that if the http.DefaultClient is modified by other components
// of your application the modifications will be picked up by the SDK as well.
func NewLongPollCommunity(vk *api.VK) (*LongPoll, error) {
resp, err := vk.GroupsGetByID(nil)
if err != nil {
return nil, err
}
lp := &LongPoll{
VK: vk,
GroupID: resp[0].ID,
Wait: 25,
Client: http.DefaultClient,
}
lp.FuncList = *events.NewFuncList()
err = lp.updateServer(true)
return lp, err
}
func (lp *LongPoll) updateServer(updateTs bool) error {
params := api.Params{
"group_id": lp.GroupID,
}
serverSetting, err := lp.VK.GroupsGetLongPollServer(params)
if err != nil {
return err
}
lp.Key = serverSetting.Key
lp.Server = serverSetting.Server
if updateTs {
lp.Ts = serverSetting.Ts
}
return nil
}
func (lp *LongPoll) check(ctx context.Context) (response Response, err error) {
u := fmt.Sprintf("%s?act=a_check&key=%s&ts=%s&wait=%d", lp.Server, lp.Key, lp.Ts, lp.Wait)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return response, err
}
resp, err := lp.Client.Do(req)
if err != nil {
return response, err
}
defer resp.Body.Close()
response, err = parseResponse(resp.Body)
if err != nil {
return response, err
}
err = lp.checkResponse(response)
return response, err
}
func parseResponse(reader io.Reader) (response Response, err error) {
decoder := json.NewDecoder(reader)
for decoder.More() {
token, err := decoder.Token()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return response, err
}
t, ok := token.(string)
if !ok {
continue
}
switch t {
case "failed":
raw, err := decoder.Token()
if err != nil {
return response, err
}
response.Failed = int(raw.(float64))
case "updates":
var updates []events.GroupEvent
err = decoder.Decode(&updates)
if err != nil {
return response, err
}
response.Updates = updates
case "ts":
// can be a number in the response with "failed" field: {"ts":8,"failed":1}
// or string, e.g. {"ts":"8","updates":[]}
rawTs, err := decoder.Token()
if err != nil {
return response, err
}
if ts, isNumber := rawTs.(float64); isNumber {
response.Ts = strconv.Itoa(int(ts))
} else {
response.Ts = rawTs.(string)
}
}
}
return response, err
}
func (lp *LongPoll) checkResponse(response Response) (err error) {
switch response.Failed {
case 0:
lp.Ts = response.Ts
case 1:
lp.Ts = response.Ts
case 2:
err = lp.updateServer(false)
case 3:
err = lp.updateServer(true)
default:
err = &Failed{response.Failed}
}
return
}
func (lp *LongPoll) autoSetting(ctx context.Context) error {
params := api.Params{
"group_id": lp.GroupID,
"enabled": true,
"api_version": vksdk.API,
}.WithContext(ctx)
for _, event := range lp.ListEvents() {
params[string(event)] = true
}
// Updating LongPoll settings
_, err := lp.VK.GroupsSetLongPollSettings(params)
return err
}
// Run handler.
func (lp *LongPoll) Run() error {
return lp.RunWithContext(context.Background())
}
// RunWithContext handler.
func (lp *LongPoll) RunWithContext(ctx context.Context) error {
return lp.run(ctx)
}
func (lp *LongPoll) run(ctx context.Context) error {
ctx, lp.cancel = context.WithCancel(ctx)
if err := lp.autoSetting(ctx); err != nil {
return err
}
for {
select {
case _, ok := <-ctx.Done():
if !ok {
return nil
}
default:
resp, err := lp.check(ctx)
if err != nil {
return err
}
ctx = context.WithValue(ctx, internal.LongPollTsKey, resp.Ts)
for _, event := range resp.Updates {
err = lp.Handler(ctx, event)
if err != nil {
return err
}
}
for _, f := range lp.funcFullResponseList {
f(resp)
}
}
}
}
// Shutdown gracefully shuts down the longpoll without interrupting any active connections.
func (lp *LongPoll) Shutdown() {
if lp.cancel != nil {
lp.cancel()
}
}
// FullResponse handler.
func (lp *LongPoll) FullResponse(f func(Response)) {
lp.funcFullResponseList = append(lp.funcFullResponseList, f)
}
|