forked from ProtonMail/proton-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rules.go
366 lines (318 loc) · 9.57 KB
/
rules.go
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (c) 2021 Proton Technologies AG
//
// This file is part of ProtonMail Bridge.
//
// ProtonMail Bridge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ProtonMail Bridge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ProtonMail Bridge. If not, see <https://www.gnu.org/licenses/>.
package transfer
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/ProtonMail/proton-bridge/pkg/pmapi"
"github.com/pkg/errors"
)
// transferRules maintains import rules, e.g. to which target mailbox should be
// source mailbox imported or what time spans.
type transferRules struct {
filePath string
// rules is map with key as hash of source mailbox to its rule.
// Every source mailbox should have rule, at least disabled one.
rules map[string]*Rule
// globalMailbox is applied to every message in the import phase.
// E.g., every message will be imported into this mailbox.
globalMailbox *Mailbox
// globalFromTime and globalToTime is applied to every rule right
// before the transfer (propagateGlobalTime has to be called).
globalFromTime int64
globalToTime int64
// skipEncryptedMessages determines whether message which cannot
// be decrypted should be imported/exported or skipped.
skipEncryptedMessages bool
}
// loadRules loads rules from `rulesPath` based on `ruleID`.
func loadRules(rulesPath, ruleID string) transferRules {
fileName := fmt.Sprintf("rules_%s.json", ruleID)
filePath := filepath.Join(rulesPath, fileName)
var rules map[string]*Rule
f, err := os.Open(filePath) //nolint[gosec]
if err != nil {
log.WithError(err).Debug("Problem to read rules")
} else {
defer f.Close() //nolint[errcheck]
if err := json.NewDecoder(f).Decode(&rules); err != nil {
log.WithError(err).Warn("Problem to umarshal rules")
}
}
if rules == nil {
rules = map[string]*Rule{}
}
return transferRules{
filePath: filePath,
rules: rules,
}
}
func (r *transferRules) setSkipEncryptedMessages(skip bool) {
r.skipEncryptedMessages = skip
}
func (r *transferRules) setGlobalMailbox(mailbox *Mailbox) {
r.globalMailbox = mailbox
}
func (r *transferRules) setGlobalTimeLimit(fromTime, toTime int64) {
r.globalFromTime = fromTime
r.globalToTime = toTime
}
func (r *transferRules) propagateGlobalTime() {
if r.globalFromTime == 0 && r.globalToTime == 0 {
return
}
for _, rule := range r.rules {
if !rule.HasTimeLimit() {
rule.FromTime = r.globalFromTime
rule.ToTime = r.globalToTime
}
}
}
func (r *transferRules) getRuleBySourceMailboxName(name string) (*Rule, error) {
for _, rule := range r.rules {
if rule.SourceMailbox.Name == name {
return rule, nil
}
}
return nil, fmt.Errorf("no rule for mailbox %s", name)
}
func (r *transferRules) iterateActiveRules() chan *Rule {
ch := make(chan *Rule)
go func() {
for _, rule := range r.rules {
if rule.Active {
ch <- rule
}
}
close(ch)
}()
return ch
}
// setDefaultRules iterates `sourceMailboxes` and sets missing rules with
// matching mailboxes from `targetMailboxes`. In case no matching mailbox
// is found, `defaultCallback` with a source mailbox as a parameter is used.
func (r *transferRules) setDefaultRules(sourceMailboxes []Mailbox, targetMailboxes []Mailbox, defaultCallback func(Mailbox) []Mailbox) {
for _, sourceMailbox := range sourceMailboxes {
h := sourceMailbox.Hash()
if _, ok := r.rules[h]; ok {
continue
}
targetMailboxes := sourceMailbox.findMatchingMailboxes(targetMailboxes)
if !containsExclusive(targetMailboxes) {
targetMailboxes = append(targetMailboxes, defaultCallback(sourceMailbox)...)
}
active := true
if len(targetMailboxes) == 0 {
active = false
}
// For both import to or export from ProtonMail, spam and draft
// mailboxes are by default deactivated.
for _, mailbox := range append([]Mailbox{sourceMailbox}, targetMailboxes...) {
if mailbox.ID == pmapi.SpamLabel || mailbox.ID == pmapi.DraftLabel || mailbox.ID == pmapi.TrashLabel {
active = false
break
}
}
r.rules[h] = &Rule{
Active: active,
SourceMailbox: sourceMailbox,
TargetMailboxes: targetMailboxes,
}
}
// There is no point showing rule which has no action (i.e., source mailbox
// is not available).
// A good reason to keep all rules and only deactivate them would be for
// multiple imports from different sources with the same or similar enough
// mailbox setup to reuse configuration. That is very minor feature which
// can be implemented in more reasonable way by allowing users to save and
// load configurations.
for key, rule := range r.rules {
found := false
for _, sourceMailbox := range sourceMailboxes {
if sourceMailbox.Name == rule.SourceMailbox.Name {
found = true
}
}
if !found {
delete(r.rules, key)
}
}
r.save()
}
// setRule sets messages from `sourceMailbox` between `fromData` and `toDate`
// (if used) to be imported to all `targetMailboxes`.
func (r *transferRules) setRule(sourceMailbox Mailbox, targetMailboxes []Mailbox, fromTime, toTime int64) error {
numberOfExclusiveMailboxes := 0
for _, mailbox := range targetMailboxes {
if mailbox.IsExclusive {
numberOfExclusiveMailboxes++
}
}
if numberOfExclusiveMailboxes > 1 {
return errors.New("rule can have only one exclusive target mailbox")
}
h := sourceMailbox.Hash()
r.rules[h] = &Rule{
Active: true,
SourceMailbox: sourceMailbox,
TargetMailboxes: targetMailboxes,
FromTime: fromTime,
ToTime: toTime,
}
r.save()
return nil
}
// unsetRule unsets messages from `sourceMailbox` to be exported.
func (r *transferRules) unsetRule(sourceMailbox Mailbox) {
h := sourceMailbox.Hash()
if rule, ok := r.rules[h]; ok {
rule.Active = false
} else {
r.rules[h] = &Rule{
Active: false,
SourceMailbox: sourceMailbox,
}
}
r.save()
}
// getRule returns rule for `sourceMailbox` or nil if it does not exist.
func (r *transferRules) getRule(sourceMailbox Mailbox) *Rule {
h := sourceMailbox.Hash()
return r.rules[h]
}
// getSortedRules returns all set rules in order by `byRuleOrder`.
func (r *transferRules) getSortedRules() []*Rule {
rules := []*Rule{}
for _, rule := range r.rules {
rules = append(rules, rule)
}
sort.Sort(byRuleOrder(rules))
return rules
}
// reset wipes our all rules.
func (r *transferRules) reset() {
r.rules = map[string]*Rule{}
r.save()
}
// save saves rules to file.
func (r *transferRules) save() {
f, err := os.Create(r.filePath)
if err != nil {
log.WithError(err).Warn("Problem to write rules")
return
}
defer f.Close() //nolint[errcheck]
if err := json.NewEncoder(f).Encode(r.rules); err != nil {
log.WithError(err).Warn("Problem to marshal rules")
}
}
// Rule is data holder of rule for one source mailbox used by `transferRules`.
type Rule struct {
Active bool `json:"active"`
SourceMailbox Mailbox `json:"source"`
TargetMailboxes []Mailbox `json:"targets"`
FromTime int64 `json:"from"`
ToTime int64 `json:"to"`
}
// String returns textual representation for log purposes.
func (r *Rule) String() string {
return fmt.Sprintf(
"%s -> %s (%d - %d)",
r.SourceMailbox.Name,
strings.Join(r.TargetMailboxNames(), ", "),
r.FromTime,
r.ToTime,
)
}
func (r *Rule) isTimeInRange(t int64) bool {
if !r.HasTimeLimit() {
return true
}
return r.FromTime <= t && t <= r.ToTime
}
// HasTimeLimit returns whether rule defines time limit.
func (r *Rule) HasTimeLimit() bool {
return r.FromTime != 0 || r.ToTime != 0
}
// FromDate returns time struct based on `FromTime`.
func (r *Rule) FromDate() time.Time {
return time.Unix(r.FromTime, 0)
}
// ToDate returns time struct based on `ToTime`.
func (r *Rule) ToDate() time.Time {
return time.Unix(r.ToTime, 0)
}
// TargetMailboxNames returns array of target mailbox names.
func (r *Rule) TargetMailboxNames() (names []string) {
for _, mailbox := range r.TargetMailboxes {
names = append(names, mailbox.Name)
}
return
}
// byRuleOrder implements sort.Interface. Sort order:
// * System folders first (as defined in getSystemMailboxes).
// * Custom folders by name.
// * Custom labels by name.
type byRuleOrder []*Rule
func (a byRuleOrder) Len() int {
return len(a)
}
func (a byRuleOrder) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a byRuleOrder) Less(i, j int) bool {
if a[i].SourceMailbox.IsExclusive && !a[j].SourceMailbox.IsExclusive {
return true
}
if !a[i].SourceMailbox.IsExclusive && a[j].SourceMailbox.IsExclusive {
return false
}
iSystemIndex := -1
jSystemIndex := -1
for index, systemFolders := range getSystemMailboxes(true) {
if a[i].SourceMailbox.Name == systemFolders.Name {
iSystemIndex = index
}
if a[j].SourceMailbox.Name == systemFolders.Name {
jSystemIndex = index
}
}
if iSystemIndex != -1 && jSystemIndex == -1 {
return true
}
if iSystemIndex == -1 && jSystemIndex != -1 {
return false
}
if iSystemIndex != -1 && jSystemIndex != -1 {
return iSystemIndex < jSystemIndex
}
return a[i].SourceMailbox.Name < a[j].SourceMailbox.Name
}
// containsExclusive returns true if there is at least one exclusive mailbox.
func containsExclusive(mailboxes []Mailbox) bool {
for _, m := range mailboxes {
if m.IsExclusive {
return true
}
}
return false
}