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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
|
/**
* @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import flatMapDeep from 'lodash/fp/flatMapDeep'
import orderBy from 'lodash/fp/orderBy'
import {
andThen,
complement,
curry,
filter,
flatten,
gt,
head,
identity,
last,
map,
pipe,
prop,
propEq,
slice,
tap,
where,
} from 'ramda'
import { savePreference } from '../service/PreferenceService'
import {
create as createAccount,
deleteAccount,
fetch as fetchAccount,
fetchAll as fetchAllAccounts,
patch as patchAccount,
update as updateAccount,
updateSignature,
} from '../service/AccountService'
import {
create as createMailbox,
deleteMailbox,
fetchAll as fetchAllMailboxes,
markMailboxRead,
patchMailbox,
} from '../service/MailboxService'
import {
deleteMessage,
fetchEnvelope,
fetchEnvelopes,
fetchMessage,
setEnvelopeFlag,
syncEnvelopes,
fetchThread,
} from '../service/MessageService'
import { createAlias, deleteAlias } from '../service/AliasService'
import logger from '../logger'
import { normalizedEnvelopeListId } from './normalization'
import { showNewMessagesNotification } from '../service/NotificationService'
import { matchError } from '../errors/match'
import SyncIncompleteError from '../errors/SyncIncompleteError'
import MailboxLockedError from '../errors/MailboxLockedError'
import { wait } from '../util/wait'
import { UNIFIED_INBOX_ID } from './constants'
const PAGE_SIZE = 20
const sliceToPage = slice(0, PAGE_SIZE)
const findIndividualMailboxes = curry((getMailboxes, specialRole) =>
pipe(
filter(complement(prop('isUnified'))),
map(prop('id')),
map(getMailboxes),
flatten,
filter(propEq('specialRole', specialRole))
)
)
const combineEnvelopeLists = pipe(flatten, orderBy(prop('dateInt'), 'desc'))
export default {
savePreference({ commit, getters }, { key, value }) {
return savePreference(key, value).then(({ value }) => {
commit('savePreference', {
key,
value,
})
})
},
fetchAccounts({ commit, getters }) {
return fetchAllAccounts().then((accounts) => {
accounts.forEach((account) => commit('addAccount', account))
return getters.accounts
})
},
fetchAccount({ commit }, id) {
return fetchAccount(id).then((account) => {
commit('addAccount', account)
return account
})
},
createAccount({ commit }, config) {
return createAccount(config).then((account) => {
logger.debug(`account ${account.id} created, fetching mailboxes …`, account)
return fetchAllMailboxes(account.id)
.then((mailboxes) => {
account.mailboxes = mailboxes
commit('addAccount', account)
})
.then(() => console.info("new account's mailboxes fetched"))
.then(() => account)
})
},
updateAccount({ commit }, config) {
return updateAccount(config).then((account) => {
console.debug('account updated', account)
commit('editAccount', account)
return account
})
},
patchAccount({ commit }, { account, data }) {
return patchAccount(account, data).then((account) => {
console.debug('account patched', account, data)
commit('patchAccount', { account, data })
return account
})
},
updateAccountSignature({ commit }, { account, signature }) {
return updateSignature(account, signature).then(() => {
console.debug('account signature updated')
const updated = Object.assign({}, account, { signature })
commit('editAccount', updated)
return account
})
},
deleteAccount({ commit }, account) {
return deleteAccount(account.id).catch((err) => {
console.error('could not delete account', err)
throw err
})
},
async deleteMailbox({ commit }, { mailbox }) {
await deleteMailbox(mailbox.databaseId)
commit('removeMailbox', { id: mailbox.databaseId })
},
async createMailbox({ commit }, { account, name }) {
const prefixed = (account.personalNamespace && !name.startsWith(account.personalNamespace))
? account.personalNamespace + name
: name
const mailbox = await createMailbox(account.id, prefixed)
console.debug(`mailbox ${prefixed} created for account ${account.id}`, { mailbox })
commit('addMailbox', { account, mailbox })
commit('expandAccount', account.id)
return mailbox
},
moveAccount({ commit, getters }, { account, up }) {
const accounts = getters.accounts
const index = accounts.indexOf(account)
if (up) {
const previous = accounts[index - 1]
accounts[index - 1] = account
accounts[index] = previous
} else {
const next = accounts[index + 1]
accounts[index + 1] = account
accounts[index] = next
}
return Promise.all(
accounts.map((account, idx) => {
if (account.id === 0) {
return
}
commit('saveAccountsOrder', { account, order: idx })
return patchAccount(account, { order: idx })
})
)
},
markMailboxRead({ getters, dispatch }, { accountId, mailboxId }) {
const mailbox = getters.getMailbox(mailboxId)
if (mailbox.isUnified) {
const findIndividual = findIndividualMailboxes(getters.getMailboxes, mailbox.specialRole)
const individualMailboxes = findIndividual(getters.accounts)
return Promise.all(
individualMailboxes.map((mb) =>
dispatch('markMailboxRead', {
accountId: mb.accountId,
mailboxId: mb.databaseId,
})
)
)
}
return markMailboxRead(mailboxId).then(
dispatch('syncEnvelopes', {
accountId,
mailboxId,
})
)
},
async changeMailboxSubscription({ commit }, { mailbox, subscribed }) {
logger.debug(`toggle subscription for mailbox ${mailbox.databaseId}`, {
mailbox,
subscribed,
})
const updated = await patchMailbox(mailbox.databaseId, { subscribed })
commit('updateMailbox', {
mailbox: updated,
})
logger.debug(`subscription for mailbox ${mailbox.databaseId} updated`, {
mailbox,
updated,
})
},
async fetchEnvelope({ commit, getters }, id) {
const cached = getters.getEnvelope(id)
if (cached) {
logger.debug(`using cached value for envelope ${id}`)
return cached
}
const envelope = await fetchEnvelope(id)
// Only commit if not undefined (not found)
if (envelope) {
commit('addEnvelope', {
envelope,
})
}
// Always use the object from the store
return getters.getEnvelope(id)
},
fetchEnvelopes({ state, commit, getters, dispatch }, { mailboxId, query }) {
const mailbox = getters.getMailbox(mailboxId)
if (mailbox.isUnified) {
const fetchIndividualLists = pipe(
map((mb) =>
dispatch('fetchEnvelopes', {
mailboxId: mb.databaseId,
query,
})
),
Promise.all.bind(Promise),
andThen(map(sliceToPage))
)
const fetchUnifiedEnvelopes = pipe(
findIndividualMailboxes(getters.getMailboxes, mailbox.specialRole),
fetchIndividualLists,
andThen(combineEnvelopeLists),
andThen(sliceToPage),
andThen(
tap(
map((envelope) =>
commit('addEnvelope', {
envelope,
query,
})
)
)
)
)
return fetchUnifiedEnvelopes(getters.accounts)
}
return pipe(
fetchEnvelopes,
andThen(
tap(
map((envelope) =>
commit('addEnvelope', {
query,
envelope,
})
)
)
)
)(mailboxId, query, undefined, PAGE_SIZE)
},
fetchNextEnvelopePage({ commit, getters, dispatch }, { mailboxId, query, rec = true }) {
const mailbox = getters.getMailbox(mailboxId)
if (mailbox.isUnified) {
const getIndivisualLists = curry((query, m) => getters.getEnvelopes(m.databaseId, query))
const individualCursor = curry((query, m) =>
prop('dateInt', last(getters.getEnvelopes(m.databaseId, query)))
)
const cursor = individualCursor(query, mailbox)
if (cursor === undefined) {
throw new Error('Unified list has no tail')
}
const nextLocalUnifiedEnvelopePage = pipe(
findIndividualMailboxes(getters.getMailboxes, mailbox.specialRole),
map(getIndivisualLists(query)),
combineEnvelopeLists,
filter(
where({
dateInt: gt(cursor),
})
),
sliceToPage
)
// We know the next page based on local data
// We have to fetch individual pages only if the page ends in the known
// next page. If it ended before, there is no data to fetch anyway. If
// it ends after, we have all the relevant data already
const needsFetch = curry((query, nextPage, f) => {
const c = individualCursor(query, f)
return nextPage.length < PAGE_SIZE || (c <= head(nextPage).dateInt && c >= last(nextPage).dateInt)
})
const mailboxesToFetch = (accounts) =>
pipe(
findIndividualMailboxes(getters.getMailboxes, mailbox.specialRole),
filter(needsFetch(query, nextLocalUnifiedEnvelopePage(accounts)))
)(accounts)
const mbs = mailboxesToFetch(getters.accounts)
if (rec && mbs.length) {
return pipe(
map((mb) =>
dispatch('fetchNextEnvelopePage', {
mailboxId: mb.databaseId,
query,
})
),
Promise.all.bind(Promise),
andThen(() =>
dispatch('fetchNextEnvelopePage', {
mailboxId,
query,
rec: false,
})
)
)(mbs)
}
const page = nextLocalUnifiedEnvelopePage(getters.accounts)
page.map((envelope) =>
commit('addEnvelope', {
query,
envelope,
})
)
return page
}
const list = mailbox.envelopeLists[normalizedEnvelopeListId(query)]
if (list === undefined) {
console.warn("envelope list is not defined, can't fetch next page", mailboxId, query)
return Promise.resolve([])
}
const lastEnvelopeId = last(list)
if (typeof lastEnvelopeId === 'undefined') {
console.error('mailbox is empty', list)
return Promise.reject(new Error('Local mailbox has no envelopes, cannot determine cursor'))
}
const lastEnvelope = getters.getEnvelope(lastEnvelopeId)
if (typeof lastEnvelope === 'undefined') {
return Promise.reject(new Error('Cannot find last envelope. Required for the mailbox cursor'))
}
return fetchEnvelopes(mailboxId, query, lastEnvelope.dateInt, PAGE_SIZE).then((envelopes) => {
logger.debug(`fetched ${envelopes.length} messages for the next page of mailbox ${mailboxId}`, {
envelopes,
})
envelopes.forEach((envelope) =>
commit('addEnvelope', {
query,
envelope,
})
)
return envelopes
})
},
syncEnvelopes({ commit, getters, dispatch }, { mailboxId, query, init = false }) {
const mailbox = getters.getMailbox(mailboxId)
if (mailbox.isUnified) {
return Promise.all(
getters.accounts
.filter((account) => !account.isUnified)
.map((account) =>
Promise.all(
getters
.getMailboxes(account.id)
.filter((mb) => mb.specialRole === mailbox.specialRole)
.map((mailbox) =>
dispatch('syncEnvelopes', {
mailboxId: mailbox.databaseId,
query,
init,
})
)
)
)
)
} else if (mailbox.isPriorityInbox && query === undefined) {
return Promise.all(
getters.accounts
.filter((account) => !account.isUnified)
.map((account) =>
Promise.all(
getters
.getMailboxes(account.id)
.filter((mb) => mb.specialRole === mailbox.specialRole)
.map((mailbox) =>
dispatch('syncEnvelopes', {
mailboxId: mailbox.databaseId,
query,
init,
})
)
)
)
)
}
const ids = getters.getEnvelopes(mailboxId, query).map((env) => env.databaseId)
return syncEnvelopes(mailbox.accountId, mailboxId, ids, query, init)
.then((syncData) => {
logger.info(`mailbox ${mailboxId} synchronized, ${syncData.newMessages.length} new, ${syncData.changedMessages.length} changed and ${syncData.vanishedMessages.length} vanished messages`)
const unifiedMailbox = getters.getUnifiedMailbox(mailbox.specialRole)
syncData.newMessages.forEach((envelope) => {
commit('addEnvelope', {
envelope,
query,
})
if (unifiedMailbox) {
commit('updateEnvelope', {
envelope,
})
}
})
syncData.changedMessages.forEach((envelope) => {
commit('updateEnvelope', {
envelope,
})
})
syncData.vanishedMessages.forEach((id) => {
commit('removeEnvelope', {
id,
})
// Already removed from unified inbox
})
return syncData.newMessages
})
.catch((error) => {
return matchError(error, {
[SyncIncompleteError.getName()]() {
console.warn('(initial) sync is incomplete, retriggering')
return dispatch('syncEnvelopes', { mailboxId, query, init })
},
[MailboxLockedError.getName()](error) {
logger.info('Sync failed because the mailbox is locked, retriggering', { error })
return wait(1500).then(() => dispatch('syncEnvelopes', { mailboxId, query, init }))
},
default(error) {
console.error('Could not sync envelopes: ' + error.message, error)
},
})
})
},
async syncInboxes({ getters, dispatch }) {
const results = await Promise.all(
getters.accounts
.filter((a) => !a.isUnified)
.map((account) => {
return Promise.all(
getters.getMailboxes(account.id).map(async(mailbox) => {
if (mailbox.specialRole !== 'inbox') {
return
}
const list = mailbox.envelopeLists[normalizedEnvelopeListId(undefined)]
if (list === undefined) {
await dispatch('fetchEnvelopes', {
mailboxId: mailbox.databaseId,
})
}
return await dispatch('syncEnvelopes', {
mailboxId: mailbox.databaseId,
})
})
)
})
)
const newMessages = flatMapDeep(identity, results).filter((m) => m !== undefined)
if (newMessages.length === 0) {
return
}
try {
// Make sure the priority inbox is updated as well
logger.info('updating priority inbox')
for (const query of ['is:important not:starred', 'is:starred not:important', 'not:starred not:important']) {
logger.info("sync'ing priority inbox section", { query })
const mailbox = getters.getMailbox(UNIFIED_INBOX_ID)
const list = mailbox.envelopeLists[normalizedEnvelopeListId(query)]
if (list === undefined) {
await dispatch('fetchEnvelopes', {
mailboxId: UNIFIED_INBOX_ID,
query,
})
}
await dispatch('syncEnvelopes', {
mailboxId: UNIFIED_INBOX_ID,
query,
})
}
} finally {
showNewMessagesNotification(newMessages)
}
},
toggleEnvelopeFlagged({ commit, getters }, envelope) {
// Change immediately and switch back on error
const oldState = envelope.flags.flagged
commit('flagEnvelope', {
envelope,
flag: 'flagged',
value: !oldState,
})
setEnvelopeFlag(envelope.databaseId, 'flagged', !oldState).catch((e) => {
console.error('could not toggle message flagged state', e)
// Revert change
commit('flagEnvelope', {
envelope,
flag: 'flagged',
value: oldState,
})
})
},
toggleEnvelopeImportant({ commit, getters }, envelope) {
// Change immediately and switch back on error
const oldState = envelope.flags.important
commit('flagEnvelope', {
envelope,
flag: 'important',
value: !oldState,
})
setEnvelopeFlag(envelope.databaseId, 'important', !oldState).catch((e) => {
console.error('could not toggle message important state', e)
// Revert change
commit('flagEnvelope', {
envelope,
flag: 'important',
value: oldState,
})
})
},
toggleEnvelopeSeen({ commit, getters }, envelope) {
// Change immediately and switch back on error
const oldState = envelope.flags.seen
commit('flagEnvelope', {
envelope,
flag: 'seen',
value: !oldState,
})
setEnvelopeFlag(envelope.databaseId, 'seen', !oldState).catch((e) => {
console.error('could not toggle message seen state', e)
// Revert change
commit('flagEnvelope', {
envelope,
flag: 'seen',
value: oldState,
})
})
},
toggleEnvelopeJunk({ commit, getters }, envelope) {
// Change immediately and switch back on error
const oldState = envelope.flags.junk
commit('flagEnvelope', {
envelope,
flag: 'junk',
value: !oldState,
})
setEnvelopeFlag(envelope.databaseId, 'junk', !oldState).catch((e) => {
console.error('could not toggle message junk state', e)
// Revert change
commit('flagEnvelope', {
envelope,
flag: 'junk',
value: oldState,
})
})
},
markEnvelopeFavoriteOrUnfavorite({ commit, getters }, { envelope, favFlag }) {
// Change immediately and switch back on error
const oldState = envelope.flags.flagged
commit('flagEnvelope', {
envelope,
flag: 'flagged',
value: favFlag,
})
setEnvelopeFlag(envelope.databaseId, 'flagged', favFlag).catch((e) => {
console.error('could not favorite/unfavorite message ' + envelope.uid, e)
// Revert change
commit('flagEnvelope', {
envelope,
flag: 'flagged',
value: oldState,
})
})
},
markEnvelopeSeenOrUnseen({ commit, getters }, { envelope, seenFlag }) {
// Change immediately and switch back on error
const oldState = envelope.flags.unseen
commit('flagEnvelope', {
envelope,
flag: 'unseen',
value: seenFlag,
})
setEnvelopeFlag(envelope.databaseId, 'unseen', seenFlag).catch((e) => {
console.error('could not mark message ' + envelope.uid + ' seen/unseen', e)
// Revert change
commit('flagEnvelope', {
envelope,
flag: 'unseen',
value: oldState,
})
})
},
async fetchThread({ getters, commit }, id) {
const thread = await fetchThread(id)
commit('addEnvelopeThread', {
id,
thread,
})
return thread
},
async fetchMessage({ getters, commit }, id) {
const message = await fetchMessage(id)
// Only commit if not undefined (not found)
if (message) {
commit('addMessage', {
message,
})
}
return message
},
async deleteMessage({ getters, commit }, { id }) {
commit('removeEnvelope', { id })
try {
await deleteMessage(id)
commit('removeMessage', { id })
console.debug('message removed')
} catch (err) {
console.error('could not delete message', err)
const envelope = getters.getEnvelope(id)
if (envelope) {
commit('addEnvelope', { envelope })
} else {
logger.error('could not find envelope', { id })
}
throw err
}
},
async createAlias({ commit }, { account, aliasToAdd }) {
const alias = await createAlias(account, aliasToAdd)
commit('createAlias', { account, alias })
},
async deleteAlias({ commit }, { account, aliasToDelete }) {
await deleteAlias(account, aliasToDelete)
commit('deleteAlias', { account, alias: aliasToDelete })
},
async renameMailbox({ commit }, { account, mailbox, newName }) {
const newMailbox = await patchMailbox(mailbox.databaseId, {
name: newName,
})
console.debug(`mailbox ${mailbox.databaseId} renamed to ${newName}`, { mailbox })
commit('removeMailbox', { id: mailbox.databaseId })
commit('addMailbox', { account, mailbox: newMailbox })
},
}
|