From a188df3ae359ab770aac85d19d23739286ef6d41 Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Tue, 9 Jun 2026 22:53:50 +0200 Subject: Initial commit --- chat/__init__.py | 0 chat/asgi.py | 28 +++ chat/consumers.py | 65 +++++++ chat/routing.py | 7 + chat/settings.py | 135 ++++++++++++++ chat/templates/chat.html | 136 ++++++++++++++ chat/templates/room.html | 451 +++++++++++++++++++++++++++++++++++++++++++++++ chat/urls.py | 26 +++ chat/views.py | 14 ++ chat/wsgi.py | 16 ++ 10 files changed, 878 insertions(+) create mode 100644 chat/__init__.py create mode 100644 chat/asgi.py create mode 100644 chat/consumers.py create mode 100644 chat/routing.py create mode 100644 chat/settings.py create mode 100644 chat/templates/chat.html create mode 100644 chat/templates/room.html create mode 100644 chat/urls.py create mode 100644 chat/views.py create mode 100644 chat/wsgi.py (limited to 'chat') diff --git a/chat/__init__.py b/chat/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chat/asgi.py b/chat/asgi.py new file mode 100644 index 0000000..247393e --- /dev/null +++ b/chat/asgi.py @@ -0,0 +1,28 @@ +""" +ASGI config for chat project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ +""" + +import os + +from channels.auth import AuthMiddlewareStack +from channels.routing import ProtocolTypeRouter, URLRouter +from channels.security.websocket import AllowedHostsOriginValidator +from django.core.asgi import get_asgi_application + +from chat.routing import websocket_urlpatterns + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chat.settings') + +application = ProtocolTypeRouter( + { + "http": get_asgi_application(), + "websocket": AllowedHostsOriginValidator( + AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) + ), + } +) diff --git a/chat/consumers.py b/chat/consumers.py new file mode 100644 index 0000000..bfba381 --- /dev/null +++ b/chat/consumers.py @@ -0,0 +1,65 @@ +import json + +from asgiref.sync import async_to_sync +from channels.generic.websocket import WebsocketConsumer + + +class ChatConsumer(WebsocketConsumer): + def connect(self): + self.room_name = self.scope["url_route"]["kwargs"]["room_name"] + self.room_group_name = f"chat_{self.room_name}" + self.username = "Anonymous" + + async_to_sync(self.channel_layer.group_add)( + self.room_group_name, self.channel_name + ) + self.accept() + + def disconnect(self, close_code): + async_to_sync(self.channel_layer.group_discard)( + self.room_group_name, self.channel_name + ) + async_to_sync(self.channel_layer.group_send)( + self.room_group_name, + {"type": "system.message", "text": f"{self.username} left the chat"}, + ) + + def receive(self, text_data): + text_data_json = json.loads(text_data) + msg_type = text_data_json.get("type", "message") + + if msg_type == "join": + self.username = text_data_json.get("username", "Anonymous") + async_to_sync(self.channel_layer.group_send)( + self.room_group_name, + {"type": "system.message", "text": f"{self.username} joined the chat"}, + ) + return + + if msg_type == "rename": + old_name = self.username + self.username = text_data_json.get("username", self.username) + async_to_sync(self.channel_layer.group_send)( + self.room_group_name, + {"type": "system.message", "text": f"{old_name} is now known as {self.username}"}, + ) + return + + message = text_data_json["message"] + username = text_data_json.get("username", self.username) + async_to_sync(self.channel_layer.group_send)( + self.room_group_name, + {"type": "chat.message", "message": message, "username": username}, + ) + + def chat_message(self, event): + self.send(text_data=json.dumps({ + "message": event["message"], + "username": event["username"], + })) + + def system_message(self, event): + self.send(text_data=json.dumps({ + "type": "system", + "text": event["text"], + })) diff --git a/chat/routing.py b/chat/routing.py new file mode 100644 index 0000000..9f08ddf --- /dev/null +++ b/chat/routing.py @@ -0,0 +1,7 @@ +from django.urls import re_path + +from . import consumers + +websocket_urlpatterns = [ + re_path(r"ws/chat/(?P\w+)/$", consumers.ChatConsumer.as_asgi()), +] diff --git a/chat/settings.py b/chat/settings.py new file mode 100644 index 0000000..653eea9 --- /dev/null +++ b/chat/settings.py @@ -0,0 +1,135 @@ +""" +Django settings for chat project. + +Generated by 'django-admin startproject' using Django 5.0.3. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.0/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-dxn^kf6b8qm@#cqg4+jncop793g7*3mgok&p$40di_cxbm+y$3' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'chat', + 'daphne', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'chat.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'chat.wsgi.application' +ASGI_APPLICATION = 'chat.asgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +CHANNEL_LAYERS = { + "default": { + "BACKEND": "channels_redis.core.RedisChannelLayer", + "CONFIG": { + "hosts": [("127.0.0.1", 6379)], + }, + }, +} diff --git a/chat/templates/chat.html b/chat/templates/chat.html new file mode 100644 index 0000000..8542368 --- /dev/null +++ b/chat/templates/chat.html @@ -0,0 +1,136 @@ + + + + + + + dreamchat + + + +
+ +

dreamchat

+

Where do you want to go?

+
+ + +
+
+ + + + diff --git a/chat/templates/room.html b/chat/templates/room.html new file mode 100644 index 0000000..de76f67 --- /dev/null +++ b/chat/templates/room.html @@ -0,0 +1,451 @@ + + + + + + + {{ room_name }} — dreamchat + + + +
+ +
+ {{ room_name }} +
+ + +
+
+ +
+ +
+ +
+ + +
+ + {{ room_name|json_script:"room-name" }} + + + diff --git a/chat/urls.py b/chat/urls.py new file mode 100644 index 0000000..b96b107 --- /dev/null +++ b/chat/urls.py @@ -0,0 +1,26 @@ +""" +URL configuration for chat project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +from chat.views import Chat, Room + +urlpatterns = [ + path('admin/', admin.site.urls), + path('/', Room.as_view()), + path('', Chat.as_view()), +] diff --git a/chat/views.py b/chat/views.py new file mode 100644 index 0000000..512837e --- /dev/null +++ b/chat/views.py @@ -0,0 +1,14 @@ +from django.views.generic import TemplateView + + +class Chat(TemplateView): + template_name = 'chat.html' + +class Room(TemplateView): + template_name = 'room.html' + + def get_context_data(self, **kwargs): + return { + **super().get_context_data(**kwargs), + 'room_name': kwargs.get('room'), + } diff --git a/chat/wsgi.py b/chat/wsgi.py new file mode 100644 index 0000000..cdfbb23 --- /dev/null +++ b/chat/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for chat project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chat.settings') + +application = get_wsgi_application() -- cgit v1.2.3