-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadability.go
2240 lines (1956 loc) · 71.1 KB
/
readability.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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010 Arc90 Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This code is heavily based on Arc90's readability.js (1.7.1) script
* available at: http://code.google.com/p/arc90labs-readability
*/
package readability
import (
"encoding/json"
"fmt"
"log/slog"
"math"
"net/url"
"reflect"
"slices"
"strconv"
"strings"
)
const (
flagStripUnlikelys = 0x1
flagWeightClasses = 0x2
flagCleanConditionally = 0x4
// Max number of nodes supported by this parser. Default: 0 (no limit)
defaultMaxElemsToParse = 0
// The number of top candidates to consider when analysing how
// tight the competition is among candidates.
defaultNTopCandidates = 5
// The default number of chars an article must have in order to return a result
defaultCharThreshold = 500
)
var (
// Element tags to score by default.
defaultTagsToScore = []string{"SECTION", "H2", "H3", "H4", "H5", "H6", "P", "TD", "PRE"}
unlinkelyRoles = []string{"menu", "menubar", "complementary", "navigation", "alert", "alertdialog", "dialog"}
divToPElemns = []string{"BLOCKQUOTE", "DL", "DIV", "IMG", "OL", "P", "PRE", "TABLE", "UL"}
alterToDiveExceptions = []string{"DIV", "ARTICLE", "SECTION", "P"}
presentationalAttribute = []string{"align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "hspace", "rules", "style", "valign", "vspace"}
deprecatedSizeAttributeElems = []string{"TABLE", "TH", "TD", "HR", "PRE"}
// The commented out elements qualify as phrasing content but tend to be
// removed by readability when put into paragraphs, so we ignore them here.
phrasingElems = []string{
// "CANVAS", "IFRAME", "SVG", "VIDEO",
"ABBR", "AUDIO", "B", "BDO", "BR", "BUTTON", "CITE", "CODE", "DATA",
"DATALIST", "DFN", "EM", "EMBED", "I", "IMG", "INPUT", "KBD", "LABEL",
"MARK", "MATH", "METER", "NOSCRIPT", "OBJECT", "OUTPUT", "PROGRESS", "Q",
"RUBY", "SAMP", "SCRIPT", "SELECT", "SMALL", "SPAN", "STRONG", "SUB",
"SUP", "TEXTAREA", "TIME", "VAR", "WBR"}
// These are the classes that readability sets itself.
classesToPreserve = []string{"page"}
)
type Readability struct {
options *Options
flags int
doc *Node
articleTitle string
articleByline string
articleDir string
articleSiteName string
articleLang string
attempts []*attempt
}
type attempt struct {
articleContent *Node
textLength int
}
// New is the public constructor of Readability and it supports the following options:
// - options.debug
// - options.maxElemsToParse
// - options.nbTopCandidates
// - options.charThreshold
// - this.classesToPreseve
// - options.keepClasses
// - options.serializer
func New(htmlSource, uri string, opts ...Option) (*Readability, error) {
if htmlSource == "" {
return nil, fmt.Errorf("first argument to Readability constructor should be a HTML document")
}
r := &Readability{
options: defaultOpts(),
}
// Configurable options
for _, opt := range opts {
opt(r.options)
}
r.doc = newDOMParser().parse(htmlSource, uri)
if r.doc == nil || r.doc.Body == nil {
return nil, fmt.Errorf("cannot parse doc")
}
// Start with all flags set
r.flags = flagStripUnlikelys | flagWeightClasses | flagCleanConditionally
return r, nil
}
type Result struct {
// article title
Title string
// HTML string of processed article HTMLContent
HTMLContent string
// text content of the article, with all the HTML tags removed
TextContent string
// length of an article, in characters (runes)
Length int
// article description, or short excerpt from the content
Excerpt string
// author metadata
Byline string
// content direction
Dir string
// name of the site
SiteName string
// content language
Lang string
// published time
PublishedTime string
}
// Run any post-process modifications to article content as necessary.
func (r *Readability) postProcessContent(articleContent *Node) {
// Readability cannot open relative uris so we convert them to absolute uris.
r.fixRelativeUris(articleContent)
r.simplifyNestedElements(articleContent)
if !r.options.keepClasses {
// Remove classes.
r.cleanClasses(articleContent)
}
}
// Iterates over a NodeList, calls `filterFn` for each node and removes node
// if function returned `true`.
// If function is not passed, removes all the nodes in node list.
func (r *Readability) removeNodes(nodeList []*Node, filterFn func(n *Node) bool) {
for i := len(nodeList) - 1; i >= 0; i-- {
node := nodeList[i]
parentNode := node.ParentNode
if parentNode != nil {
if filterFn == nil || filterFn(node) {
if _, err := parentNode.RemoveChild(node); err != nil {
slog.Error("cannot remove child", slog.String("err", err.Error()))
}
}
}
}
}
// Iterates over a NodeList, and calls setNodeTag for each node.
func (r *Readability) replaceNodeTags(nodeList []*Node, newtagName string) {
for _, node := range nodeList {
r.setNodeTag(node, newtagName)
}
}
// Iterate over a NodeList, return true if any of the provided iterate
// function calls returns true, false otherwise.
func (r *Readability) someNode(nodeList []*Node, fn func(n *Node) bool) bool {
for _, node := range nodeList {
if fn(node) {
return true
}
}
return false
}
// Iterate over a NodeList, return true if all of the provided iterate
// function calls return true, false otherwise.
func (r *Readability) everyNode(nodeList []*Node, fn func(n *Node) bool) bool {
for _, node := range nodeList {
if !fn(node) {
return false
}
}
return true
}
// Concat all nodelists passed as arguments.
func (r *Readability) concatNodeLists(nodeLists ...[]*Node) []*Node {
ret := make([]*Node, 0)
for _, list := range nodeLists {
ret = append(ret, list...)
}
return ret
}
func (r *Readability) getAllNodesWithTag(n *Node, tagNames ...string) []*Node {
nodes := make([]*Node, 0)
for _, tag := range tagNames {
nodes = append(nodes, n.getElementsByTagName(tag)...)
}
return nodes
}
// Removes the class="" attribute from every element in the given
// subtree, except those that match CLASSES_TO_PRESERVE and
// the classesToPreserve array from the options object.
func (r *Readability) cleanClasses(n *Node) {
className := n.GetAttribute("class")
if className != "" {
className = strings.Join(filter(r.preserve, multipleWhitespaces.Split(className, -1)...), " ")
}
if className != "" {
n.SetAttribute("class", className)
} else {
n.RemoveAttribute("class")
}
for n := n.FirstElementChild(); n != nil; n = n.NextElementSibling {
r.cleanClasses(n)
}
}
func (r *Readability) preserve(s string) bool {
return slices.Contains(r.options.classesToPreserve, s)
}
func filter(filterFn func(string) bool, strs ...string) []string {
var filtered []string
for _, str := range strs {
if filterFn(str) {
filtered = append(filtered, str)
}
}
return filtered
}
// Converts each <a> and <img> uri in the given element to an absolute URI,
// ignoring #ref URIs.
func (r *Readability) fixRelativeUris(articleContent *Node) {
baseURI := r.doc.getBaseURI()
documentURI := r.doc.DocumentURI
var toAbsoluteURI = func(uri string) string {
uri = strings.TrimSpace(uri)
// Leave hash links alone if the base URI matches the document URI:
if baseURI == documentURI && []rune(uri)[0] == '#' {
return uri
}
base, err := url.Parse(baseURI)
if err != nil {
// Something went wrong, just return the original:
return uri
}
ref, err := url.Parse(uri)
if err != nil {
// Something went wrong, just return the original:
return uri
}
u := base.ResolveReference(ref)
var abs string
if u.Scheme != "" {
abs += u.Scheme
if strings.HasPrefix(u.Scheme, "http") {
abs += "://"
} else {
abs += ":"
}
}
abs += strings.ToLower(u.Host)
var b, a string
if strings.Contains(uri, "?") {
before, _, _ := strings.Cut(uri, "?")
b = before
} else if strings.Contains(uri, "#") {
before, after, _ := strings.Cut(uri, "#")
b = before
a = after
} else {
b = uri
}
if u.Path != "" {
p := u.Path
if strings.Contains(uri, "%") {
if strings.HasPrefix(uri, "//") {
p = doubleForwardSlashes.ReplaceAllString(b, "")
} else {
p = strings.ReplaceAll(b, abs, "")
}
}
abs += strings.ReplaceAll(p, "/C|/", "/C:/")
} else if u.Opaque != "" {
abs += u.Opaque
} else {
abs += "/"
}
if u.RawQuery != "" {
abs += "?" + u.RawQuery
}
if u.Fragment != "" {
if strings.Contains(a, "%") {
abs += "#" + a
} else {
abs += "#" + u.Fragment
}
}
if strings.HasSuffix(uri, "#") && !strings.HasSuffix(abs, "#") {
abs += "#"
}
if strings.HasSuffix(uri, "?") && !strings.HasSuffix(abs, "?") {
abs += "?"
}
return abs
}
var links = r.getAllNodesWithTag(articleContent, "a")
for _, link := range links {
var href = link.GetAttribute("href")
if href != "" {
// Remove links with javascript: URIs, since
// they won't work after scripts have been removed from the page.
if strings.HasPrefix(href, "javascript:") {
// if the link only contains simple text content, it can be converted to a text node
if len(link.ChildNodes) == 1 && link.ChildNodes[0].NodeType == textNode {
var text = r.doc.createTextNode(link.GetTextContent())
link.ParentNode.ReplaceChild(text, link)
} else {
// if the link has multiple children, they should all be preserved
var container = r.doc.createElementNode("span")
for link.FirstChild() != nil {
container.AppendChild(link.FirstChild())
}
link.ParentNode.ReplaceChild(container, link)
}
} else {
if strings.Contains(href, ",%20") {
var hrefs []string
for _, link := range strings.Split(href, ",%20") {
hrefs = append(hrefs, toAbsoluteURI(link))
}
link.SetAttribute("href", strings.Join(hrefs, ",%20"))
} else {
link.SetAttribute("href", toAbsoluteURI(href))
}
}
}
}
var medias = r.getAllNodesWithTag(articleContent,
"img", "picture", "figure", "video", "audio", "source",
)
for _, media := range medias {
var src = media.GetAttribute("src")
if src != "" {
media.SetAttribute("src", toAbsoluteURI(src))
}
var poster = media.GetAttribute("poster")
if poster != "" {
media.SetAttribute("poster", toAbsoluteURI(poster))
}
var srcset = media.GetAttribute("srcset")
if srcset != "" {
submatches := srcsetUrl.FindAllStringSubmatch(srcset, -1)
var newSrcset []string
for _, submatch := range submatches {
newSrcset = append(newSrcset, toAbsoluteURI(submatch[1])+submatch[2]+submatch[3])
}
if !strings.Contains(srcset, ", ") {
media.SetAttribute("srcset", strings.Join(newSrcset, ""))
} else {
media.SetAttribute("srcset", strings.Join(newSrcset, " "))
}
}
}
}
func (r *Readability) simplifyNestedElements(articleContent *Node) {
var node = articleContent
for node != nil {
if node.ParentNode != nil && slices.Contains([]string{"DIV", "SECTION"}, node.TagName) && !strings.HasPrefix(node.GetId(), "readability") {
if r.isElementWithoutContent(node) {
node = r.removeAndGetNext(node)
continue
} else if r.hasSingleTagInsideElement(node, "DIV") || r.hasSingleTagInsideElement(node, "SECTION") {
var child = node.Children[0]
for i := 0; i < node.GetAttributeLen(); i++ {
child.SetAttribute(node.GetAttributeByIndex(i).getName(), node.GetAttributeByIndex(i).getValue())
}
node.ParentNode.ReplaceChild(child, node)
node = child
continue
}
}
node = r.getNextNode(node, false)
}
}
// Get the article title as an H1.
func (r *Readability) getArticleTitle() string {
var doc = r.doc
var curTitle = strings.TrimSpace(doc.title)
var origTitle = curTitle
// If they had an element with id "title" in their HTML
if curTitle == "" {
titles := doc.getElementsByTagName("title")
if len(titles) != 0 {
curTitle = r.getInnerText(doc.getElementsByTagName("title")[0], true)
origTitle = curTitle
}
}
var titleHadHierarchicalSeparators bool
var wordCount func(string) int = func(s string) int {
return len(multipleWhitespaces.Split(s, -1))
}
// If there's a separator in the title, first remove the final part
if titleFinalPart.MatchString(curTitle) {
titleHadHierarchicalSeparators = titleSeparators.MatchString(curTitle)
submatches := otherTitleSeparators.FindAllStringSubmatch(origTitle, -1)
if len(submatches) != 0 && len(submatches[0]) > 0 {
curTitle = submatches[0][1]
}
// If the resulting title is too short (3 words or fewer), remove
// the first part instead:
if wordCount(curTitle) < 3 {
curTitle = titleFirstPart.ReplaceAllStringFunc(origTitle, func(s string) string {
return s
})
}
} else if strings.Contains(curTitle, ": ") {
// Check if we have an heading containing this exact string, so we
// could assume it's the full title.
var headings = r.concatNodeLists(
doc.getElementsByTagName("h1"),
doc.getElementsByTagName("h2"),
)
var trimmedTitle = strings.TrimSpace(curTitle)
var match = r.someNode(headings, func(heading *Node) bool {
return strings.TrimSpace(heading.GetTextContent()) == trimmedTitle
})
// If we don't, let's extract the title out of the original title string.
if !match {
curTitle = origTitle[strings.LastIndex(origTitle, ":")+1:]
}
// If the title is now too short, try the first colon instead:
if wordCount(curTitle) < 3 {
curTitle = origTitle[strings.Index(origTitle, ":")+1:]
// But if we have too many words before the colon there's something weird
// with the titles and the H tags so let's just use the original title instead
} else if wordCount(origTitle[:strings.Index(origTitle, ":")]) > 5 {
curTitle = origTitle
}
} else if len([]rune(curTitle)) > 150 || len([]rune(curTitle)) < 15 {
var hOnes = doc.getElementsByTagName("h1")
if len(hOnes) == 1 {
curTitle = r.getInnerText(hOnes[0], true)
}
}
curTitle = normalize.ReplaceAllString(strings.TrimSpace(curTitle), " ")
// If we now have 4 words or fewer as our title, and either no
// 'hierarchical' separators (\, /, > or ») were found in the original
// title or we decreased the number of words by more than 1 word, use
// the original title.
var curTitleWordCount = wordCount(curTitle)
if curTitleWordCount <= 4 &&
(!titleHadHierarchicalSeparators || curTitleWordCount != wordCount(separators.ReplaceAllString(origTitle, ""))) {
curTitle = origTitle
}
return curTitle
}
// Prepare the HTML document for readability to scrape it.
// This includes things like stripping javascript, CSS, and handling terrible markup.
func (r *Readability) prepDocument() {
var doc = r.doc
// Remove all style tags in head
r.removeNodes(r.getAllNodesWithTag(doc, "style"), nil)
if doc.Body != nil {
r.replaceBrs(doc.Body)
}
r.replaceNodeTags(r.getAllNodesWithTag(doc, "font"), "SPAN")
}
// Finds the next node, starting from the given node, and ignoring
// whitespace in between. If the given node is an element, the same node is
// returned.
func (r *Readability) nextNode(n *Node) *Node {
var next = n
for next != nil &&
next.NodeType != elementNode &&
whitespace.MatchString(next.GetTextContent()) {
next = next.NextSibling
}
return next
}
// Replaces 2 or more successive <br> elements with a single <p>.
// Whitespace between <br> elements are ignored. For example:
//
// <div>foo<br>bar<br> <br><br>abc</div>
//
// will become:
//
// <div>foo<br>bar<p>abc</p></div>
func (r *Readability) replaceBrs(n *Node) {
for _, br := range r.getAllNodesWithTag(n, "br") {
var next = br.NextSibling
// Whether 2 or more <br> elements have been found and replaced with a
// <p> block.
var replaced = false
// If we find a <br> chain, remove the <br>s until we hit another node
// or non-whitespace. This leaves behind the first <br> in the chain
// (which will be replaced with a <p> later).
for next = r.nextNode(next); next != nil && next.TagName == "BR"; {
replaced = true
var brSibling = next.NextSibling
if _, err := next.ParentNode.RemoveChild(next); err != nil {
slog.Error("cannot remove child", slog.String("err", err.Error()))
}
next = brSibling
}
// If we removed a <br> chain, replace the remaining <br> with a <p>. Add
// all sibling nodes as children of the <p> until we hit another <br>
// chain.
if replaced {
var p = r.doc.createElementNode("p")
br.ParentNode.ReplaceChild(p, br)
next = p.NextSibling
for next != nil {
// If we've hit another <br><br>, we're done adding children to this <p>.
if next.TagName == "BR" {
var nextElem = r.nextNode(next.NextSibling)
if nextElem != nil && nextElem.TagName == "BR" {
break
}
}
if !r.isPhrasingContent(next) {
break
}
// Otherwise, make this node a child of the new <p>.
var sibling = next.NextSibling
p.AppendChild(next)
next = sibling
}
for p.LastChild() != nil && r.isWhitespace(p.LastChild()) {
if _, err := p.RemoveChild(p.LastChild()); err != nil {
slog.Error("cannot remove child", slog.String("err", err.Error()))
}
}
if p.ParentNode.TagName == "P" {
r.setNodeTag(p.ParentNode, "DIV")
}
}
}
}
func (r *Readability) setNodeTag(n *Node, tag string) *Node {
slog.Debug("setNodeTag", "node", n, "tag", tag)
n.LocalName = strings.ToLower(tag)
n.TagName = strings.ToUpper(tag)
return n
}
// Prepare the article node for display. Clean out any inline styles,
// iframes, forms, strip extraneous <p> tags, etc.
func (r *Readability) prepArticle(articleContent *Node) {
r.cleanStyles(articleContent)
// Check for data tables before we continue, to avoid removing items in
// those tables, which will often be isolated even though they're
// visually linked to other content-ful elements (text, images, etc.).
r.markDataTables(articleContent)
r.fixLazyImages(articleContent)
// Clean out junk from the article content
r.cleanConditionally(articleContent, "form")
r.cleanConditionally(articleContent, "fieldset")
r.clean(articleContent, "object")
r.clean(articleContent, "embed")
r.clean(articleContent, "footer")
r.clean(articleContent, "link")
r.clean(articleContent, "aside")
// Clean out elements with little content that have "share" in their id/class combinations from final top candidates,
// which means we don't remove the top candidates even they have "share".
var shareElementThreshold = defaultCharThreshold
for _, topCandidate := range articleContent.Children {
r.cleanMatchedNodes(topCandidate, func(n *Node, matchString string) bool {
return shareElements.MatchString(matchString) &&
len([]rune(n.GetTextContent())) < shareElementThreshold
})
}
r.clean(articleContent, "iframe")
r.clean(articleContent, "input")
r.clean(articleContent, "textarea")
r.clean(articleContent, "select")
r.clean(articleContent, "button")
r.cleanHeaders(articleContent)
// Do these last as the previous stuff may have removed junk
// that will affect these
r.cleanConditionally(articleContent, "table")
r.cleanConditionally(articleContent, "ul")
r.cleanConditionally(articleContent, "div")
// replace H1 with H2 as H1 should be only title that is displayed separately
r.replaceNodeTags(r.getAllNodesWithTag(articleContent, "h1"), "h2")
// Remove extra paragraphs
r.removeNodes(r.getAllNodesWithTag(articleContent, "p"), func(paragraph *Node) bool {
var imgCount = len(paragraph.getElementsByTagName("img"))
var embedCount = len(paragraph.getElementsByTagName("embed"))
var objectCount = len(paragraph.getElementsByTagName("object"))
// At this point, nasty iframes have been removed, only remain embedded video ones.
var iframeCount = len(paragraph.getElementsByTagName("iframe"))
var totalCount = imgCount + embedCount + objectCount + iframeCount
return totalCount == 0 && r.getInnerText(paragraph, false) == ""
})
for _, br := range r.getAllNodesWithTag(articleContent, "br") {
var next = r.nextNode(br.NextSibling)
if next != nil && next.TagName == "P" {
if _, err := br.ParentNode.RemoveChild(br); err != nil {
slog.Error("cannot remove child", slog.String("err", err.Error()))
}
}
}
// Remove single-cell tables
for _, table := range r.getAllNodesWithTag(articleContent, "table") {
var tbody *Node = table
if r.hasSingleTagInsideElement(table, "TBODY") {
tbody = table.FirstElementChild()
}
if r.hasSingleTagInsideElement(tbody, "TR") {
var row = tbody.FirstElementChild()
if r.hasSingleTagInsideElement(row, "TD") {
var cell = row.FirstElementChild()
var tag = "DIV"
if r.everyNode(cell.ChildNodes, r.isPhrasingContent) {
tag = "P"
}
cell = r.setNodeTag(cell, tag)
table.ParentNode.ReplaceChild(cell, table)
}
}
}
}
// Initialize a node with the readability object. Also checks the
// className/id for special names to add to its score.
func (r *Readability) initializeNode(n *Node) {
n.ReadabilityNode = &readabilityNode{
ContentScore: 0,
}
switch n.TagName {
case "DIV":
n.ReadabilityNode.ContentScore += 5
case "PRE", "TD", "BLOCKQUOTE":
n.ReadabilityNode.ContentScore += 3
case "ADDRESS", "OL", "UL", "DL", "DD", "DT", "LI", "FORM":
n.ReadabilityNode.ContentScore -= 3
case "H1", "H2", "H3", "H4", "H5", "H6", "TH":
n.ReadabilityNode.ContentScore -= 5
}
n.ReadabilityNode.ContentScore += r.getClassWeight(n)
}
func (r *Readability) removeAndGetNext(n *Node) *Node {
var nextNode = r.getNextNode(n, true)
if _, err := n.ParentNode.RemoveChild(n); err != nil {
slog.Error("cannot remove child", slog.String("err", err.Error()))
}
return nextNode
}
// Traverse the DOM from node to node, starting at the node passed in.
// Pass true for the second parameter to indicate this node itself
// (and its kids) are going away, and we want the next node over.
// Calling this in a loop will traverse the DOM depth-first.
func (r *Readability) getNextNode(n *Node, ignoreSelfAndKids bool) *Node {
// First check for kids if those aren't being ignored
if !ignoreSelfAndKids && n.FirstElementChild() != nil {
return n.FirstElementChild()
}
// Then for siblings...
if n.NextElementSibling != nil {
return n.NextElementSibling
}
// And finally, move up the parent chain *and* find a sibling
// (because this is depth-first traversal, we will have already
// seen the parent nodes themselves).
n = n.ParentNode
for n != nil && n.NextElementSibling == nil {
n = n.ParentNode
}
if n != nil {
return n.NextElementSibling
}
return n
}
// Compares second text to first one
// 1 = same text, 0 = completely different text.
// Works the way that it splits both texts into words and then finds words that are unique in second text
// the result is given by the lower length of unique parts.
func (r *Readability) textSimilarity(textA, textB string) float64 {
var tokensA = tokenize.Split(strings.ToLower(textA), -1)
var tokensB = tokenize.Split(strings.ToLower(textB), -1)
if len(tokensA) == 0 || len(tokensB) == 0 {
return 0
}
var uniqTokensB []string
for _, t := range tokensB {
if !slices.Contains(tokensA, t) && t != "" {
uniqTokensB = append(uniqTokensB, t)
}
}
var distanceB = float64(len(strings.Join(uniqTokensB, " "))) / float64(len(strings.Join(tokensB, " ")))
return 1 - distanceB
}
func (r *Readability) checkByline(n *Node, matchString string) bool {
if r.articleByline != "" {
return false
}
var rel = n.GetAttribute("rel")
var itemprop = n.GetAttribute("itemprop")
if (rel == "author" || strings.Contains(itemprop, "author") || byline.MatchString(matchString)) && r.isValidByline(n.GetTextContent()) {
r.articleByline = strings.TrimSpace(n.GetTextContent())
return true
}
return false
}
func (r *Readability) getNodeAncestors(n *Node, maxDepth int) []*Node {
var i, ancestors = 0, []*Node{}
for n.ParentNode != nil {
ancestors = append(ancestors, n.ParentNode)
if i++; i == maxDepth {
break
}
n = n.ParentNode
}
return ancestors
}
// Using a variety of metrics (content score, classname, element types), find the content that is
// most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
func (r *Readability) grabArticle(page *Node) *Node {
slog.Debug("**** grabArticle ****")
var doc = r.doc
var isPaging bool
if page != nil {
isPaging = true
}
if page == nil {
page = r.doc.Body
}
// We can't grab an article if we don't have a page!
if page == nil {
slog.Debug("No body found in document. Abort.")
return nil
}
var pageCacheHtml = page.GetInnerHTML()
for {
slog.Debug("Starting grabArticle loop")
var stripUnlikelyCandidates = r.flagIsActive(flagStripUnlikelys)
// First, node prepping. Trash nodes that look cruddy (like ones with the
// class name "comment", etc), and turn divs into P tags where they have been
// used inappropriately (as in, where they contain no other block level elements.)
var elementsToScore []*Node
var n = r.doc.DocumentElement
var shouldRemoveTitleHeader bool = true
for n != nil {
slog.Debug("elementsToScore", "nodeText", n.GetTextContent())
if n.TagName == "HTML" {
r.articleLang = n.GetAttribute("lang")
}
var matchString = n.GetClassName() + " " + n.GetId()
if !isProbablyVisible(n) {
slog.Debug("Removing hidden node - " + matchString)
n = r.removeAndGetNext(n)
continue
}
// User is not able to see elements applied with both "aria-modal = true" and "role = dialog"
if n.GetAttribute("aria-modal") == "true" && n.GetAttribute("role") == "dialog" {
n = r.removeAndGetNext(n)
continue
}
// Check to see if this node is a byline, and remove it if it is.
if r.checkByline(n, matchString) {
n = r.removeAndGetNext(n)
continue
}
if shouldRemoveTitleHeader && r.headerDuplicatesTitle(n) {
slog.Debug("Removing header:", "textContent", strings.TrimSpace(n.GetTextContent()), "articleTitle", strings.TrimSpace(r.articleTitle))
shouldRemoveTitleHeader = false
n = r.removeAndGetNext(n)
continue
}
// Remove unlikely candidates
if stripUnlikelyCandidates {
if unlikelyCandidates.MatchString(matchString) &&
!okMaybeItsACandidate.MatchString(matchString) &&
!r.hasAncestorTag(n, "table", 3, nil) &&
!r.hasAncestorTag(n, "code", 3, nil) &&
n.TagName != "BODY" &&
n.TagName != "A" {
slog.Debug("Removing unlikely candidate", "matchString", matchString)
n = r.removeAndGetNext(n)
continue
}
}
if slices.Contains(unlinkelyRoles, n.GetAttribute("role")) {
slog.Debug("Removing content", "role", n.GetAttribute("role"), "matchString", matchString)
n = r.removeAndGetNext(n)
continue
}
// Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
if (n.TagName == "DIV" || n.TagName == "SECTION" || n.TagName == "HEADER" ||
n.TagName == "H1" || n.TagName == "H2" || n.TagName == "H3" ||
n.TagName == "H4" || n.TagName == "H5" || n.TagName == "H6") &&
r.isElementWithoutContent(n) {
n = r.removeAndGetNext(n)
continue
}
if slices.Contains(defaultTagsToScore, n.TagName) {
elementsToScore = append(elementsToScore, n)
}
// Turn all divs that don't have children block level elements into p's
if n.TagName == "DIV" {
// Put phrasing content into paragraphs.
var p *Node
var childNode = n.FirstChild()
for childNode != nil {
var nextSibling = childNode.NextSibling
if r.isPhrasingContent(childNode) {
if p != nil {
p.AppendChild(childNode)
} else if !r.isWhitespace(childNode) {
p = doc.createElementNode("p")
n.ReplaceChild(p, childNode)
p.AppendChild(childNode)
}
} else if p != nil {
for p.LastChild() != nil && r.isWhitespace(p.LastChild()) {
if _, err := p.RemoveChild(p.LastChild()); err != nil {
slog.Error("cannot remove child", slog.String("err", err.Error()))
}
}
p = nil
}
childNode = nextSibling
}
// Sites like http://mobile.slate.com encloses each paragraph with a DIV
// element. DIVs with only a P element inside and no text content can be
// safely converted into plain P elements to avoid confusing the scoring
// algorithm with DIVs with are, in practice, paragraphs.
if r.hasSingleTagInsideElement(n, "P") && r.getLinkDensity(n) < 0.25 {
var newNode = n.Children[0]
n.ParentNode.ReplaceChild(newNode, n)
n = newNode
elementsToScore = append(elementsToScore, n)
} else if !r.hasChildBlockElement(n) {
n = r.setNodeTag(n, "P")
elementsToScore = append(elementsToScore, n)
}
}
n = r.getNextNode(n, false)
}
// Loop through all paragraphs, and assign a score to them based on how content-y they look.
// Then add their score to their parent node.
// A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
var candidates []*Node
for _, elementToScore := range elementsToScore {
if elementToScore.ParentNode == nil {
continue
}
// If this paragraph is less than 25 characters, don't even count it.
var innerText = r.getInnerText(elementToScore, true)
if len([]rune(innerText)) < 25 {
continue
}
// Exclude nodes with no ancestor.
var ancestors = r.getNodeAncestors(elementToScore, 5)
if len(ancestors) == 0 {
continue
}
var contentScore float64 = 0
// Add a point for the paragraph itself as a base.
contentScore += 1
// Add points for any commas within this paragraph.
contentScore += float64(len(commas.Split(innerText, -1)))
// For every 100 characters in this paragraph, add another point. Up to 3 points.
contentScore += math.Min(math.Floor(float64(len([]rune(innerText)))/100), 3)
for level, ancestor := range ancestors {
if ancestor.TagName == "" || ancestor.ParentNode == nil || ancestor.ParentNode.TagName == "" {
continue
}
if ancestor.ReadabilityNode == nil {
r.initializeNode(ancestor)
candidates = append(candidates, ancestor)
}
// Node score divider:
// - parent: 1 (no division)
// - grandparent: 2
// - great grandparent+: ancestor level * 3
var scoreDivider int
if level == 0 {
scoreDivider = 1
} else if level == 1 {
scoreDivider = 2