Beispiel #1
0
    def receive(self, text_data):
        global max_id
        obj = json.loads(text_data)
        player = players[self.scope["session"]["player"]]
        if obj["action"] == "move":
            new_x = player.x + obj["deltaX"]
            new_y = player.y + obj["deltaY"]
            player.x = max(min(new_x, map_width / 2 - char_size / 2),
                           -map_width / 2 + char_size / 2)
            player.y = max(min(new_y, map_height / 2 - char_size / 2),
                           -map_height / 2 + char_size / 2)

        elif obj["action"] == "fire":
            target = get_target(player, obj["rotation"])
            if target is not None:
                if target.is_player:
                    player.score += player_kill
                    database_sync_to_async(
                        updateScore(player.score,
                                    self.scope["session"]["name"]))
                    target.reset()
                else:
                    player.score -= bot_kill
                    database_sync_to_async(
                        updateScore(player.score,
                                    self.scope["session"]["name"]))
                    del bots[target.uid]
                    new_c = Character(map_width, map_height, rand, max_id,
                                      speed, False)
                    bots[max_id] = new_c
                    max_id += 1
Beispiel #2
0
    async def poll_specifications(
            self) -> Tuple['SandboxSpecs', 'ContainerSpecs']:
        """Poll the specifications of the sandbox's host and its containers.

        The sandbox must be enabled, `SandboxDisabledError` will be raised
        otherwise."""
        if not self.enabled:
            raise SandboxDisabledError(
                "Cannot poll specifications of a disabled sandbox")

        async with ASandbox(self.url) as asandbox:
            raw_specs, libs = await asyncio.gather(asandbox.specifications(),
                                                   asandbox.libraries())

        host, container = raw_specs["host"], raw_specs["container"]

        aw1 = database_sync_to_async(
            SandboxSpecs.objects.filter(sandbox=self).update)(
                polled=True,
                sandbox_version=host["sandbox_version"],
                docker_version=host["docker_version"],
                cpu_core=host["cpu"]["core"],
                cpu_logical=host["cpu"]["logical"],
                cpu_freq_min=host["cpu"]["freq_min"],
                cpu_freq_max=host["cpu"]["freq_max"],
                memory_ram=host["memory"]["ram"],
                memory_swap=host["memory"]["swap"],
                memory_storage=host["memory"]["storage"])
        aw2 = database_sync_to_async(
            ContainerSpecs.objects.filter(sandbox=self).update)(
                polled=True,
                working_dir_device=container["working_dir_device"],
                count=container["count"],
                process=container["process"],
                cpu_count=container["cpu"]["count"],
                cpu_period=container["cpu"]["period"],
                cpu_shares=container["cpu"]["shares"],
                cpu_quota=container["cpu"]["quota"],
                memory_ram=container["memory"]["ram"],
                memory_swap=container["memory"]["swap"],
                memory_storage=container["memory"]["storage"],
                writing_io=container["io"]["read_iops"],
                writing_bytes=container["io"]["read_bps"],
                reading_io=container["io"]["write_iops"],
                reading_bytes=container["io"]["write_bps"],
                libraries=libs["libraries"],
                bin=libs["bin"])
        await asyncio.gather(aw1, aw2)

        host = await database_sync_to_async(SandboxSpecs.objects.get
                                            )(sandbox=self)
        container = await database_sync_to_async(ContainerSpecs.objects.get
                                                 )(sandbox=self)

        return host, container
Beispiel #3
0
    def __call__(self, scope):
        database_sync_to_async(close_old_connections)()
        if scope['headers'][0][0] == 'pytest':
            return self.inner(dict(scope, user=scope['headers'][0][1]))
        token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]
        #  todo add token verification
        decoded_data = jwt_decode(token,
                                  settings.SECRET_KEY,
                                  algorithms=["HS256"])
        pk = decoded_data["user_id"]

        return self.inner(dict(scope, user=pk))
