forked from SlyMarbo/rss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrss.go
283 lines (242 loc) · 7.22 KB
/
rss.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
package rss
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"strings"
"text/tabwriter"
"time"
)
// Parse RSS or Atom data.
func Parse(data []byte) (*Feed, error) {
if strings.Contains(string(data), "<rss") {
if debug {
fmt.Println("[i] Parsing as RSS 2.0")
}
return parseRSS2(data, database)
} else if strings.Contains(string(data), "xmlns=\"http://purl.org/rss/1.0/\"") {
if debug {
fmt.Println("[i] Parsing as RSS 1.0")
}
return parseRSS1(data, database)
} else {
if debug {
fmt.Println("[i] Parsing as Atom")
}
return parseAtom(data, database)
}
}
// CacheParsedItemIDs enables or disable Item.ID caching when parsing feeds.
// Returns whether Item.ID were cached prior to function call.
func CacheParsedItemIDs(flag bool) (didCache bool) {
didCache = !disabled
disabled = !flag
return
}
type FetchFunc func(url string) (resp *http.Response, err error)
// Fetch downloads and parses the RSS feed at the given URL
func Fetch(url string) (*Feed, error) {
return FetchByClient(url, http.DefaultClient)
}
func FetchByClient(url string, client *http.Client) (*Feed, error) {
fetchFunc := func(url string) (resp *http.Response, err error) {
return client.Get(url)
}
return FetchByFunc(fetchFunc, url)
}
func FetchByFunc(fetchFunc FetchFunc, url string) (*Feed, error) {
resp, err := fetchFunc(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
out, err := Parse(body)
if err != nil {
return nil, err
}
if out.Link == "" {
out.Link = url
}
out.UpdateURL = url
out.FetchFunc = fetchFunc
return out, nil
}
// Feed is the top-level structure.
type Feed struct {
Nickname string `json:"nickname"` // This is not set by the package, but could be helpful.
Title string `json:"title"`
Description string `json:"description"`
Link string `json:"link"` // Link to the creator's website.
UpdateURL string `json:"updateurl"` // URL of the feed itself.
Image *Image `json:"image"` // Feed icon.
Items []*Item `json:"items"`
ItemMap map[string]struct{} `json:"itemmap"` // Used in checking whether an item has been seen before.
Refresh time.Time `json:"refresh"` // Earliest time this feed should next be checked.
Unread uint32 `json:"unread"` // Number of unread items. Used by aggregators.
FetchFunc FetchFunc `json:"-"`
}
type refreshError string
var _ net.Error = refreshError("")
func (r refreshError) Error() string {
return string(r)
}
func (r refreshError) Timeout() bool {
return false
}
func (r refreshError) Temporary() bool {
return true
}
var ErrUpdateNotReady refreshError = "not ready to update: too soon to refresh"
// Update fetches any new items and updates f.
func (f *Feed) Update() error {
// Check that we don't update too often.
if f.Refresh.After(time.Now()) {
return ErrUpdateNotReady
}
if f.UpdateURL == "" {
return errors.New("Error: feed has no URL.")
}
if f.ItemMap == nil {
f.ItemMap = make(map[string]struct{})
for _, item := range f.Items {
if _, ok := f.ItemMap[item.ID]; !ok {
f.ItemMap[item.ID] = struct{}{}
}
}
}
update, err := FetchByFunc(f.FetchFunc, f.UpdateURL)
if err != nil {
return err
}
f.Refresh = update.Refresh
f.Title = update.Title
f.Description = update.Description
for _, item := range update.Items {
if _, ok := f.ItemMap[item.ID]; !ok {
f.Items = append(f.Items, item)
f.ItemMap[item.ID] = struct{}{}
f.Unread++
}
}
return nil
}
func (f *Feed) String() string {
buf := new(bytes.Buffer)
if debug {
w := tabwriter.NewWriter(buf, 0, 8, 0, '\t', tabwriter.StripEscape)
fmt.Fprintf(w, "Feed {\n")
fmt.Fprintf(w, "\xff\t\xffNickname:\t%q\n", f.Nickname)
fmt.Fprintf(w, "\xff\t\xffTitle:\t%q\n", f.Title)
fmt.Fprintf(w, "\xff\t\xffDescription:\t%q\n", f.Description)
fmt.Fprintf(w, "\xff\t\xffLink:\t%q\n", f.Link)
fmt.Fprintf(w, "\xff\t\xffUpdateURL:\t%q\n", f.UpdateURL)
fmt.Fprintf(w, "\xff\t\xffImage:\t%q (%s)\n", f.Image.Title, f.Image.Url)
fmt.Fprintf(w, "\xff\t\xffRefresh:\t%s\n", f.Refresh.Format(DATE))
fmt.Fprintf(w, "\xff\t\xffUnread:\t%d\n", f.Unread)
fmt.Fprintf(w, "\xff\t\xffItems:\t(%d) {\n", len(f.Items))
for _, item := range f.Items {
fmt.Fprintf(w, "%s\n", item.Format(2))
}
fmt.Fprintf(w, "\xff\t\xff}\n}\n")
w.Flush()
} else {
w := buf
fmt.Fprintf(w, "Feed %q\n", f.Title)
fmt.Fprintf(w, "\t%q\n", f.Description)
fmt.Fprintf(w, "\t%q\n", f.Link)
fmt.Fprintf(w, "\t%s\n", f.Image)
fmt.Fprintf(w, "\tRefresh at %s\n", f.Refresh.Format(DATE))
fmt.Fprintf(w, "\tUnread: %d\n", f.Unread)
fmt.Fprintf(w, "\tItems:\n")
for _, item := range f.Items {
fmt.Fprintf(w, "\t%s\n", item.Format(2))
}
}
return buf.String()
}
// Item represents a single story.
type Item struct {
Title string `json:"title"`
Summary string `json:"summary"`
Content string `json:"content"`
Category string `json:"category"`
Link string `json:"link"`
Date time.Time `json:"date"`
ID string `json:"id"`
Enclosures []*Enclosure `json:"enclosures"`
Read bool `json:"read"`
}
func (i *Item) String() string {
return i.Format(0)
}
func (i *Item) Format(indent int) string {
buf := new(bytes.Buffer)
single := strings.Repeat("\t", indent)
double := single + "\t"
if debug {
w := tabwriter.NewWriter(buf, 0, 8, 0, '\t', tabwriter.StripEscape)
fmt.Fprintf(w, "\xff%s\xffItem {\n", single)
fmt.Fprintf(w, "\xff%s\xffTitle:\t%q\n", double, i.Title)
fmt.Fprintf(w, "\xff%s\xffSummary:\t%q\n", double, i.Summary)
fmt.Fprintf(w, "\xff%s\xffCategory:\t%q\n", double, i.Category)
fmt.Fprintf(w, "\xff%s\xffLink:\t%s\n", double, i.Link)
fmt.Fprintf(w, "\xff%s\xffDate:\t%s\n", double, i.Date.Format(DATE))
fmt.Fprintf(w, "\xff%s\xffID:\t%s\n", double, i.ID)
fmt.Fprintf(w, "\xff%s\xffRead:\t%v\n", double, i.Read)
fmt.Fprintf(w, "\xff%s\xffContent:\t%q\n", double, i.Content)
fmt.Fprintf(w, "\xff%s\xff}\n", single)
w.Flush()
} else {
w := buf
fmt.Fprintf(w, "%sItem %q\n", single, i.Title)
fmt.Fprintf(w, "%s%q\n", double, i.Link)
fmt.Fprintf(w, "%s%s\n", double, i.Date.Format(DATE))
fmt.Fprintf(w, "%s%q\n", double, i.ID)
fmt.Fprintf(w, "%sRead: %v\n", double, i.Read)
fmt.Fprintf(w, "%s%q\n", double, i.Content)
}
return buf.String()
}
type Enclosure struct {
Url string `json:"url"`
Type string `json:"type"`
Rel string `json:"rel"`
Length int `json:"length"`
}
func (e *Enclosure) Get() (io.ReadCloser, error) {
if e == nil || e.Url == "" {
return nil, errors.New("No enclosure")
}
res, err := http.Get(e.Url)
if err != nil {
return nil, err
}
return res.Body, nil
}
type Image struct {
Title string `json:"title"`
Url string `json:"url"`
Height uint32 `json:"height"`
Width uint32 `json:"width"`
}
func (i *Image) Get() (io.ReadCloser, error) {
if i == nil || i.Url == "" {
return nil, errors.New("No image")
}
res, err := http.Get(i.Url)
if err != nil {
return nil, err
}
return res.Body, nil
}
func (i *Image) String() string {
return fmt.Sprintf("Image %q", i.Title)
}