Something went wrong. Try again.
Kagi Mail CLI client
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361package cmd
import ( "context" "encoding/json" "errors" "fmt" "strings"
"github.com/spf13/cobra"
"tangled.org/matilde.at/km/internal/compose" "tangled.org/matilde.at/km/internal/idref" "tangled.org/matilde.at/km/internal/jmap" "tangled.org/matilde.at/km/internal/mail" "tangled.org/matilde.at/km/internal/query" "tangled.org/matilde.at/km/internal/render")
func newDraftCmd(f *Factory) *cobra.Command { c := &cobra.Command{Use: "draft <command>", Short: "Manage drafts"} c.AddCommand(newDraftListCmd(f), newDraftEditCmd(f), newDraftSendCmd(f), newDraftDeleteCmd(f)) return c}
func newDraftListCmd(f *Factory) *cobra.Command { limit := 30 c := &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "List drafts", Long: "List the messages in the Drafts mailbox, newest first.", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { p, err := f.Printer(cmd) if err != nil { return err } if limit <= 0 { return usagef("--limit must be positive") } svc, err := f.Mail(cmd.Context()) if err != nil { return err } mb, err := svc.MailboxByRole(cmd.Context(), "drafts") if err != nil { return err } emails, err := svc.ListEmails(cmd.Context(), query.Filter{"inMailbox": mb.ID}, limit, 0) if err != nil { return err } return printEmailList(f, p, emails) }, } c.Flags().IntVarP(&limit, "limit", "L", 30, "Maximum number of rows") render.AddOutputFlags(c, emailFields) return c}
// loadDraft resolves the id and fetches the email, refusing a non-draft.func loadDraft(ctx context.Context, f *Factory, svc *mail.Service, arg string) (mail.Email, error) { id, err := f.IDs.Resolve(arg, idref.Email) if err != nil { return mail.Email{}, err } e, err := svc.GetEmail(ctx, id) if err != nil { return mail.Email{}, err } if !e.Draft() { return mail.Email{}, fmt.Errorf("message %s is not a draft", e.ID) } return e, nil}
func firstAddr(as []mail.Address) mail.Address { if len(as) == 0 { return mail.Address{} } return as[0]}
// draftMessage turns a draft into a compose.Message. The identity is matched// by From when one exists; IdentityID stays empty otherwise.func draftMessage(e mail.Email, ids []mail.Identity) compose.Message { m := compose.Message{ From: firstAddr(e.From), To: e.To, Cc: e.Cc, Bcc: e.Bcc, Subject: e.Subject, InReplyTo: e.InReplyTo, References: e.References, } var body strings.Builder for _, part := range e.TextBody { body.WriteString(e.BodyValues[part.PartID].Value) } m.Body = body.String() for _, a := range e.Attachments { m.Attachments = append(m.Attachments, compose.Attachment{BlobID: a.BlobID, Name: a.Name, Type: a.Type, Size: a.Size}) } for _, id := range ids { if m.From.Email != "" && strings.EqualFold(id.Email, m.From.Email) { m.IdentityID = id.ID break } } return m}
func newDraftEditCmd(f *Factory) *cobra.Command { return &cobra.Command{ Use: "edit <id>", Short: "Edit a draft in $EDITOR", Long: `Edit a draft in $EDITOR. Messages are immutable on the server, so theedited draft is saved as a new message and the old one is destroyed in thesame request; the id changes. Needs a terminal.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if !f.IO.StdinTTY { return usagef("draft edit needs a terminal") } return runDraftEdit(cmd.Context(), f, args[0]) }, }}
func runDraftEdit(ctx context.Context, f *Factory, arg string) error { svc, err := f.Mail(ctx) if err != nil { return err } e, err := loadDraft(ctx, f, svc, arg) if err != nil { return err } ids, err := svc.Identities(ctx) if err != nil { return err } orig := draftMessage(e, ids) initial := compose.Serialise(orig) edited, err := f.Prompt.Edit(initial, ".eml") if err != nil { return err } parsed, err := compose.ParseEdited(initial, edited) if errors.Is(err, compose.ErrUnchanged) { fmt.Fprintln(f.IO.ErrOut, "No changes") return nil } if err != nil { return err } m := parsed.Merge(orig) if err := m.Validate(false); err != nil { return err } drafts, err := svc.MailboxByRole(ctx, "drafts") if err != nil { return err } acct, err := svc.Account(ctx) if err != nil { return err } var req jmap.Request c := req.Add("Email/set", map[string]any{ "accountId": acct, "create": map[string]any{"draft": compose.EmailCreate(m, drafts.ID)}, }) resp, err := svc.J.Do(ctx, &req) if err != nil { return err } var r mail.SetResponse if err := resp.Decode(c, &r); err != nil { return err } if se := r.NotCreated["draft"]; se != nil { return fmt.Errorf("draft not saved: %w", se) } var created struct { ID string `json:"id"` } if raw, ok := r.Created["draft"]; ok { _ = json.Unmarshal(raw, &created) } if created.ID == "" { return errors.New("draft not saved: the server returned no id") } // Destroy the old draft only once the new one exists: create and // destroy in one Email/set are independent, so a failed create could // otherwise lose the draft. if err := svc.DestroyEmails(ctx, []string{e.ID}); err != nil { fmt.Fprintf(f.IO.ErrOut, "warning: saved %s, but the old draft %s was not removed: %v\n", created.ID, e.ID, err) } if !f.IO.StdoutTTY { fmt.Fprintln(f.IO.Out, created.ID) return nil } fmt.Fprintf(f.IO.ErrOut, "Saved draft %s\n", created.ID) return nil}
type draftYesOpts struct{ yes bool }
func newDraftSendCmd(f *Factory) *cobra.Command { o := &draftYesOpts{} c := &cobra.Command{ Use: "send <id>", Short: "Send a draft", Long: `Send an existing draft as it is. On a terminal the message is summarisedand you are asked to confirm unless --yes is given; in a script it is sentwithout asking.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runDraftSend(cmd.Context(), f, args[0], o.yes) }, } c.Flags().BoolVarP(&o.yes, "yes", "y", false, "Do not ask for confirmation") return c}
func runDraftSend(ctx context.Context, f *Factory, arg string, yes bool) error { svc, err := f.Mail(ctx) if err != nil { return err } e, err := loadDraft(ctx, f, svc, arg) if err != nil { return err } m := draftMessage(e, nil) if len(m.Recipients()) == 0 { return fmt.Errorf("draft %s has no recipients; edit it with km draft edit", e.ID) } if m.From.Email == "" { return fmt.Errorf("draft %s has no From address; edit it with km draft edit", e.ID) } ids, err := svc.Identities(ctx) if err != nil { return err } ident, err := compose.SelectIdentity(ids, m.From.Email) if err != nil { return err } if f.IO.StdinTTY && !yes { fmt.Fprint(f.IO.ErrOut, sendSummary(m)) ok, err := f.Prompt.Confirm("Send this draft?", true) if err != nil { return err } if !ok { fmt.Fprintln(f.IO.ErrOut, "Cancelled") return silentErr } } drafts, err := svc.MailboxByRole(ctx, "drafts") if err != nil { return err } sent, err := svc.MailboxByRole(ctx, "sent") if err != nil { return err } sess, err := svc.J.Session(ctx) if err != nil { return err } subAcct, err := sess.AccountID(jmap.CapSubmission) if err != nil { return err } req := jmap.Request{Using: []string{jmap.CapCore, jmap.CapMail, jmap.CapSubmission}} c := req.Add("EmailSubmission/set", map[string]any{ "accountId": subAcct, "create": map[string]any{"sub": map[string]any{ "identityId": ident.ID, "emailId": e.ID, }}, "onSuccessUpdateEmail": map[string]any{ "#sub": map[string]any{ "mailboxIds/" + drafts.ID: nil, "keywords/$draft": nil, "mailboxIds/" + sent.ID: true, }, }, }) resp, err := svc.J.Do(ctx, &req) if err != nil { return err } var r mail.SetResponse if err := resp.Decode(c, &r); err != nil { return fmt.Errorf("draft %s not sent: %w", e.ID, err) } if se := r.NotCreated["sub"]; se != nil { return fmt.Errorf("draft %s not sent: %w", e.ID, se) } var up mail.SetResponse if err := resp.DecodeNamed(c, "Email/set", &up); err == nil { for id, se := range up.NotUpdated { fmt.Fprintf(f.IO.ErrOut, "warning: updating %s after sending failed: %v\n", id, se) } } if !f.IO.StdoutTTY { fmt.Fprintln(f.IO.Out, e.ID) return nil } fmt.Fprintf(f.IO.ErrOut, "Sent draft %s\n", e.ID) return nil}
func newDraftDeleteCmd(f *Factory) *cobra.Command { o := &draftYesOpts{} c := &cobra.Command{ Use: "delete <id>", Short: "Delete a draft", Long: `Permanently delete a draft. On a terminal that asks for confirmation; in ascript it requires --yes.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() if !o.yes && !f.IO.StdinTTY { return usagef("draft delete needs --yes when not run from a terminal") } svc, err := f.Mail(ctx) if err != nil { return err } e, err := loadDraft(ctx, f, svc, args[0]) if err != nil { return err } if !o.yes { subj := e.Subject if subj == "" { subj = "(no subject)" } ok, err := f.Prompt.Confirm(fmt.Sprintf("Delete draft %q? This cannot be undone.", subj), false) if err != nil { return err } if !ok { fmt.Fprintln(f.IO.ErrOut, "Cancelled") return silentErr } } if err := svc.DestroyEmails(ctx, []string{e.ID}); err != nil { return err } if f.IO.StdoutTTY { fmt.Fprintf(f.IO.ErrOut, "Deleted draft %s\n", e.ID) } return nil }, } c.Flags().BoolVarP(&o.yes, "yes", "y", false, "Do not ask for confirmation") return c}