File size: 10,748 Bytes
4bae792
 
 
 
 
 
 
 
8c762ac
b4bf04d
57f5158
 
4bae792
 
8c762ac
 
4bae792
 
 
8c762ac
 
 
 
 
 
57f5158
 
 
 
8c762ac
4bae792
 
 
 
 
 
4c47e22
8c762ac
 
 
 
4c47e22
8c762ac
4bae792
 
8c762ac
4c47e22
57f5158
 
 
 
 
4bae792
 
57f5158
 
 
b4bf04d
 
 
57f5158
 
 
 
 
 
 
4bae792
 
 
4c47e22
4bae792
 
 
4c47e22
8c762ac
 
 
4c47e22
4bae792
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
 
 
 
57f5158
 
 
4bae792
 
8c762ac
 
 
 
 
 
 
 
 
 
 
b4bf04d
 
8c762ac
 
 
 
b4bf04d
 
8c762ac
 
 
b4bf04d
 
4c47e22
 
b4bf04d
 
8c762ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
 
57f5158
 
 
 
4bae792
 
 
57f5158
 
 
 
 
 
 
 
 
 
4bae792
 
 
 
 
 
 
8c762ac
57f5158
 
 
 
 
8c762ac
 
 
57f5158
 
 
 
 
8c762ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f5158
 
 
 
8c762ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
 
 
 
57f5158
 
 
 
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import { io } from "socket.io-client";

const SOCKET_URL = import.meta.env.VITE_SOCKET_URL || "http://localhost:3000";

class SocketService {
  constructor() {
    this.socket = null;
    this.listeners = new Map();
    this._connected = false;
    this._activeDMRooms = new Set();
    this._activeRooms = new Set();
    this._joinedRooms = new Set(); // Rooms that have received 'joinedRoom' ack
  }

  // ==================== Connection ====================

  connect() {
    if (this.socket?.connected) return;

    const token = localStorage.getItem("access_token");
    if (!token) {
      return;
    }

    this.socket = io(`${SOCKET_URL}/chat`, {
      // Use auth callback so socket.io reads fresh token on every connect/reconnect
      auth: (cb) => {
        cb({ token: localStorage.getItem("access_token") });
      },
      transports: ["websocket", "polling"],
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5,
    });

    this.socket.on("connect", () => {
      console.log("[Socket] Connected:", this.socket.id);
      this._connected = true;
    });

    this.socket.on("disconnect", (reason) => {
      console.log("[Socket] Disconnected:", reason);
      this._connected = false;
    });

    this.socket.on("connect_error", (error) => {
      console.error("[Socket] Connect error:", error.message);
      // If auth failed due to expired token, try to trigger a token refresh
      // by making a dummy API call. The axios interceptor will handle 401.
      if (error.message?.includes("jwt expired") || error.message?.includes("auth")) {
        this._handleAuthError();
      }
    });

    this.socket.on("reconnect", async (attemptNumber) => {
      console.log("[Socket] Reconnected after", attemptNumber, "attempts");
      // Re-join all active rooms with fresh token
      this._activeDMRooms.forEach((conversationId) => {
        this.joinDM(conversationId);
      });
      // Await room joins to ensure server is ready before sending
      const roomJoinPromises = Array.from(this._activeRooms).map((roomId) =>
        this.joinRoom(roomId).catch((err) => {
          console.warn("[Socket] Failed to rejoin room:", roomId, err);
        }),
      );
      await Promise.all(roomJoinPromises);
    });

    this.socket.on("reconnect_error", (error) => {
      console.error("[Socket] Reconnect error:", error.message);
    });

    this.socket.on("error", (error) => {
      console.error("[Socket] Error:", error);
    });

    this.socket.on("connected", (data) => {
      console.log("[Socket] Server ack:", data);
    });
  }

  // Trigger a token refresh by making a lightweight API call.
  // The axios response interceptor will handle 401 and refresh the token.
  _handleAuthError() {
    console.log("[Socket] Token may be expired, triggering refresh via API...");
    // Use a lightweight endpoint to trigger the refresh flow
    // The access token will be updated in localStorage by the interceptor
    import("./api").then(({ default: api }) => {
      api.get("/users/me").catch(() => {
        // Expected to fail or succeed; either way, token may have been refreshed
      });
    });
  }

