Debian Codegraph @

commands/account/export-mbox.go

raw
1 package account
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "sync"
10 "time"
11
12 "git.sr.ht/~rjarry/aerc/app"
13 "git.sr.ht/~rjarry/aerc/commands"
14 "git.sr.ht/~rjarry/aerc/lib"
15 "git.sr.ht/~rjarry/aerc/lib/log"
16 "git.sr.ht/~rjarry/aerc/lib/xdg"
17 "git.sr.ht/~rjarry/aerc/models"
18 mboxer "git.sr.ht/~rjarry/aerc/worker/mbox"
19 "git.sr.ht/~rjarry/aerc/worker/types"
20 )
21
22 type ExportMbox struct {
23 Filename string `opt:"filename" complete:"CompleteFilename" desc:"Output file path."`
24 }
25
26 func init() {
27 commands.Register(ExportMbox{})
28 }
29
30 func (ExportMbox) Description() string {
31 return "Export messages in the current folder to an mbox file."
32 }
33
34 func (ExportMbox) Context() commands.CommandContext {
35 return commands.MESSAGE_LIST
36 }
37
38 func (ExportMbox) Aliases() []string {
39 return []string{"export-mbox"}
40 }
41
42 func (*ExportMbox) CompleteFilename(arg string) []string {
43 return commands.CompletePath(arg, false)
44 }
45
46 func (e ExportMbox) Execute(args []string) error {
47 acct := app.SelectedAccount()
48 if acct == nil {
49 return errors.New("No account selected")
50 }
51 store := acct.Store()
52 if store == nil {
53 return errors.New("No message store selected")
54 }
55
56 e.Filename = xdg.ExpandHome(e.Filename)
57
58 fi, err := os.Stat(e.Filename)
59 if err == nil && fi.IsDir() {
60 if path := acct.SelectedDirectory(); path != "" {
61 if f := filepath.Base(path); f != "" {
62 e.Filename = filepath.Join(e.Filename, f+".mbox")
63 }
64 }
65 }
66
67 app.PushStatus("Exporting to "+e.Filename, 10*time.Second)
68
69 // uids of messages to export
70 var uids []models.UID
71
72 // check if something is marked - we export that then
73 msgProvider, ok := app.SelectedTabContent().(app.ProvidesMessages)
74 if !ok {
75 msgProvider = app.SelectedAccount()
76 }
77 if msgProvider != nil {
78 marked, err := msgProvider.MarkedMessages()
79 if err == nil && len(marked) > 0 {
80 uids, err = sortMarkedUids(marked, store)
81 if err != nil {
82 return err
83 }
84 }
85 }
86
87 // if no messages were marked, we export everything
88 if len(uids) == 0 {
89 var err error
90 uids, err = sortAllUids(store)
91 if err != nil {
92 return err
93 }
94 }
95
96 go func() {
97 defer log.PanicHandler()
98 file, err := os.Create(e.Filename)
99 if err != nil {
100 log.Errorf("failed to create file: %v", err)
101 app.PushError(err.Error())
102 return
103 }
104 defer file.Close()
105
106 var mu sync.Mutex
107 var ctr uint
108 var retries int
109
110 done := make(chan bool)
111
112 t := time.Now()
113 total := len(uids)
114 processedUids := make(map[models.UID]struct{})
115
116 for len(uids) > 0 {
117 if retries > 0 {
118 if retries > 10 {
119 errorMsg := fmt.Sprintf("too many retries: %d; stopping export", retries)
120 log.Errorf(errorMsg)
121 app.PushError(args[0] + " " + errorMsg)
122 break
123 }
124 sleeping := time.Duration(retries * 1e9 * 2)
125 log.Debugf("sleeping for %s before retrying; retries: %d", sleeping, retries)
126 time.Sleep(sleeping)
127 }
128
129 log.Debugf("fetching %d for export", len(uids))
130 acct.Worker().PostAction(context.TODO(), &types.FetchFullMessages{
131 Uids: uids,
132 Directory: store.Name,
133 }, func(msg types.WorkerMessage) {
134 switch msg := msg.(type) {
135 case *types.Done:
136 done <- true
137 case *types.Error:
138 log.Errorf("failed to fetch message: %v", msg.Error)
139 app.PushError(args[0] + " error encountered: " + msg.Error.Error())
140 done <- false
141 case *types.FullMessage:
142 mu.Lock()
143 err := mboxer.Write(file, msg.Content.Reader, "", t)
144 if err != nil {
145 log.Warnf("failed to write mbox: %v", err)
146 }
147 processedUids[msg.Content.Uid] = struct{}{}
148 ctr++
149 mu.Unlock()
150 }
151 })
152 if ok := <-done; ok {
153 break
154 }
155
156 // filter uids in place to keep the ones to retry
157 n := 0
158 for _, uid := range uids {
159 if _, ok := processedUids[uid]; !ok {
160 uids[n] = uid
161 n++
162 }
163 }
164 uids = uids[:n]
165
166 retries++
167 }
168 statusInfo := fmt.Sprintf("Exported %d of %d messages to %s.", ctr, total, e.Filename)
169 app.PushStatus(statusInfo, 10*time.Second)
170 log.Debugf(statusInfo)
171 }()
172
173 return nil
174 }
175
176 func sortMarkedUids(marked []models.UID, store *lib.MessageStore) ([]models.UID, error) {
177 lookup := map[models.UID]bool{}
178 for _, uid := range marked {
179 lookup[uid] = true
180 }
181 uids := []models.UID{}
182 iter := store.UidsIterator()
183 for iter.Next() {
184 uid, ok := iter.Value().(models.UID)
185 if !ok {
186 return nil, errors.New("Invalid message UID value")
187 }
188 _, marked := lookup[uid]
189 if marked {
190 uids = append(uids, uid)
191 }
192 }
193 return uids, nil
194 }
195
196 func sortAllUids(store *lib.MessageStore) ([]models.UID, error) {
197 uids := []models.UID{}
198 iter := store.UidsIterator()
199 for iter.Next() {
200 uid, ok := iter.Value().(models.UID)
201 if !ok {
202 return nil, errors.New("Invalid message UID value")
203 }
204 uids = append(uids, uid)
205 }
206 return uids, nil
207 }