0.3.4
chat v3
This commit is contained in:
@@ -103,7 +103,7 @@ def send_msg(data):
|
|||||||
})
|
})
|
||||||
|
|
||||||
html = render_to_string(tpl_name, res_Dict)
|
html = render_to_string(tpl_name, res_Dict)
|
||||||
return {'html': html}
|
return {'html': html, 'sender': data['sender']}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
msg = f'send_msg_ajax Error = {str(e)}'
|
msg = f'send_msg_ajax Error = {str(e)}'
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
from django.urls import re_path
|
from django.urls import re_path
|
||||||
|
|
||||||
from .websocket_views import *
|
from .websocket_views import *
|
||||||
|
|
||||||
websocket_urlpatterns = [
|
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<room_name>\w+)/$', consumers.ChatConsumer),
|
||||||
]
|
]
|
||||||
@@ -1,17 +1,23 @@
|
|||||||
import json
|
import json
|
||||||
from channels.generic.websocket import WebsocketConsumer
|
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer, JsonWebsocketConsumer
|
||||||
from asgiref.sync import async_to_sync
|
from asgiref.sync import async_to_sync, sync_to_async
|
||||||
# from .funcs import *
|
# from channels.auth import channel_session_user, channel_session_user_from_http
|
||||||
|
from channels.layers import get_channel_layer
|
||||||
|
|
||||||
class ChatConsumer(WebsocketConsumer):
|
class ChatConsumer(WebsocketConsumer):
|
||||||
|
|
||||||
|
# def __init__(self, *args, **kwargs):
|
||||||
|
# super().__init__(args, kwargs)
|
||||||
|
# self.room_name = None
|
||||||
|
|
||||||
def connect(self):
|
def connect(self):
|
||||||
print('ws connect')
|
print('ws connect')
|
||||||
self.room_group_name = 'test'
|
self.room_group_name = 'test'
|
||||||
|
|
||||||
async_to_sync(self.channel_layer.group_add)(
|
# async_to_sync(self.channel_layer.group_add)(
|
||||||
self.room_group_name,
|
# f'user_{self.scope["user"]["id"]}',
|
||||||
self.channel_name
|
# self.channel_name
|
||||||
)
|
# )
|
||||||
print(f'self.room_group_name = {self.room_group_name}')
|
print(f'self.room_group_name = {self.room_group_name}')
|
||||||
print(f'self.channel_name = {self.channel_name}')
|
print(f'self.channel_name = {self.channel_name}')
|
||||||
self.accept()
|
self.accept()
|
||||||
@@ -20,15 +26,15 @@ class ChatConsumer(WebsocketConsumer):
|
|||||||
print(f'ws receive text_data = {text_data}')
|
print(f'ws receive text_data = {text_data}')
|
||||||
|
|
||||||
from .funcs import send_msg
|
from .funcs import send_msg
|
||||||
resDict = send_msg(text_data)
|
Dict = send_msg(text_data)
|
||||||
resDict.update({
|
resDict = {
|
||||||
'type': 'ws_send_msg',
|
'type': 'ws_send_msg',
|
||||||
'message': resDict,
|
'message': Dict,
|
||||||
# 'sender': sender
|
# 'sender': resDict['sender']
|
||||||
})
|
}
|
||||||
print(f'send_msg res = {len(resDict)}')
|
print(f'send_msg res = {len(resDict)}')
|
||||||
|
|
||||||
self.send(json.dumps(resDict))
|
# self.send(text_data='!!!!')
|
||||||
|
|
||||||
async_to_sync(self.channel_layer.group_send)(
|
async_to_sync(self.channel_layer.group_send)(
|
||||||
self.room_group_name,
|
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')
|
print('ws ws_send_msg')
|
||||||
|
|
||||||
message = event['message']
|
data['type'] = 'chat'
|
||||||
# sender = event['sender']
|
|
||||||
|
|
||||||
self.send(text_data=json.dumps({
|
self.send(text_data=json.dumps(data))
|
||||||
'type': 'chat',
|
|
||||||
'message': message,
|
|
||||||
# 'sender': sender
|
|
||||||
}))
|
|
||||||
22
TWB/asgi.py
22
TWB/asgi.py
@@ -13,14 +13,32 @@ from django.core.asgi import get_asgi_application
|
|||||||
from channels.routing import ProtocolTypeRouter, URLRouter
|
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||||
from channels.auth import AuthMiddlewareStack
|
from channels.auth import AuthMiddlewareStack
|
||||||
from ChatServiceApp.websocket_urls import websocket_urlpatterns
|
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')
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TWB.settings')
|
||||||
|
|
||||||
application = ProtocolTypeRouter({
|
application = ProtocolTypeRouter({
|
||||||
'http': get_asgi_application(),
|
'http': get_asgi_application(),
|
||||||
'websocket': AuthMiddlewareStack(
|
"websocket": AuthMiddlewareStack(
|
||||||
URLRouter(
|
URLRouter(
|
||||||
websocket_urlpatterns
|
websocket_urlpatterns
|
||||||
)
|
)
|
||||||
)
|
),
|
||||||
|
# 'websocket': AuthMiddlewareStack(
|
||||||
|
# URLRouter(
|
||||||
|
# websocket_urlpatterns
|
||||||
|
# )
|
||||||
|
# )
|
||||||
|
# "websocket": AllowedHostsOriginValidator(
|
||||||
|
# SessionMiddlewareStack(
|
||||||
|
# AuthMiddlewareStack(
|
||||||
|
# URLRouter(
|
||||||
|
# websocket_urlpatterns
|
||||||
|
# )
|
||||||
|
# )
|
||||||
|
# )
|
||||||
|
# ),
|
||||||
})
|
})
|
||||||
|
|||||||
8
TWB/run_daphne.py
Normal file
8
TWB/run_daphne.py
Normal file
@@ -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()
|
||||||
@@ -33,7 +33,9 @@ ALLOWED_HOSTS = ["*"]
|
|||||||
# Application definition
|
# Application definition
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
'channels',
|
# 'channels',
|
||||||
|
"daphne",
|
||||||
|
'ChatServiceApp',
|
||||||
'modeltranslation',
|
'modeltranslation',
|
||||||
|
|
||||||
'django.contrib.admin',
|
'django.contrib.admin',
|
||||||
@@ -51,7 +53,7 @@ INSTALLED_APPS = [
|
|||||||
'AuthApp',
|
'AuthApp',
|
||||||
'RoutesApp',
|
'RoutesApp',
|
||||||
'ReferenceDataApp',
|
'ReferenceDataApp',
|
||||||
'ChatServiceApp',
|
|
||||||
]
|
]
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
@@ -86,12 +88,16 @@ TEMPLATES = [
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
# WSGI_APPLICATION = 'TWB.wsgi.application'
|
WSGI_APPLICATION = 'TWB.wsgi.application'
|
||||||
ASGI_APPLICATION = 'TWB.asgi.application'
|
ASGI_APPLICATION = 'TWB.asgi.application'
|
||||||
|
|
||||||
CHANNEL_LAYERS = {
|
CHANNEL_LAYERS = {
|
||||||
'default': {
|
'default': {
|
||||||
'BACKEND': 'channels.layers.InMemoryChannelLayer'
|
# 'BACKEND': 'channels.layers.InMemoryChannelLayer'
|
||||||
|
"BACKEND": "channels_redis.core.RedisChannelLayer",
|
||||||
|
"CONFIG": {
|
||||||
|
"hosts": [("127.0.0.1", 6379)],
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
26
TWB/ws_middleware.py
Normal file
26
TWB/ws_middleware.py
Normal file
@@ -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)
|
||||||
@@ -42,75 +42,63 @@
|
|||||||
|
|
||||||
// var i = 0
|
// 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/`;
|
let url = `ws://localhost:8000/ws/socket-server/`;
|
||||||
|
|
||||||
const chatSocket = new WebSocket(url);
|
const chatSocket = new WebSocket(url);
|
||||||
|
|
||||||
|
function sendMessageSocket (data) {
|
||||||
|
chatSocket.send(JSON.stringify(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
chatSocket.onmessage = function (e) {
|
chatSocket.onmessage = function (e) {
|
||||||
let data = JSON.parse(e.data)
|
let data = JSON.parse(e.data);
|
||||||
console.log('Data: ', data)
|
console.log('Data:', data);
|
||||||
|
console.log("return")
|
||||||
if (data.type === 'chat') {
|
if (data.type === 'chat'){
|
||||||
// let messages = document.getElementById('messages')
|
document.querySelector(".container-messages").innerHTML = data.html;
|
||||||
//
|
document.querySelector(".enter-message-inp").focus()
|
||||||
// messages.insertAdjacentHTML('beforeend', `<div>
|
}
|
||||||
// <p>${data.message}</p>
|
|
||||||
// </div>`
|
|
||||||
// )
|
|
||||||
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', `<div>
|
||||||
|
// // <p>${data.message}</p>
|
||||||
|
// // </div>`
|
||||||
|
// // )
|
||||||
|
// document.querySelector(".container-messages").innerHTML = data.html;
|
||||||
|
// document.querySelector(".enter-message-inp").focus()
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
|
||||||
btn.addEventListener('click', (e) => {
|
// function send_ws_msg(data) {
|
||||||
e.preventDefault()
|
// chatSocket.send(JSON.stringify(data));
|
||||||
// let message = e.target.message.value
|
// }
|
||||||
chatSocket.send(JSON.stringify({
|
|
||||||
'data':'data'
|
// window.onload = function () {
|
||||||
}))
|
//
|
||||||
// btn.reset()
|
// 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')
|
// let form = document.getElementById('form')
|
||||||
|
|
||||||
|
|||||||
@@ -63,6 +63,7 @@
|
|||||||
<div class="right-part-block-enter-message">
|
<div class="right-part-block-enter-message">
|
||||||
<button class="attach-file-btn-message" onclick="attachFilemeassge()"></button>
|
<button class="attach-file-btn-message" onclick="attachFilemeassge()"></button>
|
||||||
<button class="send-message" onclick="sendMessage(null,{{ user.id }},{{ cur_receiver.id }})"></button>
|
<button class="send-message" onclick="sendMessage(null,{{ user.id }},{{ cur_receiver.id }})"></button>
|
||||||
|
{# <button class="send-message" onclick="send_ws_msg('message')"></button>#}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
<script src='{% static "js/user_profile.js" %}'> </script>
|
<script src='{% static "js/user_profile.js" %}'> </script>
|
||||||
<script src='{% static "js/user_profile(boris).js" %}'> </script>
|
<script src='{% static "js/user_profile(boris).js" %}'> </script>
|
||||||
<script src='{% static "js/check_new_messages.js" %}'></script>
|
<script src='{% static "js/check_new_messages.js" %}'></script>
|
||||||
<script src='{% static "js/chat_sockets.js" %}'></script>
|
{# <script src='{% static "js/chat_sockets.js" %}'></script>#}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
|
|
||||||
<script src='{% static "js/jquery_v3_6_4.js" %}'> </script>
|
<script src='{% static "js/jquery_v3_6_4.js" %}'> </script>
|
||||||
|
|
||||||
|
<script src='{% static "js/chat_sockets.js" %}'></script>
|
||||||
|
|
||||||
|
|
||||||
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
|
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user