2018-08-14 20:12:52 -04:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""
|
|
|
|
Consumers available for the /quest websocket.
|
|
|
|
"""
|
2018-08-15 17:41:51 -04:00
|
|
|
import json
|
|
|
|
|
2018-08-14 20:12:52 -04:00
|
|
|
from channels.generic.websocket import WebsocketConsumer
|
|
|
|
|
2018-08-15 17:41:51 -04:00
|
|
|
from .events import events
|
|
|
|
|
2018-08-14 20:12:52 -04:00
|
|
|
class QuestConsumer(WebsocketConsumer):
|
|
|
|
"""
|
|
|
|
The main consumer for /quest websockets.
|
|
|
|
"""
|
2018-08-15 17:41:51 -04:00
|
|
|
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)
|
|
|
|
|
2018-08-14 20:12:52 -04:00
|
|
|
def connect(self):
|
|
|
|
self.accept()
|
2018-08-15 17:41:51 -04:00
|
|
|
|
|
|
|
def disconnect(self, close_code):
|
2018-08-14 20:12:52 -04:00
|
|
|
pass
|
|
|
|
|
|
|
|
def receive(self, text_data):
|
2018-08-15 17:41:51 -04:00
|
|
|
"""
|
|
|
|
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'))
|
|
|
|
|
2018-08-24 17:45:18 -04:00
|
|
|
def send(self, event, data={}):
|
2018-08-15 17:41:51 -04:00
|
|
|
"""
|
|
|
|
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)
|