-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
372 lines (297 loc) · 12.3 KB
/
server.js
File metadata and controls
372 lines (297 loc) · 12.3 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/***
*
* Deprecated File :
*
* 15.12.2024
*/
const express = require('express');
const http = require('http');
const compression = require('compression');
const cors = require('cors');
const cookieParser = require('cookie-parser');
//const socketIo = require('socket.io');
const { Server } = require('socket.io');
const dotenv = require('dotenv');
const db = require("./config/database");
const userRoutes = require("./routes/usersRoutes");
const specializationRoutes = require("./routes/SpecializationsRoutes");
const articleRoutes = require("./routes/articleRoutes");
const analyticsRoute = require('./routes/analyticsRoute');
const uploadRoute = require('./routes/uploadRoute');
require('./controllers/commentController');
const swaggerUi = require('swagger-ui-express');
const swaggerSpec = require('./swagger');
//////////////////////////////////////////
const Article = require('./models/Articles');
const User = require('./models/UserModel');
const Comment = require('./models/commentSchema');
const expressAsyncHandler = require('express-async-handler');
// Load environment variables from .env file
dotenv.config();
const PORT = process.env.PORT || 4000;
const app = express();
const server = http.createServer(app);
// Database connection
db.dbConnect(); // Make sure your database connection works properly
// Use middlewares
app.use(cookieParser()); // Parse cookies
app.use(compression()); // Compress response bodies
app.use(express.json()); // Parse incoming JSON requests
// Enable CORS (with appropriate configuration)
app.use(cors({
origin: '*', // Allow all origins (be careful with this in production)
methods: ['GET', 'POST', 'PUT', 'DELETE']
}));
// Define routes
app.use("/api", userRoutes);
app.use("/api", specializationRoutes);
app.use("/api", articleRoutes);
app.use("/api", uploadRoute);
app.use("/api/analytics", analyticsRoute);
// Swagger
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// Test route (can be removed later)
app.get("/hello", (req, res) => {
console.log("Hello World");
res.send('Hello World');
});
// Initialize Socket.io
const io = new Server(server, {
cors: {
origin: '*', // Allow all origins
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type'],
credentials: true
}
});
//const io = socketIo(server, );
// Handle socket events for comments
//handleSocketEvents(io);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('connect', () => {
console.log('Connected to server');
socket.emit("connect", "Some thing to show");
});
socket.on('add-comment', expressAsyncHandler(
async (data) => {
console.log('Add Event called');
const { userId, articleId, content, parentCommentId } = data;
if (!userId || !articleId || !content || content.trim() === '') {
socket.emit('error', 'Missing required fields');
return;
}
try {
const [user, article] = await Promise.all([
User.findById(userId),
Article.findById(Number(articleId))
]);
if (!user || !article || article.is_removed) {
socket.emit('error', 'User or article not found');
return;
}
if (user.isBlockUser || user.isBannedUser) {
socket.emit('error', { message: 'User is blocked or banned' });
return;
}
const newComment = new Comment({
userId,
articleId,
parentCommentId: parentCommentId || null,
content
});
await newComment.save();
// Now emit event
if (parentCommentId) {
const parentComment = Comment.findById(parentCommentId);
if (!parentComment) {
socket.emit('error', { message: 'Parent comment not found' });
return;
}
parentComment.replies.push(newComment._id);
await parentComment.save();
io.emit('update-parent-comment', {
parentCommentId: parentComment._id,
parentComment
});
io.emit('new-reply', {
parentCommentId: parentCommentId,
reply: newComment,
articleId: articleId
});
} else {
io.emit('new-comment', {
comment: newComment,
articleId
});
}
} catch (err) {
console.error('Error adding comment:', err);
socket.emit('error', { message: 'Error adding comment' });
}
}
))
socket.on('edit-comment', expressAsyncHandler(
async (data) => {
const { commentId, content, articleId } = data;
if (!commentId || !content || !articleId || content.trim() === '') {
socket.emit('error', { message: 'Invalid request: Comment ID and non-empty content are required.' });
return;
}
try {
const [comment, user, article] = await Promise.all([
Comment.findById(commentId),
User.findById(data.userId),
Article.findById(articleId)
]);
if (!comment || !user || !article || article.is_removed) {
socket.emit('error', { message: 'Comment or user or article not found' });
return;
}
if (user.isBlockUser || user.isBannedUser) {
socket.emit('error', { message: 'You are blocked or banned' });
return;
}
if (comment.userId.toString() !== user._id.toString()) {
socket.emit('error', { message: 'You are not authorized to edit this comment' });
return;
}
comment.content = content;
comment.updatedAt = new Date();
comment.isEdited = true;
await comment.save();
io.emit('edit-comment', comment); // Broadcast the edited comment
} catch (err) {
console.error("Error editing comment:", err);
socket.emit('error', { message: 'Error editing comment' });
}
}
));
socket.on('delete-comment', expressAsyncHandler(
async (data) => {
const { commentId, articleId } = data;
if (!commentId || !articleId) {
socket.emit('error', { message: 'Invalid request: Comment ID and article ID are required.' });
return;
}
try {
const [comment, user] = await Promise.all([
Comment.findById(commentId),
User.findById(data.userId)
]);
if (!comment || !user) {
socket.emit('error', { message: 'Comment or user not found' });
return;
}
// Check if the user is authorized to delete the comment
if (comment.userId.toString() !== data.userId) {
socket.emit('error', { message: 'You are not authorized to delete this comment' });
return;
}
if (user.isBlockUser || user.isBannedUser) {
socket.emit('error', { message: 'You are blocked or banned' });
return;
}
comment.status = 'Deleted';
comment.updatedAt = new Date();
await comment.save();
// If it's a reply, update the parent comment
if (comment.parentCommentId) {
const parentComment = await Comment.findById(comment.parentCommentId);
if (parentComment) {
parentComment.replies = parentComment.replies.filter(replyId => replyId.toString() !== commentId);
await parentComment.save();
io.emit('update-parent-comment', {
parentCommentId: comment.parentCommentId,
parentComment
});
}
}
io.emit('delete-comment', { commentId, articleId });
} catch (err) {
console.error('Error deleting comment:', err);
socket.emit('error', { message: 'Error deleting comment' });
}
}
));
socket.on('like-comment', expressAsyncHandler(
async (data) => {
const { commentId, articleId, userId } = data;
if (!commentId || !articleId || !userId) {
socket.emit('error', { message: "Invalid request: Comment ID, Article ID, and User ID are required." });
return;
}
try {
const [comment, user] = await Promise.all([
Comment.findById(commentId).populate('likedUsers'),
User.findById(userId)
]);
if (!comment || !user) {
socket.emit('error', { message: 'Comment or user not found' });
return;
}
if (user.isBlockUser || user.isBannedUser) {
socket.emit('error', { message: 'User is blocked or banned' });
return;
}
const hasLiked = comment.likedUsers.some(like => like._id.toString() === userId);
if (hasLiked) {
// Unlike the comment
await Comment.findByIdAndUpdate(commentId, {
$pull: { likedUsers: userId }
});
io.emit('unlike-comment', { commentId, userId, articleId });
} else {
// Like the comment
await Comment.findByIdAndUpdate(commentId, {
$addToSet: { likedUsers: userId }
});
io.emit('like-comment', { commentId, userId, articleId });
}
} catch (err) {
console.error('Error liking/unliking comment:', err);
socket.emit('error', { message: 'Error processing like/unlike' });
}
}
));
socket.on('fetch-comments', expressAsyncHandler(
async (data) => {
const { articleId } = data;
console.log("fetch comment called");
if (!articleId) {
socket.emit('error', { message: 'Article ID is required.' });
return;
}
try {
const article = await Article.findById(articleId);
if (!article || article.is_removed) {
socket.emit('error', { message: 'Article not found.' });
return;
}
// Fetch all active comments related to the article
const comments = await Comment.find({ articleId: articleId, status: 'Active' })
.populate('userId', 'user_handle Profile_image') // Populate user details
.populate('replies') // Populate replies for each comment
.sort({ createdAt: -1 }); // Sort by most recent first
// Emit the comments and replies to the client
socket.emit('comments-loaded', {
articleId,
comments: comments
});
} catch (err) {
console.error('Error fetching comments:', err);
socket.emit('error', { message: 'Error fetching comments.' });
}
}
));
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
// Start server
server.listen(PORT, () => {
// console.log(`Server is running on port ${PORT}`);
console.log(`Docs: http://localhost:${PORT}/docs`);
});
// Export the app for testing or other purposes
module.exports = app;