Debian Codegraph @

lib/inlineimages.go

raw
1 package lib
2
3 import (
4 "bytes"
5 "encoding/base64"
6 "io"
7 "maps"
8 "strings"
9 "sync"
10
11 "git.sr.ht/~rjarry/aerc/lib/log"
12 "git.sr.ht/~rjarry/aerc/models"
13 "golang.org/x/net/html"
14 )
15
16 // InlineHTMLImages transforms an HTML email by replacing <img> tags with cid:
17 // URLs with base64-encoded data: URLs. This allows HTML emails with embedded
18 // images to be viewed in browsers that support data: URLs, including w3m when
19 // used with the -sixel option and img2sixel installed.
20 //
21 // This function uses callbacks and will call the provided callback
22 // asynchronously once all images have been fetched and inlined.
23 func InlineHTMLImages(
24 htmlReader io.Reader,
25 msg MessageView,
26 callback func(io.Reader),
27 ) {
28 // Read the HTML content
29 htmlBytes, err := io.ReadAll(htmlReader)
30 if err != nil {
31 log.Errorf("Failed to read HTML: %v", err)
32 callback(bytes.NewReader(htmlBytes))
33 return
34 }
35
36 // Parse the HTML
37 doc, err := html.Parse(bytes.NewReader(htmlBytes))
38 if err != nil {
39 log.Errorf("Failed to parse HTML: %v", err)
40 callback(bytes.NewReader(htmlBytes))
41 return
42 }
43
44 // Build a map of Content-ID to part index
45 cidMap := buildContentIDMap(msg.BodyStructure(), []int{})
46
47 // If no Content-IDs found, return the original HTML
48 if len(cidMap) == 0 {
49 log.Tracef("No Content-IDs found in message, skipping image inlining")
50 callback(bytes.NewReader(htmlBytes))
51 return
52 }
53
54 // Find all cid: references in img tags
55 cidReferences := make(map[string]bool)
56 var findCids func(*html.Node)
57 findCids = func(n *html.Node) {
58 if n.Type == html.ElementNode && n.Data == "img" {
59 for _, attr := range n.Attr {
60 if attr.Key == "src" && strings.HasPrefix(attr.Val, "cid:") {
61 cid := strings.Trim(strings.TrimPrefix(attr.Val, "cid:"), "<>")
62 if _, ok := cidMap[cid]; ok {
63 cidReferences[cid] = true
64 }
65 }
66 }
67 }
68 for c := n.FirstChild; c != nil; c = c.NextSibling {
69 findCids(c)
70 }
71 }
72 findCids(doc)
73
74 if len(cidReferences) == 0 {
75 log.Tracef("No cid: references found in HTML, returning original")
76 callback(bytes.NewReader(htmlBytes))
77 return
78 }
79
80 log.Tracef("Found %d cid: references to inline", len(cidReferences))
81
82 // Fetch all images asynchronously and encode as data: URLs
83 var wg sync.WaitGroup
84 var mu sync.Mutex
85 imageURLs := make(map[string]string)
86
87 for cid := range cidReferences {
88 info := cidMap[cid]
89 wg.Add(1)
90
91 msg.FetchBodyPart(info.index, func(reader io.Reader) {
92 defer wg.Done()
93
94 data, err := io.ReadAll(reader)
95 if err != nil {
96 log.Errorf("Failed to read image part for CID %s: %v", cid, err)
97 return
98 }
99
100 // Encode as base64
101 encoded := base64.StdEncoding.EncodeToString(data)
102
103 // Create data: URL
104 dataURL := "data:" + info.mimeType + ";base64," + encoded
105
106 mu.Lock()
107 imageURLs[cid] = dataURL
108 mu.Unlock()
109
110 log.Tracef("Encoded image with Content-ID %s as data: URL (%d bytes)", cid, len(data))
111 })
112 }
113
114 // Wait for all images to be fetched, then transform HTML
115 go func() {
116 defer log.PanicHandler()
117 wg.Wait()
118
119 // Replace all cid: references with data: URLs
120 modified := false
121 var processNode func(*html.Node)
122 processNode = func(n *html.Node) {
123 if n.Type == html.ElementNode && n.Data == "img" {
124 for i, attr := range n.Attr {
125 if attr.Key == "src" && strings.HasPrefix(attr.Val, "cid:") {
126 cid := strings.Trim(strings.TrimPrefix(attr.Val, "cid:"), "<>")
127 if dataURL, ok := imageURLs[cid]; ok {
128 n.Attr[i].Val = dataURL
129 modified = true
130 log.Tracef("Replaced cid:%s with data: URL", cid)
131 }
132 }
133 }
134 }
135 for c := n.FirstChild; c != nil; c = c.NextSibling {
136 processNode(c)
137 }
138 }
139 processNode(doc)
140
141 if !modified {
142 log.Warnf("No images were inlined despite finding CID references")
143 callback(bytes.NewReader(htmlBytes))
144 return
145 }
146
147 // Render the modified HTML back to bytes
148 var buf bytes.Buffer
149 err = html.Render(&buf, doc)
150 if err != nil {
151 log.Errorf("Failed to render HTML: %v", err)
152 callback(bytes.NewReader(htmlBytes))
153 return
154 }
155
156 callback(&buf)
157 }()
158 }
159
160 // partInfo stores the index and MIME type of a part
161 type partInfo struct {
162 index []int
163 mimeType string
164 }
165
166 // buildContentIDMap recursively builds a map from Content-ID to part information
167 func buildContentIDMap(bs *models.BodyStructure, index []int) map[string]partInfo {
168 result := make(map[string]partInfo)
169
170 if bs == nil {
171 log.Tracef("buildContentIDMap: body structure is nil")
172 return result
173 }
174
175 // Log the current part being examined
176 log.Tracef("buildContentIDMap: examining part index=%v mime=%s contentid=%q numParts=%d",
177 index, bs.FullMIMEType(), bs.ContentID, len(bs.Parts))
178
179 // Add this part if it has a Content-ID
180 if bs.ContentID != "" {
181 result[strings.Trim(bs.ContentID, "<>")] = partInfo{
182 index: append([]int{}, index...),
183 mimeType: bs.FullMIMEType(),
184 }
185 log.Tracef("Found Content-ID: %s at index %v (%s)",
186 bs.ContentID, index, bs.FullMIMEType())
187 }
188
189 // Recursively process child parts
190 for i, part := range bs.Parts {
191 childIndex := append(append([]int{}, index...), i+1)
192 maps.Copy(result, buildContentIDMap(part, childIndex))
193 }
194
195 return result
196 }