-
Notifications
You must be signed in to change notification settings - Fork 1
/
vk.go
165 lines (145 loc) · 3.22 KB
/
vk.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/reconquest/hierr-go"
"io/ioutil"
"net/http"
"net/url"
"strings"
"bytes"
)
type VKClient struct {
client *http.Client
version string
}
type VKCommand struct {
AccessToken string
Method string
Payload interface{}
}
type VKCommands []VKCommand
type VKCommandsChunk struct {
AccessToken string
Commands []VKCommand
}
type VKExecuteResponsePayload struct {
Response []interface{} `json:"response"`
}
func NewVKClient(rps int, version string) *VKClient {
client := &http.Client{Transport: &http.Transport{
MaxIdleConnsPerHost: rps * 2,
MaxIdleConns: rps * 2,
}}
return &VKClient{
client: client,
version: version,
}
}
func (vk *VKClient) Run(chunksCh <-chan VKCommandsChunk) {
go func() {
for {
select {
case chunk := <-chunksCh:
go func(chunk VKCommandsChunk) {
err, cnt := vk.execute(chunk.AccessToken, chunk.Commands)
if err != nil {
e := hierr.Errorf(
err,
"can't execute chunk of commands: %+v",
chunk,
)
if cnt > 0 {
logger.Warning(e)
} else {
logger.Error(e)
}
}
}(chunk)
}
}
}()
}
func (vk *VKClient) execute(
accessToken string,
commands VKCommands,
) (error, int) {
total := len(commands)
logger.Debugf("sending execute request with %d commands", total)
code, err := compileCode(commands)
if err != nil {
return hierr.Errorf(err, "unable to compile code"), 0
}
form := url.Values{"code": []string{code}}
request, err := http.NewRequest(
"POST",
"https://api.vk.com/method/execute",
strings.NewReader(form.Encode()),
)
if err != nil {
return hierr.Errorf(err, "can't create http request"), 0
}
query := request.URL.Query()
query.Add("access_token", accessToken)
query.Add("version", vk.version)
request.URL.RawQuery = query.Encode()
response, err := vk.client.Do(request)
if err != nil {
return hierr.Errorf(err, "can't do http request"), 0
}
defer response.Body.Close()
content, err := ioutil.ReadAll(response.Body)
if err != nil {
return hierr.Errorf(err, "can't read response body"), 0
}
payload := VKExecuteResponsePayload{}
err = json.Unmarshal([]byte(content), &payload)
if err != nil {
return hierr.Errorf(err, "can't json unmarshal response body"), 0
}
failed := payload.getFailed()
var e error
if failed > 0 {
e = errors.New(fmt.Sprintf(
"failed to deliver %d/%d messages: %s",
failed,
total,
content,
))
}
return e, total - failed
}
func compileCode(commands []VKCommand) (string, error) {
commandsCode := make([]string, len(commands))
for i, command := range commands {
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(command.Payload)
if err != nil {
return "", hierr.Errorf(
err,
"can't marshal command payload %+v",
command.Payload,
)
}
commandsCode[i] = fmt.Sprintf(
"%s(%s)",
command.Method,
string(buf.Bytes()),
)
}
code := fmt.Sprintf("return [%s];", strings.Join(commandsCode, ","))
return code, nil
}
func (payload *VKExecuteResponsePayload) getFailed() int {
cnt := 0
for _, id := range payload.Response {
switch id.(type) {
case bool:
cnt++
}
}
return cnt
}