-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkvite.go
More file actions
492 lines (429 loc) · 13.3 KB
/
linkvite.go
File metadata and controls
492 lines (429 loc) · 13.3 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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Package linkvite provides a Go SDK for the Linkvite API.
//
// Linkvite is a bookmarking service that allows users to save, organize,
// and share bookmarks. This SDK provides a convenient way to interact
// with the Linkvite API from Go applications.
//
// # Authentication
//
// Three authentication methods are supported:
//
// API key:
//
// client, err := linkvite.NewClient("link_your-api-key")
//
// Access token (e.g. from a previous session):
//
// client, err := linkvite.NewClientWithTokens(accessToken, refreshToken)
//
// Username or email + password:
//
// client, err := linkvite.NewClientWithCredentials(ctx, "user@example.com", "password")
//
// To obtain tokens without immediately creating a client, use Login:
//
// result, err := linkvite.Login(ctx, "user@example.com", "password")
// // result.AccessToken, result.RefreshToken, result.User
//
// # Basic usage
//
// // Get current user
// user, err := client.User.Get(ctx)
//
// // Create a bookmark
// bookmark, err := client.Bookmarks.Create(ctx, &linkvite.CreateBookmarkInput{
// URL: "https://example.com",
// })
package linkvite
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
// DefaultBaseURL is the default Linkvite API base URL.
DefaultBaseURL = "https://api.linkvite.io"
)
// AuthType represents the type of authentication used by the client.
type AuthType int
const (
// AuthTypeUnset indicates that no authentication method has been set.
AuthTypeUnset AuthType = iota
// AuthTypeAPIKey indicates that the client is using API key authentication.
AuthTypeAPIKey
// AuthTypeAccessToken indicates that the client is using access token authentication.
AuthTypeAccessToken
)
func (a AuthType) String() string {
switch a {
case AuthTypeAPIKey:
return "api_key"
case AuthTypeAccessToken:
return "access_token"
default:
return "unset"
}
}
// Client is the Linkvite API client.
type Client struct {
httpClient *http.Client
baseURL string
userAgent string
authType AuthType
apiKey string
accessToken string
refreshToken string
User *UserService
Bookmarks *BookmarksService
Collections *CollectionsService
Comments *CommentsService
Highlights *HighlightsService
Reminders *RemindersService
Invites *InvitesService
Search *SearchService
RSSFeeds *RSSFeedsService
APIKeys *APIKeysService
Parser *ParserService
}
// Option configures a Client.
type Option func(*Client) error
// WithBaseURL sets a custom base URL.
func WithBaseURL(u string) Option {
return func(c *Client) error {
ul := strings.TrimSpace(u)
if ul == "" {
return fmt.Errorf("linkvite: baseURL cannot be empty")
}
c.baseURL = ul
return nil
}
}
// WithHTTPClient sets a custom HTTP client.
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) error {
if hc == nil {
return fmt.Errorf("linkvite: http client cannot be nil")
}
c.httpClient = hc
return nil
}
}
// WithUserAgent sets a custom User-Agent header.
func WithUserAgent(ua string) Option {
return func(c *Client) error {
u := strings.TrimSpace(ua)
if u == "" {
return fmt.Errorf("linkvite: userAgent cannot be empty")
}
c.userAgent = u
return nil
}
}
// WithAPIKey configures API key authentication.
func WithAPIKey(apiKey string) Option {
return func(c *Client) error {
k := strings.TrimSpace(apiKey)
if k == "" {
return fmt.Errorf("linkvite: apiKey cannot be empty")
}
if !strings.HasPrefix(k, "link_") {
return fmt.Errorf("linkvite: invalid apiKey format")
}
// conflict detection: do not allow both auth methods
if c.authType != AuthTypeUnset && c.authType != AuthTypeAPIKey {
return fmt.Errorf("linkvite: cannot set apiKey when authType is %s", c.authType.String())
}
c.apiKey = k
c.authType = AuthTypeAPIKey
return nil
}
}
// WithAccessToken configures access-token authentication.
func WithAccessToken(token string) Option {
return func(c *Client) error {
t := strings.TrimSpace(token)
if t == "" {
return fmt.Errorf("linkvite: accessToken cannot be empty")
}
// conflict detection: do not allow both auth methods
if c.authType != AuthTypeUnset && c.authType != AuthTypeAPIKey {
return fmt.Errorf("linkvite: cannot set accessToken when authType is %s", c.authType.String())
}
c.accessToken = t
c.authType = AuthTypeAccessToken
return nil
}
}
// WithRefreshToken sets the refresh token for token refresh operations.
func WithRefreshToken(token string) Option {
return func(c *Client) error {
t := strings.TrimSpace(token)
if t == "" {
return fmt.Errorf("linkvite: refreshToken cannot be empty")
}
c.refreshToken = t
return nil
}
}
// WithTokens configures access-token authentication and adds a refresh token if provided.
func WithTokens(accessToken, refreshToken string) Option {
return func(c *Client) error {
if err := WithAccessToken(accessToken)(c); err != nil {
return err
}
if refreshToken != "" {
if err := WithRefreshToken(refreshToken)(c); err != nil {
return err
}
}
return nil
}
}
// NewClient creates a new Linkvite API client.
func NewClient(apiKey string, opts ...Option) (*Client, error) {
c := &Client{
httpClient: &http.Client{Timeout: 30 * time.Second},
baseURL: DefaultBaseURL,
userAgent: fmt.Sprintf("linkvite-go/%s", Version),
authType: AuthTypeUnset,
}
if strings.TrimSpace(apiKey) != "" {
if err := WithAPIKey(apiKey)(c); err != nil {
return nil, err
}
}
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt(c); err != nil {
return nil, err
}
}
switch c.authType {
case AuthTypeUnset:
return nil, fmt.Errorf("linkvite: either apiKey or accessToken is required")
case AuthTypeAPIKey:
if strings.TrimSpace(c.apiKey) == "" {
return nil, fmt.Errorf("linkvite: apiKey is required for AuthTypeAPIKey")
}
case AuthTypeAccessToken:
if strings.TrimSpace(c.accessToken) == "" {
return nil, fmt.Errorf("linkvite: accessToken is required for AuthTypeAccessToken")
}
default:
return nil, fmt.Errorf("linkvite: invalid authType %d", int(c.authType))
}
c.User = &UserService{client: c}
c.Bookmarks = &BookmarksService{client: c}
c.Collections = &CollectionsService{client: c}
c.Comments = &CommentsService{client: c}
c.Highlights = &HighlightsService{client: c}
c.Reminders = &RemindersService{client: c}
c.Invites = &InvitesService{client: c}
c.Search = &SearchService{client: c}
c.RSSFeeds = &RSSFeedsService{client: c}
c.APIKeys = &APIKeysService{client: c}
c.Parser = &ParserService{client: c}
return c, nil
}
// NewClientWithTokens creates a new Linkvite API client using access and refresh tokens.
func NewClientWithTokens(accessToken, refreshToken string, opts ...Option) (*Client, error) {
opts = append([]Option{WithTokens(accessToken, refreshToken)}, opts...)
return NewClient("", opts...)
}
// Login authenticates with an identifier (username or email) and password,
// returning tokens and the authenticated user. Use the returned tokens with
// NewClientWithTokens to create an authenticated client.
func Login(ctx context.Context, identifier, password string, opts ...Option) (*LoginResult, error) {
if strings.TrimSpace(identifier) == "" {
return nil, fmt.Errorf("linkvite: identifier cannot be empty")
}
if strings.TrimSpace(password) == "" {
return nil, fmt.Errorf("linkvite: password cannot be empty")
}
cfg := &Client{
httpClient: &http.Client{Timeout: 30 * time.Second},
baseURL: DefaultBaseURL,
userAgent: fmt.Sprintf("linkvite-go/%s", Version),
}
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt(cfg); err != nil {
return nil, err
}
}
payload := struct {
Identifier string `json:"identifier"`
Password string `json:"password"`
}{Identifier: identifier, Password: password}
jsonBody, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("linkvite: marshal error: %w", err)
}
authURL := cfg.baseURL + "/v1/auth/login"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, authURL, bytes.NewReader(jsonBody))
if err != nil {
return nil, fmt.Errorf("linkvite: request error: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", cfg.userAgent)
resp, err := cfg.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("linkvite: request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("linkvite: read error: %w", err)
}
var apiResp struct {
OK bool `json:"ok"`
Data *LoginResult `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Errors any `json:"errors,omitempty"`
}
if err := json.Unmarshal(respBody, &apiResp); err != nil {
return nil, fmt.Errorf("linkvite: parse error: %w", err)
}
if !apiResp.OK {
return nil, &Error{
StatusCode: resp.StatusCode,
Message: apiResp.Error,
Errors: apiResp.Errors,
}
}
return apiResp.Data, nil
}
// NewClientWithCredentials creates a new client by logging in with an identifier
// (username or email) and password. Options such as WithBaseURL and WithHTTPClient
// are applied to both the login request and the resulting client.
func NewClientWithCredentials(ctx context.Context, identifier, password string, opts ...Option) (*Client, error) {
result, err := Login(ctx, identifier, password, opts...)
if err != nil {
return nil, err
}
return NewClientWithTokens(result.AccessToken, result.RefreshToken, opts...)
}
// RefreshAccessToken refreshes the access token using the refresh token
func (c *Client) RefreshAccessToken(ctx context.Context) error {
if c.refreshToken == "" {
return fmt.Errorf("linkvite: no refresh token available")
}
var result struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
err := c.post(ctx, "/auth/token/refresh", map[string]string{"refresh_token": c.refreshToken}, &result)
if err != nil {
return err
}
c.accessToken = result.AccessToken
c.refreshToken = result.RefreshToken
return nil
}
func (c *Client) do(ctx context.Context, method, path string, body, result any) error {
reqURL, err := url.Parse(c.baseURL + "/v1" + path)
if err != nil {
return fmt.Errorf("linkvite: invalid URL: %w", err)
}
var bodyReader io.Reader
if body != nil {
jsonBody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("linkvite: marshal error: %w", err)
}
bodyReader = bytes.NewReader(jsonBody)
}
req, err := http.NewRequestWithContext(ctx, method, reqURL.String(), bodyReader)
if err != nil {
return fmt.Errorf("linkvite: request error: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
switch c.authType {
case AuthTypeAPIKey:
req.Header.Set("x-api-key", c.apiKey)
case AuthTypeAccessToken:
req.Header.Set("Authorization", "Bearer "+c.accessToken)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("linkvite: request failed: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("linkvite: read error: %w", err)
}
var apiResp struct {
OK bool `json:"ok"`
Data any `json:"data,omitempty"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
Errors any `json:"errors,omitempty"`
}
if err := json.Unmarshal(respBody, &apiResp); err != nil {
return fmt.Errorf("linkvite: parse error: %w", err)
}
if !apiResp.OK {
return &Error{
StatusCode: resp.StatusCode,
Message: apiResp.Error,
Errors: apiResp.Errors,
}
}
if result != nil && apiResp.Data != nil {
dataBytes, _ := json.Marshal(apiResp.Data)
if err := json.Unmarshal(dataBytes, result); err != nil {
return fmt.Errorf("linkvite: unmarshal error: %w", err)
}
}
return nil
}
func (c *Client) get(ctx context.Context, path string, result any) error {
return c.do(ctx, http.MethodGet, path, nil, result)
}
func (c *Client) post(ctx context.Context, path string, body, result any) error {
return c.do(ctx, http.MethodPost, path, body, result)
}
func (c *Client) patch(ctx context.Context, path string, body, result any) error {
return c.do(ctx, http.MethodPatch, path, body, result)
}
func (c *Client) delete(ctx context.Context, path string) error {
return c.do(ctx, http.MethodDelete, path, nil, nil)
}
// Error represents an API error.
type Error struct {
StatusCode int
Message string
Errors any
}
func (e *Error) Error() string {
if e.Message != "" {
return fmt.Sprintf("linkvite: %s", e.Message)
}
return fmt.Sprintf("linkvite: API error (status %d)", e.StatusCode)
}
// IsNotFound returns true if this is a 404 error.
func (e *Error) IsNotFound() bool { return e.StatusCode == http.StatusNotFound }
// IsUnauthorized returns true if this is a 401 error.
func (e *Error) IsUnauthorized() bool { return e.StatusCode == http.StatusUnauthorized }
// IsForbidden returns true if this is a 403 error.
func (e *Error) IsForbidden() bool { return e.StatusCode == http.StatusForbidden }
// IsRateLimited returns true if this is a 429 error.
func (e *Error) IsRateLimited() bool { return e.StatusCode == http.StatusTooManyRequests }
// Ptr returns a pointer to the value.
func Ptr[T any](v T) *T { return &v }