-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
295 lines (254 loc) · 7.03 KB
/
main.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
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/feeds"
"github.com/mmcdole/gofeed"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"golang.org/x/sync/singleflight"
)
const (
userAgent = "svenska-yle-rss-content-fixer/0.1"
maxFeedSize = 5 * 1024 * 1024 // 5 MB.
maxBodySize = 5 * 1024 * 1024 // 5 MB.
maxWorkers = 5
rssBaseURL = "https://svenska.yle.fi/rss"
)
func main() {
bind := flag.String("bind", "127.0.0.1", "Listen to requests on this interface")
port := flag.Int("port", 8080, "Port to listen to")
flag.Parse()
addr := fmt.Sprintf("%s:%d", *bind, *port)
log.Printf("Listening on %s", addr)
log.Fatal(http.ListenAndServe(addr, http.HandlerFunc(handler)))
}
func handler(w http.ResponseWriter, r *http.Request) {
rssURL := fmt.Sprintf("%s%s", rssBaseURL, r.URL.Path)
log.Printf("Serving RSS: %s", rssURL)
rss, err := fetchRSS(r.Context(), rssURL)
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
log.Printf("error serving request: %v", err)
return
}
w.Write(rss)
}
type articleData struct {
Author string
Content string
}
var articleCache = &sync.Map{} // map[articleKey]articleData
// Cache on GUID (URL) and update timestamp so articles can be refreshed.
type articleKey struct {
guid string
updated time.Time
}
func newArticleKey(item *gofeed.Item) articleKey {
t := item.PublishedParsed
if item.UpdatedParsed != nil {
t = item.UpdatedParsed
}
return articleKey{guid: item.GUID, updated: *t}
}
func fetchRSS(ctx context.Context, url string) ([]byte, error) {
client := http.DefaultClient
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
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("http status failed: %d", resp.StatusCode)
}
r := io.LimitReader(resp.Body, maxFeedSize)
fp := gofeed.NewParser()
feed, err := fp.Parse(r)
if err != nil {
return nil, err
}
sem := semaphore.NewWeighted(maxWorkers)
eg, egCtx := errgroup.WithContext(ctx)
sf := singleflight.Group{}
currentGUIDs := make(map[string]bool)
for i, item := range feed.Items {
currentGUIDs[item.GUID] = true
i := i
item := item
eg.Go(func() error {
_, err, _ := sf.Do(item.GUID, func() (interface{}, error) {
key := newArticleKey(item)
if _, ok := articleCache.Load(key); ok {
return nil, nil
}
req, err := http.NewRequestWithContext(egCtx, "GET", item.Link, nil)
if err != nil {
log.Printf("Skipping item %d: %v", i, err)
return nil, nil
}
if err := sem.Acquire(egCtx, 1); err != nil {
return nil, err
}
defer sem.Release(1)
resp, err := client.Do(req)
if err != nil {
log.Printf("Skipping item %d: %v", i, err)
return nil, nil
}
if err = func() error {
defer resp.Body.Close()
r := io.LimitReader(resp.Body, maxBodySize)
doc, err := goquery.NewDocumentFromReader(r)
if err != nil {
return err
}
// Clean up content.
category := strings.TrimSpace(doc.Find("header h2").Text())
sel := doc.Find("#main-content")
authorSel := sel.Find(".ydd-author-list")
author := authorSel.Text()
authorSel.Remove()
sel.Find(".ydd-article-headline").Parent().Remove()
sel.Find(".ydd-articles-list").Remove()
sel.Find(".ydd-author-list").Remove()
sel.Find(".ydd-share-buttons").Remove()
sel.Find("#comments").Remove()
for _, img := range sel.Find("img").Nodes {
var content, src string
for i := range img.Attr {
if img.Attr[i].Key == "content" {
content = img.Attr[i].Val
}
if img.Attr[i].Key == "data-src" {
src = img.Attr[i].Val
}
}
if content == "" && src != "" {
content = src
}
match := false
for _, prefix := range []string{
"https://images.cdn.yle.fi/image/upload/c_",
"https://images.cdn.yle.fi/image/upload/f_",
"https://images.cdn.yle.fi/image/upload/fl_",
"https://images.cdn.yle.fi/image/upload/h_",
"https://images.cdn.yle.fi/image/upload/q_",
"https://images.cdn.yle.fi/image/upload/w_",
"https://images.cdn.yle.fi/image/upload/x_",
"https://images.cdn.yle.fi/image/upload/y_",
} {
if strings.HasPrefix(content, prefix) {
match = true
}
}
// Fix image SRCs, avoid Yle cropping service because it's slow.
if match {
// https://images.cdn.yle.fi/image/upload/f_auto,fl_progressive/q_88/w_4819,h_2711,c_crop,x_431,y_422/w_1200/v1622036527/39-81151860ae4f34508bf.jpg
// =>
// https://images.cdn.yle.fi/image/upload/v1622036527/39-81151860ae4f34508bf.jpg
parts := strings.Split(content, "/")
parts = append(parts[0:5], parts[len(parts)-2:]...)
content = strings.Join(parts, "/")
}
for i := range img.Attr {
if img.Attr[i].Key == "src" {
img.Attr[i].Val = content
}
}
}
content, err := sel.Html()
if err != nil {
return err
}
category = fmt.Sprintf("<p>Kategori: %s</p>", category)
articleCache.Store(key, articleData{
Author: author,
Content: category + content,
})
return nil
}(); err != nil {
log.Printf("Skipping item %d: %v", i, err)
return nil, nil
}
return nil, nil
})
if err != nil {
return err
}
return nil
})
}
// Clear stale cache while we're waiting.
articleCache.Range(func(key, value interface{}) bool {
k := key.(articleKey)
if !currentGUIDs[k.guid] {
log.Printf("Article %s expired, removing from cache", k.guid)
articleCache.Delete(k)
}
return true
})
if err = eg.Wait(); err != nil {
return nil, err
}
newFeed := &feeds.Feed{
Title: feed.Title,
Link: &feeds.Link{Href: feed.FeedLink},
Description: feed.Description,
Updated: *feed.UpdatedParsed,
}
if len(feed.Authors) > 0 {
newFeed.Author = &feeds.Author{
Name: feed.Authors[0].Name,
Email: feed.Authors[0].Email,
}
}
if feed.PublishedParsed != nil {
newFeed.Created = *feed.PublishedParsed
}
if feed.UpdatedParsed != nil {
newFeed.Updated = *feed.UpdatedParsed
}
for _, item := range feed.Items {
key := newArticleKey(item)
var data articleData
if c, ok := articleCache.Load(key); ok {
data = c.(articleData)
}
newItem := &feeds.Item{
Title: item.Title,
Link: &feeds.Link{Href: item.Link},
Author: &feeds.Author{Name: data.Author},
Description: item.Description,
Id: item.GUID,
Content: data.Content,
}
if item.PublishedParsed != nil {
newItem.Created = *item.PublishedParsed
}
if item.UpdatedParsed != nil {
newItem.Updated = *item.UpdatedParsed
}
newFeed.Items = append(newFeed.Items, newItem)
}
rss, err := newFeed.ToRss()
if err != nil {
return nil, err
}
return []byte(rss), nil
}