<s> import json <EOL> from channels import Channel <EOL> from channels . auth import channel_session_user_from_http , channel_session_user <EOL> from . models import Room <EOL> from . utils import get_room_or_error , catch_client_error <EOL> @ channel_session_user_from_http <EOL> def ws_connect ( message ) : <EOL> message . channel_session [ '<STR_LIT>' ] = [ ] <EOL> def ws_receive ( message ) : <EOL> payload = json . loads ( message [ '<STR_LIT:text>' ] ) <EOL> payload [ '<STR_LIT>' ] = message . content [ '<STR_LIT>' ] <EOL> Channel ( "<STR_LIT>" ) . send ( payload ) <EOL> @ channel_session_user <EOL> def ws_disconnect ( message ) : <EOL> for room_id in message . channel_session . get ( "<STR_LIT>" , set ( ) ) : <EOL> try : <EOL> room = Room . objects . get ( pk = room_id ) <EOL> room . websocket_group . discard ( message . reply_channel ) <EOL> except Room . DoesNotExist : <EOL> pass <EOL> @ channel_session_user <EOL> @ catch_client_error <EOL> def chat_join ( message ) : <EOL> room = get_room_or_error ( message [ "<STR_LIT>" ] , message . user ) <EOL> room . websocket_group . add ( message . reply_channel ) <EOL> message . channel_session [ '<STR_LIT>' ] = list ( set ( message . channel_session [ '<STR_LIT>' ] ) . union ( [ room . id ] ) ) <EOL> message . reply_channel . send ( { <EOL> "<STR_LIT:text>" : json . dumps ( { <EOL> "<STR_LIT>" : str ( room . id ) , <EOL> "<STR_LIT:title>" : room . title , <EOL> } ) , <EOL> } ) <EOL> @ channel_session_user <EOL> @ catch_client_error <EOL> def chat_leave ( message ) : <EOL> room = get_room_or_error ( message [ "<STR_LIT>" ] , message . user ) <EOL> room . websocket_group . discard ( message . reply_channel ) <EOL> message . channel_session [ '<STR_LIT>' ] = list ( set ( message . channel_session [ '<STR_LIT>' ] ) . difference ( [ room . id ] ) ) <EOL> message . reply_channel . send ( { <EOL> "<STR_LIT:text>" : json . dumps ( { <EOL> "<STR_LIT>" : str ( room . id ) , <EOL> } ) , <EOL> } ) <EOL> @ channel_session_user <EOL> @ catch_client_error <EOL> def chat_send ( message ) : <EOL> room = get_room_or_error ( message [ "<STR_LIT>" ] , message . user ) <EOL> room . send_message ( message [ "<STR_LIT:message>" ] , message . user ) </s>
