forked from seenaburns/picofeed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
picofeed.go
296 lines (252 loc) · 6.55 KB
/
picofeed.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
package picofeed
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/mmcdole/gofeed"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
const (
FETCH_TIMEOUT = 10 * time.Second
DATE_FORMAT = "Jan 2006"
)
func Render(f io.Writer, posts []*Post) {
grouped := groupByDate(posts, DATE_FORMAT)
for _, group := range grouped {
for i, p := range group {
if i == 0 {
fmt.Fprintf(f, "%s\n", p.Timestamp.Format(DATE_FORMAT))
}
if len(p.Title) > 70 {
fmt.Fprintf(f, " %v\n", p.Title)
fmt.Fprintf(f, " %70v %s\n", "", p.Link)
} else {
fmt.Fprintf(f, " %-70v %s\n", p.Title, p.Link)
}
}
}
}
// RenderHTML writes HTML output of the feed to f
func RenderHTML(f io.Writer, posts []*Post) {
fmt.Fprintf(f, `<!DOCTYPE html>
<head>
<style>
body {
margin: 0 auto;
padding: 2em 0px;
max-width: 800px;
color: #888;
font-family: -apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
font-size: 14px;
line-height: 1.4em;
}
h4 {color: #000;}
a {color: #000;}
a:visited {color: #888;}
</style>
</head>
<body>
<h4 style="padding-bottom: 2em">Picofeed</h4>
`)
grouped := groupByDate(posts, DATE_FORMAT)
var lastTimestamp string
for _, group := range grouped {
for i, p := range group {
timestamp := p.Timestamp.Format("Jan 2")
if i == 0 {
fmt.Fprintf(f, "<h4>%s</h4>\n", p.Timestamp.Format(DATE_FORMAT))
} else if timestamp != lastTimestamp {
fmt.Fprintf(f, "<br />")
}
fmt.Fprintf(
f,
"<div><b>%s</b>\t<a href=\"%s\" target=blank>%s</a> (%s)</div>\n",
timestamp, p.Link, p.Title, p.shortFeedLink(),
)
lastTimestamp = timestamp
}
}
fmt.Fprintf(f, `</body>
</html>
`)
}
type Post struct {
Title string
Link string
Timestamp *time.Time
FeedLink string
FeedTitle string
}
func (p *Post) shortFeedLink() string {
u, err := url.Parse(p.FeedLink)
if err != nil {
return ""
}
return u.Host
}
type Posts []*Post
func (posts Posts) Len() int { return len(posts) }
func (posts Posts) Swap(i, j int) { posts[i], posts[j] = posts[j], posts[i] }
type ByTimestamp struct{ Posts }
func (posts ByTimestamp) Less(i, j int) bool {
return posts.Posts[i].Timestamp.After(*posts.Posts[j].Timestamp)
}
// Return list of lists of posts, where each given list has the same date
// E.g. [Dec 2018 -> []*Post, Nov 2018 -> []*Post, ...]
// Mutates posts (sorts) before running
func groupByDate(posts []*Post, dateFormat string) [][]*Post {
sort.Sort(ByTimestamp{posts})
// Initialize with 1 list
grouped := [][]*Post{[]*Post{}}
lastDate := ""
for _, p := range posts {
date := p.Timestamp.Format(dateFormat)
if date != lastDate {
// New date, make new list
grouped = append(grouped, []*Post{})
lastDate = date
}
current := len(grouped) - 1
grouped[current] = append(grouped[current], p)
}
return grouped
}
type Fetcher struct {
Validate bool
UserAgent string
}
// Fetch list of feeds in parallel, aggregate results
func (fe *Fetcher) FetchAll(ctx context.Context, feeds []*url.URL) ([]*Post, error) {
ctxTimeout, timeoutCancel := context.WithTimeout(ctx, FETCH_TIMEOUT)
defer timeoutCancel()
var wg errgroup.Group
postChan := make(chan *Post, 10000)
for _, f := range feeds {
feed := *f
wg.Go(func() error {
feed := &feed
feedData, err := fe.fetchFeed(ctxTimeout, feed, 0)
if err != nil {
log.Printf("ERROR: failed fetching feed %q: %v\n", feed, err)
if fe.Validate {
return fmt.Errorf("failed fetching feed %q: %v\n", feed, err)
} else {
return nil
}
}
posts, err := parseFeed(feed, feedData)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: failed reading feed data %q: %v\n", feed, err)
if fe.Validate {
return fmt.Errorf("failed fetching feed %q: %v\n", feed, err)
} else {
return nil
}
}
for _, p := range posts {
postChan <- p
}
return nil
})
}
err := wg.Wait()
close(postChan)
if err != nil {
return nil, err
}
posts := []*Post{}
for p := range postChan {
posts = append(posts, p)
}
return posts, err
}
// Fetch a single feed into a list of posts
func (fe *Fetcher) fetchFeed(ctx context.Context, feedUrl *url.URL, depth int) (*gofeed.Feed, error) {
feedParser := gofeed.NewParser()
client := &http.Client{}
req, _ := http.NewRequest("GET", feedUrl.String(), nil)
req.Header.Set("User-Agent", fe.UserAgent)
req = req.WithContext(ctx)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("Unexpected status code: %s", resp.Status)
}
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrapf(err, "Failed reading response body")
}
feed, err := feedParser.ParseString(string(contents))
if err == gofeed.ErrFeedTypeNotDetected && depth == 0 {
// User possibly tried to pass in a non-feed page, try to look for link to feed in header
// If found, recurse
newFeed := extractFeedLink(feedUrl, string(contents))
if newFeed == nil {
return nil, errors.New("Feed type not recognized, could not extract feed from <head>")
}
fmt.Fprintf(os.Stderr, "Autodiscovering feed %q for %q\n", newFeed, feedUrl)
return fe.fetchFeed(ctx, newFeed, 1)
}
return feed, err
}
func extractFeedLink(baseUrl *url.URL, contents string) *url.URL {
regexes := []string{
`\s*<link.*type="application/rss\+xml.*href="([^"]*)"`,
`\s*<link.*type="application/atom\+xml.*href="([^"]*)"`,
}
for _, r := range regexes {
re := regexp.MustCompile(r)
matches := re.FindStringSubmatch(contents)
if len(matches) > 1 {
if strings.HasPrefix(matches[1], "/") {
// relative path
newUrl := *baseUrl
newUrl.Path = matches[1]
return &newUrl
}
u, err := url.Parse(matches[1])
if err != nil {
fmt.Fprintf(os.Stderr, "Autodetected %q for %q but could not parse url", matches[1], baseUrl)
continue
}
return u
}
}
return nil
}
func parseFeed(feedUrl *url.URL, feed *gofeed.Feed) ([]*Post, error) {
posts := []*Post{}
for _, i := range feed.Items {
t := i.PublishedParsed
if i.PublishedParsed == nil {
if i.UpdatedParsed != nil {
t = i.UpdatedParsed
} else {
fmt.Fprintf(os.Stderr, "Invalid time (%q): %v", i.Title, i.PublishedParsed)
continue
}
}
posts = append(posts, &Post{
Title: i.Title,
Link: i.Link,
Timestamp: t,
FeedTitle: feed.Title,
FeedLink: feedUrl.String(),
})
}
fmt.Fprintf(os.Stderr, "Fetched %q: %d posts\n", feedUrl, len(feed.Items))
return posts, nil
}