File size: 4,143 Bytes
c0b84a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Real-time Messaging Service using WebSockets
 * 
 * Manages WebSocket connections for real-time message delivery.
 * Each user can have a WebSocket connection that receives messages in real-time.
 */

interface MessageSubscriber {
    userId: string;
    callback: (message: any) => void;
}

interface ActiveConnection {
    userId: string;
    listeners: Set<(message: any) => void>;
}

class RealtimeMessagingService {
    private activeConnections: Map<string, ActiveConnection> = new Map();
    private messageSubscribers: MessageSubscriber[] = [];

    /**
     * Register a new WebSocket connection for a user
     */
    registerConnection(userId: string, callback: (message: any) => void): () => void {
        if (!this.activeConnections.has(userId)) {
            this.activeConnections.set(userId, {
                userId,
                listeners: new Set(),
            });
        }

        const connection = this.activeConnections.get(userId)!;
        connection.listeners.add(callback);

        // Return unsubscribe function
        return () => {
            connection.listeners.delete(callback);
            if (connection.listeners.size === 0) {
                this.activeConnections.delete(userId);
            }
        };
    }

    /**
     * Broadcast a message to a specific user
     */
    broadcastToUser(userId: string, message: any): void {
        const connection = this.activeConnections.get(userId);
        if (connection) {
            connection.listeners.forEach(callback => {
                try {
                    callback(message);
                } catch (error) {
                    console.error(`Error broadcasting message to user ${userId}:`, error);
                }
            });
        }
    }

    /**
     * Notify both sender and receiver of a new message
     */
    notifyMessageSent(message: {
        id: string;
        sender_id: string;
        receiver_id: string;
        content: string;
        read: boolean;
        timestamp: string;
        edited_at?: string | null;
    }): void {
        // Notify receiver
        this.broadcastToUser(message.receiver_id, {
            type: 'message_received',
            data: message,
        });

        // Notify sender (for UI update confirmation)
        this.broadcastToUser(message.sender_id, {
            type: 'message_sent',
            data: message,
        });
    }

    /**
     * Notify user of message read status update
     */
    notifyMessageRead(messageId: string, senderId: string): void {
        this.broadcastToUser(senderId, {
            type: 'message_read',
            data: { messageId },
        });
    }

    /**
     * Notify user of message edit
     */
    notifyMessageEdited(message: {
        id: string;
        sender_id: string;
        receiver_id: string;
        content: string;
        edited_at: string;
    }): void {
        this.broadcastToUser(message.receiver_id, {
            type: 'message_edited',
            data: message,
        });

        this.broadcastToUser(message.sender_id, {
            type: 'message_edited',
            data: message,
        });
    }

    /**
     * Notify user of message deletion
     */
    notifyMessageDeleted(messageId: string, senderId: string, receiverId: string): void {
        this.broadcastToUser(receiverId, {
            type: 'message_deleted',
            data: { messageId },
        });

        this.broadcastToUser(senderId, {
            type: 'message_deleted',
            data: { messageId },
        });
    }

    /**
     * Get the list of active user IDs
     */
    getActiveUsers(): string[] {
        return Array.from(this.activeConnections.keys());
    }

    /**
     * Check if a user is currently connected
     */
    isUserOnline(userId: string): boolean {
        return this.activeConnections.has(userId);
    }

    /**
     * Get number of active connections for a user
     */
    getConnectionCount(userId: string): number {
        return this.activeConnections.get(userId)?.listeners.size ?? 0;
    }
}

export const realtimeMessaging = new RealtimeMessagingService();