Fred808 commited on
Commit
7085b88
·
verified ·
1 Parent(s): f674d57

Update app/services/websocket.py

Browse files
Files changed (1) hide show
  1. app/services/websocket.py +80 -63
app/services/websocket.py CHANGED
@@ -1,63 +1,80 @@
1
- from typing import List, Dict, Any
2
- from fastapi import WebSocket
3
- from datetime import datetime
4
- from ..db.database import db
5
- from ..utils.cache import cache
6
-
7
- # Store active WebSocket connections
8
- active_connections: List[WebSocket] = []
9
-
10
- async def connect(websocket: WebSocket):
11
- """Accept a new WebSocket connection"""
12
- await websocket.accept()
13
- active_connections.append(websocket)
14
-
15
- async def disconnect(websocket: WebSocket):
16
- """Remove a WebSocket connection"""
17
- if websocket in active_connections:
18
- active_connections.remove(websocket)
19
-
20
- async def broadcast_message(message: dict):
21
- """Broadcast a message to all connected clients"""
22
- disconnected = []
23
- for connection in active_connections:
24
- try:
25
- await connection.send_json(message)
26
- except:
27
- disconnected.append(connection)
28
-
29
- # Clean up disconnected clients
30
- for connection in disconnected:
31
- await disconnect(connection)
32
-
33
- async def create_and_broadcast_notification(
34
- user_id: str,
35
- title: str,
36
- message: str,
37
- notification_type: str,
38
- data: Dict[str, Any] = None
39
- ) -> Dict[str, Any]:
40
- """Create and broadcast a notification"""
41
- notification = {
42
- "user_id": user_id,
43
- "title": title,
44
- "message": message,
45
- "type": notification_type,
46
- "data": data,
47
- "created_at": datetime.utcnow(),
48
- "read": False
49
- }
50
-
51
- # Store in database
52
- await db.db["notifications"].insert_one(notification)
53
-
54
- # Broadcast to connected clients
55
- await broadcast_message({
56
- "type": "notification",
57
- "data": notification
58
- })
59
-
60
- # Clear user's notification cache
61
- await cache.delete_cache(f"user_notifications:{user_id}")
62
-
63
- return notification
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Any
2
+ from fastapi import WebSocket
3
+ from datetime import datetime
4
+ from ..db.database import db
5
+ from ..utils.cache import cache
6
+ from ..db.models import Notification
7
+
8
+ # Store active WebSocket connections
9
+ active_connections: List[WebSocket] = []
10
+
11
+ async def connect(websocket: WebSocket):
12
+ """Accept a new WebSocket connection"""
13
+ await websocket.accept()
14
+ active_connections.append(websocket)
15
+
16
+ async def disconnect(websocket: WebSocket):
17
+ """Remove a WebSocket connection"""
18
+ if websocket in active_connections:
19
+ active_connections.remove(websocket)
20
+
21
+ async def broadcast_message(message: dict):
22
+ """Broadcast a message to all connected clients"""
23
+ disconnected = []
24
+ for connection in active_connections:
25
+ try:
26
+ await connection.send_json(message)
27
+ except:
28
+ disconnected.append(connection)
29
+
30
+ # Clean up disconnected clients
31
+ for connection in disconnected:
32
+ await disconnect(connection)
33
+
34
+ async def create_and_broadcast_notification(
35
+ user_id: str,
36
+ title: str,
37
+ message: str,
38
+ notification_type: str,
39
+ data: Dict[str, Any] = None
40
+ ) -> Dict[str, Any]:
41
+ """Create and broadcast a notification"""
42
+ async with db.session() as session:
43
+ # Create notification
44
+ notification = Notification(
45
+ user_id=user_id,
46
+ title=title,
47
+ message=message,
48
+ type=notification_type,
49
+ data=data,
50
+ created_at=datetime.utcnow(),
51
+ read=False
52
+ )
53
+
54
+ # Store in database
55
+ session.add(notification)
56
+ await session.commit()
57
+ await session.refresh(notification)
58
+
59
+ # Convert to dict for broadcasting
60
+ notification_dict = {
61
+ "id": notification.id,
62
+ "user_id": notification.user_id,
63
+ "title": notification.title,
64
+ "message": notification.message,
65
+ "type": notification.type,
66
+ "data": notification.data,
67
+ "created_at": notification.created_at.isoformat(),
68
+ "read": notification.read
69
+ }
70
+
71
+ # Broadcast to connected clients
72
+ await broadcast_message({
73
+ "type": "notification",
74
+ "data": notification_dict
75
+ })
76
+
77
+ # Clear user's notification cache
78
+ await cache.delete_cache(f"user_notifications:{user_id}")
79
+
80
+ return notification_dict