def connect_wait_page(message, params): session_pk, page_index, group_id_in_subsession = params.split(',') session_pk = int(session_pk) page_index = int(page_index) group_name = channels_wait_page_group_name( session_pk, page_index, group_id_in_subsession ) group = Group(group_name) group.add(message.reply_channel) # in case message was sent before this web socket connects if group_id_in_subsession: ready = CompletedGroupWaitPage.objects.filter( page_index=page_index, id_in_subsession=int(group_id_in_subsession), session_id=session_pk, fully_completed=True).exists() else: # subsession ready = CompletedSubsessionWaitPage.objects.filter( page_index=page_index, session_id=session_pk, fully_completed=True).exists() if ready: message.reply_channel.send( {'text': json.dumps( {'status': 'ready'})})
def ws_connect(message): group = Group(GRUPO_TRACKERS) # Adiciona no grupo group.add(message.reply_channel) # Envia menssagem Accept the connection request message.reply_channel.send({"accept": True}) print("connect-tracker")
def connect_wait_page(message, params): session_pk, page_index, model_name, model_pk = params.split(',') session_pk = int(session_pk) page_index = int(page_index) model_pk = int(model_pk) group_name = channels_wait_page_group_name( session_pk, page_index, model_name, model_pk ) group = Group(group_name) group.add(message.reply_channel) # in case message was sent before this web socket connects if model_name == 'group': ready = CompletedGroupWaitPage.objects.filter( page_index=page_index, group_pk=model_pk, session_pk=session_pk, after_all_players_arrive_run=True).exists() else: # subsession ready = CompletedSubsessionWaitPage.objects.filter( page_index=page_index, session_pk=session_pk, after_all_players_arrive_run=True).exists() if ready: message.reply_channel.send( {'text': json.dumps( {'status': 'ready'})})
def ws_connect(message): group = Group("users") # adiciona no grupo group.add(message.reply_channel) # Envia messangem Accept the connection request message.reply_channel.send({"accept": True}) print("accept")
def connect_wait_page(message, params): session_pk, page_index, model_name, model_pk = params.split(',') session_pk = int(session_pk) page_index = int(page_index) model_pk = int(model_pk) group_name = channels_wait_page_group_name( session_pk, page_index, model_name, model_pk ) group = Group(group_name) group.add(message.reply_channel) # in case message was sent before this web socket connects if model_name == 'group': ready = CompletedGroupWaitPage.objects.filter( page_index=page_index, group_pk=model_pk, session_id=session_pk, after_all_players_arrive_run=True).exists() else: # subsession ready = CompletedSubsessionWaitPage.objects.filter( page_index=page_index, session_id=session_pk, after_all_players_arrive_run=True).exists() if ready: message.reply_channel.send( {'text': json.dumps( {'status': 'ready'})})
def join(room, chatuser, reply_channel): if not room.is_banned(chatuser): room.users.add(chatuser) chatuser.chatrooms.add(room) group = Group("chat-%s" % room.pk) group.add(reply_channel) send_notify(room, "{} joined the room".format(chatuser), chatuser)
def ws_connect(message): # Extract the room from the message. This expects message.path to be of the # form /room/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: prefixroom, prefix, label = message['path'].decode('ascii').strip( '/').split('/') if prefix != 'chat': log.debug('invalid ws path=%s', message['path']) return room = Room.objects.get(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 = Group('chat-' + label, channel_layer=message.channel_layer) group.add(message.reply_channel) send_user_login(group, message, True) message.channel_session['room'] = room.label
def ws_connect(message): group = Group("monitors") # Adiciona no grupo group.add(message.reply_channel) # Envia messangem Accept the connection request message.reply_channel.send({"accept": True}) #rbpi3.start() print("connect-Monitor")
def ws_connect(message): """ Channels connection setup. Register the current client on the related Group according to the language """ prefix, language = message['path'].strip('/').split('/') gr = Group('knocker-{0}'.format(language)) gr.add(message.reply_channel) message.channel_session['knocker'] = language
def ws_connect(message): """ Channels connection setup. Register the current client on the related Group according to the language """ prefix, language = message['path'].strip('/').split('/') gr = Group('knocker-{0}'.format(language)) gr.add(message.reply_channel) message.channel_session['knocker'] = language message.reply_channel.send({"accept": True})
def ws_connect(message, post_pk): # message.user group = Group('post-{}'.format(post_pk)) group.add(message.reply_channel) # 접속 유저의 http 세션키로서, 유저별 세션 Group을 생성합니다. session_key = message.http_session.session_key message.channel_session['session_group_name'] = 'session-{}'.format( session_key) group = Group(message.channel_session['session_group_name']) group.add(message.reply_channel)
def sign_in(self, request, data, *args, **kwargs): serializer = IsAuthenticatedSerializer(data=data) serializer.is_valid(raise_exception=True) band_id = kwargs.get("band_id") user = self.check_chat_perms(serializer, band_id) if user is not None: request.channel_session["user"] = user.id group = Group(self.CHAT_GROUP_TEMPLATE % band_id) group.add(request.reply_channel) messages = Message.objects.select_related("author").filter(band_id=band_id)[: self.MESSAGES_COUNT][::-1] self.route_send(request.reply_channel, MessagesSerializer({"messages": messages}).data) else: raise PermissionDenied
def ws_connect(message): """ Channels connection setup. Register the current client on the related Groups according to the language and according to the combination of language and username """ # Accept the connection message.reply_channel.send({"accept": True}) prefix, language = message['path'].strip('/').split('/') grLangUser = Group('knocker-{0}-{1}'.format(language, message.user.id)) grLangUser.add(message.reply_channel) message.channel_session['knocker'] = language
def connect_wait_for_session(message, pre_create_id): group = Group(channels_create_session_group_name(pre_create_id)) group.add(message.reply_channel) # in case message was sent before this web socket connects if Session.objects.filter(_pre_create_id=pre_create_id): group.send({'text': json.dumps({'status': 'ready'})}) elif FailedSessionCreation.objects.filter( pre_create_id=pre_create_id).exists(): group.send({ 'text': json.dumps( {'error': 'Failed to create session. Check the server logs.'}) })
def connect_auto_advance(message, params): participant_code, page_index = params.split(',') page_index = int(page_index) group = Group('auto-advance-{}'.format(participant_code)) group.add(message.reply_channel) # in case message was sent before this web socket connects participant = Participant.objects.get(code=participant_code) if participant._index_in_pages > page_index: message.reply_channel.send( {'text': json.dumps( {'new_index_in_pages': participant._index_in_pages})} )
def connect_wait_for_session(message, pre_create_id): group = Group(channels_create_session_group_name(pre_create_id)) group.add(message.reply_channel) # in case message was sent before this web socket connects if Session.objects.filter(_pre_create_id=pre_create_id): group.send( {'text': json.dumps( {'status': 'ready'})} ) elif FailedSessionCreation.objects.filter( pre_create_id=pre_create_id ).exists(): group.send( {'text': json.dumps( {'error': 'Failed to create session. Check the server logs.'})} )
def connect_wait_for_session(message, pre_create_id): group = Group(channels_create_session_group_name(pre_create_id)) group.add(message.reply_channel) # in case message was sent before this web socket connects if Session.objects.filter(_pre_create_id=pre_create_id, ready=True): group.send( {'text': json.dumps( {'status': 'ready'})} ) else: failure = FailedSessionCreation.objects.filter( pre_create_id=pre_create_id ).first() if failure: group.send( {'text': json.dumps( {'error': failure.message, 'traceback': failure.traceback})} )
def connect_wait_for_session(message, pre_create_id): group = Group(channels_create_session_group_name(pre_create_id)) group.add(message.reply_channel) # in case message was sent before this web socket connects if Session.objects.filter(_pre_create_id=pre_create_id, ready=True): group.send( {'text': json.dumps( {'status': 'ready'})} ) else: failures = FailedSessionCreation.objects.filter( pre_create_id=pre_create_id ) if failures: failure = failures[0] group.send( {'text': json.dumps( {'error': failure.message})} )
def connect_auto_advance(message, params): participant_code, page_index = params.split(',') page_index = int(page_index) group = Group('auto-advance-{}'.format(participant_code)) group.add(message.reply_channel) # in case message was sent before this web socket connects try: participant = Participant.objects.get(code=participant_code) except Participant.DoesNotExist: message.reply_channel.send( {'text': json.dumps( # doesn't get shown because not yet localized {'error': 'Participant not found in database.'})}) return if participant._index_in_pages > page_index: message.reply_channel.send( {'text': json.dumps( {'new_index_in_pages': participant._index_in_pages})})
def connect_group_by_arrival_time(message, params): session_pk, page_index, app_name, player_id = params.split(',') session_pk = int(session_pk) page_index = int(page_index) player_id = int(player_id) group_name = channels_group_by_arrival_time_group_name(session_pk, page_index) group = Group(group_name) group.add(message.reply_channel) models_module = get_models_module(app_name) player = models_module.Player.objects.get(id=player_id) group_id_in_subsession = player.group.id_in_subsession ready = CompletedGroupWaitPage.objects.filter( page_index=page_index, id_in_subsession=int(group_id_in_subsession), session_id=session_pk, fully_completed=True).exists() if ready: message.reply_channel.send( {'text': json.dumps( {'status': 'ready'})})
def group(self): """ get a django channels Group consisting of all the reply_channels in the QuerySet """ self._channel_names = self.values_list('channel_name', flat=True) if not self._channel_names: empty_group = Group('emptyname') empty_group.empty = True return empty_group # group name is the hash of all the channel_names combined_names = b''.join( i.encode('utf-8', errors='replace') for i in self._channel_names) group_id = md5(combined_names).hexdigest() combined_group = Group(name=group_id) for channel_name in self._channel_names: if channel_name.startswith('bot-'): continue combined_group.add(Channel(channel_name)) return combined_group
def connect_waiter(message): # When the phone number progress websocket connects # we need to check if the task already finnished by # the time the WS connected. task_id = message.http_session['active_phone_number_task_id'] task = AsyncResult(task_id) # If that's the case, send back an already done message if task.ready(): content = json.dumps({'success': True, 'msg': 'already done'}) message.reply_channel.send({'text': content}) else: group = Group("phone_verify-%s" % message.user.username) group.add(message.reply_channel) content = json.dumps({ 'sending': True, }) # Send currently in progress message group.send({'text': content})
def connect_auto_advance(message, params): participant_code, page_index = params.split(',') page_index = int(page_index) group = Group('auto-advance-{}'.format(participant_code)) group.add(message.reply_channel) # in case message was sent before this web socket connects result = Participant.objects.filter( code=participant_code).values_list( '_index_in_pages', flat=True) try: page_should_be_on = result[0] except IndexError: message.reply_channel.send( {'text': json.dumps( # doesn't get shown because not yet localized {'error': 'Participant not found in database.'})}) return if page_should_be_on > page_index: message.reply_channel.send( {'text': json.dumps( {'auto_advanced': True})})
def connect_wait_page(message, params): app_label, page_index, model_name, model_pk = params.split(',') page_index = int(page_index) model_pk = int(model_pk) group_name = channels_wait_page_group_name( app_label, page_index, model_name, model_pk ) group = Group(group_name) group.add(message.reply_channel) # in case message was sent before this web socket connects # fixme: app name or app label? models_module = common_internal.get_models_module(app_label) GroupOrSubsession = { 'subsession': getattr(models_module, 'Subsession'), 'group': getattr(models_module, 'Group') }[model_name] group_or_subsession = GroupOrSubsession.objects.get(pk=model_pk) participants_for_this_page = set( p.participant for p in group_or_subsession.player_set.all() ) unvisited = set( p for p in participants_for_this_page if p._index_in_pages < page_index ) if not unvisited: message.reply_channel.send( {'text': json.dumps( {'status': 'ready'})})
def chat_receive(msg): if not msg.user.is_authenticated(): # TODO return data = json.loads(msg.content['text']) pprint(data) tag = data['tag'] room = data['data']['room'] group = Group('chat-' + room) if tag == 'send': group.add(msg.reply_channel) group.send({ 'text': json.dumps({ 'user': msg.user.player.id, 'room': room, 'msg': data['data']['msg'], }), }) elif tag == 'subscribe': if data['data']['yes']: group.add(msg.reply_channel) else: group.discard(msg.reply_channel)
def ws_add(message, params): print("ws_add called. params = " + params) page, group_id, player_id, session_code = params.split(',') player_id = int(player_id) group_id = int(group_id) # add them to the channels group group = Group(get_group_name(group_id, session_code)) group.add(message.reply_channel) # need to check to see if someone in the group has already chosen to move on - if so, send the done message upon joining with transaction.atomic(): models_module = get_models_module('channelsmin') group_object = models_module.Group.objects.get(id=group_id) if page == 'finished' and group_object.firstpage_done: print( "inside ws_add, checking to see if group's first page is done. firstpage_done=" + str(group_object.firstpage_done)) reply = { 'type': 'done', } message.reply_channel.send({'text': json.dumps(reply)})
def chat_join(message): group = Group("room-%s" % message.user.id) group.add(message.reply_channel) logging.debug("[Server] User %s joined chat." % message.user.id)
def party_message(message): content = json.loads(message.content['text']) action = content['action'] if action == 'hello': party = Party.objects.get(id=message.http_session['party_id']) member = PartyMember.objects.get(id=message.http_session['member_id']) member.nick = content['nick'] group = Group(f"party-{party.id}") all_colours = [ '#058fbe', '#d70000', '#00b100', '#a300c4', '#ee7600', '#122b53' ] used_colours = set(x.colour for x in party.members.all()) for colour in all_colours: if colour not in used_colours: member.colour = colour break member.save() message.http_session['nickname'] = content['nick'] message.reply_channel.send({ "text": json.dumps({ "action": "member_list", "members": { x.channel: { 'nick': x.nick, 'colour': x.colour, 'id': x.id } for x in party.members.all() }, }) }) message.reply_channel.send({ "text": json.dumps({ "action": "playlist", "playlist": get_playlist(party) }) }) group.add(message.reply_channel) group.send({ "text": json.dumps({ "action": "new_member", "channel": message.reply_channel.name, "nick": member.nick, "colour": member.colour, "id": member.id, }) }) message.http_session.save() elif action == 'relay': Channel(content['target']).send({ "text": json.dumps({ "action": "relay", "origin": message.reply_channel.name, "message": content['message'], }) }) elif action == 'addToQueue': party = Party.objects.get(id=message.http_session['party_id']) song = Song.objects.get(id=content['song']) if Playlist.objects.filter(party=party, song=song).exists(): # Silently do nothing if this would be a duplicate. return entry = Playlist(party=party, song=song, order=1) entry.save() Group(f"party-{party.id}").send({ "text": json.dumps({ "action": "playlist", "playlist": get_playlist(party) }) }) elif action == 'removeFromQueue': party = Party.objects.get(id=message.http_session['party_id']) song = Song.objects.get(id=content['song']) Playlist.objects.filter(party=party, song=song).delete() Group(f"party-{party.id}").send({ "text": json.dumps({ "action": "playlist", "playlist": get_playlist(party) }) })
def chat_connect(message): room = message.content['path'].strip('/') message.channel_session['room'] = room group = Group('chat-%s' % room) group.add(message.reply_channel)
def ws_connect(message, room): g = Group('chat:{}'.format(room)) data = {'text': 'A new user connected', 'type': 'log'} g.send({'text': json.dumps(data)}) g.add(message.reply_channel)