@@ -92,10 +92,27 @@ async def receive(self, text_data=None, bytes_data=None):
9292 :param text_data:
9393 :param bytes_data:
9494 """
95- text_data_json = json .loads (text_data )
96- message = text_data_json .get ('message' )
95+ try :
96+ text_data_json = json .loads (text_data )
97+ except json .JSONDecodeError :
98+ await self .send (text_data = json .dumps ({
99+ 'error' : 'Invalid JSON format'
100+ }))
101+ return
102+
103+ message = text_data_json .get ('message' , '' ).strip ()
97104
98105 if not message :
106+ await self .send (text_data = json .dumps ({
107+ 'error' : 'Message content is required'
108+ }))
109+ return
110+
111+ # Add message length validation
112+ if len (message ) > 1000 : # Adjust limit as needed
113+ await self .send (text_data = json .dumps ({
114+ 'error' : 'Message too long. Maximum 1000 characters allowed.'
115+ }))
99116 return
100117
101118 now = timezone .now ()
@@ -105,12 +122,18 @@ async def receive(self, text_data=None, bytes_data=None):
105122 # Seller is sending - recipient should be the buyer
106123 recipient_username = text_data_json .get ('recipient' )
107124 if not recipient_username :
125+ await self .send (text_data = json .dumps ({
126+ 'error' : 'Recipient username is required when seller sends message'
127+ }))
108128 return
109129 User = get_user_model ()
110130
111131 try :
112132 recipient = await sync_to_async (User .objects .get )(username = recipient_username )
113133 except User .DoesNotExist :
134+ await self .send (text_data = json .dumps ({
135+ 'error' : 'Recipient user not found'
136+ }))
114137 return
115138 else :
116139 # Buyer is sending - recipient is the seller
@@ -124,16 +147,31 @@ async def receive(self, text_data=None, bytes_data=None):
124147 'message' : message ,
125148 'sender' : self .user .username ,
126149 'datetime' : now .isoformat (),
150+ 'message_id' : None , # Will be set after saving to DB
127151 }
128152 )
129153
130154 # Save message to database
131- await Message .objects .acreate (
132- sender = self .user ,
133- recipient = recipient ,
134- product = self .product ,
135- content = message
136- )
155+ try :
156+ saved_message = await Message .objects .acreate (
157+ sender = self .user ,
158+ recipient = recipient ,
159+ product = self .product ,
160+ content = message
161+ )
162+
163+ # Send confirmation back to sender with message ID
164+ await self .send (text_data = json .dumps ({
165+ 'type' : 'message_sent' ,
166+ 'message_id' : saved_message .id ,
167+ 'timestamp' : saved_message .sent_at .isoformat ()
168+ }))
169+
170+ except Exception as e :
171+ await self .send (text_data = json .dumps ({
172+ 'error' : 'Failed to save message. Please try again.'
173+ }))
174+ return
137175
138176 async def chat_message (self , event ):
139177 """
0 commit comments