39 lines
1.5 KiB
Python
39 lines
1.5 KiB
Python
import json
|
|
import redis
|
|
from django.conf import settings
|
|
from channels.generic.websocket import WebsocketConsumer
|
|
from asgiref.sync import async_to_sync
|
|
from waiting_room.tasks import calculate_min_distance, run_tasks_from_queue, render_location_in_the_queue, notify_of_new_position
|
|
|
|
class MyConsumer(WebsocketConsumer):
|
|
|
|
redis_conn = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0)
|
|
|
|
def connect(self):
|
|
self.room_group_name = self.scope["url_route"]["kwargs"]["room_name"]
|
|
async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name)
|
|
self.accept()
|
|
notify_of_new_position()
|
|
|
|
def disconnect(self, close_code):
|
|
async_to_sync(self.channel_layer.group_discard)(self.room_group_name, self.channel_name)
|
|
self.close()
|
|
|
|
def receive(self, text_data):
|
|
json_data = json.loads(text_data)
|
|
# Run task
|
|
if json_data['task'] == 'calculate':
|
|
# Check if the new task is already in the queue
|
|
if self.redis_conn.lrange('enqueue', 0, -1).count(self.room_group_name.encode()) == 0:
|
|
# Add the task to the queue
|
|
self.redis_conn.rpush('enqueue', self.room_group_name)
|
|
notify_of_new_position()
|
|
# Send accurate location in the queue
|
|
run_tasks_from_queue()
|
|
|
|
def channel_message(self, event):
|
|
message = event['message']
|
|
|
|
# Send message to WebSocket
|
|
self.send(text_data=str(message))
|