Debian Codegraph @

lib/jwz/jwz.go

raw
1 // Package jwz is an implementation of the email threading algorithm created by Jamie Zawinski and explained by him
2 // at: https://www.jwz.org/doc/threading.html
3 //
4 // This package was created by cribbing from the code at:
5 //
6 // https://www.jwz.org/doc/threading.html#:~:text=grendel-1999-05-14.tar.gz
7 //
8 // from the Java source code in view/Threader.java - it contains no ham and cheese sandwiches.
9 //
10 // The code, interface etc. was obviously adapted in to Go form, though where possible, the code reflects the
11 // original Java if it is not too ungolike.
12 //
13 // Author: Jim Idle - [email protected] / [email protected]
14 // SPDX-License-Identifier: Apache-2.0
15 //
16 // See the LICENSE file, sit down, have a scone.
17
18 package jwz
19
20 import (
21 "errors"
22 "fmt"
23 )
24
25 // Threader arranges a set of messages into a thread hierarchy, by references.
26 type Threader struct {
27 rootNode *threadContainer
28 idTable map[string]*threadContainer
29 bogusIDCount int
30 }
31
32 // NewThreader returns an instance of the Threader struct, that is ready to attack
33 // your Threadable
34 //
35 //goland:noinspection GoUnusedExportedFunction
36 func NewThreader() *Threader {
37 t := &Threader{
38 idTable: make(map[string]*threadContainer),
39 }
40 return t
41 }
42
43 // Thread will create a threadable organized so that the root node
44 // is the original reference, creating dummy placeholders for the emails
45 // we don't have yet
46 func (t *Threader) Thread(threadable Threadable) (Threadable, error) {
47 if threadable == nil {
48 return nil, nil
49 }
50
51 // Build a thread container from this single email
52 //
53 if !threadable.IsDummy() {
54 if err := t.buildContainer(threadable); err != nil {
55 return nil, err
56 }
57 } else {
58 return nil, errors.New("cannot thread a single email with a dummy root")
59 }
60
61 var err error
62
63 // Organize the root set from what we have
64 //
65 t.rootNode, err = t.findRootSet()
66 if err != nil {
67 return nil, err
68 }
69
70 // We no longer need the map - probably no real need to blank it here, but the original Java code did that,
71 // and it won't harm to let the GC reclaim this in case our caller keeps the *Threader around for some reason
72 //
73 t.idTable = nil
74
75 // We do this to avoid flipping the input order each time through.
76 //
77 t.rootNode.reverseChildren()
78
79 // There should not be a next in the root of a conversation thread
80 //
81 if t.rootNode.next != nil {
82 return nil, fmt.Errorf("root node contains a next and should not: %#v", t.rootNode)
83 }
84
85 // Because the result of this function is a tree that does actually contain dummies for missing references
86 // we need to add a dummy threadable for any node that does not yet have one. Then we can flush the chain
87 // of containers in to the threadable
88 //
89 t.rootNode.fillDummy(threadable)
90
91 var result Threadable
92 if t.rootNode.child != nil {
93 result = t.rootNode.child.threadable
94 }
95
96 // Flush the tree structure of each element of the root set down into
97 // their underlying Threadables
98 //
99 _ = t.rootNode.flush()
100 t.rootNode = nil
101
102 return result, nil
103 }
104
105 // ThreadSlice will thread the set of messages contained within threadableSlice.
106 // The Threadable returned is the new first element of the root set.
107 func (t *Threader) ThreadSlice(threadableSlice []Threadable) (Threadable, error) {
108 if len(threadableSlice) == 0 {
109 return nil, nil
110 }
111
112 // Iterate all the Threadable represented by the root and build the
113 // threadContainer from them
114 //
115 for _, nt := range threadableSlice {
116 if !nt.IsDummy() {
117 if err := t.buildContainer(nt); err != nil {
118 return nil, err
119 }
120 }
121 }
122 return t.threadRoot()
123 }
124
125 // ThreadRoot will thread the set of messages provided by ThreadableRoot.
126 // The Threadable returned is the new first element of the root set.
127 func (t *Threader) ThreadRoot(threadableRoot ThreadableRoot) (Threadable, error) {
128 if threadableRoot == nil {
129 return nil, nil
130 }
131
132 // Iterate all the Threadable represented by the root and build the
133 // threadContainer from them
134 //
135 for threadableRoot.Next() {
136 nt := threadableRoot.Get()
137 if !nt.IsDummy() {
138 if err := t.buildContainer(nt); err != nil {
139 return nil, err
140 }
141 }
142 }
143 return t.threadRoot()
144 }
145
146 func (t *Threader) threadRoot() (Threadable, error) {
147 var err error
148
149 // Organize the root set from what we have
150 //
151 t.rootNode, err = t.findRootSet()
152 if err != nil {
153 return nil, err
154 }
155
156 // We no longer need the map - probably no real need to blank it here, but the original Java code did that,
157 // and it won't harm to let the GC reclaim this in case our caller keeps the *Threader around for some reason
158 //
159 t.idTable = nil
160
161 // Get rid of any empty containers. They should no longer needed
162 //
163 t.pruneEmptyContainers(t.rootNode)
164
165 // We do this so to avoid flipping the input order each time through.
166 //
167 t.rootNode.reverseChildren()
168
169 // We might need to sort on subjects, so let's process them
170 //
171 t.gatherSubjects()
172
173 // There should not be a next in the root of a conversation thread
174 //
175 if t.rootNode.next != nil {
176 return nil, fmt.Errorf("root node contains a next and should not: %#v", t.rootNode)
177 }
178
179 for r := t.rootNode.child; r != nil; r = r.next {
180 // If this direct child of the root node has no threadable in it,
181 // manufacture a dummy container to bind its children together.
182 // Note that these dummies can only ever occur as elements of
183 // the root set.
184 //
185 if r.threadable == nil {
186 r.threadable = r.child.threadable.MakeDummy(r.forID)
187 }
188 }
189
190 var result Threadable
191 if t.rootNode.child != nil {
192 result = t.rootNode.child.threadable
193 }
194
195 // Flush the tree structure of each element of the root set down into
196 // their underlying Threadables
197 //
198 _ = t.rootNode.flush()
199 t.rootNode = nil
200
201 return result, nil
202 }
203
204 // buildContainer() does three things:
205 //
206 // - It walks the tree of Threadable, and wraps each in a
207 // threadContainer object.
208 // - It indexes each threadContainer object in the idTable, under
209 // the message ID of the contained Threadable.
210 // - For each of the references within Threadable, it ensures that there
211 // is a threadContainer in the table (an empty one, if necessary.)
212 func (t *Threader) buildContainer(threadable Threadable) error {
213 var present bool
214
215 // See if we already have a container for this threadable
216 //
217 id := threadable.MessageThreadID()
218 tid := id
219
220 c, present := t.idTable[id]
221 if present {
222 // There is already a ThreadContainer in the table for this ID.
223 // Under normal circumstances, there will be no IThreadable in it
224 // (since it was a forward reference from a References field.)
225 //
226 // If there is already a threadable in it, then that means there
227 // are two IThreadables with the same ID. Generate a new ID for
228 // this one, sigh... This ID is only used to cause the two entries
229 // in the hash table to not stomp each other.
230 //
231 if c.threadable != nil {
232 id = fmt.Sprintf("<Bogus-id:%d>", t.bogusIDCount)
233 t.bogusIDCount++
234 c = nil
235 } else {
236 c.threadable = threadable
237 }
238 }
239
240 // Create a ThreadContainer for this Threadable, and store it in
241 // the map
242 //
243 if c == nil {
244 c = &threadContainer{forID: tid}
245 c.threadable = threadable
246 c.forID = tid
247 t.idTable[id] = c
248 }
249
250 // Create ThreadContainers for each of the references which don't
251 // have them. Link each of the referenced messages together in the
252 // order implied by the references field, unless they are already
253 // linked.
254 //
255 var parentRef, ref *threadContainer
256
257 // Iterate through the references field of the threadable and see if we
258 // already have a reference to them in our map. Create one if not
259 //
260 refs := threadable.MessageThreadReferences()
261 for _, refString := range refs {
262
263 ref, present = t.idTable[refString]
264 if !present {
265
266 ref = &threadContainer{forID: refString}
267
268 t.idTable[refString] = ref
269 }
270
271 // If we have references A B C D, make D be a child of C, etc.,
272 // except if they have parents already.
273 //
274 if parentRef != nil && // there is a parent
275 ref.parent == nil && // don't have a parent already
276 parentRef != ref && // not a tight loop
277 !ref.findChild(parentRef) && // already linked
278 !parentRef.findChild(ref) { // not a wide loop
279
280 // Ok, link it into the parent's child list.
281 //
282 ref.parent = parentRef
283 ref.next = parentRef.child
284 parentRef.child = ref
285 }
286 parentRef = ref
287 }
288
289 // At this point `parentRef' is set to the container of the last element
290 // in the references field. Make that be the parent of this container,
291 // unless doing so would introduce a circularity.
292 //
293 if parentRef != nil &&
294 (parentRef == c ||
295 c.findChild(parentRef)) {
296 parentRef = nil
297 }
298
299 if c.parent != nil {
300
301 // If it has a parent already, that's there because we saw this message
302 // in a references field, and presumed a parent based on the other
303 // entries in that field. Now that we have the actual message, we can
304 // be more definitive, so throw away the old parent and use this new one.
305 // Find this container in the parent's child-list, and unlink it.
306 //
307 // Note that this could cause this message to now have no parent, if it
308 // has no references field, but some message referred to it as the
309 // non-first element of its references. (Which would have been some
310 // kind of lie...)
311 //
312 var rest, prev *threadContainer
313 for prev, rest = nil, c.parent.child; rest != nil; {
314 if rest == c {
315 break
316 }
317 prev = rest
318 rest = rest.next
319 }
320
321 if rest == nil {
322 return fmt.Errorf("didn't find %#v in parent %#v", c, c.parent)
323 }
324
325 if prev == nil {
326 c.parent.child = c.next
327 } else {
328 prev.next = c.next
329 }
330
331 c.next = nil
332 c.parent = nil
333 }
334
335 // If we have a parent, link c into the parent's child list.
336 //
337 if parentRef != nil {
338 c.parent = parentRef
339 c.next = parentRef.child
340 parentRef.child = c
341 }
342
343 // No error
344 //
345 return nil
346 }
347
348 // findRootSet finds the root set of the threadContainers, and returns a root node.
349 //
350 // NB: A container is in the root set if it has no parents.
351 func (t *Threader) findRootSet() (*threadContainer, error) {
352 root := &threadContainer{}
353 for _, c := range t.idTable {
354 if c.parent == nil {
355 if c.next != nil {
356 return nil, fmt.Errorf("container has no parent, but has a next value: %#v", c.next)
357 }
358 c.next = root.child
359 root.child = c
360 }
361 }
362 return root, nil
363 }
364
365 // Walk through the threads and discard any empty container objects.
366 // After calling this, there will only be any empty container objects
367 // at depth 0, and those will all have at least two kids.
368 func (t *Threader) pruneEmptyContainers(parent *threadContainer) {
369 var prev *threadContainer
370 container := parent.child
371 var next *threadContainer
372
373 if container != nil {
374 next = container.next
375 }
376
377 for container != nil {
378 switch {
379 case container.threadable == nil && container.child == nil:
380 // This is an empty container with no kids. Nuke it.
381 //
382 // Normally such containers won't occur, but they can show up when
383 // two messages have References lines that disagree. For example,
384 // assuming A and B are messages, and 1, 2, and 3 are references for
385 // messages we haven't seen:
386 //
387 // A has refs: 1 2 3
388 // B has refs: 1 3
389 //
390 // There is ambiguity whether 3 is a child of 1 or 2. So,
391 // depending on the processing order, we might end up with either
392 //
393 // -- 1
394 // |-- 2
395 // |-- 3
396 // |-- A
397 // |-- B
398 // or
399 // -- 1
400 // |-- 2 <--- non-root childless container
401 // |-- 3
402 // |-- A
403 // |-- B
404 //
405 if prev == nil {
406 parent.child = container.next
407 } else {
408 prev.next = container.next
409 }
410
411 // Set container to prev so that prev keeps its same value
412 // the next time through the loop.
413 //
414 container = prev
415
416 case container.threadable == nil && // expired, and
417 container.child != nil && // has kids, and
418 (container.parent != nil || // not at root, or
419 container.child.next == nil):
420
421 // Expired message with kids. Promote the kids to this level.
422 // Don't do this if we would be promoting them to the root level,
423 // unless there is only one kid.
424 //
425 var tail *threadContainer
426 kids := container.child
427
428 // Remove this container from the list, replacing it with `kids'
429 //
430 if prev == nil {
431 parent.child = kids
432 } else {
433 prev.next = kids
434 }
435
436 // Make each child's parent be this level's parent.
437 // Make the last child's next be this container's next
438 // - splicing `kids' into the list in place of `container'
439 //
440 for tail = kids; tail.next != nil; tail = tail.next {
441 tail.parent = container.parent
442 }
443 tail.parent = container.parent
444 tail.next = container.next
445
446 // Since we've inserted items in the chain, `next' currently points
447 // to the item after them (tail.next); reset that so that we process
448 // the newly promoted items the very next time around.
449 //
450 next = kids
451
452 // Set container to prev so that prev keeps its same value
453 // the next time through the loop.
454 //
455 container = prev
456
457 case container.child != nil:
458 // A container with children.
459 // Iterate over its children, and try to strip out the junk.
460 //
461 t.pruneEmptyContainers(container)
462
463 // The recursion may have cleared all of a dummy's children.
464 // If so, remove the now-empty container.
465 //
466 if container.threadable == nil && container.child == nil {
467 if prev == nil {
468 parent.child = container.next
469 } else {
470 prev.next = container.next
471 }
472 container = prev
473 }
474 }
475
476 // Set up for the next iteration
477 //
478 prev = container
479 container = next
480 if container == nil {
481 next = nil
482 } else {
483 next = container.next
484 }
485 }
486 }
487
488 // If any two members of the root set have the same subject, merge them.
489 // This is so that messages which don't have References headers at all
490 // still get threaded (to the extent possible, at least.)
491 func (t *Threader) gatherSubjects() {
492 var count int
493
494 subjTable := make(map[string]*threadContainer)
495
496 for c := t.rootNode.child; c != nil; c = c.next {
497
498 threadable := c.threadable
499
500 // If there is no threadable, this is a dummy node in the root set.
501 // Only root set members may be dummies, and they always have at least
502 // two kids. Take the first kid as representative of the subject.
503 //
504 if threadable == nil {
505 threadable = c.child.threadable
506 }
507
508 subj := threadable.SimplifiedSubject()
509 if subj == "" {
510 continue
511 }
512
513 old := subjTable[subj]
514
515 // Add this container to the table if:
516 // - There is no container in the table with this subject, or
517 // - This one is a dummy container and the old one is not: the dummy
518 // one is more interesting as a root, so put it in the table instead.
519 // - The container in the table has a "Re:" version of this subject,
520 // and this container has a non-"Re:" version of this subject.
521 // The non-re version is the more interesting of the two.
522 //
523 if old == nil ||
524 (c.threadable == nil && old.threadable != nil) ||
525 (old.threadable != nil && old.threadable.SubjectIsReply() &&
526 c.threadable != nil && !c.threadable.SubjectIsReply()) {
527 subjTable[subj] = c
528 count++
529 }
530 }
531
532 // We are done if the table is empty
533 //
534 if count == 0 {
535 return
536 }
537
538 // The subj_table is now populated with one entry for each subject which
539 // occurs in the root set. Now iterate over the root set, and gather
540 // together the difference.
541 //
542 var prev, c, rest *threadContainer
543
544 prev = nil
545 c = t.rootNode.child
546 rest = c.next
547
548 for c != nil {
549
550 threadable := c.threadable
551
552 // might be a dummy -- see above
553 //
554 if threadable == nil {
555 threadable = c.child.threadable
556 }
557
558 subj := threadable.SimplifiedSubject()
559
560 // Don't thread together all subject-less messages; let them dangle.
561 //
562 if subj != "" {
563
564 old := subjTable[subj]
565
566 if old != c { // Avoid processing ourselves
567
568 // Ok, so now we have found another container in the root set with
569 // the same subject. There are a few possibilities:
570 //
571 // - If both are dummies, append one's children to the other, and remove
572 // the now-empty container.
573 //
574 // - If one container is a dummy and the other is not, make the non-dummy
575 // one be a child of the dummy, and a sibling of the other "real"
576 // messages with the same subject (the dummy's children.)
577 //
578 // - If that container is a non-dummy, and that message's subject does
579 // not begin with "Re:", but *this* message's subject does, then
580 // make this be a child of the other.
581 //
582 // - If that container is a non-dummy, and that message's subject begins
583 // with "Re:", but *this* message's subject does *not*, then make that
584 // be a child of this one -- they were mis-ordered. (This happens
585 // somewhat implicitly, since if there are two messages, one with Re:
586 // and one without, the one without will be in the hash table,
587 // regardless of the order in which they were seen.)
588 //
589 // - Otherwise, make a new dummy container and make both messages be a
590 // child of it. This catches the both-are-replies and neither-are-
591 // replies cases, and makes them be siblings instead of asserting a
592 // hierarchical relationship which might not be true.
593 //
594 // (People who reply to a message without using "Re:" and without using
595 // a References line will break this slightly. Those people suck.)
596 //
597 // (It has occurred to me that taking the date or message number into
598 // account would be one way of resolving some ambiguous cases,
599 // but that's not altogether straightforward either.)
600 // JI: You cannot rely on the clock settings being correct on a server/client that sent a message
601 //
602
603 // Remove the "second" message from the root set.
604 if prev == nil {
605 t.rootNode.child = c.next
606 } else {
607 prev.next = c.next
608 }
609 c.next = nil
610
611 switch {
612 case old.threadable == nil && c.threadable == nil:
613 // They're both dummies; merge them.
614 //
615 var tail *threadContainer
616 for tail = old.child; tail != nil && tail.next != nil; tail = tail.next {
617 }
618
619 tail.next = c.child
620 for tail = c.child; tail != nil; tail = tail.next {
621 tail.parent = old
622 }
623 c.child = nil
624
625 case old.threadable == nil || // old is empty, or
626 (c.threadable != nil &&
627 c.threadable.SubjectIsReply() && // c has Re, and
628 !old.threadable.SubjectIsReply()): // old does not.
629
630 // Make this message be a child of the other.
631 c.parent = old
632 c.next = old.child
633 old.child = c
634
635 default:
636 // Make the old and new messages be children of a new dummy container.
637 // We do this by creating a new container object for old->msg and
638 // transforming the old container into a dummy (by merely emptying it),
639 // so that the table still points to the one that is at depth 0
640 // instead of depth 1.
641 //
642 newC := &threadContainer{}
643
644 newC.threadable = old.threadable
645 newC.child = old.child
646 for tail := newC.child; tail != nil; tail = tail.next {
647 tail.parent = newC
648 }
649
650 old.threadable = nil
651 old.child = nil
652
653 c.parent = old
654 newC.parent = old
655
656 // old is now a dummy; make it have exactly two kids, c and newC.
657 //
658 old.child = c
659 c.next = newC
660 }
661
662 // we've done a merge, so keep the same `prev' next time around.
663 //
664 c = prev
665 }
666 }
667 prev = c
668 c = rest
669 if rest != nil {
670 rest = rest.next
671 }
672 }
673 }