aboutsummaryrefslogtreecommitdiff
path: root/vendor/maunium.net/go/mautrix/format/htmlparser.go
blob: b681be613666cab8b12e0f07c703794c98a1e5b6 (plain)
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
// Copyright 2018 Tulir Asokan
package format

import (
	"fmt"
	"math"
	"regexp"
	"strings"

	"golang.org/x/net/html"
	"strconv"
)

var MatrixToURL = regexp.MustCompile("^(?:https?://)?(?:www\\.)?matrix\\.to/#/([#@!+].*)(?:/(\\$.+))?")

type TextConverter func(string) string

type HTMLParser struct {
	PillConverter           func(mxid, eventID string) string
	TabsToSpaces            int
	Newline                 string
	BoldConverter           TextConverter
	ItalicConverter         TextConverter
	StrikethroughConverter  TextConverter
	UnderlineConverter      TextConverter
	MonospaceBlockConverter TextConverter
	MonospaceConverter      TextConverter
}

type TaggedString struct {
	string
	tag string
}

func (parser *HTMLParser) getAttribute(node *html.Node, attribute string) string {
	for _, attr := range node.Attr {
		if attr.Key == attribute {
			return attr.Val
		}
	}
	return ""
}

func Digits(num int) int {
	return int(math.Floor(math.Log10(float64(num))) + 1)
}

func (parser *HTMLParser) listToString(node *html.Node, stripLinebreak bool) string {
	ordered := node.Data == "ol"
	taggedChildren := parser.nodeToTaggedStrings(node.FirstChild, stripLinebreak)
	counter := 1
	indentLength := 0
	if ordered {
		start := parser.getAttribute(node, "start")
		if len(start) > 0 {
			counter, _ = strconv.Atoi(start)
		}

		longestIndex := (counter - 1) + len(taggedChildren)
		indentLength = Digits(longestIndex)
	}
	indent := strings.Repeat(" ", indentLength+2)
	var children []string
	for _, child := range taggedChildren {
		if child.tag != "li" {
			continue
		}
		var prefix string
		if ordered {
			indexPadding := indentLength - Digits(counter)
			prefix = fmt.Sprintf("%d. %s", counter, strings.Repeat(" ", indexPadding))
		} else {
			prefix = "● "
		}
		str := prefix + child.string
		counter++
		parts := strings.Split(str, "\n")
		for i, part := range parts[1:] {
			parts[i+1] = indent + part
		}
		str = strings.Join(parts, "\n")
		children = append(children, str)
	}
	return strings.Join(children, "\n")
}

func (parser *HTMLParser) basicFormatToString(node *html.Node, stripLinebreak bool) string {
	str := parser.nodeToTagAwareString(node.FirstChild, stripLinebreak)
	switch node.Data {
	case "b", "strong":
		if parser.BoldConverter != nil {
			return parser.BoldConverter(str)
		}
		return fmt.Sprintf("**%s**", str)
	case "i", "em":
		if parser.ItalicConverter != nil {
			return parser.ItalicConverter(str)
		}
		return fmt.Sprintf("_%s_", str)
	case "s", "del":
		if parser.StrikethroughConverter != nil {
			return parser.StrikethroughConverter(str)
		}
		return fmt.Sprintf("~~%s~~", str)
	case "u", "ins":
		if parser.UnderlineConverter != nil {
			return parser.UnderlineConverter(str)
		}
	case "tt", "code":
		if parser.MonospaceConverter != nil {
			return parser.MonospaceConverter(str)
		}
	}
	return str
}

func (parser *HTMLParser) headerToString(node *html.Node, stripLinebreak bool) string {
	children := parser.nodeToStrings(node.FirstChild, stripLinebreak)
	length := int(node.Data[1] - '0')
	prefix := strings.Repeat("#", length) + " "
	return prefix + strings.Join(children, "")
}

func (parser *HTMLParser) blockquoteToString(node *html.Node, stripLinebreak bool) string {
	str := parser.nodeToTagAwareString(node.FirstChild, stripLinebreak)
	childrenArr := strings.Split(strings.TrimSpace(str), "\n")
	for index, child := range childrenArr {
		childrenArr[index] = "> " + child
	}
	return strings.Join(childrenArr, "\n")
}

