Debian Codegraph @

app/account-wizard.go

raw
1 package app
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "net/url"
8 "os"
9 "os/exec"
10 "regexp"
11 "strings"
12 "sync"
13 "time"
14
15 "github.com/emersion/go-message/mail"
16 "github.com/go-ini/ini"
17 "golang.org/x/sys/unix"
18
19 "git.sr.ht/~rjarry/aerc/config"
20 "git.sr.ht/~rjarry/aerc/lib/autoconfig"
21 "git.sr.ht/~rjarry/aerc/lib/format"
22 "git.sr.ht/~rjarry/aerc/lib/log"
23 "git.sr.ht/~rjarry/aerc/lib/ui"
24 "git.sr.ht/~rjarry/aerc/lib/xdg"
25 "go.rockorager.dev/vaxis"
26 )
27
28 const (
29 CONFIGURE_BASICS = iota
30 CONFIGURE_SOURCE = iota
31 CONFIGURE_OUTGOING = iota
32 CONFIGURE_COMPLETE = iota
33 )
34
35 type AccountWizard struct {
36 step int
37 steps []*ui.Grid
38 focus int
39 temporary bool
40 // CONFIGURE_BASICS
41 accountName *ui.TextInput
42 email *ui.TextInput
43 discovered *autoconfig.Config
44 discoveredFor string
45 fullName *ui.TextInput
46 basics []ui.Interactive
47 spinner *ui.Text
48 // CONFIGURE_SOURCE
49 sourceProtocol *Selector
50 sourceTransport *Selector
51
52 sourceUsername *ui.TextInput
53 sourcePassword *ui.TextInput
54 sourceServer *ui.TextInput
55 sourceStr *ui.Text
56 sourceUrl url.URL
57 source []ui.Interactive
58 // CONFIGURE_OUTGOING
59 outgoingProtocol *Selector
60 outgoingTransport *Selector
61
62 outgoingUsername *ui.TextInput
63 outgoingPassword *ui.TextInput
64 outgoingServer *ui.TextInput
65 outgoingStr *ui.Text
66 outgoingUrl url.URL
67 outgoingCopyTo *ui.TextInput
68 outgoing []ui.Interactive
69 // CONFIGURE_COMPLETE
70 complete []ui.Interactive
71 }
72
73 func showPasswordWarning() {
74 accountConfig := xdg.TildeHome(xdg.ConfigPath("aerc", "accounts.conf"))
75 title := "ATTENTION"
76 text := `
77 The Wizard will store your passwords as clear text in:
78
79 %s
80
81 It is recommended to remove the clear text passwords and configure
82 'source-cred-cmd' and 'outgoing-cred-cmd' using your own password store
83 after the setup.
84 `
85 warning := NewSelectorDialog(
86 title, fmt.Sprintf(text, accountConfig), []string{"OK"}, 0,
87 SelectedAccountUiConfig(),
88 func(_ string, _ error) {
89 CloseDialog()
90 },
91 )
92 AddDialog(warning)
93 }
94
95 type configStep struct {
96 introduction string
97 labels []string
98 fields []ui.Drawable
99 interactive *[]ui.Interactive
100 }
101
102 func NewConfigStep(intro string, interactive *[]ui.Interactive) configStep {
103 return configStep{introduction: intro, interactive: interactive}
104 }
105
106 func (s *configStep) AddField(label string, field ui.Drawable) {
107 s.labels = append(s.labels, label)
108 s.fields = append(s.fields, field)
109 if i, ok := field.(ui.Interactive); ok {
110 *s.interactive = append(*s.interactive, i)
111 }
112 }
113
114 func (s *configStep) Grid() *ui.Grid {
115 introduction := strings.TrimSpace(s.introduction)
116 h := strings.Count(introduction, "\n") + 1
117 spec := []ui.GridSpec{
118 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)}, // padding
119 {Strategy: ui.SIZE_EXACT, Size: ui.Const(h)}, // intro text
120 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)}, // padding
121 }
122 for range s.fields {
123 spec = append(spec, []ui.GridSpec{
124 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)}, // label
125 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)}, // field
126 {Strategy: ui.SIZE_EXACT, Size: ui.Const(1)}, // padding
127 }...)
128 }
129 justify := ui.GridSpec{Strategy: ui.SIZE_WEIGHT, Size: ui.Const(1)}
130 spec = append(spec, justify)
131 grid := ui.NewGrid().Rows(spec).Columns([]ui.GridSpec{justify})
132
133 intro := ui.NewText(introduction, config.Ui().GetStyle(config.STYLE_DEFAULT))
134 fill := ui.NewFill(' ', vaxis.Style{})
135
136 grid.AddChild(fill).At(0, 0)
137 grid.AddChild(intro).At(1, 0)
138 grid.AddChild(fill).At(2, 0)
139
140 row := 3
141 for i, field := range s.fields {
142 label := ui.NewText(s.labels[i], config.Ui().GetStyle(config.STYLE_HEADER))
143 grid.AddChild(label).At(row, 0)
144 grid.AddChild(field).At(row+1, 0)
145 grid.AddChild(fill).At(row+2, 0)
146 row += 3
147 }
148
149 grid.AddChild(fill).At(row, 0)
150
151 return grid
152 }
153
154 const (
155 // protocols
156 IMAP = "IMAP"
157 JMAP = "JMAP"
158 MAILDIR = "Maildir"
159 MAILDIRPP = "Maildir++"
160 NOTMUCH = "notmuch"
161 SMTP = "SMTP"
162 SENDMAIL = "sendmail"
163 // transports
164 SSL_TLS = "SSL/TLS"
165 OAUTH = "SSL/TLS+OAUTHBEARER"
166 XOAUTH = "SSL/TLS+XOAUTH2"
167 STARTTLS = "STARTTLS"
168 INSECURE = "Insecure"
169 )
170
171 var (
172 sources = []string{IMAP, JMAP, MAILDIR, MAILDIRPP, NOTMUCH}
173 outgoings = []string{SMTP, JMAP, SENDMAIL}
174 transports = []string{SSL_TLS, OAUTH, XOAUTH, STARTTLS, INSECURE}
175 )
176
177 func NewAccountWizard() *AccountWizard {
178 wizard := &AccountWizard{
179 accountName: ui.NewTextInput("", config.Ui()).Prompt("> "),
180 temporary: false,
181 email: ui.NewTextInput("", config.Ui()).Prompt("> "),
182 fullName: ui.NewTextInput("", config.Ui()).Prompt("> "),
183 spinner: ui.NewText("", config.Ui().GetStyle(config.STYLE_DEFAULT)),
184 sourcePassword: ui.NewTextInput("", config.Ui()).Prompt("] ").Password(true),
185 sourceServer: ui.NewTextInput("", config.Ui()).Prompt("> "),
186 sourceStr: ui.NewText("", config.Ui().GetStyle(config.STYLE_DEFAULT)),
187 sourceUsername: ui.NewTextInput("", config.Ui()).Prompt("> "),
188 outgoingPassword: ui.NewTextInput("", config.Ui()).Prompt("] ").Password(true),
189 outgoingServer: ui.NewTextInput("", config.Ui()).Prompt("> "),
190 outgoingStr: ui.NewText("", config.Ui().GetStyle(config.STYLE_DEFAULT)),
191 outgoingUsername: ui.NewTextInput("", config.Ui()).Prompt("> "),
192 outgoingCopyTo: ui.NewTextInput("", config.Ui()).Prompt("> "),
193
194 sourceProtocol: NewSelector(sources, 0, config.Ui()).Chooser(true),
195 sourceTransport: NewSelector(transports, 0, config.Ui()).Chooser(true),
196 outgoingProtocol: NewSelector(outgoings, 0, config.Ui()).Chooser(true),
197 outgoingTransport: NewSelector(transports, 0, config.Ui()).Chooser(true),
198 }
199
200 // Autofill some stuff for the user
201 wizard.email.OnFocusLost(func(_ *ui.TextInput) {
202 value := wizard.email.String()
203 if wizard.sourceUsername.String() == "" {
204 wizard.sourceUsername.Set(value)
205 }
206 if wizard.outgoingUsername.String() == "" {
207 wizard.outgoingUsername.Set(value)
208 }
209 wizard.sourceUri()
210 wizard.outgoingUri()
211 })
212 wizard.sourceProtocol.OnSelect(func(option string) {
213 wizard.sourceServer.Set("")
214 wizard.autofill()
215 wizard.sourceUri()
216 })
217 wizard.sourceServer.OnChange(func(_ *ui.TextInput) {
218 wizard.sourceUri()
219 })
220 wizard.sourceServer.OnFocusLost(func(_ *ui.TextInput) {
221 src := wizard.sourceServer.String()
222 out := wizard.outgoingServer.String()
223 if out == "" && strings.HasPrefix(src, "imap.") {
224 out = strings.Replace(src, "imap.", "smtp.", 1)
225 wizard.outgoingServer.Set(out)
226 }
227 wizard.outgoingUri()
228 })
229 wizard.sourceUsername.OnChange(func(_ *ui.TextInput) {
230 wizard.sourceUri()
231 })
232 wizard.sourceUsername.OnFocusLost(func(_ *ui.TextInput) {
233 if wizard.outgoingUsername.String() == "" {
234 wizard.outgoingUsername.Set(wizard.sourceUsername.String())
235 wizard.outgoingUri()
236 }
237 })
238 wizard.sourceTransport.OnSelect(func(option string) {
239 wizard.sourceUri()
240 })
241 var once sync.Once
242 wizard.sourcePassword.OnChange(func(_ *ui.TextInput) {
243 wizard.outgoingPassword.Set(wizard.sourcePassword.String())
244 wizard.sourceUri()
245 wizard.outgoingUri()
246 })
247 wizard.sourcePassword.OnFocusLost(func(_ *ui.TextInput) {
248 if wizard.sourcePassword.String() != "" {
249 once.Do(func() {
250 showPasswordWarning()
251 })
252 }
253 })
254 wizard.outgoingProtocol.OnSelect(func(option string) {
255 wizard.outgoingServer.Set("")
256 wizard.autofill()
257 wizard.outgoingUri()
258 })
259 wizard.outgoingServer.OnChange(func(_ *ui.TextInput) {
260 wizard.outgoingUri()
261 })
262 wizard.outgoingUsername.OnChange(func(_ *ui.TextInput) {
263 wizard.outgoingUri()
264 })
265 wizard.outgoingPassword.OnChange(func(_ *ui.TextInput) {
266 if wizard.outgoingPassword.String() != "" {
267 once.Do(func() {
268 showPasswordWarning()
269 })
270 }
271 wizard.outgoingUri()
272 })
273 wizard.outgoingTransport.OnSelect(func(option string) {
274 wizard.outgoingUri()
275 })
276
277 // CONFIGURE_BASICS
278 basics := NewConfigStep(
279 `
280 Welcome to aerc! Let's configure your account.
281
282 Key bindings:
283
284 <Tab>, <Down> or <Ctrl+j> Next field
285 <Shift+Tab>, <Up> or <Ctrl+k> Previous field
286 <Ctrl+x> Ex command
287 <Ctrl+q> Exit aerc
288 `,
289 &wizard.basics,
290 )
291 basics.AddField(
292 "Name for this account? (e.g. 'Personal' or 'Work')",
293 wizard.accountName,
294 )
295 basics.AddField(
296 "Full name for outgoing emails? (e.g. 'John Doe')",
297 wizard.fullName,
298 )
299 basics.AddField(
300 "Your email address? (e.g. '[email protected]')",
301 wizard.email,
302 )
303 basics.AddField("", NewSelector([]string{"Next"}, 0, config.Ui()).
304 OnChoose(func(option string) {
305 go func() {
306 defer log.PanicHandler()
307 wizard.discoverServices()
308 wizard.autofill()
309 wizard.sourceUri()
310 wizard.outgoingUri()
311 wizard.advance(option)
312 }()
313 }),
314 )
315 basics.AddField("", wizard.spinner)
316
317 // CONFIGURE_SOURCE
318 source := NewConfigStep("Configure email source", &wizard.source)
319 source.AddField("Protocol", wizard.sourceProtocol)
320 source.AddField("Username", wizard.sourceUsername)
321 source.AddField("Password", wizard.sourcePassword)
322 source.AddField(
323 "Server address (or path to email store or notmuch profile)",
324 wizard.sourceServer,
325 )
326 source.AddField("Transport security", wizard.sourceTransport)
327 source.AddField("Connection URL", wizard.sourceStr)
328 source.AddField(
329 "", NewSelector([]string{"Previous", "Next"}, 1, config.Ui()).
330 OnChoose(wizard.advance),
331 )
332
333 // CONFIGURE_OUTGOING
334 outgoing := NewConfigStep("Configure outgoing mail", &wizard.outgoing)
335 outgoing.AddField("Protocol", wizard.outgoingProtocol)
336 outgoing.AddField("Username", wizard.outgoingUsername)
337 outgoing.AddField("Password", wizard.outgoingPassword)
338 outgoing.AddField(
339 "Server address (or path to sendmail)",
340 wizard.outgoingServer,
341 )
342 outgoing.AddField("Transport security", wizard.outgoingTransport)
343 outgoing.AddField("Connection URL", wizard.outgoingStr)
344 outgoing.AddField(
345 "Copy sent messages to folder (leave empty to disable)",
346 wizard.outgoingCopyTo,
347 )
348 outgoing.AddField(
349 "", NewSelector([]string{"Previous", "Next"}, 1, config.Ui()).
350 OnChoose(wizard.advance),
351 )
352
353 // CONFIGURE_COMPLETE
354 complete := NewConfigStep(
355 fmt.Sprintf(`
356 Configuration complete!
357
358 You can go back and double check your settings, or choose [Finish] to
359 save your settings to %s/accounts.conf.
360
361 Make sure to review the contents of this file and read the
362 aerc-accounts(5) man page for guidance and further tweaking.
363
364 To add another account in the future, run ':new-account'.
365 `, xdg.TildeHome(xdg.ConfigPath("aerc"))),
366 &wizard.complete,
367 )
368 complete.AddField(
369 "", NewSelector([]string{
370 "Previous",
371 "Finish & open tutorial",
372 "Finish",
373 }, 1, config.Ui()).OnChoose(func(option string) {
374 switch option {
375 case "Previous":
376 wizard.advance("Previous")
377 case "Finish & open tutorial":
378 wizard.finish(true)
379 case "Finish":
380 wizard.finish(false)
381 }
382 }),
383 )
384
385 wizard.steps = []*ui.Grid{
386 basics.Grid(), source.Grid(), outgoing.Grid(), complete.Grid(),
387 }
388
389 return wizard
390 }
391
392 func (wizard *AccountWizard) ConfigureTemporaryAccount(temporary bool) {
393 wizard.temporary = temporary
394 }
395
396 func (wizard *AccountWizard) errorFor(d ui.Interactive, err error) {
397 if d == nil {
398 PushError(err.Error())
399 wizard.Invalidate()
400 return
401 }
402 for step, interactives := range [][]ui.Interactive{
403 wizard.basics,
404 wizard.source,
405 wizard.outgoing,
406 } {
407 for focus, item := range interactives {
408 if item == d {
409 wizard.Focus(false)
410 wizard.step = step
411 wizard.focus = focus
412 wizard.Focus(true)
413 PushError(err.Error())
414 wizard.Invalidate()
415 return
416 }
417 }
418 }
419 }
420
421 func (wizard *AccountWizard) finish(tutorial bool) {
422 accountsConf := xdg.ConfigPath("aerc", "accounts.conf")
423
424 // Validation
425 if wizard.accountName.String() == "" {
426 wizard.errorFor(wizard.accountName,
427 errors.New("Account name is required"))
428 return
429 }
430 if wizard.email.String() == "" {
431 wizard.errorFor(wizard.email,
432 errors.New("Email address is required"))
433 return
434 }
435 if wizard.sourceServer.String() == "" &&
436 wizard.sourceProtocol.Selected() != NOTMUCH {
437 wizard.errorFor(wizard.sourceServer,
438 errors.New("Email source configuration is required"))
439 return
440 }
441 if wizard.outgoingServer.String() == "" &&
442 wizard.outgoingProtocol.Selected() != JMAP {
443 wizard.errorFor(wizard.outgoingServer,
444 errors.New("Outgoing mail configuration is required"))
445 return
446 }
447 switch wizard.sourceProtocol.Selected() {
448 case MAILDIR, MAILDIRPP:
449 path := xdg.ExpandHome(wizard.sourceServer.String())
450 s, err := os.Stat(path)
451 if err == nil && !s.IsDir() {
452 err = fmt.Errorf("%s: Not a directory", s.Name())
453 }
454 if err == nil {
455 err = unix.Access(path, unix.X_OK)
456 }
457 if err != nil {
458 wizard.errorFor(wizard.sourceServer, err)
459 return
460 }
461 }
462 if wizard.outgoingProtocol.Selected() == SENDMAIL {
463 path := xdg.ExpandHome(wizard.outgoingServer.String())
464 s, err := os.Stat(path)
465 if err == nil && !s.Mode().IsRegular() {
466 err = fmt.Errorf("%s: Not a regular file", s.Name())
467 }
468 if err == nil {
469 err = unix.Access(path, unix.X_OK)
470 }
471 if err != nil {
472 wizard.errorFor(wizard.outgoingServer, err)
473 return
474 }
475 }
476
477 file, err := ini.Load(accountsConf)
478 if err != nil {
479 file = ini.Empty()
480 }
481
482 var sec *ini.Section
483 if sec, _ = file.GetSection(wizard.accountName.String()); sec != nil {
484 wizard.errorFor(wizard.accountName,
485 errors.New("An account by this name already exists"))
486 return
487 }
488 sec, _ = file.NewSection(wizard.accountName.String())
489 // these can't fail
490 _, _ = sec.NewKey("source", wizard.sourceUrl.String())
491 _, _ = sec.NewKey("outgoing", wizard.outgoingUrl.String())
492 _, _ = sec.NewKey("default", "INBOX")
493 from := mail.Address{
494 Name: wizard.fullName.String(),
495 Address: wizard.email.String(),
496 }
497 _, _ = sec.NewKey("from", format.AddressForHumans(&from))
498 if wizard.outgoingCopyTo.String() != "" {
499 _, _ = sec.NewKey("copy-to", wizard.outgoingCopyTo.String())
500 }
501
502 switch wizard.sourceProtocol.Selected() {
503 case IMAP:
504 _, _ = sec.NewKey("cache-headers", "true")
505 case JMAP:
506 _, _ = sec.NewKey("use-labels", "true")
507 _, _ = sec.NewKey("cache-state", "true")
508 _, _ = sec.NewKey("cache-blobs", "false")
509 case NOTMUCH:
510 querymap := ini.Empty()
511 def := querymap.Section("")
512 cmd := exec.Command("notmuch", "config", "list")
513 out, err := cmd.Output()
514 if err == nil {
515 re := regexp.MustCompile(`(?m)^query\.([^=]+)=(.+)$`)
516 for _, m := range re.FindAllStringSubmatch(string(out), -1) {
517 _, _ = def.NewKey(m[1], m[2])
518 }
519 }
520 if len(def.Keys()) == 0 {
521 _, _ = def.NewKey("INBOX", "tag:inbox and not tag:archived")
522 }
523 if !wizard.temporary {
524 qmapPath := xdg.ConfigPath("aerc",
525 wizard.accountName.String()+".qmap")
526 f, err := os.OpenFile(qmapPath, os.O_WRONLY|os.O_CREATE, 0o600)
527 if err != nil {
528 wizard.errorFor(nil, err)
529 return
530 }
531 defer f.Close()
532 if _, err = querymap.WriteTo(f); err != nil {
533 wizard.errorFor(nil, err)
534 return
535 }
536 _, _ = sec.NewKey("query-map", xdg.TildeHome(qmapPath))
537 }
538 }
539
540 if !wizard.temporary {
541 f, err := os.OpenFile(accountsConf, os.O_WRONLY|os.O_CREATE, 0o600)
542 if err != nil {
543 wizard.errorFor(nil, err)
544 return
545 }
546 defer f.Close()
547 if _, err = file.WriteTo(f); err != nil {
548 wizard.errorFor(nil, err)
549 return
550 }
551 }
552
553 account, err := config.ParseAccountConfig(sec.Name(), sec)
554 if err != nil {
555 wizard.errorFor(nil, err)
556 return
557 }
558 config.Accounts = append(config.Accounts, account)
559
560 view, err := NewAccountView(account, nil)
561 if err != nil {
562 NewTab(errorScreen(err.Error()), account.Name)
563 return
564 }
565 aerc.accounts[account.Name] = view
566 NewTab(view, account.Name)
567
568 if tutorial {
569 name := "aerc-tutorial"
570 if _, err := os.Stat("./aerc-tutorial.7"); !os.IsNotExist(err) {
571 // For development
572 name = "./aerc-tutorial.7"
573 }
574 term, err := NewTerminal(exec.Command("man", name))
575 if err != nil {
576 wizard.errorFor(nil, err)
577 return
578 }
579 NewTab(term, "Tutorial")
580 term.OnClose = func(err error) {
581 RemoveTab(term, false)
582 if err != nil {
583 PushError(err.Error())
584 }
585 }
586 }
587
588 RemoveTab(wizard, false)
589 }
590
591 func splitHostPath(server string) (string, string) {
592 host, path, found := strings.Cut(server, "/")
593 if found {
594 path = "/" + path
595 }
596 return host, path
597 }
598
599 func makeURLs(scheme, host, path, user, pass string) (url.URL, url.URL) {
600 var opaque string
601
602 // If everything is unset, the rendered URL is '<scheme>:'.
603 // Force a '//' opaque suffix so that it is rendered as '<scheme>://'.
604 if scheme != "" && host == "" && path == "" && user == "" && pass == "" {
605 opaque = "//"
606 }
607
608 uri := url.URL{Scheme: scheme, Host: host, Path: path, Opaque: opaque}
609 clean := uri
610
611 switch {
612 case pass != "":
613 uri.User = url.UserPassword(user, pass)
614 clean.User = url.UserPassword(user, strings.Repeat("*", len(pass)))
615 case user != "":
616 uri.User = url.User(user)
617 clean.User = url.User(user)
618 }
619
620 return uri, clean
621 }
622
623 func (wizard *AccountWizard) sourceUri() url.URL {
624 host, path := splitHostPath(wizard.sourceServer.String())
625 user := wizard.sourceUsername.String()
626 pass := wizard.sourcePassword.String()
627 var scheme string
628 switch wizard.sourceProtocol.Selected() {
629 case IMAP:
630 switch wizard.sourceTransport.Selected() {
631 case STARTTLS:
632 scheme = "imap"
633 case INSECURE:
634 scheme = "imap+insecure"
635 case OAUTH:
636 scheme = "imaps+oauthbearer"
637 case XOAUTH:
638 scheme = "imaps+xoauth2"
639 default:
640 scheme = "imaps"
641 }
642 case JMAP:
643 switch wizard.sourceTransport.Selected() {
644 case OAUTH:
645 scheme = "jmap+oauthbearer"
646 default:
647 scheme = "jmap"
648 }
649 case MAILDIR:
650 scheme = "maildir"
651 case MAILDIRPP:
652 scheme = "maildirpp"
653 case NOTMUCH:
654 scheme = "notmuch"
655 }
656 switch wizard.sourceProtocol.Selected() {
657 case MAILDIR, MAILDIRPP:
658 path = host + path
659 host = ""
660 user = ""
661 pass = ""
662 case NOTMUCH:
663 host = wizard.sourceServer.String()
664 path = ""
665 user = ""
666 pass = ""
667 }
668
669 uri, clean := makeURLs(scheme, host, path, user, pass)
670
671 wizard.sourceStr.Text(
672 " " + strings.ReplaceAll(clean.String(), "%2A", "*"))
673 wizard.sourceUrl = uri
674 return uri
675 }
676
677 func (wizard *AccountWizard) outgoingUri() url.URL {
678 host, path := splitHostPath(wizard.outgoingServer.String())
679 user := wizard.outgoingUsername.String()
680 pass := wizard.outgoingPassword.String()
681 var scheme string
682 switch wizard.outgoingProtocol.Selected() {
683 case SMTP:
684 switch wizard.outgoingTransport.Selected() {
685 case OAUTH:
686 scheme = "smtps+oauthbearer"
687 case XOAUTH:
688 scheme = "smtps+xoauth2"
689 case INSECURE:
690 scheme = "smtp+insecure"
691 case STARTTLS:
692 scheme = "smtp"
693 default:
694 scheme = "smtps"
695 }
696 case JMAP:
697 switch wizard.outgoingTransport.Selected() {
698 case OAUTH:
699 scheme = "jmap+oauthbearer"
700 default:
701 scheme = "jmap"
702 }
703 case SENDMAIL:
704 scheme = ""
705 path = host + path
706 host = ""
707 user = ""
708 pass = ""
709 }
710
711 uri, clean := makeURLs(scheme, host, path, user, pass)
712
713 wizard.outgoingStr.Text(
714 " " + strings.ReplaceAll(clean.String(), "%2A", "*"))
715 wizard.outgoingUrl = uri
716 return uri
717 }
718
719 func (wizard *AccountWizard) Invalidate() {
720 ui.Invalidate()
721 }
722
723 func (wizard *AccountWizard) Draw(ctx *ui.Context) {
724 wizard.steps[wizard.step].Draw(ctx)
725 }
726
727 func (wizard *AccountWizard) getInteractive() []ui.Interactive {
728 switch wizard.step {
729 case CONFIGURE_BASICS:
730 return wizard.basics
731 case CONFIGURE_SOURCE:
732 return wizard.source
733 case CONFIGURE_OUTGOING:
734 return wizard.outgoing
735 case CONFIGURE_COMPLETE:
736 return wizard.complete
737 }
738 return nil
739 }
740
741 func (wizard *AccountWizard) advance(direction string) {
742 wizard.Focus(false)
743 if direction == "Next" && wizard.step < len(wizard.steps)-1 {
744 wizard.step++
745 }
746 if direction == "Previous" && wizard.step > 0 {
747 wizard.step--
748 }
749 wizard.focus = 0
750 wizard.Focus(true)
751 wizard.Invalidate()
752 }
753
754 func (wizard *AccountWizard) Focus(focus bool) {
755 if interactive := wizard.getInteractive(); interactive != nil {
756 interactive[wizard.focus].Focus(focus)
757 }
758 }
759
760 func (wizard *AccountWizard) Event(event vaxis.Event) bool {
761 interactive := wizard.getInteractive()
762 if key, ok := event.(vaxis.Key); ok {
763 switch {
764 case key.Matches('k', vaxis.ModCtrl),
765 key.Matches(vaxis.KeyTab, vaxis.ModShift),
766 key.Matches(vaxis.KeyUp):
767 if interactive != nil {
768 interactive[wizard.focus].Focus(false)
769 wizard.focus--
770 if wizard.focus < 0 {
771 wizard.focus = len(interactive) - 1
772 }
773 interactive[wizard.focus].Focus(true)
774 }
775 wizard.Invalidate()
776 return true
777 case key.Matches('j', vaxis.ModCtrl),
778 key.Matches(vaxis.KeyTab),
779 key.Matches(vaxis.KeyDown):
780
781 if interactive != nil {
782 interactive[wizard.focus].Focus(false)
783 wizard.focus++
784 if wizard.focus >= len(interactive) {
785 wizard.focus = 0
786 }
787 interactive[wizard.focus].Focus(true)
788 }
789 wizard.Invalidate()
790 return true
791 }
792 }
793 if interactive != nil {
794 return interactive[wizard.focus].Event(event)
795 }
796 return false
797 }
798
799 func (wizard *AccountWizard) showDiscoverSpinner(ctx context.Context) {
800 defer log.PanicHandler()
801 spinner := []string{"◜", "◠", "◝", "◞", "◡", "◟"}
802 var i int
803 tick := time.NewTicker(100 * time.Millisecond)
804 for {
805 select {
806 case <-tick.C:
807 wizard.spinner.Text(fmt.Sprintf(" %s The wizard is currently looking into his crystal ball to find your server…", spinner[i]))
808 i++
809 if i >= len(spinner) {
810 i = 0
811 }
812 wizard.spinner.Invalidate()
813 case <-ctx.Done():
814 wizard.spinner.Text("")
815 wizard.spinner.Invalidate()
816 return
817 }
818 }
819 }
820
821 func (wizard *AccountWizard) discoverServices() {
822 email := wizard.email.String()
823 if !strings.ContainsRune(email, '@') {
824 return
825 }
826 if wizard.discoveredFor == email {
827 // we already have these details
828 return
829 }
830
831 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
832 defer cancel()
833
834 go wizard.showDiscoverSpinner(ctx)
835
836 cfg := autoconfig.GetConfig(ctx, email)
837 wizard.discovered = cfg
838 if cfg == nil {
839 log.Errorf("no config retrieved")
840 wizard.sourceServer.Set("")
841 wizard.outgoingServer.Set("")
842 return
843 }
844
845 log.Debugf("retrieved config: %#v", *cfg)
846 switch cfg.Found {
847 case autoconfig.ProtocolIMAP:
848 wizard.sourceProtocol.Select(IMAP)
849 wizard.outgoingProtocol.Select(SMTP)
850 case autoconfig.ProtocolJMAP:
851 wizard.sourceProtocol.Select(JMAP)
852 wizard.outgoingProtocol.Select(JMAP)
853 }
854 wizard.sourceServer.Set("")
855 wizard.outgoingServer.Set("")
856 wizard.sourceUsername.Set(email)
857 wizard.outgoingUsername.Set(email)
858 wizard.discoveredFor = email
859 }
860
861 func (wizard *AccountWizard) autofill() {
862 if wizard.discovered == nil {
863 return
864 }
865 if wizard.sourceServer.String() == "" {
866 switch wizard.sourceProtocol.Selected() {
867 case IMAP:
868 if wizard.discovered.IMAP.Address != "" {
869 wizard.sourceServer.Set(
870 fmt.Sprintf(
871 "%s:%d",
872 wizard.discovered.IMAP.Address,
873 wizard.discovered.IMAP.Port,
874 ),
875 )
876 switch wizard.discovered.IMAP.Encryption {
877 case autoconfig.EncryptionTLS:
878 wizard.sourceTransport.Select(SSL_TLS)
879 case autoconfig.EncryptionSTARTTLS:
880 wizard.sourceTransport.Select(STARTTLS)
881 }
882 }
883 case JMAP:
884 if wizard.discovered.JMAP.Address != "" {
885 wizard.sourceServer.Set(
886 fmt.Sprintf(
887 "%s:%d/.well-known/jmap",
888 wizard.discovered.JMAP.Address,
889 wizard.discovered.JMAP.Port,
890 ),
891 )
892 }
893 case MAILDIR, MAILDIRPP:
894 wizard.sourceServer.Set("~/mail")
895 wizard.sourceUsername.Set("")
896 wizard.sourcePassword.Set("")
897 case NOTMUCH:
898 wizard.sourceServer.Set("")
899 wizard.sourceUsername.Set("")
900 wizard.sourcePassword.Set("")
901 }
902 }
903 if wizard.outgoingServer.String() == "" {
904 switch wizard.outgoingProtocol.Selected() {
905 case SMTP:
906 if wizard.discovered.SMTP.Address != "" {
907 wizard.outgoingServer.Set(fmt.Sprintf("%s:%d", wizard.discovered.SMTP.Address, wizard.discovered.SMTP.Port))
908 switch wizard.discovered.SMTP.Encryption {
909 case autoconfig.EncryptionTLS:
910 wizard.outgoingTransport.Select(SSL_TLS)
911 case autoconfig.EncryptionSTARTTLS:
912 wizard.outgoingTransport.Select(STARTTLS)
913 }
914 }
915 case JMAP:
916 wizard.outgoingTransport.Select(SSL_TLS)
917 case SENDMAIL:
918 wizard.outgoingServer.Set("/usr/sbin/sendmail")
919 wizard.outgoingUsername.Set("")
920 wizard.outgoingPassword.Set("")
921 }
922 }
923 }