forked from mjg123/node-multilang-chat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
77 lines (65 loc) · 2.71 KB
/
server.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
/*global require console*/
(function () {
var http = require('http'),
io = require('socket.io'),
https = require('https'),
qs = require('querystring'),
node_static = require('node-static'),
server = http.createServer(),
socket = io.listen(server),
clients = [],
file_server = new (node_static.Server)('./client');
server.on("request", function (req, res) {
req.on("end", function () {
file_server.serve(req, res);
});
});
socket.on("connection", function (client) {
clients.push(client);
client.on("message", function (data) {
var message = JSON.parse(data),
recipient,
translateUrl,
receiveTrans;
receiveTrans = function (recipient, message) {
return function (res) {
res.on("data", function (data) {
var translation = JSON.parse(data),
transMsg;
if (translation.data) {
transMsg = translation.data.translations[0].translatedText;
recipient.send(JSON.stringify({action: "message", user: message.user, message: transMsg}));
}
});
};
};
if (message.action === "message") {
for (recipient in clients) {
if (clients.hasOwnProperty(recipient)) {
if (clients[recipient] === client) {
client.send(JSON.stringify(message));
} else {
translateUrl = "/language/translate/v2" +
"?key=AIzaSyDQvD2F99tMbspU6aA6-WWFQ1nZ1Ote0eA" +
"&source=" + client.lang +
"&target=" + clients[recipient].lang +
"&q=" + qs.escape(message.message);
https.get(
{ host: "www.googleapis.com",
path: translateUrl },
receiveTrans(clients[recipient], message));
}
}
}
} else if (message.action === "lang") {
client.lang = message.lang;
console.log("Client " + client.sessionId + " set lang to " + message.lang);
}
});
client.on("disconnect", function () {
var index = clients.indexOf(client);
clients.splice(index, 1);
});
});
server.listen(1337);
}());