Beispiel #4
0
 async def receive_json(self, data):
     # Incomming messages:
     # {type: FOO, data: {...}}
     type = data.get("type")
     if not type:
         return
     if type == "ADD_PATH":
         # {type: ADD_PATH, data: {points: [], color: foo, ...}}
         path_data = data.get("data")
         add_path = database_sync_to_async(Board.add_path)
         new_version = await add_path(self.board_id, path_data)
         # broadcast to other clients
         await self.channel_layer.group_send(
             self.group_name,
             {
                 "type": "broadcast_path",
                 "message": {
                     "type": "REMOTE_CHANGE",
                     "data": {
                         "path": path_data,
                         "version": new_version,
                     },
                     "from": self.channel_name,
                 },
             },
         )
         await self.send_json({
             "type": "ACK",
             "data": {
                 "version": new_version
             }
         })
     if type == "REQ_INIT":
         # await self.send_json({})
         await self.init_data()
Beispiel #5
0
    async def auth_by_api_key(self, api_key: str):
        # Already authenticated
        if self._authed:
            return

        if not api_key:
            await self.send_json(
                {
                    "code": 400,
                    "detail": _("No api key provided")
                }, close=True)

        async_is_valid = database_sync_to_async(APIKey.objects.is_valid)
        result = await async_is_valid(api_key)
        if result:
            await self.send_json({"code": 200, "detail": _("ok")})
            self._authed = True
        else:
            await self.send_json(
                {
                    "code": 400,
                    "detail": _("Invalid api key")
                },
                close=True,
            )
Beispiel #6
0
    async def site_updated(self, event: Dict[str, Any]) -> None:  # pylint: disable=unused-argument
        if self.site is not None:
            await database_sync_to_async(self.site.refresh_from_db)()

            if not database_sync_to_async(self.site.can_be_edited_by)(
                    self.scope["user"]):
                await self.close()
Beispiel #7
0
 async def connect(self):
     print(self.scope["user"])
     # await self.addChannelToGroupsOnConnect('0706a3c0da537a63bdf372c7c32176d6c2c1ea1c')
     grouplist = database_sync_to_async(
         self.createGroupList)('0706a3c0da537a63bdf372c7c32176d6c2c1ea1c')
     print(grouplist)
     await self.channel_layer.group_add("mamad", self.channel_name)
     await self.accept()
Beispiel #8
0
    async def site_updated(self, event: Dict[str, Any]) -> None:  # pylint: disable=unused-argument
        for site_id in self.site_ids:
            site = Site.objects.get(id=site_id)

            await database_sync_to_async(site.refresh_from_db)()

            if not database_sync_to_async(site.can_be_edited_by)(self.scope["user"]):
                await self.close()
Beispiel #9
0
 def __call__(self, scope):
     user = None
     database_sync_to_async(close_old_connections)()
     parsed_qs = parse_qs(scope["query_string"].decode("utf8"))
     if parsed_qs:
         token = parsed_qs["token"][0]
         try:
             UntypedToken(token)
         except (InvalidToken, TokenError) as e:
             return self.inner(dict(scope, user=user))
         else:
             decoded_data = jwt_decode(token,
                                       settings.SECRET_KEY,
                                       algorithms=["HS256"])
             user = database_sync_to_async(
                 User.objects.get)(id=decoded_data["user_id"])
     return self.inner(dict(scope, user=user))
Beispiel #10
0
    def __call__(self, scope):
        database_sync_to_async(close_old_connections)()
        if scope['headers'][0][0] == 'pytest':
            return self.inner(dict(scope, user=scope['headers'][0][1]))
        token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]

        try:
            UntypedToken(token)
        except (InvalidToken, TokenError):
            return None
        else:
            decoded_data = jwt_decode(token,
                                      settings.SECRET_KEY,
                                      algorithms=["HS256"])

            pk = decoded_data["user_id"]

        return self.inner(dict(scope, user=pk))
Beispiel #11
0
    async def get_daq(pk=None, name=None, tags=None):
        # TODO: add ability to choose wanted daq

        # for now, hardcoded
        try:
            daq = database_sync_to_async(DAQServer.objects.get(pk=1))
        except ObjectDoesNotExist:
            daq = None

        return daq
Beispiel #12
0
    async def auth(self, token: str):
        # Already authenticated
        if self.user.is_authenticated:
            return

        async_user_get = database_sync_to_async(User.objects.get)
        try:
            user = await async_user_get(auth_token__key=token)
            self.user = user
            await self.send_json({"code": 200, "detail": "认证成功"})
        except User.DoesNotExist:
            await self.send_json({"code": 400, "detail": "认证失败"}, close=True)
