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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import logging
from typing import Dict, List, Optional, Any
from fastapi import WebSocket, WebSocketDisconnect, APIRouter
from pydantic import BaseModel
import json
import time

# Cấu hình logging
logger = logging.getLogger(__name__)

# Models cho Swagger documentation
class ConnectionStatus(BaseModel):
    user_id: str
    active: bool
    connection_count: int
    last_activity: Optional[float] = None

class UserConnection(BaseModel):
    user_id: str
    connection_count: int

class AllConnectionsStatus(BaseModel):
    total_users: int
    total_connections: int
    users: List[UserConnection]

# Khởi tạo router
router = APIRouter(
    prefix="/ws",
    tags=["WebSockets"],
)

class ConnectionManager:
    """Quản lý các kết nối WebSocket"""
    
    def __init__(self):
        # Lưu trữ các kết nối theo user_id
        self.active_connections: Dict[str, List[WebSocket]] = {}
        
    async def connect(self, websocket: WebSocket, user_id: str):
        """Kết nối một WebSocket mới"""
        await websocket.accept()
        if user_id not in self.active_connections:
            self.active_connections[user_id] = []
        self.active_connections[user_id].append(websocket)
        logger.info(f"New WebSocket connection for user {user_id}. Total connections: {len(self.active_connections[user_id])}")
        
    def disconnect(self, websocket: WebSocket, user_id: str):
        """Ngắt kết nối WebSocket"""
        if user_id in self.active_connections:
            if websocket in self.active_connections[user_id]:
                self.active_connections[user_id].remove(websocket)
            # Xóa user_id khỏi dict nếu không còn kết nối nào
            if not self.active_connections[user_id]:
                del self.active_connections[user_id]
        logger.info(f"WebSocket disconnected for user {user_id}")
        
    async def send_message(self, message: Dict[str, Any], user_id: str):
        """Gửi tin nhắn tới tất cả kết nối của một user"""
        if user_id in self.active_connections:
            disconnected_websockets = []
            for websocket in self.active_connections[user_id]:
                try:
                    await websocket.send_text(json.dumps(message))
                except Exception as e:
                    logger.error(f"Error sending message to WebSocket: {str(e)}")
                    disconnected_websockets.append(websocket)
            
            # Xóa các kết nối bị ngắt
            for websocket in disconnected_websockets:
                self.disconnect(websocket, user_id)
    
    def get_connection_status(self, user_id: str = None) -> Dict[str, Any]:
        """Lấy thông tin về trạng thái kết nối WebSocket"""
        if user_id:
            # Trả về thông tin kết nối cho user cụ thể
            if user_id in self.active_connections:
                return {
                    "user_id": user_id,
                    "active": True,
                    "connection_count": len(self.active_connections[user_id]),
                    "last_activity": time.time()
                }
            else:
                return {
                    "user_id": user_id,
                    "active": False,
                    "connection_count": 0,
                    "last_activity": None
                }
        else:
            # Trả về thông tin tất cả kết nối
            result = {
                "total_users": len(self.active_connections),
                "total_connections": sum(len(connections) for connections in self.active_connections.values()),
                "users": []
            }
            
            for uid, connections in self.active_connections.items():
                result["users"].append({
                    "user_id": uid,
                    "connection_count": len(connections)
                })
            
            return result


# Tạo instance của ConnectionManager
manager = ConnectionManager()

# Test route for manual WebSocket sending
@router.get("/ws/test/{user_id}")
async def test_websocket_send(user_id: str):
    """
    Test route to manually send a WebSocket message to a user
    This is useful for debugging WebSocket connections
    """
    logger.info(f"Attempting to send test message to user: {user_id}")
    
    # Check if user has a connection
    status = manager.get_connection_status(user_id)
    if not status["active"]:
        logger.warning(f"No active WebSocket connection for user: {user_id}")
        return {"success": False, "message": f"No active WebSocket connection for user: {user_id}"}
    
    # Send test message
    await manager.send_message({
        "type": "test_message",
        "message": "This is a test WebSocket message",
        "timestamp": int(time.time())
    }, user_id)
    
    logger.info(f"Test message sent to user: {user_id}")
    return {"success": True, "message": f"Test message sent to user: {user_id}"}

