1// Package webops implements shared functionality between webapisrv and webmail.
16 "github.com/mjl-/bstore"
18 "github.com/mjl-/mox/junk"
19 "github.com/mjl-/mox/message"
20 "github.com/mjl-/mox/mlog"
21 "github.com/mjl-/mox/moxio"
22 "github.com/mjl-/mox/store"
25var ErrMessageNotFound = errors.New("no such message")
28 DBWrite func(ctx context.Context, acc *store.Account, fn func(tx *bstore.Tx))
29 Checkf func(ctx context.Context, err error, format string, args ...any)
30 Checkuserf func(ctx context.Context, err error, format string, args ...any)
33func (x XOps) mailboxID(ctx context.Context, tx *bstore.Tx, mailboxID int64) store.Mailbox {
35 x.Checkuserf(ctx, errors.New("invalid zero mailbox ID"), "getting mailbox")
37 mb, err := store.MailboxID(tx, mailboxID)
38 if err == bstore.ErrAbsent || err == store.ErrMailboxExpunged {
39 x.Checkuserf(ctx, err, "getting mailbox")
41 x.Checkf(ctx, err, "getting mailbox")
45// messageID returns a non-expunged message or panics with a sherpa error.
46func (x XOps) messageID(ctx context.Context, tx *bstore.Tx, messageID int64) store.Message {
48 x.Checkuserf(ctx, errors.New("invalid zero message id"), "getting message")
50 m := store.Message{ID: messageID}
52 if err == bstore.ErrAbsent {
53 x.Checkuserf(ctx, ErrMessageNotFound, "getting message")
54 } else if err == nil && m.Expunged {
55 x.Checkuserf(ctx, errors.New("message was removed"), "getting message")
57 x.Checkf(ctx, err, "getting message")
61func (x XOps) MessageDelete(ctx context.Context, log mlog.Log, acc *store.Account, messageIDs []int64) {
62 acc.WithWLock(func() {
63 var changes []store.Change
65 x.DBWrite(ctx, acc, func(tx *bstore.Tx) {
66 var modseq store.ModSeq
67 changes = x.MessageDeleteTx(ctx, log, tx, acc, messageIDs, &modseq)
70 store.BroadcastChanges(acc, changes)
74func (x XOps) MessageDeleteTx(ctx context.Context, log mlog.Log, tx *bstore.Tx, acc *store.Account, messageIDs []int64, modseq *store.ModSeq) []store.Change {
75 changes := make([]store.Change, 0, 1+1) // 1 remove, 1 mailbox counts, optimistic that all messages are in 1 mailbox.
80 err := jf.CloseDiscard()
81 log.Check(err, "close junk filter")
88 var changeRemoveUIDs store.ChangeRemoveUIDs
89 xflushMailbox := func() {
91 x.Checkf(ctx, err, "updating mailbox counts")
92 slices.Sort(changeRemoveUIDs.UIDs)
93 changeRemoveUIDs.UIDNext = mb.UIDNext
94 changeRemoveUIDs.MessageCountIMAP = mb.MessageCountIMAP()
95 changeRemoveUIDs.Unseen = uint32(mb.MailboxCounts.Unseen)
96 changes = append(changes, mb.ChangeCounts(), changeRemoveUIDs)
99 for _, id := range messageIDs {
100 m := x.messageID(ctx, tx, id)
104 *modseq, err = acc.NextModSeq(tx)
105 x.Checkf(ctx, err, "assigning next modseq")
108 if m.MailboxID != mb.ID {
112 mb = x.mailboxID(ctx, tx, m.MailboxID)
114 changeRemoveUIDs = store.ChangeRemoveUIDs{MailboxID: mb.ID, ModSeq: *modseq}
117 if m.Junk != m.Notjunk && jf == nil && conf.JunkFilter != nil {
119 jf, _, err = acc.OpenJunkFilter(ctx, log)
120 x.Checkf(ctx, err, "open junk filter")
123 opts := store.RemoveOpts{JunkFilter: jf}
124 _, _, err := acc.MessageRemove(log, tx, *modseq, &mb, opts, m)
125 x.Checkf(ctx, err, "expunge message")
127 changeRemoveUIDs.UIDs = append(changeRemoveUIDs.UIDs, m.UID)
128 changeRemoveUIDs.MsgIDs = append(changeRemoveUIDs.MsgIDs, m.ID)
136 x.Checkf(ctx, err, "close junk filter")
142func (x XOps) MessageFlagsAdd(ctx context.Context, log mlog.Log, acc *store.Account, messageIDs []int64, flaglist []string) {
143 flags, keywords, err := store.ParseFlagsKeywords(flaglist)
144 x.Checkuserf(ctx, err, "parsing flags")
146 acc.WithRLock(func() {
147 var changes []store.Change
149 x.DBWrite(ctx, acc, func(tx *bstore.Tx) {
150 var modseq store.ModSeq
151 var retrain []store.Message
152 var mb, origmb store.Mailbox
154 for _, mid := range messageIDs {
155 m := x.messageID(ctx, tx, mid)
158 modseq, err = acc.NextModSeq(tx)
159 x.Checkf(ctx, err, "assigning next modseq")
162 if mb.ID != m.MailboxID {
165 err := tx.Update(&mb)
166 x.Checkf(ctx, err, "updating mailbox")
167 if mb.MailboxCounts != origmb.MailboxCounts {
168 changes = append(changes, mb.ChangeCounts())
170 if mb.KeywordsChanged(origmb) {
171 changes = append(changes, mb.ChangeKeywords())
174 mb = x.mailboxID(ctx, tx, m.MailboxID)
177 mb.Keywords, _ = store.MergeKeywords(mb.Keywords, keywords)
179 mb.Sub(m.MailboxCounts())
181 m.Flags = m.Flags.Set(flags, flags)
183 m.Keywords, kwChanged = store.MergeKeywords(m.Keywords, keywords)
184 mb.Add(m.MailboxCounts())
186 if m.Flags == oflags && !kwChanged {
192 x.Checkf(ctx, err, "updating message")
194 changes = append(changes, m.ChangeFlags(oflags, mb))
195 retrain = append(retrain, m)
200 err := tx.Update(&mb)
201 x.Checkf(ctx, err, "updating mailbox")
202 if mb.MailboxCounts != origmb.MailboxCounts {
203 changes = append(changes, mb.ChangeCounts())
205 if mb.KeywordsChanged(origmb) {
206 changes = append(changes, mb.ChangeKeywords())
210 err = acc.RetrainMessages(ctx, log, tx, retrain)
211 x.Checkf(ctx, err, "retraining messages")
214 store.BroadcastChanges(acc, changes)
218func (x XOps) MessageFlagsClear(ctx context.Context, log mlog.Log, acc *store.Account, messageIDs []int64, flaglist []string) {
219 flags, keywords, err := store.ParseFlagsKeywords(flaglist)
220 x.Checkuserf(ctx, err, "parsing flags")
222 acc.WithRLock(func() {
223 var retrain []store.Message
224 var changes []store.Change
226 x.DBWrite(ctx, acc, func(tx *bstore.Tx) {
227 var modseq store.ModSeq
228 var mb, origmb store.Mailbox
230 for _, mid := range messageIDs {
231 m := x.messageID(ctx, tx, mid)
234 modseq, err = acc.NextModSeq(tx)
235 x.Checkf(ctx, err, "assigning next modseq")
238 if mb.ID != m.MailboxID {
241 err := tx.Update(&mb)
242 x.Checkf(ctx, err, "updating counts for mailbox")
243 if mb.MailboxCounts != origmb.MailboxCounts {
244 changes = append(changes, mb.ChangeCounts())
246 // note: cannot remove keywords from mailbox by removing keywords from message.
248 mb = x.mailboxID(ctx, tx, m.MailboxID)
253 mb.Sub(m.MailboxCounts())
254 m.Flags = m.Flags.Set(flags, store.Flags{})
256 m.Keywords, changed = store.RemoveKeywords(m.Keywords, keywords)
257 mb.Add(m.MailboxCounts())
259 if m.Flags == oflags && !changed {
265 x.Checkf(ctx, err, "updating message")
267 changes = append(changes, m.ChangeFlags(oflags, mb))
268 retrain = append(retrain, m)
273 err := tx.Update(&mb)
274 x.Checkf(ctx, err, "updating keywords in mailbox")
275 if mb.MailboxCounts != origmb.MailboxCounts {
276 changes = append(changes, mb.ChangeCounts())
278 // note: cannot remove keywords from mailbox by removing keywords from message.
281 err = acc.RetrainMessages(ctx, log, tx, retrain)
282 x.Checkf(ctx, err, "retraining messages")
285 store.BroadcastChanges(acc, changes)
289// MailboxesMarkRead updates all messages in the referenced mailboxes as seen when
290// they aren't yet. The mailboxes are updated with their unread messages counts,
291// and the changes are propagated.
292func (x XOps) MailboxesMarkRead(ctx context.Context, log mlog.Log, acc *store.Account, mailboxIDs []int64) {
293 acc.WithRLock(func() {
294 var changes []store.Change
296 x.DBWrite(ctx, acc, func(tx *bstore.Tx) {
297 var modseq store.ModSeq
299 // Note: we don't need to retrain, changing the "seen" flag is not relevant.
301 for _, mbID := range mailboxIDs {
302 mb := x.mailboxID(ctx, tx, mbID)
304 // Find messages to update.
305 q := bstore.QueryTx[store.Message](tx)
306 q.FilterNonzero(store.Message{MailboxID: mb.ID})
307 q.FilterEqual("Seen", false)
308 q.FilterEqual("Expunged", false)
311 err := q.ForEach(func(m store.Message) error {
312 have = true // We need to update mailbox.
315 mb.Sub(m.MailboxCounts())
317 mb.Add(m.MailboxCounts())
321 modseq, err = acc.NextModSeq(tx)
322 x.Checkf(ctx, err, "assigning next modseq")
326 x.Checkf(ctx, err, "updating message")
328 changes = append(changes, m.ChangeFlags(oflags, mb))
331 x.Checkf(ctx, err, "listing messages to mark as read")
335 err := tx.Update(&mb)
336 x.Checkf(ctx, err, "updating mailbox")
337 changes = append(changes, mb.ChangeCounts())
342 store.BroadcastChanges(acc, changes)
346// MessageMove moves messages to the mailbox represented by mailboxName, or to mailboxID if mailboxName is empty.
348// If markSeen is true, the messages are marked as seen.
349func (x XOps) MessageMove(ctx context.Context, log mlog.Log, acc *store.Account, messageIDs []int64, mailboxName string, mailboxID int64, markSeen bool) {
350 acc.WithWLock(func() {
351 var changes []store.Change
355 for _, id := range newIDs {
356 p := acc.MessagePath(id)
358 log.Check(err, "removing delivered message after failure", slog.String("path", p))
362 x.DBWrite(ctx, acc, func(tx *bstore.Tx) {
363 if mailboxName != "" {
364 mb, err := acc.MailboxFind(tx, mailboxName)
365 x.Checkf(ctx, err, "looking up mailbox name")
367 x.Checkuserf(ctx, errors.New("not found"), "looking up mailbox name")
373 mbDst := x.mailboxID(ctx, tx, mailboxID)
375 if len(messageIDs) == 0 {
379 var modseq store.ModSeq
380 newIDs, changes = x.MessageMoveTx(ctx, log, acc, tx, messageIDs, mbDst, &modseq, markSeen)
384 store.BroadcastChanges(acc, changes)
388// MessageMoveTx moves message to a new mailbox, which must be different than their
389// current mailbox. Moving a message is done by changing the MailboxID and
390// assigning an appropriate new UID, and then inserting a replacement Message record
391// with new ID that is marked expunged in the original mailbox, along with a
392// MessageErase record so the message gets erased when all sessions stopped
393// referencing the message.
395// If markSeen is true, the messages are marked as seen.
396func (x XOps) MessageMoveTx(ctx context.Context, log mlog.Log, acc *store.Account, tx *bstore.Tx, messageIDs []int64, mbDst store.Mailbox, modseq *store.ModSeq, markSeen bool) ([]int64, []store.Change) {
403 for _, id := range newIDs {
404 p := acc.MessagePath(id)
406 log.Check(err, "removing delivered message after failure", slog.String("path", p))
411 // n adds, 1 remove, 2 mailboxcounts, 1 mailboxkeywords, optimistic that messages are in a single source mailbox.
412 changes := make([]store.Change, 0, len(messageIDs)+4)
416 *modseq, err = acc.NextModSeq(tx)
417 x.Checkf(ctx, err, "assigning next modseq")
420 mbDst.ModSeq = *modseq
423 l := make([]store.Message, len(messageIDs))
424 for i, id := range messageIDs {
425 l[i] = x.messageID(ctx, tx, id)
426 if l[i].MailboxID == mbDst.ID {
427 // Client should filter out messages that are already in mailbox.
428 x.Checkuserf(ctx, fmt.Errorf("message %d already in destination mailbox", l[i].ID), "moving message")
432 // Sort (group) by mailbox, sort by UID.
433 sort.Slice(l, func(i, j int) bool {
434 if l[i].MailboxID != l[j].MailboxID {
435 return l[i].MailboxID < l[j].MailboxID
437 return l[i].UID < l[j].UID
443 err := jf.CloseDiscard()
444 log.Check(err, "close junk filter")
448 accConf, _ := acc.Conf()
450 var mbSrc store.Mailbox
451 var changeRemoveUIDs store.ChangeRemoveUIDs
452 xflushMailbox := func() {
453 changeRemoveUIDs.UIDNext = mbSrc.UIDNext
454 changeRemoveUIDs.MessageCountIMAP = mbSrc.MessageCountIMAP()
455 changeRemoveUIDs.Unseen = uint32(mbSrc.MailboxCounts.Unseen)
456 changes = append(changes, changeRemoveUIDs, mbSrc.ChangeCounts())
458 err = tx.Update(&mbSrc)
459 x.Checkf(ctx, err, "updating source mailbox counts")
462 nkeywords := len(mbDst.Keywords)
465 syncDirs := map[string]struct{}{}
467 for _, om := range l {
468 if om.MailboxID != mbSrc.ID {
472 mbSrc = x.mailboxID(ctx, tx, om.MailboxID)
473 mbSrc.ModSeq = *modseq
474 changeRemoveUIDs = store.ChangeRemoveUIDs{MailboxID: mbSrc.ID, ModSeq: *modseq}
478 nm.MailboxID = mbDst.ID
479 nm.UID = mbDst.UIDNext
480 err := mbDst.UIDNextAdd(1)
481 x.Checkf(ctx, err, "adding uid")
483 nm.CreateSeq = *modseq
485 if nm.IsReject && nm.MailboxDestinedID != 0 {
486 // Incorrectly delivered to Rejects mailbox. Adjust MailboxOrigID so this message
487 // is used for reputation calculation during future deliveries.
488 nm.MailboxOrigID = nm.MailboxDestinedID
496 nm.JunkFlagsForMailboxMove(mbSrc, mbDst, accConf)
499 x.Checkf(ctx, err, "updating message with new mailbox")
501 mbDst.Add(nm.MailboxCounts())
503 mbSrc.Sub(om.MailboxCounts())
509 x.Checkf(ctx, err, "inserting expunged message in old mailbox")
511 dstPath := acc.MessagePath(om.ID)
512 dstDir := filepath.Dir(dstPath)
513 if _, ok := syncDirs[dstDir]; !ok {
514 os.MkdirAll(dstDir, 0770)
515 syncDirs[dstDir] = struct{}{}
518 err = moxio.LinkOrCopy(log, dstPath, acc.MessagePath(nm.ID), nil, false)
519 x.Checkf(ctx, err, "duplicating message in old mailbox for current sessions")
520 newIDs = append(newIDs, nm.ID)
521 // We don't sync the directory. In case of a crash and files disappearing, the
522 // eraser will simply not find the file at next startup.
524 err = tx.Insert(&store.MessageErase{ID: om.ID, SkipUpdateDiskUsage: true})
525 x.Checkf(ctx, err, "insert message erase")
527 mbDst.Keywords, _ = store.MergeKeywords(mbDst.Keywords, nm.Keywords)
529 if accConf.JunkFilter != nil && nm.NeedsTraining() {
530 // Lazily open junk filter.
532 jf, _, err = acc.OpenJunkFilter(ctx, log)
533 x.Checkf(ctx, err, "open junk filter")
535 err := acc.RetrainMessage(ctx, log, tx, jf, &nm)
536 x.Checkf(ctx, err, "retrain message after moving")
539 changeRemoveUIDs.UIDs = append(changeRemoveUIDs.UIDs, om.UID)
540 changeRemoveUIDs.MsgIDs = append(changeRemoveUIDs.MsgIDs, om.ID)
541 changes = append(changes, nm.ChangeAddUID(mbDst))
544 for dir := range syncDirs {
545 err := moxio.SyncDir(log, dir)
546 x.Checkf(ctx, err, "sync directory")
551 changes = append(changes, mbDst.ChangeCounts())
552 if nkeywords > len(mbDst.Keywords) {
553 changes = append(changes, mbDst.ChangeKeywords())
556 err = tx.Update(&mbDst)
557 x.Checkf(ctx, err, "updating destination mailbox with uidnext and modseq")
561 x.Checkf(ctx, err, "saving junk filter")
566 return newIDs, changes
569func isText(p message.Part) bool {
570 return p.MediaType == "" && p.MediaSubType == "" || p.MediaType == "TEXT" && p.MediaSubType == "PLAIN"
573func isHTML(p message.Part) bool {
574 return p.MediaType == "" && p.MediaSubType == "" || p.MediaType == "TEXT" && p.MediaSubType == "HTML"
577func isAlternative(p message.Part) bool {
578 return p.MediaType == "MULTIPART" && p.MediaSubType == "ALTERNATIVE"
581func readPart(p message.Part, maxSize int64) (string, error) {
582 buf, err := io.ReadAll(io.LimitReader(p.ReaderUTF8OrBinary(), maxSize))
584 return "", fmt.Errorf("reading part contents: %v", err)
586 return string(buf), nil
589// ReadableParts returns the contents of the first text and/or html parts,
590// descending into multiparts, truncated to maxSize bytes if longer.
591func ReadableParts(p message.Part, maxSize int64) (text string, html string, found bool, err error) {
592 // todo: may want to merge this logic with webmail's message parsing.
594 // For non-multipart messages, top-level part.
596 data, err := readPart(p, maxSize)
597 return data, "", true, err
598 } else if isHTML(p) {
599 data, err := readPart(p, maxSize)
600 return "", data, true, err
603 // Look in sub-parts. Stop when we have a readable part, don't continue with other
604 // subparts unless we have a multipart/alternative.
605 // todo: we may have to look at disposition "inline".
606 var haveText, haveHTML bool
607 for _, pp := range p.Parts {
610 text, err = readPart(pp, maxSize)
611 if !isAlternative(p) {
614 } else if isHTML(pp) {
616 html, err = readPart(pp, maxSize)
617 if !isAlternative(p) {
622 if haveText || haveHTML {
623 return text, html, true, err
626 // Descend into the subparts.
627 for _, pp := range p.Parts {
628 text, html, found, err = ReadableParts(pp, maxSize)