stub-transport.js
2.82 KB
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
'use strict';
var packageData = require('../package.json');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
module.exports = function (options) {
return new StubTransport(options);
};
function StubTransport(options) {
EventEmitter.call(this);
this.options = options || {};
this.name = 'Stub';
this.version = packageData.version;
}
util.inherits(StubTransport, EventEmitter);
StubTransport.prototype.isIdle = function () {
return true;
};
StubTransport.prototype.verify = function (callback) {
setImmediate(function () {
if (this.options.error) {
return callback(new Error(this.options.error));
}
return callback(null, true);
}.bind(this));
};
StubTransport.prototype.send = function (mail, callback) {
if (this.options.error) {
setImmediate(function () {
callback(new Error(this.options.error));
}.bind(this));
return;
}
if (this.options.keepBcc) {
mail.message.keepBcc = true;
}
var message = mail.message.createReadStream();
var chunks = [];
var chunklen = 0;
var envelope = mail.data.envelope || mail.message.getEnvelope();
this._log('info', 'envelope', JSON.stringify(envelope));
this.emit('envelope', envelope);
message.on('error', function (err) {
setImmediate(function () {
callback(err);
});
});
message.on('data', function (chunk) {
chunks.push(chunk);
chunklen += chunk.length;
this._log('verbose', 'message', chunk.toString());
this.emit('data', chunk.toString());
}.bind(this));
message.on('end', function () {
setImmediate(function () {
var messageId = (mail.message.getHeader('message-id') || '').replace(/[<>\s]/g, '');
var response = Buffer.concat(chunks, chunklen);
var info = {
envelope: mail.data.envelope || mail.message.getEnvelope(),
messageId: messageId,
response: response
};
this._log('info', 'end', 'Processed <%s> (%sB)', messageId, response.length);
this.emit('end', info);
callback(null, info);
}.bind(this));
}.bind(this));
};
/**
* Log emitter
* @param {String} level Log level
* @param {String} type Optional type of the log message
* @param {String} message Message to log
*/
StubTransport.prototype._log = function ( /* level, type, message */ ) {
var args = Array.prototype.slice.call(arguments);
var level = (args.shift() || 'INFO').toUpperCase();
var type = (args.shift() || '');
var message = util.format.apply(util, args);
this.emit('log', {
name: packageData.name,
version: packageData.version,
level: level,
type: type,
message: message
});
};