Skip to content

Commit

Permalink
finished demo page
Browse files Browse the repository at this point in the history
  • Loading branch information
Jpadilla1 committed Jul 13, 2014
1 parent e125c41 commit d3293a7
Show file tree
Hide file tree
Showing 15 changed files with 263 additions and 18 deletions.
13 changes: 13 additions & 0 deletions chatrooms/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from django.http import HttpResponse
from django.views.generic.base import TemplateView
from ws4redis.publisher import RedisPublisher


class DemoChatView(TemplateView):
template_name = 'index.html'

def post(self, request, *args, **kwargs):
redis_publisher = RedisPublisher(
facility='demo', broadcast=True)
redis_publisher.publish_message(request.POST.get('message'))
return HttpResponse('OK')
41 changes: 30 additions & 11 deletions chatrooms/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ class Common(Configuration):

ALLOWED_HOSTS = []

SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_PREFIX = 'session'

# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
Expand All @@ -31,28 +34,27 @@ class Common(Configuration):
'django_extensions',
'rest_framework',
'rest_framework_swagger',
'corsheaders',

# Apps
'chatrooms.users',
'chatrooms.rooms',
'chatrooms.messages',
)

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.static',
'ws4redis.context_processors.default',
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

# Rest Framework Settings
Expand Down Expand Up @@ -95,8 +97,6 @@ class Common(Configuration):

ROOT_URLCONF = 'chatrooms.urls'

WSGI_APPLICATION = 'chatrooms.wsgi.application'

# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = values.DatabaseURLValue(
Expand Down Expand Up @@ -130,18 +130,37 @@ class Common(Configuration):

AUTH_USER_MODEL = 'users.User'

WSGI_APPLICATION = 'ws4redis.django_runserver.application'

WEBSOCKET_URL = '/ws/'
WS4REDIS_ALLOWED_CHANNELS = ['subscribe-room', ]
# WS4REDIS_ALLOWED_CHANNELS = ['subscribe-room', 'subscribe-demo', ]
WS4REDIS_EXPIRE = 7200
WS4REDIS_PREFIX = 'ws'
WSGI_APPLICATION = 'ws4redis.django_runserver.application'

WS4REDIS_HEARTBEAT = '--heartbeat--'
WS4REDIS_CONNECTION = {
'host': 'localhost',
'port': 6379,
}
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_PREFIX = 'session'

# CORS settings
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api-v1/.*$'
CORS_ALLOW_METHODS = (
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'
)
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'x-csrftoken'
)


class Development(Common):
Expand Down
4 changes: 3 additions & 1 deletion chatrooms/urls.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from django.conf.urls import patterns, include, url
# from django.views.generic import TemplateView

from django.contrib import admin
admin.autodiscover()

from .demo import DemoChatView

urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', DemoChatView.as_view(), name='index'),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^api-v1/', include('chatrooms.router')),
url(r'^api-auth/',
Expand Down
3 changes: 3 additions & 0 deletions chatrooms/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@
"""

import os
import sys

from django.conf import settings
from ws4redis.uwsgi_runserver import uWSGIWebsocketServer
from configurations.wsgi import get_wsgi_application


sys.path.insert(0, os.path.abspath('..'))

ENVIRONMENT = os.getenv('ENVIRONMENT', 'DEVELOPMENT').title()

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chatrooms.settings')
Expand Down
5 changes: 3 additions & 2 deletions manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@

import dotenv

dotenv.read_dotenv()
sys.path.insert(0, os.path.abspath('..'))

dotenv.read_dotenv()

if __name__ == "__main__":
ENVIRONMENT = os.getenv('ENVIRONMENT', 'DEVELOPMENT').title()

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chatrooms.settings')
os.environ.update(DJANGO_SETTINGS_MODULE='chatrooms.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', ENVIRONMENT)

from configurations.management import execute_from_command_line
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ dj-database-url==0.3.0
dj-static==0.0.5
django-autoslug==1.7.2
django-configurations==0.8
django-cors-headers==0.12
django-debug-toolbar==1.2.1
django-dotenv==1.2
django-extensions==1.3.8
Expand Down
76 changes: 76 additions & 0 deletions static/css/app.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
@font-face {
font-family: Roboto-light;
src: url("../fonts/RobotoTTF/Roboto-Light.ttf");
}
html, header,
body, footer {
margin: 0;
padding: 0;
width: 100%;
font-family: Roboto-light, Helvetica, sans-serif;
}
hr {
border: none;
border-top: 1px solid rgba(150, 150, 150, 0.4);
}
textarea {
margin: 0;
width: 100%;
border-radius: 5px;
border-color: rgba(0, 0, 0, 0.2);
font-family: Roboto-light, Helvetica, sans-serif;
font-size: 16px;
padding: 5px;
}
textarea:focus {
border-color: rgba(0, 146, 219, 0.5);
outline: none;
}
.list-inline {
display: inline-block;
}
.text-center {
text-align: center;
}
.container {
width: 960px;
margin: auto;
padding: 20px 15px;
}
#messages {
margin: 0;
float: left;
width: 45%;
height: 300px;
max-height: 300px;
background-color: rgba(230, 230, 230, 0.5);
overflow-y: scroll;
padding: 15px;
border-radius: 5px;
}
.message {
font-size: 16px;
line-height: 1.3em;
}
.form-wrapper {
margin: 0;
margin-left: 30px;
float: left;
width: 45%;
}
#send_message {
border: 1px solid rgba(0, 0, 0, 0.3);
border-radius: 5px;
padding: 10px 15px;
background-color: #fff;
font-size: 18px;
cursor: pointer;
}
#send_message:hover {
transition: .3s;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
}
#send_message:focus {
outline: none;
border: 1px solid rgba(0, 146, 219, 0.8);
}
Binary file added static/fonts/RobotoTTF/Roboto-Light.ttf
Binary file not shown.
Binary file added static/fonts/RobotoTTF/Roboto-LightItalic.ttf
Binary file not shown.
Binary file added static/fonts/RobotoTTF/Roboto-Thin.ttf
Binary file not shown.
Binary file added static/fonts/RobotoTTF/Roboto-ThinItalic.ttf
Binary file not shown.
Binary file removed static/img/ocean.jpg
Binary file not shown.
83 changes: 83 additions & 0 deletions static/js/ws4redis.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@

function WS4Redis(options, $) {
'use strict';
var opts, ws, deferred, timer, timer_interval = 0;
var heartbeat_interval = null, missed_heartbeats = 0;

if (this === undefined)
return new WS4Redis(options, $);
if (options.uri === undefined)
throw new Error('No Websocket URI in options');
if ($ === undefined)
$ = jQuery;
opts = $.extend({ heartbeat_msg: null }, options);
connect(opts.uri);

function connect(uri) {
try {
console.log("Connecting to " + uri + " ...");
deferred = $.Deferred();
ws = new WebSocket(uri);
ws.onopen = on_open;
ws.onmessage = on_message;
ws.onerror = on_error;
ws.onclose = on_close;
timer = null;
} catch (err) {
deferred.reject(new Error(err));
}
}

function send_heartbeat() {
try {
missed_heartbeats++;
if (missed_heartbeats > 3)
throw new Error("Too many missed heartbeats.");
ws.send(opts.heartbeat_msg);
} catch(e) {
clearInterval(heartbeat_interval);
heartbeat_interval = null;
console.warn("Closing connection. Reason: " + e.message);
ws.close();
}
}

function on_open() {
console.log('Connected!');
timer_interval = 500;
deferred.resolve();
if (opts.heartbeat_msg && heartbeat_interval === null) {
missed_heartbeats = 0;
heartbeat_interval = setInterval(send_heartbeat, 5000);
}
}

function on_close(evt) {
console.log("Connection closed!");
if (!timer) {
// try to reconnect
timer = setTimeout(function() {
connect(ws.url);
}, timer_interval);
timer_interval = Math.min(timer_interval + 500, 5000);
}
}

function on_error(evt) {
console.error("Websocket connection is broken!");
deferred.reject(new Error(evt));
}

function on_message(evt) {
if (opts.heartbeat_msg && evt.data === opts.heartbeat_msg) {
// reset the counter for missed heartbeats
missed_heartbeats = 0;
} else if (typeof opts.receive_message === 'function') {
return opts.receive_message(evt.data);
}
}

this.send_message = function(message) {
ws.send(message);
}
}
6 changes: 5 additions & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
</header>

{% block content %}{% endblock content %}

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="{% static 'js/ws4redis.js' %}"></script>
{% block extra_js %}

{% endblock extra_js %}
</body>

</html>
49 changes: 46 additions & 3 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,49 @@
Chatrooms API
{% endblock title %}

{% block header %}

{% endblock header %}
{% block content %}
<div class="container">
<h1 class="text-center">Chatrooms Demo</h1>
<hr>

<section id="messages">

</section>

<div class="form-wrapper">
{% csrf_token %}
<textarea name="text_message" id="text_message" cols="50" rows="10" wrap="hard"></textarea>
<br>
<center>
<button id="send_message">Send</button>
</center>
</div>
</div>
{% endblock content %}

{% block extra_js %}
<script type="text/javascript">
$(document).ready(function($) {
var ws4redis = WS4Redis({
uri: '{{ WEBSOCKET_URI }}demo?subscribe-broadcast&echo',
receive_message: receiveMessage,
heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});

// send message though the Websocket to the server
$('#send_message').click(function() {
$.post('', {
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
message: $('#text_message').val()
});
});

// receive a message though the Websocket from the server
function receiveMessage(msg) {
console.log(msg);
$('#messages').append(
"<div class='message'>" + msg + "</div>");
}
});
</script>
{% endblock extra_js %}

0 comments on commit d3293a7

Please sign in to comment.