-
Notifications
You must be signed in to change notification settings - Fork 57
/
index.js
177 lines (134 loc) · 4.96 KB
/
index.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
'use strict'
const config = require('config-yml')
const express = require('express')
const compression = require('compression')
const path = require('path')
const IO = require('socket.io')
const xss = require('xss')
const db = require('./db')
const filter = require('./utils/filter')
const app = express()
const roomRouter = require('./router/room')
app.use(compression())
app.use(express.static(path.join(__dirname, 'assets')))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
const server = require('http').Server(app)
const socketIO = IO(server)
const roomList = {}
const REGEX_HEX_COLOR = /^#(?:[0-9a-fA-F]{3,4}){1,2}$/
// When new connection incoming
socketIO.on('connection', socket => {
// Get Room ID / Session ID
const { roomId='default', t: sid } = socket.handshake.query
const { cookie } = socket.handshake.headers
// Get nickname from the cookie or generate a random name
const name = processInput(getCookie(cookie, 'name').trim().substring(0, 32) || `user_${Math.random().toString(36).substr(2, 5)}`)
// Get uid from the cookies or set the uid to be the same as the session ID on the first connection
const uid = processInput(getCookie(cookie, 'uid').trim().substring(0, 7) || sid)
socket.join(roomId)
let user = { session: [sid], uid, name }
if (!roomList[roomId]) roomList[roomId] = []
// Reuse user info if uid exists
const index = roomList[roomId].findIndex(obj => obj.uid === user.uid)
if (index !== -1) {
roomList[roomId][index]['session'].push(sid)
user = roomList[roomId][index]
}else{
roomList[roomId].push(user)
socketIO.to(roomId).emit('sys', `${user.name}(${user.uid}) join the chat.`)
console.log(`${user.name}(${user.uid})::${sid} join the room(${roomId})`)
}
socketIO.to(roomId).emit('init', user)
socketIO.to(roomId).emit('online', roomList[roomId])
socket.on('change-name', name => {
name = processInput(name.trim()).substring(0, 32)
const index = roomList[roomId].findIndex(obj => obj.uid === user.uid)
const oldName = roomList[roomId][index]['name'].substring(0, 32)
if(oldName === name) return
roomList[roomId][index]['name'] = name
socketIO.to(roomId).emit('rename', { uid: processInput(user.uid), name })
socketIO.to(roomId).emit('online', roomList[roomId])
const msg = `${oldName}(${user.uid}) changed the name from ${oldName} to ${name}.`
socketIO.to(roomId).emit('sys', processInput(msg))
console.log(msg)
})
socket.on('leave', () => {
socket.emit('disconnect')
})
socket.on('disconnect', () => {
// Socket session leave chat room
socket.leave(roomId)
// Mark the user offline if the last session leaves
const userIndex = roomList[roomId].findIndex(item => item.uid === uid)
if (userIndex !== -1) {
const user = roomList[roomId][userIndex]
const sessionIndex = user.session.findIndex(item => item === sid)
user.session.splice(sessionIndex, 1)
if(user.session.length === 0) {
roomList[roomId].splice(userIndex, 1)
socketIO.to(roomId).emit('sys', `${processInput(user.name)}(${processInput(user.uid)}) leave the chat.`)
socketIO.to(roomId).emit('online', roomList[roomId])
}
console.log(`${user.name}(${user.uid})::${sid} leave the room(${roomId})`)
}
// Clean the room if no one is chatting
if(roomList[roomId].length === 0) delete roomList[roomId]
})
// Broadcast the message to everyone in the room when it is received
socket.on('message', msg => {
const msgItem = {
...msg,
sid,
room: roomId,
ts: Date.now() / 1000 | 0,
name: processInput(msg.name, true).substring(0, 32),
msg: processInput(msg.msg, true).substring(0, 1000),
namecolor: REGEX_HEX_COLOR.test(msg.namecolor) ? msg.namecolor : '#117743',
msgcolor: REGEX_HEX_COLOR.test(msg.msgcolor) ? msg.msgcolor : '#3d3d3d'
}
socketIO.to(roomId).emit('msg', msgItem)
if(roomId === 'demo') return
// Log message into the database
db.setRecord(msgItem)
})
})
// Print room list to console
setInterval(() => {
console.log('room list:', JSON.stringify(roomList))
}, 1000 * 30)
app.set('roomList', roomList)
app.use('/room', roomRouter)
app.get('/', (req, res) => {
res.redirect('/room/@demo')
});
app.get('/filter', (req, res) => {
const { q } = req.query
res.send(processInput(q))
});
app.get('/heart-beat', (req, res) => {
res.set({
'cache-control': 'max-age=0, no-cache, no-store, must-revalidate'
})
res.send('alive')
console.log('heart-beat')
});
server.listen(config.app.port, () => {
console.log(`server listening on port ${config.app.port}`)
})
function getCookie(cookie, name) {
cookie = `; ${cookie}`
const parts = cookie.split(`; ${name}=`)
if (parts.length === 2) {
try {
return decodeURIComponent(parts.pop().split(';').shift())
} catch {
return 'wrong_name'
}
}
return ''
}
function processInput(source, flag){
if(flag) source = xss(source)
return filter(source)
}