-
Notifications
You must be signed in to change notification settings - Fork 206
/
html.go
244 lines (224 loc) · 6.12 KB
/
html.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
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package html
import (
"bytes"
"fmt"
"strings"
api "github.com/documize/community/core/convapi"
"github.com/documize/community/core/log"
"github.com/documize/community/core/utility"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"golang.org/x/net/context"
)
const maxTitle = 2000 // NOTE: must be the same length as database page.title
const maxBody = 4000000 // NOTE: must be less than the mysql max_allowed_packet limit, amongst other values
type htmlToSplit struct {
CFR *api.DocumentConversionResponse
thisSect api.Page
nodeCache map[*html.Node]bool
}
// Convert provides the standard interface for conversion of an HTML document.
// All the function does is return a pointer to api.DocumentConversionResponse with
// PagesHTML set to the given (*api.DocumentConversionRequest).Filedata - so effectively a no-op.
func Convert(ctx context.Context, in interface{}) (interface{}, error) {
return &api.DocumentConversionResponse{
PagesHTML: in.(*api.DocumentConversionRequest).Filedata}, nil
}
// SplitIfHTML splits HTML code into pages, if it exists.
func SplitIfHTML(req *api.DocumentConversionRequest, res *api.DocumentConversionResponse) error {
if len(res.PagesHTML) == 0 {
return nil
}
hd := &htmlToSplit{CFR: res, nodeCache: make(map[*html.Node]bool)}
err := hd.testableSplit(req, res)
/*
for k, v := range hd.CFR.Pages {
fmt.Printf("DEBUG hd.CFR.Pages[%d] = Level: %d Title: %s len(Body)=%d\n",
k, v.Level, v.Title, len(v.Body))
}
*/
return err
}
// testableSplit, NOTE pointer receiver so that test code can inspect generated datastructures.
func (h *htmlToSplit) testableSplit(request *api.DocumentConversionRequest,
response *api.DocumentConversionResponse) error {
doc, err := html.Parse(bytes.NewReader(response.PagesHTML))
if err != nil {
return err
}
if doc.Type != html.DocumentNode {
return fmt.Errorf("no HTML document node")
}
for htm := doc.FirstChild; htm != nil; htm = htm.NextSibling {
if htm.Type == html.ElementNode && htm.DataAtom == atom.Html {
for bdy := htm.FirstChild; bdy != nil; bdy = bdy.NextSibling {
if bdy.Type == html.ElementNode && bdy.DataAtom == atom.Body {
h.thisSect = api.Page{
Level: 1,
Title: utility.BeautifyFilename(request.Filename),
Body: []byte(``)}
err := h.processChildren(bdy)
if err != nil {
h.CFR.Err = err.Error()
}
h.CFR.Pages = append(h.CFR.Pages, h.thisSect)
}
}
}
}
return nil
}
func getLevel(at atom.Atom) uint64 {
level := uint64(1)
switch at {
case atom.H6:
level++
fallthrough
case atom.H5:
level++
fallthrough
case atom.H4:
level++
fallthrough
case atom.H3:
level++
fallthrough
case atom.H2:
level++
fallthrough
case atom.H1:
level++
}
return level
}
func (h *htmlToSplit) processChildren(bdy *html.Node) error {
for c := bdy.FirstChild; c != nil; c = c.NextSibling {
var err error
if c.Type == html.ElementNode {
if level := getLevel(c.DataAtom); level > 1 {
err = h.renderHeading(c, level)
} else {
err = h.renderNonHeading(c)
}
} else {
err = h.renderAppend(c)
}
if err != nil {
return err
}
}
return nil
}
func stripZeroWidthSpaces(str string) string {
ret := ""
for _, r := range str {
if r != 0x200B { // zero width space
ret += string(r) // stripped of zero-width spaces
}
}
return ret
}
func (h *htmlToSplit) renderHeading(c *html.Node, level uint64) error {
byt, err := byteRenderChildren(c) // get heading html
if err != nil {
return err
}
str, err := utility.HTML(string(byt)).Text(false) // heading text
if err != nil {
return err
}
str = stripZeroWidthSpaces(str)
if strings.TrimSpace(str) != "" { // only put in non-empty headings
h.newSect(str, level)
}
return nil
}
func (h *htmlToSplit) newSect(tstr string, level uint64) {
h.CFR.Pages = append(h.CFR.Pages, h.thisSect)
title := tstr //was: utility.EscapeHTMLcomplexChars(tstr) -- removed to avoid double-escaping
body := ``
if len(title) > maxTitle {
body = title[maxTitle:]
title = title[:maxTitle]
}
h.thisSect = api.Page{
Level: level,
Title: title,
Body: []byte(body)}
}
func (h *htmlToSplit) renderNonHeading(c *html.Node) error {
if h.nodeContainsHeading(c) { // ignore this atom in order to get at the contents
err := h.processChildren(c)
if err != nil {
return err
}
} else {
if err := h.renderAppend(c); err != nil {
return err
}
}
return nil
}
func (h *htmlToSplit) renderAppend(c *html.Node) error {
byt, err := byteRender(c)
if err != nil {
return err
}
ebyt := utility.EscapeHTMLcomplexCharsByte(byt)
if len(ebyt) > maxBody {
msg := fmt.Sprintf("(Documize warning: HTML render element ignored, size of %d exceeded maxBody of %d.)", len(ebyt), maxBody)
log.Info(msg)
ebyt = []byte("<p><b>" + msg + "</b></p>")
}
if len(h.thisSect.Body)+len(ebyt) > maxBody {
h.newSect("-", h.thisSect.Level+1) // plus one so that the new "-" one is part of the previous
}
h.thisSect.Body = append(h.thisSect.Body, ebyt...)
return nil
}
func byteRender(n *html.Node) ([]byte, error) {
var b bytes.Buffer
err := html.Render(&b, n)
return b.Bytes(), err
}
func byteRenderChildren(n *html.Node) ([]byte, error) {
var b bytes.Buffer
for c := n.FirstChild; c != nil; c = c.NextSibling {
err := html.Render(&b, c)
if err != nil {
return nil, err
}
}
return b.Bytes(), nil
}
func (h *htmlToSplit) nodeContainsHeading(n *html.Node) bool {
val, ok := h.nodeCache[n]
if ok {
return val
}
switch n.DataAtom {
case atom.H6, atom.H5, atom.H4, atom.H3, atom.H2, atom.H1:
h.nodeCache[n] = true
return true
default:
for c := n.FirstChild; c != nil; c = c.NextSibling {
if h.nodeContainsHeading(c) {
h.nodeCache[n] = true
h.nodeCache[c] = true
return true
}
}
}
h.nodeCache[n] = false
return false
}