Commits

boralyl committed a018c64

Initial import

  • Participants

Comments (0)

Files changed (11)

+syntax: glob
+*.pyc
+

File __init__.py

Empty file added.
+# -*- coding: utf-8 -*-
+from django.contrib import admin
+
+from chat.forms import ChatRoomAdminForm
+from chat.models import ChatRoom
+
+
+class ChatRoomAdmin(admin.ModelAdmin):
+    """
+    Options for the Admin interface
+    """
+    list_display = ('name', )
+    ordering = ('name', )
+    form = ChatRoomAdminForm
+    
+
+admin.site.register(ChatRoom, ChatRoomAdmin)
+from django import forms
+
+from chat.models import ChatRoom
+
+class ChatRoomForm(forms.Form):
+    """
+    Form that allows a user to select a chatroom
+    """
+    room = forms.ModelChoiceField(queryset=ChatRoom.objects.all())
+        
+
+class ChatRoomAdminForm(forms.ModelForm):
+    
+    class Meta:
+        model = ChatRoom
+        exclude = ('slug', )
+# -*- coding: utf-8 -*-
+from django.contrib.auth.models import User
+from django.db import models
+from django.template.defaultfilters import slugify
+
+
+class ChatRoom(models.Model):
+    """
+    Stores chatrooms
+    """
+    name = models.CharField(max_length=125)
+    slug = models.SlugField()
+    
+    def __unicode__(self):
+        return self.name
+        
+    def save(self, *args, **kwargs):
+        """
+        Override to populate the slug
+        """
+        self.slug = slugify(self.name)
+        super(ChatRoom, self).save(*args, **kwargs)
+
+
+class Message(models.Model):
+    """
+    Stores a chat message.
+    """
+    user = models.ForeignKey(User)
+    chatroom = models.ForeignKey(ChatRoom)
+    message = models.TextField()
+    date_added = models.DateTimeField(auto_now_add=True)
+    
+    def __unicode__(self):
+        return "%s: %s" % (self.user.username, self.message)

File templates/chat/base.html

+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="eng">
+<head>
+	<title>{% block title %}Chat{% endblock %}</title>
+</head>
+<body>
+{% block content %}{% endblock %}
+{% block deferred_js %}{% endblock %}
+</body>
+</html>

File templates/chat/chatroom.html

+{% extends "chat/base.html" %}
+
+{% block title %}Chatroom :: {{ object.name }}{% endblock %}
+
+{% block content %}
+<h1>{{ object.name }} Chatroom</h1>
+<div id="chat" style="width:100%;height:500px;border:1px solid #000;margin-bottom:5px;overflow-x:hidden;
+ overflow-y:scroll;"></div>
+<form action="." id="msg_form" method="post">{% csrf_token %}
+	<input type="text" name="msg" id="msg" style="width:94%" />
+	<input type="submit" value="send" style="width:4%" />
+</form>
+{% endblock %}
+
+{% block deferred_js %}
+<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
+<script type="text/javascript">
+	$(document).ready(function() {
+		// Avoid 403 error because of CSRF during ajax requests
+		$('html').ajaxSend(function(event, xhr, settings) {
+			function getCookie(name) {
+				var cookieValue = null;
+				if (document.cookie && document.cookie != '') {
+					var cookies = document.cookie.split(';');
+					for (var i = 0; i < cookies.length; i++) {
+						var cookie = jQuery.trim(cookies[i]);
+						// Does this cookie string begin with the name we want?
+						if (cookie.substring(0, name.length + 1) == (name + '=')) {
+							cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
+							break;
+						}
+					}
+				}
+				return cookieValue;
+			}
+			xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
+		});
+		// Append new messages to the chat window
+		function add_msg(data) {
+			var d = $.parseJSON(data);
+			var output = "[" + d.msg.time + "] &lt;" + d.msg.user + "&gt; " + d.msg.msg + "<br />";
+			$("#chat").append(output);
+			}
+		
+		// Poll for new messages
+		function checkIncoming() {
+				$.get({% url chat-check-incoming %}, {'room': {{ object.id }}}, function(data) {
+					//alert(data);
+					var da = $.parseJSON(data);
+					
+					for(var i = 0; i < da.msgs.length; i++) {
+						d = da.msgs[i];
+						var output = "[" + d.time + "] &lt;" + d.user + "&gt; " + d.msg + "<br />";
+						$("#chat").append(output);
+					}
+					setTimeout(checkIncoming, 7000);
+				});
+		}
+		checkIncoming();
+		// Handle form submission
+		$("#msg_form").submit(function() {
+			var msg = $("#msg").val();
+			$.post({% url chat-post-msg %}, {'msg': msg, 'room': {{ object.id }}}, add_msg);
+			$("#msg").val("");
+			return false;
+		});
+		
+	});
+</script>
+{% endblock %}