Beispiel #13
0
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)

        message_body = text_data_json['message_body']

        user_id = self.scope['user'].id

        creator = {
            'id': self.member['id'],
            'first_name': self.member['first_name'],
            'last_name': self.member['last_name'],
            'preferred_name': self.member['preferred_name']
        }

        if self.member['id'] == user_id:
            create_message = database_sync_to_async(
                lambda: Message.objects.create(creator_id=user_id,
                                               message_body=message_body,
                                               room_id=self.room_id))
            messageObject = await create_message()
            save_message = database_sync_to_async(lambda: messageObject.save())
            await save_message()

            await self.channel_layer.group_send(
                self.room_group_name, {
                    'type':
                    'chat_message',
                    'id':
                    messageObject.id,
                    'message_body':
                    message_body,
                    'creator':
                    creator,
                    'datetime_created':
                    messageObject.datetime_created.strftime(
                        "%Y-%m-%dT%H:%M:%S.%fZ")
                })
        else:
            await self.channel_layer.group_discard(self.room_group_name,
                                                   self.channel_name)
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

        # note: アクセス権がある room つくって permission 確認とかいれたい
        self.user = self.scope.get('user')
        self.chat_room = database_sync_to_async(ChatRoom.objects.get)(room_id=self.room_name)
Beispiel #15
0
    async def connect(self):
        self.room_id = int(self.scope['url_route']['kwargs']['room_id'])
        self.room_group_name = 'chat_%s' % str(self.room_id)

        try:
            user_id = self.scope['user'].id
            get_user = database_sync_to_async(lambda: Room.objects.get(
                id=self.room_id).members.get(id=user_id))
            user = await get_user()
            self.member = user.__dict__

            await self.channel_layer.group_add(self.room_group_name,
                                               self.channel_name)
            await self.accept()
        except ObjectDoesNotExist:
            pass
Beispiel #16
0
 async def receive_like(self, text_data_json: dict) -> dict:
     message_id = text_data_json["message_id"]
     is_liked = text_data_json["like"]
     get_message = database_sync_to_async(
         lambda: Message.objects.get(id=message_id))
     message: Message = await get_message()
     if is_liked:
         await database_sync_to_async(
             lambda: message.liked_users.add(self.scope["user"].id))()
     else:
         await database_sync_to_async(
             lambda: message.liked_users.remove(self.scope["user"].id))()
     return {
         "type": "send_like",
         "message_id": message_id,
         "like": is_liked,
         "user_id": self.scope["user"].id,
     }
Beispiel #17
0
    async def auth_by_auth_token(self, auth_token: str):
        """Authenticate by auth token."""
        # Already authenticated
        if self._authed:
            return

        async_token_get = database_sync_to_async(Token.objects.get)

        try:
            await async_token_get(key=auth_token)
        except Token.DoesNotExist:
            await self.send_json({
                "code": 401,
                "detail": _("Invalid auth token.")
            })
            return

        await self.send_json({"code": 200, "detail": _("Authenticated.")})
        self._authed = True
Beispiel #18
0
    async def receive_message(self, text_data_json: dict) -> dict:
        message_body = text_data_json["message_body"]
        previous_message_id = text_data_json["previous_message_id"]
        tagged_users = text_data_json["tagged_users"]
        creator = {
            "id": self.member["id"],
            "first_name": self.member["first_name"],
            "last_name": self.member["last_name"],
            "preferred_name": self.member["preferred_name"],
        }
        previous_message = None
        if previous_message_id is not None:
            get_previous_message = database_sync_to_async(
                lambda: Message.objects.get(id=previous_message_id))
            previous_message_result = await get_previous_message()
            get_previous_message_tagged_users = database_sync_to_async(
                lambda: previous_message_result.tagged_users.values_list(
                    "id", flat=True))
            tagged_users_previous = await get_previous_message_tagged_users()
            previous_message = {
                "id":
                previous_message_id,
                "message_body":
                previous_message_result.content,
                "creator_id":
                previous_message_result.creator_id,
                "datetime_created":
                previous_message_result.datetime_created.strftime(
                    "%Y-%m-%dT%H:%M:%S.%fZ"),
                "tagged_users":
                list(tagged_users_previous),
            }

        create_message = database_sync_to_async(lambda: Message.objects.create(
            creator_id=self.scope["user"].id,
            content=message_body,
            room_id=self.room_id,
            previous_message_id=previous_message_id,
        ))

        message_object: Message = await create_message()
        save_message = database_sync_to_async(lambda: message_object.save())
        await save_message()
        add_tagged_users = database_sync_to_async(
            lambda: message_object.tagged_users.add(*tagged_users))
        await add_tagged_users()
        return {
            "type":
            "send_message",
            "id":
            message_object.id,
            "message_body":
            message_body,
            "creator":
            creator,
            "previous_message":
            previous_message,
            "datetime_created":
            message_object.datetime_created.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
            "tagged_users":
            tagged_users,
        }
