Beispiel #1
0
def send_data(message):
    """
    Informs all site users and projector clients about changed data.
    """
    collection_elements = CollectionElementList.from_channels_message(message)

    # Loop over all logged in site users and the anonymous user and send changed data.
    for user in itertools.chain(get_logged_in_users(), [AnonymousUser()]):
        channel = Group('user-{}'.format(user.id))
        output = collection_elements.as_autoupdate_for_user(user)
        channel.send({'text': json.dumps(output)})

    # Check whether broadcast is active at the moment and set the local
    # projector queryset.
    if config['projector_broadcast'] > 0:
        queryset = Projector.objects.filter(pk=config['projector_broadcast'])
    else:
        queryset = Projector.objects.all()

    # Loop over all projectors and send data that they need.
    for projector in queryset:
        output = []
        for collection_element in collection_elements:
            if collection_element.is_deleted():
                output.append(collection_element.as_autoupdate_for_projector())
            else:
                for element in projector.get_collection_elements_required_for_this(collection_element):
                    output.append(element.as_autoupdate_for_projector())
        if output:
            if config['projector_broadcast'] > 0:
                Group('projector-all').send(
                    {'text': json.dumps(output)})
            else:
                Group('projector-{}'.format(projector.pk)).send(
                    {'text': json.dumps(output)})
Beispiel #2
0
def ws_message(message):
    '''Send a message via web sockets.  Currently uses a group identified by
    notify-username.  When a volume export form submission is received,
    the message is handed off to the volume-export channel, which is handled
    by :mod:`readux.books.consumers`.  Otherwise, messages are routed to the
    user notification channel.'''
    # does this really need to be a group? can we just use the reply channel?
    notify = Group("notify-%s" % message.user.username)
    # check for volume export data (form submission)
    if 'volume_export' in message.content['text']:
        data = json.loads(message.content['text'])
        # parse_qs returns values as lists
        formdata = dict((key, val[0])
                        for key, val in parse_qs(data['volume_export']).iteritems())
        # breaking changes as of channels 1.0
        # need to specify immediately=True to send messages before the consumer completes to the end
        Channel('volume-export').send({
            # has to be json serializable, so send username rather than user
            'user': message.user.username,
            'formdata': formdata,
            # fixme: why is reply channel not automatically set?
            # 'reply_channel': message.reply_channel
        }, immediately=True)
    else:
        notify.send({
            "text": "%s" % message.content['text'],
        }, immediately=True)
Beispiel #3
0
def send_data(message):
    """
    Informs all users about changed data.

    The argument message has to be a dict with the keywords collection_string
    (string), pk (positive integer), id_deleted (boolean) and dispatch_uid
    (string).
    """
    for access_permissions in BaseAccessPermissions.get_all():
        if access_permissions.get_dispatch_uid() == message['dispatch_uid']:
            break
    else:
        raise ValueError('Invalid message. A valid dispatch_uid is missing.')

    if not message['is_deleted']:
        Model = get_model_from_collection_string(message['collection_string'])
        instance = Model.objects.get(pk=message['pk'])
        full_data = access_permissions.get_full_data(instance)

    # Loop over all logged in users and the anonymous user.
    for user in itertools.chain(get_logged_in_users(), [AnonymousUser()]):
        channel = Group('user-{}'.format(user.id))
        output = {
            'collection': message['collection_string'],
            'id': instance.get_rest_pk(),
            'action': 'deleted' if message['is_deleted'] else 'changed'}
        if not message['is_deleted']:
            data = access_permissions.get_restricted_data(full_data, user)
            if data is None:
                # There are no data for the user so he can't see the object. Skip him.
                continue
            output['data'] = data
        channel.send({'text': json.dumps(output)})
Beispiel #4
0
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'})})
Beispiel #5
0
def ws_disconnect(message):
    """
    Channels connection close.
    Deregister the client
    """
    language = message.channel_session['knocker']
    gr = Group('knocker-{0}'.format(language))
    gr.discard(message.reply_channel)
Beispiel #6
0
 def send_knock(self, created=False):
     """
     Send the knock in the associated channels Group
     """
     knock = self.as_knock(created)
     if knock:
         gr = Group('knocker-{0}'.format(knock['language']))
         gr.send({'text': json.dumps(knock)})
Beispiel #7
0
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 chat_consumer(message):
    room = message.content['room']
    text = message.content['message']
    username = message.content['username']
    ChatMessage.objects.create(room=room, message=message)

    data = json.dumps({'message': text, 'username': username})

    group = Group('chat-%s' % room)
    group.send({'text': data})
Beispiel #9
0
def disconnect_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.discard(message.reply_channel)
Beispiel #10
0
class GroupStreamer(Streamer):
    def __init__(self):
        pass

    def prepare(self):
        from django.conf import settings
        from channels import Group
        self.group = Group(settings.TEMP_GROUP_NAME)

    def __call__(self, temperature):
        self.group.send({'text': self.format(temperature)})
 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
