-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (89 loc) · 2.43 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
const express = require("express");
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const bp = require("body-parser");
const Connection = require('./utils/db.js')
const { UserActivity, Room, Chat } = require('./utils/models.js');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(bp.json());
app.use(bp.urlencoded({ extended: false }))
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: '*',
}
});
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('message', async (msg) => {
console.log('Message received:', msg);
try {
const chatExists = await Chat.exists({ user: msg?.user });
if (chatExists) {
const updatedChat = await Chat.updateOne(
{ user: msg?.user },
{ $push: { msg: msg?.text } }
);
console.log("Old chat updated", updatedChat);
} else {
const newChat = new Chat({
user: msg?.user,
msg: [msg?.text]
});
await newChat.save();
console.log("New chat saved");
}
io.emit('message', msg);
} catch (error) {
console.error('Error handling message:', error);
socket.emit('error', { message: 'Failed to process message' });
}
});
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
app.post('/saveRoom', (req, res) => {
const { id } = req.body;
Room.exists({ roomId: id })
.then(exists => {
if (exists) {
res.send({ res: false });
} else {
const room = new Room({
roomId: id
})
room.save();
res.send({ res: true });
}
})
.catch(error => {
console.error('Error checking room existence:', error);
});
});
app.get('/checkRoom/:roomID/:usn', (req, res) => {
const { roomID, usn } = req.params;
Room.exists({ roomId: roomID })
.then(exists => {
if (exists) {
const userActivity = new UserActivity({
username: usn,
roomJoined: roomID
})
userActivity.save();
res.send({ exists: true });
} else {
res.send({ exists: false });
}
})
.catch(error => {
console.error('Error checking room existence:', error);
});
});
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
Connection();
});