This repository has been archived by the owner on May 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
189 lines (175 loc) · 4.13 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
package tuyacloud
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/go-log/log"
"github.com/go-playground/validator/v10"
"github.com/pkg/errors"
)
// Client for tuya cloud.
type Client struct {
endpoint string
accessID string
accessKey string
lock sync.Mutex
httpClient HTTPClient
logger log.Logger
storage TokenStorage
validator *validator.Validate
maxRetires uint64
}
// NewClient returns API client.
func NewClient(endpoint Endpoint, accessID, accessKey string, opts ...Option) (c *Client) {
c = &Client{endpoint: string(endpoint), accessID: accessID, accessKey: accessKey}
conf := &options{
httpClient: &http.Client{Timeout: 10 * time.Second},
logger: log.DefaultLogger,
storage: &MemoryStore{},
maxRetires: 5,
}
for _, opt := range opts {
opt(conf)
}
c.httpClient = conf.httpClient
c.logger = conf.logger
c.storage = conf.storage
c.validator = validator.New()
c.maxRetires = conf.maxRetires
return
}
func (c *Client) isBody(r Request) bool {
// WTF: Some cases uploads body with http.MethodDelete
if _, ok := r.(RequestBody); ok {
return true
}
if r.Method() != http.MethodGet && r.Method() != http.MethodDelete {
return true
}
return false
}
// Request to TUYA.
func (c *Client) Request(r Request) (req *http.Request, err error) {
// Check params by go-playground/validator
err = c.validator.Struct(r)
if err != nil {
return
}
target := c.endpoint + r.URL()
var buf io.Reader
if c.isBody(r) {
i := r.(RequestBody).Body()
var b []byte
b, err = json.Marshal(i)
if err != nil {
return
}
buf = bytes.NewReader(b)
}
c.logger.Logf("%s %s", r.Method(), target)
req, err = http.NewRequest(r.Method(), target, buf)
if err != nil {
return
}
timestamp := Timestamp()
// TODO: dirty hack for infinity loop
if !strings.Contains(r.URL(), "/v1.0/token") {
var token string
token, err = c.Token()
if err != nil {
return
}
sign := c.TokenSign(token, timestamp)
req.Header.Add("access_token", token)
req.Header.Add("sign", sign)
}
req.Header.Add("client_id", c.accessID)
req.Header.Add("sign_method", "HMAC-SHA256")
req.Header.Add("t", timestamp)
if c.isBody(r) {
req.Header.Add("Content-Type", "application/json")
}
return
}
// Parse response body.
func (c *Client) Parse(res *http.Response, resp interface{}) error {
defer res.Body.Close()
var body Response
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
c.logger.Logf("Recv: %s", string(b))
err = json.Unmarshal(b, &body)
if err != nil {
return err
}
if !body.Success {
// compensation mechanism for token invalid.
// e.g. tuya restarts its server all token will expires right now.
if body.Code == 1010 || body.Code == 1011 {
c.lock.Lock()
_ = c.storage.Refresh(c)
c.lock.Unlock()
}
return errors.Wrap(&Error{
Code: body.Code,
Msg: body.Msg,
}, "call failed")
}
err = json.Unmarshal(body.Result, resp)
return err
}
// Do send HTTP request.
func (c *Client) Do(r *http.Request) (res *http.Response, err error) {
// ExponentialBackOff support.
err = backoff.Retry(func() error {
var e error
res, e = c.httpClient.Do(r)
return e
}, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), c.maxRetires))
return
}
// DoAndParse = Do + Parse.
func (c *Client) DoAndParse(r Request, resp interface{}) (err error) {
var req *http.Request
var res *http.Response
req, err = c.Request(r)
if err != nil {
return
}
res, err = c.Do(req)
if err != nil {
return
}
err = c.Parse(res, resp)
return
}
// PlainSign returns sign.
func (c *Client) PlainSign(timestamp string) string {
return strings.ToUpper(HmacSha256(c.accessID+timestamp, c.accessKey))
}
// TokenSign returns token sign.
func (c *Client) TokenSign(token, timestamp string) string {
return strings.ToUpper(HmacSha256(c.accessID+token+timestamp, c.accessKey))
}
// Token returns access token.
func (c *Client) Token() (token string, err error) {
c.lock.Lock()
defer c.lock.Unlock()
token = c.storage.Token()
if token == "" {
err = c.storage.Refresh(c)
if err != nil {
return
}
token = c.storage.Token()
}
return
}