Debian Codegraph @

format/htmlparser.go

raw
1 // Copyright (c) 2020 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package format
8
9 import (
10 "fmt"
11 "math"
12 "strconv"
13 "strings"
14
15 "golang.org/x/net/html"
16
17 "maunium.net/go/mautrix/id"
18 )
19
20 type Context map[string]interface{}
21 type TextConverter func(string, Context) string
22 type CodeBlockConverter func(code, language string, ctx Context) string
23 type PillConverter func(displayname, mxid, eventID string, ctx Context) string
24
25 func DefaultPillConverter(displayname, mxid, eventID string, _ Context) string {
26 switch {
27 case len(mxid) == 0, mxid[0] == '@':
28 // User link, always just show the displayname
29 return displayname
30 case len(eventID) > 0:
31 // Event ID link, always just show the link
32 return fmt.Sprintf("https://matrix.to/#/%s/%s", mxid, eventID)
33 case mxid[0] == '!' && displayname == mxid:
34 // Room ID link with no separate display text, just show the link
35 return fmt.Sprintf("https://matrix.to/#/%s", mxid)
36 case mxid[0] == '#':
37 // Room alias link, just show the alias
38 return mxid
39 default:
40 // Other link (e.g. room ID link with display text), show text and link
41 return fmt.Sprintf("%s (https://matrix.to/#/%s)", displayname, mxid)
42 }
43 }
44
45 // HTMLParser is a somewhat customizable Matrix HTML parser.
46 type HTMLParser struct {
47 PillConverter PillConverter
48 TabsToSpaces int
49 Newline string
50 HorizontalLine string
51 BoldConverter TextConverter
52 ItalicConverter TextConverter
53 StrikethroughConverter TextConverter
54 UnderlineConverter TextConverter
55 MonospaceBlockConverter CodeBlockConverter
56 MonospaceConverter TextConverter
57 }
58
59 // TaggedString is a string that also contains a HTML tag.
60 type TaggedString struct {
61 string
62 tag string
63 }
64
65 func (parser *HTMLParser) getAttribute(node *html.Node, attribute string) string {
66 for _, attr := range node.Attr {
67 if attr.Key == attribute {
68 return attr.Val
69 }
70 }
71 return ""
72 }
73
74 // Digits counts the number of digits (and the sign, if negative) in an integer.
75 func Digits(num int) int {
76 if num == 0 {
77 return 1
78 } else if num < 0 {
79 return Digits(-num) + 1
80 }
81 return int(math.Floor(math.Log10(float64(num))) + 1)
82 }
83
84 func (parser *HTMLParser) listToString(node *html.Node, stripLinebreak bool, ctx Context) string {
85 ordered := node.Data == "ol"
86 taggedChildren := parser.nodeToTaggedStrings(node.FirstChild, stripLinebreak, ctx)
87 counter := 1
88 indentLength := 0
89 if ordered {
90 start := parser.getAttribute(node, "start")
91 if len(start) > 0 {
92 counter, _ = strconv.Atoi(start)
93 }
94
95 longestIndex := (counter - 1) + len(taggedChildren)
96 indentLength = Digits(longestIndex)
97 }
98 indent := strings.Repeat(" ", indentLength+2)
99 var children []string
100 for _, child := range taggedChildren {
101 if child.tag != "li" {
102 continue
103 }
104 var prefix string
105 // TODO make bullets and numbering configurable
106 if ordered {
107 indexPadding := indentLength - Digits(counter)
108 prefix = fmt.Sprintf("%d. %s", counter, strings.Repeat(" ", indexPadding))
109 } else {
110 prefix = "* "
111 }
112 str := prefix + child.string
113 counter++
114 parts := strings.Split(str, "\n")
115 for i, part := range parts[1:] {
116 parts[i+1] = indent + part
117 }
118 str = strings.Join(parts, "\n")
119 children = append(children, str)
120 }
121 return strings.Join(children, "\n")
122 }
123
124 func (parser *HTMLParser) basicFormatToString(node *html.Node, stripLinebreak bool, ctx Context) string {
125 str := parser.nodeToTagAwareString(node.FirstChild, stripLinebreak, ctx)
126 switch node.Data {
127 case "b", "strong":
128 if parser.BoldConverter != nil {
129 return parser.BoldConverter(str, ctx)
130 }
131 return fmt.Sprintf("**%s**", str)
132 case "i", "em":
133 if parser.ItalicConverter != nil {
134 return parser.ItalicConverter(str, ctx)
135 }
136 return fmt.Sprintf("_%s_", str)
137 case "s", "del", "strike":
138 if parser.StrikethroughConverter != nil {
139 return parser.StrikethroughConverter(str, ctx)
140 }
141 return fmt.Sprintf("~~%s~~", str)
142 case "u", "ins":
143 if parser.UnderlineConverter != nil {
144 return parser.UnderlineConverter(str, ctx)
145 }
146 case "tt", "code":
147 if parser.MonospaceConverter != nil {
148 return parser.MonospaceConverter(str, ctx)
149 }
150 return fmt.Sprintf("`%s`", str)
151 }
152 return str
153 }
154
155 func (parser *HTMLParser) headerToString(node *html.Node, stripLinebreak bool, ctx Context) string {
156 children := parser.nodeToStrings(node.FirstChild, stripLinebreak, ctx)
157 length := int(node.Data[1] - '0')
158 prefix := strings.Repeat("#", length) + " "
159 return prefix + strings.Join(children, "")
160 }
161
162 func (parser *HTMLParser) blockquoteToString(node *html.Node, stripLinebreak bool, ctx Context) string {
163 str := parser.nodeToTagAwareString(node.FirstChild, stripLinebreak, ctx)
164 childrenArr := strings.Split(strings.TrimSpace(str), "\n")
165 // TODO make blockquote prefix configurable
166 for index, child := range childrenArr {
167 childrenArr[index] = "> " + child
168 }
169 return strings.Join(childrenArr, "\n")
170 }
171
172 func (parser *HTMLParser) linkToString(node *html.Node, stripLinebreak bool, ctx Context) string {
173 str := parser.nodeToTagAwareString(node.FirstChild, stripLinebreak, ctx)
174 href := parser.getAttribute(node, "href")
175 if len(href) == 0 {
176 return str
177 }
178 if parser.PillConverter != nil {
179 parsedMatrix, err := id.ParseMatrixURIOrMatrixToURL(href)
180 if err == nil && parsedMatrix != nil {
181 return parser.PillConverter(str, parsedMatrix.PrimaryIdentifier(), parsedMatrix.SecondaryIdentifier(), ctx)
182 }
183 }
184 if str == href {
185 return str
186 }
187 return fmt.Sprintf("%s (%s)", str, href)
188 }
189
190 func (parser *HTMLParser) tagToString(node *html.Node, stripLinebreak bool, ctx Context) string {
191 switch node.Data {
192 case "blockquote":
193 return parser.blockquoteToString(node, stripLinebreak, ctx)
194 case "ol", "ul":
195 return parser.listToString(node, stripLinebreak, ctx)
196 case "h1", "h2", "h3", "h4", "h5", "h6":
197 return parser.headerToString(node, stripLinebreak, ctx)
198 case "br":
199 return parser.Newline
200 case "b", "strong", "i", "em", "s", "strike", "del", "u", "ins", "tt", "code":
201 return parser.basicFormatToString(node, stripLinebreak, ctx)
202 case "a":
203 return parser.linkToString(node, stripLinebreak, ctx)
204 case "p":
205 return parser.nodeToTagAwareString(node.FirstChild, stripLinebreak, ctx)
206 case "hr":
207 return parser.HorizontalLine
208 case "pre":
209 var preStr, language string
210 if node.FirstChild != nil && node.FirstChild.Type == html.ElementNode && node.FirstChild.Data == "code" {
211 class := parser.getAttribute(node.FirstChild, "class")
212 if strings.HasPrefix(class, "language-") {
213 language = class[len("language-"):]
214 }
215 preStr = parser.nodeToString(node.FirstChild.FirstChild, false, ctx)
216 } else {
217 preStr = parser.nodeToString(node.FirstChild, false, ctx)
218 }
219 if parser.MonospaceBlockConverter != nil {
220 return parser.MonospaceBlockConverter(preStr, language, ctx)
221 }
222 if len(preStr) == 0 || preStr[len(preStr)-1] != '\n' {
223 preStr += "\n"
224 }
225 return fmt.Sprintf("```%s\n%s```", language, preStr)
226 default:
227 return parser.nodeToTagAwareString(node.FirstChild, stripLinebreak, ctx)
228 }
229 }
230
231 func (parser *HTMLParser) singleNodeToString(node *html.Node, stripLinebreak bool, ctx Context) TaggedString {
232 switch node.Type {
233 case html.TextNode:
234 if stripLinebreak {
235 node.Data = strings.Replace(node.Data, "\n", "", -1)
236 }
237 return TaggedString{node.Data, "text"}
238 case html.ElementNode:
239 return TaggedString{parser.tagToString(node, stripLinebreak, ctx), node.Data}
240 case html.DocumentNode:
241 return TaggedString{parser.nodeToTagAwareString(node.FirstChild, stripLinebreak, ctx), "html"}
242 default:
243 return TaggedString{"", "unknown"}
244 }
245 }
246
247 func (parser *HTMLParser) nodeToTaggedStrings(node *html.Node, stripLinebreak bool, ctx Context) (strs []TaggedString) {
248 for ; node != nil; node = node.NextSibling {
249 strs = append(strs, parser.singleNodeToString(node, stripLinebreak, ctx))
250 }
251 return
252 }
253
254 var BlockTags = []string{"p", "h1", "h2", "h3", "h4", "h5", "h6", "ol", "ul", "pre", "blockquote", "div", "hr", "table"}
255
256 func (parser *HTMLParser) isBlockTag(tag string) bool {
257 for _, blockTag := range BlockTags {
258 if tag == blockTag {
259 return true
260 }
261 }
262 return false
263 }
264
265 func (parser *HTMLParser) nodeToTagAwareString(node *html.Node, stripLinebreak bool, ctx Context) string {
266 strs := parser.nodeToTaggedStrings(node, stripLinebreak, ctx)
267 var output strings.Builder
268 for _, str := range strs {
269 tstr := str.string
270 if parser.isBlockTag(str.tag) {
271 tstr = fmt.Sprintf("\n%s\n", tstr)
272 }
273 output.WriteString(tstr)
274 }
275 return strings.TrimSpace(output.String())
276 }
277
278 func (parser *HTMLParser) nodeToStrings(node *html.Node, stripLinebreak bool, ctx Context) (strs []string) {
279 for ; node != nil; node = node.NextSibling {
280 strs = append(strs, parser.singleNodeToString(node, stripLinebreak, ctx).string)
281 }
282 return
283 }
284
285 func (parser *HTMLParser) nodeToString(node *html.Node, stripLinebreak bool, ctx Context) string {
286 return strings.Join(parser.nodeToStrings(node, stripLinebreak, ctx), "")
287 }
288
289 // Parse converts Matrix HTML into text using the settings in this parser.
290 func (parser *HTMLParser) Parse(htmlData string, ctx Context) string {
291 if parser.TabsToSpaces >= 0 {
292 htmlData = strings.Replace(htmlData, "\t", strings.Repeat(" ", parser.TabsToSpaces), -1)
293 }
294 node, _ := html.Parse(strings.NewReader(htmlData))
295 return parser.nodeToTagAwareString(node, true, ctx)
296 }
297
298 // HTMLToText converts Matrix HTML into text with the default settings.
299 func HTMLToText(html string) string {
300 return (&HTMLParser{
301 TabsToSpaces: 4,
302 Newline: "\n",
303 HorizontalLine: "\n---\n",
304 PillConverter: DefaultPillConverter,
305 }).Parse(html, make(Context))
306 }