-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
235 lines (202 loc) · 6.69 KB
/
server.ts
File metadata and controls
235 lines (202 loc) · 6.69 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
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { Server, Socket } from "socket.io";
// Extend Socket interface to include custom properties
interface ExtendedSocket extends Socket {
userId?: string;
}
// Types pour le status manager
type UserStatus = 'ONLINE' | 'IDLE' | 'DND' | 'OFFLINE' | 'INVISIBLE';
interface StatusData {
userId: string;
status: UserStatus;
lastSeen: Date;
}
// Status Manager simplifié inline
class StatusManager {
private static instance: StatusManager;
private statusMap: Map<string, StatusData> = new Map();
private heartbeatIntervals: Map<string, NodeJS.Timeout> = new Map();
private readonly HEARTBEAT_INTERVAL = 5 * 60 * 1000; // 5 minutes
private readonly OFFLINE_TIMEOUT = 15 * 60 * 1000; // 15 minutes without heartbeat
static getInstance(): StatusManager {
if (!StatusManager.instance) {
StatusManager.instance = new StatusManager();
}
return StatusManager.instance;
}
registerUser(userId: string, initialStatus: UserStatus = 'ONLINE'): void {
const statusData: StatusData = {
userId,
status: initialStatus,
lastSeen: new Date()
};
this.statusMap.set(userId, statusData);
this.startHeartbeat(userId);
}
unregisterUser(userId: string): void {
this.stopHeartbeat(userId);
this.updateStatus(userId, 'OFFLINE');
}
updateStatus(userId: string, status: UserStatus): void {
const current = this.statusMap.get(userId);
if (current) {
current.status = status;
current.lastSeen = new Date();
this.statusMap.set(userId, current);
}
}
recordActivity(userId: string): void {
const current = this.statusMap.get(userId);
if (current && current.status !== 'DND' && current.status !== 'INVISIBLE') {
current.status = 'ONLINE';
current.lastSeen = new Date();
this.statusMap.set(userId, current);
}
}
getStatus(userId: string): UserStatus | null {
const statusData = this.statusMap.get(userId);
if (!statusData) return null;
const timeSinceLastSeen = Date.now() - statusData.lastSeen.getTime();
if (timeSinceLastSeen > this.OFFLINE_TIMEOUT && statusData.status !== 'INVISIBLE') {
statusData.status = 'OFFLINE';
this.statusMap.set(userId, statusData);
}
return statusData.status;
}
getAllStatuses(): Map<string, UserStatus> {
const result = new Map<string, UserStatus>();
this.statusMap.forEach((statusData, userId) => {
result.set(userId, this.getStatus(userId) || 'OFFLINE');
});
return result;
}
private startHeartbeat(userId: string): void {
this.stopHeartbeat(userId);
const interval = setInterval(() => {
this.updateStatus(userId, this.getStatus(userId) || 'OFFLINE');
}, this.HEARTBEAT_INTERVAL);
this.heartbeatIntervals.set(userId, interval);
}
private stopHeartbeat(userId: string): void {
const interval = this.heartbeatIntervals.get(userId);
if (interval) {
clearInterval(interval);
this.heartbeatIntervals.delete(userId);
}
}
}
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const httpServer = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url!, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error occurred handling", req.url, err);
res.statusCode = 500;
res.end("internal server error");
}
});
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
const statusManager = StatusManager.getInstance();
io.on("connection", (socket: ExtendedSocket) => {
console.log("A user connected:", socket.id);
// Handle user authentication and status registration
socket.on("authenticate", (userData) => {
console.log(`User ${userData.userId} authenticated with socket ${socket.id}`);
socket.userId = userData.userId;
socket.join(`user-${userData.userId}`);
// Register user for status tracking
statusManager.registerUser(userData.userId, userData.status || 'ONLINE');
// Broadcast status to all users
io.emit("user-status-update", {
userId: userData.userId,
status: statusManager.getStatus(userData.userId)
});
});
socket.on("join-room", (roomId) => {
socket.join(roomId);
console.log(`User ${socket.userId} joined room ${roomId}`);
});
socket.on("send-message", (data) => {
// Only send to users in the specific channel
io.to(data.channelId).emit("new-message", data.message);
});
socket.on("typing", (data) => {
// Send typing indicator only to users in the same channel
socket.to(data.channelId).emit("user-typing", data);
});
// Handle status updates
socket.on("status-update", (status: UserStatus) => {
if (socket.userId) {
statusManager.updateStatus(socket.userId, status);
io.emit("user-status-update", {
userId: socket.userId,
status: status
});
}
});
// Handle activity tracking
socket.on("activity", () => {
if (socket.userId) {
statusManager.recordActivity(socket.userId);
const currentStatus = statusManager.getStatus(socket.userId);
if (currentStatus && currentStatus !== statusManager.getStatus(socket.userId)) {
io.emit("user-status-update", {
userId: socket.userId,
status: currentStatus
});
}
}
});
// Handle heartbeat
socket.on("heartbeat", () => {
if (socket.userId) {
const currentStatus = statusManager.getStatus(socket.userId);
if (currentStatus) {
statusManager.updateStatus(socket.userId, currentStatus);
}
}
});
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
if (socket.userId) {
// Mark user as offline and broadcast
statusManager.unregisterUser(socket.userId);
io.emit("user-status-update", {
userId: socket.userId,
status: 'OFFLINE'
});
}
});
});
// Periodic status broadcast and cleanup
setInterval(() => {
const allStatuses = statusManager.getAllStatuses();
allStatuses.forEach((status, userId) => {
io.emit("user-status-update", {
userId,
status
});
});
}, 30000); // Broadcast every 30 seconds
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});