1// Package webaccount provides a web app for users to view and change their account
2// settings, and to import/export email.
3package webaccount
4
5import (
6 "bytes"
7 "context"
8 cryptorand "crypto/rand"
9 "encoding/base64"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "log/slog"
15 "net/http"
16 "net/url"
17 "os"
18 "path/filepath"
19 "strings"
20 "time"
21
22 _ "embed"
23
24 "github.com/mjl-/bstore"
25 "github.com/mjl-/sherpa"
26 "github.com/mjl-/sherpadoc"
27 "github.com/mjl-/sherpaprom"
28
29 "github.com/mjl-/mox/config"
30 "github.com/mjl-/mox/mlog"
31 "github.com/mjl-/mox/mox-"
32 "github.com/mjl-/mox/moxvar"
33 "github.com/mjl-/mox/queue"
34 "github.com/mjl-/mox/smtp"
35 "github.com/mjl-/mox/store"
36 "github.com/mjl-/mox/webapi"
37 "github.com/mjl-/mox/webauth"
38 "github.com/mjl-/mox/webhook"
39 "github.com/mjl-/mox/webops"
40)
41
42var pkglog = mlog.New("webaccount", nil)
43
44//go:embed api.json
45var accountapiJSON []byte
46
47//go:embed account.html
48var accountHTML []byte
49
50//go:embed account.js
51var accountJS []byte
52
53var webaccountFile = &mox.WebappFile{
54 HTML: accountHTML,
55 JS: accountJS,
56 HTMLPath: filepath.FromSlash("webaccount/account.html"),
57 JSPath: filepath.FromSlash("webaccount/account.js"),
58}
59
60var accountDoc = mustParseAPI("account", accountapiJSON)
61
62func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
63 err := json.Unmarshal(buf, &doc)
64 if err != nil {
65 pkglog.Fatalx("parsing webaccount api docs", err, slog.String("api", api))
66 }
67 return doc
68}
69
70var sherpaHandlerOpts *sherpa.HandlerOpts
71
72func makeSherpaHandler(cookiePath string, isForwarded bool) (http.Handler, error) {
73 return sherpa.NewHandler("/api/", moxvar.Version, Account{cookiePath, isForwarded}, &accountDoc, sherpaHandlerOpts)
74}
75
76func init() {
77 collector, err := sherpaprom.NewCollector("moxaccount", nil)
78 if err != nil {
79 pkglog.Fatalx("creating sherpa prometheus collector", err)
80 }
81
82 sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
83 // Just to validate.
84 _, err = makeSherpaHandler("", false)
85 if err != nil {
86 pkglog.Fatalx("sherpa handler", err)
87 }
88
89 mox.NewWebaccountHandler = func(basePath string, isForwarded bool) http.Handler {
90 return http.HandlerFunc(Handler(basePath, isForwarded))
91 }
92}
93
94// Handler returns a handler for the webaccount endpoints, customized for the
95// cookiePath.
96func Handler(cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
97 sh, err := makeSherpaHandler(cookiePath, isForwarded)
98 return func(w http.ResponseWriter, r *http.Request) {
99 if err != nil {
100 http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
101 return
102 }
103 handle(sh, isForwarded, w, r)
104 }
105}
106
107func xcheckf(ctx context.Context, err error, format string, args ...any) {
108 if err == nil {
109 return
110 }
111 // If caller tried saving a config that is invalid, or because of a bad request, cause a user error.
112 if errors.Is(err, mox.ErrConfig) || errors.Is(err, mox.ErrRequest) {
113 xcheckuserf(ctx, err, format, args...)
114 }
115
116 msg := fmt.Sprintf(format, args...)
117 errmsg := fmt.Sprintf("%s: %s", msg, err)
118 pkglog.WithContext(ctx).Errorx(msg, err)
119 code := "server:error"
120 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
121 code = "user:error"
122 }
123 panic(&sherpa.Error{Code: code, Message: errmsg})
124}
125
126func xcheckuserf(ctx context.Context, err error, format string, args ...any) {
127 if err == nil {
128 return
129 }
130 msg := fmt.Sprintf(format, args...)
131 errmsg := fmt.Sprintf("%s: %s", msg, err)
132 pkglog.WithContext(ctx).Errorx(msg, err)
133 panic(&sherpa.Error{Code: "user:error", Message: errmsg})
134}
135
136// Account exports web API functions for the account web interface. All its
137// methods are exported under api/. Function calls require valid HTTP
138// Authentication credentials of a user.
139type Account struct {
140 cookiePath string // From listener, for setting authentication cookies.
141 isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
142}
143
144func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
145 ctx := context.WithValue(r.Context(), mlog.CidKey, mox.Cid())
146 log := pkglog.WithContext(ctx).With(slog.String("userauth", ""))
147
148 // Without authentication. The token is unguessable.
149 if r.URL.Path == "/importprogress" {
150 if r.Method != "GET" {
151 http.Error(w, "405 - method not allowed - get required", http.StatusMethodNotAllowed)
152 return
153 }
154
155 q := r.URL.Query()
156 token := q.Get("token")
157 if token == "" {
158 http.Error(w, "400 - bad request - missing token", http.StatusBadRequest)
159 return
160 }
161
162 flusher, ok := w.(http.Flusher)
163 if !ok {
164 log.Error("internal error: ResponseWriter not a http.Flusher")
165 http.Error(w, "500 - internal error - cannot access underlying connection", 500)
166 return
167 }
168
169 l := importListener{token, make(chan importEvent, 100), make(chan bool, 1)}
170 importers.Register <- &l
171 ok = <-l.Register
172 if !ok {
173 http.Error(w, "400 - bad request - unknown token, import may have finished more than a minute ago", http.StatusBadRequest)
174 return
175 }
176 defer func() {
177 importers.Unregister <- &l
178 }()
179
180 h := w.Header()
181 h.Set("Content-Type", "text/event-stream")
182 h.Set("Cache-Control", "no-cache")
183 _, err := w.Write([]byte(": keepalive\n\n"))
184 if err != nil {
185 return
186 }
187 flusher.Flush()
188
189 cctx := r.Context()
190 for {
191 select {
192 case e := <-l.Events:
193 _, err := w.Write(e.SSEMsg)
194 flusher.Flush()
195 if err != nil {
196 return
197 }
198
199 case <-cctx.Done():
200 return
201 }
202 }
203 }
204
205 // HTML/JS can be retrieved without authentication.
206 if r.URL.Path == "/" {
207 switch r.Method {
208 case "GET", "HEAD":
209 webaccountFile.Serve(ctx, log, w, r)
210 default:
211 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
212 }
213 return
214 }
215
216 isAPI := strings.HasPrefix(r.URL.Path, "/api/")
217 // Only allow POST for calls, they will not work cross-domain without CORS.
218 if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
219 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
220 return
221 }
222
223 var loginAddress, accName string
224 var sessionToken store.SessionToken
225 // All other URLs, except the login endpoint require some authentication.
226 if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
227 var ok bool
228 isExport := r.URL.Path == "/export"
229 requireCSRF := isAPI || r.URL.Path == "/import" || isExport
230 accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webaccount", isForwarded, w, r, isAPI, requireCSRF, isExport)
231 if !ok {
232 // Response has been written already.
233 return
234 }
235 }
236
237 if isAPI {
238 reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
239 ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
240 apiHandler.ServeHTTP(w, r.WithContext(ctx))
241 return
242 }
243
244 switch r.URL.Path {
245 case "/export":
246 webops.Export(log, accName, w, r)
247
248 case "/import":
249 if r.Method != "POST" {
250 http.Error(w, "405 - method not allowed - post required", http.StatusMethodNotAllowed)
251 return
252 }
253
254 f, _, err := r.FormFile("file")
255 if err != nil {
256 if errors.Is(err, http.ErrMissingFile) {
257 http.Error(w, "400 - bad request - missing file", http.StatusBadRequest)
258 } else {
259 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
260 }
261 return
262 }
263 defer func() {
264 err := f.Close()
265 log.Check(err, "closing form file")
266 }()
267 skipMailboxPrefix := r.FormValue("skipMailboxPrefix")
268 tmpf, err := os.CreateTemp("", "mox-import")
269 if err != nil {
270 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
271 return
272 }
273 defer func() {
274 if tmpf != nil {
275 store.CloseRemoveTempFile(log, tmpf, "upload")
276 }
277 }()
278 if _, err := io.Copy(tmpf, f); err != nil {
279 log.Errorx("copying import to temporary file", err)
280 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
281 return
282 }
283 token, isUserError, err := importStart(log, accName, tmpf, skipMailboxPrefix)
284 if err != nil {
285 log.Errorx("starting import", err, slog.Bool("usererror", isUserError))
286 if isUserError {
287 http.Error(w, "400 - bad request - "+err.Error(), http.StatusBadRequest)
288 } else {
289 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
290 }
291 return
292 }
293 tmpf = nil // importStart is now responsible for cleanup.
294
295 w.Header().Set("Content-Type", "application/json")
296 _ = json.NewEncoder(w).Encode(ImportProgress{Token: token})
297
298 default:
299 http.NotFound(w, r)
300 }
301}
302
303// ImportProgress is returned after uploading a file to import.
304type ImportProgress struct {
305 // For fetching progress, or cancelling an import.
306 Token string
307}
308
309type ctxKey string
310
311var requestInfoCtxKey ctxKey = "requestInfo"
312
313type requestInfo struct {
314 LoginAddress string
315 AccountName string
316 SessionToken store.SessionToken
317 Response http.ResponseWriter
318 Request *http.Request // For Proto and TLS connection state during message submit.
319}
320
321// LoginPrep returns a login token, and also sets it as cookie. Both must be
322// present in the call to Login.
323func (w Account) LoginPrep(ctx context.Context) string {
324 log := pkglog.WithContext(ctx)
325 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
326
327 var data [8]byte
328 _, err := cryptorand.Read(data[:])
329 xcheckf(ctx, err, "generate token")
330 loginToken := base64.RawURLEncoding.EncodeToString(data[:])
331
332 webauth.LoginPrep(ctx, log, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
333
334 return loginToken
335}
336
337// Login returns a session token for the credentials, or fails with error code
338// "user:badLogin". Call LoginPrep to get a loginToken.
339func (w Account) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
340 log := pkglog.WithContext(ctx)
341 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
342
343 csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
344 if _, ok := err.(*sherpa.Error); ok {
345 panic(err)
346 }
347 xcheckf(ctx, err, "login")
348 return csrfToken
349}
350
351// Logout invalidates the session token.
352func (w Account) Logout(ctx context.Context) {
353 log := pkglog.WithContext(ctx)
354 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
355
356 err := webauth.Logout(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.AccountName, reqInfo.SessionToken)
357 xcheckf(ctx, err, "logout")
358}
359
360// SetPassword saves a new password for the account, invalidating the previous password.
361// Sessions are not interrupted, and will keep working. New login attempts must use the new password.
362// Password must be at least 8 characters.
363func (Account) SetPassword(ctx context.Context, password string) {
364 log := pkglog.WithContext(ctx)
365 if len(password) < 8 {
366 panic(&sherpa.Error{Code: "user:error", Message: "password must be at least 8 characters"})
367 }
368
369 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
370 acc, err := store.OpenAccount(log, reqInfo.AccountName)
371 xcheckf(ctx, err, "open account")
372 defer func() {
373 err := acc.Close()
374 log.Check(err, "closing account")
375 }()
376
377 // Retrieve session, resetting password invalidates it.
378 ls, err := store.SessionUse(ctx, log, reqInfo.AccountName, reqInfo.SessionToken, "")
379 xcheckf(ctx, err, "get session")
380
381 err = acc.SetPassword(log, password)
382 xcheckf(ctx, err, "setting password")
383
384 // Session has been invalidated. Add it again.
385 err = store.SessionAddToken(ctx, log, &ls)
386 xcheckf(ctx, err, "restoring session after password reset")
387}
388
389// Account returns information about the account.
390// StorageUsed is the sum of the sizes of all messages, in bytes.
391// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
392func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64, suppressions []webapi.Suppression) {
393 log := pkglog.WithContext(ctx)
394 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
395
396 acc, err := store.OpenAccount(log, reqInfo.AccountName)
397 xcheckf(ctx, err, "open account")
398 defer func() {
399 err := acc.Close()
400 log.Check(err, "closing account")
401 }()
402
403 var accConf config.Account
404 acc.WithRLock(func() {
405 accConf, _ = acc.Conf()
406
407 storageLimit = acc.QuotaMessageSize()
408 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
409 du := store.DiskUsage{ID: 1}
410 err := tx.Get(&du)
411 storageUsed = du.MessageSize
412 return err
413 })
414 xcheckf(ctx, err, "get disk usage")
415 })
416
417 suppressions, err = queue.SuppressionList(ctx, reqInfo.AccountName)
418 xcheckf(ctx, err, "list suppressions")
419
420 return accConf, storageUsed, storageLimit, suppressions
421}
422
423// AccountSaveFullName saves the full name (used as display name in email messages)
424// for the account.
425func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
426 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
427 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
428 acc.FullName = fullName
429 })
430 xcheckf(ctx, err, "saving account full name")
431}
432
433// DestinationSave updates a destination.
434// OldDest is compared against the current destination. If it does not match, an
435// error is returned. Otherwise newDest is saved and the configuration reloaded.
436func (Account) DestinationSave(ctx context.Context, destName string, oldDest, newDest config.Destination) {
437 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
438
439 err := mox.AccountSave(ctx, reqInfo.AccountName, func(conf *config.Account) {
440 curDest, ok := conf.Destinations[destName]
441 if !ok {
442 xcheckuserf(ctx, errors.New("not found"), "looking up destination")
443 }
444 if !curDest.Equal(oldDest) {
445 xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
446 }
447
448 // Keep fields we manage.
449 newDest.DMARCReports = curDest.DMARCReports
450 newDest.HostTLSReports = curDest.HostTLSReports
451 newDest.DomainTLSReports = curDest.DomainTLSReports
452
453 // Make copy of reference values.
454 nd := map[string]config.Destination{}
455 for dn, d := range conf.Destinations {
456 nd[dn] = d
457 }
458 nd[destName] = newDest
459 conf.Destinations = nd
460 })
461 xcheckf(ctx, err, "saving destination")
462}
463
464// ImportAbort aborts an import that is in progress. If the import exists and isn't
465// finished, no changes will have been made by the import.
466func (Account) ImportAbort(ctx context.Context, importToken string) error {
467 req := importAbortRequest{importToken, make(chan error)}
468 importers.Abort <- req
469 return <-req.Response
470}
471
472// Types exposes types not used in API method signatures, such as the import form upload.
473func (Account) Types() (importProgress ImportProgress) {
474 return
475}
476
477// SuppressionList lists the addresses on the suppression list of this account.
478func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
479 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
480 l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
481 xcheckf(ctx, err, "list suppressions")
482 return l
483}
484
485// SuppressionAdd adds an email address to the suppression list.
486func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
487 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
488 addr, err := smtp.ParseAddress(address)
489 xcheckuserf(ctx, err, "parsing address")
490 sup := webapi.Suppression{
491 Account: reqInfo.AccountName,
492 Manual: manual,
493 Reason: reason,
494 }
495 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
496 if err != nil && errors.Is(err, bstore.ErrUnique) {
497 xcheckuserf(ctx, err, "add suppression")
498 }
499 xcheckf(ctx, err, "add suppression")
500 return sup
501}
502
503// SuppressionRemove removes the email address from the suppression list.
504func (Account) SuppressionRemove(ctx context.Context, address string) {
505 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
506 addr, err := smtp.ParseAddress(address)
507 xcheckuserf(ctx, err, "parsing address")
508 err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
509 if err != nil && err == bstore.ErrAbsent {
510 xcheckuserf(ctx, err, "remove suppression")
511 }
512 xcheckf(ctx, err, "remove suppression")
513}
514
515// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
516// is empty, the webhook is disabled. If authorization is non-empty it is used for
517// the Authorization header in HTTP requests. Events specifies the outgoing events
518// to be delivered, or all if empty/nil.
519func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
520 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
521 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
522 if url == "" {
523 acc.OutgoingWebhook = nil
524 } else {
525 acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
526 }
527 })
528 xcheckf(ctx, err, "saving account outgoing webhook")
529}
530
531// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
532// authorization. If the HTTP request is made this call will succeed also for
533// non-2xx HTTP status codes.
534func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
535 log := pkglog.WithContext(ctx)
536
537 xvalidURL(ctx, urlStr)
538 log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
539
540 var b bytes.Buffer
541 enc := json.NewEncoder(&b)
542 enc.SetIndent("", "\t")
543 enc.SetEscapeHTML(false)
544 err := enc.Encode(data)
545 xcheckf(ctx, err, "encoding outgoing webhook data")
546
547 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
548 if err != nil {
549 errmsg = err.Error()
550 }
551 log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
552 return code, response, errmsg
553}
554
555// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
556// empty, the webhook is disabled. If authorization is not empty, it is used in
557// the Authorization header in requests.
558func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
559 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
560 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
561 if url == "" {
562 acc.IncomingWebhook = nil
563 } else {
564 acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
565 }
566 })
567 xcheckf(ctx, err, "saving account incoming webhook")
568}
569
570func xvalidURL(ctx context.Context, s string) {
571 u, err := url.Parse(s)
572 xcheckuserf(ctx, err, "parsing url")
573 if u.Scheme != "http" && u.Scheme != "https" {
574 xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
575 }
576}
577
578// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
579// with optional authorization header. If the HTTP call is made, this function
580// returns non-error regardless of HTTP status code.
581func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
582 log := pkglog.WithContext(ctx)
583
584 xvalidURL(ctx, urlStr)
585 log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
586
587 var b bytes.Buffer
588 enc := json.NewEncoder(&b)
589 enc.SetEscapeHTML(false)
590 enc.SetIndent("", "\t")
591 err := enc.Encode(data)
592 xcheckf(ctx, err, "encoding incoming webhook data")
593 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
594 if err != nil {
595 errmsg = err.Error()
596 }
597 log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
598 return code, response, errmsg
599}
600
601// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
602// MAIL FROM addresses ("fromid") for deliveries from the queue.
603func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
604 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
605 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
606 acc.FromIDLoginAddresses = loginAddresses
607 })
608 xcheckf(ctx, err, "saving account fromid login addresses")
609}
610
611// KeepRetiredPeriodsSave saves periods to save retired messages and webhooks.
612func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
613 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
614 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
615 acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
616 acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
617 })
618 xcheckf(ctx, err, "saving account keep retired periods")
619}
620
621// AutomaticJunkFlagsSave saves settings for automatically marking messages as
622// junk/nonjunk when moved to mailboxes matching certain regular expressions.
623func (Account) AutomaticJunkFlagsSave(ctx context.Context, enabled bool, junkRegexp, neutralRegexp, notJunkRegexp string) {
624 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
625 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
626 acc.AutomaticJunkFlags = config.AutomaticJunkFlags{
627 Enabled: enabled,
628 JunkMailboxRegexp: junkRegexp,
629 NeutralMailboxRegexp: neutralRegexp,
630 NotJunkMailboxRegexp: notJunkRegexp,
631 }
632 })
633 xcheckf(ctx, err, "saving account automatic junk flags")
634}
635
636// JunkFilterSave saves junk filter settings. If junkFilter is nil, the junk filter
637// is disabled. Otherwise all fields except Threegrams are stored.
638func (Account) JunkFilterSave(ctx context.Context, junkFilter *config.JunkFilter) {
639 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
640 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
641 if junkFilter == nil {
642 acc.JunkFilter = nil
643 return
644 }
645 old := acc.JunkFilter
646 acc.JunkFilter = junkFilter
647 acc.JunkFilter.Params.Threegrams = false
648 if old != nil {
649 acc.JunkFilter.Params.Threegrams = old.Params.Threegrams
650 }
651 })
652 xcheckf(ctx, err, "saving account junk filter settings")
653}
654
655// RejectsSave saves the RejectsMailbox and KeepRejects settings.
656func (Account) RejectsSave(ctx context.Context, mailbox string, keep bool) {
657 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
658 err := mox.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
659 acc.RejectsMailbox = mailbox
660 acc.KeepRejects = keep
661 })
662 xcheckf(ctx, err, "saving account rejects settings")
663}
664