Debian Codegraph @

ui/messages/html/parser.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // gomuks - A terminal Matrix client written in Go.
2 // Copyright (C) 2020 Tulir Asokan
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU Affero General Public License for more details.
13 //
14 // You should have received a copy of the GNU Affero General Public License
15 // along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17 package html
18
19 import (
20 "fmt"
21 "regexp"
22 "strconv"
23 "strings"
24
25 "github.com/alecthomas/chroma"
26 "github.com/alecthomas/chroma/lexers"
27 "github.com/alecthomas/chroma/styles"
28 "github.com/lucasb-eyer/go-colorful"
29 "golang.org/x/net/html"
30 "mvdan.cc/xurls/v2"
31
•32 "github.com/gdamore/tcell/v2"
33
34 "maunium.net/go/mautrix/event"
35 "maunium.net/go/mautrix/id"
36
37 "maunium.net/go/gomuks/config"
38 "maunium.net/go/gomuks/matrix/muksevt"
39 "maunium.net/go/gomuks/matrix/rooms"
40 "maunium.net/go/gomuks/ui/widget"
41 )
42
43 type htmlParser struct {
44 prefs *config.UserPreferences
45 room *rooms.Room
46 evt *muksevt.Event
47
48 preserveWhitespace bool
49 linkIDCounter int
50 }
51
52 func AdjustStyleBold(style tcell.Style) tcell.Style {
53 return style.Bold(true)
54 }
55
56 func AdjustStyleItalic(style tcell.Style) tcell.Style {
57 return style.Italic(true)
58 }
59
60 func AdjustStyleUnderline(style tcell.Style) tcell.Style {
61 return style.Underline(true)
62 }
63
64 func AdjustStyleStrikethrough(style tcell.Style) tcell.Style {
65 return style.StrikeThrough(true)
66 }
67
68 func AdjustStyleTextColor(color tcell.Color) AdjustStyleFunc {
69 return func(style tcell.Style) tcell.Style {
70 return style.Foreground(color)
71 }
72 }
73
74 func AdjustStyleBackgroundColor(color tcell.Color) AdjustStyleFunc {
75 return func(style tcell.Style) tcell.Style {
76 return style.Background(color)
77 }
78 }
79
80 func AdjustStyleLink(url, id string) AdjustStyleFunc {
81 return func(style tcell.Style) tcell.Style {
82 return style.Url(url).UrlId(id)
83 }
84 }
85
86 func (parser *htmlParser) maybeGetAttribute(node *html.Node, attribute string) (string, bool) {
87 for _, attr := range node.Attr {
88 if attr.Key == attribute {
89 return attr.Val, true
90 }
91 }
92 return "", false
93 }
94
95 func (parser *htmlParser) getAttribute(node *html.Node, attribute string) string {
96 val, _ := parser.maybeGetAttribute(node, attribute)
97 return val
98 }
99
100 func (parser *htmlParser) hasAttribute(node *html.Node, attribute string) bool {
101 _, ok := parser.maybeGetAttribute(node, attribute)
102 return ok
103 }
104
105 func (parser *htmlParser) listToEntity(node *html.Node) Entity {
106 children := parser.nodeToEntities(node.FirstChild)
107 ordered := node.Data == "ol"
108 start := 1
109 if ordered {
110 if startRaw := parser.getAttribute(node, "start"); len(startRaw) > 0 {
111 var err error
112 start, err = strconv.Atoi(startRaw)
113 if err != nil {
114 start = 1
115 }
116 }
117 }
118 listItems := children[:0]
119 for _, child := range children {
120 if child.GetTag() == "li" {
121 listItems = append(listItems, child)
122 }
123 }
124 return NewListEntity(ordered, start, listItems)
125 }
126
127 func (parser *htmlParser) basicFormatToEntity(node *html.Node) Entity {
128 entity := &ContainerEntity{
129 BaseEntity: &BaseEntity{
130 Tag: node.Data,
131 },
132 Children: parser.nodeToEntities(node.FirstChild),
133 }
134 switch node.Data {
135 case "b", "strong":
136 entity.AdjustStyle(AdjustStyleBold, AdjustStyleReasonNormal)
137 case "i", "em":
138 entity.AdjustStyle(AdjustStyleItalic, AdjustStyleReasonNormal)
139 case "s", "del", "strike":
140 entity.AdjustStyle(AdjustStyleStrikethrough, AdjustStyleReasonNormal)
141 case "u", "ins":
142 entity.AdjustStyle(AdjustStyleUnderline, AdjustStyleReasonNormal)
143 case "code":
144 bgColor := tcell.ColorDarkSlateGray
145 fgColor := tcell.ColorWhite
146 entity.AdjustStyle(AdjustStyleBackgroundColor(bgColor), AdjustStyleReasonNormal)
147 entity.AdjustStyle(AdjustStyleTextColor(fgColor), AdjustStyleReasonNormal)
148 case "font", "span":
149 fgColor, ok := parser.parseColor(node, "data-mx-color", "color")
150 if ok {
151 entity.AdjustStyle(AdjustStyleTextColor(fgColor), AdjustStyleReasonNormal)
152 }
153 bgColor, ok := parser.parseColor(node, "data-mx-bg-color", "background-color")
154 if ok {
155 entity.AdjustStyle(AdjustStyleBackgroundColor(bgColor), AdjustStyleReasonNormal)
156 }
157 spoilerReason, isSpoiler := parser.maybeGetAttribute(node, "data-mx-spoiler")
158 if isSpoiler {
159 return NewSpoilerEntity(entity, spoilerReason)
160 }
161 }
162 return entity
163 }
164
165 func (parser *htmlParser) parseColor(node *html.Node, mainName, altName string) (color tcell.Color, ok bool) {
166 hex := parser.getAttribute(node, mainName)
167 if len(hex) == 0 {
168 hex = parser.getAttribute(node, altName)
169 if len(hex) == 0 {
170 return
171 }
172 }
173
174 cful, err := colorful.Hex(hex)
175 if err != nil {
176 color2, found := colorMap[strings.ToLower(hex)]
177 if !found {
178 return
179 }
180 cful, _ = colorful.MakeColor(color2)
181 }
182
183 r, g, b := cful.RGB255()
184 return tcell.NewRGBColor(int32(r), int32(g), int32(b)), true
185 }
186
187 func (parser *htmlParser) headerToEntity(node *html.Node) Entity {
188 return (&ContainerEntity{
189 BaseEntity: &BaseEntity{
190 Tag: node.Data,
191 },
192 Children: append(
193 []Entity{NewTextEntity(strings.Repeat("#", int(node.Data[1]-'0')) + " ")},
194 parser.nodeToEntities(node.FirstChild)...,
195 ),
196 }).AdjustStyle(AdjustStyleBold, AdjustStyleReasonNormal)
197 }
198
199 func (parser *htmlParser) blockquoteToEntity(node *html.Node) Entity {
200 return NewBlockquoteEntity(parser.nodeToEntities(node.FirstChild))
201 }
202
203 func (parser *htmlParser) linkToEntity(node *html.Node) Entity {
204 sameURL := false
205 href := parser.getAttribute(node, "href")
206
207 entity := &ContainerEntity{
208 BaseEntity: &BaseEntity{
209 Tag: "a",
210 },
211 Children: parser.nodeToEntities(node.FirstChild),
212 }
213
214 if len(href) == 0 {
215 return entity
216 }
217
218 if len(entity.Children) == 1 {
219 entity, ok := entity.Children[0].(*TextEntity)
220 if ok && entity.Text == href {
221 sameURL = true
222 }
223 }
224
225 matrixURI, _ := id.ParseMatrixURIOrMatrixToURL(href)
226 if matrixURI != nil && (matrixURI.Sigil1 == '@' || matrixURI.Sigil1 == '#') && matrixURI.Sigil2 == 0 {
227 text := NewTextEntity(matrixURI.PrimaryIdentifier())
228 if matrixURI.Sigil1 == '@' {
229 if member := parser.room.GetMember(matrixURI.UserID()); member != nil {
230 text.Text = member.Displayname
231 text.Style = text.Style.Foreground(widget.GetHashColor(matrixURI.UserID()))
232 }
233 entity.Children = []Entity{text}
234 } else if matrixURI.Sigil1 == '#' {
235 entity.Children = []Entity{text}
236 }
237 } else if parser.prefs.EnableInlineURLs() {
238 linkID := fmt.Sprintf("%s-%d", parser.evt.ID, parser.linkIDCounter)
239 parser.linkIDCounter++
240 entity.AdjustStyle(AdjustStyleLink(href, linkID), AdjustStyleReasonNormal)
241 } else if !sameURL && !parser.prefs.DisableShowURLs && !parser.hasAttribute(node, "data-mautrix-exclude-plaintext") {
242 entity.Children = append(entity.Children, NewTextEntity(fmt.Sprintf(" (%s)", href)))
243 }
244 return entity
245 }
246
247 func (parser *htmlParser) imageToEntity(node *html.Node) Entity {
248 alt := parser.getAttribute(node, "alt")
249 if len(alt) == 0 {
250 alt = parser.getAttribute(node, "title")
251 if len(alt) == 0 {
252 alt = "[inline image]"
253 }
254 }
255 entity := &TextEntity{
256 BaseEntity: &BaseEntity{
257 Tag: "img",
258 },
259 Text: alt,
260 }
261 // TODO add click action and underline on hover for inline images
262 return entity
263 }
264
265 func colourToColor(colour chroma.Colour) tcell.Color {
266 if !colour.IsSet() {
267 return tcell.ColorDefault
268 }
269 return tcell.NewRGBColor(int32(colour.Red()), int32(colour.Green()), int32(colour.Blue()))
270 }
271
272 func styleEntryToStyle(se chroma.StyleEntry) tcell.Style {
273 return tcell.StyleDefault.
274 Bold(se.Bold == chroma.Yes).
275 Italic(se.Italic == chroma.Yes).
276 Underline(se.Underline == chroma.Yes).
277 Foreground(colourToColor(se.Colour)).
278 Background(colourToColor(se.Background))
279 }
280
281 func tokenToTextEntity(style *chroma.Style, token *chroma.Token) *TextEntity {
282 return &TextEntity{
283 BaseEntity: &BaseEntity{
284 Tag: token.Type.String(),
285 Style: styleEntryToStyle(style.Get(token.Type)),
286 DefaultHeight: 1,
287 },
288 Text: token.Value,
289 }
290 }
291
292 func (parser *htmlParser) syntaxHighlight(text, language string) Entity {
293 lexer := lexers.Get(strings.ToLower(language))
294 if lexer == nil {
295 lexer = lexers.Get("plaintext")
296 }
297 iter, err := lexer.Tokenise(nil, text)
298 if err != nil {
299 return nil
300 }
301 // TODO allow changing theme
302 style := styles.SolarizedDark
303
304 tokens := iter.Tokens()
305
306 var children []Entity
307 for _, token := range tokens {
308 lines := strings.SplitAfter(token.Value, "\n")
309 for _, line := range lines {
310 line_len := len(line)
311 if line_len == 0 {
312 continue
313 }
314 t := token.Clone()
315
316 if line[line_len-1:] == "\n" {
317 t.Value = line[:line_len-1]
318 children = append(children, tokenToTextEntity(style, &t), NewBreakEntity())
319 } else {
320 t.Value = line
321 children = append(children, tokenToTextEntity(style, &t))
322 }
323 }
324 }
325
326 return NewCodeBlockEntity(children, styleEntryToStyle(style.Get(chroma.Background)))
327 }
328
329 func (parser *htmlParser) codeblockToEntity(node *html.Node) Entity {
330 lang := "plaintext"
331 // TODO allow disabling syntax highlighting
332 if node.FirstChild != nil && node.FirstChild.Type == html.ElementNode && node.FirstChild.Data == "code" {
333 node = node.FirstChild
334 attr := parser.getAttribute(node, "class")
335 for _, class := range strings.Split(attr, " ") {
336 if strings.HasPrefix(class, "language-") {
337 lang = class[len("language-"):]
338 break
339 }
340 }
341 }
342 parser.preserveWhitespace = true
343 text := (&ContainerEntity{
344 Children: parser.nodeToEntities(node.FirstChild),
345 }).PlainText()
346 parser.preserveWhitespace = false
347 return parser.syntaxHighlight(text, lang)
348 }
349
350 func (parser *htmlParser) tagNodeToEntity(node *html.Node) Entity {
351 switch node.Data {
352 case "blockquote":
353 return parser.blockquoteToEntity(node)
354 case "ol", "ul":
355 return parser.listToEntity(node)
356 case "h1", "h2", "h3", "h4", "h5", "h6":
357 return parser.headerToEntity(node)
358 case "br":
359 return NewBreakEntity()
360 case "b", "strong", "i", "em", "s", "strike", "del", "u", "ins", "font", "span", "code":
361 return parser.basicFormatToEntity(node)
362 case "a":
363 return parser.linkToEntity(node)
364 case "img":
365 return parser.imageToEntity(node)
366 case "pre":
367 return parser.codeblockToEntity(node)
368 case "hr":
369 return NewHorizontalLineEntity()
370 case "mx-reply":
371 return nil
372 default:
373 return &ContainerEntity{
374 BaseEntity: &BaseEntity{
375 Tag: node.Data,
376 Block: parser.isBlockTag(node.Data),
377 },
378 Children: parser.nodeToEntities(node.FirstChild),
379 }
380 }
381 }
382
383 var spaces = regexp.MustCompile("\\s+")
384
385 // textToHTMLEntity converts a plain text string into an HTML Entity while preserving newlines.
386 func textToHTMLEntity(text string) Entity {
387 if strings.Index(text, "\n") == -1 {
388 return NewTextEntity(text)
389 }
390 return &ContainerEntity{
391 BaseEntity: &BaseEntity{Tag: "span"},
392 Children: textToHTMLEntities(text),
393 }
394 }
395
396 func textToHTMLEntities(text string) []Entity {
397 lines := strings.SplitAfter(text, "\n")
398 entities := make([]Entity, 0, len(lines))
399 for _, line := range lines {
400 line_len := len(line)
401 if line_len == 0 {
402 continue
403 }
404 if line == "\n" {
405 entities = append(entities, NewBreakEntity())
406 } else if line[line_len-1:] == "\n" {
407 entities = append(entities, NewTextEntity(line[:line_len-1]), NewBreakEntity())
408 } else {
409 entities = append(entities, NewTextEntity(line))
410 }
411 }
412 return entities
413 }
414
415 func TextToEntity(text string, eventID id.EventID, linkify bool) Entity {
416 if len(text) == 0 {
417 return nil
418 }
419 if !linkify {
420 return textToHTMLEntity(text)
421 }
422 indices := xurls.Strict().FindAllStringIndex(text, -1)
423 if len(indices) == 0 {
424 return textToHTMLEntity(text)
425 }
426 ent := &ContainerEntity{
427 BaseEntity: &BaseEntity{Tag: "span"},
428 }
429 var lastEnd int
430 for i, item := range indices {
431 start, end := item[0], item[1]
432 if start > lastEnd {
433 ent.Children = append(ent.Children, textToHTMLEntities(text[lastEnd:start])...)
434 }
435 link := text[start:end]
436 linkID := fmt.Sprintf("%s-%d", eventID, i)
437 ent.Children = append(ent.Children, NewTextEntity(link).AdjustStyle(AdjustStyleLink(link, linkID), AdjustStyleReasonNormal))
438 lastEnd = end
439 }
440 if lastEnd < len(text) {
441 ent.Children = append(ent.Children, textToHTMLEntities(text[lastEnd:])...)
442 }
443 return ent
444 }
445
446 func (parser *htmlParser) singleNodeToEntity(node *html.Node) Entity {
447 switch node.Type {
448 case html.TextNode:
449 if !parser.preserveWhitespace {
450 node.Data = strings.ReplaceAll(node.Data, "\n", "")
451 node.Data = spaces.ReplaceAllLiteralString(node.Data, " ")
452 }
453 return TextToEntity(node.Data, parser.evt.ID, parser.prefs.EnableInlineURLs())
454 case html.ElementNode:
455 parsed := parser.tagNodeToEntity(node)
456 if parsed != nil && !parsed.IsBlock() && parsed.IsEmpty() {
457 return nil
458 }
459 return parsed
460 case html.DocumentNode:
461 if node.FirstChild.Data == "html" && node.FirstChild.NextSibling == nil {
462 return parser.singleNodeToEntity(node.FirstChild)
463 }
464 return &ContainerEntity{
465 BaseEntity: &BaseEntity{
466 Tag: "html",
467 Block: true,
468 },
469 Children: parser.nodeToEntities(node.FirstChild),
470 }
471 default:
472 return nil
473 }
474 }
475
476 func (parser *htmlParser) nodeToEntities(node *html.Node) (entities []Entity) {
477 for ; node != nil; node = node.NextSibling {
478 if entity := parser.singleNodeToEntity(node); entity != nil {
479 entities = append(entities, entity)
480 }
481 }
482 return
483 }
484
485 var BlockTags = []string{"p", "h1", "h2", "h3", "h4", "h5", "h6", "ol", "ul", "li", "pre", "blockquote", "div", "hr", "table"}
486
487 func (parser *htmlParser) isBlockTag(tag string) bool {
488 for _, blockTag := range BlockTags {
489 if tag == blockTag {
490 return true
491 }
492 }
493 return false
494 }
495
496 func (parser *htmlParser) Parse(htmlData string) Entity {
497 node, _ := html.Parse(strings.NewReader(htmlData))
498 bodyNode := node.FirstChild.FirstChild
499 for bodyNode != nil && (bodyNode.Type != html.ElementNode || bodyNode.Data != "body") {
500 bodyNode = bodyNode.NextSibling
501 }
502 if bodyNode != nil {
503 return parser.singleNodeToEntity(bodyNode)
504 }
505
506 return parser.singleNodeToEntity(node)
507 }
508
509 const TabLength = 4
510
511 // Parse parses a HTML-formatted Matrix event into a UIMessage.
512 func Parse(prefs *config.UserPreferences, room *rooms.Room, content *event.MessageEventContent, evt *muksevt.Event, senderDisplayname string) Entity {
513 htmlData := content.FormattedBody
514
515 if content.Format != event.FormatHTML {
516 htmlData = strings.Replace(html.EscapeString(content.Body), "\n", "<br/>", -1)
517 }
518 htmlData = strings.Replace(htmlData, "\t", strings.Repeat(" ", TabLength), -1)
519
520 parser := htmlParser{room: room, prefs: prefs, evt: evt}
521 root := parser.Parse(htmlData)
522 if root == nil {
523 return nil
524 }
525 beRoot, ok := root.(*ContainerEntity)
526 if ok {
527 beRoot.Block = false
528 if len(beRoot.Children) > 0 {
529 beChild, ok := beRoot.Children[0].(*ContainerEntity)
530 if ok && beChild.Tag == "p" {
531 // Hacky fix for m.emote
532 beChild.Block = false
533 }
534 }
535 }
536
537 if content.MsgType == event.MsgEmote {
538 root = &ContainerEntity{
539 BaseEntity: &BaseEntity{
540 Tag: "emote",
541 },
542 Children: []Entity{
543 NewTextEntity("* "),
544 NewTextEntity(senderDisplayname).AdjustStyle(AdjustStyleTextColor(widget.GetHashColor(evt.Sender)), AdjustStyleReasonNormal),
545 NewTextEntity(" "),
546 root,
547 },
548 }
549 }
550
551 return root
552 }