-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
346 lines (313 loc) · 9.48 KB
/
Copy pathapi.go
File metadata and controls
346 lines (313 loc) · 9.48 KB
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type apiClient struct {
base string
token string
http *http.Client
}
func newAPIClient(base, token string) *apiClient {
return &apiClient{
base: strings.TrimRight(base, "/"),
token: token,
http: &http.Client{Timeout: 30 * time.Second},
}
}
type signupIntentResp struct {
IntentID string `json:"intent_id"`
SignupURL string `json:"signup_url"`
ExpiresAt string `json:"expires_at"`
}
type signupIntentPollResp struct {
Status string `json:"status"`
APIToken string `json:"api_token,omitempty"`
}
type shareResp struct {
UUID string `json:"uuid"`
ShortID string `json:"short_id"`
Filename string `json:"filename"`
Path string `json:"path,omitempty"`
Watch bool `json:"watch"`
URL string `json:"url"`
CommentAccess string `json:"comment_access"`
DocVisibility string `json:"doc_visibility"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
SizeBytes int `json:"size_bytes"`
UnresolvedCount int `json:"unresolved_count"`
AgentUnresolvedCount int `json:"agent_unresolved_count"`
Labels []string `json:"labels"`
}
// shareOpts are POST /api/shares policy fields. Empty strings are omitted so
// an upsert does not clobber stored values (server omitted = no-touch).
type shareOpts struct {
CommentAccess string
DocVisibility string
Labels *[]string
}
type commentView struct {
UUID string `json:"uuid"`
AuthorKind string `json:"author_kind"`
AuthorName string `json:"author_name"`
Body string `json:"body"`
CreatedAt string `json:"created_at"`
}
type commentTarget struct {
Path string `json:"path"`
Text string `json:"text"`
MDStart int `json:"md_start"`
MDEnd int `json:"md_end"`
}
type threadView struct {
UUID string `json:"uuid"`
Anchor string `json:"anchor"`
CurrentAnchor string `json:"current_anchor"`
AnchorType string `json:"anchor_type"`
Quote string `json:"quote"`
QuoteIndex int `json:"quote_index"`
QuoteStart int `json:"quote_start"`
QuoteEnd int `json:"quote_end"`
MDStart int `json:"md_start"`
MDEnd int `json:"md_end"`
QueuePosition int `json:"queue_position"`
QueueLength int `json:"queue_length"`
Orphaned bool `json:"orphaned"`
Resolved bool `json:"resolved"`
CreatedVersion int `json:"created_version"`
Comments []commentView `json:"comments"`
Target *commentTarget `json:"target,omitempty"`
}
type threadsResp struct {
Threads []threadView `json:"threads"`
}
func (c *apiClient) do(method, path string, body, dst any) error {
status, err := c.doStatus(method, path, body, dst)
if err != nil {
return err
}
_ = status
return nil
}
func (c *apiClient) doStatus(method, path string, body, dst any) (int, error) {
var rdr io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return 0, fmt.Errorf("marshal: %w", err)
}
rdr = bytes.NewReader(buf)
}
req, err := http.NewRequest(method, c.base+path, rdr)
if err != nil {
return 0, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.http.Do(req)
if err != nil {
return 0, fmt.Errorf("request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return resp.StatusCode, fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
}
if dst == nil {
_, _ = io.Copy(io.Discard, resp.Body)
return resp.StatusCode, nil
}
if err := json.NewDecoder(resp.Body).Decode(dst); err != nil {
return resp.StatusCode, fmt.Errorf("decode: %w", err)
}
return resp.StatusCode, nil
}
func (c *apiClient) Signup(email string) (*signupIntentResp, error) {
var out signupIntentResp
if err := c.do("POST", "/api/signup/intent", map[string]string{"email": email}, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *apiClient) PollSignupIntent(id string) (*signupIntentPollResp, error) {
var out signupIntentPollResp
if err := c.do("GET", "/api/signup/intent/"+id, nil, &out); err != nil {
return nil, err
}
return &out, nil
}
type manageIntentResp struct {
IntentID string `json:"intent_id"`
DashboardURL string `json:"dashboard_url"`
ExpiresAt string `json:"expires_at"`
}
func (c *apiClient) OpenManageIntent() (*manageIntentResp, error) {
var out manageIntentResp
if err := c.do("POST", "/api/manage/intent", nil, &out); err != nil {
return nil, err
}
return &out, nil
}
type inviteResp struct {
InviteURL string `json:"invite_url"`
ExpiresAt string `json:"expires_at"`
Email string `json:"email,omitempty"`
ShortID string `json:"short_id,omitempty"`
}
func (c *apiClient) CreateInvite(email, shortID string) (*inviteResp, error) {
var body any
if email != "" || shortID != "" {
m := map[string]string{}
if email != "" {
m["email"] = email
}
if shortID != "" {
m["short_id"] = shortID
}
body = m
}
var out inviteResp
status, err := c.doStatus("POST", "/api/invites", body, &out)
if err != nil {
return nil, mapInviteAPIError(status, err)
}
return &out, nil
}
func (c *apiClient) CreateShare(filename, path, content string, watch bool, opts shareOpts) (*shareResp, bool, error) {
var out shareResp
body := map[string]any{
"filename": filename,
"path": path,
"content": content,
"watch": watch,
}
if opts.CommentAccess != "" {
body["comment_access"] = opts.CommentAccess
}
if opts.DocVisibility != "" {
body["doc_visibility"] = opts.DocVisibility
}
if opts.Labels != nil {
body["labels"] = *opts.Labels
}
status, err := c.doStatus("POST", "/api/shares", body, &out)
if err != nil {
return nil, false, err
}
return &out, status == http.StatusCreated, nil
}
func (c *apiClient) UpdateShare(uuid, content string) (*shareResp, error) {
var out shareResp
if err := c.do("PUT", fmt.Sprintf("/api/shares/%s", uuid), map[string]string{"content": content}, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *apiClient) DeleteShare(uuid string) error {
return c.do("DELETE", fmt.Sprintf("/api/shares/%s", uuid), nil, nil)
}
func (c *apiClient) ValidateToken() error {
return c.do("GET", "/api/shares", nil, nil)
}
func (c *apiClient) ListShares() ([]shareResp, error) {
var out []shareResp
if err := c.do("GET", "/api/shares", nil, &out); err != nil {
return nil, err
}
return out, nil
}
func (c *apiClient) ListSharesIfNoneMatch(etag string) (shares []shareResp, newETag string, notModified bool, err error) {
req, err := http.NewRequest(http.MethodGet, c.base+"/api/shares", nil)
if err != nil {
return nil, "", false, err
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
if etag != "" {
req.Header.Set("If-None-Match", etag)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, "", false, fmt.Errorf("request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotModified {
_, _ = io.Copy(io.Discard, resp.Body)
return nil, etag, true, nil
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return nil, "", false, fmt.Errorf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
}
if err := json.NewDecoder(resp.Body).Decode(&shares); err != nil {
return nil, "", false, fmt.Errorf("decode: %w", err)
}
if shares == nil {
shares = []shareResp{}
}
return shares, resp.Header.Get("ETag"), false, nil
}
func (c *apiClient) ListSharesByFilename(filename string) ([]shareResp, error) {
var out []shareResp
path := "/api/shares?filename=" + url.QueryEscape(filename)
if err := c.do("GET", path, nil, &out); err != nil {
return nil, err
}
return out, nil
}
func (c *apiClient) ListComments(shareUUID string, unresolved, forAgent bool) ([]threadView, error) {
path := fmt.Sprintf("/api/shares/%s/comments", shareUUID)
q := url.Values{}
if unresolved {
q.Set("unresolved", "1")
}
if forAgent {
q.Set("for_agent", "1")
}
if enc := q.Encode(); enc != "" {
path += "?" + enc
}
var out threadsResp
if err := c.do("GET", path, nil, &out); err != nil {
return nil, err
}
return out.Threads, nil
}
func (c *apiClient) ReplyComment(shareUUID, threadUUID, body string) (*threadView, error) {
var out threadView
path := fmt.Sprintf("/api/shares/%s/comments/%s/replies", shareUUID, threadUUID)
if err := c.do("POST", path, map[string]string{"body": body}, &out); err != nil {
return nil, err
}
return &out, nil
}
func (c *apiClient) ResolveThread(shareUUID, threadUUID string) error {
return c.do("POST", fmt.Sprintf("/api/shares/%s/comments/%s/resolve", shareUUID, threadUUID), nil, nil)
}
func (c *apiClient) UnresolveThread(shareUUID, threadUUID string) error {
return c.do("POST", fmt.Sprintf("/api/shares/%s/comments/%s/unresolve", shareUUID, threadUUID), nil, nil)
}
func (c *apiClient) GetShareByShortID(shortID string) (*shareResp, error) {
all, err := c.ListShares()
if err != nil {
return nil, err
}
for i := range all {
if all[i].ShortID == shortID {
return &all[i], nil
}
}
return nil, fmt.Errorf("share %s not found in your account", shortID)
}