Beispiel #12
0
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})}
        )
Beispiel #13
0
def notify_subscribers(notifications, key):
    """
    Notify all open channels about new notifications
    """

    logger.debug("Broadcasting to subscribers")

    notification_type_ids = models.NotificationType.objects.values('key').filter(key=key)

    for notification_type in notification_type_ids:
        g = Group(
            settings.NOTIFICATION_CHANNEL.format(
                notification_key=notification_type['key']
            )
        )
        g.send(
            {'text': 'new-notification'}
        )
Beispiel #14
0
def data_entry_receive(message, game_id):
    game = Game.objects.get(pk=game_id)
    group = Group('data-entry-%s' % game_id)
    data = json.loads(message['text'])
    round_score, created = RoundScore.objects.get_or_create(
        score__game=game,
        score_id=data['score'],
        round_number=data['round'],
        defaults={'value': data['value']},
    )
    if not created:
        round_score.value = data['value']
        round_score.save()
    group.send({
        'text': json.dumps({
            'data': _round_scores_for_game(game)
        })
    })
Beispiel #15
0
def create_session(message):

    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']
    try:
        otree.session.create_session(**kwargs)
    except Exception as e:
        group.send(
            {'text': json.dumps(
                {'error': 'Failed to create session. Check the server logs.'})}
        )
        FailedSessionCreation(pre_create_id=kwargs['_pre_create_id']).save()
        raise e

    group.send(
        {'text': json.dumps(
            {'status': 'ready'})}
)
Beispiel #16
0
def create_session(message):
    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']

    try:
        session = otree.session.create_session(**kwargs)
        if message['use_browser_bots']:
            otree.bots.browser.initialize_session(
                session_pk=session.pk,
                case_number=None
            )
        session.ready_for_browser = True
        session.save()
    except Exception as e:

        # full error message is printed to console (though sometimes not?)
        error_message = 'Failed to create session: "{}"'.format(e)
        traceback_str = traceback.format_exc()
        group.send(
            {'text': json.dumps(
                {
                    'error': error_message,
                    'traceback': traceback_str,
                })}
        )
        FailedSessionCreation.objects.create(
            pre_create_id=kwargs['pre_create_id'],
            message=error_message[:FAILURE_MESSAGE_MAX_LENGTH],
            traceback=traceback_str
        )
        raise

    group.send(
        {'text': json.dumps(
            {'status': 'ready'})}
    )

    if 'room_name' in kwargs:
        Group(channel_utils.room_participants_group_name(kwargs['room_name'])).send(
            {'text': json.dumps(
                {'status': 'session_ready'})}
        )
Beispiel #17
0
def create_session(message):

    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']
    try:
        otree.session.create_session(**kwargs)
    except Exception as e:
        error_message = 'Failed to create session: "{}" - Check the server logs'.format(
                    str(e))
        group.send(
            {'text': json.dumps(
                {'error': error_message})}
        )
        FailedSessionCreation(
            pre_create_id=kwargs['_pre_create_id'],
            message=error_message[:FAILURE_MESSAGE_MAX_LENGTH]
        ).save()
        raise
    group.send({'text': json.dumps({'status': 'ready'})})
Beispiel #18
0
def send_game_list(channel):
    games = Game.objects.filter(status__in=['Created', 'Started'])
    game_list = []
    for game in games:
        state = cache.get(GAME + str(game.id), new_state())
        game_list.append({
            'id': game.id,
            'name': game.name,
            'level': game.level,
            'players_num': game.players_num,
            'players': state['players']
        })

    if isinstance(channel, str):
        channel = Group(channel)

    channel.send({
        'text': json.dumps({
            'game_list': game_list,
        })
    })
Beispiel #19
0
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})})
Beispiel #20
0
def create_session(message):
    group = Group(message['channels_group_name'])

    kwargs = message['kwargs']

    # because it's launched through web UI
    kwargs['honor_browser_bots_config'] = True
    try:
        otree.session.create_session(**kwargs)
    except Exception as e:

        # full error message is printed to console (though sometimes not?)
        error_message = 'Failed to create session: "{}"'.format(e)
        traceback_str = traceback.format_exc()
        group.send(
            {'text': json.dumps(
                {
                    'error': error_message,
                    'traceback': traceback_str,
                })}
        )
        FailedSessionCreation.objects.create(
            pre_create_id=kwargs['pre_create_id'],
            message=error_message[:FAILURE_MESSAGE_MAX_LENGTH],
            traceback=traceback_str
        )
        raise

    group.send(
        {'text': json.dumps(
            {'status': 'ready'})}
    )

    if 'room_name' in kwargs:
        Group(channel_utils.room_participants_group_name(kwargs['room_name'])).send(
            {'text': json.dumps(
                {'status': 'session_ready'})}
        )
