-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
216 lines (171 loc) · 4.58 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
package golibre
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
)
type client struct {
httpClient *http.Client
userAgent string
apiURL string
requestPreProcessors []RequestPreProcessor
authentication Authentication
jwt jwtAuth
}
type jwtAuth struct {
rawToken string
mutex *sync.RWMutex
}
func (c *client) do(request *http.Request, target any) error {
if request.URL.Host == "" {
request.URL.Host = c.apiURL
}
request.URL.Scheme = "https"
// Required
request.Header.Set("cache-control", "no-cache")
request.Header.Set("content-type", "application/json")
request.Header.Set("product", "llu.android")
request.Header.Set("version", "4.8.0")
for _, requestPreProcessor := range c.requestPreProcessors {
if err := requestPreProcessor.ProcessRequest(request); err != nil {
return err
}
}
response, err := c.httpClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= http.StatusBadRequest {
return fmt.Errorf("network request error: %d", response.StatusCode)
}
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
return err
}
// NOTE: Libreview API returns HTTP Status OK for every request, and changes the "status" field
// in the response body based on the success / failure of a request.
responseErr := APIError{
RawResponse: response,
}
if err := json.Unmarshal(bodyBytes, &responseErr); err != nil {
return err
}
switch responseErr.Status {
case StatusOK:
if target != nil {
if err := json.Unmarshal(bodyBytes, target); err != nil {
return err
}
}
return nil
case StatusUnauthenticated:
c.jwt.mutex.Lock()
defer c.jwt.mutex.Unlock()
c.jwt.rawToken = ""
return &responseErr
default:
// Unknown status code, return the response error if possible
return &responseErr
}
}
func (c *client) Do(request *http.Request, target any) error {
if err := c.addAuthentication(request); err != nil {
return err
}
return c.do(request, target)
}
func (c *client) addAuthentication(r *http.Request) error {
if token, tokenExists := c.checkForAuthToken(); tokenExists {
r.Header.Set("Authorization", "Bearer "+token)
return nil
}
if err := c.getNewAuthToken(r.Context()); err != nil {
return err
}
return c.addAuthentication(r)
}
func (c *client) checkForAuthToken() (authToken string, authTokenExists bool) {
c.jwt.mutex.RLock()
defer c.jwt.mutex.RUnlock()
authToken = c.jwt.rawToken
authTokenExists = authToken != ""
return authToken, authTokenExists
}
func (c *client) getNewAuthToken(ctx context.Context) error {
c.jwt.mutex.Lock()
defer c.jwt.mutex.Unlock()
// NOTE: Assuming >1 thread requesting refresh, ensure that after first thread unlocks,
// subsequent threads check the JWT Token before requesting a new token
if c.jwt.rawToken != "" {
return nil
}
authenticationRequestBody, err := json.Marshal(c.authentication)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
fmt.Sprintf("https://%s/llu/auth/login", c.apiURL),
bytes.NewReader(authenticationRequestBody),
)
if err != nil {
return err
}
// Required
req.Header.Set("cache-control", "no-cache")
req.Header.Set("content-type", "application/json")
req.Header.Set("product", "llu.android")
req.Header.Set("version", "4.8.0")
for _, requestPreProcessor := range c.requestPreProcessors {
if err := requestPreProcessor.ProcessRequest(req); err != nil {
return err
}
}
response, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= http.StatusBadRequest {
return fmt.Errorf("network request error: %d", response.StatusCode)
}
bodyBytes, err := io.ReadAll(response.Body)
if err != nil {
return err
}
target := LoginResponse{}
responseErr := APIError{
RawResponse: response,
}
if err := json.Unmarshal(bodyBytes, &responseErr); err != nil {
return err
}
switch responseErr.Status {
case StatusOK:
if err := json.Unmarshal(bodyBytes, &target); err != nil {
return err
}
c.jwt.rawToken = target.Data.AuthTicket.Token
return nil
case StatusUnauthenticated:
return &responseErr
default:
// Unknown status code, return the response error if possible
return &responseErr
}
}
type Authentication struct {
Email string `json:"email"`
Password string `json:"password"`
}
type BaseResponse[data []ConnectionData | ConnectionGraphData | UserData | AccountDetailData] struct {
Status uint `json:"status"`
Data data `json:"data"`
Ticket AuthTicket `json:"ticket"`
}