Debian Codegraph @

lib/threadbuilder.go

raw
1 package lib
2
3 import (
4 "fmt"
5 "sync"
6 "time"
7
8 "git.sr.ht/~rjarry/aerc/lib/iterator"
9 "git.sr.ht/~rjarry/aerc/lib/jwz"
10 "git.sr.ht/~rjarry/aerc/lib/log"
11 "git.sr.ht/~rjarry/aerc/models"
12 "git.sr.ht/~rjarry/aerc/worker/types"
13 sortthread "github.com/emersion/go-imap-sortthread"
14 )
15
16 type ThreadBuilder struct {
17 sync.Mutex
18 threadBlocks map[models.UID]jwz.Threadable
19 threadedUids []models.UID
20 threadMap map[models.UID]*types.Thread
21 iterFactory iterator.Factory
22 bySubject bool
23 }
24
25 func NewThreadBuilder(i iterator.Factory, bySubject bool) *ThreadBuilder {
26 tb := &ThreadBuilder{
27 threadBlocks: make(map[models.UID]jwz.Threadable),
28 iterFactory: i,
29 threadMap: make(map[models.UID]*types.Thread),
30 bySubject: bySubject,
31 }
32 return tb
33 }
34
35 func (builder *ThreadBuilder) ThreadForUid(uid models.UID) (*types.Thread, error) {
36 builder.Lock()
37 defer builder.Unlock()
38 t, ok := builder.threadMap[uid]
39 var err error
40 if !ok {
41 err = fmt.Errorf("no thread found for uid '%s'", uid)
42 }
43 return t, err
44 }
45
46 // Uids returns the uids in threading order
47 func (builder *ThreadBuilder) Uids() []models.UID {
48 builder.Lock()
49 defer builder.Unlock()
50
51 if builder.threadedUids == nil {
52 return []models.UID{}
53 }
54 return builder.threadedUids
55 }
56
57 // Update updates the thread builder with a new message header
58 func (builder *ThreadBuilder) Update(msg *models.MessageInfo) {
59 builder.Lock()
60 defer builder.Unlock()
61
62 if msg != nil {
63 threadable := newThreadable(msg, builder.bySubject)
64 if threadable != nil {
65 builder.threadBlocks[msg.Uid] = threadable
66 }
67 }
68 }
69
70 // Threads returns a slice of threads for the given list of uids
71 func (builder *ThreadBuilder) Threads(uids []models.UID, inverse bool, sort bool,
72 ) []*types.Thread {
73 builder.Lock()
74 defer builder.Unlock()
75
76 start := time.Now()
77
78 threads := builder.buildAercThreads(builder.generateStructure(uids),
79 uids, sort)
80
81 // sort threads according to uid ordering
82 builder.sortThreads(threads, uids)
83
84 // rebuild uids from threads
85 builder.RebuildUids(threads, inverse)
86
87 elapsed := time.Since(start)
88 log.Tracef("%d threads from %d uids created in %s", len(threads),
89 len(uids), elapsed)
90
91 return threads
92 }
93
94 func (builder *ThreadBuilder) generateStructure(uids []models.UID) jwz.Threadable {
95 jwzThreads := make([]jwz.Threadable, 0, len(builder.threadBlocks))
96 for _, uid := range uids {
97 if thr, ok := builder.threadBlocks[uid]; ok {
98 jwzThreads = append(jwzThreads, thr)
99 }
100 }
101
102 threader := jwz.NewThreader()
103 threadStructure, err := threader.ThreadSlice(jwzThreads)
104 if err != nil {
105 log.Errorf("failed slicing threads: %v", err)
106 }
107 return threadStructure
108 }
109
110 func (builder *ThreadBuilder) buildAercThreads(structure jwz.Threadable,
111 uids []models.UID, sort bool,
112 ) []*types.Thread {
113 threads := make([]*types.Thread, 0, len(builder.threadBlocks))
114
115 if structure == nil {
116 for _, uid := range uids {
117 threads = append(threads, &types.Thread{Uid: uid})
118 }
119 } else {
120
121 // prepare bigger function
122 var bigger func(l, r *types.Thread) bool
123 if sort {
124 sortMap := make(map[models.UID]int)
125 for i, uid := range uids {
126 sortMap[uid] = i
127 }
128 bigger = func(left, right *types.Thread) bool {
129 if left == nil || right == nil {
130 return false
131 }
132 return sortMap[left.Uid] > sortMap[right.Uid]
133 }
134 } else {
135 bigger = func(left, right *types.Thread) bool {
136 if left == nil || right == nil {
137 return false
138 }
139 l := builder.threadBlocks[left.Uid]
140 r := builder.threadBlocks[right.Uid]
141 if l == nil || r == nil {
142 return false
143 }
144 return l.Subject() > r.Subject()
145 }
146 }
147
148 // add uids for the unfetched messages
149 for _, uid := range uids {
150 if _, ok := builder.threadBlocks[uid]; !ok {
151 threads = append(threads, &types.Thread{Uid: uid})
152 }
153 }
154
155 // build thread tree
156 root := &types.Thread{}
157 builder.buildTree(structure, root, bigger, true)
158
159 // copy top-level threads to thread slice
160 for thread := root.FirstChild; thread != nil; thread = thread.NextSibling {
161 thread.Parent = nil
162 threads = append(threads, thread)
163 }
164
165 }
166 return threads
167 }
168
169 // buildTree recursively translates the jwz threads structure into aerc threads
170 func (builder *ThreadBuilder) buildTree(c jwz.Threadable, parent *types.Thread,
171 bigger func(l, r *types.Thread) bool, rootLevel bool,
172 ) {
173 if c == nil || parent == nil {
174 return
175 }
176 for node := c; node != nil; node = node.GetNext() {
177 thread := builder.newThread(node, parent, node.IsDummy())
178 if rootLevel {
179 thread.NextSibling = parent.FirstChild
180 parent.FirstChild = thread
181 } else {
182 parent.InsertCmp(thread, bigger)
183 }
184 builder.buildTree(node.GetChild(), thread, bigger, node.IsDummy())
185 }
186 }
187
188 func (builder *ThreadBuilder) newThread(c jwz.Threadable, parent *types.Thread,
189 hidden bool,
190 ) *types.Thread {
191 hide := 0
192 if hidden {
193 hide += 1
194 }
195 if threadable, ok := c.(*threadable); ok {
196 return &types.Thread{
197 Uid: threadable.UID(),
198 Parent: parent,
199 Hidden: hide,
200 }
201 }
202 return nil
203 }
204
205 func (builder *ThreadBuilder) sortThreads(threads []*types.Thread, orderedUids []models.UID) {
206 types.SortThreadsBy(threads, orderedUids)
207 }
208
209 // RebuildUids rebuilds the uids from the given slice of threads
210 func (builder *ThreadBuilder) RebuildUids(threads []*types.Thread, inverse bool) {
211 uids := make([]models.UID, 0, len(threads))
212 iterT := builder.iterFactory.NewIterator(threads)
213 for iterT.Next() {
214 var threaduids []models.UID
215 _ = iterT.Value().(*types.Thread).Walk(
216 func(t *types.Thread, level int, currentErr error) error {
217 stored, ok := builder.threadMap[t.Uid]
218 if ok {
219 // make this info persistent
220 t.Hidden = stored.Hidden
221 t.Deleted = stored.Deleted
222 }
223 builder.threadMap[t.Uid] = t
224 if t.Deleted || t.Hidden != 0 {
225 return nil
226 }
227 threaduids = append(threaduids, t.Uid)
228 return nil
229 })
230 if inverse {
231 for j := len(threaduids) - 1; j >= 0; j-- {
232 uids = append(uids, threaduids[j])
233 }
234 } else {
235 uids = append(uids, threaduids...)
236 }
237 }
238
239 result := make([]models.UID, 0, len(uids))
240 iterU := builder.iterFactory.NewIterator(uids)
241 for iterU.Next() {
242 result = append(result, iterU.Value().(models.UID))
243 }
244 builder.threadedUids = result
245 }
246
247 // threadable implements the jwz.threadable interface which is required for the
248 // jwz threading algorithm
249 type threadable struct {
250 MsgInfo *models.MessageInfo
251 MessageId string
252 Next jwz.Threadable
253 Parent jwz.Threadable
254 Child jwz.Threadable
255 Dummy bool
256 bySubject bool
257 }
258
259 func newThreadable(msg *models.MessageInfo, bySubject bool) *threadable {
260 msgid, err := msg.MsgId()
261 if err != nil {
262 return nil
263 }
264 return &threadable{
265 MessageId: msgid,
266 MsgInfo: msg,
267 Next: nil,
268 Parent: nil,
269 Child: nil,
270 Dummy: false,
271 bySubject: bySubject,
272 }
273 }
274
275 func (t *threadable) MessageThreadID() string {
276 return t.MessageId
277 }
278
279 func (t *threadable) MessageThreadReferences() []string {
280 if t.IsDummy() || t.MsgInfo == nil {
281 return nil
282 }
283 irp, err := t.MsgInfo.InReplyTo()
284 if err != nil {
285 irp = ""
286 }
287 refs, err := t.MsgInfo.References()
288 if err != nil || len(refs) == 0 {
289 if irp == "" {
290 return nil
291 }
292 refs = []string{irp}
293 }
294 return cleanRefs(t.MessageThreadID(), irp, refs)
295 }
296
297 // cleanRefs cleans up the references headers for threading
298 // 1) message-id should not be part of the references
299 // 2) no message-id should occur twice (avoid circularities)
300 // 3) in-reply-to header should not be at the beginning
301 func cleanRefs(m, irp string, refs []string) []string {
302 considered := make(map[string]any)
303 cleanRefs := make([]string, 0, len(refs))
304 for _, r := range refs {
305 if _, seen := considered[r]; r != m && !seen {
306 considered[r] = nil
307 cleanRefs = append(cleanRefs, r)
308 }
309 }
310 if irp != "" && len(cleanRefs) > 0 {
311 if cleanRefs[0] == irp {
312 cleanRefs = append(cleanRefs[1:], irp)
313 }
314 }
315 return cleanRefs
316 }
317
318 func (t *threadable) UID() models.UID {
319 if t.MsgInfo == nil {
320 return ""
321 }
322 return t.MsgInfo.Uid
323 }
324
325 func (t *threadable) Subject() string {
326 if !t.bySubject || t.MsgInfo == nil || t.MsgInfo.Envelope == nil {
327 return ""
328 }
329 return t.MsgInfo.Envelope.Subject
330 }
331
332 func (t *threadable) SimplifiedSubject() string {
333 if t.bySubject {
334 subject, _ := sortthread.GetBaseSubject(t.Subject())
335 return subject
336 }
337 return ""
338 }
339
340 func (t *threadable) SubjectIsReply() bool {
341 if t.bySubject {
342 _, replyOrForward := sortthread.GetBaseSubject(t.Subject())
343 return replyOrForward
344 }
345 return false
346 }
347
348 func (t *threadable) SetNext(next jwz.Threadable) {
349 t.Next = next
350 }
351
352 func (t *threadable) SetChild(kid jwz.Threadable) {
353 t.Child = kid
354 if kid != nil {
355 kid.SetParent(t)
356 }
357 }
358
359 func (t *threadable) SetParent(parent jwz.Threadable) {
360 t.Parent = parent
361 }
362
363 func (t *threadable) GetNext() jwz.Threadable {
364 return t.Next
365 }
366
367 func (t *threadable) GetChild() jwz.Threadable {
368 return t.Child
369 }
370
371 func (t *threadable) GetParent() jwz.Threadable {
372 return t.Parent
373 }
374
375 func (t *threadable) GetDate() time.Time {
376 if t.IsDummy() {
377 if t.GetChild() != nil {
378 return t.GetChild().GetDate()
379 }
380 return time.Unix(0, 0)
381 }
382 if t.MsgInfo == nil || t.MsgInfo.Envelope == nil {
383 return time.Unix(0, 0)
384 }
385 return t.MsgInfo.Envelope.Date
386 }
387
388 func (t *threadable) MakeDummy(forID string) jwz.Threadable {
389 return &threadable{
390 MessageId: forID,
391 Dummy: true,
392 }
393 }
394
395 func (t *threadable) IsDummy() bool {
396 return t.Dummy
397 }