Beispiel #21
0
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'})})
Beispiel #22
0
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})})
Beispiel #23
0
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.'})}
        )
Beispiel #24
0
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})}
            )
Beispiel #25
0
    def receive(self, content, **kwargs):
        print("receive Chat json :")
        print(content)

        if "groupname" in kwargs:

            goodTokenAndUserInGroup, user = checkToken(kwargs, False)

            if goodTokenAndUserInGroup:
                qwirkGroup = QwirkGroup.objects.get(
                    name=kwargs["groupname"]
                )  # TODO check with exist or with try catch but not sur because check in connect need to be tested

                if content["action"] == "message":

                    utils.sendMessageToAllUserGroup(qwirkGroup, user,
                                                    content["content"]["text"],
                                                    "message")

                    self.chatbot(qwirkGroup,
                                 user,
                                 text=content["content"]["text"])

                elif content["action"] == "call":
                    Group(kwargs["groupname"]).send({
                        "text":
                        json.dumps(content),
                    })
                elif content["action"] == "get-message":

                    try:
                        Notification.objects.filter(
                            message__qwirkGroup__name=kwargs["groupname"],
                            qwirkUser=user.qwirkuser).delete()
                    except Notification.DoesNotExist:
                        pass

                    messages = Message.objects.filter(
                        qwirkGroup__name=kwargs["groupname"]).order_by(
                            "-dateTime"
                        )[int(content["content"]["startMessage"]
                              ):int(content["content"]["endMessage"])]
                    messageToSend = list()
                    for message in messages:
                        messageToSend.append(MessageSerializer(message).data)
                    # print(messageToSend)
                    text = {
                        "action": "saved-messages",
                        "content": json.dumps(messageToSend)
                    }
                    self.send(text)
                elif content["action"] == "get-group-informations":

                    groupInfo = dict()

                    groupInfo["isPrivate"] = qwirkGroup.isPrivate
                    groupInfo["isContactGroup"] = qwirkGroup.isContactGroup

                    if user.qwirkuser in qwirkGroup.admins.all():
                        groupInfo["isAdmin"] = True
                    else:
                        groupInfo["isAdmin"] = False

                    groupInfo["qwirkUsers"] = list()

                    if groupInfo["isContactGroup"]:
                        contacts = qwirkGroup.contact_set.all()
                        for contact in contacts:
                            if contact.qwirkUser.user.username != user.username:
                                groupInfo[
                                    "titleGroupName"] = contact.qwirkUser.user.username
                                groupInfo["qwirkUsers"].append(
                                    QwirkUserSerializerSimple(
                                        contact.qwirkUser).data)
                                for qwirkUser in groupInfo["qwirkUsers"]:
                                    qwirkUser["isAdmin"] = True
                                groupInfo["statusContact"] = contact.status
                    else:
                        qwirkUsers = qwirkGroup.qwirkuser_set.all()
                        for qwirkUser in qwirkUsers:
                            groupInfo["qwirkUsers"].append(
                                QwirkUserSerializerSimple(qwirkUser).data)
                            for qwirkUser in groupInfo["qwirkUsers"]:
                                qwirkUser[
                                    "isAdmin"] = qwirkUser in qwirkGroup.admins.all(
                                    )
                        groupInfo["titleGroupName"] = qwirkGroup.name
                    text = {
                        "action": "group-informations",
                        "content": json.dumps(groupInfo)
                    }
                    self.send(text)
                elif content["action"] == "accept-contact-request":
                    if qwirkGroup.isContactGroup:
                        contacts = qwirkGroup.contact_set.all()
                        for contact in contacts:
                            contact.status = "Friend"
                            contact.save()

                        requestMessage = qwirkGroup.message_set.get(
                            type='requestMessage')
                        requestMessage.type = "acceptMessage"
                        requestMessage.save()

                        utils.sendFriendshipResponse(qwirkGroup, user,
                                                     "acceptMessage",
                                                     requestMessage)

                elif content["action"] == "decline-contact-request":
                    if qwirkGroup.isContactGroup:
                        contacts = qwirkGroup.contact_set.all()
                        for contact in contacts:
                            contact.status = "Refuse"
                            contact.save()

                        requestMessage = qwirkGroup.message_set.get(
                            type='requestMessage')
                        requestMessage.type = "refuseMessage"
                        requestMessage.save()

                        utils.sendFriendshipResponse(qwirkGroup, user,
                                                     "refuseMessage",
                                                     requestMessage)
                elif content["action"] == "remove-contact":
                    qwirkGroup.delete()
                elif content["action"] == "block-contact":
                    if qwirkGroup.isContactGroup:
                        for contact in qwirkGroup.contact_set.all():
                            contact.status = "Block"
                            contact.save()

                        requestMessage = qwirkGroup.message_set.get(
                            type='requestMessage')
                        requestMessage.type = "blockMessage"
                        requestMessage.save()

                        utils.sendFriendshipResponse(qwirkGroup, user,
                                                     "blockMessage",
                                                     requestMessage)
                    else:
                        username = content["content"]["username"]
                        userToBlock = QwirkUser.objects.get(
                            user__username=username)
                        qwirkGroup.blockedUsers.add(userToBlock)

                        textMessage = user.username + " has blocked " + userToBlock.user.username

                        utils.sendMessageToAllUserGroup(
                            qwirkGroup, user, textMessage, "informations")

        else:
            print("no groupname in url")
 def add_user_to_group(self, group_name):
     Group(group_name).add(self.message.reply_channel)
 def disconnect(self, request, *args, **kwargs):
     band_id = kwargs.get("band_id")
     group = Group(self.CHAT_GROUP_TEMPLATE % band_id)
     group.discard(request.reply_channel)
