From 75de13e7a278c6649473d19a7f65b3fe539756e7 Mon Sep 17 00:00:00 2001 From: Andros Fenollosa Date: Sun, 15 Nov 2020 10:52:18 +0100 Subject: [PATCH] add --- apps/chat/__init__.py | 0 apps/chat/admin.py | 3 + apps/chat/apps.py | 5 ++ apps/chat/consumers.py | 60 +++++++++++++ apps/chat/migrations/__init__.py | 0 apps/chat/models.py | 3 + apps/chat/routing.py | 7 ++ apps/chat/tests.py | 3 + apps/chat/views.py | 3 + apps/front/__init__.py | 0 apps/front/admin.py | 3 + apps/front/apps.py | 5 ++ apps/front/migrations/__init__.py | 0 apps/front/models.py | 3 + apps/front/templates/chat.html | 118 ++++++++++++++++++++++++++ apps/front/tests.py | 3 + apps/front/views.py | 4 + asgi.py | 18 ++++ db.sqlite3 | 0 manage.py | 22 +++++ mi_web/__init__.py | 0 mi_web/asgi.py | 16 ++++ mi_web/settings.py | 134 ++++++++++++++++++++++++++++++ mi_web/urls.py | 23 +++++ mi_web/wsgi.py | 16 ++++ 25 files changed, 449 insertions(+) create mode 100644 apps/chat/__init__.py create mode 100644 apps/chat/admin.py create mode 100644 apps/chat/apps.py create mode 100644 apps/chat/consumers.py create mode 100644 apps/chat/migrations/__init__.py create mode 100644 apps/chat/models.py create mode 100644 apps/chat/routing.py create mode 100644 apps/chat/tests.py create mode 100644 apps/chat/views.py create mode 100644 apps/front/__init__.py create mode 100644 apps/front/admin.py create mode 100644 apps/front/apps.py create mode 100644 apps/front/migrations/__init__.py create mode 100644 apps/front/models.py create mode 100644 apps/front/templates/chat.html create mode 100644 apps/front/tests.py create mode 100644 apps/front/views.py create mode 100644 asgi.py create mode 100644 db.sqlite3 create mode 100755 manage.py create mode 100644 mi_web/__init__.py create mode 100644 mi_web/asgi.py create mode 100644 mi_web/settings.py create mode 100644 mi_web/urls.py create mode 100644 mi_web/wsgi.py diff --git a/apps/chat/__init__.py b/apps/chat/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/chat/admin.py b/apps/chat/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/apps/chat/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/apps/chat/apps.py b/apps/chat/apps.py new file mode 100644 index 0000000..8ebb9f0 --- /dev/null +++ b/apps/chat/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class ChatConfig(AppConfig): + name = 'chat' diff --git a/apps/chat/consumers.py b/apps/chat/consumers.py new file mode 100644 index 0000000..17c6042 --- /dev/null +++ b/apps/chat/consumers.py @@ -0,0 +1,60 @@ +import json +from channels.generic.websocket import AsyncWebsocketConsumer +from asgiref.sync import sync_to_async + +class ChatConsumer(AsyncWebsocketConsumer): + + async def connect(self): + ''' Cliente se conecta ''' + + # Recoge el nombre de la sala + self.room_name = self.scope["url_route"]["kwargs"]["room_name"] + self.room_group_name = "chat_%s" % self.room_name + + # Se une a la sala + await self.channel_layer.group_add(self.room_group_name, self.channel_name) + + # Informa al cliente del éxito + await self.accept() + + async def disconnect(self, close_code): + ''' Cliente se desconecta ''' + # Leave room group + await self.channel_layer.group_discard(self.room_group_name, self.channel_name) + + async def receive(self, text_data): + ''' Cliente envía información ''' + text_data_json = json.loads(text_data) + text = text_data_json["text"] + member_send = text_data_json["member_send"] + member_receive = text_data_json["member_receive"] + + await self.save_message(member_send, member_receive, text) + + # Send message to room group + await self.channel_layer.group_send( + self.room_group_name, + { + "type": "chat_message", + "text": text, + "member_send": member_send, + "member_receive": member_receive, + }, + ) + + async def chat_message(self, event): + ''' Recibe información de la sala ''' + text = event["text"] + member_send = event["member_send"] + member_receive = event["member_receive"] + + # Send message to WebSocket + await self.send( + text_data=json.dumps( + { + "text": text, + "member_send": member_send, + "member_receive": member_receive, + } + ) + ) diff --git a/apps/chat/migrations/__init__.py b/apps/chat/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/chat/models.py b/apps/chat/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/apps/chat/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/apps/chat/routing.py b/apps/chat/routing.py new file mode 100644 index 0000000..90bf611 --- /dev/null +++ b/apps/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), +] diff --git a/apps/chat/tests.py b/apps/chat/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/apps/chat/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/chat/views.py b/apps/chat/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/apps/chat/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/apps/front/__init__.py b/apps/front/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/front/admin.py b/apps/front/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/apps/front/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/apps/front/apps.py b/apps/front/apps.py new file mode 100644 index 0000000..3616320 --- /dev/null +++ b/apps/front/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class FrontConfig(AppConfig): + name = 'front' diff --git a/apps/front/migrations/__init__.py b/apps/front/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/front/models.py b/apps/front/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/apps/front/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/apps/front/templates/chat.html b/apps/front/templates/chat.html new file mode 100644 index 0000000..8f16785 --- /dev/null +++ b/apps/front/templates/chat.html @@ -0,0 +1,118 @@ + + + + + Chat + + + + + + +
+

