Skip to content

Commit

Permalink
Merge pull request #1851 from anirudh-mk/dev
Browse files Browse the repository at this point in the history
feat(lc):chat implemented
  • Loading branch information
adnankattekaden authored Dec 25, 2023
2 parents 3ddbc28 + 879dd5e commit 6c4440b
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 1 deletion.
62 changes: 62 additions & 0 deletions api/dashboard/lc/dash_lc_consumers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from db.learning_circle import UserCircleLink


class LcChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
try:
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f"chat_{self.room_name}"
self.lc_id = self.scope['url_route']['kwargs']['lc_id']
self.user_id = self.scope['url_route']['kwargs']['user_id']

user_circle_link = await self.get_user_circle_link()

if user_circle_link is None:
await self.close()
return

await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)

await self.accept()

except Exception as e:
print(f"Error during WebSocket connection: {str(e)}")
await self.close()

@database_sync_to_async
def get_user_circle_link(self):
return UserCircleLink.objects.filter(
user_id=self.user_id,
circle_id=self.lc_id,
accepted=True,
).first()

async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']

await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat.message',
'message': message
}
)

async def chat_message(self, event):
message = event['message']
await self.send(text_data=json.dumps({
'message': message
}))
6 changes: 6 additions & 0 deletions api/dashboard/lc/dash_lc_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.urls import path
from . import dash_lc_consumers

urlpatterns = [
path("<str:lc_id>/chat/<str:room_name>/<str:user_id>/", dash_lc_consumers.LcChatConsumer.as_asgi())
]
4 changes: 3 additions & 1 deletion api/routing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from django.urls import path, include
from channels.routing import URLRouter
from api.common import routing as common_routing
from api.dashboard.lc import dash_lc_routing

urlpatterns = [
path("public/", URLRouter(common_routing.urlpatterns)),
]
path('dashboard/', URLRouter(dash_lc_routing.urlpatterns)),
]

0 comments on commit 6c4440b

Please sign in to comment.