-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
343 lines (263 loc) · 7.62 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
337
338
339
340
341
342
343
package zendesk
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
const (
httpSecure string = "https"
websocketSecure string = "wss"
)
const (
RequestHeaderRetryAttempts string = "X-Attempt-Count"
)
type client struct {
httpClientForZendesk *http.Client
httpClientForZopim *http.Client
zendeskAuth authentication
chatCredentials ChatCredentials
chatToken *chatToken
chatMutex *sync.Mutex
subDomain string
userAgent string
requestPreProcessors []RequestPreProcessor
}
func (c *client) doWithRetry(request *http.Request, target any) error {
attempts := 0
maxAttempts := 3
retryAfter := int64(0)
var latestAttemptError error
for attempts < maxAttempts {
attempts++
// Set the current attempt count in the request header, so that consumers of the library can identify when a request is being retried
request.Header.Set(RequestHeaderRetryAttempts, fmt.Sprintf("%d", attempts))
time.Sleep(time.Duration(retryAfter) * time.Second)
latestAttemptError = c.do(request, target)
if latestAttemptError == nil {
return nil
}
// Check to see if the error is a network error
networkErr, ok := latestAttemptError.(*url.Error)
if ok {
// If the error is determined temporary, retry
if networkErr.Temporary() {
continue
}
return networkErr
}
zendeskErr, ok := latestAttemptError.(*Error)
if !ok {
return latestAttemptError
}
if zendeskErr.Response.StatusCode != http.StatusTooManyRequests {
return latestAttemptError
}
// Check for a "retry-after" header and then continue
retryAfterString := zendeskErr.Response.Header.Get("retry-after")
if retryAfterString != "" {
var err error
retryAfter, err = strconv.ParseInt(retryAfterString, 10, 64)
if err != nil {
return err
}
}
continue
}
return latestAttemptError
}
func (c *client) do(request *http.Request, target any) error {
if request.URL.Host == "" {
request.URL.Host = fmt.Sprintf("%s.zendesk.com", c.subDomain)
}
request.URL.Scheme = httpSecure
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", c.userAgent)
if request.Header.Get("Content-Type") == "" {
request.Header.Set("Content-Type", "application/json")
}
for _, requestPreProcessor := range c.requestPreProcessors {
if err := requestPreProcessor.ProcessRequest(request); err != nil {
return err
}
}
clientToUse := c.httpClientForZendesk
if strings.Contains(request.Host, "zopim.com") {
clientToUse = c.httpClientForZopim
}
response, err := clientToUse.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode >= http.StatusBadRequest {
responseErr := &Error{
Response: response,
}
// There are times where Zendesk will report an error, but not provide a json encoded body response - handle these by
// providing the body bytes directly along with what the content type header is
contentType := response.Header.Get("Content-Type")
if !strings.Contains(contentType, "application/json") {
responseErr.Description = fmt.Sprintf("encountered error - response content is '%s', not JSON", contentType)
responseErr.Message = string(bodyBytes)
return responseErr
}
if err := json.Unmarshal(bodyBytes, responseErr); err != nil {
return err
}
return responseErr
}
if target != nil {
if err := json.Unmarshal(bodyBytes, target); err != nil {
return err
}
}
return nil
}
func (c *client) ZendeskRequest(request *http.Request, target any) error {
c.zendeskAuth.AddZendeskAuthentication(request)
if request.Method == http.MethodGet {
return c.doWithRetry(request, target)
}
return c.do(request, target)
}
func (c *client) ZendeskGetRequest(ctx context.Context, url string) (*http.Response, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
c.zendeskAuth.AddZendeskAuthentication(request)
return c.httpClientForZendesk.Do(request)
}
/*
NOTE: The RealTimeChat API uses a different URL to the LiveChat API/Zendesk API
https://developer.zendesk.com/api-reference/live-chat/real-time-chat-api/rest/
*/
func (c *client) RealTimeChatRequest(request *http.Request, target any) error {
if request.URL.Host == "" {
request.URL.Host = "rtm.zopim.com"
}
request.URL.Scheme = httpSecure
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", c.userAgent)
if request.Header.Get("Content-Type") == "" {
request.Header.Set("Content-Type", "application/json")
}
attempts := 0
maxAttempts := 2
for attempts < maxAttempts {
attempts++
if err := c.getAccessToken(request.Context()); err != nil {
return err
}
if c.chatToken == nil {
return errors.New("no token")
}
if c.chatToken.AccessToken == "" {
return errors.New("blank token")
}
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.chatToken.AccessToken))
if err := c.do(request, target); err != nil {
if zdError, ok := err.(*Error); ok {
if zdError.Response.StatusCode == http.StatusUnauthorized {
// Clear out the token
c.chatToken = nil
continue
}
}
return err
}
break
}
return nil
}
func (c *client) ChatRequest(request *http.Request, target any) error {
if request.URL.Host == "" {
request.URL.Host = "www.zopim.com"
}
request.URL.Scheme = httpSecure
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", c.userAgent)
if request.Header.Get("Content-Type") == "" {
request.Header.Set("Content-Type", "application/json")
}
attempts := 0
maxAttempts := 2
for attempts < maxAttempts {
attempts++
if err := c.getAccessToken(request.Context()); err != nil {
return err
}
if c.chatToken == nil {
return errors.New("no token")
}
if c.chatToken.AccessToken == "" {
return errors.New("blank token")
}
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.chatToken.AccessToken))
if err := c.do(request, target); err != nil {
if zdError, ok := err.(*Error); ok {
if zdError.Response.StatusCode == http.StatusUnauthorized {
// Clear out the token
c.chatToken = nil
continue
}
}
return err
}
break
}
return nil
}
type chatToken struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
}
/*
NOTE: You must configure the API Client in Zendesk Chat to be "client_type": "confidential". By default it is "public"
and this setting reverts to "public" if you interact with the client via the Zendesk Chat Web UI.
https://developer.zendesk.com/documentation/live-chat/getting-started/auth/#implementing-an-oauth-authorization-flow
https://developer.zendesk.com/documentation/live-chat/getting-started/auth/#confidential-grant-types
*/
func (c *client) getAccessToken(ctx context.Context) error {
if c.chatToken != nil {
return nil
}
c.chatMutex.Lock()
defer c.chatMutex.Unlock()
if c.chatToken != nil {
return nil
}
data := url.Values{}
data.Set("grant_type", "client_credentials")
data.Set("client_id", c.chatCredentials.ClientID)
data.Set("client_secret", c.chatCredentials.ClientSecret)
request, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
"https://www.zopim.com/oauth2/token",
strings.NewReader(data.Encode()),
)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
target := chatToken{}
if err := c.do(request, &target); err != nil {
return err
}
c.chatToken = &target
return nil
}