-
Notifications
You must be signed in to change notification settings - Fork 7
/
readable.go
626 lines (592 loc) · 14 KB
/
readable.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
package url2epub
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"sync"
"time"
"go.yhsif.com/immutable"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"go.yhsif.com/url2epub/grayscale"
)
const (
imgSrc = "src"
imgSrcset = "srcset"
jpgExt = ".jpg"
langKey = "lang"
)
var emptyStringSet = immutable.EmptySet[string]()
var imgAtoms = immutable.SetLiteral(atom.Img, atom.Source)
// A map of:
// key: atoms we want to keep in the readable html.
// value: the attributes we want to keep inside this atom.
var atoms = map[atom.Atom]immutable.Set[string]{
atom.A: immutable.SetLiteral(
"href",
),
atom.Abbr: immutable.SetLiteral(
"title",
),
atom.Acronym: immutable.SetLiteral(
"title",
),
atom.Html: immutable.SetLiteral(
"lang",
),
atom.Img: immutable.SetLiteral(
imgSrc,
imgSrcset,
"alt",
// Do not keep width and height here as we might downscale it
),
atom.Source: immutable.SetLiteral(
imgSrc,
imgSrcset,
"type",
),
atom.Article: emptyStringSet,
atom.B: emptyStringSet,
atom.Big: emptyStringSet,
atom.Blockquote: emptyStringSet,
atom.Body: emptyStringSet,
atom.Br: emptyStringSet,
atom.Center: emptyStringSet,
atom.Cite: emptyStringSet,
atom.Code: emptyStringSet,
atom.Content: emptyStringSet,
atom.Del: emptyStringSet,
atom.Details: emptyStringSet,
atom.Dd: emptyStringSet,
atom.Dfn: emptyStringSet,
atom.Div: emptyStringSet,
atom.Dl: emptyStringSet,
atom.Dt: emptyStringSet,
atom.Em: emptyStringSet,
atom.Figure: emptyStringSet,
atom.Figcaption: emptyStringSet,
atom.Footer: emptyStringSet,
atom.H1: emptyStringSet,
atom.H2: emptyStringSet,
atom.H3: emptyStringSet,
atom.H4: emptyStringSet,
atom.H5: emptyStringSet,
atom.H6: emptyStringSet,
atom.Head: emptyStringSet,
atom.Header: emptyStringSet,
atom.I: emptyStringSet,
atom.Li: emptyStringSet,
atom.Main: emptyStringSet,
atom.Mark: emptyStringSet,
atom.Noscript: emptyStringSet,
atom.Ol: emptyStringSet,
atom.P: emptyStringSet,
atom.Picture: emptyStringSet,
atom.Pre: emptyStringSet,
atom.Q: emptyStringSet,
atom.S: emptyStringSet,
atom.Section: emptyStringSet,
atom.Small: emptyStringSet,
atom.Span: emptyStringSet,
atom.Strike: emptyStringSet,
atom.Strong: emptyStringSet,
atom.Sub: emptyStringSet,
atom.Summary: emptyStringSet,
atom.Sup: emptyStringSet,
atom.Table: emptyStringSet,
atom.Tbody: emptyStringSet,
atom.Tfoot: emptyStringSet,
atom.Td: emptyStringSet,
atom.Th: emptyStringSet,
atom.Thead: emptyStringSet,
atom.Tr: emptyStringSet,
atom.Time: emptyStringSet,
atom.Title: emptyStringSet,
atom.U: emptyStringSet,
atom.Ul: emptyStringSet,
}
// The atoms that we need to keep even if they have no attributes and no
// children after stripping.
var keepEmptyAtoms = immutable.SetLiteral(
atom.Br,
atom.Td,
)
// Replace some amp elements that's not defined in atoms with their
// atom-equivalents.
var ampAtoms = map[string]atom.Atom{
"amp-img": atom.Img,
}
// ReadableArgs defines the args used by Readable function.
type ReadableArgs struct {
// Base URL of the document, used in case the image URLs are relative.
BaseURL *url.URL
// User-Agent to be used to download images.
UserAgent string
// Directory prefix for downloaded images.
ImagesDir string
// If Grayscale is set to true,
// all images will be grayscaled and encoded as jpegs.
Grayscale bool
// Downscale images to fit in NxN,
// only used when Grayscale is set to true.
FitImage int
// Set the minimal number of readable nodes under the first article node to
// use that instead of body.
//
// If the first article node has too few nodes under it, we'll skip using it
// and use the body node instead.
//
// <=0 to disable this check (always use first article node if found).
MinArticleNodes int
}
// Readable strips node n into a readable one, with all images downloaded and
// replaced.
func (n *Node) Readable(ctx context.Context, args ReadableArgs) (*html.Node, map[string]io.Reader, error) {
imgPointers := make(map[string]*io.Reader)
imgMapping := make(map[string]string)
var wg sync.WaitGroup
var counter int
head, err := n.FindFirstAtomNode(atom.Head).readableRecursive(
ctx,
&wg,
args.BaseURL,
args.UserAgent,
args.ImagesDir,
imgPointers,
imgMapping,
&counter,
args.Grayscale,
args.FitImage,
)
if err != nil {
return nil, nil, err
}
if head == nil {
head = &html.Node{
Type: html.ElementNode,
DataAtom: atom.Head,
Data: atom.Head.String(),
}
}
head.AppendChild(&html.Node{
Type: html.ElementNode,
DataAtom: atom.Meta,
Data: atom.Meta.String(),
Attr: []html.Attribute{
{
Key: "itemprop",
Val: "generated-by: https://pkg.go.dev/go.yhsif.com/url2epub#Node.Readable",
},
},
})
head.AppendChild(&html.Node{
Type: html.ElementNode,
DataAtom: atom.Meta,
Data: atom.Meta.String(),
Attr: []html.Attribute{
{
Key: "itemprop",
Val: "generated-at: " + time.Now().Format(time.RFC3339),
},
},
})
if args.BaseURL != nil {
head.AppendChild(&html.Node{
Type: html.ElementNode,
DataAtom: atom.Meta,
Data: atom.Meta.String(),
Attr: []html.Attribute{
{
Key: "itemprop",
Val: "generated-from: " + args.BaseURL.String(),
},
},
})
}
var body *html.Node
articleNode := n.FindFirstAtomNode(atom.Article)
if articleNode != nil && args.MinArticleNodes > 0 {
count, hasMin := articleNode.countRecursive(args.MinArticleNodes)
slog.DebugContext(ctx, "found article node", "nodes", count, "min", args.MinArticleNodes, "hasMin", hasMin)
if !hasMin {
articleNode = nil
}
}
article, err := articleNode.readableRecursive(
ctx,
&wg,
args.BaseURL,
args.UserAgent,
args.ImagesDir,
imgPointers,
imgMapping,
&counter,
args.Grayscale,
args.FitImage,
)
if err != nil {
return nil, nil, err
}
if article == nil {
body, err = n.FindFirstAtomNode(atom.Body).readableRecursive(
ctx,
&wg,
args.BaseURL,
args.UserAgent,
args.ImagesDir,
imgPointers,
imgMapping,
&counter,
args.Grayscale,
args.FitImage,
)
if err != nil {
return nil, nil, err
}
if body == nil {
return nil, nil, errors.New("no body tag found")
}
} else {
body = &html.Node{
Type: html.ElementNode,
DataAtom: atom.Body,
Data: atom.Body.String(),
}
body.AppendChild(article)
}
root := &html.Node{
Type: html.ElementNode,
DataAtom: atom.Html,
Data: atom.Html.String(),
}
if lang := n.GetLang(); lang != "" {
root.Attr = []html.Attribute{
{
Key: langKey,
Val: lang,
},
}
}
if head != nil {
root.AppendChild(head)
}
root.AppendChild(body)
wg.Wait()
images := make(map[string]io.Reader, len(imgPointers))
for k, v := range imgPointers {
var reader io.Reader
if v != nil && *v != nil {
reader = *v
} else {
reader = strings.NewReader("")
}
images[k] = reader
}
return root, images, err
}
var allowedSrcSchemes = immutable.SetLiteral(
"", // important for relative image urls
"https",
"http",
)
func tryParseImgURL(s string) *url.URL {
u, err := url.Parse(s)
if err == nil && allowedSrcSchemes.Contains(u.Scheme) {
return u
}
return nil
}
// Examples:
// * "url 640w"
// * " url 640w"
// * "url"
var srcsetRE = regexp.MustCompile(`^\s*(.+?)(?: (\d+)w)?\s*$`)
func tryParseImgSrcset(s string) *url.URL {
urls := strings.Split(s, ",")
var maxWidth int64 = -1
var maxURL *url.URL
for _, item := range urls {
groups := srcsetRE.FindStringSubmatch(item)
if len(groups) == 0 {
continue
}
// Should not fail based on the regexp
width, _ := strconv.ParseInt(groups[2], 10, 64)
if width > maxWidth {
u := tryParseImgURL(groups[1])
if u == nil {
continue
}
maxWidth = width
maxURL = u
}
}
return maxURL
}
func findSrcURLFromIMGNode(
node *html.Node,
srcIndex int,
srcsetIndex int,
) *url.URL {
if srcIndex >= 0 {
if u := tryParseImgURL(node.Attr[srcIndex].Val); u != nil {
return u
}
}
if srcsetIndex < 0 {
return nil
}
return tryParseImgSrcset(node.Attr[srcsetIndex].Val)
}
func (n *Node) countRecursive(minCount int) (count int, hasMin bool) {
if n == nil {
return 0, false
}
node := n.AsNode()
switch node.Type {
default:
return 0, false
case html.TextNode:
if strings.TrimSpace(node.Data) == "" {
// This text node is all white space, skipping.
return 0, false
}
if minCount <= 1 {
return 0, true
}
return 1, false
case html.ElementNode:
if _, ok := atoms[node.DataAtom]; !ok {
// Not an atom we want to keep.
return 0, false
}
count += 1
minCount -= 1
if minCount <= 0 {
return 0, true
}
for c := range n.Children() {
subCount, hit := c.countRecursive(minCount)
if hit {
hasMin = hit
break
}
count += subCount
minCount -= subCount
if minCount <= 0 {
hasMin = hit
break
}
}
if hasMin {
return 0, true
}
return count, false
}
}
func (n *Node) readableRecursive(
ctx context.Context,
wg *sync.WaitGroup,
baseURL *url.URL,
userAgent string,
imagesDir string,
images map[string]*io.Reader,
imgMapping map[string]string,
imgCounter *int,
gray bool,
fitImage int,
) (*html.Node, error) {
if n == nil {
return nil, nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
node := n.AsNode()
switch node.Type {
default:
return nil, nil
case html.TextNode:
if strings.TrimSpace(node.Data) == "" {
// This text node is all white space, skipping.
return nil, nil
}
return &html.Node{
Type: node.Type,
Data: node.Data,
}, nil
case html.ElementNode:
if node.DataAtom == atom.Noscript {
child := node.FirstChild
if child == nil || child != node.LastChild || child.Type != html.TextNode {
// We only care about a single TextNode inside noscript.
return nil, nil
}
childNode, err := html.Parse(strings.NewReader(child.Data))
if err != nil {
slog.DebugContext(
ctx,
"Failed to parse noscript data",
"err", err,
"data", child.Data,
)
}
if img := FromNode(childNode).FindFirstAtomNode(atom.Img); img != nil {
node = img.AsNode()
} else {
// No img node found
return nil, nil
}
}
// Copy key fields.
newNode := &html.Node{
Type: node.Type,
DataAtom: node.DataAtom,
Data: node.Data,
}
if newNode.DataAtom == 0 {
newNode.DataAtom = ampAtoms[newNode.Data]
if newNode.DataAtom != 0 {
newNode.Data = newNode.DataAtom.String()
}
}
attrs, ok := atoms[newNode.DataAtom]
if !ok {
// Not an atom we want to keep.
return nil, nil
}
srcIndex := -1
srcsetIndex := -1
for _, attr := range node.Attr {
i := len(newNode.Attr)
if !attrs.Contains(attr.Key) {
continue
}
newNode.Attr = append(newNode.Attr, attr)
switch attr.Key {
case imgSrc:
srcIndex = i
case imgSrcset:
srcsetIndex = i
}
}
if imgAtoms.Contains(newNode.DataAtom) {
// Special handling for images.
newNode.DataAtom = atom.Img
newNode.Data = atom.Img.String()
srcURL := findSrcURLFromIMGNode(newNode, srcIndex, srcsetIndex)
if srcURL == nil {
// No usable src, skip this image
return nil, nil
}
srcURL = baseURL.ResolveReference(srcURL)
src := srcURL.String()
if srcIndex < 0 {
srcIndex = len(newNode.Attr)
newNode.Attr = append(newNode.Attr, html.Attribute{
Key: imgSrc,
})
}
if filename, exists := imgMapping[src]; exists {
// This image url already appeared before, reuse the same local file.
newNode.Attr[srcIndex].Val = filename
} else {
*imgCounter++
ext := path.Ext(srcURL.Path)
if gray {
ext = jpgExt
}
filename = fmt.Sprintf("%03d", *imgCounter) + ext
filename = path.Join(imagesDir, filename)
newNode.Attr[srcIndex].Val = filename
imgMapping[src] = filename
reader := new(io.Reader)
images[filename] = reader
wg.Add(1)
go func() {
defer wg.Done()
downloadImage(ctx, srcURL, userAgent, reader, gray, fitImage)
}()
}
// Remove srcset if they are there
if srcsetIndex >= 0 {
newNode.Attr = append(
newNode.Attr[:srcsetIndex],
newNode.Attr[srcsetIndex+1:]...,
)
}
// Skip adding childrens to img tags.
// When img tags have childrens, the render will fail with:
// html: void element <img> has child nodes
// But amp-img tags are actually allowed to have children (fallbacks)
// For those cases, just drop them.
// See https://github.com/fishy/url2epub/issues/3.
return newNode, nil
}
for c := range n.Children() {
child, err := c.readableRecursive(ctx, wg, baseURL, userAgent, imagesDir, images, imgMapping, imgCounter, gray, fitImage)
if err != nil {
return nil, err
}
if child == nil {
continue
}
newNode.AppendChild(child)
}
if len(newNode.Attr) == 0 && newNode.FirstChild == nil && !keepEmptyAtoms.Contains(newNode.DataAtom) {
// This node has no children and no attributes, skipping
return nil, nil
}
return newNode, nil
}
}
func downloadImage(ctx context.Context, src *url.URL, userAgent string, dest *io.Reader, gray bool, fitImage int) {
body, _, err := get(ctx, src, userAgent)
if err != nil {
slog.ErrorContext(
ctx,
"Error while trying to get image",
"err", err,
"url", src.String(),
)
return
}
defer DrainAndClose(body)
if !gray {
buf := new(bytes.Buffer)
io.Copy(buf, body)
*dest = buf
return
}
img, orig, err := grayscale.FromReader(body)
if err != nil {
slog.ErrorContext(
ctx,
"Error while trying to grayscale",
"err", err,
"url", src.String(),
)
*dest = orig
return
}
reader, err := grayscale.ToJPEG(grayscale.Downscale(img, fitImage))
if err != nil {
slog.ErrorContext(
ctx,
"Error while trying to encode grayscaled %q: %v",
"err", err,
"url", src.String(),
)
*dest = orig
return
}
*dest = reader
}