Exemplo n.º 1
0
    def handle(self, *args, **options):
        # Get the channel layer they asked for (or see if one isn't configured)
        if "layer" in options:
            self.channel_layer = get_channel_layer(options["layer"])
        else:
            self.channel_layer = get_channel_layer()

        if self.channel_layer is None:
            raise CommandError("You do not have any CHANNEL_LAYERS configured.")

        # Get beatconfig here.
        from beatserver.parser import Parser
        project_path = settings.SETTINGS_MODULE.replace('.settings', '')
        beat_config = Parser(project_path + '.beatconfig').get_beat_config()

        logger.debug("[CONFIG] %s", beat_config)

        # Run the worker
        logger.info("Starting beatserver...")

        server = self.server_class(
            application=get_default_application(),
            channel_layer=self.channel_layer,
            beat_config=beat_config
        )

        server.run()
Exemplo n.º 2
0
    def save(self):

        # 1. Unconfirm the other, if necessary
        if self.cleaned_data['confirmed']:
            if self.debate.confirmed_ballot != self.ballotsub and self.debate.confirmed_ballot is not None:
                self.debate.confirmed_ballot.confirmed = False
                self.debate.confirmed_ballot.save()

        # 2. Save ballot submission so that we can create related objects
        if self.ballotsub.pk is None:
            self.ballotsub.save()

        # 3. Save the specifics of the ballot
        self.save_ballot()

        # 4. Save ballot and result status
        self.ballotsub.discarded = self.cleaned_data['discarded']
        self.ballotsub.confirmed = self.cleaned_data['confirmed']
        self.ballotsub.save()

        self.debate.result_status = self.cleaned_data['debate_result_status']
        self.debate.save()

        t = self.debate.round.tournament
        # Need to provide a timestamp immediately for BallotStatusConsumer
        # as it will broadcast before the view finishes assigning one
        if self.ballotsub.confirmed:
            self.ballotsub.confirm_timestamp = timezone.now()

        # 5. Notify the Latest Results consumer (for results/overview)
        if self.ballotsub.confirmed:
            if self.debate.result_status is self.debate.STATUS_CONFIRMED:
                group_name = BallotResultConsumer.group_prefix + "_" + t.slug
                async_to_sync(get_channel_layer().group_send)(group_name, {
                    "type": "send_json",
                    "data": self.ballotsub.serialize_like_actionlog
                })

        # 6. Notify the Results Page/Ballots Status Graph
        group_name = BallotStatusConsumer.group_prefix + "_" + t.slug
        meta = get_status_meta(self.debate)
        async_to_sync(get_channel_layer().group_send)(group_name, {
            "type": "send_json",
            "data": {
                'status': self.cleaned_data['debate_result_status'],
                'icon': meta[0],
                'class': meta[1],
                'sort': meta[2],
                'ballot': self.ballotsub.serialize(t),
                'round': self.debate.round.id
            }
        })

        return self.ballotsub
Exemplo n.º 3
0
 def test_override_settings(self):
     """
     The channel layers cache is reset when the CHANNEL_LAYERS setting
     changes.
     """
     with override_settings(
         CHANNEL_LAYERS={
             "default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}
         }
     ):
         self.assertEqual(channel_layers.backends, {})
         get_channel_layer()
         self.assertNotEqual(channel_layers.backends, {})
     self.assertEqual(channel_layers.backends, {})
Exemplo n.º 4
0
    def post(self, request):
        """ """
        body = json.loads(request.body)
        print("Got POST request with body: ", body)

        # VALIDATE TOKEN
        token = self._get_token(request)
        spotify_user = SpotifyUser(token)
        if not spotify_user.is_token_valid():
            return HttpResponseForbidden('Spotify token is not valid')

        # VALIDATE SEARCH ARGS
        # Parse request for search arguments
        search_args = body
        if not self._valid_search_args(search_args):
            return HttpResponseBadRequest("Bad Search Arguments")

        # Get Playlist ID
        playlistURL = spotify_user.get_spotify_playlist(erase=True)

        # Asynchronously populate playlist
        async_to_sync(get_channel_layer().send)(
            "search",
            {
                "type": "start_search",
                "playlist": playlistURL,
                "search_args": search_args,
                "token": token,
            },
        )

        return JsonResponse({ "playlist": playlistURL })
Exemplo n.º 5
0
    def send_browser_message_for_all_users(self, user):

        message = {
            "id": self.id,
            "subject": self.subject,
            "body": html2text(self.body),
            "created": self.created.strftime("%a %d %b %Y %H:%M"),
        }

        # Encode and send that message to the whole channels Group for our
        # liveblog. Note how you can send to a channel or Group from any part
        # of Django, not just inside a consumer.
        if not DJANGO2:
            from channels import Group
            Group(PUBLIC_GROUP).send({
                # WebSocket text frame, with JSON content
                "text": json.dumps(message),
            })
        else:
            from channels.layers import get_channel_layer
            channel_layer = get_channel_layer()
            from asgiref.sync import async_to_sync
            async_to_sync(channel_layer.group_send)(PUBLIC_GROUP, {"text": json.dumps(message)})

        return
Exemplo n.º 6
0
def send_ws_action_chapter_member(sender, instance, created, **kwargs):

    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "online_users",
        {
            'type': 'action',
            'payload': {
                'type': 'chapter_member',
                'id': instance.chapter_id,
                'slug': instance.member.slug
            }
        }
    )

    if instance.member.discord_id is not None:
        # send new chapter member alert to discord
        async_to_sync(channel_layer.group_send)(
            "discord_bot",
            {
                'type': 'push_update',
                'payload': {
                    'type': 'chapter_member',
                    'id': instance.member,
                    'discord_id': instance.member.discord_id,
                }
            }
        )
Exemplo n.º 7
0
async def test_websocket_consumer_groups():
    """
    Tests that WebsocketConsumer adds and removes channels from groups.
    """
    results = {}

    class TestConsumer(WebsocketConsumer):
        groups = ["chat"]

        def receive(self, text_data=None, bytes_data=None):
            results["received"] = (text_data, bytes_data)
            self.send(text_data=text_data, bytes_data=bytes_data)

    channel_layers_setting = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
        },
    }
    with override_settings(CHANNEL_LAYERS=channel_layers_setting):
        communicator = WebsocketCommunicator(TestConsumer, "/testws/")
        await communicator.connect()

        channel_layer = get_channel_layer()
        # Test that the websocket channel was added to the group on connect
        message = {"type": "websocket.receive", "text": "hello"}
        await channel_layer.group_send("chat", message)
        response = await communicator.receive_from()
        assert response == "hello"
        assert results["received"] == ("hello", None)
        # Test that the websocket channel was discarded from the group on disconnect
        await communicator.disconnect()
        assert channel_layer.groups == {}
Exemplo n.º 8
0
    def send_browser_message(self, user):

        message = {
            "id": self.id,
            "subject": str(self.subject),
            "body": html2text(self.body),
            "created": self.created.strftime("%a %d %b %Y %H:%M"),
        }

        # Encode and send that message to the whole channels Group for our
        # Websocket. Note how you can send to a channel or Group from any part
        # of Django, not just inside a consumer.
        logger.info("Sending browser notification to %s", user.username)
        if not DJANGO2:
            from channels import Group
            Group(groupname(user.username)).send({
                # WebSocket text frame, with JSON content
                "text": json.dumps(message),
            })
        else:
            from channels.layers import get_channel_layer
            channel_layer = get_channel_layer()
            from asgiref.sync import async_to_sync
            async_to_sync(channel_layer.group_send)(user.username, {"type": "send.notification",
                                                                    "text": message['body']})

        return
Exemplo n.º 9
0
def announce_likes(sender, instance, created, **kwargs):
    if created:
        channel_layer=get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "likes", {
                "type": "like_message",
                "message": instance.contents,
            }
    )
Exemplo n.º 10
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     # Get the channel layer they asked for (or see if one isn't configured)
     if "layer" in options:
         self.channel_layer = get_channel_layer(options["layer"])
     else:
         self.channel_layer = get_channel_layer()
     if self.channel_layer is None:
         raise CommandError("You do not have any CHANNEL_LAYERS configured.")
     # Run the worker
     logger.info("Running worker for channels %s", options["channels"])
     worker = self.worker_class(
         application=get_default_application(),
         channels=options["channels"],
         channel_layer=self.channel_layer,
     )
     worker.run()
Exemplo n.º 11
0
    async def async_handle_collection_elements(elements: Iterable[Element]) -> None:
        """
        Async helper function to update cache and send autoupdate.
        """
        # Update cache
        change_id = await update_cache(elements)

        # Send autoupdate
        channel_layer = get_channel_layer()
        await channel_layer.group_send(
            "autoupdate", {"type": "send_data", "change_id": change_id}
        )

        projector_data = await get_projector_data()
        # Send projector
        channel_layer = get_channel_layer()
        await channel_layer.group_send(
            "projector", {"type": "projector_changed", "data": projector_data}
        )
Exemplo n.º 12
0
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if not self.reply:
            channel_layer = get_channel_layer()
            payload = {
                    "type": "receive",
                    "key": "additional_news",
                    "actor_name": self.user.username

                }
            async_to_sync(channel_layer.group_send)('notifications', payload)
Exemplo n.º 13
0
def send_ws_action_user(sender, instance, **kwargs):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "online_users",
        {
            'type': 'action',
            'payload': {
                'type': 'user',
                'slug': instance.slug
            }
        }
    )
Exemplo n.º 14
0
 def dispatch(self):
     # Finally, dispatch the message to the group
     if not self.is_valid():
         return
     response = {}
     response['data'] = self.get_allowed_data()
     response['type'] = self.sub_type
     response = serializer.filter_json(response)
     async_to_sync(get_channel_layer().group_send)(
         self.group_name,
         response
     )
Exemplo n.º 15
0
def send_ws_action(sender, instance, created, **kwargs):

    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "online_users",
        {
            'type': 'action',
            'payload': {
                'type': 'comment',
                'id': instance.id
            }
        }
    )