@router.websocket("/ws/pdf/{user_id}")
async def websocket_endpoint(websocket: WebSocket, user_id: str):
    """Endpoint WebSocket để cập nhật tiến trình xử lý PDF"""
    logger.info(f"WebSocket connection request received for user: {user_id}")
    
    try:
        await manager.connect(websocket, user_id)
        logger.info(f"WebSocket connection accepted for user: {user_id}")
        
        # Send a test message to confirm connection
        await manager.send_message({
            "type": "connection_established",
            "message": "WebSocket connection established successfully",
            "user_id": user_id,
            "timestamp": int(time.time())
        }, user_id)
        
        try:
            while True:
                # Đợi tin nhắn từ client (chỉ để giữ kết nối)
                data = await websocket.receive_text()
                logger.debug(f"Received from client: {data}")
                
                # Echo back to confirm receipt
                if data != "heartbeat":  # Don't echo heartbeats
                    await manager.send_message({
                        "type": "echo",
                        "message": f"Received: {data}",
                        "timestamp": int(time.time())
                    }, user_id)
        except WebSocketDisconnect:
            logger.info(f"WebSocket disconnected for user: {user_id}")
            manager.disconnect(websocket, user_id)
        except Exception as e:
            logger.error(f"WebSocket error: {str(e)}")
            manager.disconnect(websocket, user_id)
    except Exception as e:
        logger.error(f"Failed to establish WebSocket connection: {str(e)}")
        # Ensure the connection is closed properly
        if websocket.client_state != 4:  # 4 = CLOSED
            await websocket.close(code=1011, reason=f"Server error: {str(e)}")

import logging
from typing import Dict, List, Optional, Any
from fastapi import WebSocket, WebSocketDisconnect, APIRouter
from pydantic import BaseModel
import json
import time

# Cấu hình logging
logger = logging.getLogger(__name__)

# Models cho Swagger documentation
class ConnectionStatus(BaseModel):
    user_id: str
    active: bool
    connection_count: int
    last_activity: Optional[float] = None

class UserConnection(BaseModel):
    user_id: str
    connection_count: int

class AllConnectionsStatus(BaseModel):
    total_users: int
    total_connections: int
    users: List[UserConnection]

# Khởi tạo router
router = APIRouter(
    prefix="",
    tags=["WebSockets"],
)

class ConnectionManager:
    """Quản lý các kết nối WebSocket"""
    
    def __init__(self):
        # Lưu trữ các kết nối theo user_id
        self.active_connections: Dict[str, List[WebSocket]] = {}
        
    async def connect(self, websocket: WebSocket, user_id: str):
        """Kết nối một WebSocket mới"""
        await websocket.accept()
        if user_id not in self.active_connections:
            self.active_connections[user_id] = []
        self.active_connections[user_id].append(websocket)
        logger.info(f"New WebSocket connection for user {user_id}. Total connections: {len(self.active_connections[user_id])}")
        
    def disconnect(self, websocket: WebSocket, user_id: str):
        """Ngắt kết nối WebSocket"""
        if user_id in self.active_connections:
            if websocket in self.active_connections[user_id]:
                self.active_connections[user_id].remove(websocket)
            # Xóa user_id khỏi dict nếu không còn kết nối nào
            if not self.active_connections[user_id]:
                del self.active_connections[user_id]
        logger.info(f"WebSocket disconnected for user {user_id}")
        
    async def send_message(self, message: Dict[str, Any], user_id: str):
        """Gửi tin nhắn tới tất cả kết nối của một user"""
        if user_id in self.active_connections:
            disconnected_websockets = []
            for websocket in self.active_connections[user_id]:
                try:
                    await websocket.send_text(json.dumps(message))
                except Exception as e:
                    logger.error(f"Error sending message to WebSocket: {str(e)}")
                    disconnected_websockets.append(websocket)
            
            # Xóa các kết nối bị ngắt
            for websocket in disconnected_websockets:
                self.disconnect(websocket, user_id)
    
    def get_connection_status(self, user_id: str = None) -> Dict[str, Any]:
        """Lấy thông tin về trạng thái kết nối WebSocket"""
        if user_id:
            # Trả về thông tin kết nối cho user cụ thể
            if user_id in self.active_connections:
                return {
                    "user_id": user_id,
                    "active": True,
                    "connection_count": len(self.active_connections[user_id]),
                    "last_activity": time.time()
                }
            else:
                return {
                    "user_id": user_id,
                    "active": False,
                    "connection_count": 0,
                    "last_activity": None
                }
        else:
            # Trả về thông tin tất cả kết nối
            result = {
                "total_users": len(self.active_connections),
                "total_connections": sum(len(connections) for connections in self.active_connections.values()),
                "users": []
            }
            
            for uid, connections in self.active_connections.items():
                result["users"].append({
                    "user_id": uid,
                    "connection_count": len(connections)
                })
            
            return result


# Tạo instance của ConnectionManager
manager = ConnectionManager()

