2024-11-05 11:46:00 +01:00
|
|
|
import json
|
2024-11-07 16:20:51 +01:00
|
|
|
import redis
|
|
|
|
from django.conf import settings
|
2024-11-05 11:46:00 +01:00
|
|
|
from channels.generic.websocket import WebsocketConsumer
|
|
|
|
from asgiref.sync import async_to_sync
|
2024-11-07 16:20:51 +01:00
|
|
|
from waiting_room.tasks import calculate_min_distance, run_tasks_from_queue, render_location_in_the_queue, notify_of_new_position
|
2024-11-05 11:46:00 +01:00
|
|
|
|
|
|
|
class MyConsumer(WebsocketConsumer):
|
|
|
|
|
2024-11-07 16:20:51 +01:00
|
|
|
redis_conn = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0)
|
|
|
|
|
2024-11-05 11:46:00 +01:00
|
|
|
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()
|
2024-11-07 16:20:51 +01:00
|
|
|
notify_of_new_position()
|
2024-11-05 11:46:00 +01:00
|
|
|
|
|
|
|
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):
|
2024-11-05 16:52:47 +01:00
|
|
|
json_data = json.loads(text_data)
|
|
|
|
# Run task
|
|
|
|
if json_data['task'] == 'calculate':
|
2024-11-07 16:20:51 +01:00
|
|
|
# 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()
|
2024-11-05 11:46:00 +01:00
|
|
|
|
|
|
|
def channel_message(self, event):
|
|
|
|
message = event['message']
|
|
|
|
|
|
|
|
# Send message to WebSocket
|
|
|
|
self.send(text_data=str(message))
|