implement message threading in backend and webmail

we match messages to their parents based on the "references" and "in-reply-to"
headers (requiring the same base subject), and in absense of those headers we
also by only base subject (against messages received max 4 weeks ago).

we store a threadid with messages. all messages in a thread have the same
threadid.  messages also have a "thread parent ids", which holds all id's of
parent messages up to the thread root.  then there is "thread missing link",
which is set when a referenced immediate parent wasn't found (but possibly
earlier ancestors can still be found and will be in thread parent ids".

threads can be muted: newly delivered messages are automatically marked as
read/seen.  threads can be marked as collapsed: if set, the webmail collapses
the thread to a single item in the basic threading view (default is to expand
threads).  the muted and collapsed fields are copied from their parent on
message delivery.

the threading is implemented in the webmail. the non-threading mode still works
as before. the new default threading mode "unread" automatically expands only
the threads with at least one unread (not seen) meessage. the basic threading
mode "on" expands all threads except when explicitly collapsed (as saved in the
thread collapsed field). new shortcuts for navigation/interaction threads have
been added, e.g. go to previous/next thread root, toggle collapse/expand of
thread (or double click), toggle mute of thread. some previous shortcuts have
changed, see the help for details.

the message threading are added with an explicit account upgrade step,
automatically started when an account is opened. the upgrade is done in the
background because it will take too long for large mailboxes to block account
operations. the upgrade takes two steps: 1. updating all message records in the
database to add a normalized message-id and thread base subject (with "re:",
"fwd:" and several other schemes stripped). 2. going through all messages in
the database again, reading the "references" and "in-reply-to" headers from
disk, and matching against their parents. this second step is also done at the
end of each import of mbox/maildir mailboxes. new deliveries are matched
immediately against other existing messages, currently no attempt is made to
rematch previously delivered messages (which could be useful for related
messages being delivered out of order).

the threading is not yet exposed over imap.
This commit is contained in:
Mechiel Lukkien
2023-09-13 08:51:50 +02:00
parent b754b5f9ac
commit 3fb41ff073
44 changed files with 5930 additions and 821 deletions

View File

@ -193,6 +193,9 @@ type importProblem struct {
}
type importDone struct{}
type importAborted struct{}
type importStep struct {
Title string
}
// importStart prepare the import and launches the goroutine to actually import.
// importStart is responsible for closing f.
@ -284,12 +287,6 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
// ID's of delivered messages. If we have to rollback, we have to remove this files.
var deliveredIDs []int64
ximportcheckf := func(err error, format string, args ...any) {
if err != nil {
panic(importError{fmt.Errorf("%s: %s", fmt.Sprintf(format, args...), err)})
}
}
sendEvent := func(kind string, v any) {
buf, err := json.Marshal(v)
if err != nil {
@ -300,11 +297,6 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
importers.Events <- importEvent{token, []byte(ssemsg), v, nil}
}
problemf := func(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
sendEvent("problem", importProblem{Message: msg})
}
canceled := func() bool {
select {
case <-ctx.Done():
@ -315,6 +307,11 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
}
}
problemf := func(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
sendEvent("problem", importProblem{Message: msg})
}
defer func() {
err := f.Close()
log.Check(err, "closing uploaded messages file")
@ -349,6 +346,15 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
}
}()
ximportcheckf := func(err error, format string, args ...any) {
if err != nil {
panic(importError{fmt.Errorf("%s: %s", fmt.Sprintf(format, args...), err)})
}
}
err := acc.ThreadingWait(log)
ximportcheckf(err, "waiting for account thread upgrade")
conf, _ := acc.Conf()
jf, _, err := acc.OpenJunkFilter(ctx, log)
@ -515,6 +521,11 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
m.ParsedBuf, err = json.Marshal(p)
ximportcheckf(err, "marshal parsed message structure")
// Set fields needed for future threading. By doing it now, DeliverMessage won't
// have to parse the Part again.
p.SetReaderAt(store.FileMsgReader(m.MsgPrefix, f))
m.PrepareThreading(log, &p)
if m.Received.IsZero() {
if p.Envelope != nil && !p.Envelope.Date.IsZero() {
m.Received = p.Envelope.Date
@ -534,7 +545,8 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
const consumeFile = true
const sync = false
const notrain = true
if err := acc.DeliverMessage(log, tx, m, f, consumeFile, sync, notrain); err != nil {
const nothreads = true
if err := acc.DeliverMessage(log, tx, m, f, consumeFile, sync, notrain, nothreads); err != nil {
problemf("delivering message %s: %s (continuing)", pos, err)
return
}
@ -797,13 +809,20 @@ func importMessages(ctx context.Context, log *mlog.Log, token string, acc *store
for _, count := range messages {
total += count
}
log.Debug("message imported", mlog.Field("total", total))
log.Debug("messages imported", mlog.Field("total", total))
// Send final update for count of last-imported mailbox.
if prevMailbox != "" {
sendEvent("count", importCount{prevMailbox, messages[prevMailbox]})
}
// Match threads.
if len(deliveredIDs) > 0 {
sendEvent("step", importStep{"matching messages with threads"})
err = acc.AssignThreads(ctx, log, tx, deliveredIDs[0], 0, io.Discard)
ximportcheckf(err, "assigning messages to threads")
}
// Update mailboxes with counts and keywords.
for mbID, mc := range destMailboxCounts {
mb := store.Mailbox{ID: mbID}