package 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 ", 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 ", Short: "Edit a draft in $EDITOR", Long: `Edit a draft in $EDITOR. Messages are immutable on the server, so the edited draft is saved as a new message and the old one is destroyed in the same 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 ", Short: "Send a draft", Long: `Send an existing draft as it is. On a terminal the message is summarised and you are asked to confirm unless --yes is given; in a script it is sent without 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 ", Short: "Delete a draft", Long: `Permanently delete a draft. On a terminal that asks for confirmation; in a script 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 }