1
1
"""chat consumer
2
2
"""
3
- from django .db .models .query import QuerySet
4
3
import json
4
+ from django .db .models .query import QuerySet
5
5
from asgiref .sync import async_to_sync
6
6
from channels .generic .websocket import WebsocketConsumer
7
7
from rest_framework .renderers import JSONRenderer
@@ -28,11 +28,12 @@ def new_message(self, data: dict):
28
28
room = Chat .objects .get (room_id = data ['room_name' ])
29
29
type = self .commands [data ['command' ]]
30
30
# use `objects.create` because I just want `insert` message!
31
- Message .objects .create (
31
+ message : Message = Message .objects .create (
32
32
author = author ,
33
33
content = data ['message' ],
34
34
room = room ,
35
35
type = type )
36
+ return message .get_time ()
36
37
37
38
def fetch_message (self , room_name : str ):
38
39
query_set : QuerySet [Message ] = Message .last_messages (room_name )
@@ -43,19 +44,16 @@ def fetch_message(self, room_name: str):
43
44
{
44
45
"message" : message ['content' ],
45
46
"author" : message ['author_username' ],
46
- "command" : self .commands [message ['type' ]]
47
+ "command" : self .commands [message ['type' ]],
48
+ "time" : message ['time' ],
47
49
}
48
50
)
49
51
50
- def send_image (self , data : dict ):
51
- self .new_message (data )
52
- self .send_to_room (data )
53
-
54
52
def notification (self , data : dict ):
55
53
room : str = data ['room_name' ]
56
54
members : list = Chat .get_members_list (room )
57
55
async_to_sync (self .channel_layer .group_send )(
58
- "chat_BFoULH5Z" ,
56
+ "chat_BFoULH5Z" , # TODO dynamic this url
59
57
{
60
58
'type' : 'chat_message' ,
61
59
'message' : data ["message" ],
@@ -99,13 +97,16 @@ def receive(self, text_data: str):
99
97
message : str = data_dict ['message' ]
100
98
if not message .strip ():
101
99
return
102
- self .new_message (data_dict )
100
+ time = self .new_message (data_dict )
101
+ data_dict ['time' ] = time
103
102
self .send_to_room (data_dict )
104
103
elif command == 'fetch_message' :
105
104
room_name : str = data_dict ['room_name' ]
106
105
self .fetch_message (room_name )
107
106
elif command == 'send_image' :
108
- self .send_image (data_dict )
107
+ time = self .new_message (data_dict )
108
+ data_dict ['time' ] = time
109
+ self .send_to_room (data_dict )
109
110
else :
110
111
print (f'Invalid Command: "{ command } "' )
111
112
@@ -118,13 +119,15 @@ def send_to_room(self, data: dict):
118
119
message : str = data ['message' ]
119
120
author : str = data ['username' ]
120
121
command : str = data .get ("command" , "new_message" )
122
+ time : str = data ['time' ]
121
123
async_to_sync (self .channel_layer .group_send )(
122
124
self .room_group_name ,
123
125
{
124
126
'type' : 'chat_message' ,
125
127
'message' : message ,
126
128
'author' : author ,
127
129
'command' : command ,
130
+ 'time' : time ,
128
131
}
129
132
)
130
133
0 commit comments