Beispiel #19
0
 async def disconnect(self, code):
     database_sync_to_async(logout)(self.scope)
def ensure_async(method: typing.Callable):
    if asyncio.iscoroutinefunction(method):
        return method
    return database_sync_to_async(method)
Beispiel #21
0
            external_source_video_id=external_source_video_id,
            external_source_channel_id=external_source_channel_id,
            video=video_record,
        )
        was_synced = True
        video_record = media_services.mark_video_as_viewable_and_synced(
            video=video_record)
        shutil.rmtree(output_dir)
        logger.info(
            'Done syncing external video %s to Channel %s of user %s...',
            external_source_video_id,
            channel_id,
            user.id,
        )
    else:
        was_synced = False
        video_record = synced_video.video
        logger.info(
            'Already synced external video %s to Channel %s of user %s...',
            external_source_video_id,
            channel_id,
            user.id,
        )
    return was_synced, video_record


get_channel_syncs_which_are_syncing_async = database_sync_to_async(
    get_channel_syncs_which_are_syncing, thread_sensitive=True)
get_channel_syncs_async = database_sync_to_async(get_channel_syncs,
                                                 thread_sensitive=True)
from base64 import b64encode

import pytest
from channels.db import database_sync_to_async
from channels.layers import get_channel_layer
from channels.testing import WebsocketCommunicator
from dateutil.relativedelta import relativedelta
from django.utils import timezone
from rest_framework.authtoken.models import Token

from karrot.subscriptions.consumers import WebsocketConsumer, TokenAuthMiddleware, get_auth_token_from_subprotocols
from karrot.subscriptions.models import ChannelSubscription
from karrot.subscriptions.routing import AllowedHostsAndFileOriginValidator
from karrot.users.factories import UserFactory

AsyncUserFactory = database_sync_to_async(UserFactory)

# These async fixtures only work for python 3.6+ (needs async yield)
#
# @pytest.fixture
# async def communicator(request):
#     communicator = WebsocketCommunicator(SyncWebsocketConsumer, '/')
#     yield communicator
#     await communicator.disconnect()
#
# @pytest.fixture
# async def user():
#     yield await AsyncUserFactory()
#
#
# @pytest.fixture
Beispiel #23
0
 def send_to_channel(self, name, event, datas={}, _from=None):
     datas.update({'type': 'send.event', 'dispatch': event, 'uid': str(self.uid)})
     if _from: datas['from'] = _from
     logger.info('send room: %s, event: %s, datas %s' % (name, event, str(datas)), extra={'user': self.user})
     database_sync_to_async(self.historize_channel)(name, event, datas)
     async_to_sync(self.channel_layer.group_send)(name, datas)
Beispiel #24
0
 def connect(self):
     self.user = self.get_user_obj(self.scope)
     database_sync_to_async(self.save_user_channel)()
     self.accept()
Beispiel #25
0
 def leave_channel(self, name):
     if name in self.channels_list:
         logger.info('leave room: %s' % name, extra={'user': self.user})
         database_sync_to_async(self.disconnect_channel)(_type, name, self.id)
         async_to_sync(self.channel_layer.group_discard)(name, self.channel_name)
Beispiel #26
0
 def join_channel(self, _type, name):
     if name not in self.channels_list:
         logger.info('join channel: %s' % name, extra={'user': self.user})
         database_sync_to_async(self.connect_channel)(_type, name, self.id)
         async_to_sync(self.channel_layer.group_add)(name, self.channel_name)