-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
307 lines (260 loc) · 7.65 KB
/
server.js
File metadata and controls
307 lines (260 loc) · 7.65 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
// MongoDB Connection
mongoose.connect('mongodb+srv://kalpeshpatil:aAizV2usnKqFAXnY@messaging.qnujm.mongodb.net/?retryWrites=true&w=majority', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('MongoDB connection error:', err));
// User Schema
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
isActive: {
type: Boolean,
default: true,
},
lastSeen: {
type: Date,
default: Date.now,
},
friends: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
pendingSentRequests: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
pendingReceivedRequests: [{ // Added this field
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
socketId: String
});
const User = mongoose.model('User', userSchema);
console.log('User', User)
// Message Schema
const messageSchema = new mongoose.Schema({
sender: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
receiver: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
content: {
type: String,
required: true
},
timestamp: {
type: Date,
default: Date.now
}
});
const Message = mongoose.model('Message', messageSchema);
// Middleware
app.use(cors({
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}));
app.use(express.json());
// Socket.IO setup
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
// Socket connection handling
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('join', async (username) => {
try {
const user = await User.findOneAndUpdate(
{ username },
{ isActive: true, lastSeen: new Date(), socketId: socket.id },
{ new: true }
);
debugger;
console.log('User',user);
if (user) {
socket.join(user._id.toString()); // Join a unique room for this user
socket.broadcast.emit('newUserLoggedIn', user);
io.emit('userStatusChanged', { userId: user._id, isActive: true });
}
} catch (error) {
console.error('Join error:', error);
}
});
socket.on('sendMessage', async (data) => {
try {
const newMessage = new Message({
sender: data.sender,
receiver: data.receiver,
content: data.content,
});
await newMessage.save();
console.log('Inside server.js');
const receiver = await User.findById(data.receiver);
if (receiver && receiver.socketId) {
io.to(receiver.socketId).emit('newMessage', newMessage);
// Emit notification for the new message
io.to(receiver.socketId).emit('notification', {
type: 'newMessage',
message: `New message from ${data.senderUsername}`,
});
}
} catch (error) {
console.error('Error sending message:', error);
}
});
socket.on('disconnect', async () => {
try {
const user = await User.findOneAndUpdate(
{ socketId: socket.id },
{ isActive: false, lastSeen: new Date() },
{ new: true }
);
if (user) {
io.emit('userStatusChanged', { userId: user._id, isActive: false });
}
} catch (error) {
console.error('Disconnect error:', error);
}
});
});
// API Routes
app.post('/api/users/login', async (req, res) => {
try {
const { username } = req.body;
let user = await User.findOne({ username });
if (!user) {
user = new User({ username });
await user.save();
}
user.isActive = true;
user.lastSeen = new Date();
await user.save();
res.json(user);
} catch (error) {
res.status(500).json({ error: 'Login failed' });
}
});
app.get('/api/users', async (req, res) => {
try {
const users = await User.find({});
res.json(users);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch users' });
}
});
app.get('/api/messages/:senderId/:receiverId', async (req, res) => {
try {
const { senderId, receiverId } = req.params;
const messages = await Message.find({
$or: [
{ sender: senderId, receiver: receiverId },
{ sender: receiverId, receiver: senderId }
]
}).sort({ timestamp: 1 });
res.json(messages);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch messages' });
}
});
app.post('/api/friend-request', async (req, res) => {
try {
const { fromUserId, toUserId } = req.body;
const [fromUser, toUser] = await Promise.all([
User.findById(fromUserId),
User.findById(toUserId),
]);
if (!toUser) {
return res.status(404).json({ error: 'User not found' });
}
if (
toUser.pendingReceivedRequests.includes(fromUserId) ||
fromUser.pendingSentRequests.includes(toUserId)
) {
return res.status(400).json({ error: 'Request already pending' });
}
fromUser.pendingSentRequests.push(toUserId);
toUser.pendingReceivedRequests.push(fromUserId);
await Promise.all([fromUser.save(), toUser.save()]);
// Emit event only to receiver
if (toUser.socketId) {
io.to(toUser.socketId).emit('friendRequest', {
fromUserId,
fromUsername: fromUser.username,
});
}
// Emit notification event
io.to(toUser.socketId).emit('notification', {
type: 'friendRequest',
message: `${fromUser.username} sent you a friend request.`,
});
res.json({ message: 'Friend request sent' });
} catch (error) {
console.error('Friend request error:', error);
res.status(500).json({ error: 'Failed to send friend request' });
}
});
app.post('/api/accept-friend', async (req, res) => {
try {
const { fromUserId, toUserId } = req.body;
const [fromUser, toUser] = await Promise.all([
User.findById(fromUserId),
User.findById(toUserId)
]);
// Add to friends lists
fromUser.friends.push(toUserId);
toUser.friends.push(fromUserId);
// Remove from pending requests
fromUser.pendingSentRequests = fromUser.pendingSentRequests.filter(
id => id.toString() !== toUserId
);
toUser.pendingReceivedRequests = toUser.pendingReceivedRequests.filter(
id => id.toString() !== fromUserId
);
await Promise.all([fromUser.save(), toUser.save()]);
// Notify both users
io.to(fromUser.socketId).emit('friendRequestAccepted', { userId: toUserId });
io.to(toUser.socketId).emit('friendRequestAccepted', { userId: fromUserId });
res.json({ message: 'Friend request accepted' });
} catch (error) {
res.status(500).json({ error: 'Failed to accept friend request' });
}
});
app.post('/api/reject-friend', async (req, res) => {
try {
const { fromUserId, toUserId } = req.body;
const toUser = await User.findById(toUserId);
toUser.pendingRequests = toUser.pendingRequests.filter(
id => id.toString() !== fromUserId
);
await toUser.save();
io.to(fromUserId).emit('friendRequestRejected', { userId: toUserId });
res.json({ message: 'Friend request rejected' });
} catch (error) {
res.status(500).json({ error: 'Failed to reject friend request' });
}
});
const PORT = process.env.PORT || 5003;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});