-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
81 lines (70 loc) · 2.16 KB
/
index.js
File metadata and controls
81 lines (70 loc) · 2.16 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
require('dotenv').config();
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const cors = require('cors');
const bodyParser = require('body-parser');
const db = require('./services/db');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
// API Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/users', require('./routes/users'));
app.use('/api/chat', require('./routes/chat'));
app.use('/api/groups', require('./routes/groups'));
app.use('/api/status', require('./routes/status'));
// Fallback for SPA (though we use a simple index.html)
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Socket.IO Connection Handling
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('join_room', (room) => {
socket.join(room);
console.log(`User ${socket.id} joined room: ${room}`);
});
socket.on('send_message', (data) => {
// Save to DB
const newMessage = db.insert('messages', {
text: data.text,
senderId: data.senderId,
senderName: data.senderName,
groupId: data.groupId || null,
timestamp: new Date().toISOString()
});
// Broadcast to the room (or globally if no groupId)
const target = data.groupId || 'global';
if (data.groupId) {
io.to(data.groupId).emit('receive_message', newMessage);
} else {
io.emit('receive_message', newMessage);
}
});
socket.on('status_update', (data) => {
// Broadcast status change to everyone
io.emit('status_changed', {
username: data.username,
status: data.status,
updatedAt: new Date().toISOString()
});
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`ChatStream server running on port ${PORT}`);
});