forked from emailjs/emailjs-imap-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
browserbox.js
2254 lines (1958 loc) · 78.5 KB
/
browserbox.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
// Copyright (c) 2014 Andris Reinman
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
(function(root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['browserbox-imap', 'utf7', 'imap-handler', 'mimefuncs', 'addressparser', 'axe'], function(ImapClient, utf7, imapHandler, mimefuncs, addressparser, axe) {
return factory(ImapClient, utf7, imapHandler, mimefuncs, addressparser, axe);
});
} else if (typeof exports === 'object') {
module.exports = factory(require('./browserbox-imap'), require('wo-utf7'), require('wo-imap-handler'), require('mimefuncs'), require('wo-addressparser'), require('axe-logger'));
} else {
root.BrowserBox = factory(root.BrowserboxImapClient, root.utf7, root.imapHandler, root.mimefuncs, root.addressparser, root.axe);
}
}(this, function(ImapClient, utf7, imapHandler, mimefuncs, addressparser, axe) {
'use strict';
var DEBUG_TAG = 'browserbox';
var SPECIAL_USE_FLAGS = ['\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash'];
var SPECIAL_USE_BOXES = {
'\\Sent': ['aika', 'bidaliak', 'bidalita', 'dihantar', 'e rometsweng', 'e tindami', 'elküldött', 'elküldöttek', 'enviadas', 'enviadas', 'enviados', 'enviats', 'envoyés', 'ethunyelweyo', 'expediate', 'ezipuru', 'gesendete', 'gestuur', 'gönderilmiş öğeler', 'göndərilənlər', 'iberilen', 'inviati', 'išsiųstieji', 'kuthunyelwe', 'lasa', 'lähetetyt', 'messages envoyés', 'naipadala', 'nalefa', 'napadala', 'nosūtītās ziņas', 'odeslané', 'padala', 'poslane', 'poslano', 'poslano', 'poslané', 'poslato', 'saadetud', 'saadetud kirjad', 'sendt', 'sendt', 'sent', 'sent items', 'sent messages', 'sända poster', 'sänt', 'terkirim', 'ti fi ranṣẹ', 'të dërguara', 'verzonden', 'vilivyotumwa', 'wysłane', 'đã gửi', 'σταλθέντα', 'жиберилген', 'жіберілгендер', 'изпратени', 'илгээсэн', 'ирсол шуд', 'испратено', 'надіслані', 'отправленные', 'пасланыя', 'юборилган', 'ուղարկված', 'נשלחו', 'פריטים שנשלחו', 'المرسلة', 'بھیجے گئے', 'سوزمژہ', 'لېګل شوی', 'موارد ارسال شده', 'पाठविले', 'पाठविलेले', 'प्रेषित', 'भेजा गया', 'প্রেরিত', 'প্রেরিত', 'প্ৰেৰিত', 'ਭੇਜੇ', 'મોકલેલા', 'ପଠାଗଲା', 'அனுப்பியவை', 'పంపించబడింది', 'ಕಳುಹಿಸಲಾದ', 'അയച്ചു', 'යැවු පණිවුඩ', 'ส่งแล้ว', 'გაგზავნილი', 'የተላኩ', 'បានផ្ញើ', '寄件備份', '寄件備份', '已发信息', '送信済みメール', '발신 메시지', '보낸 편지함'],
'\\Trash': ['articole șterse', 'bin', 'borttagna objekt', 'deleted', 'deleted items', 'deleted messages', 'elementi eliminati', 'elementos borrados', 'elementos eliminados', 'gelöschte objekte', 'item dipadam', 'itens apagados', 'itens excluídos', 'mục đã xóa', 'odstraněné položky', 'pesan terhapus', 'poistetut', 'praht', 'prügikast', 'silinmiş öğeler', 'slettede beskeder', 'slettede elementer', 'trash', 'törölt elemek', 'usunięte wiadomości', 'verwijderde items', 'vymazané správy', 'éléments supprimés', 'видалені', 'жойылғандар', 'удаленные', 'פריטים שנמחקו', 'العناصر المحذوفة', 'موارد حذف شده', 'รายการที่ลบ', '已删除邮件', '已刪除項目', '已刪除項目'],
'\\Junk': ['bulk mail', 'correo no deseado', 'courrier indésirable', 'istenmeyen', 'istenmeyen e-posta', 'junk', 'levélszemét', 'nevyžiadaná pošta', 'nevyžádaná pošta', 'no deseado', 'posta indesiderata', 'pourriel', 'roskaposti', 'skräppost', 'spam', 'spam', 'spamowanie', 'søppelpost', 'thư rác', 'спам', 'דואר זבל', 'الرسائل العشوائية', 'هرزنامه', 'สแปม', '垃圾郵件', '垃圾邮件', '垃圾電郵'],
'\\Drafts': ['ba brouillon', 'borrador', 'borrador', 'borradores', 'bozze', 'brouillons', 'bản thảo', 'ciorne', 'concepten', 'draf', 'drafts', 'drög', 'entwürfe', 'esborranys', 'garalamalar', 'ihe edeturu', 'iidrafti', 'izinhlaka', 'juodraščiai', 'kladd', 'kladder', 'koncepty', 'koncepty', 'konsep', 'konsepte', 'kopie robocze', 'layihələr', 'luonnokset', 'melnraksti', 'meralo', 'mesazhe të padërguara', 'mga draft', 'mustandid', 'nacrti', 'nacrti', 'osnutki', 'piszkozatok', 'rascunhos', 'rasimu', 'skice', 'taslaklar', 'tsararrun saƙonni', 'utkast', 'vakiraoka', 'vázlatok', 'zirriborroak', 'àwọn àkọpamọ́', 'πρόχειρα', 'жобалар', 'нацрти', 'нооргууд', 'сиёҳнавис', 'хомаки хатлар', 'чарнавікі', 'чернетки', 'чернови', 'черновики', 'черновиктер', 'սևագրեր', 'טיוטות', 'مسودات', 'مسودات', 'موسودې', 'پیش نویسها', 'ڈرافٹ/', 'ड्राफ़्ट', 'प्रारूप', 'খসড়া', 'খসড়া', 'ড্ৰাফ্ট', 'ਡ੍ਰਾਫਟ', 'ડ્રાફ્ટસ', 'ଡ୍ରାଫ୍ଟ', 'வரைவுகள்', 'చిత్తు ప్రతులు', 'ಕರಡುಗಳು', 'കരടുകള്', 'කෙටුම් පත්', 'ฉบับร่าง', 'მონახაზები', 'ረቂቆች', 'សារព្រាង', '下書き', '草稿', '草稿', '草稿', '임시 보관함']
};
var SPECIAL_USE_BOX_FLAGS = Object.keys(SPECIAL_USE_BOXES);
var SESSIONCOUNTER = 0;
/**
* High level IMAP client
*
* @constructor
*
* @param {String} [host='localhost'] Hostname to conenct to
* @param {Number} [port=143] Port number to connect to
* @param {Object} [options] Optional options object
*/
function BrowserBox(host, port, options) {
this.options = options || {};
// Session identified used for logging
this.options.sessionId = this.options.sessionId || '[' + (++SESSIONCOUNTER) + ']';
/**
* List of extensions the server supports
*/
this.capability = [];
/**
* Server ID (rfc2971) as key value pairs
*/
this.serverId = false;
/**
* Current state
*/
this.state = false;
/**
* Is the connection authenticated
*/
this.authenticated = false;
/**
* Selected mailbox
*/
this.selectedMailbox = false;
/**
* IMAP client object
*/
this.client = new ImapClient(host, port, this.options);
this._enteredIdle = false;
this._idleTimeout = false;
this._init();
}
// State constants
BrowserBox.prototype.STATE_CONNECTING = 1;
BrowserBox.prototype.STATE_NOT_AUTHENTICATED = 2;
BrowserBox.prototype.STATE_AUTHENTICATED = 3;
BrowserBox.prototype.STATE_SELECTED = 4;
BrowserBox.prototype.STATE_LOGOUT = 5;
// Timeout constants
/**
* Milliseconds to wait for the greeting from the server until the connection is considered failed
*/
BrowserBox.prototype.TIMEOUT_CONNECTION = 90 * 1000;
/**
* Milliseconds between NOOP commands while idling
*/
BrowserBox.prototype.TIMEOUT_NOOP = 60 * 1000;
/**
* Milliseconds until IDLE command is cancelled
*/
BrowserBox.prototype.TIMEOUT_IDLE = 60 * 1000;
/**
* Initialization method. Setup event handlers and such
*/
BrowserBox.prototype._init = function() {
// proxy error events
this.client.onerror = function(err) {
this.onerror(err);
}.bind(this);
// allows certificate handling for platforms w/o native tls support
this.client.oncert = function(cert) {
this.oncert(cert);
}.bind(this);
// proxy close events
this.client.onclose = function() {
clearTimeout(this._connectionTimeout);
clearTimeout(this._idleTimeout);
this.onclose();
}.bind(this);
// handle ready event which is fired when server has sent the greeting
this.client.onready = this._onReady.bind(this);
// start idling
this.client.onidle = this._onIdle.bind(this);
// set default handlers for untagged responses
// capability updates
this.client.setHandler('capability', this._untaggedCapabilityHandler.bind(this));
// notifications
this.client.setHandler('ok', this._untaggedOkHandler.bind(this));
// message count has changed
this.client.setHandler('exists', this._untaggedExistsHandler.bind(this));
// message has been deleted
this.client.setHandler('expunge', this._untaggedExpungeHandler.bind(this));
// message has been updated (eg. flag change), not supported by gmail
this.client.setHandler('fetch', this._untaggedFetchHandler.bind(this));
};
// Event placeholders
BrowserBox.prototype.onclose = function() {};
BrowserBox.prototype.onauth = function() {};
BrowserBox.prototype.onupdate = function() {};
BrowserBox.prototype.oncert = function() {};
/* BrowserBox.prototype.onerror = function(err){}; // not defined by default */
BrowserBox.prototype.onselectmailbox = function() {};
BrowserBox.prototype.onclosemailbox = function() {};
// Event handlers
/**
* Connection to the server is closed. Proxies to 'onclose'.
*
* @event
*/
BrowserBox.prototype._onClose = function() {
axe.debug(DEBUG_TAG, this.options.sessionId + ' connection closed. goodbye.');
this.onclose();
};
/**
* Connection to the server was not established. Proxies to 'onerror'.
*
* @event
*/
BrowserBox.prototype._onTimeout = function() {
clearTimeout(this._connectionTimeout);
var error = new Error(this.options.sessionId + ' Timeout creating connection to the IMAP server');
axe.error(DEBUG_TAG, error);
this.onerror(error);
this.client._destroy();
};
/**
* Connection to the server is established. Method performs initial
* tasks like updating capabilities and authenticating the user
*
* @event
*/
BrowserBox.prototype._onReady = function() {
clearTimeout(this._connectionTimeout);
axe.debug(DEBUG_TAG, this.options.sessionId + ' session: connection established');
this._changeState(this.STATE_NOT_AUTHENTICATED);
this.updateCapability(function() {
this.upgradeConnection(function(err) {
if (err) {
// emit an error
this.onerror(err);
this.close();
return;
}
this.updateId(this.options.id, function() {
// ignore errors for exchanging ID values
this.login(this.options.auth, function(err) {
if (err) {
// emit an error
this.onerror(err);
this.close();
return;
}
// can't setup compression before authnetication
this.compressConnection(function() {
// ignore errors for setting up compression
// emit
this.onauth();
}.bind(this));
}.bind(this));
}.bind(this));
}.bind(this));
}.bind(this));
};
/**
* Indicates that the connection started idling. Initiates a cycle
* of NOOPs or IDLEs to receive notifications about updates in the server
*/
BrowserBox.prototype._onIdle = function() {
if (!this.authenticated || this._enteredIdle) {
// No need to IDLE when not logged in or already idling
return;
}
axe.debug(DEBUG_TAG, this.options.sessionId + ' client: started idling');
this.enterIdle();
};
// Public methods
/**
* Initiate connection to the IMAP server
*/
BrowserBox.prototype.connect = function() {
axe.debug(DEBUG_TAG, this.options.sessionId + ' connecting to ' + this.client.host + ':' + this.client.port);
this._changeState(this.STATE_CONNECTING);
// set timeout to fail connection establishing
clearTimeout(this._connectionTimeout);
this._connectionTimeout = setTimeout(this._onTimeout.bind(this), this.TIMEOUT_CONNECTION);
this.client.connect();
};
/**
* Close current connection
*/
BrowserBox.prototype.close = function(callback) {
var promise;
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
axe.debug(DEBUG_TAG, this.options.sessionId + ' closing connection');
this._changeState(this.STATE_LOGOUT);
this.exec('LOGOUT', function(err) {
if (typeof callback === 'function') {
callback(err || null);
}
this.client.close();
}.bind(this));
return promise;
};
/**
* Run an IMAP command.
*
* @param {Object} request Structured request object
* @param {Array} acceptUntagged a list of untagged responses that will be included in 'payload' property
* @param {Function} callback Callback function to run once the command has been processed
*/
BrowserBox.prototype.exec = function() {
var args = Array.prototype.slice.call(arguments),
callback = args.pop();
if (typeof callback !== 'function') {
args.push(callback);
callback = undefined;
}
args.push(function(response, next) {
var error = null;
if (response && response.capability) {
this.capability = response.capability;
}
if (this.client.isError(response)) {
error = response;
} else if (['NO', 'BAD'].indexOf((response && response.command || '').toString().toUpperCase().trim()) >= 0) {
error = new Error(response.humanReadable || 'Error');
if (response.code) {
error.code = response.code;
}
}
if (typeof callback === 'function') {
callback(error, response, next);
} else {
next();
}
}.bind(this));
this.breakIdle(function() {
this.client.exec.apply(this.client, args);
}.bind(this));
};
// IMAP macros
/**
* The connection is idling. Sends a NOOP or IDLE command
*
* IDLE details:
* https://tools.ietf.org/html/rfc2177
*/
BrowserBox.prototype.enterIdle = function() {
if (this._enteredIdle) {
return;
}
this._enteredIdle = this.capability.indexOf('IDLE') >= 0 ? 'IDLE' : 'NOOP';
axe.debug(DEBUG_TAG, this.options.sessionId + ' entering idle with ' + this._enteredIdle);
if (this._enteredIdle === 'NOOP') {
this._idleTimeout = setTimeout(function() {
this.exec('NOOP');
}.bind(this), this.TIMEOUT_NOOP);
} else if (this._enteredIdle === 'IDLE') {
this.client.exec({
command: 'IDLE'
}, function(response, next) {
next();
}.bind(this));
this._idleTimeout = setTimeout(function() {
axe.debug(DEBUG_TAG, this.options.sessionId + ' sending idle DONE');
this.client.send('DONE\r\n');
this._enteredIdle = false;
}.bind(this), this.TIMEOUT_IDLE);
}
};
/**
* Stops actions related idling, if IDLE is supported, sends DONE to stop it
*
* @param {Function} callback Function to run after required actions are performed
*/
BrowserBox.prototype.breakIdle = function(callback) {
if (!this._enteredIdle) {
return callback();
}
clearTimeout(this._idleTimeout);
if (this._enteredIdle === 'IDLE') {
axe.debug(DEBUG_TAG, this.options.sessionId + ' sending idle DONE');
this.client.send('DONE\r\n');
}
this._enteredIdle = false;
axe.debug(DEBUG_TAG, this.options.sessionId + ' idle terminated');
return callback();
};
/**
* Runs STARTTLS command if needed
*
* STARTTLS details:
* http://tools.ietf.org/html/rfc3501#section-6.2.1
*
* @param {Boolean} [forced] By default the command is not run if capability is already listed. Set to true to skip this validation
* @param {Function} callback Callback function
*/
BrowserBox.prototype.upgradeConnection = function(callback) {
// skip request, if already secured
if (this.client.secureMode) {
return callback(null, false);
}
// skip if STARTTLS not available or starttls support disabled
if ((this.capability.indexOf('STARTTLS') < 0 || this.options.ignoreTLS) && !this.options.requireTLS) {
return callback(null, false);
}
this.exec('STARTTLS', function(err, response, next) {
if (err) {
callback(err);
next();
} else {
this.capability = [];
this.client.upgrade(function(err, upgraded) {
this.updateCapability(function() {
callback(err, upgraded);
});
next();
}.bind(this));
}
}.bind(this));
};
/**
* Runs CAPABILITY command
*
* CAPABILITY details:
* http://tools.ietf.org/html/rfc3501#section-6.1.1
*
* Doesn't register untagged CAPABILITY handler as this is already
* handled by global handler
*
* @param {Boolean} [forced] By default the command is not run if capability is already listed. Set to true to skip this validation
* @param {Function} callback Callback function
*/
BrowserBox.prototype.updateCapability = function(forced, callback) {
if (!callback && typeof forced === 'function') {
callback = forced;
forced = undefined;
}
// skip request, if not forced update and capabilities are already loaded
if (!forced && this.capability.length) {
return callback(null, false);
}
// If STARTTLS is required then skip capability listing as we are going to try
// STARTTLS anyway and we re-check capabilities after connection is secured
if (!this.client.secureMode && this.options.requireTLS) {
return callback(null, false);
}
this.exec('CAPABILITY', function(err, response, next) {
if (err) {
callback(err);
} else {
callback(null, true);
}
next();
});
};
/**
* Runs NAMESPACE command
*
* NAMESPACE details:
* https://tools.ietf.org/html/rfc2342
*
* @param {Function} callback Callback function with the namespace information
*/
BrowserBox.prototype.listNamespaces = function(callback) {
var promise;
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
if (this.capability.indexOf('NAMESPACE') < 0) {
setTimeout(function() {
callback(null, false);
}, 0);
return promise;
}
this.exec('NAMESPACE', 'NAMESPACE', function(err, response, next) {
if (err) {
callback(err);
} else {
callback(null, this._parseNAMESPACE(response));
}
next();
}.bind(this));
return promise;
};
/**
* Runs COMPRESS command
*
* COMPRESS details:
* https://tools.ietf.org/html/rfc4978
*
* @param {Function} callback Callback function with the namespace information
*/
BrowserBox.prototype.compressConnection = function(callback) {
var promise;
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
if (!this.options.enableCompression || this.capability.indexOf('COMPRESS=DEFLATE') < 0 || this.client.compressed) {
setTimeout(function() {
callback(null, false);
}, 0);
return promise;
}
this.exec({
command: 'COMPRESS',
attributes: [{
type: 'ATOM',
value: 'DEFLATE'
}]
}, function(err, response, next) {
if (err) {
callback(err);
} else {
axe.debug(DEBUG_TAG, this.options.sessionId + ' compression enabled, all data sent and received is deflated');
this.client.enableCompression();
callback(null, true);
}
next();
}.bind(this));
return promise;
};
/**
* Runs LOGIN or AUTHENTICATE XOAUTH2 command
*
* LOGIN details:
* http://tools.ietf.org/html/rfc3501#section-6.2.3
* XOAUTH2 details:
* https://developers.google.com/gmail/xoauth2_protocol#imap_protocol_exchange
*
* @param {String} username
* @param {String} password
* @param {Function} callback Returns error if login failed
*/
BrowserBox.prototype.login = function(auth, callback) {
var command, options = {};
if (!auth) {
return callback(new Error('Authentication information not provided'));
}
if (this.capability.indexOf('AUTH=XOAUTH2') >= 0 && auth && auth.xoauth2) {
command = {
command: 'AUTHENTICATE',
attributes: [{
type: 'ATOM',
value: 'XOAUTH2'
}, {
type: 'ATOM',
value: this._buildXOAuth2Token(auth.user, auth.xoauth2),
sensitive: true
}]
};
options.onplustagged = function(response, next) {
var payload;
if (response && response.payload) {
try {
payload = JSON.parse(mimefuncs.base64Decode(response.payload));
} catch (e) {
axe.error(DEBUG_TAG, this.options.sessionId + ' error parsing XOAUTH2 payload: ' + e + '\nstack trace: ' + e.stack);
}
}
// + tagged error response expects an empty line in return
this.client.send('\r\n');
next();
}.bind(this);
} else {
command = {
command: 'login',
attributes: [{
type: 'STRING',
value: auth.user || ''
}, {
type: 'STRING',
value: auth.pass || '',
sensitive: true
}]
};
}
this.exec(command, 'capability', options, function(err, response, next) {
var capabilityUpdated = false;
if (err) {
callback(err);
return next();
}
this._changeState(this.STATE_AUTHENTICATED);
this.authenticated = true;
// update post-auth capabilites
// capability list shouldn't contain auth related stuff anymore
// but some new extensions might have popped up that do not
// make much sense in the non-auth state
if (response.capability && response.capability.length) {
// capabilites were listed with the OK [CAPABILITY ...] response
this.capability = [].concat(response.capability || []);
capabilityUpdated = true;
axe.debug(DEBUG_TAG, this.options.sessionId + ' post-auth capabilites updated: ' + this.capability);
callback(null, true);
} else if (response.payload && response.payload.CAPABILITY && response.payload.CAPABILITY.length) {
// capabilites were listed with * CAPABILITY ... response
this.capability = [].concat(response.payload.CAPABILITY.pop().attributes || []).map(function(capa) {
return (capa.value || '').toString().toUpperCase().trim();
});
capabilityUpdated = true;
axe.debug(DEBUG_TAG, this.options.sessionId + ' post-auth capabilites updated: ' + this.capability);
callback(null, true);
} else {
// capabilities were not automatically listed, reload
this.updateCapability(true, function(err) {
if (err) {
callback(err);
} else {
axe.debug(DEBUG_TAG, this.options.sessionId + ' post-auth capabilites updated: ' + this.capability);
callback(null, true);
}
}.bind(this));
}
next();
}.bind(this));
};
/**
* Runs ID command. Retrieves server ID
*
* ID details:
* http://tools.ietf.org/html/rfc2971
*
* Sets this.serverId value
*
* @param {Object} id ID as key value pairs. See http://tools.ietf.org/html/rfc2971#section-3.3 for possible values
* @param {Function} callback
*/
BrowserBox.prototype.updateId = function(id, callback) {
if (this.capability.indexOf('ID') < 0) {
return callback(null, false);
}
var attributes = [
[]
];
if (id) {
if (typeof id === 'string') {
id = {
name: id
};
}
Object.keys(id).forEach(function(key) {
attributes[0].push(key);
attributes[0].push(id[key]);
});
} else {
attributes[0] = null;
}
this.exec({
command: 'ID',
attributes: attributes
}, 'ID', function(err, response, next) {
if (err) {
axe.error(DEBUG_TAG, this.options.sessionId + ' error updating server id: ' + err + '\n' + err.stack);
callback(err);
return next();
}
if (!response.payload || !response.payload.ID || !response.payload.ID.length) {
callback(null, false);
return next();
}
this.serverId = {};
var key;
[].concat([].concat(response.payload.ID.shift().attributes || []).shift() || []).forEach(function(val, i) {
if (i % 2 === 0) {
key = (val && val.value || '').toString().toLowerCase().trim();
} else {
this.serverId[key] = (val && val.value || '').toString();
}
}.bind(this));
callback(null, this.serverId);
next();
}.bind(this));
};
/**
* Runs LIST and LSUB commands. Retrieves a tree of available mailboxes
*
* LIST details:
* http://tools.ietf.org/html/rfc3501#section-6.3.8
* LSUB details:
* http://tools.ietf.org/html/rfc3501#section-6.3.9
*
* @param {Function} callback Returns mailbox tree object
*/
BrowserBox.prototype.listMailboxes = function(callback) {
var promise;
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
this.exec({
command: 'LIST',
attributes: ['', '*']
}, 'LIST', function(err, response, next) {
if (err) {
callback(err);
return next();
}
var tree = {
root: true,
children: []
};
if (!response.payload || !response.payload.LIST || !response.payload.LIST.length) {
callback(null, false);
return next();
}
response.payload.LIST.forEach(function(item) {
if (!item || !item.attributes || item.attributes.length < 3) {
return;
}
var branch = this._ensurePath(tree, (item.attributes[2].value || '').toString(), (item.attributes[1] ? item.attributes[1].value : '/').toString());
branch.flags = [].concat(item.attributes[0] || []).map(function(flag) {
return (flag.value || '').toString();
});
branch.listed = true;
this._checkSpecialUse(branch);
}.bind(this));
this.exec({
command: 'LSUB',
attributes: ['', '*']
}, 'LSUB', function(err, response, next) {
if (err) {
axe.error(DEBUG_TAG, this.options.sessionId + ' error while listing subscribed mailboxes: ' + err + '\n' + err.stack);
callback(null, tree);
return next();
}
if (!response.payload || !response.payload.LSUB || !response.payload.LSUB.length) {
callback(null, tree);
return next();
}
response.payload.LSUB.forEach(function(item) {
if (!item || !item.attributes || item.attributes.length < 3) {
return;
}
var branch = this._ensurePath(tree, (item.attributes[2].value || '').toString(), (item.attributes[1] ? item.attributes[1].value : '/').toString());
[].concat(item.attributes[0] || []).map(function(flag) {
flag = (flag.value || '').toString();
if (!branch.flags || branch.flags.indexOf(flag) < 0) {
branch.flags = [].concat(branch.flags || []).concat(flag);
}
});
branch.subscribed = true;
}.bind(this));
callback(null, tree);
next();
}.bind(this));
next();
}.bind(this));
return promise;
};
/**
* Create a mailbox with the given path.
*
* CREATE details:
* http://tools.ietf.org/html/rfc3501#section-6.3.3
*
* @param {String} path
* The path of the mailbox you would like to create. This method will
* handle utf7 encoding for you.
* @param {Function} callback
* Callback that takes an error argument and a boolean indicating
* whether the folder already existed. If the mailbox creation
* succeeds, the error argument will be null. If creation fails, error
* will have an error value. In the event the server says NO
* [ALREADYEXISTS], we treat that as success and return true for the
* second argument.
*/
BrowserBox.prototype.createMailbox = function(path, callback) {
var promise;
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
this.exec({
command: 'CREATE',
attributes: [utf7.imap.encode(path)]
}, function(err, response, next) {
if (err && err.code === 'ALREADYEXISTS') {
callback(null, true);
} else {
callback(err, false);
}
next();
});
return promise;
};
/**
* Runs FETCH command
*
* FETCH details:
* http://tools.ietf.org/html/rfc3501#section-6.4.5
* CHANGEDSINCE details:
* https://tools.ietf.org/html/rfc4551#section-3.3
*
* @param {String} sequence Sequence set, eg 1:* for all messages
* @param {Object} [items] Message data item names or macro
* @param {Object} [options] Query modifiers
* @param {Function} callback Callback function with fetched message info
*/
BrowserBox.prototype.listMessages = function(sequence, items, options, callback) {
var promise;
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
if (!callback && typeof items === 'function') {
callback = items;
items = undefined;
}
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
items = items || {
fast: true
};
options = options || {};
var command = this._buildFETCHCommand(sequence, items, options);
this.exec(command, 'FETCH', {
precheck: options.precheck,
ctx: options.ctx
}, function(err, response, next) {
if (err) {
callback(err);
} else {
callback(null, this._parseFETCH(response));
}
next();
}.bind(this));
return promise;
};
/**
* Runs SEARCH command
*
* SEARCH details:
* http://tools.ietf.org/html/rfc3501#section-6.4.4
*
* @param {Object} query Search terms
* @param {Object} [options] Query modifiers
* @param {Function} callback Callback function with the array of matching seq. or uid numbers
*/
BrowserBox.prototype.search = function(query, options, callback) {
var promise;
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}
options = options || {};
var command = this._buildSEARCHCommand(query, options);
this.exec(command, 'SEARCH', {
precheck: options.precheck,
ctx: options.ctx
}, function(err, response, next) {
if (err) {
callback(err);
} else {
callback(null, this._parseSEARCH(response));
}
next();
}.bind(this));
return promise;
};
/**
* Runs STORE command
*
* STORE details:
* http://tools.ietf.org/html/rfc3501#section-6.4.6
*
* @param {String} sequence Message selector which the flag change is applied to
* @param {Array} flags
* @param {Object} [options] Query modifiers
* @param {Function} callback Callback function with the array of matching seq. or uid numbers
*/
BrowserBox.prototype.setFlags = function(sequence, flags, options, callback) {
var key = '';
var list = [];
if (Array.isArray(flags) || typeof flags !== 'object') {
list = [].concat(flags || []);
key = '';
} else if (flags.add) {
list = [].concat(flags.add || []);
key = '+';
} else if (flags.set) {
key = '';
list = [].concat(flags.set || []);
} else if (flags.remove) {
key = '-';
list = [].concat(flags.remove || []);
}
return this.store(sequence, key + 'FLAGS', list, options, callback);
};
/**
* Runs STORE command
*
* STORE details:
* http://tools.ietf.org/html/rfc3501#section-6.4.6
*
* @param {String} sequence Message selector which the flag change is applied to
* @param {String} action STORE method to call, eg "+FLAGS"
* @param {Array} flags
* @param {Object} [options] Query modifiers
* @param {Function} callback Callback function with the array of matching seq. or uid numbers
*/
BrowserBox.prototype.store = function(sequence, action, flags, options, callback) {
var promise;
if (!callback && typeof options === 'function') {
callback = options;
options = undefined;
}
if (!callback) {
promise = new Promise(function(resolve, reject) {
callback = callbackPromise(resolve, reject);
});
}