-
-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathmessages.js
4195 lines (3781 loc) · 173 KB
/
messages.js
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const config = require('wild-config');
const log = require('npmlog');
const libmime = require('libmime');
const Joi = require('joi');
const MongoPaging = require('mongo-cursor-pagination');
const addressparser = require('nodemailer/lib/addressparser');
const MailComposer = require('nodemailer/lib/mail-composer');
const { htmlToText } = require('html-to-text');
const ObjectId = require('mongodb').ObjectId;
const tools = require('../tools');
const consts = require('../consts');
const libbase64 = require('libbase64');
const libqp = require('libqp');
const forward = require('../forward');
const Maildropper = require('../maildropper');
const util = require('util');
const roles = require('../roles');
const { nextPageCursorSchema, previousPageCursorSchema, pageNrSchema, sessSchema, sessIPSchema, booleanSchema, metaDataSchema } = require('../schemas');
const { preprocessAttachments } = require('../data-url');
const TaskHandler = require('../task-handler');
const { prepareSearchFilter, uidRangeStringToQuery } = require('../prepare-search-filter');
const { getMongoDBQuery /*, getElasticSearchQuery*/ } = require('../search-query');
//const { getClient } = require('../elasticsearch');
let iconv = require('iconv-lite');
const BimiHandler = require('../bimi-handler');
const {
Address,
AddressOptionalNameArray,
Header,
Attachment,
ReferenceWithAttachments,
Bimi,
AddressOptionalName
} = require('../schemas/request/messages-schemas');
const { userId, mailboxId, messageId } = require('../schemas/request/general-schemas');
const { MsgEnvelope } = require('../schemas/response/messages-schemas');
const { successRes } = require('../schemas/response/general-schemas');
module.exports = (db, server, messageHandler, userHandler, storageHandler, settingsHandler) => {
let maildrop = new Maildropper({
db,
zone: config.sender.zone,
collection: config.sender.collection,
gfs: config.sender.gfs,
loopSecret: config.sender.loopSecret
});
const bimiHandler = BimiHandler.create({
database: db.database,
loggelf: message => server.loggelf(message)
});
const taskHandler = new TaskHandler({ database: db.database });
const putMessage = util.promisify(messageHandler.put.bind(messageHandler));
const updateMessage = util.promisify(messageHandler.update.bind(messageHandler));
const encryptMessage = util.promisify(messageHandler.encryptMessage.bind(messageHandler));
const getMailboxCounter = util.promisify(tools.getMailboxCounter);
const asyncForward = util.promisify(forward);
const addMessage = util.promisify((...args) => {
let callback = args.pop();
messageHandler.add(...args, (err, status, data) => {
if (err) {
return callback(err);
}
return callback(null, { status, data });
});
});
const moveMessage = util.promisify((...args) => {
let callback = args.pop();
messageHandler.move(...args, (err, result, info) => {
if (err) {
return callback(err);
}
return callback(null, { result, info });
});
});
const addThreadCountersToMessageList = async (user, list) => {
const threadIdsToCount = list.map(message => message.thread);
const threadCounts = await db.database
.collection('messages')
.aggregate([
{
$match: {
user: new ObjectId(user),
thread: { $in: threadIdsToCount }
}
},
{
$group: {
_id: '$thread',
count: {
$sum: 1
}
}
}
])
.toArray();
return list.map(message => {
const matchingThreadCount = threadCounts.find(thread => thread._id.toString() === message.thread.toString());
message.threadMessageCount = matchingThreadCount ? matchingThreadCount.count : undefined;
return message;
});
};
const applyBimiToListing = async messages => {
let bimiList = new Set();
for (let messageData of messages) {
if (
messageData.verificationResults &&
messageData.verificationResults.bimi &&
typeof messageData.verificationResults.bimi.toHexString === 'function'
) {
let bimiId = messageData.verificationResults.bimi.toString();
bimiList.add(bimiId);
}
}
if (bimiList.size) {
try {
let bimiEntries = await db.database
.collection('bimi')
.find({ _id: { $in: Array.from(bimiList).map(id => new ObjectId(id)) } })
.toArray();
for (let messageData of messages) {
if (messageData.verificationResults && messageData.verificationResults.bimi) {
let bimiData = bimiEntries.find(entry => entry._id.equals(messageData.verificationResults.bimi));
if (bimiData?.content && !bimiData?.error) {
messageData.bimi = {
certified: bimiData.type === 'authority',
url: bimiData.url,
image: `data:image/svg+xml;base64,${bimiData.content.toString('base64')}`,
type: bimiData.type === 'authority' ? bimiData.vmc?.type || 'VMC' : undefined
};
}
delete messageData.verificationResults.bimi;
}
}
} catch (err) {
log.error('BIMI', 'messages=%s error=%s', Array.from(bimiList).join(','), err.message);
}
}
};
const putMessageHandler = async (req, res) => {
res.charSet('utf-8');
const { requestBody, queryParams, pathParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...requestBody,
...queryParams,
...pathParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
if (result.value.metaData) {
if (typeof result.value.metaData === 'object') {
try {
result.value.metaData = JSON.stringify(result.value.metaData);
} catch (err) {
res.status(400);
return res.json({
error: 'metaData value must be serializable to JSON',
code: 'InputValidationError'
});
}
} else {
try {
let value = JSON.parse(result.value.metaData);
if (!value || typeof value !== 'object') {
throw new Error('Not an object');
}
} catch (err) {
res.status(400);
return res.json({
error: 'metaData value must be valid JSON object string',
code: 'InputValidationError'
});
}
}
}
// permissions check
if (req.user && req.user === result.value.user) {
req.validate(roles.can(req.role).updateOwn('messages'));
} else {
req.validate(roles.can(req.role).updateAny('messages'));
}
let user = new ObjectId(result.value.user);
let mailbox = new ObjectId(result.value.mailbox);
let moveTo = result.value.moveTo ? new ObjectId(result.value.moveTo) : false;
let message = result.value.message;
let messageQuery = uidRangeStringToQuery(message);
if (!messageQuery) {
res.status(404);
return res.json({
error: 'Invalid message identifier',
code: 'MessageNotFound'
});
}
if (moveTo) {
let info;
let lockKey = ['mbwr', mailbox.toString()].join(':');
let lock;
let extendLockIntervalTimer = null;
try {
const LOCK_TTL = 2 * 60 * 1000;
lock = await server.lock.waitAcquireLock(lockKey, LOCK_TTL, 1 * 60 * 1000);
if (!lock.success) {
throw new Error('Failed to get folder write lock');
}
log.verbose(
'API',
'Acquired lock for moving messages user=%s mailbox=%s message=%s moveTo=%s lock=%s',
user.toString(),
mailbox.toString(),
message,
moveTo,
lock.id
);
extendLockIntervalTimer = setInterval(() => {
server.lock
.extendLock(lock, LOCK_TTL)
.then(info => {
log.verbose('API', `Lock extended lock=${info.id} result=${info.success ? 'yes' : 'no'}`);
})
.catch(err => {
log.verbose('API', 'Failed to extend lock lock=%s error=%s', lock?.id, err.message);
});
}, Math.round(LOCK_TTL * 0.8));
} catch (err) {
res.status(500);
return res.json({
error: err.message,
code: err.code || 'LockFail'
});
}
try {
let data = await moveMessage({
user,
source: { user, mailbox },
destination: { user, mailbox: moveTo },
updates: result.value,
messageQuery
});
info = data.info;
} catch (err) {
res.status(500); // TODO: use response code specific status
return res.json({
error: err.message,
code: err.code
});
} finally {
clearInterval(extendLockIntervalTimer);
await server.lock.releaseLock(lock);
}
if (!info || !info.destinationUid || !info.destinationUid.length) {
res.status(404);
return res.json({
error: 'Could not move message, check if message exists',
code: 'MessageNotFound'
});
}
return res.json({
success: true,
mailbox: moveTo,
id: info && info.sourceUid && info.sourceUid.map((uid, i) => [uid, info.destinationUid && info.destinationUid[i]])
});
}
let updated;
try {
updated = await updateMessage(user, mailbox, messageQuery, result.value);
} catch (err) {
res.status(500); // TODO: use response code specific status
return res.json({
error: err.message,
code: err.code
});
}
if (!updated) {
res.status(404);
return res.json({
error: 'No message matched query',
code: 'MessageNotFound'
});
}
return res.json({
success: true,
updated
});
};
server.get(
{
path: '/users/:user/mailboxes/:mailbox/messages',
summary: 'List messages in a Mailbox',
name: 'getMessages',
description: 'Lists all messages in a mailbox',
validationObjs: {
requestBody: {},
pathParams: {
user: Joi.string().hex().lowercase().length(24).required().description('ID of the User'),
mailbox: Joi.string().hex().lowercase().length(24).required().description('ID of the Mailbox')
},
queryParams: {
unseen: booleanSchema.description('If true, then returns only unseen messages'),
metaData: booleanSchema.default(false).description('If true, then includes metaData in the response'),
threadCounters: booleanSchema
.default(false)
.description('If true, then includes threadMessageCount in the response. Counters come with some overhead'),
limit: Joi.number().empty('').default(20).min(1).max(250).description('How many records to return'),
order: Joi.any().empty('').allow('asc', 'desc').default('desc').description('Ordering of the records by insert date'),
next: nextPageCursorSchema,
previous: previousPageCursorSchema,
page: pageNrSchema,
sess: sessSchema,
ip: sessIPSchema,
includeHeaders: Joi.alternatives()
.try(Joi.string(), booleanSchema)
.description('Comma separated list of header keys to include in the response')
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: booleanSchema.description('Indicates successful response').required(),
total: Joi.number().description('How many results were found').required(),
page: Joi.number().description('Current page number. Derived from page query argument').required(),
previousCursor: Joi.alternatives()
.try(Joi.string(), booleanSchema)
.description('Either a cursor string or false if there are not any previous results')
.required(),
nextCursor: Joi.alternatives()
.try(Joi.string(), booleanSchema)
.description('Either a cursor string or false if there are not any next results')
.required(),
specialUse: Joi.string().description('Special use. If available').required(),
results: Joi.array()
.items(
Joi.object({
id: Joi.number().required().description('ID of the Message'),
mailbox: Joi.string().required().description('ID of the Mailbox'),
thread: Joi.string().required().description('ID of the Thread'),
threadMessageCount: Joi.number().description(
'Amount of messages in the Thread. Included if threadCounters query argument was true'
),
from: Address.description('Sender in From: field'),
to: Joi.array().items(Address).required().description('Recipients in To: field'),
cc: Joi.array().items(Address).required().description('Recipients in Cc: field'),
bcc: Joi.array().items(Address).required().description('Recipients in Bcc: field. Usually only available for drafts'),
messageId: Joi.string().required().description('Message ID'),
subject: Joi.string().required().description('Message subject'),
date: Joi.date().required().description('Date string from header'),
idate: Joi.date().description('Date string of receive time'),
intro: Joi.string().required().description('First 128 bytes of the message'),
attachments: booleanSchema.required().description('Does the message have attachments'),
attachmentsList: Joi.array()
.items(
Joi.object({
id: Joi.string().required().description('Attachment ID'),
hash: Joi.string().description('SHA-256 hash of the contents of the attachment'),
filename: Joi.string().required().description('Filename of the attachment'),
contentType: Joi.string().required().description('MIME type'),
disposition: Joi.string().required().description('Attachment disposition'),
transferEncoding: Joi.string()
.required()
.description(
'Which transfer encoding was used (actual content when fetching attachments is not encoded)'
),
related: booleanSchema
.required()
.description(
'Was this attachment found from a multipart/related node. This usually means that this is an embedded image'
),
sizeKb: Joi.number().required().description('Approximate size of the attachment in kilobytes')
})
)
.description('Attachments for the message'),
size: Joi.number().required().description('Message size in bytes'),
seen: booleanSchema.required().description('Is this message already seen or not'),
deleted: booleanSchema
.required()
.description(
'Does this message have a Deleted flag (should not have as messages are automatically deleted once this flag is set)'
),
flagged: booleanSchema.required().description('Does this message have a Flagged flag'),
draft: booleanSchema.required().description('is this message a draft'),
answered: booleanSchema.required().description('Does this message have a Answered flag'),
forwarded: booleanSchema.required().description('Does this message have a $Forwarded flag'),
references: Joi.array().items(ReferenceWithAttachments).required().description('References'),
bimi: Bimi.required().description(
'Marks BIMI verification as passed for a domain. NB! BIMI record and logo files for the domain must be valid.'
),
contentType: Joi.object({
value: Joi.string().required().description('MIME type of the message, eg. "multipart/mixed"'),
params: Joi.object().required().description('An object with Content-Type params as key-value pairs')
})
.$_setFlag('objectName', 'ContentType')
.required()
.description('Parsed Content-Type header. Usually needed to identify encrypted messages and such'),
encrypted: booleanSchema.description('Specifies whether the message is encrypted'),
metaData: Joi.object().description('Custom metadata value. Included if metaData query argument was true'),
headers: Joi.object().description('Header object keys requested with the includeHeaders argument')
}).$_setFlag('objectName', 'GetMessagesResult')
)
.required()
.description('Message listing')
}).$_setFlag('objectName', 'GetMessagesResponse')
}
}
},
tags: ['Messages']
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { requestBody, pathParams, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...requestBody,
...pathParams,
...queryParams
});
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
// permissions check
if (req.user && req.user === result.value.user) {
req.validate(roles.can(req.role).readOwn('messages'));
} else {
req.validate(roles.can(req.role).readAny('messages'));
}
let user = new ObjectId(result.value.user);
let mailbox = new ObjectId(result.value.mailbox);
let limit = result.value.limit;
let threadCounters = result.value.threadCounters;
let page = result.value.page;
let pageNext = result.value.next;
let pagePrevious = result.value.previous;
let sortAscending = result.value.order === 'asc';
let filterUnseen = result.value.unseen;
let includeHeaders = result.value.includeHeaders ? result.value.includeHeaders.split(',') : false;
let mailboxData;
try {
mailboxData = await db.database.collection('mailboxes').findOne(
{
_id: mailbox,
user
},
{
projection: {
path: true,
specialUse: true,
uidNext: true
}
}
);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
if (!mailboxData) {
res.status(404);
return res.json({
error: 'This mailbox does not exist',
code: 'NoSuchMailbox'
});
}
let filter = {
mailbox
};
if (filterUnseen) {
filter.unseen = true;
}
let total = await getFilteredMessageCount(filter);
let opts = {
limit,
query: filter,
fields: {
idate: true,
// FIXME: MongoPaging inserts fields value as second argument to col.find()
projection: {
_id: true,
uid: true,
msgid: true,
mailbox: true,
[result.value.metaData ? 'meta' : 'meta.from']: true,
'mimeTree.attachmentMap': true,
hdate: true,
idate: true,
subject: true,
ha: true,
attachments: true,
size: true,
intro: true,
unseen: true,
undeleted: true,
flagged: true,
draft: true,
thread: true,
flags: true,
verificationResults: true
}
},
paginatedField: 'idate',
sortAscending
};
if (includeHeaders) {
// get all headers
opts.fields.projection['mimeTree.parsedHeader'] = true;
} else {
// get only required headers
for (let requiredHeader of [
'mimeTree.parsedHeader.from',
'mimeTree.parsedHeader.sender',
'mimeTree.parsedHeader.to',
'mimeTree.parsedHeader.cc',
'mimeTree.parsedHeader.bcc',
'mimeTree.parsedHeader.content-type',
'mimeTree.parsedHeader.references'
]) {
opts.fields.projection[requiredHeader] = true;
}
}
if (pageNext) {
opts.next = pageNext;
} else if ((!page || page > 1) && pagePrevious) {
opts.previous = pagePrevious;
}
let listing;
try {
listing = await MongoPaging.find(db.database.collection('messages'), opts);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
if (!listing.hasPrevious) {
page = 1;
}
if (threadCounters) {
listing.results = await addThreadCountersToMessageList(user, listing.results);
}
await applyBimiToListing(listing.results);
let response = {
success: true,
total,
page,
previousCursor: listing.hasPrevious ? listing.previous : false,
nextCursor: listing.hasNext ? listing.next : false,
specialUse: mailboxData.specialUse,
results: (listing.results || []).map(entry => formatMessageListing(entry, includeHeaders))
};
return res.json(response);
})
);
const searchSchema = {
q: Joi.string().trim().empty('').max(1024).optional().description('Additional query string'),
mailbox: Joi.string().hex().length(24).empty('').description('ID of the Mailbox'),
id: Joi.string()
.trim()
.empty('')
.regex(/^\d+(,\d+)*$|^\d+:(\d+|\*)$/i)
.description(
'Message ID values, only applies when used in combination with `mailbox`. Either comma separated numbers (1,2,3) or colon separated range (3:15), or a range from UID to end (3:*)'
),
thread: Joi.string().hex().length(24).empty('').description('Thread ID'),
or: Joi.object({
query: Joi.string()
.trim()
.max(255)
.empty('')
.description('Search string, uses MongoDB fulltext index. Covers data from message body and also common headers like from, to, subject etc.'),
from: Joi.string().trim().empty('').description('Partial match for the From: header line'),
to: Joi.string().trim().empty('').description('Partial match for the To: and Cc: header lines'),
subject: Joi.string().trim().empty('').description('Partial match for the Subject: header line')
}).description('At least onOne of the included terms must match'),
query: Joi.string()
.trim()
.max(255)
.empty('')
.description('Search string, uses MongoDB fulltext index. Covers data from message body and also common headers like from, to, subject etc.'),
datestart: Joi.date().label('Start time').empty('').description('Datestring for the earliest message storing time'),
dateend: Joi.date().label('End time').empty('').description('Datestring for the latest message storing time'),
from: Joi.string().trim().empty('').description('Partial match for the From: header line'),
to: Joi.string().trim().empty('').description('Partial match for the To: and Cc: header lines'),
subject: Joi.string().trim().empty('').description('Partial match for the Subject: header line'),
minSize: Joi.number().empty('').description('Minimal message size in bytes'),
maxSize: Joi.number().empty('').description('Maximal message size in bytes'),
attachments: booleanSchema.description('If true, then matches only messages with attachments'),
flagged: booleanSchema.description('If true, then matches only messages with \\Flagged flags'),
unseen: booleanSchema.description('If true, then matches only messages without \\Seen flags'),
includeHeaders: Joi.string()
.max(1024)
.trim()
.empty('')
.example('List-ID, MIME-Version')
.description('Comma separated list of header keys to include in the response'),
searchable: booleanSchema.description('If true, then matches messages not in Junk or Trash'),
sess: sessSchema,
ip: sessIPSchema
};
server.get(
{
path: '/users/:user/search',
validationObjs: {
queryParams: {
...searchSchema,
...{
threadCounters: booleanSchema
.default(false)
.description('If true, then includes threadMessageCount in the response. Counters come with some overhead'),
limit: Joi.number().default(20).min(1).max(250).description('How many records to return'),
order: Joi.any()
.empty('')
.allow('asc', 'desc')
.optional()
.description('Ordering of the records by insert date. If no order is supplied, results are sorted by heir mongoDB ObjectId.'),
includeHeaders: Joi.string()
.max(1024)
.trim()
.empty('')
.example('List-ID, MIME-Version')
.description('Comma separated list of header keys to include in the response'),
next: nextPageCursorSchema,
previous: previousPageCursorSchema,
page: pageNrSchema
}
},
pathParams: { user: userId },
requestBody: {},
response: {
200: {
description: 'Success',
model: Joi.object({
success: booleanSchema.required().description('Indicates successful response'),
query: Joi.string().required('Query'),
total: Joi.number().required('How many results were found'),
page: Joi.number().required('Current page number. Derived from page query argument'),
previousCursor: Joi.alternatives()
.try(booleanSchema, Joi.string())
.required()
.description('Either a cursor string or false if there are not any previous results'),
nextCursor: Joi.alternatives()
.try(booleanSchema, Joi.string())
.required()
.description('Either a cursor string or false if there are not any next results'),
results: Joi.array()
.items(
Joi.object({
id: messageId,
mailbox: mailboxId,
messageId: Joi.string().required().description('The message ID'),
thread: Joi.string().required().description('ID of the Thread'),
threadMessageCount: Joi.number().description(
'Amount of messages in the Thread. Included if threadCounters query argument was true'
),
from: Address,
to: Joi.array().items(Address).required().description('Recipients in To: field'),
cc: Joi.array().items(Address).required().description('Recipients in Cc: field'),
bcc: Joi.array().items(Address).required().description('Recipients in Bcc: field. Usually only available for drafts'),
subject: Joi.string().required().description('Message subject'),
date: Joi.date().required().description('Date string from header'),
idate: Joi.date().description('Date string of receive time'),
size: Joi.number().required().description('Message size in bytes'),
intro: Joi.string().required().description('First 128 bytes of the message'),
attachments: booleanSchema.required().description('Does the message have attachments'),
seen: booleanSchema.required().description('Is this message already seen or not'),
deleted: booleanSchema
.required()
.description(
'Does this message have a \\Deleted flag (should not have as messages are automatically deleted once this flag is set)'
),
flagged: booleanSchema.required().description('Does this message have a \\Flagged flag'),
answered: booleanSchema.required().description('Does this message have a \\Answered flag'),
forwarded: booleanSchema.required().description('Does this message have a $Forwarded flag'),
draft: booleanSchema.description('True if message is a draft').required(),
contentType: Joi.object({
value: Joi.string().required().description('MIME type of the message, eg. "multipart/mixed"'),
params: Joi.object().required().description('An object with Content-Type params as key-value pairs')
})
.$_setFlag('objectName', 'ContentType')
.required()
.description('Parsed Content-Type header. Usually needed to identify encrypted messages and such'),
metadata: metaDataSchema.description('Custom metadata value. Included if metaData query argument was true'),
headers: Joi.object().description('Header object keys requested with the includeHeaders argument'),
encrypted: booleanSchema.description('True if message is encryrpted'),
references: Joi.array().items(ReferenceWithAttachments).required().description('References'),
bimi: Bimi.required().description(
'Marks BIMI verification as passed for a domain. NB! BIMI record and logo files for the domain must be valid.'
)
}).$_setFlag('objectName', 'GetMessagesResult')
)
.required()
.description('Message listing')
}).$_setFlag('objectName', 'SearchMessagesResponse')
}
}
},
summary: 'Search for messages',
description: 'This method allows searching for matching messages.',
tags: ['Messages'],
name: 'searchMessages'
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { requestBody, queryParams, pathParams } = req.route.spec.validationObjs;
const schema = Joi.object({ ...requestBody, ...queryParams, ...pathParams });
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
// permissions check
if (req.user && req.user === result.value.user) {
req.validate(roles.can(req.role).readOwn('messages'));
} else {
req.validate(roles.can(req.role).readAny('messages'));
}
let user = new ObjectId(result.value.user);
let threadCounters = result.value.threadCounters;
let limit = result.value.limit;
let page = result.value.page;
let pageNext = result.value.next;
let pagePrevious = result.value.previous;
let order = result.value.order;
let includeHeaders = result.value.includeHeaders ? result.value.includeHeaders.split(',') : false;
let filter;
let query;
if (result.value.q) {
let hasESFeatureFlag = await db.redis.sismember(`feature:indexing`, user.toString());
if (hasESFeatureFlag) {
// search from ElasticSearch
/*
// TODO: paging and cursors for ElasticSearch results
let searchQuery = await getElasticSearchQuery(db, user, result.value.q);
const esclient = getClient();
const searchOpts = {
index: config.elasticsearch.index,
body: { query: searchQuery, sort: { uid: 'desc' } }
};
let searchResult = await esclient.search(searchOpts);
const searchHits = searchResult && searchResult.body && searchResult.body.hits;
console.log('ES RESULTS');
console.log(util.inspect(searchResult, false, 22, true));
*/
}
filter = await getMongoDBQuery(db, user, result.value.q);
query = result.value.q;
} else {
let prepared = await prepareSearchFilter(db, user, result.value);
filter = prepared.filter;
query = prepared.query;
}
let total = await getFilteredMessageCount(filter);
log.verbose('API', 'Searching %s', JSON.stringify(filter));
let opts = {
limit,
query: filter,
fields: {
// FIXME: hack to keep _id in response
_id: true,
// FIXME: MongoPaging inserts fields value as second argument to col.find()
projection: {
_id: true,
uid: true,
msgid: true,
mailbox: true,
'meta.from': true,
hdate: true,
idate: true,
subject: true,
ha: true,
intro: true,
size: true,
unseen: true,
undeleted: true,
flagged: true,
draft: true,
thread: true,
flags: true,
verificationResults: true
}
},
paginatedField: order !== undefined ? 'idate' : '_id',
sortAscending: order === 'asc' ? true : undefined
};
if (includeHeaders) {
// get all headers
opts.fields.projection['mimeTree.parsedHeader'] = true;
} else {
// get only required headers
for (let requiredHeader of [
'mimeTree.parsedHeader.from',
'mimeTree.parsedHeader.sender',
'mimeTree.parsedHeader.to',
'mimeTree.parsedHeader.cc',
'mimeTree.parsedHeader.bcc',
'mimeTree.parsedHeader.content-type',
'mimeTree.parsedHeader.references'
]) {
opts.fields.projection[requiredHeader] = true;
}
}
if (pageNext) {
opts.next = pageNext;
} else if ((!page || page > 1) && pagePrevious) {
opts.previous = pagePrevious;
}
let listing;
try {
listing = await MongoPaging.find(db.database.collection('messages'), opts);
} catch (err) {
res.status(500);
return res.json({
error: 'MongoDB Error: ' + err.message,
code: 'InternalDatabaseError'
});
}
if (!listing.hasPrevious) {
page = 1;
}
if (threadCounters) {
listing.results = await addThreadCountersToMessageList(user, listing.results);
}
await applyBimiToListing(listing.results);
let response = {
success: true,
query,
total,
page,
previousCursor: listing.hasPrevious ? listing.previous : false,
nextCursor: listing.hasNext ? listing.next : false,
results: (listing.results || []).map(entry => formatMessageListing(entry, includeHeaders))
};
return res.json(response);
})
);
server.post(
{
name: 'searchApplyMessages',
path: '/users/:user/search',
summary: 'Search and update messages',
description:
'This method allows applying an action to all matching messages. This is an async method so that it will return immediately. Actual modifications are run in the background.',
tags: ['Messages'],
validationObjs: {
requestBody: {
...searchSchema,
...{
// actions to take on matching messages
action: Joi.object()
.keys({
moveTo: Joi.string().hex().lowercase().length(24).description('ID of the target Mailbox if you want to move messages'),
seen: booleanSchema.description('State of the \\Seen flag'),
flagged: booleanSchema.description('State of the \\Flagged flag')
})
.required()
.description('Define actions to take with matching messages')
}
},
queryParams: {},
pathParams: {
user: Joi.string().hex().lowercase().length(24).required()
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: booleanSchema.required().description('Indicates if the action succeeded or not'),
scheduled: Joi.string().required().description('ID of the scheduled operation'),
existing: booleanSchema.required().description('Indicates if the scheduled operation already exists')
}).$_setFlag('objectName', 'SearchApplyMessagesResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { pathParams, requestBody, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({ ...pathParams, ...requestBody, ...queryParams });
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: true
});