-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
78 lines (55 loc) · 2.07 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
78
const express = require('express')
const Filter = require('bad-words')
const path = require('path')
const http = require('http')
const socketio = require('socket.io')
const metadata = require('./public/js/metadata')
const {addUser,removeUser,getUser,getUserInRoom} = require('./public/js/user')
const qs = require('qs')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
const PORT = process.env.PORT || 1000
const publicDirectory = path.join(__dirname+'/public')
app.use(express.static(publicDirectory))
io.on('connection', (socket)=>{
socket.on('join',({username,room}, callback)=>{
const {error,user} = addUser({id:socket.id,username,room})
if(error)
return callback(error)
socket.join(user.room)
socket.emit('event', "Welcome!")
socket.broadcast.to(room).emit('event', `Wild ${user.username} appeared`)
io.to(room).emit('userlist',getUserInRoom(room))
callback()
})
socket.on('sendMessage', (message, callback)=>{
const {error,user} = getUser(socket.id)
if(error)
return callback(error)
const filter = new Filter()
if(message == '')
return callback('Write some text')
if(filter.isProfane(message))
return callback('Profanity not allowed')
io.to(user.room).emit('message',metadata(message,user.username))
callback('message delivered')
})
socket.on('sendLocation', ({latitude,longitude}, callback)=>{
const {error,user} = getUser(socket.id)
if(error)
callback(error)
io.to(user.room).emit('locationMessage', `https:google.com/maps?q=${latitude},${longitude}`, user.username)
callback('Location shared')
})
socket.on('disconnect', ()=>{
const user = removeUser(socket.id)
if(user)
io.to(user.room).emit('event', `${user.username} left the room`)
})
})
server.listen(PORT, (err)=>{
if(err)
return console.log(err)
return console.log(`Server is running at port ${PORT}`)
})