Spaces:
Running

File size: 5,344 Bytes
5b6905f
 
 
 
 
 
 
 
 
22d0ba7
5b6905f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8da7f23
5b6905f
 
 
 
 
 
 
8da7f23
5b6905f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8da7f23
5b6905f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8da7f23
 
 
5b6905f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
WebSocket Chat - Real-time messaging for chat interface.

Provides instant message updates without polling.
"""

from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query
from app.core.security import decode_access_token
from app.core.database import get_session
from app.models.lead import Lead, Message, Conversation
from sqlalchemy import select
from uuid import UUID
from typing import Dict, Set
import logging
import json
import asyncio

router = APIRouter()
logger = logging.getLogger(__name__)

# Store active connections per lead_id
# Structure: {lead_id: {websocket1, websocket2, ...}}
active_connections: Dict[str, Set[WebSocket]] = {}


class ConnectionManager:
    """Manages WebSocket connections for chat."""
    
    def __init__(self):
        self.connections: Dict[str, Set[WebSocket]] = {}
    
    async def connect(self, lead_id: str, websocket: WebSocket):
        """Add a connection for a lead."""
        if lead_id not in self.connections:
            self.connections[lead_id] = set()
        self.connections[lead_id].add(websocket)
        logger.debug(f"πŸ”Œ Chat WS connected: lead={lead_id}, total={len(self.connections[lead_id])}")
    
    def disconnect(self, lead_id: str, websocket: WebSocket):
        """Remove a connection."""
        if lead_id in self.connections:
            self.connections[lead_id].discard(websocket)
            if not self.connections[lead_id]:
                del self.connections[lead_id]
            logger.debug(f"πŸ”Œ Chat WS disconnected: lead={lead_id}")
    
    async def broadcast_to_lead(self, lead_id: str, message: dict):
        """Send message to all connections watching a lead."""
        if lead_id in self.connections:
            dead_connections = set()
            for ws in self.connections[lead_id]:
                try:
                    await ws.send_json(message)
                except Exception as e:
                    logger.warning(f"Failed to send to WS: {e}")
                    dead_connections.add(ws)
            
            # Clean up dead connections
            for ws in dead_connections:
                self.connections[lead_id].discard(ws)


manager = ConnectionManager()


@router.websocket("/{lead_id}")
async def chat_websocket(
    websocket: WebSocket,
    lead_id: str,
    token: str = Query(...)
):
    """
    WebSocket endpoint for real-time chat updates.
    
    Events sent to client:
    - new_message: New message in conversation
    - lead_updated: Lead data changed
    - typing: Someone is typing
    
    Client can send:
    - ping: Keep-alive
    - typing: Notify others of typing
    """
    await websocket.accept()
    
    # Authenticate
    try:
        payload = decode_access_token(token)
        user_id = payload.get("sub")
        tenant_id = payload.get("tenant_id")
        
        if not user_id:
            await websocket.close(code=4001, reason="Invalid token")
            return
        
        logger.debug(f"πŸ”Œ Chat WS authenticated: user={user_id}, lead={lead_id}")
        
    except Exception as e:
        logger.error(f"Chat WS auth failed: {e}")
        await websocket.close(code=4003, reason="Authentication failed")
        return
    
    # Connect
    await manager.connect(lead_id, websocket)
    
    try:
        # Send initial connection confirmation
        await websocket.send_json({
            "type": "connected",
            "lead_id": lead_id
        })
        
        while True:
            # Receive messages from client
            message = await websocket.receive()
            
            if "text" in message:
                try:
                    data = json.loads(message["text"])
                    msg_type = data.get("type")
                    
                    if msg_type == "ping":
                        await websocket.send_json({"type": "pong"})
                    
                    elif msg_type == "typing":
                        # Broadcast typing indicator to others
                        await manager.broadcast_to_lead(lead_id, {
                            "type": "typing",
                            "user_id": user_id
                        })
                        
                except json.JSONDecodeError:
                    pass
                    
    except WebSocketDisconnect:
        manager.disconnect(lead_id, websocket)
    except Exception as e:
        # Suppress expected disconnect errors
        if "disconnect" not in str(e).lower():
            logger.warning(f"Chat WS error: {e}")
        manager.disconnect(lead_id, websocket)
        try:
            await websocket.close()
        except:
            pass


async def notify_new_message(lead_id: str, message_data: dict):
    """
    Call this from message handlers to notify WebSocket clients.
    
    Args:
        lead_id: The lead ID
        message_data: Message dict with id, content, sender_type, media_url, etc.
    """
    await manager.broadcast_to_lead(str(lead_id), {
        "type": "new_message",
        "message": message_data
    })


async def notify_lead_updated(lead_id: str, lead_data: dict):
    """
    Call this when lead data changes (status, heat_level, etc.)
    """
    await manager.broadcast_to_lead(str(lead_id), {
        "type": "lead_updated",
        "lead": lead_data
    })