File tree Expand file tree Collapse file tree 3 files changed +16
-5
lines changed Expand file tree Collapse file tree 3 files changed +16
-5
lines changed Original file line number Diff line number Diff line change 1616
1717def format_return (data ):
1818 try :
19+ if isinstance (data , bytes ):
20+ data = data .decode (encoding = 'utf-8' )
1921 return json .loads (data )
2022 except :
2123 return data
Original file line number Diff line number Diff line change 2121from common .core .config import UserConfig
2222from common .decorators import cached_method
2323from common .utils import get_logger
24- from message .utils import async_push_message
24+ from common .utils .timezone import local_now_display
25+ from message .utils import async_push_message , online_caches
2526from system .models import UserInfo
2627from system .serializers .userinfo import UserInfoSerializer
2728
@@ -79,6 +80,8 @@ async def connect(self):
7980 self .disconnected = False
8081 # Join room group
8182 await self .channel_layer .group_add (self .room_group_name , self .channel_name )
83+ online_caches .push (self .room_group_name , {'time' : local_now_display (), 'name' : self .channel_name })
84+
8285 await self .accept ()
8386 # 建立连接,推送用户信息
8487 # await self.userinfo(None)
@@ -87,6 +90,10 @@ async def disconnect(self, close_code):
8790 self .disconnected = True
8891 if self .room_group_name :
8992 await self .channel_layer .group_discard (self .room_group_name , self .channel_name )
93+
94+ if self .channel_layer ._get_group_channel_name (self .room_group_name ) not in self .channel_layer .groups :
95+ online_caches .pop (self .room_group_name )
96+
9097 logger .info (f"{ self .user } disconnect" )
9198
9299 @classmethod
Original file line number Diff line number Diff line change 1212from django .conf import settings
1313from rest_framework .utils import encoders
1414
15+ from common .cache .redis import CacheHash
1516
16- @async_to_sync
17- async def get_online_user_pks ():
18- channel_layer = get_channel_layer ()
19- return {int (key .split ('_' )[- 1 ]) for key in channel_layer .groups .keys ()}
17+ online_caches = CacheHash (key = 'online_users_socket' )
18+
19+
20+ def get_online_user_pks ():
21+ return {int (key .split ('_' )[- 1 ]) for key in online_caches .get_all ().keys ()}
2022
2123
2224async def async_push_message (user_pk : str | int , message : Dict , message_type = 'push_message' ):
You can’t perform that action at this time.
0 commit comments