Exemplo n.º 16
0
 def update(cls):
     if not cls.thread:
         cls.thread=uuid4().hex
     aircrafts = Aircraft.objects.filter(state__gte=1)
     if not aircrafts.count():
         return
     acfts = []
     for aircraft in aircrafts:
         acfts.append(aircraft)    
     message = {'type': 'aircrafts_update', 'Model':'Aircraft','data':json.loads(serialize('json',acfts))}
     channel_layer = get_channel_layer()
     llogger.debug("Updater: sending %s" % message)
     async_to_sync(channel_layer.group_send)("aircrafts",message)
 def handler():
     """Send a notification to the given channel."""
     try:
         async_to_sync(get_channel_layer().send)(
             CHANNEL_MAIN,
             {
                 'type': TYPE_ORM_NOTIFY,
                 'table': table,
                 'kind': kind,
                 'primary_key': str(primary_key),
             },
         )
     except ChannelFull:
         logger.exception("Unable to notify workers.")
Exemplo n.º 18
0
def send_ws_action_notification(sender, instance, created, **kwargs):

    if created:
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            instance.user.username,
            {
                'type': 'action',
                'payload': {
                    'type': 'notification',
                    'id': instance.id
                }
            }
        )
Exemplo n.º 19
0
def send_ws_action_chapter_division(sender, instance, created, **kwargs):

    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "online_users",
        {
            'type': 'action',
            'payload': {
                'type': 'chapter_division',
                'id': instance.chapter_id,
                'slug': instance.slug
            }
        }
    )
Exemplo n.º 20
0
def broadcast_presence(sender, user, **kwargs):
    # Broadcast the new list of present users to the room.
    channel_layer = get_channel_layer()
    serializer = PresenceSerializer(Presence.objects.get_online(), many=True)
    async_to_sync(channel_layer.group_send)(
        "online_users",
        {
            'type': 'presence',
            'payload': {
                'type': 'online_users',
                'presences': serializer.data,
                'lurkers': Presence.objects.get_anonymous_count(),
            }
        }
    )
Exemplo n.º 21
0
    def log_action(self, **kwargs):
        """Logs the action. Subclasses can call this if the class doesn't
        have `FormMixin`. If keyword arguments are provided, they override the
        keyword arguments provided by `get_action_log_fields()`, except for
        `ip_address`, which cannot be overridden.
        """
        ip_address = get_ip_address(self.request)
        action_log_fields = self.get_action_log_fields()
        action_log_fields.update(kwargs)
        log = ActionLogEntry.objects.log(ip_address=ip_address, **action_log_fields)

        # Notify the actionlog consumer to broadcast the event
        if self.tournament:
            print('Broadcasting notification of ActionLogEntryConsumer')
            group_name = ActionLogEntryConsumer.group_prefix + "_" + self.tournament.slug
            async_to_sync(get_channel_layer().group_send)(group_name, {
                "type": "send_json",
                "data": log.serialize,
            })
Exemplo n.º 22
0
def send_ws_discord_user(sender, instance, **kwargs):
    # If there is no way to match a user to discord don't bother sending anything
    if instance.discord_id is not None:
        # Cache discord id for user
        cache.set(instance.discord_id, instance.id, None)

        old_discord_id = instance.discord_id_tracker.previous('discord_id')

        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "discord_bot",
            {
                'type': 'push_update',
                'payload': {
                    'type': 'user',
                    'id': instance.id,
                    'discord_id': instance.discord_id,
                    'old_discord_id': old_discord_id
                }
            }
        )
Exemplo n.º 23
0
async def run_consumer(timeout=None, dry_run=False):
    """Run the consumer until it finishes processing.

    :param timeout: Set maximum execution time before cancellation, or
        ``None`` (default) for unlimited.
    :param dry_run: If ``True``, don't actually dispatch messages, just
        dequeue them. Defaults to ``False``.
    """
    channel = state.MANAGER_CONTROL_CHANNEL
    scope = {
        'type': 'control_event',
        'channel': channel,
    }

    app = ApplicationCommunicator(ManagerConsumer, scope)

    channel_layer = get_channel_layer()

    async def _consume_loop():
        """Run a loop to consume messages off the channels layer."""
        while True:
            message = await channel_layer.receive(channel)
            if dry_run:
                continue
            if message.get('type', {}) == '_resolwe_manager_quit':
                break
            message.update(scope)
            await app.send_input(message)

    if timeout is None:
        await _consume_loop()
    try:
        # A further grace period to catch late messages.
        async with async_timeout.timeout(timeout or 1):
            await _consume_loop()
    except asyncio.TimeoutError:
        pass

    await app.wait()
Exemplo n.º 24
0
def taillog(request, hostname, port, username, password, private, tail):
    """
    执行 tail log 接口
    """
    channel_layer = get_channel_layer()
    user = request.user.username
    os.environ["".format(user)] = "true"
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    if password:
        ssh.connect(hostname=hostname, port=port, username=username, password=decrypt_p(password))
    else:
        pkey = paramiko.RSAKey.from_private_key_file("{0}".format(private))
        ssh.connect(hostname=hostname, port=port, username=username, pkey=pkey)
    cmd = "tail " + tail
    stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
    for line in iter(stdout.readline, ""):
        if os.environ.get("".format(user)) == 'false':
            break
        result = {"status": 0, 'data': line}
        result_all = json.dumps(result)
        async_to_sync(channel_layer.group_send)(user, {"type": "user.message", 'text': result_all})
async def test_poll_observer():
    main = ApplicationCommunicator(
        MainConsumer, {'type': 'channel', 'channel': CHANNEL_MAIN}
    )

    await main.send_input({'type': TYPE_POLL, 'observer': 'test', 'interval': 2})

    channel_layer = get_channel_layer()

    # Nothing should be received in the first second.
    async with async_timeout.timeout(1):
        try:
            await channel_layer.receive(CHANNEL_WORKER)
            assert False
        except CancelledError:
            pass

    async with async_timeout.timeout(2):
        # Then after another second we should get a notification.
        notify = await channel_layer.receive(CHANNEL_WORKER)
        assert notify['type'] == TYPE_EVALUATE
        assert notify['observer'] == 'test'
Exemplo n.º 26
0
def send_ws_action_chapter(sender, instance, created, **kwargs):

    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "online_users",
        {
            'type': 'action',
            'payload': {
                'type': 'chapter',
                'id': instance.id
            }
        }
    )

    # send new chapter alert to discord
    async_to_sync(channel_layer.group_send)(
        "discord_bot",
        {
            'type': 'push_update',
            'payload': {
                'type': 'chapter',
            }
        }
    )
Exemplo n.º 27
0
 def receive(self, text_data):
     text_data_json = json.loads(text_data)
     type = strip_tags(text_data_json['type'])
     if type == "message":
         message = strip_tags(text_data_json['message'])
         user = self.user
         user_messaging_with_id = int(
             strip_tags(text_data_json['user_messaging_with_id']))
         user_messaging_with = None
         try:
             user_messaging_with = User.objects.get(
                 pk=user_messaging_with_id)
         except:
             pass
         # Проверка на нахождение в чёрном списке
         check = True
         user_blacklist = user.profile.blacklist
         viewed_user_blacklist = user_messaging_with.profile.blacklist
         if viewed_user_blacklist.filter(
                 pk=user.pk).exists() or user_blacklist.filter(
                     pk=user_messaging_with.pk).exists():
             check = False
         # Последние проверки на само сообщение и авторизацию
         if message is not None and message.strip() != "" and check:
             if user.is_authenticated and user_messaging_with is not None:
                 # Создаем сообщение и кладём в переписку
                 new_conversation_message = ConversationMessage(
                     user=user,
                     text=message,
                     date_time=datetime.datetime.now())
                 new_conversation_message.save()
                 current_conversation = get_conversation_and_create_if_not(
                     user, user_messaging_with)
                 current_conversation.messages.add(new_conversation_message)
                 current_conversation.save()
                 current_conversation.update_interaction()
                 # Если пользователь отправил сообщение, считаем, что он просмотрел предыдущие.
                 # Выбираем нужного пользователя и обновляем время последнего прочтения
                 if current_conversation.user1.username == user.username:
                     current_conversation.update_last_view_user1()
                 else:
                     current_conversation.update_last_view_user2()
                 #  Создаём уведомление о сообщении
                 notifications.create_notification_on_pm(
                     user, user_messaging_with)
                 # Обновляем список диалогов обоим пользователям, создавая событие в WebSocket'ах
                 channel_layer_temp = get_channel_layer()
                 async_to_sync(channel_layer_temp.group_send)(
                     "dialog_list_" + user.username, {
                         "type": "update_dialogs"
                     })
                 async_to_sync(channel_layer_temp.group_send)(
                     "dialog_list_" + user_messaging_with.username, {
                         "type": "update_dialogs"
                     })
                 # Отправляем событие создания сообщения
                 async_to_sync(self.channel_layer.group_send)(
                     self.room_group_name, {
                         'type':
                         'pm_message',
                         'message':
                         message,
                         'message_id':
                         new_conversation_message.id,
                         'username':
                         str(new_conversation_message.user.username),
                         'datetime':
                         str(
                             new_conversation_message.date_time.strftime(
                                 '%d.%m.%Y %H:%M'))
                     })
     elif type == "delete":
         id = text_data_json['id']
         user_messaging_with = text_data_json['user_messaging_with']
         try:
             message = ConversationMessage.objects.get(id=id)
         except ConversationMessage.DoesNotExist:
             message = "ok"
         if message == "ok" and self.user.is_authenticated:
             # Обновляем список диалогов обоим пользователям, создавая событие в WebSocket'ах
             channel_layer_temp = get_channel_layer()
             async_to_sync(channel_layer_temp.group_send)(
                 "dialog_list_" + self.user.username, {
                     "type": "update_dialogs"
                 })
             async_to_sync(channel_layer_temp.group_send)(
                 "dialog_list_" + user_messaging_with, {
                     "type": "update_dialogs"
                 })
             async_to_sync(self.channel_layer.group_send)(
                 self.room_group_name, {
                     'type': 'delete_message',
                     'message_id': id,
                 })
     elif type == "edit":
         id = text_data_json['id']
         user_messaging_with = text_data_json['user_messaging_with']
         try:
             message = ConversationMessage.objects.get(id=id)
         except ConversationMessage.DoesNotExist:
             message = "error"
         if message != "error" and self.user.is_authenticated and self.user.id == message.user.id and message.is_earlier_24(
         ):
             # Обновляем список диалогов обоим пользователям, создавая событие в WebSocket'ах
             channel_layer_temp = get_channel_layer()
             async_to_sync(channel_layer_temp.group_send)(
                 "dialog_list_" + self.user.username, {
                     "type": "update_dialogs"
                 })
             async_to_sync(channel_layer_temp.group_send)(
                 "dialog_list_" + user_messaging_with, {
                     "type": "update_dialogs"
                 })
             async_to_sync(self.channel_layer.group_send)(
                 self.room_group_name, {
                     'type': 'edit_message',
                     'message_id': id,
                 })