def chat_disconnect(message):
    room = message.channel_session['room']

    group = Group('chat-%s' % room)
    group.discard(message.reply_channel)
Beispiel #29
0
def ws_connect(message):
    Group(PUBLIC_GROUP).add(message.reply_channel)
def ws_disconnectNew(message):
    Group("chat").discard(message.reply_channel)
Beispiel #31
0
def websocket_connect(message, channel):
    print "Test Connect %s " % channel
    message.reply_channel.send({"accept": True})
    Group("test").add(message.reply_channel)
Beispiel #32
0
def ws_disconnect(message):
    Group("user-{}".format(message.user.id)).discard(message.reply_channel)
Beispiel #33
0
def ws_connect(message):
    message.reply_channel.send({"accept": True})
    Group("user-{}".format(message.user.id)).add(message.reply_channel)
Beispiel #34
0
def ws_disconnect(message):
    print("User: "******"Someone left us")
    Group('auction').discard(message.reply_channel)
Beispiel #35
0
def room_ai_delete_consumer(message):
    data = message.content
    reply_channel = Channel(data['reply'])
    nonce = data['nonce']
    username = data['username']
    ai_name = data.get('ai_name', None)

    if ai_name is None:
        reply_channel.send(
            reply_error('No ai_name', nonce=nonce, type='room-ai-delete'))
        return

    player_room_cache_key = 'player-room:' + username

    with cache.lock('lock:' + player_room_cache_key):
        room_id = cache.get(player_room_cache_key)

        if room_id is None:
            reply_channel.send(
                reply_error('You are currently not in the room',
                            nonce=nonce,
                            type='room-ai-delete'))
            return

    room_cache_key = 'room:' + room_id
    with cache.lock('lock:' + room_cache_key):
        room = cache.get(room_cache_key)

        if room['game']['state'] is not RoomState.NOT_PLAYING:
            reply_channel.send(
                reply_error('You cannot delete AI at playing',
                            nonce=nonce,
                            type='room-ai-delete'))
            return

        if room['players'][0]['username'] != username:
            reply_channel.send(
                reply_error('You are not host',
                            nonce=nonce,
                            type='room-ai-delete'))
            return

        found = False
        for i, p in enumerate(room['players']):
            if p['username'] == ai_name:
                del room['players'][i]
                found = True
                break

        if not found:
            reply_channel.send(
                reply_error('AI not found', nonce=nonce,
                            type='room-ai-delete'))
            return

        try:
            room_model = Room.objects.get(room_id=room_id)
        except Room.DoesNotExist:
            reply_channel.send(
                reply_error('Room does not exists',
                            nonce=nonce,
                            type='room-ai-add'))
            return

        room_model.player_count -= 1
        room_model.save()
        cache.set('room:' + room_id, room)

        reply_channel.send(response({}, nonce=nonce))
        event_data = {
            'player': ai_name,
            'ai': True,
        }
        Group(room_id).send(event('room-leave', event_data))
Beispiel #36
0
def ws_connect(message):
    Group('graphing').add(message.reply_channel)
    Group('graphing').send({'text': 'connected'})
Beispiel #37
0
def websocket_disconnect(message, channel):
    print "Test Disconnect %s " % channel
    Group("test").discard(message.reply_channel)
Beispiel #38
0
def websocket_receive(message, channel):
    print "Test Receive %s " % channel
    Group("test").send({
        "text": "[user] %s" % message.content['text'],
    })
Beispiel #39
0
def ws_connect(message):
    prefix, label = message['path'].strip('/').split('/')
    room = Project.objects.get(chatRoom=label)
    message.reply_channel.send({"accept": True})
    Group('chat-' + label).add(message.reply_channel)
    message.channel_session['room'] = room.chatRoom
 def disconnect(self, message, **kwargs):
     print("on close::::")
     for group_name in self.get_all_groups_names():
         Group(group_name).discard(message.reply_channel)
