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
|
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"within.website/x/web"
)
// All of these types match descriptions in the Hacker News API documentation.
//
// https://github.com/HackerNews/API
// UnixTime is a type that represents a Unix timestamp.
type UnixTime time.Time
func (u UnixTime) String() string {
return time.Time(u).Format(time.RFC3339)
}
// UnmarshalJSON converts the unix timestamp into a time.Time.
func (u *UnixTime) UnmarshalJSON(data []byte) error {
s := strings.Trim(string(data), "\"")
unix, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
*u = UnixTime(time.Unix(unix, 0))
return nil
}
// MarshalJSON converts the time.Time into a unix timestamp.
func (u UnixTime) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(time.Time(u).Unix(), 10)), nil
}
// HNUser is a type that represents a Hacker News user.
type HNUser struct {
ID string `json:"id"`
Created UnixTime `json:"created"`
Karma int `json:"karma"`
About string `json:"about"` // HTML
Submitted []int `json:"submitted"`
}
// HNItem is a type that represents a Hacker News item. This is a superset of all other types of items.
type HNItem struct {
ID int `json:"id"`
Deleted *bool `json:"deleted,omitempty"`
Type string `json:"type"`
By string `json:"by"`
Time UnixTime `json:"time"`
Text string `json:"text,omitempty"` // HTML
Dead *bool `json:"dead,omitempty"`
Parent *int `json:"parent,omitempty"`
Poll *int `json:"poll,omitempty"`
Kids []int `json:"kids,omitempty"`
URL string `json:"url,omitempty"`
Score int `json:"score,omitempty"`
Title string `json:"title,omitempty"` // HTML
Parts []int `json:"parts,omitempty"`
Descendants *int `json:"descendants,omitempty"`
}
type HNClient struct {
t *time.Ticker // for rate limiting requests based on --scrape-delay
cli *http.Client
cacheFolder *string
}
func NewHNClient(delay time.Duration) *HNClient {
return &HNClient{
t: time.NewTicker(delay),
cli: &http.Client{},
}
}
func (h *HNClient) Close() {
h.t.Stop()
}
func (h *HNClient) WithClient(c *http.Client) *HNClient {
h.cli = c
return h
}
func (h *HNClient) WithCacheFolder(f string) *HNClient {
h.cacheFolder = &f
return h
}
func (h *HNClient) GetItem(ctx context.Context, id int) (*HNItem, error) {
if h.cacheFolder != nil {
item, err := h.getItemFromCache(id)
if err == nil {
return item, nil
}
}
item, err := h.getItem(ctx, id)
if err != nil {
return nil, err
}
if h.cacheFolder != nil {
err = h.saveItemToCache(item)
if err != nil {
return nil, err
}
}
return item, nil
}
func (h *HNClient) saveItemToCache(item *HNItem) error {
if h.cacheFolder == nil {
return nil
}
folder := *h.cacheFolder
fname := filepath.Join(folder, "items", strconv.Itoa(item.ID)+".json")
f, err := os.Create(fname)
if err != nil {
return fmt.Errorf("failed to create cache file: %w", err)
}
defer f.Close()
if err = json.NewEncoder(f).Encode(item); err != nil {
return fmt.Errorf("failed to write item to cache: %w", err)
}
return nil
}
func (h *HNClient) getItemFromCache(id int) (*HNItem, error) {
if h.cacheFolder == nil {
return nil, nil
}
folder := *h.cacheFolder
fname := filepath.Join(folder, "items", strconv.Itoa(id)+".json")
f, err := os.Open(fname)
if err != nil {
return nil, fmt.Errorf("failed to open cache file: %w", err)
}
defer f.Close()
var item HNItem
if err = json.NewDecoder(f).Decode(&item); err != nil {
return nil, fmt.Errorf("failed to read item from cache: %w", err)
}
return &item, nil
}
func (h *HNClient) GetUser(ctx context.Context, id string) (*HNUser, error) {
<-h.t.C
req, err := http.NewRequestWithContext(ctx, "GET", "https://hacker-news.firebaseio.com/v0/user/"+id+".json", nil)
if err != nil {
return nil, err
}
resp, err := h.cli.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, web.NewError(http.StatusOK, resp)
}
var user HNUser
err = json.NewDecoder(resp.Body).Decode(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (h *HNClient) getItem(ctx context.Context, id int) (*HNItem, error) {
<-h.t.C
req, err := http.NewRequestWithContext(ctx, "GET", "https://hacker-news.firebaseio.com/v0/item/"+strconv.Itoa(id)+".json", nil)
if err != nil {
return nil, err
}
resp, err := h.cli.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, web.NewError(http.StatusOK, resp)
}
var item HNItem
err = json.NewDecoder(resp.Body).Decode(&item)
if err != nil {
return nil, err
}
return &item, nil
}
func (h *HNClient) PathToRoot(ctx context.Context, id int) ([]int, error) {
item, err := h.GetItem(ctx, id)
if err != nil {
return nil, err
}
if item.Parent == nil {
return []int{id}, nil
}
parents, err := h.PathToRoot(ctx, *item.Parent)
if err != nil {
return nil, err
}
return append(parents, id), nil
}
func (h *HNClient) GetUltimateParent(ctx context.Context, id int) (*HNItem, error) {
item, err := h.GetItem(ctx, id)
if err != nil {
return nil, err
}
if item.Parent == nil {
return item, nil
}
return h.GetUltimateParent(ctx, *item.Parent)
}
|