aboutsummaryrefslogtreecommitdiffstats
path: root/commands/account/import-mbox.go
blob: 85e9a341a9f50a35f803905fc7d0caf8ec152c53 (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
145
146
147
148
149
150
151
152
153
154
package account

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sync/atomic"
	"time"

	"git.sr.ht/~rjarry/aerc/commands"
	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/models"
	"git.sr.ht/~rjarry/aerc/widgets"
	mboxer "git.sr.ht/~rjarry/aerc/worker/mbox"
	"git.sr.ht/~rjarry/aerc/worker/types"
)

type ImportMbox struct{}

func init() {
	register(ImportMbox{})
}

func (ImportMbox) Aliases() []string {
	return []string{"import-mbox"}
}

func (ImportMbox) Complete(aerc *widgets.Aerc, args []string) []string {
	return commands.CompletePath(filepath.Join(args...))
}

func (ImportMbox) Execute(aerc *widgets.Aerc, args []string) error {
	if len(args) != 2 {
		return importFolderUsage(args[0])
	}
	filename := args[1]

	acct := aerc.SelectedAccount()
	if acct == nil {
		return errors.New("No account selected")
	}
	store := acct.Store()
	if store == nil {
		return errors.New("No message store selected")
	}

	folder := acct.SelectedDirectory()
	if folder == "" {
		return errors.New("No directory selected")
	}

	importFolder := func() {
		defer log.PanicHandler()
		statusInfo := fmt.Sprintln("Importing", filename, "to folder", folder)
		aerc.PushStatus(statusInfo, 10*time.Second)
		log.Debugf(statusInfo)
		f, err := os.Open(filename)
		if err != nil {
			aerc.PushError(err.Error())
			return
		}
		defer f.Close()

		messages, err := mboxer.Read(f)
		if err != nil {
			aerc.PushError(err.Error())
			return
		}
		worker := acct.Worker()

		var appended uint32
		for i, m := range messages {
			done := make(chan bool)
			var retries int = 4
			for retries > 0 {
				var buf bytes.Buffer
				r, err := m.NewReader()
				if err != nil {
					log.Errorf("could not get reader for uid %d", m.UID())
					break
				}
				nbytes, _ := io.Copy(&buf, r)
				worker.PostAction(&types.AppendMessage{
					Destination: folder,
					Flags:       models.SeenFlag,
					Date:        time.Now(),
					Reader:      &buf,
					Length:      int(nbytes),
				}, func(msg types.WorkerMessage) {
					switch msg := msg.(type) {
					case *types.Unsupported:
						errMsg := fmt.Sprintf("%s: AppendMessage is unsupported", args[0])
						log.Errorf(errMsg)
						aerc.PushError(errMsg)
						return
					case *types.Error:
						log.Errorf("AppendMessage failed: %v", msg.Error)
						done <- false
					case *types.Done:
						atomic.AddUint32(&appended, 1)
						done <- true
					}
				})

				select {
				case ok := <-done:
					if ok {
						retries = 0
					} else {
						// error encountered; try to append again after a quick nap
						retries -= 1
						sleeping := time.Duration((5 - retries) * 1e9)

						log.Debugf("sleeping for %s before append message %d again", sleeping, i)
						time.Sleep(sleeping)
					}
				case <-time.After(30 * time.Second):
					log.Warnf("timed-out; appended %d of %d", appended, len(messages))
					return
				}
			}
		}
		infoStr := fmt.Sprintf("%s: imported %d of %d successfully.", args[0], appended, len(messages))
		log.Debugf(infoStr)
		aerc.PushSuccess(infoStr)
	}

	if len(store.Uids()) > 0 {
		confirm := widgets.NewSelectorDialog(
			"Selected directory is not empty",
			fmt.Sprintf("Import mbox file to %s anyways?", folder),
			[]string{"No", "Yes"}, 0, aerc.SelectedAccountUiConfig(),
			func(option string, err error) {
				aerc.CloseDialog()
				aerc.Invalidate()
				if option == "Yes" {
					go importFolder()
				}
			},
		)
		aerc.AddDialog(confirm)
	} else {
		go importFolder()
	}

	return nil
}

func importFolderUsage(cmd string) error {
	return fmt.Errorf("Usage: %s <filename>", cmd)
}