forked from telehash/telehash-js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
chat.js
90 lines (78 loc) · 1.9 KB
/
chat.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
var telehash = require("../index.js").telehash;
var chatCache = {};
var connector;
var chatRoom = "telechat:lobby";
var nickName = "@user";
var stdin = process.openStdin();
stdin.setEncoding("UTF-8");
if (!process.argv[2]) {
console.log("Usage: node chat.js nickname [chatroom]\n");
process.exit();
}
nickName = process.argv[2];
if (process.argv[3]) chatRoom = process.argv[3];
telehash.init(function (err) {
if (err) {
console.log(err);
process.exit();
return;
}
telehash.seed(function (status, info) {
if (status === 'offline' && info === 'snat-detected') {
console.log("SNAT detected. Exiting...");
process.exit();
}
if (status !== "online") {
console.log(status);
return;
}
if (!connector) {
stdin.on('data', function (chunk) {
if (chunk.length > 1) {
if (connector) connector.send({
txt: chunk,
nick: nickName
});
}
});
}
chat(chatRoom);
});
});
function chat(name) {
if (!connector) {
connector = telehash.connect(name, true);
telehash.listen(name, function (MSG) {
var msg_sig = MSG.guid + MSG.message;
if (!chatCache[msg_sig]) {
if (MSG.message.x) {
if (MSG.message.x == 'join') console.log("[JOINED] " + MSG.message.nick);
if (MSG.message.x == 'leave') console.log("[LEFT THE CHAT] <" + MSG.message.nick + ">");
} else {
if (MSG.message.txt) console.log("<" + MSG.message.nick + ">: " + MSG.message.txt);
}
chatCache[msg_sig] = true;
}
});
}
console.log("Connected. Joining chat room: " + name + " as " + nickName);
connector.send({
x: 'join',
nick: nickName
});
}
//cant catch SIGINT signals on windows!
if (process.platform != 'win32') {
process.on('SIGINT', function () {
console.log("Use Control-D to exit.");
});
}
stdin.on('end', function () {
if (this.exiting) return;
this.exiting = true;
if (connector) connector.send({
x: 'leave',
nick: nickName
});
telehash.shutdown();
});