Browse Source

web sockets (WIP)

Websocket_painel
Edward Ribeiro 3 years ago
parent
commit
307de59b86
  1. 2
      requirements/requirements.txt
  2. 19
      sapl/asgi.py
  3. 21
      sapl/painel/consumers.py
  4. 6
      sapl/painel/routing.py
  5. 5
      sapl/painel/urls.py
  6. 6
      sapl/painel/views.py
  7. 17
      sapl/settings.py
  8. 51
      sapl/templates/painel/room.html

2
requirements/requirements.txt

@ -35,3 +35,5 @@ whitenoise==5.1.0
git+https://github.com/interlegis/trml2pdf
git+https://github.com/interlegis/django-admin-bootstrapped
channels==3.0.4
channels-redis==3.3.0

19
sapl/asgi.py

@ -0,0 +1,19 @@
import os
import django
from channels.http import AsgiHandler
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import sapl.painel.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sapl.settings')
django.setup()
application = ProtocolTypeRouter({
"http": AsgiHandler(),
"websocket": AuthMiddlewareStack(
URLRouter(
sapl.painel.routing.websocket_urlpatterns
)
),
})

21
sapl/painel/consumers.py

@ -0,0 +1,21 @@
import json
from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()
print('conectado ao ws')
def disconnect(self, close_code):
print('desconectado ao ws')
pass
def receive(self, text_data):
print('receive message')
text_data_json = json.loads(text_data)
message = text_data_json['message']
self.send(text_data=json.dumps({
'message': message
}))

6
sapl/painel/routing.py

@ -0,0 +1,6 @@
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/painel/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]

5
sapl/painel/urls.py

@ -1,9 +1,11 @@
from django.conf.urls import url
from django.urls import path
from .apps import AppConfig
from .views import (cronometro_painel, get_dados_painel, painel_mensagem_view,
painel_parlamentar_view, painel_view, painel_votacao_view,
switch_painel, verifica_painel, votante_view)
switch_painel, verifica_painel, votante_view, room)
app_name = AppConfig.name
@ -24,4 +26,5 @@ urlpatterns = [
url(r'^voto-individual/$', votante_view,
name='voto_individual'),
path(r'<str:room_name>/', room, name='room'),
]

6
sapl/painel/views.py

@ -643,3 +643,9 @@ def get_dados_painel(request, pk):
# Retorna que não há nenhuma matéria já votada ou aberta
return response_nenhuma_materia(get_presentes(pk, response, None))
def room(request, room_name):
return render(request, 'painel/room.html', {
'room_name': room_name
})

17
sapl/settings.py

@ -96,6 +96,7 @@ INSTALLED_APPS = (
'speedinfo',
'webpack_loader',
'channels'
) + SAPL_APPS
@ -126,6 +127,20 @@ HAYSTACK_CONNECTIONS = {
},
}
CHANNEL_LAYERS = {
'default': {
### Method 1: Via local Redis
# 'BACKEND': 'channels_redis.core.RedisChannelLayer',
# 'CONFIG': {
# "hosts": [('127.0.0.1', 6379)],
# },
### Method 3: Via In-memory channel layer
## Using this method.
"BACKEND": "channels.layers.InMemoryChannelLayer"
}
}
MIDDLEWARE = [
'reversion.middleware.RevisionMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
@ -203,6 +218,8 @@ TEMPLATES = [
WSGI_APPLICATION = 'sapl.wsgi.application'
ASGI_APPLICATION = 'sapl.asgi.application'
CELERY_BROKER_URL = 'redis://localhost:6379'

51
sapl/templates/painel/room.html

@ -0,0 +1,51 @@
<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ room_name|json_script:"room-name" }}
<script>
const roomName = JSON.parse(document.getElementById('room-name').textContent);
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/painel/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
};
</script>
</body>
</html>
Loading…
Cancel
Save