/
client.go
336 lines (269 loc) · 8.34 KB
/
client.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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package seatalkbot
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/tidwall/gjson"
"github.com/anandawira/seatalkbot/helper"
)
const (
// defaultHost is the default host to use on API calls when not set in the config.
defaultHost = "https://openapi.seatalk.io"
// pageSize is the page size for each API call that uses pagination
pageSize = 50
)
// Client is a Seatalkbot API caller. Client must initialize access token and update it with a new one before expired.
// You MUST call Close() on a client to avoid leaks, it will not be garbage-collected automatically when it passes out of scope.
// It is safe to share a client amongst many users.
type Client interface {
// SendPrivateMessage send a private message to a user by employeeCode.
SendPrivateMessage(ctx context.Context, employeeCode string, message Message) error
// GetGroupIDs get list of group ids joined by the bot.
GetGroupIDs(ctx context.Context) ([]string, error)
// SendGroupMessage send a message to a group by groupID.
SendGroupMessage(ctx context.Context, groupID string, message Message) (messageID string, err error)
// UpdateAccessToken gets new access token by using the credentials and store it in the client.
UpdateAccessToken(ctx context.Context) error
// AccessToken gets the underlying access token inside the client.
// It might be used to implement your own API caller that's not yet supported by this library.
AccessToken() string
// Close stops the goroutines that auto refresh the access token. It is required to call
// this function before the object passes out of scope, as it will otherwise leak memory.
Close() error
}
type client struct {
httpClient *http.Client
host string
appID string
appSecret string
accessToken string
stop context.CancelFunc
}
type Config struct {
// HTTPClient will be used for every HTTP calls made by the seatalkbot client.
HTTPClient *http.Client
// Host is the url of the bot api. It's https://openapi.seatalk.io by default.
Host string
// AppID of the seatalk bot. It can be found in the app setting at the seatalk dashboard.
AppID string
// AppSecret of the seatalk bot. It can be found in the app setting at the seatalk dashboard.
AppSecret string
}
// NewClient returns a Client with the provided *http.Client and bot credentials. It will initialize access token using
// the credentials and automatically refresh the access token every 7000 seconds (expiration is 7200 seconds).
// It is required to call Close() before the object passes out of scope, as it will otherwise leak memory.
func NewClient(config Config) (Client, error) {
if config.HTTPClient == nil {
return nil, errors.New("http client should not be nil")
}
if config.Host == "" {
config.Host = defaultHost
}
ctx, cancel := context.WithCancel(context.Background())
c := &client{
httpClient: config.HTTPClient,
host: config.Host,
appID: config.AppID,
appSecret: config.AppSecret,
accessToken: "",
stop: cancel,
}
err := helper.RunWithRetry(
func() error {
return c.UpdateAccessToken(ctx)
},
3,
1*time.Second,
)
if err != nil {
return nil, fmt.Errorf("can't initialize access token, %w", err)
}
c.runAccessTokenScheduler(ctx)
return c, nil
}
// SendPrivateMessage implements Client
func (c *client) SendPrivateMessage(ctx context.Context, employeeCode string, message Message) error {
reqBody, err := json.Marshal(sendPrivateMessageReqBody{
EmployeeCode: employeeCode,
Message: message.Message(),
})
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.host+"/messaging/v2/single_chat", bytes.NewReader(reqBody))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http response code not 200, got: %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if code := gjson.Get(string(respBody), "code"); !code.Exists() || code.Int() != 0 {
return fmt.Errorf("code in response body is not exist or not 0, resp_body: %s", respBody)
}
return nil
}
// GetGroupIDs implements Client
func (c *client) GetGroupIDs(ctx context.Context) ([]string, error) {
var groupIDs []string
var cursor string
for {
ids, nextCursor, err := c.getGroupIDs(ctx, cursor)
if err != nil {
return nil, err
}
groupIDs = append(groupIDs, ids...)
if nextCursor == "" {
break
}
}
return groupIDs, nil
}
// SendGroupMessage implements Client
func (c *client) SendGroupMessage(ctx context.Context, groupID string, message Message) (messageID string, err error) {
reqBody, err := json.Marshal(sendGroupMessageReqBody{
GroupID: groupID,
Message: message.Message(),
})
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.host+"/messaging/v2/group_chat", bytes.NewReader(reqBody))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("http response code not 200, got: %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
if code := gjson.Get(string(respBody), "code"); !code.Exists() || code.Int() != 0 {
return "", fmt.Errorf("code in response body is not exist or not 0, resp_body: %s", respBody)
}
return gjson.Get(string(respBody), "message_id").String(), nil
}
// UpdateAccessToken implements Client
func (c *client) UpdateAccessToken(ctx context.Context) error {
reqBody, err := json.Marshal(accessTokenReqBody{
AppID: c.appID,
AppSecret: c.appSecret,
})
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.host+"/auth/app_access_token", bytes.NewReader(reqBody))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status code is not 200, got: %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
accessToken := gjson.Get(string(respBody), "app_access_token")
if !accessToken.Exists() {
return fmt.Errorf("access token not exist. resp_body: %s", respBody)
}
c.accessToken = accessToken.String()
return nil
}
// AccessToken implements Client
func (c *client) AccessToken() string {
return c.accessToken
}
// Close implements Client
func (c *client) Close() error {
if c.stop != nil {
c.stop()
}
return nil
}
func (c *client) getGroupIDs(ctx context.Context, cursor string) (groupIDs []string, nextCursor string, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.host+"/messaging/v2/group_chat/joined", http.NoBody)
if err != nil {
return nil, "", err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
q := url.Values{}
q.Set("page_size", strconv.Itoa(pageSize))
if cursor != "" {
q.Set("cursor", cursor)
}
req.URL.RawQuery = q.Encode()
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("status code not 200, got: %d", resp.StatusCode)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
response := getGroupIDsRespBody{
Code: -1, // To know if the code is not found in the response body.
}
err = json.Unmarshal(respBody, &response)
if err != nil {
return nil, "", err
}
if response.Code != 0 {
return nil, "", fmt.Errorf("error code is not 0, got: %d", response.Code)
}
return response.JoinedGroupChats.GroupIDs, response.NextCursor, nil
}
func (c *client) runAccessTokenScheduler(ctx context.Context) {
go func() {
ticker := time.NewTicker(7000 * time.Second)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_ = helper.RunWithRetry(
func() error {
return c.UpdateAccessToken(ctx)
},
-1,
10*time.Second,
)
}
}
}()
}