add notify_sessions module
This commit is contained in:
parent
fc05c7c1d8
commit
434dfe807e
7 changed files with 189 additions and 10 deletions
10
core/notify_sessions/admin.py
Normal file
10
core/notify_sessions/admin.py
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from notify_sessions.models import SystemEvent
|
||||||
|
|
||||||
|
|
||||||
|
class SystemEventAdmin(admin.ModelAdmin):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
admin.site.register(SystemEvent, SystemEventAdmin)
|
21
core/notify_sessions/api_v2.py
Normal file
21
core/notify_sessions/api_v2.py
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
from rest_framework import routers, viewsets, serializers
|
||||||
|
|
||||||
|
from tickets.models import IssueThread
|
||||||
|
from notify_sessions.models import SystemEvent
|
||||||
|
|
||||||
|
|
||||||
|
class SystemEventSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = SystemEvent
|
||||||
|
fields = '__all__'
|
||||||
|
|
||||||
|
|
||||||
|
class SystemEventViewSet(viewsets.ModelViewSet):
|
||||||
|
serializer_class = SystemEventSerializer
|
||||||
|
queryset = SystemEvent.objects.all()
|
||||||
|
|
||||||
|
|
||||||
|
router = routers.SimpleRouter()
|
||||||
|
router.register(r'systemevents', SystemEventViewSet, basename='systemevents')
|
||||||
|
|
||||||
|
urlpatterns = router.urls
|
|
@ -1,3 +1,4 @@
|
||||||
|
import logging
|
||||||
from json.decoder import JSONDecodeError
|
from json.decoder import JSONDecodeError
|
||||||
from json import loads as json_loads
|
from json import loads as json_loads
|
||||||
from json import dumps as json_dumps
|
from json import dumps as json_dumps
|
||||||
|
@ -6,18 +7,16 @@ from channels.generic.websocket import AsyncWebsocketConsumer
|
||||||
|
|
||||||
|
|
||||||
class NotifyConsumer(AsyncWebsocketConsumer):
|
class NotifyConsumer(AsyncWebsocketConsumer):
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(args, kwargs)
|
super().__init__(args, kwargs)
|
||||||
|
self.log = logging.getLogger("server.log")
|
||||||
self.room_group_name = "general"
|
self.room_group_name = "general"
|
||||||
# self.event_slug = None
|
|
||||||
|
|
||||||
async def connect(self):
|
async def connect(self):
|
||||||
# self.event_slug = self.scope["url_route"]["kwargs"]["event_slug"]
|
|
||||||
# self.room_group_name = f"chat_{self.event_slug}"
|
|
||||||
|
|
||||||
# Join room group
|
# Join room group
|
||||||
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
|
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
|
||||||
|
self.log.info(f"Added {self.channel_name} channel to {self.room_group_name} group")
|
||||||
await self.accept()
|
await self.accept()
|
||||||
|
|
||||||
async def disconnect(self, close_code):
|
async def disconnect(self, close_code):
|
||||||
|
@ -25,26 +24,34 @@ class NotifyConsumer(AsyncWebsocketConsumer):
|
||||||
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
|
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
|
||||||
|
|
||||||
# Receive message from WebSocket
|
# Receive message from WebSocket
|
||||||
async def receive(self, text_data):
|
async def receive(self, text_data=None, bytes_data=None):
|
||||||
|
self.log.info(f"Received message: {text_data}")
|
||||||
try:
|
try:
|
||||||
text_data_json = json_loads(text_data)
|
text_data_json = json_loads(text_data)
|
||||||
message = text_data_json["message"]
|
message = text_data_json["message"]
|
||||||
|
|
||||||
# Send message to room group
|
# Send message to room group
|
||||||
await self.channel_layer.group_send(
|
await self.channel_layer.group_send(
|
||||||
self.room_group_name, {"type": "chat.message", "message": message}
|
self.room_group_name,
|
||||||
|
{"type": "generic.event", "message": message, "name": "send_message_to_frontend", "event_id": 1}
|
||||||
)
|
)
|
||||||
except JSONDecodeError:
|
except JSONDecodeError as e:
|
||||||
await self.send(text_data=json_dumps({"message": "error", "error": "malformed json"}))
|
await self.send(text_data=json_dumps({"message": "error", "error": "malformed json"}))
|
||||||
|
self.log.error(e)
|
||||||
except KeyError as e:
|
except KeyError as e:
|
||||||
await self.send(text_data=json_dumps({"message": "error", "error": f"missing key: {str(e)}"}))
|
await self.send(text_data=json_dumps({"message": "error", "error": f"missing key: {str(e)}"}))
|
||||||
|
self.log.error(e)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await self.send(text_data=json_dumps({"message": "error", "error": "unknown error"}))
|
await self.send(text_data=json_dumps({"message": "error", "error": "unknown error"}))
|
||||||
|
self.log.error(e)
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
# Receive message from room group
|
# Receive message from room group
|
||||||
async def chat_message(self, event):
|
async def generic_event(self, event):
|
||||||
|
self.log.info(f"Received event: {event}")
|
||||||
message = event["message"]
|
message = event["message"]
|
||||||
|
name = event["name"]
|
||||||
|
event_id = event["event_id"]
|
||||||
|
|
||||||
# Send message to WebSocket
|
# Send message to WebSocket
|
||||||
await self.send(text_data=json_dumps({"message": message}))
|
await self.send(text_data=json_dumps({"message": message, "name": name, "event_id": event_id}))
|
||||||
|
|
27
core/notify_sessions/migrations/0001_initial.py
Normal file
27
core/notify_sessions/migrations/0001_initial.py
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
# Generated by Django 4.2.7 on 2023-12-09 02:13
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='SystemEvent',
|
||||||
|
fields=[
|
||||||
|
('id', models.AutoField(primary_key=True, serialize=False)),
|
||||||
|
('timestamp', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('type', models.CharField(choices=[('ticket_created', 'ticket_created'), ('ticket_updated', 'ticket_updated'), ('ticket_deleted', 'ticket_deleted'), ('item_created', 'item_created'), ('item_updated', 'item_updated'), ('item_deleted', 'item_deleted'), ('user_created', 'user_created'), ('event_created', 'event_created'), ('event_updated', 'event_updated'), ('event_deleted', 'event_deleted')], max_length=255)),
|
||||||
|
('reference', models.IntegerField(blank=True, null=True)),
|
||||||
|
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
48
core/notify_sessions/models.py
Normal file
48
core/notify_sessions/models.py
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from django.db import models
|
||||||
|
from asgiref.sync import sync_to_async
|
||||||
|
from channels.layers import get_channel_layer
|
||||||
|
|
||||||
|
from authentication.models import ExtendedUser
|
||||||
|
|
||||||
|
|
||||||
|
class SystemEvent(models.Model):
|
||||||
|
TYPE_CHOICES = [('ticket_created', 'ticket_created'),
|
||||||
|
('ticket_updated', 'ticket_updated'),
|
||||||
|
('ticket_deleted', 'ticket_deleted'),
|
||||||
|
('item_created', 'item_created'),
|
||||||
|
('item_updated', 'item_updated'),
|
||||||
|
('item_deleted', 'item_deleted'),
|
||||||
|
('user_created', 'user_created'),
|
||||||
|
('event_created', 'event_created'),
|
||||||
|
('event_updated', 'event_updated'),
|
||||||
|
('event_deleted', 'event_deleted'), ]
|
||||||
|
id = models.AutoField(primary_key=True)
|
||||||
|
timestamp = models.DateTimeField(auto_now_add=True)
|
||||||
|
user = models.ForeignKey(ExtendedUser, models.SET_NULL, null=True)
|
||||||
|
type = models.CharField(max_length=255, choices=TYPE_CHOICES)
|
||||||
|
reference = models.IntegerField(blank=True, null=True)
|
||||||
|
|
||||||
|
|
||||||
|
async def trigger_event(user, type, reference=None):
|
||||||
|
log = logging.getLogger('server.log')
|
||||||
|
log.info(f"Triggering event {type} for user {user} with reference {reference}")
|
||||||
|
try:
|
||||||
|
event = await sync_to_async(SystemEvent.objects.create, thread_sensitive=True)(user=user, type=type,
|
||||||
|
reference=reference)
|
||||||
|
channel_layer = get_channel_layer()
|
||||||
|
await channel_layer.group_send(
|
||||||
|
'general',
|
||||||
|
{
|
||||||
|
'type': 'generic.event',
|
||||||
|
'name': 'send_message_to_frontend',
|
||||||
|
'message': "event_trigered_from_views",
|
||||||
|
'event_id': event.id,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
log.info(f"SystemEvent {event.id} triggered")
|
||||||
|
return event
|
||||||
|
except Exception as e:
|
||||||
|
log.error(e)
|
||||||
|
raise e
|
0
core/notify_sessions/tests/__init__.py
Normal file
0
core/notify_sessions/tests/__init__.py
Normal file
66
core/notify_sessions/tests/test_notify_socket.py
Normal file
66
core/notify_sessions/tests/test_notify_socket.py
Normal file
|
@ -0,0 +1,66 @@
|
||||||
|
from django.test import TestCase
|
||||||
|
from channels.testing import WebsocketCommunicator
|
||||||
|
|
||||||
|
from notify_sessions.consumers import NotifyConsumer
|
||||||
|
from asgiref.sync import async_to_sync
|
||||||
|
|
||||||
|
|
||||||
|
class NotifyWebsocketTestCase(TestCase):
|
||||||
|
|
||||||
|
async def test_connect(self):
|
||||||
|
communicator = WebsocketCommunicator(NotifyConsumer.as_asgi(), "/ws/2/notify/")
|
||||||
|
connected, subprotocol = await communicator.connect()
|
||||||
|
self.assertTrue(connected)
|
||||||
|
await communicator.disconnect()
|
||||||
|
|
||||||
|
async def fut_send_message(self):
|
||||||
|
communicator = WebsocketCommunicator(NotifyConsumer.as_asgi(), "/ws/2/notify/")
|
||||||
|
connected, subprotocol = await communicator.connect()
|
||||||
|
self.assertTrue(connected)
|
||||||
|
await communicator.send_json_to({
|
||||||
|
"name": "foo",
|
||||||
|
"message": "bar",
|
||||||
|
})
|
||||||
|
response = await communicator.receive_json_from()
|
||||||
|
await communicator.disconnect()
|
||||||
|
return response
|
||||||
|
|
||||||
|
def test_send_message(self):
|
||||||
|
response = async_to_sync(self.fut_send_message)()
|
||||||
|
self.assertEqual(response["message"], "bar")
|
||||||
|
self.assertEqual(response["event_id"], 1)
|
||||||
|
self.assertEqual(response["name"], "send_message_to_frontend")
|
||||||
|
# events = SystemEvent.objects.all()
|
||||||
|
# self.assertEqual(len(events), 1)
|
||||||
|
# event = events[0]
|
||||||
|
# self.assertEqual(event.event_id, 1)
|
||||||
|
# self.assertEqual(event.name, "send_message_to_frontend")
|
||||||
|
# self.assertEqual(event.message, "bar")
|
||||||
|
|
||||||
|
async def fut_send_and_receive_message(self):
|
||||||
|
communicator1 = WebsocketCommunicator(NotifyConsumer.as_asgi(), "/ws/2/notify/")
|
||||||
|
communicator2 = WebsocketCommunicator(NotifyConsumer.as_asgi(), "/ws/2/notify/")
|
||||||
|
connected1, subprotocol1 = await communicator1.connect()
|
||||||
|
connected2, subprotocol2 = await communicator2.connect()
|
||||||
|
self.assertTrue(connected1)
|
||||||
|
self.assertTrue(connected2)
|
||||||
|
await communicator1.send_json_to({
|
||||||
|
"name": "foo",
|
||||||
|
"message": "bar",
|
||||||
|
})
|
||||||
|
response = await communicator2.receive_json_from()
|
||||||
|
await communicator1.disconnect()
|
||||||
|
await communicator2.disconnect()
|
||||||
|
return response
|
||||||
|
|
||||||
|
def test_send_and_receive_message(self):
|
||||||
|
response = async_to_sync(self.fut_send_and_receive_message)()
|
||||||
|
self.assertEqual(response["message"], "bar")
|
||||||
|
self.assertEqual(response["event_id"], 1)
|
||||||
|
self.assertEqual(response["name"], "send_message_to_frontend")
|
||||||
|
# events = SystemEvent.objects.all()
|
||||||
|
# self.assertEqual(len(events), 1)
|
||||||
|
# event = events[0]
|
||||||
|
# self.assertEqual(event.event_id, 1)
|
||||||
|
# self.assertEqual(event.name, "send_message_to_frontend")
|
||||||
|
# self.assertEqual(event.message, "bar")
|
Loading…
Reference in a new issue