<filename>server/ws/consumers.py<gh_stars>0
from channels.generic.websocket import AsyncWebsocketConsumer
import json

from api0.models import AgentToken, Agent, Space
from api0.models import Frame as ModelFrame
from zentropi import Frame, Kind


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.token = self.scope['url_route']['kwargs'].get('token')
        if self.token:
            self.agent = AgentToken.objects.get(key=self.token).agent
        else:
            self.agent = Agent.objects.get(name=self.scope['user'])
        self.spaces = self.agent.spaces.all()
        for space in self.spaces:
            await self.channel_layer.group_add(
                space.name,
                self.channel_name
            )
        await self.accept()

    async def disconnect(self, close_code):
        for space in self.spaces:
            await self.channel_layer.group_discard(
                space.name,
                self.channel_name
            )

    async def receive(self, text_data):
        frame_as_dict = json.loads(text_data)
        frame = Frame.from_dict(frame_as_dict)
        defined_space = frame.meta.get('space', '')
        if defined_space:
            try:
                Space.objects.get(name=defined_space)
            except Exception as e:
                await self.send(json.dumps(
                    Frame(kind=Kind.event, name=f'Error: unknown/un-joined space: {defined_space}').to_dict()))
                return
        if defined_space:
            spaces = defined_space
        else:
            spaces = ','.join([s.name for s in self.agent.spaces.all()])
        ModelFrame.objects.create(owner=self.agent.owner,
                                  agent=self.agent,
                                  spaces=spaces,
                                  **frame_as_dict)
        for space in spaces.split(','):
            meta = dict(frame.meta)
            meta.update({'space': space})
            meta.update({'source': self.agent.name})
            await self.channel_layer.group_send(
                space,
                {
                    'type': 'frame_broadcast',
                    'id': frame.id,
                    'kind': frame.kind,
                    'name': frame.name,
                    'data': frame.data,
                    'meta': meta,
                }
            )

    async def frame_broadcast(self, event):
        print(event)
        await self.send(text_data=json.dumps({
            'kind': event['kind'],
            'id': event['id'],
            'name': event['name'],
            'data': event['data'],
            'meta': event['meta'],
        }))

<filename>server/ws/consumers.py<gh_stars>0
from channels.generic.websocket import AsyncWebsocketConsumer
import json

from api0.models import AgentToken, Agent, Space
from api0.models import Frame as ModelFrame
from zentropi import Frame, Kind


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.token = self.scope['url_route']['kwargs'].get('token')
        if self.token:
            self.agent = AgentToken.objects.get(key=self.token).agent
        else:
            self.agent = Agent.objects.get(name=self.scope['user'])
        self.spaces = self.agent.spaces.all()
        for space in self.spaces:
            await self.channel_layer.group_add(
                space.name,
                self.channel_name
            )
        await self.accept()

    async def disconnect(self, close_code):
        for space in self.spaces:
            await self.channel_layer.group_discard(
                space.name,
                self.channel_name
            )

    async def receive(self, text_data):
        frame_as_dict = json.loads(text_data)
        frame = Frame.from_dict(frame_as_dict)
        defined_space = frame.meta.get('space', '')
        if defined_space:
            try:
                Space.objects.get(name=defined_space)
            except Exception as e:
                await self.send(json.dumps(
                    Frame(kind=Kind.event, name=f'Error: unknown/un-joined space: {defined_space}').to_dict()))
                return
        if defined_space:
            spaces = defined_space
        else:
            spaces = ','.join([s.name for s in self.agent.spaces.all()])
        ModelFrame.objects.create(owner=self.agent.owner,
                                  agent=self.agent,
                                  spaces=spaces,
                                  **frame_as_dict)
        for space in spaces.split(','):
            meta = dict(frame.meta)
            meta.update({'space': space})
            meta.update({'source': self.agent.name})
            await self.channel_layer.group_send(
                space,
                {
                    'type': 'frame_broadcast',
                    'id': frame.id,
                    'kind': frame.kind,
                    'name': frame.name,
                    'data': frame.data,
                    'meta': meta,
                }
            )

    async def frame_broadcast(self, event):
        print(event)
        await self.send(text_data=json.dumps({
            'kind': event['kind'],
            'id': event['id'],
            'name': event['name'],
            'data': event['data'],
            'meta': event['meta'],
        }))
