@channel_session
def ws_connect(message):
# Extract the room from the message. This expects message.path to be of the
# form /chat/{label}/, and finds a Room if the message path is applicable,
# and if the Room exists. Otherwise, bails (meaning this is a some othersort
# of websocket). So, this is effectively a version of _get_object_or_404.
try:
# prefix, label = message['path'].decode('ascii').strip('/').split('/')
prefix, label = message['path'].strip('/').split('/')
if prefix != 'chat':
log.debug('invalid ws path=%s', message['path'])
return
room, created = Room.objects.get_or_create(label=label)
except ValueError:
log.debug('invalid ws path=%s', message['path'])
return
except Room.DoesNotExist:
log.debug('ws room does not exist label=%s', label)
return
log.debug('chat connect room=%s client=%s:%s',
room.label, message['client'][0], message['client'][1])
# Need to be explicit about the channel layer so that testability works
# This may be a FIXME?
Group('chat-' + label, channel_layer=message.channel_layer).add(message.reply_channel)
message.channel_session['room'] = room.label
@channel_session
def ws_receive(message):
# Look up the room from the channel session, bailing if it doesn't exist
try:
label = message.channel_session['room']
room = Room.objects.get(label=label)
except KeyError:
log.debug('no room in channel_session')
return
except Room.DoesNotExist:
log.debug('recieved message, buy room does not exist label=%s', label)
return
# Parse out a chat message from the content text, bailing if it doesn't
# conform to the expected message format.
try:
# data = json.loads(message['bytes'].decode(errors='replace'))
tcl_json_info = message['bytes'].decode('utf-8', errors="replace").strip()
tcl_json_info = tcl_json_info.replace("\n", "\\n")
tcl_json_info = tcl_json_info.replace("\r", "\\r")
tcl_json_info = tcl_json_info.replace("\t", "\\t")
# data = json.loads(tcl_json_info)
data = ast.literal_eval(tcl_json_info)
except ValueError:
log.debug("ws message isn't json binary=%s", data)
return
if set(data.keys()) != set(('newline', 'mf', 'message', 'level', 'timestamp', 'color', 'type')):
log.debug("ws message unexpected format data=%s", data)
return
if data:
log.debug('chat message room=%s timestamp=%s newline=%s mf=%s level=%s color=%s type=%s message=%s',
room.label, data['timestamp'], data['newline'], data['mf'], data['level'], data['color'], data['type'], data['message'])
# with transaction.atomic():
# m = room.messages.create(**data)
# m = room.messages.create(**data)
# See above for the note about Group
# Group('chat-' + label, channel_layer=message.channel_layer).send({'text': json.dumps(m.as_dict())})
Group('chat-' + label, channel_layer=message.channel_layer).send({'text': json.dumps(data)})