Debian Codegraph @

worker/imap/fetch.go

raw
1 package imap
2
3 import (
4 "bufio"
5 "context"
6 "fmt"
7 "slices"
8 "time"
9
10 "github.com/emersion/go-imap"
11 "github.com/emersion/go-message"
12 _ "github.com/emersion/go-message/charset"
13 "github.com/emersion/go-message/mail"
14 "github.com/emersion/go-message/textproto"
15
16 "git.sr.ht/~rjarry/aerc/lib/log"
17 "git.sr.ht/~rjarry/aerc/lib/parse"
18 "git.sr.ht/~rjarry/aerc/models"
19 "git.sr.ht/~rjarry/aerc/worker/types"
20 "github.com/emersion/go-imap/utf7"
21 )
22
23 func (imapw *IMAPWorker) attachGMLabels(_msg *imap.Message, info *models.MessageInfo) {
24 if len(_msg.Items["X-GM-LABELS"].([]any)) == 0 {
25 return
26 }
27 imapw.worker.Debugf("Attaching labels %v to message %v\n", _msg.Items["X-GM-LABELS"], _msg.Uid)
28 enc := utf7.Encoding.NewDecoder()
29 for _, label := range _msg.Items["X-GM-LABELS"].([]any) {
30 decodedLabel, err := enc.String(label.(string))
31 if err != nil {
32 imapw.worker.Errorf("Failed to decode label %v from UTF-7\n", label.(string))
33 info.Labels = append(info.Labels, label.(string))
34 } else {
35 info.Labels = append(info.Labels, decodedLabel)
36 }
37 }
38 }
39
40 func (imapw *IMAPWorker) handleFetchMessageHeaders(
41 msg *types.FetchMessageHeaders,
42 ) error {
43 if err := imapw.ensureSelected(msg.Directory); err != nil {
44 return err
45 }
46 if msg.Context().Err() != nil {
47 return msg.Context().Err()
48 }
49 toFetch := msg.Uids
50
51 // Expand UIDs to include entire threads when Gmail X-GM-EXT-1 is available
52 if imapw.caps.Has("X-GM-EXT-1") {
53 uids, err := imapw.fetchEntireThreads(toFetch)
54 if err != nil {
55 imapw.worker.Warnf("failed to fetch entire threads: %v", err)
56 } else if len(uids) > 0 {
57 toFetch = uids
58 }
59 }
60
61 cacheEnabled := imapw.config.cacheEnabled && imapw.cache != nil
62 if cacheEnabled {
63 msg.Uids = toFetch
64 toFetch = imapw.getCachedHeaders(msg)
65 }
66 if len(toFetch) == 0 {
67 return nil
68 }
69 imapw.worker.Tracef("Fetching message headers: %v", toFetch)
70 hdrBodyPart := imap.BodyPartName{
71 Specifier: imap.HeaderSpecifier,
72 }
73 switch {
74 case len(imapw.config.headersExclude) > 0:
75 hdrBodyPart.NotFields = true
76 hdrBodyPart.Fields = imapw.config.headersExclude
77 case len(imapw.config.headers) > 0:
78 hdrBodyPart.Fields = imapw.config.headers
79 }
80 section := &imap.BodySectionName{
81 BodyPartName: hdrBodyPart,
82 Peek: true,
83 }
84
85 items := []imap.FetchItem{
86 imap.FetchBodyStructure,
87 imap.FetchEnvelope,
88 imap.FetchInternalDate,
89 imap.FetchFlags,
90 imap.FetchUid,
91 imap.FetchRFC822Size,
92 section.FetchItem(),
93 }
94
95 return imapw.handleFetchMessages(context.WithoutCancel(msg.Context()),
96 msg, toFetch, items,
97 func(_msg *imap.Message) error {
98 if len(_msg.Body) == 0 {
99 // ignore duplicate messages with only flag updates
100 return nil
101 }
102 reader := _msg.GetBody(section)
103 if reader == nil {
104 return fmt.Errorf("failed to find part: %v", section)
105 }
106 textprotoHeader, err := textproto.ReadHeader(bufio.NewReader(reader))
107 if err != nil {
108 return fmt.Errorf("failed to read part header: %w", err)
109 }
110 header := &mail.Header{Header: message.Header{Header: textprotoHeader}}
111 systemFlags, keywordFlags := translateImapFlags(_msg.Flags)
112 info := &models.MessageInfo{
113 BodyStructure: translateBodyStructure(_msg.BodyStructure),
114 Envelope: translateEnvelope(_msg.Envelope),
115 Flags: systemFlags,
116 InternalDate: _msg.InternalDate,
117 RFC822Headers: header,
118 Refs: parse.MsgIDList(header, "references"),
119 Directory: msg.Directory,
120 Size: _msg.Size,
121 Uid: imapw.Uint32ToUid(_msg.Uid),
122 }
123
124 if imapw.caps.Has("X-GM-EXT-1") {
125 imapw.attachGMLabels(_msg, info)
126 } else if len(imapw.selected.PermanentFlags) == 0 || slices.Contains(imapw.selected.PermanentFlags, "\\*") {
127 info.Labels = keywordFlags
128 }
129
130 if cacheEnabled && !info.Flags.Has(models.SeenFlag) &&
131 time.Since(info.InternalDate) < imapw.config.checkMail {
132 // Consider unread messages received within the last CheckMail
133 // period as Recent, regardless of what the IMAP server says.
134 info.Flags |= models.RecentFlag
135 }
136
137 imapw.worker.PostMessage(&types.MessageInfo{
138 Message: types.RespondTo(msg),
139 Info: info,
140 }, nil)
141 if imapw.config.cacheEnabled && imapw.cache != nil {
142 imapw.cacheHeader(info)
143 }
144 return nil
145 })
146 }
147
148 func (imapw *IMAPWorker) handleFetchMessageBodyPart(
149 msg *types.FetchMessageBodyPart,
150 ) error {
151 if err := imapw.ensureSelected(msg.Directory); err != nil {
152 return err
153 }
154 imapw.worker.Tracef("Fetching message %d part: %v", msg.Uid, msg.Part)
155
156 var partHeaderSection imap.BodySectionName
157 partHeaderSection.Peek = true
158 if len(msg.Part) > 0 {
159 partHeaderSection.Specifier = imap.MIMESpecifier
160 } else {
161 partHeaderSection.Specifier = imap.HeaderSpecifier
162 }
163 partHeaderSection.Path = msg.Part
164
165 var partBodySection imap.BodySectionName
166 if len(msg.Part) > 0 {
167 partBodySection.Specifier = imap.EntireSpecifier
168 } else {
169 partBodySection.Specifier = imap.TextSpecifier
170 }
171 partBodySection.Path = msg.Part
172 partBodySection.Peek = true
173
174 items := []imap.FetchItem{
175 imap.FetchEnvelope,
176 imap.FetchUid,
177 imap.FetchBodyStructure,
178 imap.FetchFlags,
179 partHeaderSection.FetchItem(),
180 partBodySection.FetchItem(),
181 }
182 return imapw.handleFetchMessages(context.WithoutCancel(msg.Context()),
183 msg, []models.UID{msg.Uid}, items,
184 func(_msg *imap.Message) error {
185 if len(_msg.Body) == 0 {
186 // ignore duplicate messages with only flag updates
187 return nil
188 }
189 body := _msg.GetBody(&partHeaderSection)
190 if body == nil {
191 return fmt.Errorf("failed to find part: %v", partHeaderSection)
192 }
193 h, err := textproto.ReadHeader(bufio.NewReader(body))
194 if err != nil {
195 return fmt.Errorf("failed to read part header: %w", err)
196 }
197
198 part, err := message.New(message.Header{Header: h},
199 _msg.GetBody(&partBodySection))
200 if message.IsUnknownCharset(err) {
201 imapw.worker.Warnf("unknown charset encountered "+
202 "for uid %d", _msg.Uid)
203 } else if err != nil {
204 return fmt.Errorf("failed to create message reader: %w", err)
205 }
206
207 imapw.worker.PostMessage(&types.MessageBodyPart{
208 Message: types.RespondTo(msg),
209 Part: &models.MessageBodyPart{
210 Reader: part.Body,
211 Uid: imapw.Uint32ToUid(_msg.Uid),
212 },
213 }, nil)
214 // Update flags (to mark message as read)
215 systemFlags, keywordFlags := translateImapFlags(_msg.Flags)
216 info := &models.MessageInfo{
217 Flags: systemFlags,
218 Directory: msg.Directory,
219 Uid: imapw.Uint32ToUid(_msg.Uid),
220 }
221 if imapw.caps.Has("X-GM-EXT-1") {
222 imapw.attachGMLabels(_msg, info)
223 } else if len(imapw.selected.PermanentFlags) == 0 || slices.Contains(imapw.selected.PermanentFlags, "\\*") {
224 info.Labels = keywordFlags
225 }
226 imapw.worker.PostMessage(&types.MessageInfo{
227 Message: types.RespondTo(msg),
228 Info: info,
229 }, nil)
230 return nil
231 })
232 }
233
234 func (imapw *IMAPWorker) handleFetchFullMessages(
235 msg *types.FetchFullMessages,
236 ) error {
237 if err := imapw.ensureSelected(msg.Directory); err != nil {
238 return err
239 }
240 imapw.worker.Tracef("Fetching full messages: %v", msg.Uids)
241 section := &imap.BodySectionName{
242 Peek: true,
243 }
244 items := []imap.FetchItem{
245 imap.FetchEnvelope,
246 imap.FetchFlags,
247 imap.FetchUid,
248 section.FetchItem(),
249 }
250 return imapw.handleFetchMessages(context.WithoutCancel(msg.Context()),
251 msg, msg.Uids, items,
252 func(_msg *imap.Message) error {
253 if len(_msg.Body) == 0 {
254 // ignore duplicate messages with only flag updates
255 return nil
256 }
257 r := _msg.GetBody(section)
258 if r == nil {
259 return fmt.Errorf("could not get section %#v", section)
260 }
261 imapw.worker.PostMessage(&types.FullMessage{
262 Message: types.RespondTo(msg),
263 Content: &models.FullMessage{
264 Reader: bufio.NewReader(r),
265 Uid: imapw.Uint32ToUid(_msg.Uid),
266 },
267 }, nil)
268 // Update flags (to mark message as read)
269 systemFlags, keywordFlags := translateImapFlags(_msg.Flags)
270 info := &models.MessageInfo{
271 Flags: systemFlags,
272 Directory: msg.Directory,
273 Uid: imapw.Uint32ToUid(_msg.Uid),
274 }
275 if imapw.caps.Has("X-GM-EXT-1") {
276 imapw.attachGMLabels(_msg, info)
277 } else if len(imapw.selected.PermanentFlags) == 0 || slices.Contains(imapw.selected.PermanentFlags, "\\*") {
278 info.Labels = keywordFlags
279 }
280 imapw.worker.PostMessage(&types.MessageInfo{
281 Message: types.RespondTo(msg),
282 Info: info,
283 }, nil)
284 return nil
285 })
286 }
287
288 func (imapw *IMAPWorker) handleFetchMessageFlags(msg *types.FetchMessageFlags) error {
289 if err := imapw.ensureSelected(msg.Directory); err != nil {
290 return err
291 }
292 items := []imap.FetchItem{
293 imap.FetchFlags,
294 imap.FetchUid,
295 }
296 return imapw.handleFetchMessages(context.WithoutCancel(msg.Context()),
297 msg, msg.Uids, items,
298 func(_msg *imap.Message) error {
299 systemFlags, keywordFlags := translateImapFlags(_msg.Flags)
300 info := &models.MessageInfo{
301 Flags: systemFlags,
302 Directory: msg.Directory,
303 Uid: imapw.Uint32ToUid(_msg.Uid),
304 }
305
306 if imapw.caps.Has("X-GM-EXT-1") {
307 imapw.attachGMLabels(_msg, info)
308 } else if len(imapw.selected.PermanentFlags) == 0 || slices.Contains(imapw.selected.PermanentFlags, "\\*") {
309 info.Labels = keywordFlags
310 }
311
312 imapw.worker.PostMessage(&types.MessageInfo{
313 Message: types.RespondTo(msg),
314 Info: info,
315 }, nil)
316 return nil
317 })
318 }
319
320 func (imapw *IMAPWorker) handleFetchMessages(
321 ctx context.Context, msg types.WorkerMessage, uids []models.UID,
322 items []imap.FetchItem, procFunc func(*imap.Message) error,
323 ) error {
324 messages := make(chan *imap.Message)
325 done := make(chan error)
326
327 missingUids := make(map[models.UID]bool)
328 for _, uid := range uids {
329 missingUids[uid] = true
330 }
331
332 go func() {
333 defer log.PanicHandler()
334
335 for {
336 select {
337 case <-ctx.Done():
338 done <- ctx.Err()
339 goto out
340 case _msg := <-messages:
341 if _msg == nil {
342 goto out
343 }
344 delete(missingUids, imapw.Uint32ToUid(_msg.Uid))
345 err := procFunc(_msg)
346 if err != nil {
347 imapw.worker.Errorf("failed to process message <%d>: %v", _msg.Uid, err)
348 imapw.worker.PostMessage(&types.MessageInfo{
349 Message: types.RespondTo(msg),
350 Info: &models.MessageInfo{
351 Uid: imapw.Uint32ToUid(_msg.Uid),
352 Error: err,
353 },
354 }, nil)
355 }
356 }
357 }
358 out:
359 close(done)
360 }()
361
362 if imapw.caps.Has("X-GM-EXT-1") {
363 items = append(items, "X-GM-LABELS")
364 }
365
366 set := imapw.UidListToSeqSet(uids)
367 if err := imapw.client.UidFetch(set, items, messages); err != nil {
368 return err
369 }
370 err := <-done
371 if err != nil {
372 return err
373 }
374
375 for uid := range missingUids {
376 imapw.worker.PostMessage(&types.MessageInfo{
377 Message: types.RespondTo(msg),
378 Info: &models.MessageInfo{
379 Uid: uid,
380 Error: fmt.Errorf("invalid response from server (detailed error in log)"),
381 },
382 }, nil)
383 }
384
385 return nil
386 }