aboutsummaryrefslogtreecommitdiff
path: root/commands/msgview/save.go
blob: 3d923916c1bd751c7f26ac6ba90e6f6cb66eeccf (plain)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package msgview

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"

	"git.sr.ht/~rjarry/aerc/commands"
	"git.sr.ht/~rjarry/aerc/config"
	"git.sr.ht/~rjarry/aerc/lib/xdg"
	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/models"
	"git.sr.ht/~rjarry/aerc/widgets"
)

type Save struct {
	Force          bool   `opt:"-f"`
	CreateDirs     bool   `opt:"-p"`
	Attachments    bool   `opt:"-a"`
	AllAttachments bool   `opt:"-A"`
	Path           string `opt:"..." required:"false" metavar:"PATH"`
}

func init() {
	register(Save{})
}

func (Save) Options() string {
	return "fpaA"
}

func (Save) Aliases() []string {
	return []string{"save"}
}

func (s Save) Complete(aerc *widgets.Aerc, args []string) []string {
	trimmed := commands.Operands(args, s.Options())
	path := strings.Join(trimmed, " ")
	defaultPath := config.General.DefaultSavePath
	if defaultPath != "" && !isAbsPath(path) {
		path = filepath.Join(defaultPath, path)
	}
	return commands.CompletePath(xdg.ExpandHome(path))
}

func (s Save) Execute(aerc *widgets.Aerc, args []string) error {
	// we either need a path or a defaultPath
	if s.Path == "" && config.General.DefaultSavePath == "" {
		return errors.New("No default save path in config")
	}

	// Absolute paths are taken as is so that the user can override the default
	// if they want to
	if !isAbsPath(s.Path) {
		s.Path = filepath.Join(config.General.DefaultSavePath, s.Path)
	}

	s.Path = xdg.ExpandHome(s.Path)

	mv, ok := aerc.SelectedTabContent().(*widgets.MessageViewer)
	if !ok {
		return fmt.Errorf("SelectedTabContent is not a MessageViewer")
	}

	if s.Attachments || s.AllAttachments {
		parts := mv.AttachmentParts(s.AllAttachments)
		if len(parts) == 0 {
			return fmt.Errorf("This message has no attachments")
		}
		names := make(map[string]struct{})
		for _, pi := range parts {
			if err := s.savePart(pi, mv, aerc, names); err != nil {
				return err
			}
		}
		return nil
	}

	pi := mv.SelectedMessagePart()
	return s.savePart(pi, mv, aerc, make(map[string]struct{}))
}

func (s *Save) savePart(
	pi *widgets.PartInfo,
	mv *widgets.MessageViewer,
	aerc *widgets.Aerc,
	names map[string]struct{},
) error {
	path := s.Path
	if s.Attachments || s.AllAttachments || isDirExists(path) {
		filename := generateFilename(pi.Part)
		path = filepath.Join(path, filename)
	}

	dir := filepath.Dir(path)
	if s.CreateDirs && dir != "" {
		err := os.MkdirAll(dir, 0o755)
		if err != nil {
			return err
		}
	}

	path = getCollisionlessFilename(path, names)
	names[path] = struct{}{}

	if pathExists(path) && !s.Force {
		return fmt.Errorf("%q already exists and -f not given", path)
	}

	ch := make(chan error, 1)
	mv.MessageView().FetchBodyPart(pi.Index, func(reader io.Reader) {
		f, err := os.Create(path)
		if err != nil {
			ch <- err
			return
		}
		defer f.Close()
		_, err = io.Copy(f, reader)
		if err != nil {
			ch <- err
			return
		}
		ch <- nil
	})

	// we need to wait for the callback prior to displaying a result
	go func() {
		defer log.PanicHandler()

		err := <-ch
		if err != nil {
			aerc.PushError(fmt.Sprintf("Save failed: %v", err))
			return
		}
		aerc.PushStatus("Saved to "+path, 10*time.Second)
	}()
	return nil
}

func getCollisionlessFilename(path string, existing map[string]struct{}) string {
	ext := filepath.Ext(path)
	name := strings.TrimSuffix(path, ext)
	_, exists := existing[path]
	counter := 1
	for exists {
		path = fmt.Sprintf("%s_%d%s", name, counter, ext)
		counter++
		_, exists = existing[path]
	}
	return path
}

// isDir returns true if path is a directory and exists
func isDirExists(path string) bool {
	pathinfo, err := os.Stat(path)
	if err != nil {
		return false // we don't really care
	}
	if pathinfo.IsDir() {
		return true
	}
	return false
}

// pathExists returns true if path exists
func pathExists(path string) bool {
	_, err := os.Stat(path)

	return err == nil
}

// isAbsPath returns true if path given is anchored to / or . or ~
func isAbsPath(path string) bool {
	if len(path) == 0 {
		return false
	}
	switch path[0] {
	case '/':
		return true
	case '.':
		return true
	case '~':
		return true
	default:
		return false
	}
}

// generateFilename tries to get the filename from the given part.
// if that fails it will fallback to a generated one based on the date
func generateFilename(part *models.BodyStructure) string {
	filename := part.FileName()
	// Some MUAs send attachments with names like /some/stupid/idea/happy.jpeg
	// Assuming non hostile intent it does make sense to use just the last
	// portion of the pathname as the filename for saving it.
	filename = filename[strings.LastIndex(filename, "/")+1:]
	switch filename {
	case "", ".", "..":
		timestamp := time.Now().Format("2006-01-02-150405")
		filename = fmt.Sprintf("aerc_%v", timestamp)
	default:
		// already have a valid name
	}
	return filename
}