File templates/chat/select_room.html

+{% extends "chat/base.html" %}
+
+{% block title %}Chatroom :: {{ obj.name }}{% endblock %}
+
+{% block content %}
+<h1>Select Chatroom</h1>
+<form action="." method="post">{% csrf_token %}
+{{ form.as_p }}
+<p><input type="submit" value="Go" /></p>
+</form>
+{% endblock %}
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.assertEqual(1 + 1, 2)
+from django.conf.urls.defaults import patterns, url
+
+
+urlpatterns = patterns('chat.views',
+    url('^$', 'select_room', name="chat-select-room"),
+    url('^check_incoming/$', 'check_incoming', name="chat-check-incoming"),
+    url('^post_msg/$', 'post_msg', name="chat-post-msg"),
+    url('^room/(?P<slug>[a-zA-Z0-9_\-]+)/$', 'chatroom', name="chat-chatroom"),
+)
+from datetime import datetime
+
+from django.contrib.auth.decorators import login_required
+from django.core import serializers
+from django.core.urlresolvers import reverse
+from django.http import HttpResponse
+from django.shortcuts import get_object_or_404, redirect, render
+from django.views.generic.list_detail import object_detail
+from django.utils import simplejson
+
+from chat.forms import ChatRoomForm
+from chat.models import ChatRoom, Message
+
+
+@login_required
+def select_room(request):
+    """
+    Allows a logged in user to select which chat room to join
+    """
+    form = ChatRoomForm(request.POST or None)
+    if form.is_valid():
+        room = form.cleaned_data['room']
+        return redirect(reverse("chat-chatroom", kwargs={'slug': room.slug}))
+    
+    return render(request, "chat/select_room.html", {'form': form})
+    
+    
+@login_required
+def chatroom(request, slug):
+    return object_detail(request, queryset=ChatRoom.objects.all(), 
+        template_name="chat/chatroom.html", slug=slug, slug_field="slug")
+
+
+@login_required
+def post_msg(request):
+    """
+    Ajax view for posting a message.
+    """
+    results = {}
+    if request.method == 'POST':
+        message = request.POST.get('msg', None)
+        room_id = request.POST.get('room', None)
+        room = get_object_or_404(ChatRoom, pk=room_id)
+        msg = Message(user=request.user)
+        msg.chatroom = room
+        msg.message = message
+        msg.save()
+        results['msg'] = {'msg': msg.message, 
+            'time':msg.date_added.strftime("%H:%M"), 'user': msg.user.username}
+        request.session['last_check'] = datetime.now()
+        
+    return HttpResponse(simplejson.dumps(results), mimetype='application/javascript')
+
+
+def check_incoming(request):
+    results = {'msgs': []}
+    if 'last_check' in request.session:
+        last_check = request.session['last_check']
+        room = request.GET.get('room', None)
+        results['msgs'] = [{'msg': m.message,
+            'time':m.date_added.strftime("%H:%M"), 'user': m.user.username} \
+            for m in Message.objects.filter(date_added__gte=last_check,
+                chatroom__id=room)]
+    request.session['last_check'] = datetime.now()
+    return HttpResponse(simplejson.dumps(results), mimetype='application/javascript')