Exemplo n.º 28
0
def push(username, event):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(username, {
        "type": "push.message",
        "event": event
    })
Exemplo n.º 29
0
    def post(self, request, *args, **kwargs):
        userId = request.data.get('userId')
        note = request.data.get('note')

        try:
            userId = int(userId)
            profile = get_object_or_404(Profile, pk=userId)
            user = profile.user

            logged_user = self.request.user

            if user.pk == logged_user.pk or profile is None:
                raise Http404

        except:
            response = {
                'message': 'Invalid Request!!',
                'error': 'Invalid UserId, No User Found',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        logged_user_profile = logged_user.userAssociated.all().first()

        blocked_status = check_blocked_status(profile, logged_user_profile)
        if blocked_status:
            response = {
                'message': 'Failed',
                'error': blocked_status[0],
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        request_status = check_request_status(profile, logged_user_profile)
        if request_status[0] != 'NAF':
            response = {
                'message': 'Failed',
                'error': request_status[0],
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        try:
            friend_request = FriendRequest.objects.create(
                sender=logged_user_profile,
                receiver=profile,
                note=note,
                request_status='pending')

            # add notification
            notif_content = "You have received a friend request from " + str(
                logged_user_profile.full_name)
            ids_assoc = "requestId:" + str(friend_request.pk)
            data = FriendRequestNotifSerializer(friend_request).data
            print(data)
            notify.send(user,
                        recipient=user,
                        description=notif_content,
                        verb='friend_request_sent',
                        data=data)
            n = Notification.objects.filter(
                data={
                    "data": data
                }, recipient=user).order_by("-timestamp").first()
            d = NotificationsSerializer(n).data
            channel_layer = get_channel_layer()

            print(d, channel_layer.group_send)
            # Trigger message sent to group
            async_to_sync(channel_layer.group_send)(f"{user.id}", {
                "type": "notifi",
                "event": "friend_request_sent",
                "data": str(d)
            })

        except Exception as e:
            pass

        response = {'message': 'success', 'body': [], 'status': HTTP_200_OK}
        return Response(response, status=HTTP_200_OK)
import graphene
from graphene_django.types import DjangoObjectType

from django.contrib.auth import get_user_model

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

from core.models import Message, Room, MessageFile


channel_layer = get_channel_layer()


class MessageFileType(DjangoObjectType):
    """ Object type for files in messages """
    size = graphene.Int()

    class Meta:
        model = MessageFile
    
    def resolve_size(self, info):
        return self.file.size
    



class MessageType(DjangoObjectType):
    """ Message object type for GraphQL """
    files = graphene.List(MessageFileType)
Exemplo n.º 31
0
 def update_ws(msg):
     # send to channel
     channel_layer = get_channel_layer()
     async_to_sync(channel_layer.group_send)("tasks", msg)
Exemplo n.º 32
0
def group_send(game_id, dictionary):
    async_to_sync(get_channel_layer().group_send)('ChessGame_%s' % game_id,
                                                  dictionary)
Exemplo n.º 33
0
def room(request, room_name, room_id):

    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            now_date_Time = datetime.datetime.now()
            reg_date = now_date_Time.date()
            reg_time = now_date_Time.time()
            file_path = reg_date.strftime('%Y') + '/' + reg_date.strftime(
                '%m') + '/' + reg_date.strftime('%d') + '/' + str(
                    room_id) + '_' + room_name + '/'
            file_name = form.name()
            download_url = form.save(file_path)

            print(download_url)
            DBmodule.DBmodule.insertMessage(room_id, request.user.id, reg_date,
                                            reg_time, file_name, 1,
                                            download_url)

            room_group_name = 'chat_%s' % (room_id)
            channel_layer = get_channel_layer()

            async_to_sync(channel_layer.group_send)(room_group_name, {
                'type': 'chat_message',
                'message': file_name,
                'user_name': request.user.username,
                'kbn': '1',
                'file_path': download_url
            })

            return HttpResponse("ファイルの送信が完了")
        else:
            return HttpResponse("ファイルの送信が失敗")
    else:

        now_date = datetime.date.today()

        #print(room_name)
        room_data = Room.objects.get(id=room_id)
        print(room_data.room_name)
        print(room_data.id)

        chatlog = DBmodule.DBmodule.getMessage(room_id, now_date)

        messageLog = list()

        for row in chatlog:
            message = Message(row[0], row[1], str(row[2]), str(row[3]), row[4],
                              row[5], row[6])
            messageLog.append(message)

        form = FileForm()

        return render(
            request, 'app/room.html', {
                'form': form,
                'message_log': messageLog,
                'room_name_json': mark_safe(json.dumps(room_name)),
                'room_id_json': mark_safe(room_id),
                'room_data': room_data
            })
Exemplo n.º 34
0
 def send_to_all(cls, text_data):
     async_to_sync(get_channel_layer().group_send)(cls.group_id, {
         'type': 'channel.receive_broadcast',
         'data': text_data
     })
Exemplo n.º 35
0
 def send_to_team(cls, team, text_data):
     async_to_sync(get_channel_layer().group_send)(
         '%s-%d' % (cls.group_id, team.user_id), {
             'type': 'channel.receive_broadcast',
             'data': text_data
         })
async def test_worker_and_client():
    client_consumer = URLRouter([url(r'^ws/(?P<subscriber_id>.+)$', ClientConsumer)])

    client = WebsocketCommunicator(client_consumer, '/ws/test-session')
    main = ApplicationCommunicator(
        MainConsumer, {'type': 'channel', 'channel': CHANNEL_MAIN}
    )
    worker = ApplicationCommunicator(
        WorkerConsumer, {'type': 'channel', 'channel': CHANNEL_WORKER}
    )

    # Connect client.
    status, _ = await client.connect()
    assert status is True

    # Create an observer.
    @database_sync_to_async
    def create_observer():
        observer = QueryObserver(
            create_request(views.PaginatedViewSet, offset=0, limit=10)
        )
        items = observer.subscribe('test-session')
        assert not items
        return observer.id

    observer_id = await create_observer()
    await assert_subscribers(1)
    await assert_subscribers(1, observer_id)

    # Create a single model instance for the observer model.
    @database_sync_to_async
    def create_model():
        return models.ExampleItem.objects.create(enabled=True, name="hello world").pk

    primary_key = await create_model()
    channel_layer = get_channel_layer()

    async with async_timeout.timeout(1):
        # Check that ORM signal was generated.
        notify = await channel_layer.receive(CHANNEL_MAIN)
        assert notify['type'] == TYPE_ORM_NOTIFY
        assert notify['kind'] == ORM_NOTIFY_KIND_CREATE
        assert notify['primary_key'] == str(primary_key)

        # Propagate notification to worker.
        await main.send_input(notify)

        # Check that observer evaluation was requested.
        notify = await channel_layer.receive(CHANNEL_WORKER)
        assert notify['type'] == TYPE_EVALUATE
        assert notify['observer'] == observer_id

        # Propagate notification to worker.
        await worker.send_input(notify)
        response = await client.receive_json_from()
        assert response['msg'] == 'added'
        assert response['primary_key'] == 'id'
        assert response['order'] == 0
        assert response['item'] == {'id': 1, 'enabled': True, 'name': 'hello world'}

    # No other messages should be sent.
    assert await client.receive_nothing() is True
    await client.disconnect()

    # Ensure that subscriber has been removed.
    await assert_subscribers(0)

    async with async_timeout.timeout(1):
        # Run observer again and it should skip evaluation because there are no more subscribers.
        await worker.send_input({'type': TYPE_EVALUATE, 'observer': observer_id})

    assert await worker.receive_nothing() is True
Exemplo n.º 37
0
 def send_to_socket(self, username, message):
     layer = get_channel_layer()
     async_to_sync(layer.group_send)('log_' + username, {
         'type': 'log_message',
         'message': message
     })
Exemplo n.º 38
0
def api(req):
    httpresponse = None
    if req.method == "POST":
        print("GET:{}".format(req.GET))
        tracker = req.GET.get("tracker")
        print("tracker:{}".format(tracker))
        trackers = tracker.split(",")
        if tracker:
            if "ffxiv-eureka" in trackers:
                instance = req.GET.get("instance")
                password = req.GET.get("password")
                print("ffxiv-eureka {}:{}".format(instance, password))
                if instance and password:
                    nm_name = req.POST.get("text")
                    if nm_name:
                        nm_id = get_nm_id("ffxiv-eureka", nm_name)
                        print("nm_name:{} id:{}".format(nm_name, nm_id))
                        if nm_id > 0:
                            print("nm_name:{} nm_id:{}".format(nm_name, nm_id))
                            # ws = create_connection("wss://ffxiv-eureka.com/socket/websocket?vsn=2.0.0")
                            ws = create_connection(
                                "wss://ffxiv-eureka.com/socket/websocket?vsn=2.0.0"
                            )
                            msg = '["1","1","instance:{}","phx_join",{{"password":"******"}}]'.format(
                                instance, password)
                            # print(msg)
                            ws.send(msg)
                            msg = '["1","2","instance:{}","set_kill_time",{{"id":{},"time":{}}}]'.format(
                                instance, nm_id, int(time.time() * 1000))
                            # print(msg)
                            ws.send(msg)
                            ws.close()
                            httpresponse = HttpResponse("OK", status=200)
                    else:
                        print("no nm_name")
            if "ffxivsc" in trackers:
                key = req.GET.get("key")
                # print("ffxivsc key: {}".format(key))
                if key:
                    nm_name = req.POST.get("text")
                    # print(nm_name)
                    if nm_name:
                        nm_level_type = get_nm_id("ffxivsc", nm_name)
                        if int(nm_level_type["type"]) > 0:
                            url = "https://api.ffxivsc.cn/ffxivsc_eureka_v2-1.2/lobby/addKillTime"
                            post_data = {
                                # "killTime": strftime(
                                #     "%Y-%m-%d %H:%M", time.localtime()
                                # ),
                                "level": "{}".format(nm_level_type["level"]),
                                "key": key,
                                "type": "{}".format(nm_level_type["type"]),
                            }
                            r = requests.post(url=url, data=post_data)
                            httpresponse = HttpResponse(r)
                        else:
                            HttpResponse("No NM can be matched", status=500)
                    else:
                        print("no nm_name")
                        HttpResponse("No NM name provided", status=500)
            if "qq" in trackers:
                bot_qq = req.GET.get("bot_qq")
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                group_id = req.GET.get("group")
                print("bot: {} qq:{} token:{}".format(bot_qq, qq, token))
                if bot_qq and qq and token:
                    bot = None
                    qquser = None
                    group = None
                    api_rate_limit = True
                    try:
                        bot = QQBot.objects.get(user_id=bot_qq)
                    except QQBot.DoesNotExist:
                        print("bot {} does not exist".format(bot_qq))
                    try:
                        qquser = QQUser.objects.get(user_id=qq,
                                                    bot_token=token)
                        if time.time(
                        ) < qquser.last_api_time + qquser.api_interval:
                            api_rate_limit = False
                            print("qquser {} api rate limit exceed".format(qq))
                        qquser.last_api_time = int(time.time())
                        qquser.save(update_fields=["last_api_time"])
                    except QQUser.DoesNotExist:
                        print("qquser {}:{} auth fail".format(qq, token))
                        httpresponse = HttpResponse(
                            "QQUser {}:{} auth fail".format(qq, token),
                            status=500)
                    if bot and qquser and api_rate_limit:
                        channel_layer = get_channel_layer()
                        msg = req.POST.get("text")
                        reqbody = req.body
                        # print("reqbody:{}".format(reqbody))
                        try:
                            if reqbody:
                                reqbody = reqbody.decode()
                                # print("reqbody1:{}".format(reqbody))
                                reqbody = json.loads(reqbody)
                                # print("reqbody2:{}".format(reqbody))
                                msg = msg or reqbody.get("content")
                                msg = re.compile(
                                    "[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]").sub(
                                        " ", msg)
                        except BaseException:
                            pass
                        if not msg:
                            try:
                                msg = github_webhook(req)
                            except BaseException:
                                pass
                        if not msg:
                            print("Can't get msg from request:{}:{}".format(
                                req, reqbody))
                            httpresponse = HttpResponse("Can't get message",
                                                        status=500)
                        else:
                            print("body:{}".format(req.body.decode()))
                            if group_id:
                                try:
                                    group = QQGroup.objects.get(
                                        group_id=group_id)
                                    group_push_list = [
                                        user["user_id"] for user in json.loads(
                                            group.member_list)
                                        if (user["role"] == "owner"
                                            or user["role"] == "admin")
                                    ]
                                    print("group push list:{}".format(
                                        group_push_list))
                                except QQGroup.DoesNotExist:
                                    print("group:{} does not exist".format(
                                        group_id))
                            msg = handle_hunt_msg(msg)
                            if (group and group.api and int(qquser.user_id)
                                    in group_push_list):
                                at_msg = ("[CQ:at,qq={}]".format(
                                    qquser.user_id) if req.GET.get(
                                        "at", "true") == "true" else str(
                                            qquser.user_id))
                                jdata = {
                                    "action": "send_group_msg",
                                    "params": {
                                        "group_id":
                                        group.group_id,
                                        "message":
                                        "Message from {}:\n{}".format(
                                            at_msg, msg),
                                    },
                                    "echo": "",
                                }
                            else:
                                jdata = {
                                    "action": "send_private_msg",
                                    "params": {
                                        "user_id": qquser.user_id,
                                        "message": msg,
                                    },
                                    "echo": "",
                                }
                            if not bot.api_post_url:
                                async_to_sync(channel_layer.send)(
                                    bot.api_channel_name,
                                    {
                                        "type": "send.event",
                                        "text": json.dumps(jdata)
                                    },
                                )
                            else:
                                url = os.path.join(
                                    bot.api_post_url,
                                    "{}?access_token={}".format(
                                        jdata["action"], bot.access_token),
                                )
                                headers = {"Content-Type": "application/json"}
                                r = requests.post(
                                    url=url,
                                    headers=headers,
                                    data=json.dumps(jdata["params"]),
                                )
                                if r.status_code != 200:
                                    logging.error(r.text)
                            httpresponse = HttpResponse("OK", status=200)
            if "hunt" in trackers:
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                group_id = req.GET.get("group")
                bot_qq = req.GET.get("bot_qq")
                print("qq:{} token:{}, group:{}".format(qq, token, group_id))
                if bot_qq and qq and token:
                    qquser = None
                    group = None
                    api_rate_limit = True
                    try:
                        bot = QQBot.objects.get(user_id=bot_qq)
                        qquser = QQUser.objects.get(user_id=qq,
                                                    bot_token=token)
                        if time.time(
                        ) < qquser.last_api_time + qquser.api_interval:
                            api_rate_limit = False
                            print("qquser {} api rate limit exceed".format(qq))
                        httpresponse = HttpResponse(
                            "User API rate limit exceed", status=500)
                    except QQUser.DoesNotExist:
                        print("qquser {}:{} auth fail".format(qq, token))
                    except QQBot.DoesNotExist:
                        print("bot {} does not exist".format(bot_qq))
                    else:
                        channel_layer = get_channel_layer()
                        try:
                            reqbody = json.loads(req.body.decode())
                        except BaseException as e:
                            print(e)
                        else:
                            print("reqbody:{}".format(reqbody))
                            try:
                                hunt_group = HuntGroup.objects.get(
                                    group__group_id=group_id)
                                group = hunt_group.group
                                group_push_list = [
                                    user["user_id"]
                                    for user in json.loads(group.member_list)
                                ]
                                assert (
                                    int(qquser.user_id) in group_push_list
                                ), "You're not in the group member list"
                                monster_name = reqbody["monster"]
                                zone_name = reqbody["zone"]
                                zone_name = (zone_name.replace(
                                    chr(57521),
                                    "").replace(chr(57522),
                                                "2").replace(chr(57523), "3"))
                                try:
                                    monster = Monster.objects.get(
                                        cn_name=monster_name)
                                except Monster.DoesNotExist:
                                    monster = Monster.objects.get(
                                        cn_name=re.sub("1|2|3", "",
                                                       monster_name))
                                world_name = reqbody.get("world", "None")
                                timestamp = int(reqbody["time"])
                                server = None
                                world_id = reqbody.get("worldid", -1)
                                servers = Server.objects.filter(
                                    worldId=world_id)
                                server = (servers[0] if servers.exists() else
                                          Server.objects.get(name=world_name))
                                success = False
                                # handle instances
                                if (req.GET.get("strict_zone",
                                                "true") == "false"
                                        or str(monster.territory) in zone_name
                                    ):  # "ZoneName2", "ZoneName"
                                    if (str(monster.territory) !=
                                            zone_name):  # "ZoneName2"
                                        monster_name = zone_name.replace(
                                            str(monster.territory),
                                            monster_name
                                        )  # "ZoneName2" -> "MonsterName2"
                                        try:
                                            monster = Monster.objects.get(
                                                cn_name=monster_name)
                                        except Monster.DoesNotExist:
                                            monster = Monster.objects.get(
                                                cn_name=re.sub(
                                                    "1|2|3", "", monster_name))
                                    print(
                                        "Get HuntLog info:\nmonster:{}\nserver:{}"
                                        .format(monster, server))
                                    if HuntLog.objects.filter(
                                            monster=monster,
                                            server=server,
                                            hunt_group=hunt_group,
                                            log_type="kill",
                                            time__gt=timestamp - 60,
                                    ).exists():
                                        msg = '{}——"{}" 已在一分钟内记录上报,此次API调用被忽略'.format(
                                            server,
                                            monster,
                                            time.strftime(
                                                "%Y-%m-%d %H:%M:%S",
                                                time.localtime(timestamp),
                                            ),
                                        )
                                        success = False
                                    else:
                                        hunt_log = HuntLog(
                                            monster=monster,
                                            hunt_group=hunt_group,
                                            server=server,
                                            log_type="kill",
                                            time=timestamp,
                                        )
                                        hunt_log.save()
                                        msg = '{}——"{}" 击杀时间: {}'.format(
                                            hunt_log.server,
                                            monster,
                                            time.strftime(
                                                "%Y-%m-%d %H:%M:%S",
                                                time.localtime(timestamp),
                                            ),
                                        )
                                        at_msg = ("[CQ:at,qq={}]".format(
                                            qquser.user_id) if req.GET.get(
                                                "at", "true") == "true" else
                                                  str(qquser.user_id))
                                        msg = at_msg + "通过API更新了如下HuntLog:\n{}".format(
                                            msg)
                                        success = True
                                else:
                                    at_msg = ("[CQ:at,qq={}]".format(
                                        qquser.user_id) if req.GET.get(
                                            "at", "true") == "true" else str(
                                                qquser.user_id))
                                    msg = at_msg + "上报 {} 失败,{} 与 {} 不兼容".format(
                                        monster, monster.territory, zone_name)
                                    success = False
                                if success or req.GET.get("verbose",
                                                          "false") == "true":
                                    jdata = {
                                        "action": "send_group_msg",
                                        "params": {
                                            "group_id":
                                            hunt_group.group.group_id,
                                            "message": msg,
                                        },
                                        "echo": "",
                                    }
                                    if not bot.api_post_url:
                                        async_to_sync(channel_layer.send)(
                                            bot.api_channel_name,
                                            {
                                                "type": "send.event",
                                                "text": json.dumps(jdata),
                                            },
                                        )
                                    else:
                                        url = os.path.join(
                                            bot.api_post_url,
                                            "{}?access_token={}".format(
                                                jdata["action"],
                                                bot.access_token),
                                        )
                                        headers = {
                                            "Content-Type": "application/json"
                                        }
                                        r = requests.post(
                                            url=url,
                                            headers=headers,
                                            data=json.dumps(jdata["params"]),
                                        )
                                        if r.status_code != 200:
                                            logging.error(r.text)
                                httpresponse = HttpResponse(status=200)
                            except HuntGroup.DoesNotExist:
                                print("HuntGroup:{} does not exist".format(
                                    group_id))
                                httpresponse = HttpResponse(
                                    "HuntGroup:{} does not exist".format(
                                        group_id),
                                    status=500,
                                )
                            except Monster.DoesNotExist:
                                print("Monster:{} does not exist".format(
                                    monster_name))
                                httpresponse = HttpResponse(
                                    "Monster:{} does not exist".format(
                                        monster_name),
                                    status=500,
                                )
                            except Server.DoesNotExist:
                                print("Server:{} does not exist".format(
                                    world_name))
                                httpresponse = HttpResponse(
                                    "Server:{} does not exist".format(
                                        world_name),
                                    status=500,
                                )
                            except AssertionError as e:
                                print(str(e))
                                httpresponse = HttpResponse(str(e), status=500)
                else:
                    httpresponse = HttpResponse("Missing URL parameters",
                                                status=500)
            if "webapi" in trackers:
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                print("qq:{}\ntoken:{}".format(qq, token))
                if qq and token:
                    qquser = None
                    try:
                        qquser = QQUser.objects.get(user_id=qq,
                                                    bot_token=token)
                    except QQUser.DoesNotExist:
                        res_dict = {
                            "response": "error",
                            "msg": "Invalid API token",
                            "rcode": "101",
                        }
                        return JsonResponse(res_dict)
                    if qquser:
                        res_dict = webapi(req)
                        return JsonResponse(res_dict)
                else:
                    res_dict = {
                        "response": "error",
                        "msg": "Invalid request",
                        "rcode": "100",
                    }
                    return JsonResponse(res_dict)
                return HttpResponse("Default API Error, contact dev please",
                                    status=500)
    return (httpresponse if httpresponse else HttpResponse(
        "Default API Error, contact dev please.", status=500))
Exemplo n.º 39
0
 def receive(self, text_data):
     text_data_json = json.loads(text_data)
     message = text_data_json       
     channel_layer = get_channel_layer()        
Exemplo n.º 40
0
    def handle_finish(self, obj):
        """Handle an incoming ``Data`` finished processing request.

        :param obj: The Channels message object. Command object format:

            .. code-block:: none

                {
                    'command': 'finish',
                    'data_id': [id of the :class:`~resolwe.flow.models.Data` object
                               this command changes],
                    'process_rc': [exit status of the processing]
                    'spawn_processes': [optional; list of spawn dictionaries],
                    'exported_files_mapper': [if spawn_processes present]
                }
        """
        data_id = obj[ExecutorProtocol.DATA_ID]
        logger.debug(
            __("Finishing Data with id {} (handle_finish).", data_id),
            extra={
                'data_id': data_id,
                'packet': obj
            }
        )
        spawning_failed = False
        with transaction.atomic():
            # Spawn any new jobs in the request.
            spawned = False
            if ExecutorProtocol.FINISH_SPAWN_PROCESSES in obj:
                if is_testing():
                    # NOTE: This is a work-around for Django issue #10827
                    # (https://code.djangoproject.com/ticket/10827), same as in
                    # TestCaseHelpers._pre_setup(). Because the listener is running
                    # independently, it must clear the cache on its own.
                    ContentType.objects.clear_cache()

                spawned = True
                exported_files_mapper = obj[ExecutorProtocol.FINISH_EXPORTED_FILES]
                logger.debug(
                    __("Spawning new Data objects for Data with id {} (handle_finish).", data_id),
                    extra={
                        'data_id': data_id
                    }
                )

                try:
                    # This transaction is needed because we're running
                    # asynchronously with respect to the main Django code
                    # here; the manager can get nudged from elsewhere.
                    with transaction.atomic():
                        parent_data = Data.objects.get(pk=data_id)

                        # Spawn processes.
                        for d in obj[ExecutorProtocol.FINISH_SPAWN_PROCESSES]:
                            d['contributor'] = parent_data.contributor
                            d['process'] = Process.objects.filter(slug=d['process']).latest()
                            d['tags'] = parent_data.tags

                            for field_schema, fields in iterate_fields(d.get('input', {}), d['process'].input_schema):
                                type_ = field_schema['type']
                                name = field_schema['name']
                                value = fields[name]

                                if type_ == 'basic:file:':
                                    fields[name] = self.hydrate_spawned_files(
                                        exported_files_mapper, value, data_id
                                    )
                                elif type_ == 'list:basic:file:':
                                    fields[name] = [self.hydrate_spawned_files(exported_files_mapper, fn, data_id)
                                                    for fn in value]

                            with transaction.atomic():
                                d = Data.objects.create(**d)
                                DataDependency.objects.create(
                                    parent=parent_data,
                                    child=d,
                                    kind=DataDependency.KIND_SUBPROCESS,
                                )

                                # Copy permissions.
                                copy_permissions(parent_data, d)

                                # Entity is added to the collection only when it is
                                # created - when it only contains 1 Data object.
                                entities = Entity.objects.filter(data=d).annotate(num_data=Count('data')).filter(
                                    num_data=1)

                                # Copy collections.
                                for collection in parent_data.collection_set.all():
                                    collection.data.add(d)

                                    # Add entities to which data belongs to the collection.
                                    for entity in entities:
                                        entity.collections.add(collection)

                except Exception:  # pylint: disable=broad-except
                    logger.error(
                        __(
                            "Error while preparing spawned Data objects of process '{}' (handle_finish):\n\n{}",
                            parent_data.process.slug,
                            traceback.format_exc()
                        ),
                        extra={
                            'data_id': data_id
                        }
                    )
                    spawning_failed = True

            # Data wrap up happens last, so that any triggered signals
            # already see the spawned children. What the children themselves
            # see is guaranteed by the transaction we're in.
            if ExecutorProtocol.FINISH_PROCESS_RC in obj:
                process_rc = obj[ExecutorProtocol.FINISH_PROCESS_RC]

                try:
                    d = Data.objects.get(pk=data_id)
                except Data.DoesNotExist:
                    logger.warning(
                        "Data object does not exist (handle_finish).",
                        extra={
                            'data_id': data_id,
                        }
                    )
                    async_to_sync(self._send_reply)(obj, {ExecutorProtocol.RESULT: ExecutorProtocol.RESULT_ERROR})
                    return

                changeset = {
                    'process_progress': 100,
                    'finished': now(),
                }

                if spawning_failed:
                    changeset['status'] = Data.STATUS_ERROR
                    changeset['process_error'] = ["Error while preparing spawned Data objects"]

                elif process_rc == 0 and not d.status == Data.STATUS_ERROR:
                    changeset['status'] = Data.STATUS_DONE

                else:
                    changeset['status'] = Data.STATUS_ERROR
                    changeset['process_rc'] = process_rc

                obj[ExecutorProtocol.UPDATE_CHANGESET] = changeset
                self.handle_update(obj, internal_call=True)

        if not getattr(settings, 'FLOW_MANAGER_KEEP_DATA', False):
            # Purge worker is not running in test runner, so we should skip triggering it.
            if not is_testing():
                channel_layer = get_channel_layer()
                try:
                    async_to_sync(channel_layer.send)(
                        CHANNEL_PURGE_WORKER,
                        {
                            'type': TYPE_PURGE_RUN,
                            'location_id': d.location.id,
                            'verbosity': self._verbosity,
                        }
                    )
                except ChannelFull:
                    logger.warning(
                        "Cannot trigger purge because channel is full.",
                        extra={'data_id': data_id}
                    )

        # Notify the executor that we're done.
        async_to_sync(self._send_reply)(obj, {ExecutorProtocol.RESULT: ExecutorProtocol.RESULT_OK})

        # Now nudge the main manager to perform final cleanup. This is
        # needed even if there was no spawn baggage, since the manager
        # may need to know when executors have finished, to keep count
        # of them and manage synchronization.
        async_to_sync(consumer.send_event)({
            WorkerProtocol.COMMAND: WorkerProtocol.FINISH,
            WorkerProtocol.DATA_ID: data_id,
            WorkerProtocol.FINISH_SPAWNED: spawned,
            WorkerProtocol.FINISH_COMMUNICATE_EXTRA: {
                'executor': getattr(settings, 'FLOW_EXECUTOR', {}).get('NAME', 'resolwe.flow.executors.local'),
            },
        })
Exemplo n.º 41
0
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

from channels.layers import get_channel_layer


channel_layer = get_channel_layer()


class EchoConsumer(WebsocketConsumer):
    def connect(self):
        # 创建channels group, 命名为:用户名,并使用channel_layer写入到redis
        async_to_sync(self.channel_layer.group_add)(self.scope['user'].username, self.channel_name)

        # 返回给receive方法处理
        self.accept()

    def receive(self, text_data):
        async_to_sync(self.channel_layer.group_send)(
            self.scope['user'].username,
            {
                "type": "user.message",
                "text": text_data,
            },
        )

    def user_message(self, event):
        # 消费
        self.send(text_data=event["text"])

    def disconnect(self, close_code):
Exemplo n.º 42
0
 def _send_channel_layers_event(cls, group_name, json_data, type_name,
                                event_name):
     data = {"type": type_name, "data": json_data, "event": event_name}
     channel_layers = get_channel_layer()
     async_to_sync(channel_layers.group_send)(group_name, data)
Exemplo n.º 43
0
import logging

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db.models.signals import post_save
from django.dispatch import receiver
from fancy_cache.memory import find_urls
from rest_framework.reverse import reverse

from apps.routes.models import RouteTelemetryData
from apps.shipments.models import TransitState

LOG = logging.getLogger('transmission')

channel_layer = get_channel_layer()  # pylint:disable=invalid-name


@receiver(post_save,
          sender=RouteTelemetryData,
          dispatch_uid='routetelemetrydata_post_save')
def telemetrydata_post_save(sender, **kwargs):
    instance = kwargs["instance"]
    LOG.debug(
        f'New telemetry_data committed to db and will be pushed to the UI. Telemetry_data: {instance.id}.'
    )

    # Invalidate cached telemetry data view for each shipment in Route
    for leg in instance.route.routeleg_set.filter(
            shipment__state=TransitState.IN_TRANSIT.value):
        telemetry_get_url = reverse('shipment-telemetry-list',
                                    kwargs={
Exemplo n.º 44
0
def outdoorCameraRecognize(outdoorNum='1'):
    """
    调用 outdoorNum 入口处摄像头并扫描车牌
    """
    image_abspath = camera_provider(local='outdoor')
    # print('照片:', image_abspath)
    global count_down
    global last_pstr
    if image_abspath is not None:
        if count_down.value == 0:
            # print('车牌识别!')
            evl = lpr_provider.recognize_single_image(image_abspath)  # noqa
            if len(evl) == 0:
                # TODO: 记录日志
                # 也可能是其他非车辆实体触碰
                print('{} 号出口车牌识别未达到精度或出现问题'.format(outdoorNum))
                # last_pstr.value = bytes(' ', encoding='utf8')
            else:
                pstr = evl[0]
                confidence = evl[1]
                print('{} 号出口车牌识别结果: {} 精度 {}'.format(outdoorNum, pstr,
                                                      confidence))
                count_down.value = 5
                channel_layer = get_channel_layer()
                if str(last_pstr.value, encoding="utf-8") != pstr:
                    last_pstr.value = bytes(pstr, encoding="utf8")
                    # TODO: 数据库更新
                    fee_dialog = operations.get_fee_and_cards(
                        pstr, datetime.datetime.utcnow())
                    fee_dialog['license_plate'] = pstr
                    fee_dialog['outdoorNum'] = outdoorNum
                    fee_dialog['outdoorName'] = operations.getDoorNameById(
                        outdoorNum)
                    async_to_sync(channel_layer.group_send)(
                        'outdoor_{}'.format(outdoorNum), {
                            'type': 'send_fee_cards',
                            'message': json.dumps(fee_dialog)
                        })
                    async_to_sync(channel_layer.group_send)(
                        'outdoor_admin_{}'.format(outdoorNum), {
                            'type': 'send_fee_cards',
                            'message': json.dumps(fee_dialog)
                        })
                else:
                    # 同一辆车
                    # 稳健性? 处理发送失败
                    pass
        else:
            # 倒计时
            count_down.value -= 1
    else:
        # print('暂无车辆在停车场出入口')
        # 置零, 防止倒计时还没技术就没有车辆在出入口了
        count_down.value = 0
        if not str(last_pstr.value, encoding='utf8').isspace():
            try:
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    'outdoor_{}'.format(outdoorNum),
                    {
                        # 这个 type 是 Consumer 中的一个 Listen method
                        # 这个 group_send 就是向该 group 下所有 Consumers
                        # 发送一个以这个字典作为数据的 event 给 consumers
                        # 中 type 指定的 method, 注意: type 中的 `.` 会被
                        # 替换为 `_`
                        'type': 'outdoor_discover_license_plate',
                        # 后面的这些字段将会被 wrap 到 event
                        'message': json.dumps({
                            'pstr': '',
                            # 其他从数据库中获取的数据
                        })
                    })
                # TODO: DCMMC: 下面这一句只是为了 Test!
                parkings = operations.getUsedParkings()
                if parkings['code'] == 'success' and len(parkings['data']) > 0:
                    # TODO: 暂定 8080 端口
                    p_id = random.sample(parkings['data'], 1)[0]
                    print('模拟离开停车场: ', p_id)
                    re = requests.post('http://' + redis_host +
                                       ':8080/parking_lot_status_update',
                                       json={
                                           'code':
                                           'updateParkingPartial',
                                           'data': [{
                                               'parking_id': p_id,
                                               'used': False,
                                               'addition_info': '模拟离开'
                                           }]
                                       })
                    print('######## post:', re, re.text)
            except Exception as e:
                print(e)
            last_pstr.value = bytes(' ', encoding='utf8')
Exemplo n.º 45
0
def login(request):
    """
    用于小程序的“登陆”功能,获得用户openid和session_key
    """
    post_data = json.loads(request.body.decode('utf-8'))
    print(request.body.decode('utf-8'))
    code = post_data.get('code', '')
    if not code:
        return HttpResponse('{"result":"error", "msg":"no code"}')
    response = requests.get(
        'https://api.weixin.qq.com/sns/jscode2session?'
        'appid={}&secret={}&js_code={}&grant_type=authorization_code'.format(
            xcx_appid, xcx_appsecret, code))
    decode = json.loads(response.content.decode())
    openid = decode.get('openid', '')

    if not openid:
        print(response.content)
        parse_response = json.loads(response.content)
        decode['errcode'] = parse_response.get('errcode')
        decode['errmsg'] = parse_response.get('errmsg')
        avatar = post_data.get('avatarUrl', None)
        if avatar is None:
            return HttpResponse(response.content)
        openid = Participant.objects.get(avatar=avatar).openid
        decode['openid'] = openid

    try:
        xcx_user = Participant.objects.get(openid=openid)
    except Participant.DoesNotExist:
        xcx_user = Participant(openid=openid)

    xcx_user.nickname = post_data.get('nickName', 'Anonymous.')
    xcx_user.avatar = post_data.get('avatarUrl', 'default_avatar')
    xcx_user.gender = post_data.get('gender', 0)
    xcx_user.country = post_data.get('country', 'Solar System')
    xcx_user.province = post_data.get('province', 'Alpha Centauri')
    xcx_user.city = post_data.get('city', 'Proxima Centauri')
    xcx_user.language = post_data.get('language', 'Xenolinguistics')
    activity_id = post_data.get('activity_id', None)
    xcx_user.activate_in = activity_id
    xcx_user.save()
    decode['result'] = 'ok'
    post_data['uid'] = openid
    post_data['avatar'] = post_data['avatarUrl']
    post_data['nickname'] = post_data['nickName']
    del post_data['avatarUrl']
    del post_data['code']
    del post_data['nickName']

    try:
        activity = Activity.objects.get(id=activity_id)
        activity.participants.add(xcx_user)
        activity.save()
        decode['activity_name'] = activity.name
        decode['activity_status'] = activity.status
        del post_data['activity_id']
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "console_" + str(activity_id), {
                'type': 'chat.message',
                'text': json.dumps({
                    'action': 'append-user',
                    'content': post_data
                })
            })
    except Activity.DoesNotExist:
        decode['activity_name'] = '<ERROR>'
        decode[
            'activity_status'] = 'no such activity' if activity_id is not None else 'no activity id'
    print(json.dumps(decode))
    return HttpResponse(json.dumps(decode))
Exemplo n.º 46
0
def indoorCameraRecognize(indoorNum='1'):
    """
    调用 indoorNum 入口处摄像头并扫描车牌
    一个树莓派 Camera 实例一个识别任务(要么是 indoor 要么是 outdoor)
    """
    # print('indoorCameraRecognize')
    image_abspath = camera_provider()
    # print('照片:', image_abspath)
    global count_down
    global last_pstr
    if image_abspath is not None:
        if count_down.value == 0:
            # print('车牌识别!')
            print('路径:\n', image_abspath)
            evl = lpr_provider.recognize_single_image(image_abspath)  # noqa
            if len(evl) == 0:
                # TODO: 记录日志
                # 也可能是其他非车辆实体触碰
                print('{} 号入口车牌识别未达到精度或出现问题'.format(indoorNum))
                # last_pstr.value = bytes(' ', encoding='utf8')
            else:
                pstr = evl[0]
                confidence = evl[1]
                print('{} 号入口车牌识别结果: {} 精度 {}'.format(indoorNum, pstr,
                                                      confidence))
                count_down.value = 5
                if str(last_pstr.value, encoding="utf-8") != pstr:
                    last_pstr.value = bytes(pstr, encoding="utf8")
                    res = operations.vehicle_enter(pstr,
                                                   datetime.datetime.utcnow,
                                                   indoorNum)
                    print('debug结果:', res)
                else:
                    # 同一辆车
                    pass
                # TODO: 从数据库中获取该车辆有关信息
                # 不管是不是发现是用一辆车, 都要发一次 ws 数据包,
                # 因为 ws 数据包有可能发送失败
                # TODO: 还可以使用其他健壮性更好地错误处理方案
                # 获取 redis 中存储的 channel layer
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    'indoor_{}'.format(indoorNum),
                    {
                        # 这个 type 是 Consumer 中的一个 Listen method
                        # 这个 group_send 就是向该 group 下所有 Consumers
                        # 发送一个以这个字典作为数据的 event 给 consumers
                        # 中 type 指定的 method, 注意: type 中的 `.` 会被
                        # 替换为 `_`
                        'type': 'indoor_discover_license_plate',
                        # 后面的这些字段将会被 wrap 到 event
                        'message': json.dumps({
                            'pstr': pstr,
                            # 其他从数据库中获取的数据
                        })
                    })
        else:
            # 倒计时
            count_down.value -= 1
    else:
        # print('暂无车辆在停车场出入口')
        # 置零, 防止倒计时还没技术就没有车辆在出入口了
        count_down.value = 0
        if not str(last_pstr.value, encoding='utf8').isspace():
            try:
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    'indoor_{}'.format(indoorNum),
                    {
                        # 这个 type 是 Consumer 中的一个 Listen method
                        # 这个 group_send 就是向该 group 下所有 Consumers
                        # 发送一个以这个字典作为数据的 event 给 consumers
                        # 中 type 指定的 method, 注意: type 中的 `.` 会被
                        # 替换为 `_`
                        'type': 'indoor_discover_license_plate',
                        # 后面的这些字段将会被 wrap 到 event
                        'message': json.dumps({
                            'pstr': '',
                            # 其他从数据库中获取的数据
                        })
                    })
                # TODO: DCMMC: 下面这一句只是为了 Test!
                parkings = operations.getAvailableParkings()
                if parkings['code'] == 'success' and len(parkings['data']) > 0:
                    # TODO: 暂定 8080 端口
                    p_id = random.sample(parkings['data'], 1)[0]
                    print('模拟进入停车场: ', p_id)
                    re = requests.post('http://' + redis_host +
                                       ':8080/parking_lot_status_update',
                                       json={
                                           'code':
                                           'updateParkingPartial',
                                           'data': [{
                                               'parking_id': p_id,
                                               'used': True,
                                               'addition_info': '模拟进入'
                                           }]
                                       })
                    print('######## post:', re, re.text)
            except Exception as e:
                print(e)
            last_pstr.value = bytes(' ', encoding='utf8')
Exemplo n.º 47
0
from django.db import transaction
import pandas as pd
import numpy as np
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

from packages.models import ItemsList  # , UploadKey, UploadKeyList
from packages.config import PaymentTypeNumber
from packages.flat_file_interface.base_excel_interface import (
    BaseExcelClass,
    BaseExcelInterFaceException,
)
from packages.utils import to_percentage
from packages.config import PaymentTypeNumber

CHANNEL_LAYER = get_channel_layer()
logger = logging.getLogger(__name__)


class PandasInterfaceException(BaseExcelInterFaceException):
    pass


class PandasInterfaceNotImplement(PandasInterfaceException):
    pass


class PandasExcelAPI(BaseExcelClass):
    def __init__(self, user_id):
        """
        Using Pandas libery as working this Class is been
Exemplo n.º 48
0
 def __init__(self, medium_id, spam_sensitivity=None) -> None:
     super().__init__(medium_id, spam_sensitivity)
     self.layer = get_channel_layer(self.channel_layer)
     self.group_send = async_to_sync(self.layer.group_send)
Exemplo n.º 49
0
    def post(self, request, *args, **kwargs):
        requestId = request.data.get('requestId')
        action = request.data.get('action')

        user = self.request.user
        profile = user.userAssociated.all().first()

        try:
            requestId = int(requestId)
        except:
            response = {
                'message': 'Failed',
                'error': 'Invalid requestId.',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        try:
            friend_request = get_object_or_404(FriendRequest, pk=requestId)
        except:
            response = {
                'message': 'Failed',
                'error':
                'You might have either Deleted the request or Rejected the Request.',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        if friend_request.request_status == 'accepted':
            response = {
                'message': 'Failed',
                'error': 'You have already accepted the request.',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        if profile.pk == friend_request.sender.pk:
            if action == 'Delete':
                friend_request.delete()
                response = {
                    'message': 'Request deleted Successfully.',
                    'body': [],
                    'status': HTTP_200_OK
                }
                return Response(response, status=HTTP_200_OK)
            response = {
                'message': 'Failed',
                'error': 'Invalid Request !!',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        blocked_status = check_blocked_status(friend_request.sender, profile)
        if blocked_status:
            response = {
                'message': 'Failed',
                'error': blocked_status[0],
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        if action == 'Accept':
            friend_request.request_status = 'accepted'
            friend_request.save()

            friend_id = []
            if profile.pk == friend_request.sender.pk:
                friend_id.append(friend_request.receiver.pk)

            if profile.pk == friend_request.receiver.pk:
                friend_id.append(friend_request.sender.pk)

            try:
                request_url = CustomFileFormats.NODE_SERVER_DOMAIN + 'user/friendship'
                node_response = requests.post(
                    request_url,
                    headers={
                        'x-auth-server': CustomFileFormats.NODE_ADMIN_TOKEN,
                        'Content-Type': "application/json",
                    },
                    json={
                        'user': profile.pk,
                        'friends': friend_id,
                    })

                node_response.raise_for_status()

            except Exception as e:
                response = {
                    'message': 'Failed',
                    'error': str(e),
                    'status': HTTP_400_BAD_REQUEST
                }
                return Response(response, status=HTTP_400_BAD_REQUEST)

            try:
                # add notification
                notif_content = friend_request.receiver.full_name + " has accepted your friend request."
                ids_assoc = "requestId:" + str(friend_request.pk)
                data = FriendRequestNotifSerializer(friend_request).data
                notify.send(friend_request.sender.user,
                            recipient=friend_request.sender.user,
                            description=notif_content,
                            verb='friend_request_accepted',
                            data=data)
                n = Notification.objects.filter(
                    data={
                        "data": data
                    }, recipient=user).order_by("-timestamp").first()
                d = NotificationsSerializer(n).data
                channel_layer = get_channel_layer()

                print(d, channel_layer.group_send)
                # Trigger message sent to group
                async_to_sync(channel_layer.group_send)(
                    f"{friend_request.sender.user.id}", {
                        "type": "notifi",
                        "event": "friend_request_accepted",
                        "data": str(d)
                    })
                # Notifications.objects.create(
                #                     user_associated=friend_request.sender,
                #                     content=notif_content,
                #                     notification_type='friend_request_accepted',
                #                     associated_ids=ids_assoc
                #                 )
            except:
                pass

            response = {
                'message': 'Success',
                'body': [],
                'status': HTTP_200_OK
            }
            return Response(response, status=HTTP_200_OK)

        elif action == 'Delete' or action == 'Reject':
            friend_request.delete()
            response = {
                'message': 'Success',
                'body': [],
                'status': HTTP_200_OK
            }
            return Response(response, status=HTTP_200_OK)

        response = {
            'message': 'Invalid Action !!',
            'error': 'only Accept, Delete or Reject are allowed.',
            'status': HTTP_400_BAD_REQUEST
        }
        return Response(response, status=HTTP_400_BAD_REQUEST)
async def test_poll_observer_integration():
    client_consumer = URLRouter([url(r'^ws/(?P<subscriber_id>.+)$', ClientConsumer)])

    client = WebsocketCommunicator(client_consumer, '/ws/test-session')
    worker = ApplicationCommunicator(
        WorkerConsumer, {'type': 'channel', 'channel': CHANNEL_WORKER_NOTIFY}
    )
    poller = ApplicationCommunicator(
        PollObserversConsumer, {'type': 'channel', 'channel': CHANNEL_POLL_OBSERVER}
    )

    # Connect client.
    status, _ = await client.connect()
    assert status is True

    # Create an observer.
    @database_sync_to_async
    def create_observer():
        observer = QueryObserver(create_request(views.PollingObservableViewSet))
        items = observer.evaluate()
        assert len(items) == 1

        add_subscriber('test-session', observer.id)
        return observer.id

    observer_id = await create_observer()

    # Ensure that a notification message was sent to the poller.
    channel_layer = get_channel_layer()

    notify = await channel_layer.receive(CHANNEL_POLL_OBSERVER)
    assert notify['type'] == TYPE_POLL_OBSERVER
    assert notify['interval'] == 5
    assert notify['observer'] == observer_id

    # Dispatch notification to poller as our poller uses a dummy queue.
    await poller.send_input(notify)

    # Nothing should be received in the frist 4 seconds.
    async with async_timeout.timeout(4):
        try:
            await channel_layer.receive(CHANNEL_WORKER_NOTIFY)
            assert False
        except CancelledError:
            pass

    # Then after two more seconds we should get a notification.
    notify = await channel_layer.receive(CHANNEL_WORKER_NOTIFY)

    # Dispatch notification to worker.
    await worker.send_input(notify)

    # Ensure another notification message was sent to the poller.
    notify = await channel_layer.receive(CHANNEL_POLL_OBSERVER)
    assert notify['type'] == TYPE_POLL_OBSERVER
    assert notify['interval'] == 5
    assert notify['observer'] == observer_id

    # Ensure client got notified of changes.
    response = await client.receive_json_from()
    assert response['msg'] == 'changed'
    assert response['primary_key'] == 'id'
    assert response['order'] == 0
    assert response['item']['static'].startswith('This is a polling observable:')

    # No other messages should be sent.
    assert await client.receive_nothing() is True

    await client.disconnect()
Exemplo n.º 51
0
def process_csv_file(id, token, csv_file, separator):
    with open(csv_file, 'r') as file:
        if 't' in separator:
            reader = csv.DictReader(file, delimiter='\t', skipinitialspace=True)

        else:
            reader = csv.DictReader(file, delimiter=separator, skipinitialspace=True)

        success_row = 0
        error_row = 0
        current_row = 1

        for row in reader:
            row_number_error = 0
            error_description = ''
            dict_row = dict(row)

            if len(list(reader.fieldnames)) != 9:

                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    token,
                    {
                        'type': 'send_message',
                        'message': {
                            'success_rows': success_row,
                            'error_rows': error_row,
                            'row_number_error': 1,
                            'error_description': 'Es posible que el separador "'+ separator + '" no sea el correcto para el archivo.',
                            'id': id
                        }
                    }
                )

                break


            try:
                invoice_obj, created = Invoice.objects.get_or_create(
                    number=dict_row['Número de factura'],
                    customer_name=dict_row['Nombres del cliente'],
                    customer_last_name=dict_row['Apellidos del cliente'],
                    customer_identification=dict_row['Identificación del cliente'],
                )

                detail_obj = InvoiceDetail.objects.create(
                    invoice=invoice_obj,
                    item_code=dict_row['Codigo del item'],
                    item_description=dict_row['Descripción del ítem'],
                    item_quantity=int(dict_row['Cantidad del ítem']),
                    unit_price=float(dict_row['Precio unitario']),
                    total_price=float(dict_row['Precio unitario']) * int(dict_row['Cantidad del ítem']),
                    discount_rate=float(dict_row['Número de factura']),

                )

                detail_obj.save()


                success_row += 1
            except ValueError as e:

                field_name = str(e).split(': ')[1]
                error_row += 1
                row_number_error = current_row

                row_data = list(dict_row.values())
                row_data_str = ','.join(row_data)

                error_description = 'Error al convertir el campo con valor: ' + field_name + " | " +row_data_str

            except KeyError as e:

                field_name = str(e)
                error_row += 1
                row_number_error = current_row

                row_data = list(reader.fieldnames)
                row_data_str = ', '.join(row_data)

                error_description = 'Error, no se encuentra la columna ' + field_name + "  | " + row_data_str

            except Exception as e:

                error_row += 1
                row_number_error = current_row
                error_description = str(e)

            current_row += 1


            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)(
                token,
                {
                    'type': 'send_message',
                    'message': {
                        'success_rows': success_row,
                        'error_rows': error_row,
                        'row_number_error': row_number_error,
                        'error_description': error_description,
                        'id': id
                    }
                }
            )

    UploadedFile.objects.get(pk=id).delete()
async def test_worker_and_client():
    client_consumer = URLRouter([url(r'^ws/(?P<subscriber_id>.+)$', ClientConsumer)])

    client = WebsocketCommunicator(client_consumer, '/ws/test-session')
    worker = ApplicationCommunicator(
        WorkerConsumer, {'type': 'channel', 'channel': CHANNEL_WORKER_NOTIFY}
    )

    # Connect client.
    status, _ = await client.connect()
    assert status is True

    # Create an observer.
    @database_sync_to_async
    def create_observer():
        observer = QueryObserver(
            create_request(views.PaginatedViewSet, offset=0, limit=10)
        )
        items = observer.evaluate()
        assert not items

        add_subscriber('test-session', observer.id)
        return observer.id

    observer_id = await create_observer()

    # Create a single model instance for the observer model.
    @database_sync_to_async
    def create_model():
        return models.ExampleItem.objects.create(enabled=True, name="hello world").pk

    primary_key = await create_model()

    # Check that ORM signal was generated.
    channel_layer = get_channel_layer()

    notify = await channel_layer.receive(CHANNEL_WORKER_NOTIFY)
    assert notify['type'] == TYPE_ORM_NOTIFY_TABLE
    assert notify['kind'] == ORM_NOTIFY_KIND_CREATE
    assert notify['primary_key'] == str(primary_key)

    # Propagate notification to worker.
    await worker.send_input(notify)

    # Check that observer evaluation was requested.
    notify = await channel_layer.receive(CHANNEL_WORKER_NOTIFY)
    assert notify['type'] == TYPE_EVALUATE_OBSERVER
    assert notify['observer'] == observer_id

    # Propagate notification to worker.
    await worker.send_input(notify)

    response = await client.receive_json_from()
    assert response['msg'] == 'added'
    assert response['primary_key'] == 'id'
    assert response['order'] == 0
    assert response['item'] == {'id': 1, 'enabled': True, 'name': 'hello world'}

    # No other messages should be sent.
    assert await client.receive_nothing() is True

    await client.disconnect()

    # Run observer again and it should remove itself because there are no more subscribers.
    await worker.send_input({'type': TYPE_EVALUATE_OBSERVER, 'observer': observer_id})
    assert await worker.receive_nothing() is True

    # Ensure that subscriber and observer have been removed.
    @database_sync_to_async
    def check_subscribers():
        assert observer_models.Subscriber.objects.all().count() == 0
        assert observer_models.Observer.objects.all().count() == 0

    await check_subscribers()
Exemplo n.º 53
0
 def get_c_layer(name="default"):
     return get_channel_layer(alias=name)
Exemplo n.º 54
0
 def __init__(self, mails):
     self.mails = mails
     super().__init__()
     self.channel_layer = get_channel_layer()
 def __init__(self):
     self.all_games = {}
     self.layer = get_channel_layer()
Exemplo n.º 56
0
    def __init__(self, instance, stream=None):
        super(TitanBotLoggingHandler, self).__init__()

        self.instance = instance
        self.channel_layer = get_channel_layer()
        self.group_name = 'titan_log'
    def subscribe(self, session_id, dependencies=None):
        """Initialize observer and register subscriber.

        :param session_id: Subscriber's session identifier
        :param dependencies: List of ORM to register as dependencies for orm_notify
        """
        try:
            change_detection = self._meta.change_detection
            if change_detection not in [
                Options.CHANGE_DETECTION_PUSH,
                Options.CHANGE_DETECTION_POLL,
            ]:
                raise NotImplementedError(
                    "Change detection mechanism '{}' not implemented.".format(
                        change_detection
                    )
                )

            viewset_results = self._viewset_results()

            poll_interval = (
                self._meta.poll_interval
                if change_detection == Options.CHANGE_DETECTION_POLL
                else None
            )

            # Subscribe to observer in a single query. First, create an
            # observer, then create a subscriber, and finally subscribe to
            # the observer. If already subscribed, ignore the conflict.
            for retry in range(MAX_INTEGRITY_ERROR_RETRIES):
                is_subscribed = False
                cursor = connection.cursor()
                try:
                    cursor.execute(
                        """
                        WITH inserted_observer AS (
                            INSERT into {observer_table} ("id", "request", "poll_interval")
                            VALUES (%(observer_id)s, %(request)s, %(poll_interval)s)
                            ON CONFLICT DO NOTHING
                        ), inserted_subscriber AS (
                            INSERT into {subscriber_table} ("session_id", "created")
                            VALUES (%(subscriber_id)s, NOW())
                            ON CONFLICT DO NOTHING
                        )
                        INSERT INTO {observer_subscribers_table} ("observer_id", "subscriber_id")
                        VALUES (%(observer_id)s, %(subscriber_id)s)
                        """.format(
                            observer_table=models.Observer._meta.db_table,
                            subscriber_table=models.Subscriber._meta.db_table,
                            observer_subscribers_table=models.Observer.subscribers.through._meta.db_table,
                        ),
                        params={
                            'observer_id': self.id,
                            'request': pickle.dumps(self._request),
                            'poll_interval': poll_interval,
                            'subscriber_id': session_id,
                        },
                    )
                    is_subscribed = True
                except IntegrityError as err:
                    msg = str(err)
                    if (
                        'Key (observer_id, subscriber_id)' in msg
                        and 'already exists' in msg
                    ):
                        # Subscriber already subscribed, we're good.
                        is_subscribed = True
                    elif (
                        'Key (observer_id)' in msg or 'Key (subscriber_id)' in msg
                    ) and 'not present in table' in msg:
                        # Could not subscribe because observer, subscriber or
                        # both are missing, retry.
                        if retry == MAX_INTEGRITY_ERROR_RETRIES - 1:
                            raise
                    else:
                        raise
                finally:
                    cursor.close()

                if is_subscribed:
                    break

            # Determine who should notify us based on the configured change
            # detection mechanism.
            if change_detection == Options.CHANGE_DETECTION_PUSH:
                if dependencies:
                    tables = [model._meta.db_table for model in dependencies]
                else:
                    tables = [self._viewset.get_queryset().model._meta.db_table]

                # Register table dependencies for push observables.
                for table in tables:
                    try:
                        models.Dependency.objects.get_or_create(
                            observer_id=self.id, table=table
                        )
                    except models.Observer.DoesNotExist:
                        # The observer was removed before dependency tables
                        # were created.
                        return viewset_results

            elif self._meta.change_detection == Options.CHANGE_DETECTION_POLL:
                # Register poller.
                async_to_sync(get_channel_layer().send)(
                    CHANNEL_MAIN,
                    {
                        'type': TYPE_POLL,
                        'observer': self.id,
                        'interval': self._meta.poll_interval,
                    },
                )

            self._evaluate(viewset_results)

        except Exception:
            logger.exception(
                "Error while subscribing to observer ({})".format(
                    self._get_logging_id()
                ),
                extra=self._get_logging_extra(),
            )

        return viewset_results
Exemplo n.º 58
0
    def post(self, request, *args, **kwargs):
        admin_token = request.data.get('admin_token')
        userID = request.data.get('userID')

        try:
            profile = get_object_or_404(Profile, pk=int(userID))
            user = profile.user

            if profile is None:
                raise Http404
        except:
            response = {
                'message': 'Failed',
                'error': 'Invalid userID',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        if admin_token != CustomFileFormats.DJANGO_ADMIN_TOKEN:
            response = {
                'message': 'Invalid Request!!',
                'error': 'send correct admin token.',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        status_id = request.data.get('statusID')
        try:
            status_id = int(status_id)
            status = get_object_or_404(Status, pk=status_id)
        except:
            response = {
                'message': 'Invalid Request !!',
                'error': 'Invalid statusId',
                'status': HTTP_400_BAD_REQUEST
            }
            return Response(response, status=HTTP_400_BAD_REQUEST)

        user_joined = Groups.objects.filter(participant=profile).filter(
            status_id=status).first()
        if user_joined:
            user_joined.joined = not user_joined.joined
            user_joined.save()
            participants = Groups.objects.filter(
                status_id=status_id, joined=True).exclude(
                    participant=profile).values_list("participant__user")
            data = {}
            #participants_profile = Groups.objects.filter(status_id=status).exclude(participant=profile).values_list("participant")
            participants_obj = User.objects.filter(id__in=participants)
            if user_joined.joined == True:
                text = 'A user has joined your group.'
                associated_ids = 'userID:' + str(
                    profile.pk) + ' ' + 'groupID:' + str(status.pk)

                print(participants_obj)

                #participants_profile_obj=Profile.objects.filter(id__in=participants_profile)
                data['group'] = StatusSerializer(status).data
                data["user"] = UserSerializer(profile).data
                print(data)
                notify.send(user,
                            recipient=list(participants_obj),
                            description=text,
                            verb='group_joined',
                            data=data)
            for user in participants_obj:
                n = Notification.objects.filter(
                    data={
                        "data": data
                    }, recipient=user).order_by("-timestamp").first()
                d = NotificationsSerializer(n).data
                try:
                    channel_layer = get_channel_layer()

                    print(d, channel_layer.group_send)
                    # Trigger message sent to group

                    async_to_sync(channel_layer.group_send)(f"{user.id}", {
                        "type": "notifi",
                        "event": "group_joined",
                        "data": str(d)
                    })
                except Exception as e:
                    print(str(e))
                #Notifications.objects.create(user_associated=profile, content=text, associated_ids=associated_ids, notification_type='group_joined')

        else:
            user_joined = Groups.objects.create(participant=profile,
                                                status_id=status)
            text = 'A user has joined your group.'
            associated_ids = 'userID:' + str(
                profile.pk) + ' ' + 'groupID:' + str(status.pk)
            participants = Groups.objects.filter(status_id=status).exclude(
                participant=profile).values_list("participant__user")

            participants_obj = User.objects.filter(id__in=participants)
            data = {}
            #participants_profile_obj=Profile.objects.filter(id__in=participants_profile)
            data['group'] = StatusSerializer(status).data
            data["user"] = UserSerializer(profile).data
            print(data)
            notify.send(user,
                        recipient=list(participants_obj),
                        description=text,
                        verb='group_joined',
                        data=data)
            for user in participants_obj:
                print(data)
                n = Notification.objects.filter(
                    data={
                        "data": data
                    }, recipient=user).order_by("-timestamp").first()
                print(n)
                d = NotificationsSerializer(n).data
                try:
                    channel_layer = get_channel_layer()

                    async_to_sync(channel_layer.group_send)(f"{user.id}", {
                        "type": "notifi",
                        "event": "group_joined",
                        "data": str(d)
                    })
                except Exception as e:
                    print(str(e))
            #Notifications.objects.create(user_associated=profile, content=text, associated_ids=associated_ids, notification_type='group_joined')

        response = {
            'message': 'success',
            'body': {
                'joined_status': user_joined.joined
            },
            'status': HTTP_200_OK
        }
        return Response(response, status=HTTP_200_OK)
Exemplo n.º 59
0
 def send_room_id(self, message):
     channel_layer = get_channel_layer()
     async_to_sync(channel_layer.group_send)(self.group_name, {
         'type': 'room_id',
         'room_id': str(message)
     })
Exemplo n.º 60
0
 def __init__(self) -> None:
     self.channel_layer = get_channel_layer()