forked from haraka/Haraka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attachment_stream.js
107 lines (96 loc) · 2.7 KB
/
attachment_stream.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
'use strict';
const Stream = require('stream');
class AttachmentStream extends Stream {
constructor (header) {
super();
this.header = header;
this.encoding = null;
this.paused = false;
this.end_emitted = false;
this.connection = null;
this.buffer = [];
}
}
AttachmentStream.prototype.emit_data = function (data) {
// console.log("YYY: DATA emit");
if (this.paused) {
return this.buffer.push(data);
}
if (this.encoding) {
this.emit('data', data.toString(this.encoding));
}
else {
this.emit('data', data);
}
};
AttachmentStream.prototype.emit_end = function (force) {
if (this.paused && !force) {
// console.log("YYY: end emit (cache)");
this.end_emitted = true;
}
else {
// console.log("YYY: end emit");
if (this.buffer.length > 0) {
while (this.buffer.length > 0) {
this.emit_data(this.buffer.shift());
}
}
this.emit('end');
}
};
AttachmentStream.prototype.pipe = function (dest, options) {
const self = this;
this.paused = false;
Stream.prototype.pipe.call(this, dest, options);
dest.on('drain', function () {
// console.log("YYY: DRAIN!!!");
if (self.paused) self.resume();
});
dest.on('end', function () {
// console.log("YYY: END!!");
if (self.paused) self.resume();
});
dest.on('close', function () {
// console.log("YYY: CLOSE!!");
if (self.paused) self.resume();
});
};
AttachmentStream.prototype.setEncoding = function (enc) {
if (enc !== 'binary') {
throw "Unable to set encoding to anything other than binary";
}
this.encoding = enc;
};
AttachmentStream.prototype.pause = function () {
// console.log("YYY: PAUSE!!");
this.paused = true;
if (this.connection) {
// console.log("YYYY: Backpressure pause");
this.connection.pause();
}
};
AttachmentStream.prototype.resume = function () {
// console.log("YYY: RESUME!!");
if (this.connection) {
// console.log("YYYY: Backpressure resume");
this.connection.resume();
}
this.paused = false;
if (this.buffer.length) {
while (this.paused === false && this.buffer.length > 0) {
this.emit_data(this.buffer.shift());
}
if (this.buffer.length === 0 && this.end_emitted) {
this.emit('end');
}
}
else if (this.end_emitted) {
this.emit('end');
}
};
AttachmentStream.prototype.destroy = function () {
// console.log("YYYY: Stream destroyed");
};
exports.createStream = function (header) {
return new AttachmentStream (header);
};