Chat con Django

+
+ +
+ + +
+ + + +
+ + +
+ +
+
+
+ + + diff --git a/apps/front/tests.py b/apps/front/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/apps/front/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/front/views.py b/apps/front/views.py new file mode 100644 index 0000000..03a6756 --- /dev/null +++ b/apps/front/views.py @@ -0,0 +1,4 @@ +from django.shortcuts import render + +def chat(request): + return render(request, 'chat.html') diff --git a/asgi.py b/asgi.py new file mode 100644 index 0000000..4141348 --- /dev/null +++ b/asgi.py @@ -0,0 +1,18 @@ +import os + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mi_web.settings") +import django + +django.setup() + +from channels.auth import AuthMiddlewareStack +from channels.routing import ProtocolTypeRouter, URLRouter +from django.core.asgi import get_asgi_application +from apps.chat.routing import websocket_urlpatterns + + +application = ProtocolTypeRouter( + { + "websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns)), + } +) diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000..e69de29 diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..089ff59 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mi_web.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/mi_web/__init__.py b/mi_web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mi_web/asgi.py b/mi_web/asgi.py new file mode 100644 index 0000000..9a0990c --- /dev/null +++ b/mi_web/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for mi_web 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/3.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mi_web.settings') + +application = get_asgi_application() diff --git a/mi_web/settings.py b/mi_web/settings.py new file mode 100644 index 0000000..f594488 --- /dev/null +++ b/mi_web/settings.py @@ -0,0 +1,134 @@ +""" +Django settings for mi_web project. + +Generated by 'django-admin startproject' using Django 3.1.3. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/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/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'pzcj^u^ktd7$9#pd196m+=#384=*%^il2r5po-)jutl^zpt%k0' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'channels', + 'apps.chat', + 'apps.front', +] + +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 = 'mi_web.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 = 'mi_web.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ + +STATIC_URL = '/static/' + +ASGI_APPLICATION = "asgi.application" +CHANNEL_LAYERS = { + "default": { + "BACKEND": "channels_redis.core.RedisChannelLayer", + "CONFIG": { + "hosts": [("127.0.0.1", 6379)], + }, + }, +} + diff --git a/mi_web/urls.py b/mi_web/urls.py new file mode 100644 index 0000000..1c7233c --- /dev/null +++ b/mi_web/urls.py @@ -0,0 +1,23 @@ +"""mi_web URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.1/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 apps.front import views + +urlpatterns = [ + path('admin/', admin.site.urls), + path('', views.chat), +] diff --git a/mi_web/wsgi.py b/mi_web/wsgi.py new file mode 100644 index 0000000..b9c965b --- /dev/null +++ b/mi_web/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mi_web 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/3.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mi_web.settings') + +application = get_wsgi_application()