-
Notifications
You must be signed in to change notification settings - Fork 1
/
pinboard.go
662 lines (610 loc) · 16.1 KB
/
pinboard.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
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
package pinboard
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// BaseURL points to and specifies the format of the Pinboard API endpoint.
// ** Note ** ideally this URI would be marked as const and only visible inside
// the package. However for testing purposes, the unit tests need to set this URI
// to point to a mock server. ** Do not ** change this URI.
var BaseURL = "https://api.pinboard.in/v1/%s/?%s"
// Pinboard a single instance to interact with bookmarks and other data
type Pinboard struct {
token string // e.g. username:TOKEN
authed bool // Authenticated with Pinboard service?
}
// Bookmark represents a Pinboard bookmark
type Bookmark struct {
URL string
Title string
Desc string
Tags []string
// Creation time for this bookmark.
Created time.Time
// Replace any existing bookmark with this URL.
Replace bool
// Make bookmark public.
Shared bool
// Marks the bookmarks as unread.
ToRead bool
Hash []byte // 32 character hexadecimal MD5 hash.
Meta []byte // 32 character hexadecimal MD5 hash.
}
// Tag represents a Pinboard tag
type Tag struct {
Name string
Count int
}
// Post represents a Pinboard post
type Post struct {
Date time.Time
Count int
}
// NoteMetadata represents Pinboard note meta data
type NoteMetadata struct {
ID string
Title string
Length int // Size of the note in bytes.
Hash []byte // 20 character long sha1 hash of note text.
Created time.Time // Time note was created. UTC time.
Updated time.Time // Time note was last updated. UTC time.
}
// Note represents a Pinboard note
type Note struct {
NoteMetadata
Text string
}
// Popular represents Pinboard popular tags
type Popular []string
// Recommended represents Pinboard recommended tags
type Recommended []string
// decodeJSON decodes a JSON structure into map key:string val:string. Decodes
// response data from Auth, LastUpdate, Add, Del, Tags, DelTag, RenTag.
func decodeJSON(jsonBlob []byte) (map[string]string, error) {
var j map[string]string
err := json.Unmarshal(jsonBlob, &j)
if err != nil {
return nil, err
}
return j, nil
}
// decodeJSONIFace decodes a JSON structure into map key:string val:interface{}.
// Decodes response data from Get, Dates, Recent, Notes, NoteID.
func decodeJSONIFace(jsonBlob []byte) (map[string]interface{}, error) {
var j map[string]interface{}
err := json.Unmarshal(jsonBlob, &j)
if err != nil {
return nil, err
}
return j, nil
}
// decodeJSONListIFace decodes a JSON structure into []interface{}. Decodes
// response data from Bookmarks, Suggest.
func decodeJSONListIFace(jsonBlob []byte) ([]interface{}, error) {
var j []interface{}
err := json.Unmarshal(jsonBlob, &j)
if err != nil {
return nil, err
}
return j, nil
}
// parseDateTime parses a date time in the format "2010-02-11 03:46:56" and
// returns a time.Time with location UTC.
func parseDateTime(dt string) time.Time {
if len(dt) != 19 {
return time.Time{}
}
yr := atoi(dt[0:4])
mo := atoi(dt[6:7])
dy := atoi(dt[8:10])
hr := atoi(dt[11:13])
mn := atoi(dt[14:16])
sd := atoi(dt[17:19])
return time.Date(yr, time.Month(mo), dy, hr, mn, sd, 0, time.UTC)
}
// stringToBool returns true if s == "yes", otherwise false.
func stringToBool(s string) bool {
if s == "yes" {
return true
}
return false
}
// boolToString return "yes" if b == true, otherwise "no".
func boolToString(b bool) string {
if b {
return "yes"
}
return "no"
}
// atoi converts a string to an integer, if there is an error in the conversion
// returns 0.
func atoi(s string) int {
l, err := strconv.Atoi(s)
if err != nil {
l = 0
}
return l
}
// do performs a HTTP GET on a URL.
func do(url string) (data []byte, err error) {
rsp, err := http.Get(url)
if err != nil {
return nil, err
}
c := rsp.StatusCode
if c != http.StatusOK {
return nil, errors.New("HTTP " + strconv.Itoa(c) + " " + http.StatusText(c))
}
defer rsp.Body.Close()
body, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, err
}
// server sent back no data or just returned '\n'.
if body == nil || (len(body) == 1 && body[0] == 10) {
return nil, errors.New("No data returned from server.")
}
return body, nil
}
// New returns a new unauthorized instance of Pinboard.
func New() *Pinboard {
return &Pinboard{}
}
// Token returns the users token in the format username:TOKEN.
func (p Pinboard) Token() string {
return p.token
}
// IsAuthed checks if the user has been authenticated with the Pinboard service
func (p Pinboard) IsAuthed() bool {
return p.authed
}
// makeURL constructs a valid URL which can be used to make a request to the
// Pinboard service.
func (p Pinboard) makeURL(method string, vals url.Values) string {
if vals == nil {
vals = url.Values{}
}
vals.Set("format", "json")
a := vals.Get("auth_token")
if a == "" {
vals.Set("auth_token", p.token)
}
return fmt.Sprintf(BaseURL, method, vals.Encode())
}
// performRequest performs a request to the Pinboard service.
func (p Pinboard) performRequest(method string, vals url.Values) ([]byte, error) {
// Only calls from Auth(...) can pass when p.auth == false, as we are
// requesting authentication. For all other calls the API must already be
// authorized by a previous call to Auth(...).
if !p.authed && method != "user/api_token" {
return nil, errors.New("API not authorized")
}
url := p.makeURL(method, vals)
data, err := do(url)
if err != nil {
return nil, err
}
return data, nil
}
// USER
// Auth validates the provided 'token' with the Pinboard service and returns the
// user's API token, The API token must be in the format: username:TOKEN.
func (p *Pinboard) Auth(token string) (string, error) {
v := url.Values{}
v.Set("auth_token", token)
data, err := p.performRequest("user/api_token", v)
if err != nil {
return "", err
}
j, err := decodeJSON(data)
if err != nil {
return "", err
}
p.token = token
p.authed = true
return j["result"], nil
}
// POSTS
// LastUpdate returns the last time a bookmark was added, updated or deleted.
// Use this before calling Bookmarks() to see if the data has changed since the
// last fetch.
func (p Pinboard) LastUpdate() (time.Time, error) {
data, err := p.performRequest("posts/update", nil)
if err != nil {
return time.Time{}, err
}
j, err := decodeJSON(data)
if err != nil {
return time.Time{}, err
}
t, err := time.Parse(time.RFC3339, j["update_time"])
if err != nil {
return time.Time{}, err
}
return t, err
}
// Add adds a bookmark.
func (p *Pinboard) Add(b Bookmark) (bool, error) {
v := url.Values{}
// mandatory.
v.Set("url", b.URL)
v.Set("description", b.Title)
// optional
if b.Desc != "" {
v.Set("extended", b.Desc)
}
if b.Tags != nil {
var g string
for _, t := range b.Tags {
g += t + ","
}
v.Set("tags", strings.Trim(g, ","))
}
var dt string
if b.Created.IsZero() {
// no creation time provided.
dt = time.Now().UTC().Format(time.RFC3339)
} else {
dt = b.Created.UTC().Format(time.RFC3339)
}
v.Set("dt", dt)
v.Set("replace", boolToString(b.Replace))
v.Set("shared", boolToString(b.Shared))
v.Set("toread", boolToString(b.ToRead))
data, err := p.performRequest("posts/add", v)
if err != nil {
return false, err
}
j, err := decodeJSON(data)
if err != nil {
return false, nil
}
if j["result_code"] != "done" {
return false, errors.New(j["result_code"])
}
return true, nil
}
// Del deletes a bookmark.
func (p Pinboard) Del(URL string) (bool, error) {
v := url.Values{}
v.Set("url", URL)
data, err := p.performRequest("posts/delete", v)
if err != nil {
return false, err
}
j, err := decodeJSON(data)
if err != nil {
return false, err
}
if j["result_code"] != "done" {
return false, errors.New(j["result_code"])
}
return true, nil
}
// Get returns one or more posts on a single day matching the arguments. If no
// date or URL is given, date of most recent bookmark will be used. The meta
// flag allows the ability to include a change detection signature for each
// bookmark.
func (p Pinboard) Get(dt time.Time, URL string, tags []string, meta bool) ([]Bookmark, error) {
v := url.Values{}
if !dt.IsZero() {
v.Set("dt", dt.UTC().Format(time.RFC3339))
}
if URL != "" {
v.Set("url", URL)
}
if tags != nil {
var g string
for _, t := range tags {
g += t + ","
}
v.Set("tag", strings.Trim(g, ","))
}
if meta {
v.Set("meta", "yes")
} else {
v.Set("meta", "no")
}
data, err := p.performRequest("posts/get", v)
if err != nil {
return nil, err
}
j, err := decodeJSONIFace(data)
if err != nil {
return nil, err
}
var bmarks []Bookmark
posts := j["posts"].([]interface{})
for i := 0; i < len(posts); i++ {
p := posts[i].(map[string]interface{})
t, err := time.Parse(time.RFC3339, p["time"].(string))
if err != nil {
t = time.Time{}
}
b := Bookmark{
URL: p["href"].(string),
Title: p["description"].(string),
Desc: p["extended"].(string),
Tags: strings.Split(p["tags"].(string), " "),
Created: t,
Shared: stringToBool(p["shared"].(string)),
ToRead: stringToBool(p["toread"].(string)),
Hash: []byte(p["hash"].(string)),
Meta: []byte(p["meta"].(string)),
}
bmarks = append(bmarks, b)
}
return bmarks, nil
}
// Dates returns a list of dates with the number of posts at each date.
func (p Pinboard) Dates(tags []string) ([]Post, error) {
v := url.Values{}
if tags != nil {
var g string
for _, t := range tags {
g += t + ","
}
v.Set("tag", strings.Trim(g, ","))
}
data, err := p.performRequest("posts/dates", v)
if err != nil {
return nil, err
}
j, err := decodeJSONIFace(data)
if err != nil {
return nil, err
}
d := j["dates"].(map[string]interface{})
var posts []Post
for k, v := range d {
w, err := time.Parse("2006-01-02", k)
if err != nil {
return nil, err
}
posts = append(posts, Post{Date: w, Count: atoi(v.(string))})
}
return posts, nil
}
// Recent returns a list of the user's most recent posts, filtered by tag. count
// indicates the number results to return, default is 15 max is 100.
func (p Pinboard) Recent(tags []string, count int) ([]Bookmark, error) {
v := url.Values{}
if tags != nil {
var g string
for _, t := range tags {
g += t + ","
}
v.Set("tag", strings.Trim(g, ","))
}
v.Set("count", strconv.Itoa(count))
data, err := p.performRequest("posts/recent", v)
if err != nil {
return nil, err
}
j, err := decodeJSONIFace(data)
if err != nil {
return nil, err
}
var bmarks []Bookmark
posts := j["posts"].([]interface{})
for i := 0; i < len(posts); i++ {
p := posts[i].(map[string]interface{})
t, err := time.Parse(time.RFC3339, p["time"].(string))
if err != nil {
t = time.Time{}
}
b := Bookmark{
URL: p["href"].(string),
Title: p["description"].(string),
Desc: p["extended"].(string),
Tags: strings.Split(p["tags"].(string), " "),
Created: t,
Shared: stringToBool(p["shared"].(string)),
ToRead: stringToBool(p["toread"].(string)),
Hash: []byte(p["hash"].(string)),
Meta: []byte(p["meta"].(string)),
}
bmarks = append(bmarks, b)
}
return bmarks, nil
}
// Bookmarks returns all bookmarks in the user's account. Provides the ability
// to:
// - 'tags' Filter by tags.
// - 'offset' Set offset value.
// - 'count' Set the number of results to return. Default is all.
// - 'start' Return only bookmarks created after this time.
// - 'end' Return only bookmarks created before this time.
// - 'meta' A meta flag to include a change detection signature for each bookmark.
func (p Pinboard) Bookmarks(tags []string, offset int, count int,
start time.Time, end time.Time, meta bool) ([]Bookmark, error) {
v := url.Values{}
if tags != nil {
var g string
for _, t := range tags {
g += t + ","
}
v.Set("tag", strings.Trim(g, ","))
}
v.Set("start", strconv.Itoa(offset))
v.Set("results", strconv.Itoa(count))
if !start.IsZero() {
v.Set("fromdt", start.UTC().Format(time.RFC3339))
}
if !end.IsZero() {
v.Set("todt", end.UTC().Format(time.RFC3339))
}
if meta {
v.Set("meta", "yes")
} else {
v.Set("meta", "no")
}
data, err := p.performRequest("posts/all", v)
if err != nil {
return nil, err
}
j, err := decodeJSONListIFace(data)
if err != nil {
return nil, err
}
var bmarks []Bookmark
for i := 0; i < len(j); i++ {
p := j[i].(map[string]interface{})
t, err := time.Parse(time.RFC3339, p["time"].(string))
if err != nil {
t = time.Time{}
}
b := Bookmark{
URL: p["href"].(string),
Title: p["description"].(string),
Desc: p["extended"].(string),
Tags: strings.Split(p["tags"].(string), " "),
Created: t,
Shared: stringToBool(p["shared"].(string)),
ToRead: stringToBool(p["toread"].(string)),
Hash: []byte(p["hash"].(string)),
Meta: []byte(p["meta"].(string)),
}
bmarks = append(bmarks, b)
}
return bmarks, nil
}
// Suggest returns a list of popular tags and recommended tags for a given URL.
// Popular tags are tags used site-wide for the url; recommended tags are drawn
// from the user's own tags.
func (p Pinboard) Suggest(URL string) (Popular, Recommended, error) {
v := url.Values{}
v.Set("url", URL)
data, err := p.performRequest("posts/suggest", v)
if err != nil {
return nil, nil, err
}
j, err := decodeJSONListIFace(data)
if err != nil {
return nil, nil, err
}
pop := make(Popular, 0)
rec := make(Recommended, 0)
if len(j) >= 2 {
a := j[0].(map[string]interface{})
b := a["popular"].([]interface{})
for _, t := range b {
pop = append(pop, t.(string))
}
a = j[1].(map[string]interface{})
b = a["recommended"].([]interface{})
for _, t := range b {
rec = append(rec, t.(string))
}
}
return pop, rec, nil
}
// TAGS
// Tags returns a full list of the user's tags along with the number of times
// they were used.
func (p Pinboard) Tags() ([]Tag, error) {
data, err := p.performRequest("tags/get", nil)
if err != nil {
return nil, err
}
j, err := decodeJSON(data)
if err != nil {
return nil, err
}
var tags []Tag
for k, v := range j {
tags = append(tags, Tag{Name: k, Count: atoi(v)})
}
return tags, nil
}
// DelTag delete an existing tag, returns true if the delete operation
// succeeds.
func (p Pinboard) DelTag(tag string) (bool, error) {
v := url.Values{}
v.Set("tag", tag)
data, err := p.performRequest("tags/delete", v)
if err != nil {
return false, err
}
j, err := decodeJSON(data)
if err != nil {
return false, err
}
if j["result"] != "done" {
return false, errors.New(j["result"])
}
return true, nil
}
// RenTag rename a tag, or fold it in to an existing tag. Match is not case
// sensitive, returns true if the rename operation succeeds.
func (p Pinboard) RenTag(oldTag, newTag string) (bool, error) {
v := url.Values{}
v.Set("old", oldTag)
v.Set("new", newTag)
data, err := p.performRequest("tags/rename", v)
if err != nil {
return false, err
}
j, err := decodeJSON(data)
if err != nil {
return false, err
}
if j["result"] != "done" {
return false, errors.New(j["result"])
}
return true, nil
}
// NOTES
// Notes returns a list of the user's notes
func (p Pinboard) Notes() ([]NoteMetadata, error) {
data, err := p.performRequest("notes/list", nil)
if err != nil {
return nil, err
}
j, err := decodeJSONIFace(data)
if err != nil {
return nil, err
}
var meta []NoteMetadata
count := int(j["count"].(float64))
notes := j["notes"].([]interface{})
for i := 0; i < count; i++ {
n := notes[i].(map[string]interface{})
t := NoteMetadata{ID: n["id"].(string),
Title: n["title"].(string),
Length: atoi(n["length"].(string)),
Hash: []byte(n["hash"].(string)),
Created: parseDateTime(n["created_at"].(string)),
Updated: parseDateTime(n["updated_at"].(string)),
}
meta = append(meta, t)
}
return meta, nil
}
// NoteID given a notes ID, returns an individual user note.
func (p *Pinboard) NoteID(id string) (Note, error) {
data, err := p.performRequest("notes/"+id, nil)
if err != nil {
return Note{}, err
}
j, err := decodeJSONIFace(data)
if err != nil {
return Note{}, err
}
n := Note{}
n.ID = j["id"].(string)
n.Title = j["title"].(string)
n.Length = int(j["length"].(float64))
n.Hash = []byte(j["hash"].(string))
n.Created = parseDateTime(j["created_at"].(string))
n.Updated = parseDateTime(j["updated_at"].(string))
n.Text = j["text"].(string)
return n, nil
}