forked from GetStream/stream-chat-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
255 lines (207 loc) · 5.79 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
package stream_chat
import (
"bytes"
"context"
"crypto"
"crypto/hmac"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
)
const (
// DefaultBaseURL is the default base URL for the stream chat api.
// It works like CDN style and connects you to the closest production server.
// By default, there is no real reason to change it. Use it only if you know what you are doing.
DefaultBaseURL = "https://chat.stream-io-api.com"
defaultTimeout = 6 * time.Second
)
type Client struct {
BaseURL string
HTTP *http.Client `json:"-"`
apiKey string
apiSecret []byte
authToken string
}
type ClientOption func(c *Client)
func WithTimeout(t time.Duration) func(c *Client) {
return func(c *Client) {
c.HTTP.Timeout = t
}
}
// NewClientFromEnvVars creates a new Client where the API key
// is retrieved from STREAM_KEY and the secret from STREAM_SECRET
// environmental variables.
func NewClientFromEnvVars() (*Client, error) {
return NewClient(os.Getenv("STREAM_KEY"), os.Getenv("STREAM_SECRET"))
}
// NewClient creates new stream chat api client.
func NewClient(apiKey, apiSecret string, options ...ClientOption) (*Client, error) {
switch {
case apiKey == "":
return nil, errors.New("API key is empty")
case apiSecret == "":
return nil, errors.New("API secret is empty")
}
baseURL := DefaultBaseURL
if baseURLEnv := os.Getenv("STREAM_CHAT_URL"); strings.HasPrefix(baseURLEnv, "http") {
baseURL = baseURLEnv
}
timeout := defaultTimeout
if timeoutEnv := os.Getenv("STREAM_CHAT_TIMEOUT"); timeoutEnv != "" {
i, err := strconv.Atoi(timeoutEnv)
if err != nil {
return nil, err
}
timeout = time.Duration(i) * time.Second
}
tr := http.DefaultTransport.(*http.Transport).Clone() //nolint:forcetypeassert
tr.MaxIdleConnsPerHost = 5
tr.IdleConnTimeout = 59 * time.Second // load balancer's idle timeout is 60 sec
tr.ExpectContinueTimeout = 2 * time.Second
client := &Client{
apiKey: apiKey,
apiSecret: []byte(apiSecret),
BaseURL: baseURL,
HTTP: &http.Client{
Timeout: timeout,
Transport: tr,
},
}
for _, fn := range options {
fn(client)
}
token, err := client.createToken(jwt.MapClaims{"server": true})
if err != nil {
return nil, err
}
client.authToken = token
return client, nil
}
// SetClient sets a new underlying HTTP client.
func (c *Client) SetClient(client *http.Client) {
c.HTTP = client
}
// Channel returns a Channel object for future API calls.
func (c *Client) Channel(channelType, channelID string) *Channel {
return &Channel{
client: c,
ID: channelID,
Type: channelType,
}
}
// Permissions returns a client for handling app permissions.
func (c *Client) Permissions() *PermissionClient {
return &PermissionClient{client: c}
}
// CreateToken creates a new token for user with optional expire time.
// Zero time is assumed to be no expire.
func (c *Client) CreateToken(userID string, expire time.Time, issuedAt ...time.Time) (string, error) {
if userID == "" {
return "", errors.New("user ID is empty")
}
claims := jwt.MapClaims{
"user_id": userID,
}
if !expire.IsZero() {
claims["exp"] = expire.Unix()
}
if len(issuedAt) > 0 && !issuedAt[0].IsZero() {
claims["iat"] = issuedAt[0].Unix()
}
return c.createToken(claims)
}
func (c *Client) createToken(claims jwt.Claims) (string, error) {
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(c.apiSecret)
}
// VerifyWebhook validates if hmac signature is correct for message body.
func (c *Client) VerifyWebhook(body, signature []byte) (valid bool) {
mac := hmac.New(crypto.SHA256.New, c.apiSecret)
_, _ = mac.Write(body)
expectedMAC := hex.EncodeToString(mac.Sum(nil))
return bytes.Equal(signature, []byte(expectedMAC))
}
// this makes possible to set content type.
type multipartForm struct {
*multipart.Writer
}
// CreateFormFile is a convenience wrapper around CreatePart. It creates
// a new form-data header with the provided field name, file name and content type.
func (form *multipartForm) CreateFormFile(fieldName, filename string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name=%q; filename=%q`, fieldName, filename))
return form.Writer.CreatePart(h)
}
func (form *multipartForm) setData(fieldName string, data interface{}) error {
field, err := form.CreateFormField(fieldName)
if err != nil {
return err
}
return json.NewEncoder(field).Encode(data)
}
func (form *multipartForm) setFile(fieldName string, r io.Reader, fileName string) error {
file, err := form.CreateFormFile(fieldName, fileName)
if err != nil {
return err
}
_, err = io.Copy(file, r)
return err
}
type SendFileResponse struct {
File string `json:"file"`
Response
}
func (c *Client) sendFile(ctx context.Context, link string, opts SendFileRequest) (*SendFileResponse, error) {
if opts.User == nil {
return nil, errors.New("user is nil")
}
tmpfile, err := ioutil.TempFile("", opts.FileName)
if err != nil {
return nil, err
}
defer func() {
_ = tmpfile.Close()
_ = os.Remove(tmpfile.Name())
}()
form := multipartForm{multipart.NewWriter(tmpfile)}
if err := form.setData("user", opts.User); err != nil {
return nil, err
}
err = form.setFile("file", opts.Reader, opts.FileName)
if err != nil {
return nil, err
}
err = form.Close()
if err != nil {
return nil, err
}
if _, err = tmpfile.Seek(0, 0); err != nil {
return nil, err
}
r, err := c.newRequest(ctx, http.MethodPost, link, nil, tmpfile)
if err != nil {
return nil, err
}
r.Header.Set("Content-Type", form.FormDataContentType())
res, err := c.HTTP.Do(r)
if err != nil {
return nil, err
}
var resp SendFileResponse
err = c.parseResponse(res, &resp)
if err != nil {
return nil, err
}
return &resp, err
}