#!/usr/bin/env python3 """ Consumers available for the /quest websocket. """ import json from channels.generic.websocket import WebsocketConsumer from .events import events class QuestConsumer(WebsocketConsumer): """ The main consumer for /quest websockets. """ def __init__(self, *args, **kwargs): """ Overriden method. Adds dictionary of events and functions to be used by self.receive(). """ self.events = events super().__init__(*args, **kwargs) def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): """ Parses the received data as JSON and dispatches the appropirate event handler. """ try: data = json.loads(text_data) except json.JSONDecodeError: return event = data.get('event') if not event or event not in self.events.keys(): return self.events[event](self, data.get('data')) def send(self, event, data): """ Overridden method. If a dictionary is provided, it is converted to JSON before sending it. If a string is provided, it is sent out directly. """ data = json.dumps({'event': event, 'data': data}) super().send(text_data=data)