| 1 |
// Author: Jim Idle - [email protected] / [email protected] |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package jwz |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"io/fs" |
| 9 |
"log" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"regexp" |
| 13 |
"strings" |
| 14 |
"testing" |
| 15 |
"time" |
| 16 |
|
| 17 |
_ "github.com/emersion/go-message/charset" |
| 18 |
"github.com/emersion/go-message/mail" |
| 19 |
) |
| 20 |
|
| 21 |
// Where we are going to store the emails. We know that the test data is of a fair size, so we tell the slice that |
| 22 |
// in advance |
| 23 |
var Emails = make([]Threadable, 0, 93) |
| 24 |
|
| 25 |
// ls -1 testdata | wc -l |
| 26 |
const MessageNumber = 93 |
| 27 |
|
| 28 |
// TestMain sets up everything for the other test(s). It essentially parses a largish set of publicly available |
| 29 |
// Emails in to a structure that can then be used to perform email threading testing. |
| 30 |
func TestMain(m *testing.M) { |
| 31 |
// Parse all the emails in the test directory |
| 32 |
// |
| 33 |
loadEmails() |
| 34 |
|
| 35 |
// OK, we have a fairly large email set all parsed, so now we can let the real tests run |
| 36 |
// |
| 37 |
os.Exit(m.Run()) |
| 38 |
} |
| 39 |
|
| 40 |
func loadEmails() { |
| 41 |
_ = filepath.WalkDir("testdata", func(path string, d fs.DirEntry, err error) error { |
| 42 |
if err != nil { |
| 43 |
log.Printf("cannot process directory/file %s because: %#v", path, err) |
| 44 |
os.Exit(1) |
| 45 |
} |
| 46 |
|
| 47 |
if d.IsDir() { |
| 48 |
// Skip any directory entries, including the base test data dir |
| 49 |
// |
| 50 |
return nil |
| 51 |
} |
| 52 |
|
| 53 |
// We only look at files that have an eml extension |
| 54 |
// |
| 55 |
if !strings.HasSuffix(path, ".eml") { |
| 56 |
return nil |
| 57 |
} |
| 58 |
|
| 59 |
f, e := os.Open(path) |
| 60 |
if e != nil { |
| 61 |
return err |
| 62 |
} |
| 63 |
r, e1 := mail.CreateReader(f) |
| 64 |
_ = f.Close() |
| 65 |
if e1 != nil { |
| 66 |
log.Printf("cannot parse email file error = %v", e1) |
| 67 |
return nil |
| 68 |
} |
| 69 |
|
| 70 |
// All is good, so let's accumulate the email |
| 71 |
// |
| 72 |
email := NewEmail(r.Header) |
| 73 |
Emails = append(Emails, email) |
| 74 |
return nil |
| 75 |
}) |
| 76 |
} |
| 77 |
|
| 78 |
// EmailRoot is a structure that implements the ThreadableRoot interface. I have not used ThreadableRoot |
| 79 |
// here, but this is what it needs to look like if your input structure is not just a slice of Threadable |
| 80 |
type EmailRoot struct { |
| 81 |
// This is some structure of the emails you want to thread, that you know how to traverse |
| 82 |
// |
| 83 |
emails []Threadable |
| 84 |
|
| 85 |
// You need some sort of position holder, which in this silly example is an index in the struct |
| 86 |
// |
| 87 |
position int |
| 88 |
} |
| 89 |
|
| 90 |
// Next sets the internal cursor to the next available Threadable |
| 91 |
func (e *EmailRoot) Next() bool { |
| 92 |
e.position = e.position + 1 |
| 93 |
if e.position < len(e.emails) { |
| 94 |
return true |
| 95 |
} |
| 96 |
return false |
| 97 |
} |
| 98 |
|
| 99 |
// Get returns the Threadable at the current internal cursor position |
| 100 |
func (e *EmailRoot) Get() Threadable { |
| 101 |
return e.emails[e.position] |
| 102 |
} |
| 103 |
|
| 104 |
// NewThreadableRoot returns a struct instance that can be traversed using the ThreadableRoot interface |
| 105 |
func NewThreadableRoot(emails []Threadable) ThreadableRoot { |
| 106 |
tr := &EmailRoot{ |
| 107 |
emails: emails, |
| 108 |
position: -1, |
| 109 |
} |
| 110 |
return tr |
| 111 |
} |
| 112 |
|
| 113 |
// Email is structure that implements the Threadable interface - this is what a user of this |
| 114 |
// package needs to do. |
| 115 |
type Email struct { |
| 116 |
header mail.Header |
| 117 |
next Threadable |
| 118 |
parent Threadable |
| 119 |
child Threadable |
| 120 |
dummy bool |
| 121 |
forID string |
| 122 |
} |
| 123 |
|
| 124 |
func (e *Email) GetNext() Threadable { |
| 125 |
return e.next |
| 126 |
} |
| 127 |
|
| 128 |
func (e *Email) GetChild() Threadable { |
| 129 |
return e.child |
| 130 |
} |
| 131 |
|
| 132 |
// GetParent the parent Threadable of this node, if any |
| 133 |
func (e *Email) GetParent() Threadable { |
| 134 |
return e.parent |
| 135 |
} |
| 136 |
|
| 137 |
// GetDate extracts the timestamp from the envelope contained in the supplied Threadable |
| 138 |
func (e *Email) GetDate() time.Time { |
| 139 |
// We can have dummies because we are likely to have parsed a set of emails with incomplete threads, |
| 140 |
// where the start of the thread or sub thread was referenced, but we did not get to parse it, at least yet. |
| 141 |
// This means it will be a placeholder as the root for the thread, so we can use the time of the child as the |
| 142 |
// time of this email. |
| 143 |
// |
| 144 |
if e.IsDummy() { |
| 145 |
if e.GetChild() != nil { |
| 146 |
return e.GetChild().GetDate() |
| 147 |
} |
| 148 |
|
| 149 |
// Protect against having nothing in the children that knows what time it is. So, back to the |
| 150 |
// beginning of time according to Unix |
| 151 |
// |
| 152 |
return time.Unix(0, 0) |
| 153 |
} |
| 154 |
d, err := e.header.Date() |
| 155 |
if err != nil { |
| 156 |
return time.Unix(0, 0) |
| 157 |
} |
| 158 |
return d |
| 159 |
} |
| 160 |
|
| 161 |
var idre = regexp.MustCompile("<.*?>") |
| 162 |
|
| 163 |
func (e *Email) MessageThreadID() string { |
| 164 |
if e.dummy { |
| 165 |
return e.forID |
| 166 |
} |
| 167 |
ref := e.header.Get("Message-Id") |
| 168 |
refs := idre.FindAllString(ref, -1) |
| 169 |
if len(refs) > 0 { |
| 170 |
return refs[0] |
| 171 |
} |
| 172 |
return "<bogus-id-in-email>" |
| 173 |
} |
| 174 |
|
| 175 |
func (e *Email) MessageThreadReferences() []string { |
| 176 |
if e.dummy { |
| 177 |
return nil |
| 178 |
} |
| 179 |
|
| 180 |
// This should be a nicely formatted field that has unique IDs enclosed within <>, and each of those should be |
| 181 |
// space separated. However, it isn't as simple as this because all sorts of garbage mail clients have been programmed |
| 182 |
// over the years by people who did not understand what the References field was (I'm looking at you |
| 183 |
// Comcast, for instance). We can get things like: |
| 184 |
// |
| 185 |
// 1) References: Your message of Friday... <actual-ID> (Some garbage the programmer thought might be useful) |
| 186 |
// 2) References: [email protected] (This isn't even a reference, it is the sender's email) |
| 187 |
// 3) References: <ref-1><ref-2><ref-3> (Either a pure bug, or they misread the spec) |
| 188 |
// |
| 189 |
// Further to this, we also need to filter out the following: |
| 190 |
// |
| 191 |
// 4) References: <this message-id> (The client author places this email as the first in the |
| 192 |
// reference chain) |
| 193 |
// 5) References: <ref-1><ref-2><ref-1> A pure bug somewhere in the chain repeats a reference |
| 194 |
// |
| 195 |
// The RFC has now been cleaned up to exactly specify this field, but we have to assume there are still |
| 196 |
// 20 year old email clients out there and cater for them. Especially when we are testing with ancient |
| 197 |
// public email bodies. |
| 198 |
// |
| 199 |
ref := e.header.Get("References") |
| 200 |
|
| 201 |
// Find all the correctly delimited references, which takes care of 1) and 3) |
| 202 |
// |
| 203 |
rawRefs := idre.FindAllString(ref, -1) |
| 204 |
|
| 205 |
// Find the message Id, so we can take care of 4) |
| 206 |
// |
| 207 |
m := e.MessageThreadID() |
| 208 |
|
| 209 |
// Find the From address, so we can deal with 2). Even though ignoring this would be harmless in that we would just |
| 210 |
// think it is an email we never saw, it is wrong not to deal with here. We can avoid the clutter in the database |
| 211 |
// by filtering them out. |
| 212 |
// |
| 213 |
fa, _ := e.header.AddressList("From") |
| 214 |
|
| 215 |
// Make a set, so we can remove duplicates and deal with 5) |
| 216 |
// |
| 217 |
set := make(map[string]any) |
| 218 |
|
| 219 |
// This will be our final return set, after de-fucking the references |
| 220 |
// |
| 221 |
refs := make([]string, 0, len(rawRefs)) |
| 222 |
|
| 223 |
// Now we range through the references that the email has given us and make sure that the reference does |
| 224 |
// not run afoul of 2), 4) or 5) |
| 225 |
// |
| 226 |
for _, r := range rawRefs { |
| 227 |
// 2) and 5) |
| 228 |
// |
| 229 |
if _, repeated := set[r]; r != m && !repeated { |
| 230 |
|
| 231 |
set[r] = nil |
| 232 |
|
| 233 |
// Technically, From: can have more than one sender (back in the day before email lists |
| 234 |
// got sorted), we will never see this in practice, but, in for a pound, in for a penny |
| 235 |
// |
| 236 |
var found bool = false |
| 237 |
for _, f := range fa { |
| 238 |
if r == "<"+f.Address+">" { |
| 239 |
found = true |
| 240 |
break |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
if !found { |
| 245 |
// If we got thorough all of those checks, then Phew! Made it! |
| 246 |
// |
| 247 |
refs = append(refs, r) |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
return refs |
| 252 |
} |
| 253 |
|
| 254 |
var re = regexp.MustCompile("[Rr][Ee][ \t]*:[ \t]*") |
| 255 |
|
| 256 |
func (e *Email) SimplifiedSubject() string { |
| 257 |
if e.dummy { |
| 258 |
return "" |
| 259 |
} |
| 260 |
subj := e.header.Get("Subject") |
| 261 |
subj = re.ReplaceAllString(subj, "") |
| 262 |
return subj |
| 263 |
} |
| 264 |
|
| 265 |
func (e *Email) Subject() string { |
| 266 |
if e.dummy { |
| 267 |
if e.child != nil { |
| 268 |
return e.child.Subject() + " :: node synthesized by https://gatherstars.com/" |
| 269 |
} |
| 270 |
|
| 271 |
return fmt.Sprintf("Placeholder %s - manufactured by https://gatherstars.com/", e.forID) |
| 272 |
} |
| 273 |
|
| 274 |
// Add in the date for a bit of extra information |
| 275 |
// |
| 276 |
var sb strings.Builder |
| 277 |
t := e.GetDate() |
| 278 |
sb.WriteString(t.UTC().String()) |
| 279 |
sb.WriteString(" : ") |
| 280 |
sb.WriteString(strings.Trim(e.header.Get("Subject"), " ")) |
| 281 |
return sb.String() |
| 282 |
} |
| 283 |
|
| 284 |
func (e *Email) SubjectIsReply() bool { |
| 285 |
subj := e.header.Get("Subject") |
| 286 |
return re.MatchString(subj) |
| 287 |
} |
| 288 |
|
| 289 |
func (e *Email) SetNext(next Threadable) { |
| 290 |
e.next = next |
| 291 |
} |
| 292 |
|
| 293 |
func (e *Email) SetChild(kid Threadable) { |
| 294 |
e.child = kid |
| 295 |
if kid != nil { |
| 296 |
kid.SetParent(e) |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
// SetParent allows us to add or change the parent Threadable of this node |
| 301 |
func (e *Email) SetParent(parent Threadable) { |
| 302 |
e.parent = parent |
| 303 |
} |
| 304 |
|
| 305 |
func (e *Email) MakeDummy(forID string) Threadable { |
| 306 |
return &Email{ |
| 307 |
dummy: true, |
| 308 |
forID: forID, |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
func (e *Email) IsDummy() bool { |
| 313 |
return e.dummy |
| 314 |
} |
| 315 |
|
| 316 |
func NewEmail(header mail.Header) Threadable { |
| 317 |
e := &Email{ |
| 318 |
header: header, |
| 319 |
dummy: false, |
| 320 |
} |
| 321 |
return e |
| 322 |
} |
| 323 |
|
| 324 |
func ExampleThreader_ThreadSlice() { |
| 325 |
// Emails := loadEmails() - your function to load emails into a slice |
| 326 |
// |
| 327 |
|
| 328 |
// Create a threader and thread using the slice of Threadable in the slice called Emails |
| 329 |
// |
| 330 |
threader := NewThreader() |
| 331 |
sliceRoot, err := threader.ThreadSlice(Emails) |
| 332 |
if err != nil { |
| 333 |
fmt.Printf("func ThreadSlice() error = %#v", err) |
| 334 |
return |
| 335 |
} |
| 336 |
|
| 337 |
// Make sure that number we got back, not including dummies, is the same as we sent in |
| 338 |
// |
| 339 |
var nc int |
| 340 |
Count(sliceRoot, &nc) |
| 341 |
if nc != MessageNumber { |
| 342 |
fmt.Printf("expected %d emails after threading, but got %d back", MessageNumber, nc) |
| 343 |
} else { |
| 344 |
fmt.Printf("There are %d test emails", nc) |
| 345 |
} |
| 346 |
// Output: There are 93 test emails |
| 347 |
} |
| 348 |
|
| 349 |
func TestThreader_ThreadSlice(t1 *testing.T) { |
| 350 |
// Emails := loadEmails() - your function to load emails into a slice |
| 351 |
// |
| 352 |
|
| 353 |
// Create a threader and thread using the slice of Threadable in the slice called Emails |
| 354 |
// |
| 355 |
threader := NewThreader() |
| 356 |
sliceRoot, err := threader.ThreadSlice(Emails) |
| 357 |
if err != nil { |
| 358 |
t1.Errorf("func ThreadSlice() error = %#v", err) |
| 359 |
} |
| 360 |
|
| 361 |
// Make sure that number we got back, not including dummies, is the same as we sent in |
| 362 |
// |
| 363 |
var nc int |
| 364 |
Count(sliceRoot, &nc) |
| 365 |
if nc != MessageNumber { |
| 366 |
t1.Errorf("expected %d emails after threading, but got %d back", MessageNumber, nc) |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
func ExampleThreader_ThreadRoot() { |
| 371 |
// Emails := loadEmails() - your function to load emails into a slice |
| 372 |
// |
| 373 |
|
| 374 |
// Create a threader and thread using the slice of Threadable in the slice called Emails |
| 375 |
// |
| 376 |
tr := NewThreadableRoot(Emails) |
| 377 |
threader := NewThreader() |
| 378 |
treeRoot, err := threader.ThreadRoot(tr) |
| 379 |
if err != nil { |
| 380 |
fmt.Printf("func ThreadRoot() error = %#v", err) |
| 381 |
} |
| 382 |
if treeRoot == nil { |
| 383 |
fmt.Printf("received no output from the threading algorithm") |
| 384 |
} |
| 385 |
// Make sure that number we got back, not including dummies, is the same as we sent in |
| 386 |
// |
| 387 |
var nc int |
| 388 |
Count(treeRoot, &nc) |
| 389 |
if nc != MessageNumber { |
| 390 |
fmt.Printf("expected %d emails after threading, but got %d back", MessageNumber, nc) |
| 391 |
} else { |
| 392 |
fmt.Printf("There are %d test emails", nc) |
| 393 |
} |
| 394 |
// Output: There are 93 test emails |
| 395 |
} |
| 396 |
|
| 397 |
func TestThreader_ThreadRoot(t1 *testing.T) { |
| 398 |
// Emails := loadEmails() - your function to load emails into a slice |
| 399 |
// |
| 400 |
|
| 401 |
// Create a threader and thread using the ThreadableRootInterface to traverse the emails |
| 402 |
// |
| 403 |
tr := NewThreadableRoot(Emails) |
| 404 |
threader := NewThreader() |
| 405 |
treeRoot, err := threader.ThreadRoot(tr) |
| 406 |
if err != nil { |
| 407 |
t1.Errorf("ThreadRoot() error = %#v", err) |
| 408 |
} |
| 409 |
if treeRoot == nil { |
| 410 |
t1.Errorf("received no output from the threading algorithm") |
| 411 |
} |
| 412 |
// Make sure that number we got back, not including dummies, is the same as we sent in |
| 413 |
// |
| 414 |
var nc int |
| 415 |
Count(treeRoot, &nc) |
| 416 |
if nc != MessageNumber { |
| 417 |
t1.Errorf("expected %d emails after threading, but got %d back", MessageNumber, nc) |
| 418 |
} |
| 419 |
} |