  // Reconnect with fresh token. Call this after token refresh succeeds.
  reconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    this.connect();
  }

  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
    this._connected = false;
    this._activeDMRooms.clear();
    this._activeRooms.clear();
  }

  isConnected() {
    return this.socket?.connected || false;
  }

  getId() {
    return this.socket?.id || null;
  }

  // ==================== DM Room Events ====================

  joinDM(conversationId) {
    if (!conversationId) return;
    this._activeDMRooms.add(conversationId);
    this.socket?.emit("joinDM", { conversationId });
  }

  leaveDM(conversationId) {
    if (!conversationId) return;
    this._activeDMRooms.delete(conversationId);
    this.socket?.emit("leaveDM", { conversationId });
  }

  sendDM(conversationId, content, tempId) {
    if (!conversationId) return;
    const clientSentAt = Date.now();
    const payload = { conversationId, content, clientSentAt };
    if (tempId) payload.tempId = tempId;
    this.socket?.emit("sendDM", payload);
  }

  dmTyping(conversationId, isTyping) {
    this.socket?.emit("dmTyping", { conversationId, isTyping });
  }

  markDMRead(conversationId) {
    this.socket?.emit("markDMRead", { conversationId });
  }

  // ==================== Status Events ====================

  setStatus(status) {
    this.socket?.emit("setStatus", { status });
  }

  getOnlineUsers() {
    this.socket?.emit("getOnlineUsers");
  }

  // ==================== Notification Events ====================

  markNotificationRead(notificationId) {
    this.socket?.emit("markNotificationRead", { notificationId });
  }

  getUnreadCount() {
    this.socket?.emit("getUnreadCount");
  }

  // ==================== Room/Space Events (legacy) ====================

  joinRoom(roomId) {
    if (!roomId) return Promise.resolve();
    this._activeRooms.add(roomId);
    return new Promise((resolve) => {
      // Fast timeout — don't block UI if server is slow to ack
      const timeout = setTimeout(() => {
        this.socket?.off("joinedRoom", onJoined);
        this._joinedRooms.add(roomId); // Allow sending anyway
        console.warn("[Socket] joinRoom timeout, allowing sends for:", roomId);
        resolve({ roomId, timeout: true });
      }, 1500);
      const onJoined = (data) => {
        if (data?.roomId === roomId) {
          clearTimeout(timeout);
          this.socket?.off("joinedRoom", onJoined);
          this._joinedRooms.add(roomId);
          console.log("[Socket] Joined room:", roomId);
          resolve(data);
        }
      };
      this.socket?.on("joinedRoom", onJoined);
      this.socket?.emit("joinRoom", { roomId });
    });
  }

  leaveRoom(roomId) {
    if (!roomId) return;
    this._activeRooms.delete(roomId);
    this._joinedRooms.delete(roomId);
    this.socket?.emit("leaveRoom", { roomId });
  }

  sendMessage(data) {
    const { roomId } = data;
    // Auto-join if not yet acked but is active room (don't block send)
    if (roomId && !this._joinedRooms.has(roomId)) {
      if (this._activeRooms.has(roomId)) {
        console.warn("[Socket] Room not yet acked, allowing send anyway:", roomId);
      } else {
        console.warn("[Socket] Cannot send message - not in active rooms:", roomId);
        return;
      }
    }
    this.socket?.emit("sendMessage", data);
  }

  updateStatus(status) {
    this.socket?.emit("updateStatus", status);
  }

  emitTyping(roomId) {
    if (roomId && !this._activeRooms.has(roomId)) {
      console.warn("[Socket] Cannot emit typing - not active room:", roomId);
      return;
    }
    this.socket?.emit("typing", { roomId });
  }

  emitStopTyping(roomId) {
    if (roomId && !this._activeRooms.has(roomId)) {
      console.warn("[Socket] Cannot emit stopTyping - not active room:", roomId);
      return;
    }
    this.socket?.emit("stopTyping", { roomId });
  }

  // ==================== Listener Management ====================

  on(event, callback) {
    this.socket?.on(event, callback);
  }

  off(event, callback) {
    this.socket?.off(event, callback);
  }

  offEvent(event) {
    this.socket?.off(event);
  }

  removeAllListeners() {
    this.socket?.removeAllListeners();
  }

  // ==================== DM-specific Listeners ====================

  onJoinedDM(callback) {
    this.socket?.on("joinedDM", callback);
  }

  onLeftDM(callback) {
    this.socket?.on("leftDM", callback);
  }

  onNewDM(callback) {
    this.socket?.on("newDM", callback);
  }

  onDmSent(callback) {
    this.socket?.on("dmSent", callback);
  }

  onDmTyping(callback) {
    this.socket?.on("dmTyping", callback);
  }

  onDmRead(callback) {
    this.socket?.on("dmRead", callback);
  }

  onDmMarkedRead(callback) {
    this.socket?.on("dmMarkedRead", callback);
  }

  // ==================== User Status Listeners ====================

  onUserStatusChanged(callback) {
    this.socket?.on("userStatusChanged", callback);
  }

  onStatusSet(callback) {
    this.socket?.on("statusSet", callback);
  }

  onOnlineUsers(callback) {
    this.socket?.on("onlineUsers", callback);
  }

  onConnected(callback) {
    this.socket?.on("connected", callback);
  }

  // ==================== Notification Listeners ====================

  onNewNotification(callback) {
    this.socket?.on("newNotification", callback);
  }

  onNotificationsMarkedRead(callback) {
    this.socket?.on("notificationsMarkedRead", callback);
  }

  onUnreadCountUpdate(callback) {
    this.socket?.on("unreadCount", callback);
  }

  // ==================== Legacy Listeners ====================

  onNewMessage(callback) {
    this.socket?.on("newMessage", callback);
  }

  onMessageSent(callback) {
    this.socket?.on("messageSent", callback);
  }

  onMessageDeleted(callback) {
    this.socket?.on("messageDeleted", callback);
  }

  onMessageUpdated(callback) {
    this.socket?.on("messageUpdated", callback);
  }

  onMessagePinned(callback) {
    this.socket?.on("messagePinned", callback);
  }

  onMessageUnpinned(callback) {
    this.socket?.on("messageUnpinned", callback);
  }

  onReactionAdded(callback) {
    this.socket?.on("reactionAdded", callback);
  }

  onReactionRemoved(callback) {
    this.socket?.on("reactionRemoved", callback);
  }

  onTyping(callback) {
    this.socket?.on("typing", callback);
  }

  onStopTyping(callback) {
    this.socket?.on("stopTyping", callback);
  }

  onUserJoined(callback) {
    this.socket?.on("userJoined", callback);
  }

  onUserLeft(callback) {
    this.socket?.on("userLeft", callback);
  }

  onMemberJoinedSpace(callback) {
    this.socket?.on("memberJoinedSpace", callback);
  }

  onMemberLeftSpace(callback) {
    this.socket?.on("memberLeftSpace", callback);
  }

  onRoomCreated(callback) {
    this.socket?.on("roomCreated", callback);
  }

  onRoomUpdated(callback) {
    this.socket?.on("roomUpdated", callback);
  }

  onRoomDeleted(callback) {
    this.socket?.on("roomDeleted", callback);
  }

  onUserProfileUpdated(callback) {
    this.socket?.on("userProfileUpdated", callback);
  }

  onNotification(callback) {
    this.socket?.on("notification", callback);
  }

  onFileUploadProgress(callback) {
    this.socket?.on("fileUploadProgress", callback);
  }

  onFileUploadComplete(callback) {
    this.socket?.on("fileUploadComplete", callback);
  }

  onFileUploadError(callback) {
    this.socket?.on("fileUploadError", callback);
  }
}

export default new SocketService();