aboutsummaryrefslogtreecommitdiffstats
path: root/commands/account/recover.go
blob: a2170edd17ccd953845d8197f06e94ff0407a77b (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
package account

import (
	"bytes"
	"errors"
	"io"
	"os"
	"path/filepath"

	"git.sr.ht/~rjarry/aerc/app"
	"git.sr.ht/~rjarry/aerc/commands"
	"git.sr.ht/~rjarry/aerc/config"
)

type Recover struct {
	Force  bool   `opt:"-f"`
	Edit   bool   `opt:"-e"`
	NoEdit bool   `opt:"-E"`
	File   string `opt:"file" complete:"CompleteFile"`
}

func init() {
	register(Recover{})
}

func (Recover) Aliases() []string {
	return []string{"recover"}
}

func (Recover) Options() string {
	return "feE"
}

func (*Recover) CompleteFile(arg string) []string {
	// file name of temp file is hard-coded in the NewComposer() function
	files, err := filepath.Glob(
		filepath.Join(os.TempDir(), "aerc-compose-*.eml"),
	)
	if err != nil {
		return nil
	}
	return commands.FilterList(files, arg, nil)
}

func (r Recover) Execute(args []string) error {
	file, err := os.Open(r.File)
	if err != nil {
		return err
	}
	defer file.Close()
	data, err := io.ReadAll(file)
	if err != nil {
		return err
	}

	acct := app.SelectedAccount()
	if acct == nil {
		return errors.New("No account selected")
	}

	editHeaders := (config.Compose.EditHeaders || r.Edit) && !r.NoEdit

	composer, err := app.NewComposer(acct,
		acct.AccountConfig(), acct.Worker(), editHeaders,
		"", nil, nil, bytes.NewReader(data))
	if err != nil {
		return err
	}
	composer.Tab = app.NewTab(composer, "Recovered")

	// remove file if force flag is set
	if r.Force {
		err = os.Remove(r.File)
		if err != nil {
			return err
		}
	}

	return nil
}