-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.js
More file actions
86 lines (82 loc) · 2.56 KB
/
Client.js
File metadata and controls
86 lines (82 loc) · 2.56 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
let ipc = require("node-ipc");
let EventEmitter = require("events").EventEmitter;
let Server = require("./Server.js");
/**
* Listens to events emitted by Server.js over its socket
* Emits events when a mail is received.
* Events:
* ready => ()
* kill => ()
* mail => (mail)
* err => (Error)
* Example:
* let Mail = new SMTP();
* Mail.on("test@example.com", mail=>{ ... });
* Mail.on("*", mail=>{ ... });
*/
class SMTPClient extends EventEmitter {
/**
* @param {Object} [opts] Options for the client
* @param {Boolean} [opts.debug] Whether to log debug info
* @param {String} [opts.socketID] The socket to connect to
*/
constructor(opts={}) {
super();
this.opts = opts;
opts.socketID = opts.socketID || "simple-smtp-listener";
this.ready = new Promise(res=>{
ipc.config.silent = !opts.debug;
ipc.connectTo(
opts.socketID,
()=>{
this.ipc = ipc.of[opts.socketID];
this.ipc.on(
"connect",
()=>{
this.debug("Connected");
this.emit("ready"); // bypass wildcard emit
}
);
this.ipc.on(
"disconnect",
()=>{
this.debug("Disconnected");
this.emit("kill"); // bypass wildcard emit
}
);
this.ipc.on(
"destroyed",
()=>{
this.debug("Server destroyed");
this.emit("kill");
}
);
this.ipc.on("email", this.handleEmail.bind(this));
res();
}
);
});
}
/**
* Handles emails received from the server
*/
handleEmail(mail) {
this.debug("Received email:",mail);
this.emit("*", mail);
for (let receipient of mail.to.value) {
this.debug("Emitting",receipient);
this.emit(receipient.address, mail);
}
}
/**
* Logs to console if debug is enabled
* @param {...any} [data] The data to emit
*/
debug(data) {
if (this.opts.debug) {
console.log.apply(console, ["[SMTP/client]",...arguments]);
}
}
}
SMTPClient.Server = Server;
module.exports = SMTPClient;