From a5362bd2ad3d9124155e12127cbac93584bb68f1 Mon Sep 17 00:00:00 2001 From: SDE Date: Sun, 13 Aug 2023 13:25:21 +0300 Subject: [PATCH] 0.3.4 chat v3 --- ChatServiceApp/funcs.py | 2 +- ChatServiceApp/websocket_urls.py | 5 +- ChatServiceApp/websocket_views.py | 43 ++++---- TWB/asgi.py | 22 +++- TWB/run_daphne.py | 8 ++ TWB/settings.py | 14 ++- TWB/ws_middleware.py | 26 +++++ static/js/chat_sockets.js | 110 +++++++++----------- templates/blocks/profile/b_chats.html | 1 + templates/pages/profile/p_user_profile.html | 2 +- templates/tb_base.html | 2 + 11 files changed, 143 insertions(+), 92 deletions(-) create mode 100644 TWB/run_daphne.py create mode 100644 TWB/ws_middleware.py diff --git a/ChatServiceApp/funcs.py b/ChatServiceApp/funcs.py index bf9fcaf..4fa6518 100644 --- a/ChatServiceApp/funcs.py +++ b/ChatServiceApp/funcs.py @@ -103,7 +103,7 @@ def send_msg(data): }) html = render_to_string(tpl_name, res_Dict) - return {'html': html} + return {'html': html, 'sender': data['sender']} except Exception as e: msg = f'send_msg_ajax Error = {str(e)}' diff --git a/ChatServiceApp/websocket_urls.py b/ChatServiceApp/websocket_urls.py index a5a4c24..f90190d 100644 --- a/ChatServiceApp/websocket_urls.py +++ b/ChatServiceApp/websocket_urls.py @@ -1,7 +1,8 @@ from django.urls import re_path + from .websocket_views import * websocket_urlpatterns = [ - re_path(r'ws/socket-server/', ChatConsumer.as_asgi()) - + re_path(r'ws/socket-server/', ChatConsumer.as_asgi()), + # re_path(r'ws/chat/(?P\w+)/$', consumers.ChatConsumer), ] \ No newline at end of file diff --git a/ChatServiceApp/websocket_views.py b/ChatServiceApp/websocket_views.py index 129f9d6..811b952 100644 --- a/ChatServiceApp/websocket_views.py +++ b/ChatServiceApp/websocket_views.py @@ -1,17 +1,23 @@ import json -from channels.generic.websocket import WebsocketConsumer -from asgiref.sync import async_to_sync -# from .funcs import * +from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer, JsonWebsocketConsumer +from asgiref.sync import async_to_sync, sync_to_async +# from channels.auth import channel_session_user, channel_session_user_from_http +from channels.layers import get_channel_layer class ChatConsumer(WebsocketConsumer): + + # def __init__(self, *args, **kwargs): + # super().__init__(args, kwargs) + # self.room_name = None + def connect(self): print('ws connect') self.room_group_name = 'test' - async_to_sync(self.channel_layer.group_add)( - self.room_group_name, - self.channel_name - ) + # async_to_sync(self.channel_layer.group_add)( + # f'user_{self.scope["user"]["id"]}', + # self.channel_name + # ) print(f'self.room_group_name = {self.room_group_name}') print(f'self.channel_name = {self.channel_name}') self.accept() @@ -20,15 +26,15 @@ class ChatConsumer(WebsocketConsumer): print(f'ws receive text_data = {text_data}') from .funcs import send_msg - resDict = send_msg(text_data) - resDict.update({ + Dict = send_msg(text_data) + resDict = { 'type': 'ws_send_msg', - 'message': resDict, - # 'sender': sender - }) + 'message': Dict, + # 'sender': resDict['sender'] + } print(f'send_msg res = {len(resDict)}') - self.send(json.dumps(resDict)) + # self.send(text_data='!!!!') async_to_sync(self.channel_layer.group_send)( self.room_group_name, @@ -40,14 +46,9 @@ class ChatConsumer(WebsocketConsumer): # } ) - def ws_send_msg(self, event): + def ws_send_msg(self, data): print('ws ws_send_msg') - message = event['message'] - # sender = event['sender'] + data['type'] = 'chat' - self.send(text_data=json.dumps({ - 'type': 'chat', - 'message': message, - # 'sender': sender - })) \ No newline at end of file + self.send(text_data=json.dumps(data)) \ No newline at end of file diff --git a/TWB/asgi.py b/TWB/asgi.py index 64e910b..7d8ce38 100644 --- a/TWB/asgi.py +++ b/TWB/asgi.py @@ -13,14 +13,32 @@ from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from ChatServiceApp.websocket_urls import websocket_urlpatterns +from channels.security.websocket import AllowedHostsOriginValidator +from channels.sessions import SessionMiddlewareStack +from .ws_middleware import QueryAuthMiddleware + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TWB.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), - 'websocket': AuthMiddlewareStack( + "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) - ) + ), + # 'websocket': AuthMiddlewareStack( + # URLRouter( + # websocket_urlpatterns + # ) + # ) + # "websocket": AllowedHostsOriginValidator( + # SessionMiddlewareStack( + # AuthMiddlewareStack( + # URLRouter( + # websocket_urlpatterns + # ) + # ) + # ) + # ), }) diff --git a/TWB/run_daphne.py b/TWB/run_daphne.py new file mode 100644 index 0000000..fe370c7 --- /dev/null +++ b/TWB/run_daphne.py @@ -0,0 +1,8 @@ +import sys + +if __name__ == '__main__': + # insert here whatever commands you use to run daphne + sys.argv = ['daphne', 'TWB.asgi:application'] + from daphne.cli import CommandLineInterface + + CommandLineInterface.entrypoint() \ No newline at end of file diff --git a/TWB/settings.py b/TWB/settings.py index 03b0d8b..a409e2d 100644 --- a/TWB/settings.py +++ b/TWB/settings.py @@ -33,7 +33,9 @@ ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ - 'channels', + # 'channels', + "daphne", + 'ChatServiceApp', 'modeltranslation', 'django.contrib.admin', @@ -51,7 +53,7 @@ INSTALLED_APPS = [ 'AuthApp', 'RoutesApp', 'ReferenceDataApp', - 'ChatServiceApp', + ] MIDDLEWARE = [ @@ -86,12 +88,16 @@ TEMPLATES = [ }, ] -# WSGI_APPLICATION = 'TWB.wsgi.application' +WSGI_APPLICATION = 'TWB.wsgi.application' ASGI_APPLICATION = 'TWB.asgi.application' CHANNEL_LAYERS = { 'default': { - 'BACKEND': 'channels.layers.InMemoryChannelLayer' + # 'BACKEND': 'channels.layers.InMemoryChannelLayer' + "BACKEND": "channels_redis.core.RedisChannelLayer", + "CONFIG": { + "hosts": [("127.0.0.1", 6379)], + }, } } diff --git a/TWB/ws_middleware.py b/TWB/ws_middleware.py new file mode 100644 index 0000000..017bbc7 --- /dev/null +++ b/TWB/ws_middleware.py @@ -0,0 +1,26 @@ +from channels.db import database_sync_to_async + +@database_sync_to_async +def get_user(user_id): + from django.contrib.auth.models import User, AnonymousUser + try: + return User.objects.get(id=user_id) + except User.DoesNotExist: + return AnonymousUser() + +class QueryAuthMiddleware: + """ + Custom middleware (insecure) that takes user IDs from the query string. + """ + + def __init__(self, app): + # Store the ASGI application we were passed + self.app = app + + async def __call__(self, scope, receive, send): + # Look up user from query string (you should also do things like + # checking if it is a valid user ID, or if scope["user"] is already + # populated). + scope['user'] = await get_user(int(scope["query_string"])) + + return await self.app(scope, receive, send) \ No newline at end of file diff --git a/static/js/chat_sockets.js b/static/js/chat_sockets.js index 0804bd5..02fbace 100644 --- a/static/js/chat_sockets.js +++ b/static/js/chat_sockets.js @@ -42,75 +42,63 @@ // var i = 0 -// function sendMessageSocket (data) { -// let chatSocket = new WebSocket(url); -// chatSocket.onopen = function (){ -// console.log("open") -// chatSocket.send(JSON.stringify(data)) -// } -// chatSocket.onclose = function () { -// console.log("close") -// return false -// } -// // -// -// // } -// // open_socket() -// // chatSocket.OPEN -// -// // chatSocket.onopen = function (){ -// // console.log("open") -// // -// -// -// // } -// } - -// -// chatSocket.onmessage = function (e) { -// let data = JSON.parse(e.data); -// console.log('Data:', data); -// console.log("return") -// if (data.type === 'chat'){ -// document.querySelector(".container-messages").innerHTML = data.html; -// document.querySelector(".enter-message-inp").focus() -// } -// } - - let url = `ws://localhost:8000/ws/socket-server/`; const chatSocket = new WebSocket(url); +function sendMessageSocket (data) { + chatSocket.send(JSON.stringify(data)); +} + + chatSocket.onmessage = function (e) { - let data = JSON.parse(e.data) - console.log('Data: ', data) - - if (data.type === 'chat') { - // let messages = document.getElementById('messages') - // - // messages.insertAdjacentHTML('beforeend', `
- //

${data.message}

- //
` - // ) - document.querySelector(".container-messages").innerHTML = data.html; - document.querySelector(".enter-message-inp").focus() - } - + let data = JSON.parse(e.data); + console.log('Data:', data); + console.log("return") + if (data.type === 'chat'){ + document.querySelector(".container-messages").innerHTML = data.html; + document.querySelector(".enter-message-inp").focus() + } } -window.onload = function () { - let btn = document.querySelector(".send-message") +// let url = `ws://localhost:8000/ws/socket-server/`; +// +// const chatSocket = new WebSocket(url); +// +// chatSocket.onmessage = function (e) { +// let data = JSON.parse(e.data) +// console.log('Data: ', data) +// +// if (data.type === 'chat') { +// // let messages = document.getElementById('messages') +// // +// // messages.insertAdjacentHTML('beforeend', `
+// //

${data.message}

+// //
` +// // ) +// document.querySelector(".container-messages").innerHTML = data.html; +// document.querySelector(".enter-message-inp").focus() +// } +// +// } - btn.addEventListener('click', (e) => { - e.preventDefault() - // let message = e.target.message.value - chatSocket.send(JSON.stringify({ - 'data':'data' - })) - // btn.reset() - }) -} +// function send_ws_msg(data) { +// chatSocket.send(JSON.stringify(data)); +// } + +// window.onload = function () { +// +// let btn = document.querySelector(".send-message") +// +// btn.addEventListener('click', (e) => { +// e.preventDefault() +// // let message = e.target.message.value +// chatSocket.send(JSON.stringify({ +// 'data':'data' +// })) +// // btn.reset() +// }) +// } // let form = document.getElementById('form') diff --git a/templates/blocks/profile/b_chats.html b/templates/blocks/profile/b_chats.html index 658ea21..f19de91 100644 --- a/templates/blocks/profile/b_chats.html +++ b/templates/blocks/profile/b_chats.html @@ -63,6 +63,7 @@
+{# #}
diff --git a/templates/pages/profile/p_user_profile.html b/templates/pages/profile/p_user_profile.html index 430baea..41147e0 100644 --- a/templates/pages/profile/p_user_profile.html +++ b/templates/pages/profile/p_user_profile.html @@ -9,7 +9,7 @@ - +{# #} diff --git a/templates/tb_base.html b/templates/tb_base.html index 8a6e258..62104fe 100644 --- a/templates/tb_base.html +++ b/templates/tb_base.html @@ -8,6 +8,8 @@ + +