-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (75 loc) · 2.21 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
const path = require('path')
const Filter = require('bad-words')
const Filter2 = require('bad-word-ar')
const formatMessage = require('./utils/messages')
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers,
} = require('./utils/users')
const express = require('express')
const http = require('http')
const socketio = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
filter = new Filter()
filter2 = new Filter2('ar')
app.use(express.static(path.join(__dirname, 'public')))
const botName = 'chilChat'
//Run when a cleint connect
io.on('connection', (socket) => {
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room)
socket.join(user.room)
//emit is used for only the user concerned
socket.emit('message', formatMessage(botName, 'Welcome to chatcord'))
// Broadcast when a user connects , it's for all other users expet the
// original user
socket.broadcast
.to(user.room)
.emit(
'message',
formatMessage(botName, `${username} has joined the chatt`)
)
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room),
})
socket.on('disconnect', () => {
const user = userLeave(socket.id)
if (user) {
io.to(user.room).emit(
'message',
formatMessage(botName, `${user.username} has left the chat`)
)
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room),
})
}
})
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id)
const arabic = /[\u0600-\u06FF]/
if (arabic.test(msg)) {
io.to(user.room).emit(
'message',
formatMessage(user.username, filter2.clean(msg))
)
} else {
io.to(user.room).emit(
'message',
formatMessage(user.username, filter.clean(msg))
)
}
})
})
// use io.emit to notify all users together
})
server.listen(process.env.PORT || 4000, () =>
console.log('server running on port 4000')
)