html.go

 1package view
 2
 3import (
 4	"fmt"
 5	"io"
 6	"mime/quotedprintable"
 7	"strings"
 8
 9	"github.com/PuerkitoBio/goquery"
10)
11
12// hyperlink formats a string as a terminal-clickable hyperlink.
13func hyperlink(url, text string) string {
14	if text == "" {
15		text = url
16	}
17	return fmt.Sprintf("\x1b]8;;%s\x07%s\x1b]8;;\x07", url, text)
18}
19
20func decodeQuotedPrintable(s string) (string, error) {
21	reader := quotedprintable.NewReader(strings.NewReader(s))
22	body, err := io.ReadAll(reader)
23	if err != nil {
24		return "", err
25	}
26	return string(body), nil
27}
28
29// ProcessBody takes a raw email body, decodes it, and formats it as plain
30// text with terminal hyperlinks.
31func ProcessBody(rawBody string) (string, error) {
32	decodedBody, err := decodeQuotedPrintable(rawBody)
33	if err != nil {
34		// If decoding fails, fallback to the raw body
35		decodedBody = rawBody
36	}
37
38	doc, err := goquery.NewDocumentFromReader(strings.NewReader(decodedBody))
39	if err != nil {
40		return "", fmt.Errorf("could not parse email body: %w", err)
41	}
42
43	// Add newlines after block elements for better spacing
44	doc.Find("p, div, h1, h2, h3, h4, h5, h6").Each(func(i int, s *goquery.Selection) {
45		s.After("\n\n")
46	})
47
48	// Replace <br> tags with newlines
49	doc.Find("br").Each(func(i int, s *goquery.Selection) {
50		s.ReplaceWithHtml("\n")
51	})
52
53	// Format links into terminal hyperlinks
54	doc.Find("a").Each(func(i int, s *goquery.Selection) {
55		href, exists := s.Attr("href")
56		if !exists {
57			return
58		}
59		s.ReplaceWithHtml(hyperlink(href, s.Text()))
60	})
61
62	// Return the document's text content, which now includes our formatting
63	return doc.Text(), nil
64}