@router.websocket("/ws/pdf/{user_id}")
async def websocket_endpoint(websocket: WebSocket, user_id: str):
    """Endpoint WebSocket để cập nhật tiến trình xử lý PDF"""
    await manager.connect(websocket, user_id)
    try:
        while True:
            # Đợi tin nhắn từ client (chỉ để giữ kết nối)
            await websocket.receive_text()
    except WebSocketDisconnect:
        manager.disconnect(websocket, user_id)
    except Exception as e:
        logger.error(f"WebSocket error: {str(e)}")
        manager.disconnect(websocket, user_id)

# API endpoints để kiểm tra trạng thái WebSocket
@router.get("/ws/status", response_model=AllConnectionsStatus, responses={
    200: {
        "description": "Successful response",
        "content": {
            "application/json": {
                "example": {
                    "total_users": 2,
                    "total_connections": 3,
                    "users": [
                        {"user_id": "user1", "connection_count": 2},
                        {"user_id": "user2", "connection_count": 1}
                    ]
                }
            }
        }
    }
})
async def get_all_websocket_connections():
    """
    Lấy thông tin về tất cả kết nối WebSocket hiện tại.
    
    Endpoint này trả về:
    - Tổng số người dùng đang kết nối
    - Tổng số kết nối WebSocket
    - Danh sách người dùng kèm theo số lượng kết nối của mỗi người
    """
    return manager.get_connection_status()

@router.get("/ws/status/{user_id}", response_model=ConnectionStatus, responses={
    200: {
        "description": "Successful response for active connection",
        "content": {
            "application/json": {
                "examples": {
                    "active_connection": {
                        "summary": "Active connection",
                        "value": {
                            "user_id": "user123",
                            "active": True,
                            "connection_count": 2,
                            "last_activity": 1634567890.123
                        }
                    },
                    "no_connection": {
                        "summary": "No active connection",
                        "value": {
                            "user_id": "user456",
                            "active": False,
                            "connection_count": 0,
                            "last_activity": None
                        }
                    }
                }
            }
        }
    }
})
async def get_user_websocket_status(user_id: str):
    """
    Lấy thông tin về kết nối WebSocket của một người dùng cụ thể.
    
    Parameters:
    - **user_id**: ID của người dùng cần kiểm tra
    
    Returns:
    - Thông tin về trạng thái kết nối, bao gồm:
      - active: Có đang kết nối hay không
      - connection_count: Số lượng kết nối hiện tại
      - last_activity: Thời gian hoạt động gần nhất
    """
    return manager.get_connection_status(user_id)

# Các hàm gửi thông báo cập nhật trạng thái

async def send_pdf_upload_started(user_id: str, filename: str, document_id: str):
    """Gửi thông báo bắt đầu upload PDF"""
    await manager.send_message({
        "type": "pdf_upload_started",
        "document_id": document_id,
        "filename": filename,
        "timestamp": int(time.time())
    }, user_id)

async def send_pdf_upload_progress(user_id: str, document_id: str, step: str, progress: float, message: str):
    """Gửi thông báo tiến độ upload PDF"""
    await manager.send_message({
        "type": "pdf_upload_progress",
        "document_id": document_id,
        "step": step,
        "progress": progress,
        "message": message,
        "timestamp": int(time.time())
    }, user_id)

async def send_pdf_upload_completed(user_id: str, document_id: str, filename: str, chunks: int):
    """Gửi thông báo hoàn thành upload PDF"""
    await manager.send_message({
        "type": "pdf_upload_completed",
        "document_id": document_id,
        "filename": filename,
        "chunks": chunks,
        "timestamp": int(time.time())
    }, user_id)

async def send_pdf_upload_failed(user_id: str, document_id: str, filename: str, error: str):
    """Gửi thông báo lỗi upload PDF"""
    await manager.send_message({
        "type": "pdf_upload_failed",
        "document_id": document_id,
        "filename": filename,
        "error": error,
        "timestamp": int(time.time())
    }, user_id)

async def send_pdf_delete_started(user_id: str, namespace: str):
    """Gửi thông báo bắt đầu xóa PDF"""
    await manager.send_message({
        "type": "pdf_delete_started",
        "namespace": namespace,
        "timestamp": int(time.time())
    }, user_id)

async def send_pdf_delete_completed(user_id: str, namespace: str, deleted_count: int = 0):
    """Gửi thông báo hoàn thành xóa PDF"""
    await manager.send_message({
        "type": "pdf_delete_completed",
        "namespace": namespace,
        "deleted_count": deleted_count,
        "timestamp": int(time.time())
    }, user_id)

async def send_pdf_delete_failed(user_id: str, namespace: str, error: str):
    """Gửi thông báo lỗi xóa PDF"""
    await manager.send_message({
        "type": "pdf_delete_failed",
        "namespace": namespace,
        "error": error,
        "timestamp": int(time.time())
    }, user_id)