aboutsummaryrefslogtreecommitdiffstats
path: root/worker/jmap/send.go
blob: 4b033d2ec6d5b67ddb33e9a0060c8610e079d44e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package jmap

import (
	"fmt"
	"io"
	"strings"

	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/worker/types"
	"git.sr.ht/~rockorager/go-jmap"
	"git.sr.ht/~rockorager/go-jmap/mail/email"
	"git.sr.ht/~rockorager/go-jmap/mail/emailsubmission"
	"git.sr.ht/~rockorager/go-jmap/mail/mailbox"
	"github.com/emersion/go-message/mail"
)

func (w *JMAPWorker) handleStartSend(msg *types.StartSendingMessage) error {
	reader, writer := io.Pipe()
	send := &jmapSendWriter{writer: writer, done: make(chan error)}

	w.w.PostMessage(&types.MessageWriter{
		Message: types.RespondTo(msg),
		Writer:  send,
	}, nil)

	go func() {
		defer log.PanicHandler()
		defer close(send.done)

		identity, err := w.getSenderIdentity(msg.Header)
		if err != nil {
			send.done <- err
			return
		}

		blob, err := w.Upload(reader)
		if err != nil {
			send.done <- err
			return
		}

		var req jmap.Request

		// Import the blob into drafts
		req.Invoke(&email.Import{
			Account: w.accountId,
			Emails: map[string]*email.EmailImport{
				"aerc": {
					BlobID: blob.ID,
					MailboxIDs: map[jmap.ID]bool{
						w.roles[mailbox.RoleDrafts]: true,
					},
					Keywords: map[string]bool{
						"$draft": true,
						"$seen":  true,
					},
				},
			},
		})

		// Create the submission
		req.Invoke(&emailsubmission.Set{
			Account: w.accountId,
			Create: map[jmap.ID]*emailsubmission.EmailSubmission{
				"sub": {
					IdentityID: identity,
					EmailID:    "#aerc",
				},
			},
			OnSuccessUpdateEmail: map[jmap.ID]jmap.Patch{
				"#sub": {
					"keywords/$draft":               nil,
					w.rolePatch(mailbox.RoleSent):   true,
					w.rolePatch(mailbox.RoleDrafts): nil,
				},
			},
		})

		resp, err := w.Do(&req)
		if err != nil {
			send.done <- err
			return
		}

		for _, inv := range resp.Responses {
			switch r := inv.Args.(type) {
			case *email.ImportResponse:
				if err, ok := r.NotCreated["aerc"]; ok {
					send.done <- wrapSetError(err)
					return
				}
			case *emailsubmission.SetResponse:
				if err, ok := r.NotCreated["sub"]; ok {
					send.done <- wrapSetError(err)
					return
				}
			case *jmap.MethodError:
				send.done <- wrapMethodError(r)
				return
			}
		}
	}()

	return nil
}

type jmapSendWriter struct {
	writer *io.PipeWriter
	done   chan error
}

func (w *jmapSendWriter) Write(data []byte) (int, error) {
	return w.writer.Write(data)
}

func (w *jmapSendWriter) Close() error {
	writeErr := w.writer.Close()
	sendErr := <-w.done
	if writeErr != nil {
		return writeErr
	}
	return sendErr
}

func (w *JMAPWorker) getSenderIdentity(header *mail.Header) (jmap.ID, error) {
	from, err := header.AddressList("from")
	if err != nil {
		return "", fmt.Errorf("msg.Header.AddressList: %w", err)
	}
	if len(from) != 1 {
		return "", fmt.Errorf("no from header in message")
	}
	name, domain, _ := strings.Cut(from[0].Address, "@")
	for _, ident := range w.identities {
		n, d, _ := strings.Cut(ident.Email, "@")
		switch {
		case n == name && d == domain:
			fallthrough
		case n == "*" && d == domain:
			return ident.ID, nil
		}
	}
	return "", fmt.Errorf("no identity found for address: %s@%s", name, domain)
}