Beispiel #41
0
def ws_receive(message):
    # ASGI WebSocket packet-received and send-packet message types
    # both have a "text" key for their textual data.
    Group("pulse-staff").send({"text": message.content['text']})

    print 'receive %s' % message.content['text']
Beispiel #42
0
def ws_disconnect_projector(message, projector_id):
    """
    This function is called, when a client on the projector disconnects.
    """
    Group('projector-{}'.format(projector_id)).discard(message.reply_channel)
Beispiel #43
0
def log_to_terminal(socketid, message):
	print message
	Group(socketid).send({"text": json.dumps(message)})
 def discard_user_from_group(self, group_name):
     Group(group_name).discard(self.message.reply_channel)
Beispiel #45
0
def websocket_receive(message, room_name):
    global m_count
    m_count = 0
    rr = Room.objects.get(id=room_name)
    q_user = User.objects.get(id=message.channel_session['_auth_user_id'])
    if rr.f_usr.id == q_user.id:
        if rr.s_in_chat == True:
            Group("chat-%s" % room_name).send({
                "text":
                json.dumps({
                    'f_usr': rr.f_usr.id,
                    'u': rr.f_usr.username,
                    'm': message.content['text'],
                })
            })
            Message.objects.create(fk=q_user,
                                   text=message.content['text'],
                                   room=rr,
                                   saw=True)
        else:
            Group("chat-%s" % room_name).send({
                "text":
                json.dumps({
                    'f_usr': rr.f_usr.id,
                    'u': rr.f_usr.username,
                    'm': message.content['text'],
                    'unseen': " (непрочитано) ",
                })
            })
            Message.objects.create(fk=q_user,
                                   text=message.content['text'],
                                   room=rr,
                                   saw=False)
            try:
                user_rooms = Room.objects.filter(
                    Q(f_usr=rr.s_usr) | Q(s_usr=rr.s_usr))
                for room in user_rooms:
                    try:
                        m = room.message.last()
                        if m.fk != rr.s_usr and m.saw == False:
                            global m_count
                            m_count += 1
                    except:
                        pass

                mm = rr.message.last()
                if mm.fk != rr.s_usr and mm.saw == False:
                    count_count = randint(0, 10000)
                    try:
                        if rr.s_usr.user_in_chat.in_chat == True:
                            s_usr_in_chat = True
                        else:
                            s_usr_in_chat = False
                    except:
                        s_usr_in_chat = False
                    try:
                        if rr.s_usr.user_in_rooms_page.in_rooms_page == True:
                            s_usr_in_rooms_page = True
                        else:
                            s_usr_in_rooms_page = False
                    except:
                        s_usr_in_rooms_page = False

                    if s_usr_in_chat == True:
                        Group("chat-%s" %
                              rr.s_usr.user_in_chat.room_id.id).send({
                                  "text":
                                  json.dumps({
                                      'u': rr.f_usr.username,
                                      'm': message.content['text'],
                                      'c': m_count,
                                      'cc': count_count
                                  })
                              })
                    elif s_usr_in_rooms_page == True:
                        Group("user-room-%s" % rr.s_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.f_usr.username,
                                'id': rr.f_usr.id,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
                    else:
                        Group("user-%s" % rr.s_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.f_usr.username,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })

                else:
                    global m_count
                    m_count += 1
                    count_count = randint(0, 10000)
                    try:
                        if rr.s_usr.user_in_chat.in_chat == True:
                            s_usr_in_chat = True
                        else:
                            s_usr_in_chat = False
                    except:
                        s_usr_in_chat = False
                    try:
                        if rr.s_usr.user_in_rooms_page.in_rooms_page == True:
                            s_usr_in_rooms_page = True
                        else:
                            s_usr_in_rooms_page = False
                    except:
                        s_usr_in_rooms_page = False

                    if s_usr_in_chat == True:
                        Group("chat-%s" %
                              rr.s_usr.user_in_chat.room_id.id).send({
                                  "text":
                                  json.dumps({
                                      'u': rr.f_usr.username,
                                      'm': message.content['text'],
                                      'c': m_count,
                                      'cc': count_count
                                  })
                              })
                    elif s_usr_in_rooms_page == True:
                        Group("user-room-%s" % rr.s_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.f_usr.username,
                                'id': rr.f_usr.id,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
                    else:
                        Group("user-%s" % rr.s_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.f_usr.username,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
            except:
                pass

    elif rr.s_usr.id == q_user.id:
        if rr.f_in_chat == True:
            Group("chat-%s" % room_name).send({
                "text":
                json.dumps({
                    's_usr': rr.s_usr.id,
                    'u': rr.s_usr.username,
                    'm': message.content['text'],
                })
            })
            Message.objects.create(fk=q_user,
                                   text=message.content['text'],
                                   room=rr,
                                   saw=True)
        else:
            Group("chat-%s" % room_name).send({
                "text":
                json.dumps({
                    's_usr': rr.s_usr.id,
                    'u': rr.s_usr.username,
                    'm': message.content['text'],
                    'unseen': " (непрочитано) ",
                })
            })
            Message.objects.create(fk=q_user,
                                   text=message.content['text'],
                                   room=rr,
                                   saw=False)
            try:
                user_rooms = Room.objects.filter(
                    Q(f_usr=rr.f_usr) | Q(s_usr=rr.f_usr))
                for room in user_rooms:
                    try:
                        m = room.message.last()
                        if m.fk != rr.f_usr and m.saw == False:
                            global m_count
                            m_count += 1
                    except:
                        pass

                mm = rr.message.last()
                if mm.fk != rr.f_usr and mm.saw == False:
                    count_count = randint(0, 10000)
                    try:
                        if rr.f_usr.user_in_chat.in_chat == True:
                            f_usr_in_chat = True
                        else:
                            f_usr_in_chat = False
                    except:
                        f_usr_in_chat = False
                    try:
                        if rr.f_usr.user_in_rooms_page.in_rooms_page == True:
                            f_usr_in_rooms_page = True
                        else:
                            f_usr_in_rooms_page = False
                    except:
                        f_usr_in_rooms_page = False

                    if f_usr_in_chat == True:
                        Group("chat-%s" %
                              rr.f_usr.user_in_chat.room_id.id).send({
                                  "text":
                                  json.dumps({
                                      'u': rr.s_usr.username,
                                      'm': message.content['text'],
                                      'c': m_count,
                                      'cc': count_count
                                  })
                              })
                    elif f_usr_in_rooms_page == True:
                        Group("user-room-%s" % rr.f_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.s_usr.username,
                                'id': rr.s_usr.id,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
                    else:
                        Group("user-%s" % rr.f_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.s_usr.username,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
                else:
                    global m_count
                    m_count += 1
                    count_count = randint(0, 10000)
                    try:
                        if rr.f_usr.user_in_chat.in_chat == True:
                            f_usr_in_chat = True
                        else:
                            f_usr_in_chat = False
                    except:
                        f_usr_in_chat = False
                    try:
                        if rr.f_usr.user_in_rooms_page.in_rooms_page == True:
                            f_usr_in_rooms_page = True
                        else:
                            f_usr_in_rooms_page = False
                    except:
                        f_usr_in_rooms_page = False

                    if f_usr_in_chat == True:
                        Group("chat-%s" %
                              rr.f_usr.user_in_chat.room_id.id).send({
                                  "text":
                                  json.dumps({
                                      'u': rr.s_usr.username,
                                      'm': message.content['text'],
                                      'c': m_count,
                                      'cc': count_count
                                  })
                              })
                    elif f_usr_in_rooms_page == True:
                        Group("user-room-%s" % rr.f_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.s_usr.username,
                                'id': rr.s_usr.id,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
                    else:
                        Group("user-%s" % rr.f_usr.id).send({
                            "text":
                            json.dumps({
                                'u': rr.s_usr.username,
                                'm': message.content['text'],
                                'c': m_count,
                                'cc': count_count
                            })
                        })
            except:
                pass
Beispiel #46
0
def ws_message(message):
    print("User: "******"Received!" + message['text'])
    product_id, product_name = get_group(message)
    command = message['text']
    if command == "bid_auction":
        try:
            product = Product.objects.get(pk=product_id)
            bidder = User.objects.get(username=message.user)
            is_user_bids = Biders.objects.filter(
                product_id=product_id, users__username=message.user).count()
            print(is_user_bids)
        except Product.DoesNotExist:
            product = None
        except User.DoesNotExist:
            bidder = None
        except Biders.DoesNotExist:
            is_user_bids = None
        #biders = Biders.objects.get(product_pk=product_id)
        #is_user_bids = Biders.objects.filter(users_username=message.user).count()
        #print(is_user_bids)
        ###
        if product and bidder and is_user_bids is not None:
            if is_user_bids == 0:
                biders = Biders.objects.get(product_id=product_id)
                biders.users.add(bidder)
                biders.save()
            product.price += decimal.Decimal(0.01)
            product.current_bidder = bidder
            product.save()
            json_response = json.dumps({
                "action": "VALUE_UP",
                "user": message.user.username,
                "value": str(product.price),
            })
            Group(str(product_id)).send({
                "text": json_response,
            })
        elif bidder == None:
            print("Not authorized bid!")
    elif command == "get_user_bid_auctions":
        try:
            user = User.objects.get(username=message.user)
        except:
            user = None

        if user:
            try:
                auctions = Biders.objects.filter(users__username=message.user)
            except Biders.DoesNotExist:
                auctions = None

            if auctions:
                json_auctions = {'auctions': []}
                for auction in auctions:
                    ended = False
                    if (timezone.now() > auction.product.ends):
                        ended = True
                    json_auctions['auctions'].append({
                        "name":
                        auction.product.name,
                        "url":
                        auction.product.get_absoulte_url(),
                        'ended':
                        str(ended)
                    })
                json_auctions = json.dumps(json_auctions)
                print(auctions.count())
                Group("dashboard-%s" % message.user.username).send(
                    {'text': json_auctions})
Beispiel #47
0
def ws_disconnect_site(message):
    """
    This function is called, when a client on the site disconnects.
    """
    Group('user-{}'.format(message.user.id)).discard(message.reply_channel)
Beispiel #48
0
def ws_message(message):
    Group("user-{}".format(message.user.id)).send({
        "text":
        "[user id: %s] %s" % (message.user.id, message.content['text']),
    })
Beispiel #49
0
def disconnect_auto_advance(message, params):
    participant_code, page_index = params.split(',')

    group = Group('auto-advance-{}'.format(participant_code))
    group.discard(message.reply_channel)
def ws_disconnect1(message):
    # Remove from reader group on clean disconnect
    Group("liveblog").discard(message.reply_channel)
Beispiel #51
0
def disconnect_wait_for_session(message, pre_create_id):
    group = Group(
        channels_create_session_group_name(pre_create_id)
    )
    group.discard(message.reply_channel)
Beispiel #52
0
def ws_disconnect(message):
    Group(PUBLIC_GROUP).discard(message.reply_channel)
Beispiel #53
0
def ws_disconnect(message):
    Group(clients_group).discard(message.reply_channel)
    return
def chat_connect(message):
    room = message.content['path'].strip('/')
    message.channel_session['room'] = room

    group = Group('chat-%s' % room)
    group.add(message.reply_channel)
Beispiel #55
0
def room_leave_consumer(message):
    data = message.content
    reply_channel = Channel(data['reply'])
    nonce = data['nonce']
    username = data['username']
    disconnected = data.get('disconnected', False)

    player_room_cache_key = 'player-room:' + username
    with cache.lock('lock:' + player_room_cache_key):

        room_id = cache.get(player_room_cache_key)

        if room_id is None:
            reply_channel.send(
                reply_error('You are currently not in the room',
                            nonce=nonce,
                            type='room-leave'))
            return

        room_cache_key = 'room:' + room_id
        with cache.lock('lock:' + room_cache_key):
            room_cache = cache.get(room_cache_key)
            if room_cache is None:
                try:
                    room = Room.objects.get(room_id=room_id)
                    room.delete()
                except Room.DoesNotExist:
                    pass
                Group(room_id).discard(reply_channel)
                cache.delete(player_room_cache_key)
                return

            found = False
            for i, player in enumerate(room_cache['players']):
                if player['username'] == username:
                    del room_cache['players'][i]
                    found = True
                    break
            ai_player_count = 0
            for player in room_cache['players']:
                if player['ai'] is True:
                    ai_player_count += 1

            if not found:
                reply_channel.send(
                    reply_error('You are currently not in the room',
                                nonce=nonce,
                                type='room-leave'))
                return

            Group(room_id).discard(reply_channel)
            cache.delete(player_room_cache_key)

            if not disconnected:
                reply_channel.send(response({}, nonce=nonce))
            player_count = len(room_cache['players'])

            if player_count == 0 or ai_player_count == player_count:
                try:
                    room = Room.objects.get(room_id=room_id)
                    room.delete()
                except Room.DoesNotExist:
                    pass
            else:
                cache.set(room_cache_key, room_cache)
                try:
                    room = Room.objects.get(room_id=room_id)
                    room.player_count -= 1
                    room.save()
                except Room.DoesNotExist:
                    pass

            event_data = {
                'player': username,
            }

            Group(room_id).send(event('room-leave', event_data))

            # only when game is playing
            if room_cache['game']['state'] is not RoomState.NOT_PLAYING:
                Channel('room-reset').send({'room_id': room_id})
Beispiel #56
0
def user_connected(message):
    if message.get('text', False):
        payload = json.loads(message['text'])
        Group(payload['username']).add(message.reply_channel)
        print(payload['username'], "is connected")
Beispiel #57
0
def ws_disconnect(message):
    Group('graphing').send({'text': 'disconnected'})
    Group('graphing').discard(message.reply_channel)
Beispiel #58
0
def room_ai_add_consumer(message):
    data = message.content
    reply_channel = Channel(data['reply'])
    nonce = data['nonce']
    username = data['username']

    player_room_cache_key = 'player-room:' + username

    with cache.lock('lock:' + player_room_cache_key):
        room_id = cache.get(player_room_cache_key)

        if room_id is None:
            reply_channel.send(
                reply_error('You are currently not in the room',
                            nonce=nonce,
                            type='room-ai-add'))
            return

    room_cache_key = 'room:' + room_id
    with cache.lock('lock:' + room_cache_key):
        room = cache.get(room_cache_key)

        if room['game']['state'] is not RoomState.NOT_PLAYING:
            reply_channel.send(
                reply_error('You cannot add AI at playing',
                            nonce=nonce,
                            type='room-ai-add'))
            return

        if len(room['players']) >= room['options']['player_number']:
            reply_channel.send(
                reply_error('Room is full', nonce=nonce, type='room-ai-add'))
            return

        if room['players'][0]['username'] != username:
            reply_channel.send(
                reply_error('You are not host',
                            nonce=nonce,
                            type='room-ai-add'))
            return

        try:
            room_model = Room.objects.get(room_id=room_id)
        except Room.DoesNotExist:
            reply_channel.send(
                reply_error('Room does not exists',
                            nonce=nonce,
                            type='room-ai-add'))
            return

        nicknames = ['doge', 'bitcoin', 'ethereum', 'egger', 'ha']
        altered_nicknames = ['doge', 'bitcoin', 'ethereum', 'egger', 'ha']

        for p in room['players']:
            if p['username'].startswith('*AI-'):
                altered_nicknames.remove(p['username'][4:])

        ind = nicknames.index(altered_nicknames[0])

        ai = AI(ind)
        room['players'].append(ai)
        room_model.player_count += 1
        room_model.save()
        cache.set('room:' + room_id, room)

        reply_channel.send(response({}, nonce=nonce))
        event_data = {
            'player': ai['username'],
            'ai': True,
        }
        Group(room_id).send(event('room-join', event_data))

        event_data = {
            'player': ai['username'],
            'ready': True,
        }
        Group(room_id).send(event('room-ready', event_data))
Beispiel #59
0
def send_message_to_group(message, group_name):
    """Send message to a group."""
    assert isinstance(message, dict), "message must be a dict instance."
    group = Group(group_name)
    group.send(message)
Beispiel #60
0
def room_join_consumer(message):
    data = message.content
    reply_channel = Channel(data['reply'])
    nonce = data['nonce']
    username = data['username']
    room_id = data.get('room_id', None)
    password = data.get('password', None)

    if room_id is None:
        reply_channel.send(
            reply_error('No room_id', nonce=nonce, type='room-join'))
        return

    player_room_cache_key = 'player-room:' + username
    with cache.lock('lock:' + player_room_cache_key):
        room_cache = cache.get(player_room_cache_key)

        if room_cache is not None:
            reply_channel.send(
                reply_error(
                    'You are already in a room',
                    nonce=nonce,
                    type='room-join',
                ))
            return

        try:
            room = Room.objects.get(room_id=room_id)
        except Room.DoesNotExist:
            reply_channel.send(
                reply_error('Room does not exist',
                            nonce=nonce,
                            type='room-join'))
            return

        # xor?
        if (password is None and room.is_private) or (password is not None
                                                      and not room.is_private):
            reply_channel.send(
                reply_error('Password mismatch', nonce=nonce,
                            type='room-join'))
            return

        if room.is_private:
            if not check_password(password, room.password):
                reply_channel.send(
                    reply_error('Password mismatch',
                                nonce=nonce,
                                type='room-join'))
                return

        room_cache_key = 'room:' + room_id

        with cache.lock('lock:' + room_cache_key):
            room_cache = cache.get(room_cache_key)

            if room_cache is None:
                room.delete()
                reply_channel.send(
                    reply_error('Room does not exist',
                                nonce=nonce,
                                type='room-join'))
                return

            if len(room_cache['players']
                   ) >= room_cache['options']['player_number']:
                reply_channel.send(
                    reply_error('Room is full', nonce=nonce, type='room'))
                return

            player_data = new_player_data(
                username=username,
                reply=reply_channel.name,
                ready=False,
            )

            event_data = {
                'player': username,
            }

            room_cache['players'].append(player_data)

            response_players = []

            for player in room_cache['players']:
                response_players.append({
                    'username': player['username'],
                    'ready': player['ready'],
                })

            response_data = {
                'room_id': room_id,
                'title': room.title,
                'player_number': room_cache['options']['player_number'],
                'players': response_players,
            }

            room.player_count += 1
            room.save()
            cache.set(room_cache_key, room_cache)
            cache.set(player_room_cache_key, room_id)

    reply_channel.send(response(response_data, nonce=nonce))

    Group(room_id).add(reply_channel)
    Group(room_id).send(event('room-join', event_data))