func (parser *HTMLParser) linkToString(node *html.Node, stripLinebreak bool) string {
	str := parser.nodeToTagAwareString(node.FirstChild, stripLinebreak)
	href := parser.getAttribute(node, "href")
	if len(href) == 0 {
		return str
	}
	match := MatrixToURL.FindStringSubmatch(href)
	if len(match) == 2 || len(match) == 3 {
		if parser.PillConverter != nil {
			mxid := match[1]
			eventID := ""
			if len(match) == 3 {
				eventID = match[2]
			}
			return parser.PillConverter(mxid, eventID)
		}
		return str
	}
	return fmt.Sprintf("%s (%s)", str, href)
}

func (parser *HTMLParser) tagToString(node *html.Node, stripLinebreak bool) string {
	switch node.Data {
	case "blockquote":
		return parser.blockquoteToString(node, stripLinebreak)
	case "ol", "ul":
		return parser.listToString(node, stripLinebreak)
	case "h1", "h2", "h3", "h4", "h5", "h6":
		return parser.headerToString(node, stripLinebreak)
	case "br":
		return parser.Newline
	case "b", "strong", "i", "em", "s", "del", "u", "ins", "tt", "code":
		return parser.basicFormatToString(node, stripLinebreak)
	case "a":
		return parser.linkToString(node, stripLinebreak)
	case "p":
		return parser.nodeToTagAwareString(node.FirstChild, stripLinebreak) + "\n"
	case "pre":
		var preStr string
		if node.FirstChild != nil && node.FirstChild.Type == html.ElementNode && node.FirstChild.Data == "code" {
			preStr = parser.nodeToString(node.FirstChild.FirstChild, false)
		} else {
			preStr = parser.nodeToString(node.FirstChild, false)
		}
		if parser.MonospaceBlockConverter != nil {
			return parser.MonospaceBlockConverter(preStr)
		}
		return preStr
	default:
		return parser.nodeToTagAwareString(node.FirstChild, stripLinebreak)
	}
}

func (parser *HTMLParser) singleNodeToString(node *html.Node, stripLinebreak bool) TaggedString {
	switch node.Type {
	case html.TextNode:
		if stripLinebreak {
			node.Data = strings.Replace(node.Data, "\n", "", -1)
		}
		return TaggedString{node.Data, "text"}
	case html.ElementNode:
		return TaggedString{parser.tagToString(node, stripLinebreak), node.Data}
	case html.DocumentNode:
		return TaggedString{parser.nodeToTagAwareString(node.FirstChild, stripLinebreak), "html"}
	default:
		return TaggedString{"", "unknown"}
	}
}

func (parser *HTMLParser) nodeToTaggedStrings(node *html.Node, stripLinebreak bool) (strs []TaggedString) {
	for ; node != nil; node = node.NextSibling {
		strs = append(strs, parser.singleNodeToString(node, stripLinebreak))
	}
	return
}

var BlockTags = []string{"p", "h1", "h2", "h3", "h4", "h5", "h6", "ol", "ul", "pre", "blockquote", "div", "hr", "table"}

func (parser *HTMLParser) isBlockTag(tag string) bool {
	for _, blockTag := range BlockTags {
		if tag == blockTag {
			return true
		}
	}
	return false
}

func (parser *HTMLParser) nodeToTagAwareString(node *html.Node, stripLinebreak bool) string {
	strs := parser.nodeToTaggedStrings(node, stripLinebreak)
	var output strings.Builder
	for _, str := range strs {
		tstr := str.string
		if parser.isBlockTag(str.tag) {
			tstr = fmt.Sprintf("\n%s\n", tstr)
		}
		output.WriteString(tstr)
	}
	return strings.TrimSpace(output.String())
}

func (parser *HTMLParser) nodeToStrings(node *html.Node, stripLinebreak bool) (strs []string) {
	for ; node != nil; node = node.NextSibling {
		strs = append(strs, parser.singleNodeToString(node, stripLinebreak).string)
	}
	return
}

func (parser *HTMLParser) nodeToString(node *html.Node, stripLinebreak bool) string {
	return strings.Join(parser.nodeToStrings(node, stripLinebreak), "")
}

func (parser *HTMLParser) Parse(htmlData string) string {
	if parser.TabsToSpaces >= 0 {
		htmlData = strings.Replace(htmlData, "\t", strings.Repeat(" ", parser.TabsToSpaces), -1)
	}
	node, _ := html.Parse(strings.NewReader(htmlData))
	return parser.nodeToTagAwareString(node, true)
}

func HTMLToText(html string) string {
	return (&HTMLParser{
		TabsToSpaces: 4,
		Newline:      "\n",
	}).Parse(html)
}