-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathNotify.ts
97 lines (73 loc) · 2.65 KB
/
Notify.ts
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
import { Mail, IMessage, ISmtpConfig } from "./Mail";
import { debug, error } from "./Log";
// todo: add messages persistance in case of crash
export class Notify {
private readonly _mail: Mail;
private _holdTill: Date = null;
private _messages: IMessage[] = [];
private _t: NodeJS.Timer;
constructor(private readonly _config: ISmtpConfig) {
this._mail = new Mail(this._config);
}
private get isEnabled() {
return this._config.batchPeriodM > 0;
}
configChanged() {
this._mail.configChanged();
clearInterval(this._t);
if (this.isEnabled) {
debug(`message batching is enabled, period = ${this._config.batchPeriodM} minutes`);
this._t = setInterval(async () => {
if (this._messages.length > 0)
await this.sendBatch();
}, this._config.batchPeriodM * 60 * 1000);
}
}
hold(till: Date) {
this._holdTill = till;
}
private async sendBatch() {
const snapshot = this._messages.slice(); // make snapshot of messages
this._messages = [];
let
body = "",
i = 1;
for (const message of snapshot)
body += `-------- ${i++} | ${message.subject} | ${message.on.toISOString()} --------<br/>${message.body}`;
const temp: IMessage = {
subject: `${snapshot[0].subject} (${snapshot.length} items)`,
body,
attachements: snapshot.filter(e => e.attachements != null).map(e => e.attachements).reduce((p, c) => p.concat(c), [])
}
try {
await this._mail.send(temp);
debug(`batch of ${snapshot.length} messages sent`);
}
catch (ex) {
// restore messages if sent fail
this._messages.unshift(...snapshot);
error(`can't send batch mail -> ${ex.message || ex}`);
}
}
async send(message: IMessage) {
const t = new Date();
message.on = t;
if (this._holdTill != null && t < this._holdTill)
return; // skip
if (this.isEnabled && message.priority !== "high") {
debug(`message (batch) -> ${message.subject}`);
this._messages.push(message);
if (this._config.batchMaxMessages > 0 && this._messages.length >= this._config.batchMaxMessages)
await this.sendBatch();
}
else {
debug(`message -> ${message.subject}`);
try {
await this._mail.send(message);
}
catch (ex) {
error(`can't send mail -> ${ex.message || ex}`);
}
}
}
}