-
Notifications
You must be signed in to change notification settings - Fork 2
/
mailbox_counts.go
257 lines (225 loc) · 7.12 KB
/
mailbox_counts.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
// Copyright (c) 2022 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 store
import (
"bytes"
"encoding/json"
"sort"
"github.com/ljanyst/peroxide/pkg/pmapi"
"github.com/pkg/errors"
bolt "go.etcd.io/bbolt"
)
// GetCounts returns numbers of total and unread messages in this mailbox bucket.
func (storeMailbox *Mailbox) GetCounts() (total, unread, unseenSeqNum uint, err error) {
err = storeMailbox.db().View(func(tx *bolt.Tx) error {
total, unread, unseenSeqNum, err = storeMailbox.txGetCounts(tx)
return err
})
return
}
func (storeMailbox *Mailbox) txGetCounts(tx *bolt.Tx) (total, unread, unseenSeqNum uint, err error) {
// For total it would be enough to use `bolt.Bucket.Stats().KeyN` but
// we also need to retrieve the count of unread emails therefore we are
// looping all messages in this mailbox by `bolt.Cursor`
metaBucket := tx.Bucket(metadataBucket)
b := storeMailbox.txGetIMAPIDsBucket(tx)
c := b.Cursor()
imapID, apiID := c.First()
for ; imapID != nil; imapID, apiID = c.Next() {
total++
rawMsg := metaBucket.Get(apiID)
if rawMsg == nil {
return 0, 0, 0, ErrNoSuchAPIID
}
// Do not unmarshal whole JSON to speed up the looping.
// Instead, we assume it will contain JSON int field `Unread`
// where `1` means true (i.e. message is unread)
if bytes.Contains(rawMsg, []byte(`"Unread":1`)) {
if unseenSeqNum == 0 {
unseenSeqNum = total
}
unread++
}
}
return total, unread, unseenSeqNum, err
}
type mailboxCounts struct {
LabelID string
LabelName string
Color string
Order int
IsFolder bool
TotalOnAPI uint
UnreadOnAPI uint
}
func txGetCountsFromBucketOrNew(bkt *bolt.Bucket, labelID string) (*mailboxCounts, error) {
mc := &mailboxCounts{}
if mcJSON := bkt.Get([]byte(labelID)); mcJSON != nil {
if err := json.Unmarshal(mcJSON, mc); err != nil {
return nil, err
}
}
mc.LabelID = labelID // if it was empty before we need to set labelID
return mc, nil
}
func (mc *mailboxCounts) txWriteToBucket(bucket *bolt.Bucket) error {
mcJSON, err := json.Marshal(mc)
if err != nil {
return err
}
return bucket.Put([]byte(mc.LabelID), mcJSON)
}
func getSystemFolders() []*mailboxCounts {
return []*mailboxCounts{
{pmapi.InboxLabel, "INBOX", "#000", -1000, true, 0, 0},
{pmapi.SentLabel, "Sent", "#000", -9, true, 0, 0},
{pmapi.ArchiveLabel, "Archive", "#000", -8, true, 0, 0},
{pmapi.SpamLabel, "Spam", "#000", -7, true, 0, 0},
{pmapi.TrashLabel, "Trash", "#000", -6, true, 0, 0},
{pmapi.AllMailLabel, "All Mail", "#000", -5, true, 0, 0},
{pmapi.DraftLabel, "Drafts", "#000", -4, true, 0, 0},
}
}
// skipThisLabel decides to skip labelIDs that *are* pmapi system labels but *aren't* local system labels
// (i.e. if it's in `pmapi.SystemLabels` but not in `getSystemFolders` then we skip it, otherwise we don't).
func skipThisLabel(labelID string) bool {
switch labelID {
case pmapi.StarredLabel, pmapi.AllSentLabel, pmapi.AllDraftsLabel:
return true
}
return false
}
func sortByOrder(labels []*pmapi.Label) {
sort.Slice(labels, func(i, j int) bool {
return labels[i].Order < labels[j].Order
})
}
func (mc *mailboxCounts) getPMLabel() *pmapi.Label {
return &pmapi.Label{
ID: mc.LabelID,
Name: mc.LabelName,
Path: mc.LabelName,
Color: mc.Color,
Order: mc.Order,
Type: pmapi.LabelTypeMailbox,
Exclusive: pmapi.Boolean(mc.IsFolder),
}
}
// createOrUpdateMailboxCountsBuckets will not change the on-API-counts.
func (store *Store) createOrUpdateMailboxCountsBuckets(labels []*pmapi.Label) error {
// Don't forget about system folders.
// It should set label id, name, color, isFolder, total, unread.
tx := func(tx *bolt.Tx) error {
countsBkt := tx.Bucket(countsBucket)
for _, label := range labels {
// Skipping is probably not necessary.
if skipThisLabel(label.ID) {
continue
}
// Get current data.
mailbox, err := txGetCountsFromBucketOrNew(countsBkt, label.ID)
if err != nil {
return err
}
// Update mailbox info, but dont change on-API-counts.
mailbox.LabelName = label.Path
mailbox.Color = label.Color
mailbox.Order = label.Order
mailbox.IsFolder = bool(label.Exclusive)
// Write.
if err = mailbox.txWriteToBucket(countsBkt); err != nil {
return err
}
}
return nil
}
return store.db.Update(tx)
}
func (store *Store) getLabelsFromLocalStorage() ([]*pmapi.Label, error) {
countsOnAPI, err := store.getOnAPICounts()
if err != nil {
return nil, err
}
labels := []*pmapi.Label{}
for _, counts := range countsOnAPI {
labels = append(labels, counts.getPMLabel())
}
sortByOrder(labels)
return labels, nil
}
func (store *Store) getOnAPICounts() (counts []*mailboxCounts, err error) {
err = store.db.View(func(tx *bolt.Tx) error {
counts, err = store.txGetOnAPICounts(tx)
return err
})
return
}
func (store *Store) txGetOnAPICounts(tx *bolt.Tx) ([]*mailboxCounts, error) {
counts := []*mailboxCounts{}
c := tx.Bucket(countsBucket).Cursor()
for k, countsB := c.First(); k != nil; k, countsB = c.Next() {
l := store.log.WithField("key", string(k))
if countsB == nil {
err := errors.New("empty counts in DB")
l.WithError(err).Error("While getting local labels")
return nil, err
}
mbCounts := &mailboxCounts{}
if err := json.Unmarshal(countsB, mbCounts); err != nil {
l.WithError(err).Error("While unmarshaling local labels")
return nil, err
}
counts = append(counts, mbCounts)
}
return counts, nil
}
// createOrUpdateOnAPICounts will change only on-API-counts.
func (store *Store) createOrUpdateOnAPICounts(mailboxCountsOnAPI []*pmapi.MessagesCount) error {
store.log.Debug("Updating API counts")
tx := func(tx *bolt.Tx) error {
countsBkt := tx.Bucket(countsBucket)
for _, countsOnAPI := range mailboxCountsOnAPI {
if skipThisLabel(countsOnAPI.LabelID) {
continue
}
// Get current data.
counts, err := txGetCountsFromBucketOrNew(countsBkt, countsOnAPI.LabelID)
if err != nil {
return err
}
// Update only counts.
counts.TotalOnAPI = uint(countsOnAPI.Total)
counts.UnreadOnAPI = uint(countsOnAPI.Unread)
if err = counts.txWriteToBucket(countsBkt); err != nil {
return err
}
}
return nil
}
return store.db.Update(tx)
}
func (store *Store) removeMailboxCount(labelID string) error {
err := store.db.Update(func(tx *bolt.Tx) error {
return tx.Bucket(countsBucket).Delete([]byte(labelID))
})
if err != nil {
store.log.WithError(err).
WithField("labelID", labelID).
Warning("Cannot remove counts")
}
return err
}