Debian Codegraph @

commands/msg/forward.go

raw
1 package msg
2
3 import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "math/rand"
11 "os"
12 "path"
13 "strings"
14 "sync"
15
16 "git.sr.ht/~rjarry/aerc/app"
17 "git.sr.ht/~rjarry/aerc/commands"
18 "git.sr.ht/~rjarry/aerc/config"
19 "git.sr.ht/~rjarry/aerc/lib"
20 "git.sr.ht/~rjarry/aerc/lib/crypto"
21 "git.sr.ht/~rjarry/aerc/lib/format"
22 "git.sr.ht/~rjarry/aerc/lib/log"
23 "git.sr.ht/~rjarry/aerc/models"
24 "git.sr.ht/~rjarry/aerc/worker/types"
25 "github.com/emersion/go-message/mail"
26 )
27
28 type forward struct {
29 AttachAll bool `opt:"-A" desc:"Forward the message and all attachments."`
30 Account string `opt:"-x" desc:"Forward with the specified account." complete:"CompleteAccount"`
31 AttachFull bool `opt:"-F" desc:"Forward the full message as an RFC 2822 attachment."`
32 Edit bool `opt:"-e" desc:"Force [compose].edit-headers = true."`
33 NoEdit bool `opt:"-E" desc:"Force [compose].edit-headers = false."`
34 Template string `opt:"-T" complete:"CompleteTemplate" desc:"Template name."`
35 SkipEditor bool `opt:"-s" desc:"Skip the editor and go directly to the review screen."`
36 To []string `opt:"..." required:"false" complete:"CompleteTo" desc:"Recipient from address book."`
37 }
38
39 func init() {
40 commands.Register(forward{})
41 }
42
43 func (forward) Description() string {
44 return "Open the composer to forward the selected message to another recipient."
45 }
46
47 func (forward) Context() commands.CommandContext {
48 return commands.MESSAGE_LIST | commands.MESSAGE_VIEWER
49 }
50
51 func (forward) Aliases() []string {
52 return []string{"forward"}
53 }
54
55 func (*forward) CompleteTemplate(arg string) []string {
56 return commands.GetTemplates(arg)
57 }
58
59 func (*forward) CompleteTo(arg string) []string {
60 return commands.GetAddress(arg)
61 }
62
63 func (*forward) CompleteAccount(arg string) []string {
64 return commands.FilterList(app.AccountNames(), arg, nil)
65 }
66
67 func (f forward) Execute(args []string) error {
68 if f.AttachAll && f.AttachFull {
69 return errors.New("Options -A and -F are mutually exclusive")
70 }
71 editHeaders := (config.Compose().EditHeaders || f.Edit) && !f.NoEdit
72
73 widget := app.SelectedTabContent().(app.ProvidesMessage)
74 var acct *app.AccountView
75 var err error
76
77 if f.Account == "" {
78 acct = widget.SelectedAccount()
79 if acct == nil {
80 return errors.New("No account selected")
81 }
82 } else {
83 acct, err = app.Account(f.Account)
84 if err != nil {
85 return err
86 }
87 }
88 msg, err := widget.SelectedMessage()
89 if err != nil {
90 return err
91 }
92 log.Debugf("Forwarding email <%s>", msg.Envelope.MessageId)
93
94 h := &mail.Header{}
95 subject := "Fwd: " + msg.Envelope.Subject
96 h.SetSubject(subject)
97
98 var tolist []*mail.Address
99 to := strings.Join(f.To, ", ")
100 if strings.Contains(to, "@") {
101 tolist, err = mail.ParseAddressList(to)
102 if err != nil {
103 return fmt.Errorf("invalid to address(es): %w", err)
104 }
105 }
106 if len(tolist) > 0 {
107 h.SetAddressList("to", tolist)
108 }
109
110 original := models.OriginalMail{
111 From: format.FormatAddresses(msg.Envelope.From),
112 Date: msg.Envelope.Date,
113 RFC822Headers: msg.RFC822Headers,
114 }
115
116 addTab := func() (*app.Composer, error) {
117 composer, err := app.NewComposer(acct,
118 acct.AccountConfig(), acct.Worker(), editHeaders,
119 f.Template, h, &original, nil)
120 if err != nil {
121 app.PushError("Error: " + err.Error())
122 return nil, err
123 }
124
125 composer.Tab = app.NewTab(composer, subject)
126 switch {
127 case f.SkipEditor:
128 composer.Terminal().Close()
129 case !h.Has("to"):
130 composer.FocusEditor("to")
131 default:
132 composer.FocusTerminal()
133 }
134 return composer, nil
135 }
136
137 mv, isMsgViewer := widget.(*app.MessageViewer)
138 store := widget.Store()
139 noStore := store == nil
140 if noStore && !isMsgViewer {
141 return errors.New("Cannot perform action. Messages still loading")
142 }
143
144 if f.AttachFull {
145 tmpDir, err := os.MkdirTemp(config.General().TempDir, "aerc-tmp-attachment")
146 if err != nil {
147 return err
148 }
149 tmpFileName := path.Join(tmpDir,
150 strings.ReplaceAll(fmt.Sprintf("%s.eml", msg.Envelope.Subject), "/", "-"))
151
152 var fetchFull func(func(io.Reader))
153
154 if isMsgViewer {
155 fetchFull = mv.MessageView().FetchFull
156 } else {
157 fetchFull = func(cb func(io.Reader)) {
158 store.FetchFull(context.TODO(), []models.UID{msg.Uid}, func(fm *types.FullMessage) {
159 if fm == nil || (fm != nil && fm.Content == nil) {
160 return
161 }
162 cb(fm.Content.Reader)
163 })
164 }
165 }
166
167 fetchFull(func(r io.Reader) {
168 tmpFile, err := os.Create(tmpFileName)
169 if err != nil {
170 log.Warnf("failed to create temporary attachment: %v", err)
171 _, err = addTab()
172 if err != nil {
173 log.Warnf("failed to add tab: %v", err)
174 }
175 return
176 }
177
178 defer tmpFile.Close()
179 _, err = io.Copy(tmpFile, r)
180 if err != nil {
181 log.Warnf("failed to write to tmpfile: %v", err)
182 return
183 }
184 composer, err := addTab()
185 if err != nil {
186 return
187 }
188 composer.AddAttachment(tmpFileName)
189 composer.OnClose(func(c *app.Composer) {
190 if c.Sent() && store != nil {
191 store.Forwarded([]models.UID{msg.Uid}, true, nil)
192 }
193 os.RemoveAll(tmpDir)
194 })
195 })
196 } else {
197 if f.Template == "" {
198 f.Template = config.Templates().Forwards
199 }
200
201 var fetchBodyPart func([]int, func(io.Reader))
202
203 if isMsgViewer {
204 fetchBodyPart = mv.MessageView().FetchBodyPart
205 } else {
206 fetchBodyPart = func(part []int, cb func(io.Reader)) {
207 store.FetchBodyPart(context.TODO(), msg.Uid, part, cb)
208 }
209 }
210
211 if crypto.IsEncrypted(msg.BodyStructure) && !isMsgViewer {
212 return fmt.Errorf("message is encrypted. " +
213 "can only forward from the message viewer")
214 }
215
216 part := getMessagePart(msg, widget)
217 if part == nil {
218 part = lib.FindFirstNonMultipart(msg.BodyStructure, nil)
219 // if it's still nil here, we don't have a multipart msg, that's fine
220 }
221
222 err = addMimeType(msg, part, &original)
223 if err != nil {
224 return err
225 }
226
227 fetchBodyPart(part, func(reader io.Reader) {
228 buf := new(bytes.Buffer)
229 scanner := bufio.NewScanner(reader)
230 for scanner.Scan() {
231 buf.WriteString(scanner.Text() + "\n")
232 }
233 original.Text = buf.String()
234
235 // create composer
236 composer, err := addTab()
237 if err != nil {
238 return
239 }
240
241 composer.OnClose(func(c *app.Composer) {
242 if c.Sent() && store != nil {
243 store.Forwarded([]models.UID{msg.Uid}, true, nil)
244 }
245 })
246
247 // add attachments
248 if f.AttachAll {
249 var mu sync.Mutex
250 parts := lib.FindAllNonMultipart(msg.BodyStructure, nil, nil)
251 for _, p := range parts {
252 if lib.EqualParts(p, part) {
253 continue
254 }
255 bs, err := msg.BodyStructure.PartAtIndex(p)
256 if err != nil {
257 log.Errorf("cannot get PartAtIndex %v: %v", p, err)
258 continue
259 }
260 fetchBodyPart(p, func(reader io.Reader) {
261 mime := bs.FullMIMEType()
262 params := lib.SetUtf8Charset(bs.Params)
263 name := bs.FileName()
264 if name == "" {
265 name = fmt.Sprintf("%s_%s_%d", bs.MIMEType, bs.MIMESubType, rand.Uint64())
266 }
267 mu.Lock()
268 err := composer.AddPartAttachment(name, mime, params, reader)
269 mu.Unlock()
270 if err != nil {
271 log.Errorf(err.Error())
272 app.PushError(err.Error())
273 }
274 })
275 }
276 }
277 })
278 }
279 return nil
280 }