-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
70 lines (60 loc) · 1.43 KB
/
reader.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
package readwise
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/marcus-crane/gunslinger/config"
)
type ReaderCount struct {
New int `json:"new"`
Later int `json:"later"`
Archive int `json:"archive"`
}
type DocumentList struct {
Count int `json:"count"`
}
const (
DocumentListURL = "https://readwise.io/api/v3/list"
)
func GetDocumentCounts(cfg config.Config) (ReaderCount, error) {
var readerCount ReaderCount
newCount, err := getDocumentCount(cfg, "new")
if err != nil {
return readerCount, err
}
laterCount, err := getDocumentCount(cfg, "later")
if err != nil {
return readerCount, err
}
archiveCount, err := getDocumentCount(cfg, "archive")
if err != nil {
return readerCount, err
}
readerCount.New = newCount
readerCount.Later = laterCount
readerCount.Archive = archiveCount
return readerCount, nil
}
func getDocumentCount(cfg config.Config, category string) (int, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/?location=%s", DocumentListURL, category), nil)
if err != nil {
return 0, err
}
req.Header.Add("Authorization", fmt.Sprintf("Token %s", cfg.Readwise.Token))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var documentList DocumentList
err = json.Unmarshal(body, &documentList)
if err != nil {
return 0, err
}
return documentList.Count, nil
}