forked from tegioz/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatServer.js
executable file
·376 lines (324 loc) · 13.7 KB
/
chatServer.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// Author: Sergio Castaño Arteaga
// Email: sergio.castano.arteaga@gmail.com
// ***************************************************************************
// General
// ***************************************************************************
var conf = {
port: 8888,
debug: false,
dbPort: 6379,
dbHost: '127.0.0.1',
dbOptions: {},
mainroom: 'MainRoom'
};
// External dependencies
var express = require('express'),
http = require('http'),
events = require('events'),
_ = require('underscore'),
sanitize = require('validator').sanitize;
var https = require('https');
var fs = require('fs');
var privateKey = fs.readFileSync('./cert/private.key', 'utf8'),
certificate = fs.readFileSync('./cert/file.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
// HTTP Server configuration & launch
var app = express();
// server = http.createServer(app);
// server.listen(conf.port);
var server = https.createServer(credentials, app);
var SSLPort = 8888;
server.listen(SSLPort, function() {
console.log('OneLib https is running', SSLPort);
});
// Express app configuration
app.configure(function() {
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static'));
});
var io = require('socket.io')(server);
var redis = require('socket.io-redis');
io.adapter(redis({ host: conf.dbHost, port: conf.dbPort }));
var db = require('redis').createClient(conf.dbPort,conf.dbHost);
// Logger configuration
var logger = new events.EventEmitter();
logger.on('newEvent', function(event, data) {
// Console log
console.log('%s: %s', event, JSON.stringify(data));
// Persistent log storage too?
// TODO
});
var musicindex = 0;
var musicstartTime = new Date().getTime();
var curMusic = {
savetime:0, // score
startPlaytime:0, // 开始播放时间
endedCount:0,
}
// ***************************************************************************
// Express routes helpers
// ***************************************************************************
// Only authenticated users should be able to use protected methods
var requireAuthentication = function(req, res, next) {
// TODO
next();
};
// Send a message to all active rooms
var sendBroadcast = function(text) {
_.each(io.nsps['/'].adapter.rooms, function(sockets, room) {
var message = {'room':room, 'username':'ServerBot', 'msg':text, 'date':new Date()};
io.to(room).emit('newMessage', message);
});
logger.emit('newEvent', 'newBroadcastMessage', {'msg':text});
};
// ***************************************************************************
// Express routes
// ***************************************************************************
// Welcome message
app.get('/', function(req, res) {
res.send(200, "Welcome to chat server");
});
// Broadcast message to all connected users
app.post('/api/broadcast/', requireAuthentication, function(req, res) {
sendBroadcast(req.body.msg);
res.send(201, "Message sent to all rooms");
});
// ***************************************************************************
// Socket.io events
// ***************************************************************************
io.sockets.on('connection', function(socket) {
// Welcome message on connection
socket.emit('connected', 'Welcome to the chat server');
logger.emit('newEvent', 'userConnected', {'socket':socket.id});
// Store user data in db
db.hset([socket.id, 'connectionDate', new Date()], redis.print);
db.hset([socket.id, 'socketID', socket.id], redis.print);
db.hset([socket.id, 'username', 'anonymous'], redis.print);
// Join user to 'MainRoom'
socket.join(conf.mainroom);
logger.emit('newEvent', 'userJoinsRoom', {'socket':socket.id, 'room':conf.mainroom});
// Confirm subscription to user
socket.emit('subscriptionConfirmed', {'room':conf.mainroom});
// Notify subscription to all users in room
var data = {'room':conf.mainroom, 'username':'anonymous', 'msg':'----- Joined the room -----', 'id':socket.id};
io.to(conf.mainroom).emit('userJoinsRoom', data);
// User wants to subscribe to [data.rooms]
socket.on('subscribe', function(data) {
// Get user info from db
db.hget([socket.id, 'username'], function(err, username) {
// Subscribe user to chosen rooms
_.each(data.rooms, function(room) {
room = room.replace(" ","");
socket.join(room);
logger.emit('newEvent', 'userJoinsRoom', {'socket':socket.id, 'username':username, 'room':room});
// Confirm subscription to user
socket.emit('subscriptionConfirmed', {'room': room});
// Notify subscription to all users in room
var message = {'room':room, 'username':username, 'msg':'----- Joined the room -----', 'id':socket.id};
io.to(room).emit('userJoinsRoom', message);
});
});
});
// User wants to unsubscribe from [data.rooms]
socket.on('unsubscribe', function(data) {
// Get user info from db
db.hget([socket.id, 'username'], function(err, username) {
// Unsubscribe user from chosen rooms
_.each(data.rooms, function(room) {
if (room != conf.mainroom) {
socket.leave(room);
logger.emit('newEvent', 'userLeavesRoom', {'socket':socket.id, 'username':username, 'room':room});
// Confirm unsubscription to user
socket.emit('unsubscriptionConfirmed', {'room': room});
// Notify unsubscription to all users in room
var message = {'room':room, 'username':username, 'msg':'----- Left the room -----', 'id': socket.id};
io.to(room).emit('userLeavesRoom', message);
}
});
});
});
// User wants to know what rooms he has joined
socket.on('getRooms', function(data) {
socket.emit('roomsReceived', socket.rooms);
logger.emit('newEvent', 'userGetsRooms', {'socket':socket.id});
});
// Get users in given room
socket.on('getUsersInRoom', function(data) {
var usersInRoom = [];
var socketsInRoom = _.keys(io.nsps['/'].adapter.rooms[data.room]);
for (var i=0; i<socketsInRoom.length; i++) {
db.hgetall(socketsInRoom[i], function(err, obj) {
usersInRoom.push({'room':data.room, 'username':obj.username, 'id':obj.socketID});
// When we've finished with the last one, notify user
if (usersInRoom.length == socketsInRoom.length) {
socket.emit('usersInRoom', {'users':usersInRoom});
}
});
}
});
socket.on('getMusics',function(data){
var usersInRoom = [];
var socketsInRoom = _.keys(io.nsps['/'].adapter.rooms[data.room]);
for (var i=0; i<socketsInRoom.length; i++) {
db.hgetall(socketsInRoom[i], function(err, obj) {
usersInRoom.push({'room':data.room, 'username':obj.username, 'id':obj.socketID});
// When we've finished with the last one, notify user
console.log('找到音乐socket');
if (usersInRoom.length == socketsInRoom.length)
{
db.zrange( [data.room+'music',0,-1, 'WITHSCORES'],function (err,obj) {
// console.log(obj);
var musics = [];
for(var i = 0; i<obj.length; i+=2)
{
var music = JSON.parse(obj[i]);
music.savetime = obj[i+1];
musics.push(music);
}
if( musics.length > 0 )
curMusic.savetime = musics[0].savetime;
if( curMusic.savetime == 0 && musics.length > 0){
curMusic.startPlaytime = new Date().getTime();
}
if( musics.length > 0 )
socket.emit('musicInRoom', {'musics':musics,'room':data.room,'starttime':(curMusic.startPlaytime)});
} )
}
});
}
});
var changeMusic = function(room)
{
var musics = [];
db.zrange( [data.room+'music',0,-1, 'WITHSCORES'],function (err,obj) {
// console.log(obj);
for(var i = 0; i<obj.length; i+=2)
{
var music = JSON.parse(obj[i]);
music.score = obj[i+1];
musics.push(music);
}
// if( musics.length > 0 )
// socket.emit('musicInRoom', {'musics':musics,'starttime':10});
db.zremrangebyscore([data.room+'music',0,parseInt(curMusic.savetime)],function (err,obj) {
console.log('切歌完毕,删除数据库成功')
console.log(err);
});
if( musics.length > 1 ){
curMusic.savetime = musics[1].score;
curMusic.endedCount = 0;
curMusic.startPlaytime = new Date().getTime();
// 删除第一首歌
// db.zremrangebyscore([data.room+'music',0,parseInt(curMusic.savetime)-1],function (err,obj) {
// console.log('切歌完毕,删除数据库成功')
// console.log(err);
// })
}else
{
curMusic.savetime = 0;
curMusic.endedCount = 0;
curMusic.startPlaytime = 0;
}
io.to(room).emit('changemusic', '切歌');
} )
}
socket.on('playended',function (data) {
console.log('playeded::' + JSON.stringify(data));
if( curMusic.savetime == 0 )
{
// 给全部人发送切歌消息
changeMusic(data.room);
return;
}
if( curMusic.savetime == data.music.savetime )
{
// 标记一次播放结束
curMusic.endedCount++;
}
// 投票过半,则发送切歌消息
var usersInRoom = [];
var socketsInRoom = _.keys(io.nsps['/'].adapter.rooms[data.room]);
if( curMusic.endedCount >= socketsInRoom.length/2 )
{
// 给全部人发送切歌消息
changeMusic(data.room);
}
});
socket.on('changeMusic',function(data){
{
// 标记一次播放结束
curMusic.endedCount++;
}
// 投票过半,则发送切歌消息
var usersInRoom = [];
var socketsInRoom = _.keys(io.nsps['/'].adapter.rooms[data.room]);
if( curMusic.endedCount >= socketsInRoom.length/2 )
{
// 给全部人发送切歌消息
changeMusic(data.room);
}else
io.to(data.room).emit('changemusiccount', {'vote':curMusic.endedCount,'all':socketsInRoom.length});
});
// User wants to change his nickname
socket.on('setNickname', function(data) {
// Get user info from db
db.hget([socket.id, 'username'], function(err, username) {
// Store user data in db
db.hset([socket.id, 'username', data.username], redis.print);
logger.emit('newEvent', 'userSetsNickname', {'socket':socket.id, 'oldUsername':username, 'newUsername':data.username});
// Notify all users who belong to the same rooms that this one
_.each(socket.rooms, function(room) {
if (room) {
var info = {'room':room, 'oldUsername':username, 'newUsername':data.username, 'id':socket.id};
io.to(room).emit('userNicknameUpdated', info);
}
});
});
});
// New message sent to group
socket.on('newMessage', function(data) {
db.hgetall(socket.id, function(err, obj) {
if (err) return logger.emit('newEvent', 'error', err);
// Check if user is subscribed to room before sending his message
if (_.contains(_.values(socket.rooms), data.room)) {
var message = {'room':data.room, 'username':obj.username, 'msg':data.msg, 'date':new Date(),'music':data.music};
if( data.music )
{
// 存储
data.music.savetime = new Date().getTime();
message.music = data.music;
db.zadd([data.room+'music',new Date().getTime(),JSON.stringify(data.music)], redis.print);
}
// Send message to room
io.to(data.room).emit('newMessage', message);
logger.emit('newEvent', 'newMessage', message);
}
});
});
// Clean up on disconnect
socket.on('disconnect', function() {
// Get current rooms of user
var rooms = socket.rooms;
// Get user info from db
db.hgetall(socket.id, function(err, obj) {
if (err) return logger.emit('newEvent', 'error', err);
logger.emit('newEvent', 'userDisconnected', {'socket':socket.id, 'username':obj.username});
// Notify all users who belong to the same rooms that this one
_.each(rooms, function(room) {
if (room) {
var message = {'room':room, 'username':obj.username, 'msg':'----- Left the room -----', 'id':obj.socketID};
io.to(room).emit('userLeavesRoom', message);
}
});
});
// Delete user from db
db.del(socket.id, redis.print);
});
});
// Automatic message generation (for testing purposes)
if (conf.debug) {
setInterval(function() {
var text = 'Testing rooms';
sendBroadcast(text);
}, 60000);
}