Skip to content

Commit

Permalink
fix: chats
Browse files Browse the repository at this point in the history
  • Loading branch information
Shavkatjon-O committed Aug 28, 2024
1 parent 6fa6d01 commit e8cfed8
Show file tree
Hide file tree
Showing 14 changed files with 191 additions and 5 deletions.
Empty file added apps/chats/__init__.py
Empty file.
7 changes: 7 additions & 0 deletions apps/chats/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.contrib import admin

from apps.chats.models import Chat, Message


admin.site.register(Chat)
admin.site.register(Message)
6 changes: 6 additions & 0 deletions apps/chats/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ChatsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.chats"
45 changes: 45 additions & 0 deletions apps/chats/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Generated by Django 5.0.7 on 2024-08-28 08:37

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Chat',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('title', models.CharField(blank=True, max_length=256, null=True)),
('is_group', models.BooleanField(default=False)),
('users', models.ManyToManyField(related_name='chats', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('content', models.TextField()),
('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='chats.chat')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
Empty file.
25 changes: 25 additions & 0 deletions apps/chats/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.db import models
from django.contrib.auth import get_user_model

from apps.common.models import BaseModel

User = get_user_model()


class Chat(BaseModel):
title = models.CharField(max_length=256, blank=True, null=True)
is_group = models.BooleanField(default=False)
users = models.ManyToManyField(User, related_name="chats")

def __str__(self):
return self.title


class Message(BaseModel):
chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name="messages")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="messages")

content = models.TextField()

def __str__(self):
return self.content
24 changes: 24 additions & 0 deletions apps/chats/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from rest_framework import serializers
from .models import Chat, Message


class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = [
"id",
"chat",
"user",
"content",
]


class ChatSerializer(serializers.ModelSerializer):
class Meta:
model = Chat
fields = [
"id",
"title",
"is_group",
"users",
]
3 changes: 3 additions & 0 deletions apps/chats/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
17 changes: 17 additions & 0 deletions apps/chats/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views

# router = DefaultRouter()
# router.register(r"chats", views.ChatViewSet)
# router.register(r"messages", views.MessageViewSet)

# urlpatterns = [
# path("", include(router.urls)),
# ]


urlpatterns = [
path("chats/<int:pk>/", views.ChatViewSet.as_view(), name="chat"),
path("messages/<int:pk>/", views.MessageViewSet.as_view(), name="message"),
]
25 changes: 25 additions & 0 deletions apps/chats/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from rest_framework import viewsets
from .models import Chat, Message
from .serializers import ChatSerializer, MessageSerializer
from rest_framework.generics import ListAPIView, RetrieveAPIView


# class ChatViewSet(RetrieveAPIView):
# queryset = Chat.objects.all()
# serializer_class = ChatSerializer


class ChatViewSet(RetrieveAPIView):
queryset = Chat.objects.all()
serializer_class = ChatSerializer


class MessageViewSet(ListAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer

def get_queryset(self):
chat_id = self.kwargs["chat_id"]

print(self.queryset.filter(chat__id=chat_id))
return self.queryset.filter(chat__id=chat_id)
38 changes: 35 additions & 3 deletions core/consumers.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
import json
from channels.generic.websocket import AsyncWebsocketConsumer
import json


class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.chat_id = self.scope["url_route"]["kwargs"]["chat_id"]
self.chat_group_name = f"chat_{self.chat_id}"

# Join chat room group
await self.channel_layer.group_add(self.chat_group_name, self.channel_name)

await self.accept()

async def disconnect(self, close_code):
pass
# Leave chat room group
await self.channel_layer.group_discard(self.chat_group_name, self.channel_name)

# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json["message"]
sender = self.scope["user"].username

# Send message to chat room group
await self.channel_layer.group_send(
self.chat_group_name,
{
"message": message,
"type": "chat_message",
"sender": sender,
},
)

# Receive message from chat room group
async def chat_message(self, event):
message = event["message"]
sender = event["sender"]

await self.send(text_data=json.dumps({"message": message}))
# Send message to WebSocket
await self.send(
text_data=json.dumps(
{
"message": message,
"sender": sender,
},
),
)
4 changes: 2 additions & 2 deletions core/routing.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.urls import re_path
from core import consumers
from . import consumers

websocket_urlpatterns = [
re_path(r"ws/messenger/$", consumers.ChatConsumer.as_asgi()),
re_path(r"ws/chat/(?P<chat_id>\d+)/$", consumers.ChatConsumer.as_asgi()),
]
1 change: 1 addition & 0 deletions core/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"apps.bot",
"apps.common",
"apps.users",
"apps.chats",
]

THIRD_PARTY_APPS = [
Expand Down
1 change: 1 addition & 0 deletions core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
path("api/users/", include("apps.users.urls")),
# path("api/bot/", include("apps.bot.urls")),
path("api/common/", include("apps.common.urls")),
path("api/chats/", include("apps.chats.urls")),
]

if not settings.DEBUG:
Expand Down

0 comments on commit e8cfed8

Please sign in to comment.