forked from joraavanes/chatify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
77 lines (54 loc) · 2.63 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
const path = require('path');
const express = require('express');
const { v4 } = require('uuid');
const { addUser, removeUser, getUser, getCurrentUsersInRoom, getOtherRooms, getAllRooms } = require('./helpers/user');
const app = require('express')();
const httpServer = require('http').createServer(app);
const io = require('socket.io')(httpServer);
const PORT = process.env.PORT || 5000;
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
io.on('connection', socket => {
socket.on('join', ({name, room}) => {
addUser({id: socket.id, name, room});
const messageId = v4();
room = room.toLowerCase().replace(' ', '-');
socket.emit('message', {messageId, name: 'admin', message: `Welcome ${name}`, date: new Date().valueOf() });
socket.broadcast.to(room).emit('message', {messageId, name: 'admin', message: `A new friend has joined, Welcome ${name}`, date: new Date().valueOf() });
socket.join(room);
const roomData = getCurrentUsersInRoom(room);
socket.emit('roomData', roomData);
socket.broadcast.to(room).emit('roomData', roomData);
io.sockets.emit('checkRooms');
// io.sockets.emit('otherRooms', otherRooms);
// socket.broadcast.emmit('otherRooms', otherRooms);
});
socket.on('userMessage', ({message}, callback) => {
const user = getUser(socket.id);
if(!user) return;
const messageId = v4();
socket.emit('message', {messageId, name: user.name, message, currentUser: true, date: new Date().valueOf() });
socket.broadcast.to(user.room).emit('message', {messageId, name: user.name, message, date: new Date().valueOf() });
callback(undefined, 'Delivered');
});
socket.on('otherRooms', () => {
const user = getUser(socket.id);
const otherRooms = getOtherRooms(user?.room);
socket.emit('otherRooms', otherRooms);
});
socket.on('allRooms', () => {
socket.emit('allRooms', getAllRooms());
});
socket.on('disconnect', reason => {
const user = removeUser(socket.id);
if(!user) return;
const messageId = v4();
socket.broadcast.to(user.room).emit('message', {messageId, name: 'admin', message: `${user.name} has left the room`, date: new Date().valueOf() });
const roomData = getCurrentUsersInRoom(user.room);
socket.broadcast.to(user.room).emit('roomData', roomData);
io.sockets.emit('checkRooms');
});
});
httpServer.listen(PORT, () => console.log(`Server is running: http://localhost:${PORT}`));