-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathuser.js
132 lines (121 loc) · 2.76 KB
/
user.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
const { debuglog } = require('util');
const to = require('flush-write-stream');
const Parser = require('./parser');
const Message = require('./message');
const { Duplex } = require('stream');
const debug = debuglog('ircs:User');
/**
* Represents a User on the server.
*/
class User extends Duplex {
/**
* @param {stream.Duplex} sock Duplex Stream to read & write commands from & to.
*/
constructor(sock) {
super({
readableObjectMode: true,
writableObjectMode: true
});
this.socket = sock;
this.channels = [];
this.nickname = null;
this.hostname = sock.remoteAddress;
this.on('end', () => {
const message = new Message(null, 'QUIT', []);
this.onReceive(message);
});
sock.pipe(Parser()).pipe(to.obj((message, enc, cb) => {
this.onReceive(message)
cb()
}));
sock.on('error', e => {
debug('error', e);
});
sock.on('end', e => {
this.emit('end', e);
});
}
onReceive(message) {
debug('receive', message + '')
message.user = this
message.prefix = this.mask()
this.push(message)
}
_read() {
//
}
_write(message, enc, cb) {
debug('write', message + '');
if (this.socket.destroyed) {
debug('user socket destroyed', this.nickname);
this.socket.emit('error');
return cb();
}
this.socket.write(`${message}\r\n`);
cb()
}
join(channel) {
if (-1 === this.channels.indexOf(channel)) {
this.channels.push(channel);
} else {
throw new Error(`Already join channel: ${channel.name}`);
}
return this;
}
/**
* Send a message to this user.
*
* @param {Message} message Message to send.
*/
send(message) {
if (!(message instanceof Message)) {
message = new Message(...arguments)
}
debug('send', message + '')
this.write(message);
}
/**
* Check if this user is matched by a given mask.
*
* @param {string} mask Mask to match.
*
* @return {boolean} Whether the user is matched by the mask.
*/
matchesMask(mask) {
// simple & temporary
return mask === this.mask();
}
/**
* Gives this user's mask.
*
* @return {string|boolean} Mask or false if this user isn't really known yet.
* @todo Just use a temporary nick or something, so we don't have to deal with `false` everywhere…
*/
mask() {
var mask = ''
if (this.nickname) {
mask += this.nickname;
if (this.username) {
mask += `!${this.username}`;
}
if (this.hostname) {
mask += `@${this.hostname}`;
}
}
return mask || false;
}
/**
* end socket
*/
end() {
this.socket.end();
return this;
}
toString() {
return this.mask();
}
inspect() {
return this.toString();
}
}
module.exports = User;