-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
384 lines (286 loc) · 10.9 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package zube
import (
"bytes"
"crypto/rsa"
"crypto/sha1"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/platogo/cache"
"github.com/platogo/zube/v2/models"
)
const (
ZubeHost string = "zube.io"
ApiUrl string = "https://zube.io/api/"
UserAgent string = "Zube-Go"
)
// Request parameter struct definitions
type Pagination struct {
Page string // Results page to paginate to
PerPage string // How many results to fetch per page, defaults to 30
}
type Order struct {
By string // Column / field to order by
Direction string // Either of `asc` or `desc`
}
type Filter struct {
Where map[string]any // Map of keys corresponding to fields to filter by
Select []string // Array of attributes to select
}
// Represents possible Zube query parameters
type Query struct {
Pagination
Order
Filter
Search string `json:"search"` // Undocumented search API query parameter, pass search query string here
}
// Encodes everything in `Query` into a flat Zube query string
func (query *Query) Encode() string {
q := url.Values{}
// Pagination
q.Add("page", query.Pagination.Page)
q.Add("per_page", query.Pagination.PerPage)
// Order
q.Add("order[by]", query.Order.By)
q.Add("order[direction]", query.Order.Direction)
// Filter
for field, v := range query.Filter.Where {
switch value := v.(type) {
case []string:
q.Add(fmt.Sprintf("where[%s][]", field), strings.Join(value, ","))
default:
q.Add(fmt.Sprintf("where[%s]", field), fmt.Sprint(v))
}
}
// Search
if query.Search != "" {
q.Add("search", query.Search)
}
for _, col := range query.Filter.Select {
q.Add("select[]", col)
}
return q.Encode()
}
type Client struct {
models.ZubeAccessToken // An encoded access JWT valid for 24h to the Zube API
Host string
ClientId string // Your unique client ID
HTTPc http.Client
}
// Creates and returns a Zube Client with an access token
// If the current access token is invalid, it is refreshes and saved to config
func NewClient(clientId, accessToken string) (*Client, error) {
client := &Client{
ClientId: clientId,
ZubeAccessToken: models.ZubeAccessToken{AccessToken: accessToken},
HTTPc: http.Client{Timeout: time.Duration(10) * time.Second},
}
if !IsTokenValid(client.ZubeAccessToken) {
privateKey, err := GetPrivateKey()
Check(err, "failed to get private key")
_, err = client.RefreshAccessToken(privateKey)
Check(err, "failed to refresh access token")
}
return client, nil
}
// Constructs a new client with only host and Client ID configured, enough to make an access token request.
func NewClientWithId(clientId string) *Client {
return &Client{Host: ZubeHost, ClientId: clientId}
}
// Fetch the access token JWT from Zube API and set it for the client. If it already exists, refresh it.
func (client *Client) RefreshAccessToken(key *rsa.PrivateKey) (*Client, error) {
refreshJWT, err := GenerateRefreshJWT(client.ClientId, key)
if err != nil {
return client, err
}
req, _ := zubeAccessTokenRequest(ApiUrl+"users/tokens", client.ClientId, refreshJWT)
rsp, err := http.DefaultClient.Do(req)
if err != nil {
return client, err
}
body, err := io.ReadAll(rsp.Body)
data := models.ZubeAccessToken{}
json.Unmarshal(body, &data)
client.AccessToken = string(data.AccessToken)
return client, err
}
func (client *Client) FetchCurrentPerson() models.CurrentPerson {
currentPerson := models.CurrentPerson{}
url := zubeURL("/api/current_person", Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, "failed to fetch current person info!")
json.Unmarshal(body, ¤tPerson)
return currentPerson
}
// Fetch and return an array of `Card`s
func (client *Client) FetchCards(query *Query) []models.Card {
var response models.PaginatedResponse[models.Card]
url := zubeURL("/api/cards", *query)
// TODO: Support pagination
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, "failed to fetch cards!")
json.Unmarshal(body, &response)
return response.Data
}
func (client *Client) FetchCardComments(cardId int) []models.Comment {
var response models.PaginatedResponse[models.Comment]
url := zubeURL("/api/cards/"+fmt.Sprint(cardId)+"/comments", Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to fetch comments for card with Id: %d", cardId))
json.Unmarshal(body, &response)
return response.Data
}
func (client *Client) CreateCard(card *models.Card) models.Card {
var respCard models.Card
url := zubeURL("/api/cards", Query{})
data, _ := json.Marshal(card)
resp, err := client.DoApiRequestUrl(http.MethodPost, &url, bytes.NewBuffer(data))
Check(err, "failed to create card!")
json.Unmarshal(resp, &respCard)
return respCard
}
// Move a card to a new destination
func (client *Client) MoveCard(cardId int, destination *models.Destination) {
url := zubeURL("/api/cards/"+fmt.Sprint(cardId)+"/move", Query{})
data, _ := json.Marshal(destination)
_, err := client.DoApiRequestUrl(http.MethodPut, &url, bytes.NewBuffer(data))
Check(err, fmt.Sprintf("failed to move card with Id: %d", cardId))
}
// Search Zube cards using a simple Query struct with `search` field in it.
func (client *Client) SearchCards(query *Query) []models.Card {
var response models.PaginatedResponse[models.Card]
url := zubeURL("/api/cards", *query)
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to find card with text: %s", query.Search))
json.Unmarshal(body, &response)
return response.Data
}
func (client *Client) FetchWorkspaces(query *Query) []models.Workspace {
var response models.PaginatedResponse[models.Workspace]
url := zubeURL("/api/workspaces", *query)
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, "failed to fetch workspaces!")
json.Unmarshal(body, &response)
return response.Data
}
// Fetch all epics for a given project
func (client *Client) FetchEpics(projectId int) []models.Epic {
var response models.PaginatedResponse[models.Epic]
url := zubeURL(fmt.Sprintf("/api/projects/%d/epics", projectId), Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to fetch card for project with Id: %d", projectId))
json.Unmarshal(body, &response)
return response.Data
}
// Fetch and return an array of `Account`s
func (client *Client) FetchAccounts(query *Query) []models.Account {
var response models.PaginatedResponse[models.Account]
url := zubeURL("/api/accounts", *query)
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, "failed to fetch accounts")
json.Unmarshal(body, &response)
return response.Data
}
// Fetch and return an array of Github `Source`s
func (client *Client) FetchSources() []models.Source {
var response models.PaginatedResponse[models.Source]
url := zubeURL("/api/sources", Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, "failed to fetch sources")
json.Unmarshal(body, &response)
return response.Data
}
func (client *Client) FetchProjects(query *Query) []models.Project {
var response models.PaginatedResponse[models.Project]
url := zubeURL("/api/projects", *query)
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, "failed to fetch projects")
json.Unmarshal(body, &response)
return response.Data
}
// Fetch cards for a specific project. The `project_id` key in the `Where` part of the `Query`'s `Filter` will have no effect.
func (client *Client) FetchProjectCards(projectId int, query *Query) []models.Card {
var response models.PaginatedResponse[models.Card]
url := zubeURL(fmt.Sprintf("/api/projects/%d/cards", projectId), *query)
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to fetch cards for project with Id: %d", projectId))
json.Unmarshal(body, &response)
return response.Data
}
func (client *Client) FetchProjectMembers(projectId int) []models.Member {
var response models.PaginatedResponse[models.Member]
url := zubeURL(fmt.Sprintf("/api/projects/%d/members", projectId), Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to fetch project members for project with Id: %d", projectId))
json.Unmarshal(body, &response)
return response.Data
}
// Fetch all labels for a given project
func (client *Client) FetchLabels(projectId int) []models.Label {
var response models.PaginatedResponse[models.Label]
url := zubeURL(fmt.Sprintf("/api/projects/%d/labels", projectId), Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to fetch labels for project with Id: %d", projectId))
json.Unmarshal(body, &response)
return response.Data
}
// Fetch all sprints for a given workspace
func (client *Client) FetchSprints(workspaceId int) []models.Sprint {
var response models.PaginatedResponse[models.Sprint]
url := zubeURL(fmt.Sprintf("/api/workspaces/%d/sprints", workspaceId), Query{})
body, err := client.DoApiRequestUrl(http.MethodGet, &url, nil)
Check(err, fmt.Sprintf("failed to fetch sprints for workspace with ID: %d", workspaceId))
json.Unmarshal(body, &response)
return response.Data
}
// Performs a generic request with URL and body
func (client *Client) DoApiRequestUrl(method string, url *url.URL, body io.Reader) ([]byte, error) {
req, _ := http.NewRequest(method, url.String(), body)
if client.AccessToken == "" {
return nil, errors.New("missing access token")
}
urlsha1 := sha1.Sum([]byte(url.String()))
cacheKey := fmt.Sprintf("%x", urlsha1)
cached, found := cache.Get(cacheKey)
if found {
req.Header.Add("If-None-Match", cached.Etag)
}
req.Header.Add("Authorization", "Bearer "+client.AccessToken)
req.Header.Add("X-Client-ID", client.ClientId)
req.Header.Add("User-Agent", UserAgent)
if body != nil {
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
}
resp, _ := client.HTTPc.Do(req)
// If cache exists and has not been changed on server, return cache data
if found && resp.StatusCode == http.StatusNotModified {
return json.Marshal(cached.Data)
}
respBody, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if etag := resp.Header.Get("ETag"); etag != "" {
cache.Save(cacheKey, etag, respBody)
}
return respBody, err
}
// Only used to create a request to fetch an access token JWT using a refresh JWT
func zubeAccessTokenRequest(url string, clientId, refreshJWT string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodPost, url, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+refreshJWT)
req.Header.Add("X-Client-ID", clientId)
req.Header.Add("User-Agent", UserAgent)
req.Header.Add("Accept", "application/json")
return req, nil
}
func zubeURL(path string, query Query) url.URL {
return url.URL{Scheme: "https", Host: ZubeHost, Path: path, RawQuery: query.Encode()}
}